ci: use esp8266 mock framework

Resolve the issue with the UnixHostDuino not really being compatible
with the esp8266 Core String (...and the rest of the Core, as well)

Port the CMakeLists.txt from the rpnlib and update it use FetchContent
instead of either manually fetching dependencies or using PIO artifacts
Caching is *expected* to work, but might need slight adjustments
This commit is contained in:
Maxim Prokhorov
2022-01-13 03:59:39 +03:00
parent 594763e349
commit eaa2e370eb
17 changed files with 545 additions and 177 deletions

View File

@@ -0,0 +1,325 @@
// direct c/p from the esp8266/Arduino, just removing the main() since we already call it
// and don't need the rest of the bootstraping done
/*
Arduino emulator main loop
Copyright (c) 2018 david gauchard. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal with the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimers.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimers in the
documentation and/or other materials provided with the distribution.
- The names of its contributors may not be used to endorse or promote
products derived from this Software without specific prior written
permission.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS WITH THE SOFTWARE.
*/
#include <Arduino.h>
#include <user_interface.h> // wifi_get_ip_info()
#include <signal.h>
#include <unistd.h>
#include <getopt.h>
#include <termios.h>
#include <stdarg.h>
#include <stdio.h>
#define MOCK_PORT_SHIFTER 9000
bool user_exit = false;
bool run_once = false;
const char* host_interface = nullptr;
size_t spiffs_kb = 1024;
size_t littlefs_kb = 1024;
bool ignore_sigint = false;
bool restore_tty = false;
bool mockdebug = false;
int mock_port_shifter = MOCK_PORT_SHIFTER;
const char* fspath = nullptr;
#define STDIN STDIN_FILENO
static struct termios initial_settings;
int mockverbose (const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
if (mockdebug)
return fprintf(stderr, MOCK) + vfprintf(stderr, fmt, ap);
return 0;
}
static int mock_start_uart(void)
{
struct termios settings;
if (!isatty(STDIN))
{
perror("setting tty in raw mode: isatty(STDIN)");
return -1;
}
if (tcgetattr(STDIN, &initial_settings) < 0)
{
perror("setting tty in raw mode: tcgetattr(STDIN)");
return -1;
}
settings = initial_settings;
settings.c_lflag &= ~(ignore_sigint ? ISIG : 0);
settings.c_lflag &= ~(ECHO | ICANON);
settings.c_iflag &= ~(ICRNL | INLCR | ISTRIP | IXON);
settings.c_oflag |= (ONLCR);
settings.c_cc[VMIN] = 0;
settings.c_cc[VTIME] = 0;
if (tcsetattr(STDIN, TCSANOW, &settings) < 0)
{
perror("setting tty in raw mode: tcsetattr(STDIN)");
return -1;
}
restore_tty = true;
return 0;
}
static int mock_stop_uart(void)
{
if (!restore_tty) return 0;
if (!isatty(STDIN)) {
perror("restoring tty: isatty(STDIN)");
return -1;
}
if (tcsetattr(STDIN, TCSANOW, &initial_settings) < 0)
{
perror("restoring tty: tcsetattr(STDIN)");
return -1;
}
printf("\e[?25h"); // show cursor
return (0);
}
static uint8_t mock_read_uart(void)
{
uint8_t ch = 0;
return (read(STDIN, &ch, 1) == 1) ? ch : 0;
}
void help (const char* argv0, int exitcode)
{
printf(
"%s - compiled with esp8266/arduino emulator\n"
"options:\n"
"\t-h\n"
"\tnetwork:\n"
"\t-i <interface> - use this interface for IP address\n"
"\t-l - bind tcp/udp servers to interface only (not 0.0.0.0)\n"
"\t-s - port shifter (default: %d, when root: 0)\n"
"\tterminal:\n"
"\t-b - blocking tty/mocked-uart (default: not blocking tty)\n"
"\t-T - show timestamp on output\n"
"\tFS:\n"
"\t-P - path for fs-persistent files (default: %s-)\n"
"\t-S - spiffs size in KBytes (default: %zd)\n"
"\t-L - littlefs size in KBytes (default: %zd)\n"
"\t (spiffs, littlefs: negative value will force mismatched size)\n"
"\tgeneral:\n"
"\t-c - ignore CTRL-C (send it via Serial)\n"
"\t-f - no throttle (possibly 100%%CPU)\n"
"\t-1 - run loop once then exit (for host testing)\n"
"\t-v - verbose\n"
, argv0, MOCK_PORT_SHIFTER, argv0, spiffs_kb, littlefs_kb);
exit(exitcode);
}
static struct option options[] =
{
{ "help", no_argument, NULL, 'h' },
{ "fast", no_argument, NULL, 'f' },
{ "local", no_argument, NULL, 'l' },
{ "sigint", no_argument, NULL, 'c' },
{ "blockinguart", no_argument, NULL, 'b' },
{ "verbose", no_argument, NULL, 'v' },
{ "timestamp", no_argument, NULL, 'T' },
{ "interface", required_argument, NULL, 'i' },
{ "fspath", required_argument, NULL, 'P' },
{ "spiffskb", required_argument, NULL, 'S' },
{ "littlefskb", required_argument, NULL, 'L' },
{ "portshifter", required_argument, NULL, 's' },
{ "once", no_argument, NULL, '1' },
};
void cleanup ()
{
mock_stop_spiffs();
mock_stop_littlefs();
mock_stop_uart();
}
void make_fs_filename (String& name, const char* fspath, const char* argv0)
{
name.clear();
if (fspath)
{
int lastSlash = -1;
for (int i = 0; argv0[i]; i++)
if (argv0[i] == '/')
lastSlash = i;
name = fspath;
name += '/';
name += &argv0[lastSlash + 1];
}
else
name = argv0;
}
void control_c (int sig)
{
(void)sig;
if (user_exit)
{
fprintf(stderr, MOCK "stuck, killing\n");
cleanup();
exit(1);
}
user_exit = true;
}
#if 0
int main (int argc, char* const argv [])
{
bool fast = false;
blocking_uart = false; // global
signal(SIGINT, control_c);
signal(SIGTERM, control_c);
if (geteuid() == 0)
mock_port_shifter = 0;
else
mock_port_shifter = MOCK_PORT_SHIFTER;
for (;;)
{
int n = getopt_long(argc, argv, "hlcfbvTi:S:s:L:P:1", options, NULL);
if (n < 0)
break;
switch (n)
{
case 'h':
help(argv[0], EXIT_SUCCESS);
break;
case 'i':
host_interface = optarg;
break;
case 'l':
global_ipv4_netfmt = NO_GLOBAL_BINDING;
break;
case 's':
mock_port_shifter = atoi(optarg);
break;
case 'c':
ignore_sigint = true;
break;
case 'f':
fast = true;
break;
case 'S':
spiffs_kb = atoi(optarg);
break;
case 'L':
littlefs_kb = atoi(optarg);
break;
case 'P':
fspath = optarg;
break;
case 'b':
blocking_uart = true;
break;
case 'v':
mockdebug = true;
break;
case 'T':
serial_timestamp = true;
break;
case '1':
run_once = true;
break;
default:
help(argv[0], EXIT_FAILURE);
}
}
mockverbose("server port shifter: %d\n", mock_port_shifter);
if (spiffs_kb)
{
String name;
make_fs_filename(name, fspath, argv[0]);
name += "-spiffs";
name += String(spiffs_kb > 0? spiffs_kb: -spiffs_kb, DEC);
name += "KB";
mock_start_spiffs(name, spiffs_kb);
}
if (littlefs_kb)
{
String name;
make_fs_filename(name, fspath, argv[0]);
name += "-littlefs";
name += String(littlefs_kb > 0? littlefs_kb: -littlefs_kb, DEC);
name += "KB";
mock_start_littlefs(name, littlefs_kb);
}
// setup global global_ipv4_netfmt
wifi_get_ip_info(0, nullptr);
if (!blocking_uart)
{
// set stdin to non blocking mode
mock_start_uart();
}
// install exit handler in case Esp.restart() is called
atexit(cleanup);
// first call to millis(): now is millis() and micros() beginning
millis();
setup();
while (!user_exit)
{
uint8_t data = mock_read_uart();
if (data)
uart_new_data(UART0, data);
if (!fast)
usleep(1000); // not 100% cpu, ~1000 loops per second
loop();
loop_end();
check_incoming_udp();
if (run_once)
user_exit = true;
}
cleanup();
return 0;
}
#endif

