TestCase.h 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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/DeprecatedString.h>
  10. #include <AK/Function.h>
  11. #include <AK/NonnullRefPtr.h>
  12. #include <AK/RefCounted.h>
  13. namespace Test {
  14. using TestFunction = Function<void()>;
  15. class TestCase : public RefCounted<TestCase> {
  16. public:
  17. TestCase(DeprecatedString const& 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. DeprecatedString const& name() const { return m_name; }
  25. TestFunction const& func() const { return m_function; }
  26. private:
  27. DeprecatedString 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(NonnullRefPtr<TestCase> const& 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() \
  39. { \
  40. Test::set_suite_setup_function(__setup); \
  41. } \
  42. }; \
  43. static struct __setup_type __setup_type; \
  44. static void __setup()
  45. #define __TESTCASE_FUNC(x) __test_##x
  46. #define __TESTCASE_TYPE(x) __TestCase_##x
  47. #define TEST_CASE(x) \
  48. static void __TESTCASE_FUNC(x)(); \
  49. struct __TESTCASE_TYPE(x) { \
  50. __TESTCASE_TYPE(x) \
  51. () \
  52. { \
  53. add_test_case_to_suite(adopt_ref(*new ::Test::TestCase(#x, __TESTCASE_FUNC(x), false))); \
  54. } \
  55. }; \
  56. static struct __TESTCASE_TYPE(x) __TESTCASE_TYPE(x); \
  57. static void __TESTCASE_FUNC(x)()
  58. #define __BENCHMARK_FUNC(x) __benchmark_##x
  59. #define __BENCHMARK_TYPE(x) __BenchmarkCase_##x
  60. #define BENCHMARK_CASE(x) \
  61. static void __BENCHMARK_FUNC(x)(); \
  62. struct __BENCHMARK_TYPE(x) { \
  63. __BENCHMARK_TYPE(x) \
  64. () \
  65. { \
  66. add_test_case_to_suite(adopt_ref(*new ::Test::TestCase(#x, __BENCHMARK_FUNC(x), true))); \
  67. } \
  68. }; \
  69. static struct __BENCHMARK_TYPE(x) __BENCHMARK_TYPE(x); \
  70. static void __BENCHMARK_FUNC(x)()