test_mqtt.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include "test_utils.h"
  2. #include "mqtt_client.h"
  3. #include "unity.h"
  4. #include <sys/time.h>
  5. #include "nvs_flash.h"
  6. #include "esp_ota_ops.h"
  7. static void test_leak_setup(const char * file, long line)
  8. {
  9. uint8_t mac[6];
  10. struct timeval te;
  11. gettimeofday(&te, NULL); // get current time
  12. esp_read_mac(mac, ESP_MAC_WIFI_STA);
  13. printf("%s:%ld: time=%ld.%lds, mac:" MACSTR "\n", file, line, te.tv_sec, te.tv_usec, MAC2STR(mac));
  14. unity_reset_leak_checks();
  15. }
  16. TEST_CASE("mqtt init with invalid url", "[mqtt][leaks=0]")
  17. {
  18. test_leak_setup(__FILE__, __LINE__);
  19. const esp_mqtt_client_config_t mqtt_cfg = {
  20. .uri = "INVALID",
  21. };
  22. esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
  23. TEST_ASSERT_EQUAL(NULL, client );
  24. }
  25. TEST_CASE("mqtt init and deinit", "[mqtt][leaks=0]")
  26. {
  27. test_leak_setup(__FILE__, __LINE__);
  28. const esp_mqtt_client_config_t mqtt_cfg = {
  29. // no connection takes place, but the uri has to be valid for init() to succeed
  30. .uri = "mqtts://localhost:8883",
  31. };
  32. esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
  33. TEST_ASSERT_NOT_EQUAL(NULL, client );
  34. esp_mqtt_client_destroy(client);
  35. }
  36. static const char* this_bin_addr(void)
  37. {
  38. spi_flash_mmap_handle_t out_handle;
  39. const void *binary_address;
  40. const esp_partition_t* partition = esp_ota_get_running_partition();
  41. esp_partition_mmap(partition, 0, partition->size, SPI_FLASH_MMAP_DATA, &binary_address, &out_handle);
  42. return binary_address;
  43. }
  44. TEST_CASE("mqtt enqueue and destroy outbox", "[mqtt][leaks=0]")
  45. {
  46. const char * bin_addr = this_bin_addr();
  47. test_leak_setup(__FILE__, __LINE__);
  48. const int messages = 20;
  49. const int size = 2000;
  50. const esp_mqtt_client_config_t mqtt_cfg = {
  51. // no connection takes place, but the uri has to be valid for init() to succeed
  52. .uri = "mqtts://localhost:8883",
  53. };
  54. esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
  55. TEST_ASSERT_NOT_EQUAL(NULL, client );
  56. int bytes_before = esp_get_free_heap_size();
  57. for (int i=0; i<messages; ++i) {
  58. esp_mqtt_client_publish(client, "test", bin_addr, size, 1, 0);
  59. }
  60. int bytes_after = esp_get_free_heap_size();
  61. // check that outbox allocated all messages on heap
  62. TEST_ASSERT_GREATER_OR_EQUAL(messages*size, bytes_before - bytes_after);
  63. esp_mqtt_client_destroy(client);
  64. }