test_nvs.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include <stdio.h>
  2. #include <ctype.h>
  3. #include <errno.h>
  4. #include <stdlib.h>
  5. #include <time.h>
  6. #include "unity.h"
  7. #include "nvs.h"
  8. #include "nvs_flash.h"
  9. #include "esp_partition.h"
  10. #include "esp_log.h"
  11. #include <string.h>
  12. static const char* TAG = "test_nvs";
  13. TEST_CASE("various nvs tests", "[nvs]")
  14. {
  15. nvs_handle handle_1;
  16. esp_err_t err = nvs_flash_init();
  17. if (err == ESP_ERR_NVS_NO_FREE_PAGES) {
  18. ESP_LOGW(TAG, "nvs_flash_init failed (0x%x), erasing partition and retrying", err);
  19. const esp_partition_t* nvs_partition = esp_partition_find_first(
  20. ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_NVS, NULL);
  21. assert(nvs_partition && "partition table must have an NVS partition");
  22. ESP_ERROR_CHECK( esp_partition_erase_range(nvs_partition, 0, nvs_partition->size) );
  23. err = nvs_flash_init();
  24. }
  25. ESP_ERROR_CHECK( err );
  26. TEST_ESP_ERR(nvs_open("test_namespace1", NVS_READONLY, &handle_1), ESP_ERR_NVS_NOT_FOUND);
  27. TEST_ESP_ERR(nvs_set_i32(handle_1, "foo", 0x12345678), ESP_ERR_NVS_INVALID_HANDLE);
  28. nvs_close(handle_1);
  29. TEST_ESP_OK(nvs_open("test_namespace2", NVS_READWRITE, &handle_1));
  30. TEST_ESP_OK(nvs_erase_all(handle_1));
  31. TEST_ESP_OK(nvs_set_i32(handle_1, "foo", 0x12345678));
  32. TEST_ESP_OK(nvs_set_i32(handle_1, "foo", 0x23456789));
  33. nvs_handle handle_2;
  34. TEST_ESP_OK(nvs_open("test_namespace3", NVS_READWRITE, &handle_2));
  35. TEST_ESP_OK(nvs_erase_all(handle_2));
  36. TEST_ESP_OK(nvs_set_i32(handle_2, "foo", 0x3456789a));
  37. const char* str = "value 0123456789abcdef0123456789abcdef";
  38. TEST_ESP_OK(nvs_set_str(handle_2, "key", str));
  39. int32_t v1;
  40. TEST_ESP_OK(nvs_get_i32(handle_1, "foo", &v1));
  41. TEST_ASSERT_EQUAL_INT32(0x23456789, v1);
  42. int32_t v2;
  43. TEST_ESP_OK(nvs_get_i32(handle_2, "foo", &v2));
  44. TEST_ASSERT_EQUAL_INT32(0x3456789a, v2);
  45. char buf[strlen(str) + 1];
  46. size_t buf_len = sizeof(buf);
  47. TEST_ESP_OK(nvs_get_str(handle_2, "key", buf, &buf_len));
  48. TEST_ASSERT_EQUAL_INT32(0, strcmp(buf, str));
  49. nvs_close(handle_1);
  50. nvs_close(handle_2);
  51. }