View File

@@ -0,0 +1,16 @@
#include <unity.h>
#include <Arduino.h>
// Ensure build system works
// ref: https://github.com/bxparks/UnixHostDuino/pull/6
void test_linkage() {
pinMode(0, INPUT);
pinMode(0, OUTPUT);
}
int main(int, char**) {
UNITY_BEGIN();
RUN_TEST(test_linkage);
return UNITY_END();
}

View File

@@ -0,0 +1,492 @@
#include <unity.h>
#include <Arduino.h>
#pragma GCC diagnostic warning "-Wall"
#pragma GCC diagnostic warning "-Wextra"
#pragma GCC diagnostic warning "-Wstrict-aliasing"
#pragma GCC diagnostic warning "-Wpointer-arith"
#pragma GCC diagnostic warning "-Wstrict-overflow=5"
#include <settings_embedis.h>
#include <array>
#include <algorithm>
#include <numeric>
namespace settings {
namespace embedis {
// TODO: either
// - throw exception and print backtrace to signify which method caused the out-of-bounds read or write
// - use a custom macro to supply (instance?) object with the correct line number
template <typename T>
struct StaticArrayStorage {
explicit StaticArrayStorage(T& blob) :
_blob(blob),
_size(blob.size())
{}
uint8_t read(size_t index) const {
TEST_ASSERT_LESS_THAN(_size, index);
return _blob[index];
}
void write(size_t index, uint8_t value) {
TEST_ASSERT_LESS_THAN(_size, index);
_blob[index] = value;
}
void commit() {
}
T& _blob;
const size_t _size;
};
} // namespace embedis
} // namespace settings
template <size_t Size>
struct StorageHandler {
using array_type = std::array<uint8_t, Size>;
using storage_type = settings::embedis::StaticArrayStorage<array_type>;
using kvs_type = settings::embedis::KeyValueStore<storage_type>;
StorageHandler() :
kvs(std::move(storage_type{blob}), 0, Size)
{
blob.fill(0xff);
}
array_type blob;
kvs_type kvs;
};
// generate stuff depending on the mode
// - Indexed: key1:val1, key2:val2, ...
// - IncreasingLength: k:v, kk:vv, ...
struct TestSequentialKvGenerator {
using kv = std::pair<String, String>;
enum class Mode {
Indexed,
IncreasingLength
};
TestSequentialKvGenerator() = default;
explicit TestSequentialKvGenerator(Mode mode) :
_mode(mode)
{}
const kv& next() {
auto index = _index++;
_current.first = "";
_current.second = "";
switch (_mode) {
case Mode::Indexed:
_current.first = String("key") + String(index);
_current.second = String("val") + String(index);
break;
case Mode::IncreasingLength: {
size_t sizes = _index;
_current.first.reserve(sizes);
_current.second.reserve(sizes);
do {
_current.first += "k";
_current.second += "v";
} while (--sizes);
break;
}
}
TEST_ASSERT(_last.first != _current.first);
TEST_ASSERT(_last.second != _current.second);
return (_last = _current);
}
std::vector<kv> make(size_t size) {;
std::vector<kv> res;
for (size_t index = 0; index < size; ++index) {
res.push_back(next());
}
return res;
}
kv _current;
kv _last;
Mode _mode { Mode::Indexed };
size_t _index { 0 };
};
// ----------------------------------------------------------------------------
using TestStorageHandler = StorageHandler<1024>;
template <typename T>
void check_kv(T& instance, const String& key, const String& value) {
auto result = instance.kvs.get(key);
TEST_ASSERT_MESSAGE(static_cast<bool>(result), key.c_str());
TEST_ASSERT(result.length());
TEST_ASSERT_EQUAL_STRING(value.c_str(), result.c_str());
};
void test_sizes() {
// empty storage is still manageble, it just does not work :)
{
StorageHandler<0> empty;
TEST_ASSERT_EQUAL(0, empty.kvs.count());
TEST_ASSERT_FALSE(empty.kvs.set("cannot", "happen"));
TEST_ASSERT_FALSE(static_cast<bool>(empty.kvs.get("cannot")));
}
// some hard-coded estimates to notify us about internal changes
{
StorageHandler<16> instance;
TEST_ASSERT_EQUAL(0, instance.kvs.count());
TEST_ASSERT_EQUAL(16, instance.kvs.available());
TEST_ASSERT_EQUAL(0, settings::embedis::estimate("", "123456"));
TEST_ASSERT_EQUAL(16, settings::embedis::estimate("123456", "123456"));
TEST_ASSERT_EQUAL(10, settings::embedis::estimate("123", "123"));
TEST_ASSERT_EQUAL(7, settings::embedis::estimate("345", ""));
TEST_ASSERT_EQUAL(0, settings::embedis::estimate("", ""));
TEST_ASSERT_EQUAL(5, settings::embedis::estimate("1", ""));
}
}
void test_longkey() {
TestStorageHandler instance;
const auto estimate = instance.kvs.size() - 6;
String key;
key.reserve(estimate);
for (size_t n = 0; n < estimate; ++n) {
key += 'a';
}
TEST_ASSERT(instance.kvs.set(key, ""));
auto result = instance.kvs.get(key);
TEST_ASSERT(static_cast<bool>(result));
}
void test_perseverance() {
// ensure we can handle setting the same key
using storage_type = StorageHandler<128>;
using blob_type = decltype(std::declval<storage_type>().blob);
// xxx: implementation detail?
// can we avoid blob modification when value is the same as the existing one
{
storage_type instance;
blob_type original(instance.blob);
TEST_ASSERT(instance.kvs.set("key", "value"));
TEST_ASSERT(instance.kvs.set("another", "keyvalue"));
TEST_ASSERT(original != instance.blob);
blob_type snapshot(instance.blob);
TEST_ASSERT(instance.kvs.set("key", "value"));
TEST_ASSERT(snapshot == instance.blob);
}
// xxx: pointless implementation detail?
// can we re-use existing 'value' storage and avoid data-shift
{
storage_type instance;
blob_type original(instance.blob);
// insert in a specific order, change middle
TEST_ASSERT(instance.kvs.set("aaa", "bbb"));
TEST_ASSERT(instance.kvs.set("cccc", "dd"));
TEST_ASSERT(instance.kvs.set("ee", "fffff"));
TEST_ASSERT(instance.kvs.set("cccc", "ff"));
TEST_ASSERT(original != instance.blob);
blob_type before(instance.blob);
// purge, insert again with updated values
TEST_ASSERT(instance.kvs.del("aaa"));
TEST_ASSERT(instance.kvs.del("cccc"));
TEST_ASSERT(instance.kvs.del("ee"));
TEST_ASSERT(instance.kvs.set("aaa", "bbb"));
TEST_ASSERT(instance.kvs.set("cccc", "ff"));
TEST_ASSERT(instance.kvs.set("ee", "fffff"));
blob_type after(instance.blob);
TEST_ASSERT(original != before);
TEST_ASSERT(original != after);
TEST_ASSERT(before == after);
}
}
template <size_t Size>
struct test_overflow_runner {
void operator ()() const {
StorageHandler<Size> instance;
TEST_ASSERT(instance.kvs.set("a", "b"));
TEST_ASSERT(instance.kvs.set("c", "d"));
TEST_ASSERT_EQUAL(2, instance.kvs.count());
TEST_ASSERT_FALSE(instance.kvs.set("e", "f"));
TEST_ASSERT(instance.kvs.del("a"));
TEST_ASSERT_EQUAL(1, instance.kvs.count());
TEST_ASSERT(instance.kvs.set("e", "f"));
TEST_ASSERT_EQUAL(2, instance.kvs.count());
check_kv(instance, "e", "f");
check_kv(instance, "c", "d");
}
};
void test_overflow() {
// slightly more that available, but we cannot fit the key
test_overflow_runner<16>();
// no more space
test_overflow_runner<12>();
}
void test_small_gaps() {
// ensure we can intemix empty and non-empty values
TestStorageHandler instance;
TEST_ASSERT(instance.kvs.set("key", "value"));
TEST_ASSERT(instance.kvs.set("empty", ""));
TEST_ASSERT(instance.kvs.set("empty_again", ""));
TEST_ASSERT(instance.kvs.set("finally", "avalue"));
auto check_empty = [&instance](const String& key) {
auto result = instance.kvs.get(key);
TEST_ASSERT(static_cast<bool>(result));
TEST_ASSERT_FALSE(result.length());
};
check_empty("empty_again");
check_empty("empty");
check_empty("empty_again");
check_empty("empty");
auto check_value = [&instance](const String& key, const String& value) {
auto result = instance.kvs.get(key);
TEST_ASSERT(static_cast<bool>(result));
TEST_ASSERT(result.length());
TEST_ASSERT_EQUAL_STRING(value.c_str(), result.c_str());
};
check_value("finally", "avalue");
check_value("key", "value");
}
void test_remove_randomized() {
// ensure we can remove keys in any order
// 8 seems like a good number to stop on, 9 will spend ~10seconds
// TODO: seems like a good start benchmarking read / write performance?
constexpr size_t KeysNumber = 8;
TestSequentialKvGenerator generator(TestSequentialKvGenerator::Mode::IncreasingLength);
auto kvs = generator.make(KeysNumber);
// generate indexes array to allow us to reference keys at random
TestStorageHandler instance;
std::array<size_t, KeysNumber> indexes;
std::iota(indexes.begin(), indexes.end(), 0);
// - insert keys sequentially
// - remove keys based on the order provided by next_permutation()
size_t index = 0;
do {
TEST_ASSERT_EQUAL(0, instance.kvs.count());
for (auto& kv : kvs) {
TEST_ASSERT(instance.kvs.set(kv.first, kv.second));
}
for (auto index : indexes) {
auto key = kvs[index].first;
TEST_ASSERT(static_cast<bool>(instance.kvs.get(key)));
TEST_ASSERT(instance.kvs.del(key));
TEST_ASSERT_FALSE(static_cast<bool>(instance.kvs.get(key)));
}
index++;
} while (std::next_permutation(indexes.begin(), indexes.end()));
String message("- keys: ");
message += KeysNumber;
message += ", permutations: ";
message += index;
TEST_MESSAGE(message.c_str());
}
void test_basic() {
TestStorageHandler instance;
constexpr size_t KeysNumber = 5;
// ensure insert works
TestSequentialKvGenerator generator;
auto kvs = generator.make(KeysNumber);
for (auto& kv : kvs) {
instance.kvs.set(kv.first, kv.second);
}
// and we can retrieve keys back
for (auto& kv : kvs) {
auto result = instance.kvs.get(kv.first);
TEST_ASSERT(static_cast<bool>(result));
TEST_ASSERT_EQUAL_STRING(kv.second.c_str(), result.c_str());
}
}
void test_storage() {
constexpr size_t Size = 32;
StorageHandler<Size> instance;
// empty keys are invalid
TEST_ASSERT_FALSE(instance.kvs.set("", "value1"));
TEST_ASSERT_FALSE(instance.kvs.del(""));
// ...and both keys are not yet set
TEST_ASSERT_FALSE(instance.kvs.del("key1"));
TEST_ASSERT_FALSE(instance.kvs.del("key2"));
// some different ways to set keys
TEST_ASSERT(instance.kvs.set("key1", "value0"));
TEST_ASSERT_EQUAL(1, instance.kvs.count());
TEST_ASSERT(instance.kvs.set("key1", "value1"));
TEST_ASSERT_EQUAL(1, instance.kvs.count());
TEST_ASSERT(instance.kvs.set("key2", "value_old"));
TEST_ASSERT_EQUAL(2, instance.kvs.count());
TEST_ASSERT(instance.kvs.set("key2", "value2"));
TEST_ASSERT_EQUAL(2, instance.kvs.count());
auto kvsize = settings::embedis::estimate("key1", "value1");
TEST_ASSERT_EQUAL((Size - (2 * kvsize)), instance.kvs.available());
// checking keys one by one by using a separate kvs object,
// working on the same underlying data-store
using storage_type = decltype(instance)::storage_type;
using kvs_type = decltype(instance)::kvs_type;
// - ensure we can operate with storage offsets
// - test for internal length optimization that will overwrite the key in-place
// - make sure we did not break the storage above
// storage_type accepts reference to the blob, so we can seamlessly use the same
// underlying data storage and share it between kvs instances
{
kvs_type slice(storage_type(instance.blob), (Size - kvsize), Size);
TEST_ASSERT_EQUAL(1, slice.count());
TEST_ASSERT_EQUAL(kvsize, slice.size());
TEST_ASSERT_EQUAL(0, slice.available());
auto result = slice.get("key1");
TEST_ASSERT(static_cast<bool>(result));
TEST_ASSERT_EQUAL_STRING("value1", result.c_str());
}
// ensure that right offset also works
{
kvs_type slice(storage_type(instance.blob), 0, (Size - kvsize));
TEST_ASSERT_EQUAL(1, slice.count());
TEST_ASSERT_EQUAL((Size - kvsize), slice.size());
TEST_ASSERT_EQUAL((Size - kvsize - kvsize), slice.available());
auto result = slice.get("key2");
TEST_ASSERT(static_cast<bool>(result));
TEST_ASSERT_EQUAL_STRING("value2", result.c_str());
}
// ensure offset does not introduce offset bugs
// for instance, test in-place key overwrite by moving left boundary 2 bytes to the right
{
const auto available = instance.kvs.available();
const auto offset = 2;
TEST_ASSERT_GREATER_OR_EQUAL(offset, available);
kvs_type slice(storage_type(instance.blob), offset, Size);
TEST_ASSERT_EQUAL(2, slice.count());
auto key1 = slice.get("key1");
TEST_ASSERT(static_cast<bool>(key1));
String updated(key1.ref());
for (size_t index = 0; index < key1.length(); ++index) {
updated[index] = 'A';
}
TEST_ASSERT(slice.set("key1", updated));
TEST_ASSERT(slice.set("key2", updated));
TEST_ASSERT_EQUAL(2, slice.count());
auto check_key1 = slice.get("key1");
TEST_ASSERT(static_cast<bool>(check_key1));
TEST_ASSERT_EQUAL_STRING(updated.c_str(), check_key1.c_str());
auto check_key2 = slice.get("key2");
TEST_ASSERT(static_cast<bool>(check_key2));
TEST_ASSERT_EQUAL_STRING(updated.c_str(), check_key2.c_str());
TEST_ASSERT_EQUAL(available - offset, slice.available());
}
}
void test_keys_iterator() {
constexpr size_t Size = 32;
StorageHandler<Size> instance;
TEST_ASSERT_EQUAL(Size, instance.kvs.available());
TEST_ASSERT_EQUAL(Size, instance.kvs.size());
TEST_ASSERT(instance.kvs.set("key", "value"));
TEST_ASSERT(instance.kvs.set("another", "thing"));
// ensure we get the same order of keys when iterating via foreach
std::vector<String> keys;
instance.kvs.foreach([&keys](decltype(instance)::kvs_type::KeyValueResult&& kv) {
keys.push_back(kv.key.read());
});
TEST_ASSERT_EQUAL(2, keys.size());
TEST_ASSERT_EQUAL(2, instance.kvs.count());
TEST_ASSERT_EQUAL_STRING("key", keys[0].c_str());
TEST_ASSERT_EQUAL_STRING("another", keys[1].c_str());
}
int main(int, char**) {
UNITY_BEGIN();
RUN_TEST(test_storage);
RUN_TEST(test_keys_iterator);
RUN_TEST(test_basic);
RUN_TEST(test_remove_randomized);
RUN_TEST(test_small_gaps);
RUN_TEST(test_overflow);
RUN_TEST(test_perseverance);
RUN_TEST(test_longkey);
RUN_TEST(test_sizes);
return UNITY_END();
}

