TestCase.h 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Andrew Kaster <akaster@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <LibTest/Macros.h> // intentionally first -- we redefine VERIFY and friends in here
  9. #include <AK/Function.h>
  10. #include <AK/NonnullRefPtr.h>
  11. #include <AK/RefCounted.h>
  12. #include <AK/String.h>
  13. namespace Test {
  14. using TestFunction = Function<void()>;
  15. class TestCase : public RefCounted<TestCase> {
  16. public:
  17. TestCase(const String& name, TestFunction&& fn, bool is_benchmark)
  18. : m_name(name)
  19. , m_function(move(fn))
  20. , m_is_benchmark(is_benchmark)
  21. {
  22. }
  23. bool is_benchmark() const { return m_is_benchmark; }
  24. const String& name() const { return m_name; }
  25. const TestFunction& func() const { return m_function; }
  26. private:
  27. String m_name;
  28. TestFunction m_function;
  29. bool m_is_benchmark;
  30. };
  31. // Helper to hide implementation of TestSuite from users
  32. void add_test_case_to_suite(const NonnullRefPtr<TestCase>& test_case);
  33. }
  34. #define __TESTCASE_FUNC(x) __test_##x
  35. #define __TESTCASE_TYPE(x) __TestCase_##x
  36. #define TEST_CASE(x) \
  37. static void __TESTCASE_FUNC(x)(); \
  38. struct __TESTCASE_TYPE(x) { \
  39. __TESTCASE_TYPE(x) \
  40. () { add_test_case_to_suite(adopt_ref(*new ::Test::TestCase(#x, __TESTCASE_FUNC(x), false))); } \
  41. }; \
  42. static struct __TESTCASE_TYPE(x) __TESTCASE_TYPE(x); \
  43. static void __TESTCASE_FUNC(x)()
  44. #define __BENCHMARK_FUNC(x) __benchmark_##x
  45. #define __BENCHMARK_TYPE(x) __BenchmarkCase_##x
  46. #define BENCHMARK_CASE(x) \
  47. static void __BENCHMARK_FUNC(x)(); \
  48. struct __BENCHMARK_TYPE(x) { \
  49. __BENCHMARK_TYPE(x) \
  50. () { add_test_case_to_suite(adopt_ref(*new ::Test::TestCase(#x, __BENCHMARK_FUNC(x), true))); } \
  51. }; \
  52. static struct __BENCHMARK_TYPE(x) __BENCHMARK_TYPE(x); \
  53. static void __BENCHMARK_FUNC(x)()