Skip to content

Instantly share code, notes, and snippets.

@nettle
Created August 1, 2019 12:04
Show Gist options
  • Select an option

  • Save nettle/5db56ab3cf34815ea4dc1850b5b2800a to your computer and use it in GitHub Desktop.

Select an option

Save nettle/5db56ab3cf34815ea4dc1850b5b2800a to your computer and use it in GitHub Desktop.

Revisions

  1. nettle created this gist Aug 1, 2019.
    83 changes: 83 additions & 0 deletions testsuite.cc
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,83 @@
    #include <iostream>
    #include <string>
    #include <vector>

    // Test suite controls test execution
    class TestSuite {
    public:
    // Abstract test case
    class TestCase {
    public:
    TestCase() {};
    TestCase(const char* n, const char* d)
    : name(n), description(d) {
    TestSuite::add(this);
    };
    virtual bool test() = 0;
    std::string name;
    std::string description;
    };

    static TestSuite& get() {
    static TestSuite testSuite;
    return testSuite;
    }
    static void add(TestCase* test) {
    get().tests.push_back(test);
    }
    static bool run() {
    bool allResults = true;
    for (auto t : get().tests) {
    bool result = t->test();
    std::cout << "[TestSuite::run] " << t->description << " : " << (result ? "PASS" : "FAIL") << std::endl;
    allResults = allResults && result;
    }
    return allResults;
    }
    private:
    std::vector<TestCase*> tests;
    };

    // TEST macro to use when defining tests
    #define TEST(name, description) \
    class TEST_##name##_Test : public TestSuite::TestCase { \
    public: \
    TEST_##name##_Test(const char* n, const char* d) \
    : TestSuite::TestCase(n, d) {} \
    bool test(); \
    } TEST_##name##_Test_instance(#name, description); \
    bool TEST_##name##_Test::test()


    // Example:
    TEST(TEST1, "Test aaa") {
    std::cout << "[TEST1] Zzzz..." << std::endl;
    return true;
    }

    TEST(TEST2, "Test bbb") {
    std::cout << "[TEST2] Hmmm..." << std::endl;
    return true;
    }

    // Cusomized test case
    class TEST3 : public TestSuite::TestCase {
    public:
    TEST3(const char* n, const char* d)
    : TestSuite::TestCase(n, d) {
    std::cout << "[TEST3] Custom constructor" << std::endl;
    }
    ~TEST3() {
    std::cout << "[TEST3] Custom destructor" << std::endl;
    }
    bool test() {
    std::cout << "[TEST3] No macro" << std::endl;
    return true;
    };
    } TEST3_instance("TEST3", "Test ccc");

    int main(void) {
    bool result = TestSuite::run();
    std::cout << "[main] Result: " << (result ? "PASS" : "FAIL") << std::endl;
    return (result ? 0 : 1);
    }