View File

@@ -0,0 +1,266 @@
#include <unity.h>
#include <Arduino.h>
#include <StreamString.h>
#include <terminal_commands.h>
// TODO: should we just use std::function at this point?
// we don't actually benefit from having basic ptr functions in handler
// test would be simplified too, we would no longer need to have static vars
// Got the idea from the Embedis test suite, set up a proxy for StreamString
// Real terminal processing happens with ringbuffer'ed stream
struct IOStreamString : public Stream {
StreamString in;
StreamString out;
size_t write(uint8_t ch) final override {
return in.write(ch);
}
int read() final override {
return out.read();
}
int available() final override {
return out.available();
}
int peek() final override {
return out.peek();
}
void flush() final override {
out.flush();
}
};
// We need to make sure that our changes to split_args actually worked
void test_hex_codes() {
static bool abc_done = false;
terminal::Terminal::addCommand(F("abc"), [](::terminal::CommandContext&& ctx) {
TEST_ASSERT_EQUAL(2, ctx.argv.size());
TEST_ASSERT_EQUAL_STRING("abc", ctx.argv[0].c_str());
TEST_ASSERT_EQUAL_STRING("abc", ctx.argv[1].c_str());
abc_done = true;
});
IOStreamString str;
str.out += String("abc \"\x61\x62\x63\"\r\n");
terminal::Terminal handler(str);
TEST_ASSERT_EQUAL(
terminal::Terminal::Result::Command,
handler.processLine()
);
TEST_ASSERT(abc_done);
}
// Ensure that we can register multiple commands (at least 3, might want to test much more in the future?)
// Ensure that registered commands can be called and they are called in order
void test_multiple_commands() {
// set up counter to be chained between commands
static int command_calls = 0;
terminal::Terminal::addCommand(F("test1"), [](::terminal::CommandContext&& ctx) {
TEST_ASSERT_EQUAL_MESSAGE(1, ctx.argv.size(), "Command without args should have argc == 1");
TEST_ASSERT_EQUAL(0, command_calls);
command_calls = 1;
});
terminal::Terminal::addCommand(F("test2"), [](::terminal::CommandContext&& ctx) {
TEST_ASSERT_EQUAL_MESSAGE(1, ctx.argv.size(), "Command without args should have argc == 1");
TEST_ASSERT_EQUAL(1, command_calls);
command_calls = 2;
});
terminal::Terminal::addCommand(F("test3"), [](::terminal::CommandContext&& ctx) {
TEST_ASSERT_EQUAL_MESSAGE(1, ctx.argv.size(), "Command without args should have argc == 1");
TEST_ASSERT_EQUAL(2, command_calls);
command_calls = 3;
});
IOStreamString str;
str.out += String("test1\r\ntest2\r\ntest3\r\n");
terminal::Terminal handler(str);
// each processing step only executes a single command
static int process_counter = 0;
handler.process([](terminal::Terminal::Result result) -> bool {
if (process_counter == 3) {
TEST_ASSERT_EQUAL(result, terminal::Terminal::Result::NoInput);
return false;
} else {
TEST_ASSERT_EQUAL(result, terminal::Terminal::Result::Command);
++process_counter;
return true;
}
TEST_FAIL_MESSAGE("Should not be reached");
return false;
});
TEST_ASSERT_EQUAL(3, command_calls);
TEST_ASSERT_EQUAL(3, process_counter);
}
void test_command() {
static int counter = 0;
terminal::Terminal::addCommand(F("test.command"), [](::terminal::CommandContext&& ctx) {
TEST_ASSERT_EQUAL_MESSAGE(1, ctx.argv.size(), "Command without args should have argc == 1");
++counter;
});
IOStreamString str;
terminal::Terminal handler(str);
TEST_ASSERT_EQUAL_MESSAGE(
terminal::Terminal::Result::NoInput, handler.processLine(),
"We have not read anything yet"
);
str.out += String("test.command\r\n");
TEST_ASSERT_EQUAL(terminal::Terminal::Result::Command, handler.processLine());
TEST_ASSERT_EQUAL_MESSAGE(1, counter, "At this time `test.command` was called just once");
str.out += String("test.command");
TEST_ASSERT_EQUAL(terminal::Terminal::Result::Pending, handler.processLine());
TEST_ASSERT_EQUAL_MESSAGE(1, counter, "We are waiting for either \\r\\n or \\n, handler still has data buffered");
str.out += String("\r\n");
TEST_ASSERT_EQUAL(terminal::Terminal::Result::Command, handler.processLine());
TEST_ASSERT_EQUAL_MESSAGE(2, counter, "We should call `test.command` the second time");
str.out += String("test.command\n");
TEST_ASSERT_EQUAL(terminal::Terminal::Result::Command, handler.processLine());
TEST_ASSERT_EQUAL_MESSAGE(3, counter, "We should call `test.command` the third time, with just LF");
}
// Ensure that we can properly handle arguments
void test_command_args() {
static bool waiting = false;
terminal::Terminal::addCommand(F("test.command.arg1"), [](::terminal::CommandContext&& ctx) {
TEST_ASSERT_EQUAL(2, ctx.argv.size());
waiting = false;
});
terminal::Terminal::addCommand(F("test.command.arg1_empty"), [](::terminal::CommandContext&& ctx) {
TEST_ASSERT_EQUAL(2, ctx.argv.size());
TEST_ASSERT(!ctx.argv[1].length());
waiting = false;
});
IOStreamString str;
terminal::Terminal handler(str);
waiting = true;
str.out += String("test.command.arg1 test\r\n");
TEST_ASSERT_EQUAL(terminal::Terminal::Result::Command, handler.processLine());
TEST_ASSERT(!waiting);
waiting = true;
str.out += String("test.command.arg1_empty \"\"\r\n");
TEST_ASSERT_EQUAL(terminal::Terminal::Result::Command, handler.processLine());
TEST_ASSERT(!waiting);
}
// Ensure that we return error when nothing was handled, but we kept feeding the processLine() with data
void test_buffer() {
IOStreamString str;
str.out += String("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n");
terminal::Terminal handler(str, str.out.available() - 8);
TEST_ASSERT_EQUAL(terminal::Terminal::Result::BufferOverflow, handler.processLine());
}
// sdssplitargs returns nullptr when quotes are not terminated and empty char for an empty string. we treat it all the same
void test_quotes() {
terminal::Terminal::addCommand(F("test.quotes"), [](::terminal::CommandContext&& ctx) {
for (auto& arg : ctx.argv) {
TEST_MESSAGE(arg.c_str());
}
TEST_FAIL_MESSAGE("`test.quotes` should not be called");
});
IOStreamString str;
terminal::Terminal handler(str);
str.out += String("test.quotes \"quote without a pair\r\n");
TEST_ASSERT_EQUAL(terminal::Terminal::Result::NoInput, handler.processLine());
str.out += String("test.quotes 'quote without a pair\r\n");
TEST_ASSERT_EQUAL(terminal::Terminal::Result::NoInput, handler.processLine());
TEST_ASSERT_EQUAL(terminal::Terminal::Result::NoInput, handler.processLine());
}
// we specify that commands lowercase == UPPERCASE, both with hashed values and with equality functions
// (internal note: we use std::unordered_map at this time)
void test_case_insensitive() {
terminal::Terminal::addCommand(F("test.lowercase1"), [](::terminal::CommandContext&&) {
TEST_FAIL_MESSAGE("`test.lowercase1` was registered first, but there's another function by the same name. This should not be called");
});
terminal::Terminal::addCommand(F("TEST.LOWERCASE1"), [](::terminal::CommandContext&&) {
__asm__ volatile ("nop");
});
IOStreamString str;
terminal::Terminal handler(str);
str.out += String("TeSt.lOwErCaSe1\r\n");
TEST_ASSERT_EQUAL(terminal::Terminal::Result::Command, handler.processLine());
}
// We can use command ctx.output to send something back into the stream
void test_output() {
terminal::Terminal::addCommand(F("test.output"), [](::terminal::CommandContext&& ctx) {
if (ctx.argv.size() != 2) return;
ctx.output.print(ctx.argv[1]);
});
IOStreamString str;
terminal::Terminal handler(str);
char match[] = "test1234567890";
str.out += String("test.output ") + String(match) + String("\r\n");
TEST_ASSERT_EQUAL(terminal::Terminal::Result::Command, handler.processLine());
TEST_ASSERT_EQUAL_STRING(match, str.in.c_str());
}
// When adding test functions, don't forget to add RUN_TEST(...) in the main()
int main(int, char**) {
UNITY_BEGIN();
RUN_TEST(test_command);
RUN_TEST(test_command_args);
RUN_TEST(test_multiple_commands);
RUN_TEST(test_hex_codes);
RUN_TEST(test_buffer);
RUN_TEST(test_quotes);
RUN_TEST(test_case_insensitive);
RUN_TEST(test_output);
return UNITY_END();
}

