TestCase.h 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. void set_suite_setup_function(Function<void()> setup);
  34. }
  35. #define TEST_SETUP \
  36. static void __setup(); \
  37. struct __setup_type { \
  38. __setup_type() { Test::set_suite_setup_function(__setup); } \
  39. }; \
  40. static struct __setup_type __setup_type; \
  41. static void __setup()
  42. #define __TESTCASE_FUNC(x) __test_##x
  43. #define __TESTCASE_TYPE(x) __TestCase_##x
  44. #define TEST_CASE(x) \
  45. static void __TESTCASE_FUNC(x)(); \
  46. struct __TESTCASE_TYPE(x) { \
  47. __TESTCASE_TYPE(x) \
  48. () { add_test_case_to_suite(adopt_ref(*new ::Test::TestCase(#x, __TESTCASE_FUNC(x), false))); } \
  49. }; \
  50. static struct __TESTCASE_TYPE(x) __TESTCASE_TYPE(x); \
  51. static void __TESTCASE_FUNC(x)()
  52. #define __BENCHMARK_FUNC(x) __benchmark_##x
  53. #define __BENCHMARK_TYPE(x) __BenchmarkCase_##x
  54. #define BENCHMARK_CASE(x) \
  55. static void __BENCHMARK_FUNC(x)(); \
  56. struct __BENCHMARK_TYPE(x) { \
  57. __BENCHMARK_TYPE(x) \
  58. () { add_test_case_to_suite(adopt_ref(*new ::Test::TestCase(#x, __BENCHMARK_FUNC(x), true))); } \
  59. }; \
  60. static struct __BENCHMARK_TYPE(x) __BENCHMARK_TYPE(x); \
  61. static void __BENCHMARK_FUNC(x)()