From 3c3ae8232d393f0f21cf44603599ad753bd12c45 Mon Sep 17 00:00:00 2001 From: Tijmen van Nesselrooij Date: Sun, 28 Apr 2019 16:10:11 +0200 Subject: [PATCH] binary tree tests added --- tests/binarytree.cpp | 86 ++++++++++++++++++++++++++++++++++++++++++++ tests/testutil.hpp | 16 +++++++++ 2 files changed, 102 insertions(+) create mode 100644 tests/binarytree.cpp create mode 100644 tests/testutil.hpp diff --git a/tests/binarytree.cpp b/tests/binarytree.cpp new file mode 100644 index 0000000..71ba9fa --- /dev/null +++ b/tests/binarytree.cpp @@ -0,0 +1,86 @@ +#include "../binary-trees/binarytree.hpp" +#include +#include "testutil.hpp" +#include + +unsigned static GetRandomNumber() +{ + static std::default_random_engine eng; + static std::uniform_int_distribution valueDist(0u, 8096u); + + return valueDist(eng); +} + +void FillWithRandomNumbers(BinaryTree::Tree & tree, + std::unordered_set & control, + unsigned const count = 512u) +{ + for(unsigned i = 0u; i < count; ++i) + { + unsigned const value = GetRandomNumber(); + control.insert(value); + tree.Insert(value); + } +} + +bool TestInsertContains() +{ + std::unordered_set control; + BinaryTree::Tree tree; + + FillWithRandomNumbers(tree, control); + + bool good = true; + for(auto const & num : control) + { + if(!tree.Contains(num)) + { + std::printf("Value %u inserted but cannot be found!\n", num); + good = false; + } + } + + return good; +} + +bool TestDeletion() +{ + std::unordered_set control; + BinaryTree::Tree tree; + + FillWithRandomNumbers(tree, control); + + unsigned i = 0u; + unsigned const toDeleteCount = control.size() / 4; + while(i < toDeleteCount) + { + auto const toDelete = GetRandomNumber(); + auto iter = control.find(toDelete); + if(iter != control.end()) + { + control.erase(iter); + tree.Delete(i); + ++i; + } + } + + bool good = true; + for(auto const & num : control) + { + if(!tree.Contains(num)) + { + std::printf("Value %u inserted but cannot be found!\n", num); + good = false; + } + } + + return good; +} + +int main() +{ + Test::Execute(TestInsertContains, "Insertion and find test"); + Test::Execute(TestDeletion, "Insertion and deletion test"); + + return 0; +} \ No newline at end of file diff --git a/tests/testutil.hpp b/tests/testutil.hpp new file mode 100644 index 0000000..04fe8eb --- /dev/null +++ b/tests/testutil.hpp @@ -0,0 +1,16 @@ +#include + +namespace Test +{ +void Execute(bool (*testFunction)(void), char const * const message) +{ + if(testFunction()) + { + std::printf("[PASS] %s\n", message); + } + else + { + std::printf("[FAIL] %s\n", message); + } +} +}; \ No newline at end of file