View File

@@ -0,0 +1,318 @@
#include <Arduino.h>
#include <Stream.h>
#include <unity.h>
// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------
#include <type_traits>
#include <queue>
#include "libs/TypeChecks.h"
#include "tuya_types.h"
#include "tuya_util.h"
#include "tuya_transport.h"
#include "tuya_protocol.h"
#include "tuya_dataframe.h"
using namespace tuya;
template <typename T>
static bool datatype_same(const T& frame, const Type expect_type) {
const auto type = dataType(frame);
return expect_type == type;
}
void test_dpmap() {
DpMap map;
// id <-> dp
map.add(1, 2);
map.add(3, 4);
map.add(5, 6);
map.add(7, 8);
TEST_ASSERT_EQUAL(4, map.size());
map.add(7,10);
map.add(5,5);
// dpmap is a 'set' of values
TEST_ASSERT_EQUAL(4, map.size());
#define TEST_FIND_DP_ID(EXPECTED_DP_ID, EXPECTED_LOCAL_ID) \
{\
auto* entry = map.find_dp(EXPECTED_DP_ID);\
TEST_ASSERT(entry != nullptr);\
TEST_ASSERT_EQUAL(EXPECTED_DP_ID, entry->dp_id);\
TEST_ASSERT_EQUAL(EXPECTED_LOCAL_ID, entry->local_id);\
}
TEST_FIND_DP_ID(2, 1);
TEST_FIND_DP_ID(4, 3);
TEST_FIND_DP_ID(6, 5);
TEST_FIND_DP_ID(8, 7);
#define TEST_FIND_LOCAL_ID(EXPECTED_LOCAL_ID, EXPECTED_DP_ID) \
{\
auto* entry = map.find_local(EXPECTED_LOCAL_ID);\
TEST_ASSERT(entry != nullptr);\
TEST_ASSERT_EQUAL(EXPECTED_DP_ID, entry->dp_id);\
TEST_ASSERT_EQUAL(EXPECTED_LOCAL_ID, entry->local_id);\
}
TEST_FIND_LOCAL_ID(1, 2);
TEST_FIND_LOCAL_ID(3, 4);
TEST_FIND_LOCAL_ID(5, 6);
TEST_FIND_LOCAL_ID(7, 8);
#undef TEST_FIND_LOCAL_ID
#undef TEST_FIND_DP_ID
}
void test_static_dataframe_bool() {
DataFrame frame(Command::SetDP, DataProtocol<bool>(0x02, false).serialize());
TEST_ASSERT_EQUAL_MESSAGE(0, frame.version(),
"Version should stay 0 unless explicitly set");
TEST_ASSERT_MESSAGE((frame.command() == Command::SetDP),
"commandEquals should return true with the same arg as in the constructor");
TEST_ASSERT_MESSAGE(datatype_same(frame, Type::BOOL),
"DataProtocol<bool> should translate to Type::BOOL");
}
void test_static_dataframe_int() {
DataFrame frame(Command::ReportDP, DataProtocol<uint32_t>(0x03, 255).serialize());
TEST_ASSERT_EQUAL_MESSAGE(0, frame.version(),
"Version should stay 0 unless explicitly set");
TEST_ASSERT_MESSAGE((frame.command() == Command::ReportDP),
"commandEquals should return true with the same arg as in the constructor");
TEST_ASSERT_EQUAL_UINT_MESSAGE(std::distance(frame.cbegin(), frame.cend()), frame.length(),
"Data is expected to be stored in a contigious memory and be equal in length to the ::length attribute");
TEST_ASSERT_EQUAL_MESSAGE(0, frame[5],
"Only last byte should be set");
TEST_ASSERT_EQUAL_MESSAGE(255, frame[7],
"Only last byte should be set");
}
void test_static_dataframe_heartbeat() {
DataFrame frame(Command::Heartbeat);
TEST_ASSERT_EQUAL_MESSAGE(0, frame.length(),
"Frame with Command::Heartbeat should not have any data attached to it");
TEST_ASSERT_EQUAL_MESSAGE(0, std::distance(frame.cbegin(), frame.cend()),
"Frame with Command::SetDP should not have any data attached to it");
//test_hexdump("static", static_frame.serialize());
}
void test_dataframe_const() {
const DataFrame frame(Command::SetDP);
TEST_ASSERT_EQUAL_MESSAGE(0, frame.length(),
"Frame with Command::SetDP should not have any data attached to it");
TEST_ASSERT_EQUAL_MESSAGE(0, std::distance(frame.cbegin(), frame.cend()),
"Frame with Command::SetDP should not have any data attached to it");
}
void test_dataframe_copy() {
DataFrame frame(Command::Heartbeat, 0x7f, container{1,2,3});
DataFrame moved_frame(std::move(frame));
TEST_ASSERT_EQUAL(3, moved_frame.length());
TEST_ASSERT_EQUAL(3, moved_frame.length());
TEST_ASSERT_EQUAL_MESSAGE(0x7f, moved_frame.version(),
"DataFrame should be movable object");
DataFrame copied_frame(moved_frame);
TEST_ASSERT_EQUAL(3, copied_frame.length());
TEST_ASSERT_EQUAL_MESSAGE(0x7f, copied_frame.version(),
"DataFrame should not be copyable");
}
void test_dataframe_raw_data() {
{
container data = {0x00, 0x00, 0x00, 0x01, 0x01};
DataFrameView frame(data);
TEST_ASSERT_MESSAGE((frame.command() == Command::Heartbeat),
"This message should be parsed as heartbeat");
TEST_ASSERT_EQUAL_MESSAGE(0, frame.version(),
"This message should have version == 0");
TEST_ASSERT_EQUAL_MESSAGE(1, frame.length(),
"Heartbeat message contains a single byte");
TEST_ASSERT_EQUAL_MESSAGE(1, frame[0],
"Heartbeat message contains a single 0x01");
auto serialized = frame.serialize();
TEST_ASSERT_MESSAGE(std::equal(data.begin(), data.end(), serialized.begin()),
"Serialized frame should match the original data");
}
{
container data = {0x00, 0x07, 0x00, 0x05, 0x01, 0x01, 0x00, 0x01, 0x01};
DataFrameView frame(data);
TEST_ASSERT_MESSAGE((frame.command() == Command::ReportDP),
"This message should be parsed as data protocol");
TEST_ASSERT_MESSAGE(datatype_same(frame, Type::BOOL),
"This message should have boolean datatype attached to it");
TEST_ASSERT_EQUAL_MESSAGE(5, frame.length(),
"Boolean DP contains 5 bytes");
const DataProtocol<bool> dp(frame.data());
TEST_ASSERT_EQUAL_MESSAGE(1, dp.id(), "This boolean DP id should be 1");
TEST_ASSERT_MESSAGE(dp.value(), "This boolean DP value should be true");
auto serialized = frame.serialize();
TEST_ASSERT_MESSAGE(std::equal(data.begin(), data.end(), serialized.begin()),
"Serialized frame should match the original data");
}
//show_datatype(frame);
//std::cout << "length=" << frame.length << std::endl;
//test_hexdump("input", frame.serialize());
//std::cout << "[" << millis() << "] -------------------bad dp frame----------------" << std::endl;
//DataFrame bad_dp_frame(Command::ReportDP, DataProtocol<uint32_t>(0x03, 255).serialize());
//show_datatype(bad_dp_frame);
//std::cout << "length=" << bad_dp_frame.length << std::endl;
//test_hexdump("input", bad_dp_frame.serialize());
}
class BufferedStream : public Stream {
public:
// Print interface
size_t write(uint8_t c) {
_buffer.push((int)c);
return 1;
}
size_t write(const unsigned char* data, unsigned long size) {
for (size_t n = 0; n < size; ++n) {
_buffer.push(data[n]);
}
return size;
}
int availableForWrite() { return 1; }
void flush() {
while (!_buffer.empty()) {
_buffer.pop();
}
}
// Stream interface
int available() {
return _buffer.size();
}
int read() {
if (!_buffer.size()) return -1;
int c = _buffer.front();
_buffer.pop();
return c;
}
int peek() {
if (!_buffer.size()) return -1;
return _buffer.front();
}
private:
std::queue<int> _buffer;
};
void test_transport() {
container data = {0x55, 0xaa, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01};
BufferedStream stream;
stream.write(data.data(), data.size());
Transport transport(stream);
TEST_ASSERT(transport.available());
for (size_t n = 0; n < data.size(); ++n) {
transport.read();
}
TEST_ASSERT(transport.done());
}
void test_dataframe_report() {
container input = {0x55, 0xaa, 0x00, 0x07, 0x00, 0x08, 0x02, 0x02, 0x00, 0x04, 0x00, 0x00, 0x00, 0x10, 0x26};
BufferedStream stream;
stream.write(input.data(), input.size());
Transport transport(stream);
while (transport.available()) {
transport.read();
}
TEST_ASSERT(transport.done());
DataFrameView frame(transport);
TEST_ASSERT(frame.command() == Command::ReportDP);
TEST_ASSERT_EQUAL(Type::INT, dataType(frame));
TEST_ASSERT_EQUAL(8, frame.length());
TEST_ASSERT_EQUAL(0, frame.version());
DataProtocol<uint32_t> proto(frame.data());
TEST_ASSERT_EQUAL(0x02, proto.id());
TEST_ASSERT_EQUAL(0x10, proto.value());
}
void test_dataframe_echo() {
BufferedStream stream;
Transport transport(stream);
{
DataProtocol<uint32_t> proto(0x02, 0x66);
TEST_ASSERT_EQUAL(0x02, proto.id());
TEST_ASSERT_EQUAL(0x66,proto.value());
DataFrame frame(Command::SetDP, proto.serialize());
transport.write(frame.serialize());
}
while (transport.available()) {
transport.read();
}
TEST_ASSERT(transport.done());
{
DataFrameView frame(transport);
TEST_ASSERT(frame.command() == Command::SetDP);
TEST_ASSERT_EQUAL(Type::INT, dataType(frame));
TEST_ASSERT_EQUAL(8, frame.length());
TEST_ASSERT_EQUAL(0, frame.version());
DataProtocol<uint32_t> proto(frame.data());
TEST_ASSERT_EQUAL(0x02, proto.id());
TEST_ASSERT_EQUAL(0x66, proto.value());
}
}
int main(int, char**) {
UNITY_BEGIN();
RUN_TEST(test_dpmap);
RUN_TEST(test_static_dataframe_bool);
RUN_TEST(test_static_dataframe_int);
RUN_TEST(test_static_dataframe_heartbeat);
RUN_TEST(test_dataframe_const);
RUN_TEST(test_dataframe_copy);
RUN_TEST(test_dataframe_raw_data);
RUN_TEST(test_dataframe_report);
RUN_TEST(test_dataframe_echo);
RUN_TEST(test_transport);
return UNITY_END();
}

View File

@@ -0,0 +1,14 @@
// minimal set of functions that are supposed to be linked with the unity.c
void setUp(void) {
}
void tearDown(void) {
}
void suiteSetUp(void) {
}
int suiteTearDown(int failures) {
return failures;
}

View File

@@ -0,0 +1,17 @@
#include <Arduino.h>
#include <unity.h>
#include "libs/URL.h"
void test_parse() {
URL url("http://api.thingspeak.com/update");
TEST_ASSERT_EQUAL_STRING("api.thingspeak.com", url.host.c_str());
TEST_ASSERT_EQUAL_STRING("/update", url.path.c_str());
TEST_ASSERT_EQUAL(80, url.port);
}
int main(int, char**) {
UNITY_BEGIN();
RUN_TEST(test_parse);
return UNITY_END();
}