From 3fcc9a3c83c807792846ae2c9f98aeb447e62805 Mon Sep 17 00:00:00 2001 From: iphydf Date: Sat, 3 Feb 2018 15:44:43 +0000 Subject: [PATCH] Add some unit tests for util.h. --- CMakeLists.txt | 1 + toxcore/BUILD.bazel | 9 +++++++ toxcore/util.h | 8 +++++++ toxcore/util_test.cpp | 55 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 73 insertions(+) create mode 100644 toxcore/util_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 742facd1..a52f11bb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -470,6 +470,7 @@ endfunction() # The actual unit tests follow. # unit_test(toxcore crypto_core) +unit_test(toxcore util) ################################################################################ # diff --git a/toxcore/BUILD.bazel b/toxcore/BUILD.bazel index 3b96dd6d..934ff16c 100644 --- a/toxcore/BUILD.bazel +++ b/toxcore/BUILD.bazel @@ -72,6 +72,15 @@ cc_library( ], ) +cc_test( + name = "util_test", + srcs = ["util_test.cpp"], + deps = [ + ":network", + "@gtest", + ], +) + cc_library( name = "ping_array", srcs = ["ping_array.c"], diff --git a/toxcore/util.h b/toxcore/util.h index 8777e191..8c86158b 100644 --- a/toxcore/util.h +++ b/toxcore/util.h @@ -32,6 +32,10 @@ #include "logger.h" +#ifdef __cplusplus +extern "C" { +#endif + #define MIN(a,b) (((a)<(b))?(a):(b)) #define PAIR(TYPE1__, TYPE2__) struct { TYPE1__ first; TYPE2__ second; } @@ -61,4 +65,8 @@ int load_state(load_state_callback_func load_state_callback, Logger *log, void * /* Returns -1 if failed or 0 if success */ int create_recursive_mutex(pthread_mutex_t *mutex); +#ifdef __cplusplus +} // extern "C" +#endif + #endif /* UTIL_H */ diff --git a/toxcore/util_test.cpp b/toxcore/util_test.cpp new file mode 100644 index 00000000..8de63848 --- /dev/null +++ b/toxcore/util_test.cpp @@ -0,0 +1,55 @@ +#include "util.h" + +#include "crypto_core.h" + +#include + +TEST(Util, UnixTimeIncreasesOverTime) +{ + unix_time_update(); + uint64_t const start = unix_time(); + + while (start == unix_time()) { + unix_time_update(); + } + + uint64_t const end = unix_time(); + EXPECT_GT(end, start); +} + +TEST(Util, IsTimeout) +{ + uint64_t const start = unix_time(); + EXPECT_FALSE(is_timeout(start, 1)); + + while (start == unix_time()) { + unix_time_update(); + } + + EXPECT_TRUE(is_timeout(start, 1)); +} + +TEST(Util, TwoRandomIdsAreNotEqual) +{ + uint8_t pk1[CRYPTO_PUBLIC_KEY_SIZE]; + uint8_t sk1[CRYPTO_SECRET_KEY_SIZE]; + uint8_t pk2[CRYPTO_PUBLIC_KEY_SIZE]; + uint8_t sk2[CRYPTO_SECRET_KEY_SIZE]; + + crypto_new_keypair(pk1, sk1); + crypto_new_keypair(pk2, sk2); + + EXPECT_FALSE(id_equal(pk1, pk2)); +} + +TEST(Util, IdCopyMakesKeysEqual) +{ + uint8_t pk1[CRYPTO_PUBLIC_KEY_SIZE]; + uint8_t sk1[CRYPTO_SECRET_KEY_SIZE]; + uint8_t pk2[CRYPTO_PUBLIC_KEY_SIZE] = {0}; + + crypto_new_keypair(pk1, sk1); + id_copy(pk2, pk1); + + EXPECT_TRUE(id_equal(pk1, pk2)); +}