1 // Copyright 2020 The Pigweed Authors
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
7 // https://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
15 // The Pigweed unit test framework requires C++17 to use its full functionality.
16 // In C++11, only the TEST, TEST_F, EXPECT_TRUE, EXPECT_FALSE, ASSERT_TRUE,
17 // ASSERT_FALSE, FAIL, and ADD_FAILURE macros may be used.
26 #include "pw_polyfill/standard.h"
27 #include "pw_preprocessor/concat.h"
28 #include "pw_preprocessor/util.h"
29 #include "pw_unit_test/event_handler.h"
31 #if PW_CXX_STANDARD_IS_SUPPORTED(17)
32 #include "pw_string/string_builder.h"
33 #endif // PW_CXX_STANDARD_IS_SUPPORTED(17)
35 #define PW_TEST(test_suite_name, test_name) \
36 _PW_TEST(test_suite_name, test_name, ::pw::unit_test::Test)
38 // TEST() is a pretty generic macro name which could conflict with other code.
39 // If GTEST_DONT_DEFINE_TEST is set, don't alias PW_TEST to TEST.
40 #if !(defined(GTEST_DONT_DEFINE_TEST) && GTEST_DONT_DEFINE_TEST)
42 #endif // !GTEST_DONT_DEFINE_TEST
44 #define TEST_F(test_fixture, test_name) \
45 _PW_TEST(test_fixture, test_name, test_fixture)
47 #define EXPECT_TRUE(expr) _PW_EXPECT_BOOL(expr, true)
48 #define EXPECT_FALSE(expr) _PW_EXPECT_BOOL(expr, false)
49 #define EXPECT_EQ(lhs, rhs) _PW_TEST_OP(_PW_TEST_EXPECT, lhs, rhs, ==)
50 #define EXPECT_NE(lhs, rhs) _PW_TEST_OP(_PW_TEST_EXPECT, lhs, rhs, !=)
51 #define EXPECT_GT(lhs, rhs) _PW_TEST_OP(_PW_TEST_EXPECT, lhs, rhs, >)
52 #define EXPECT_GE(lhs, rhs) _PW_TEST_OP(_PW_TEST_EXPECT, lhs, rhs, >=)
53 #define EXPECT_LT(lhs, rhs) _PW_TEST_OP(_PW_TEST_EXPECT, lhs, rhs, <)
54 #define EXPECT_LE(lhs, rhs) _PW_TEST_OP(_PW_TEST_EXPECT, lhs, rhs, <=)
55 #define EXPECT_STREQ(lhs, rhs) _PW_TEST_STREQ(_PW_TEST_EXPECT, lhs, rhs)
56 #define EXPECT_STRNE(lhs, rhs) _PW_TEST_STRNE(_PW_TEST_EXPECT, lhs, rhs)
58 #define ASSERT_TRUE(expr) _PW_ASSERT_BOOL(expr, true)
59 #define ASSERT_FALSE(expr) _PW_ASSERT_BOOL(expr, false)
60 #define ASSERT_EQ(lhs, rhs) _PW_TEST_OP(_PW_TEST_ASSERT, lhs, rhs, ==)
61 #define ASSERT_NE(lhs, rhs) _PW_TEST_OP(_PW_TEST_ASSERT, lhs, rhs, !=)
62 #define ASSERT_GT(lhs, rhs) _PW_TEST_OP(_PW_TEST_ASSERT, lhs, rhs, >)
63 #define ASSERT_GE(lhs, rhs) _PW_TEST_OP(_PW_TEST_ASSERT, lhs, rhs, >=)
64 #define ASSERT_LT(lhs, rhs) _PW_TEST_OP(_PW_TEST_ASSERT, lhs, rhs, <)
65 #define ASSERT_LE(lhs, rhs) _PW_TEST_OP(_PW_TEST_ASSERT, lhs, rhs, <=)
66 #define ASSERT_STREQ(lhs, rhs) _PW_TEST_STREQ(_PW_TEST_ASSERT, lhs, rhs)
67 #define ASSERT_STRNE(lhs, rhs) _PW_TEST_STRNE(_PW_TEST_ASSERT, lhs, rhs)
69 // Generates a non-fatal failure with a generic message.
70 #define ADD_FAILURE() \
71 _PW_TEST_MESSAGE("(line is not executed)", "(line was executed)", false)
73 // Generates a fatal failure with a generic message.
74 #define GTEST_FAIL() return ADD_FAILURE()
76 // Define either macro to 1 to omit the definition of FAIL(), which is a
77 // generic name and clashes with some other libraries.
78 #if !(defined(GTEST_DONT_DEFINE_FAIL) && GTEST_DONT_DEFINE_FAIL)
79 #define FAIL() GTEST_FAIL()
80 #endif // !GTEST_DONT_DEFINE_FAIL
82 // Generates a success with a generic message.
83 #define GTEST_SUCCEED() _PW_TEST_MESSAGE("(success)", "(success)", true)
85 // Define either macro to 1 to omit the definition of SUCCEED(), which
86 // is a generic name and clashes with some other libraries.
87 #if !(defined(GTEST_DONT_DEFINE_SUCCEED) && GTEST_DONT_DEFINE_SUCCEED)
88 #define SUCCEED() GTEST_SUCCEED()
89 #endif // !GTEST_DONT_DEFINE_SUCCEED
91 // pw_unit_test framework entry point. Runs every registered test case and
92 // dispatches the results through the event handler. Returns a status of zero
93 // if all tests passed, or nonzero if there were any failures.
94 // This is compatible with Googletest.
96 // In order to receive test output, an event handler must be registered before
100 // MyEventHandler handler;
101 // pw::unit_test::RegisterEventHandler(&handler);
102 // return RUN_ALL_TESTS();
105 #define RUN_ALL_TESTS() \
106 ::pw::unit_test::internal::Framework::Get().RunAllTests()
110 #if PW_CXX_STANDARD_IS_SUPPORTED(17)
114 // This function is used to print unknown types that are used in EXPECT or
115 // ASSERT statements in tests.
117 // You can add support for displaying custom types by defining a ToString
118 // template specialization. For example:
123 // StatusWithSize ToString<MyType>(const MyType& value,
124 // std::span<char> buffer) {
125 // return string::Format("<MyType|%d>", value.id);
130 // See the documentation in pw_string/string_builder.h for more information.
131 template <typename T>
132 StatusWithSize UnknownTypeToString(const T& value, std::span<char> buffer) {
133 StringBuilder sb(buffer);
134 sb << '<' << sizeof(value) << "-byte object at 0x" << &value << '>';
135 return sb.status_with_size();
138 } // namespace string
140 #endif // PW_CXX_STANDARD_IS_SUPPORTED(17)
142 namespace unit_test {
150 // Singleton test framework class responsible for managing and running test
151 // cases. This implementation is internal to Pigweed test; free functions
152 // wrapping its functionality are exposed as the public interface.
155 constexpr Framework()
156 : current_test_(nullptr),
157 current_result_(TestResult::kSuccess),
158 run_tests_summary_{.passed_tests = 0, .failed_tests = 0},
160 event_handler_(nullptr),
163 static Framework& Get() { return framework_; }
165 // Registers a single test case with the framework. The framework owns the
166 // registered unit test. Called during static initialization.
167 void RegisterTest(TestInfo* test);
169 // Sets the handler to which the framework dispatches test events. During a
170 // test run, the framework owns the event handler.
171 void RegisterEventHandler(EventHandler* event_handler) {
172 event_handler_ = event_handler;
175 // Runs all registered test cases, returning a status of 0 if all succeeded or
176 // nonzero if there were any failures. Test events that occur during the run
177 // are sent to the registered event handler, if any.
180 // Constructs an instance of a unit test class and runs the test.
182 // Tests are constructed within a static memory pool at run time instead of
183 // being statically allocated to avoid blowing up the size of the test binary
184 // in cases where users have large test fixtures (e.g. containing buffers)
185 // reused many times. Instead, only a small, fixed-size TestInfo struct is
186 // statically allocated per test case, with a run() function that references
187 // this method instantiated for its test class.
188 template <typename TestInstance>
189 static void CreateAndRunTest(const TestInfo& test_info) {
190 // TODO(frolv): Update the assert message with the name of the config option
191 // for memory pool size once it is configurable.
193 sizeof(TestInstance) <= sizeof(memory_pool_),
194 "The test memory pool is too small for this test. Either increase "
195 "kTestMemoryPoolSizeBytes or decrease the size of your test fixture.");
197 Framework& framework = Get();
198 framework.StartTest(test_info);
200 // Reset the memory pool to a marker value to help detect use of
201 // uninitialized memory.
202 std::memset(&framework.memory_pool_, 0xa5, sizeof(framework.memory_pool_));
204 // Construct the test object within the static memory pool. The StartTest
205 // function has already been called by the TestInfo at this point.
206 TestInstance* test_instance = new (&framework.memory_pool_) TestInstance;
207 test_instance->PigweedTestRun();
209 // Manually call the destructor as it is not called automatically for
210 // objects constructed using placement new.
211 test_instance->~TestInstance();
213 framework.EndCurrentTest();
216 // Runs an expectation function for the currently active test case.
217 template <typename Expectation, typename Lhs, typename Rhs>
218 bool CurrentTestExpect(Expectation expectation,
221 const char* expectation_string,
222 const char* expression,
224 // Size of the buffer into which to write the string with the evaluated
225 // version of the arguments. This buffer is allocated on the unit test's
226 // stack, so it shouldn't be too large.
227 // TODO(hepler): Make this configurable.
228 constexpr size_t kExpectationBufferSizeBytes = 128;
230 bool result = expectation(lhs, rhs);
231 ExpectationResult(expression,
232 #if PW_CXX_STANDARD_IS_SUPPORTED(17)
233 MakeString<kExpectationBufferSizeBytes>(
234 lhs, ' ', expectation_string, ' ', rhs)
237 "(evaluation requires C++17)",
238 #endif // PW_CXX_STANDARD_IS_SUPPORTED(17)
242 static_cast<void>(expectation_string);
243 static_cast<void>(kExpectationBufferSizeBytes);
248 // Dispatches an event indicating the result of an expectation.
249 void ExpectationResult(const char* expression,
250 const char* evaluated_expression,
255 // Sets current_test_ and dispatches an event indicating that a test started.
256 void StartTest(const TestInfo& test);
258 // Dispatches event indicating that a test finished and clears current_test_.
259 void EndCurrentTest();
261 // Singleton instance of the framework class.
262 static Framework framework_;
264 // Linked list of all registered test cases. This is static as it tests are
265 // registered using static initialization.
266 static TestInfo* tests_;
268 // The current test case which is running.
269 const TestInfo* current_test_;
271 // Overall result of the current test case (pass/fail).
272 TestResult current_result_;
274 // Overall result of the ongoing test run, which covers multiple tests.
275 RunTestsSummary run_tests_summary_;
277 // Program exit status returned by RunAllTests for Googletest compatibility.
280 // Handler to which to dispatch test events.
281 EventHandler* event_handler_;
283 // Memory region in which to construct test case classes as they are run.
284 // TODO(frolv): Make the memory pool size configurable.
285 static constexpr size_t kTestMemoryPoolSizeBytes = 16384;
286 std::aligned_storage_t<kTestMemoryPoolSizeBytes, alignof(std::max_align_t)>
290 // Information about a single test case, including a pointer to a function which
291 // constructs and runs the test class. These are statically allocated instead of
292 // the test classes, as test classes can be very large.
295 TestInfo(const char* const test_suite_name,
296 const char* const test_name,
297 const char* const file_name,
298 void (*run_func)(const TestInfo&))
300 .suite_name = test_suite_name,
301 .test_name = test_name,
302 .file_name = file_name,
304 Framework::Get().RegisterTest(this);
307 // The name of the suite to which the test case belongs, the name of the test
308 // case itself, and the path to the file in which the test case is located.
309 const TestCase& test_case() const { return test_case_; }
311 bool enabled() const;
313 void run() const { run_(*this); }
315 TestInfo* next() const { return next_; }
316 void set_next(TestInfo* next) { next_ = next; }
321 // Function which runs the test case. Refers to Framework::CreateAndRunTest
322 // instantiated for the test case's class.
323 void (*run_)(const TestInfo&);
325 // TestInfo structs are registered with the test framework and stored as a
327 TestInfo* next_ = nullptr;
330 } // namespace internal
332 // Base class for all test cases or custom test fixtures.
333 // Every unit test created using the TEST or TEST_F macro defines a class that
334 // inherits from this (or a subclass of this).
336 // For example, given the following test definition:
338 // TEST(MyTest, SaysHello) {
339 // ASSERT_STREQ(SayHello(), "Hello, world!");
342 // A new class is defined for the test, e.g. MyTest_SaysHello_Test. This class
343 // inherits from the Test class and implements its PigweedTestBody function with
344 // the block provided to the TEST macro.
347 Test(const Test&) = delete;
348 Test& operator=(const Test&) = delete;
350 virtual ~Test() = default;
352 // Runs the unit test.
353 void PigweedTestRun() {
362 // Called immediately before executing the test body.
364 // Setup and cleanup can typically be done in the test fixture's constructor
365 // and destructor, but there are cases where SetUp/TearDown must be used
366 // instead. See the Google Test documentation for more information.
367 virtual void SetUp() {}
369 // Called immediately after executing the test body.
370 virtual void TearDown() {}
373 friend class internal::Framework;
375 // The user-provided body of the test case. Populated by the TEST macro.
376 virtual void PigweedTestBody() = 0;
379 } // namespace unit_test
382 #define _PW_TEST_CLASS_NAME(test_suite_name, test_name) \
383 PW_CONCAT(test_suite_name, _, test_name, _Test)
385 #define _PW_TEST(test_suite_name, test_name, parent_class) \
386 static_assert(sizeof(#test_suite_name) > 1, \
387 "test_suite_name must not be empty"); \
388 static_assert(sizeof(#test_name) > 1, "test_name must not be empty"); \
390 class _PW_TEST_CLASS_NAME(test_suite_name, test_name) final \
391 : public parent_class { \
393 void PigweedTestBody() override; \
395 static ::pw::unit_test::internal::TestInfo test_info_; \
398 ::pw::unit_test::internal::TestInfo \
399 _PW_TEST_CLASS_NAME(test_suite_name, test_name)::test_info_( \
403 ::pw::unit_test::internal::Framework::CreateAndRunTest< \
404 _PW_TEST_CLASS_NAME(test_suite_name, test_name)>); \
406 void _PW_TEST_CLASS_NAME(test_suite_name, test_name)::PigweedTestBody()
408 #define _PW_TEST_EXPECT(lhs, rhs, expectation, expectation_string) \
409 ::pw::unit_test::internal::Framework::Get().CurrentTestExpect( \
413 expectation_string, \
414 #lhs " " expectation_string " " #rhs, \
417 #define _PW_TEST_ASSERT(lhs, rhs, expectation, expectation_string) \
419 if (!_PW_TEST_EXPECT(lhs, rhs, expectation, expectation_string)) { \
424 #define _PW_TEST_MESSAGE(expected, actual, success) \
425 ::pw::unit_test::internal::Framework::Get().ExpectationResult( \
426 expected, actual, __LINE__, success)
428 #define _PW_TEST_OP(expect_or_assert, lhs, rhs, op) \
432 [](const auto& _pw_lhs, const auto& _pw_rhs) { \
433 return _pw_lhs op _pw_rhs; \
437 // Implement boolean expectations in a C++11-compatible way.
438 #define _PW_EXPECT_BOOL(expr, value) \
439 ::pw::unit_test::internal::Framework::Get().CurrentTestExpect( \
440 [](bool lhs, bool rhs) { return lhs == rhs; }, \
441 static_cast<bool>(expr), \
444 #expr " is " #value, \
447 #define _PW_ASSERT_BOOL(expr, value) \
449 if (!_PW_EXPECT_BOOL(expr, value)) { \
454 #define _PW_TEST_STREQ(expect_or_assert, lhs, rhs) \
458 [](const auto& _pw_lhs, const auto& _pw_rhs) { \
459 return std::strcmp(_pw_lhs, _pw_rhs) == 0; \
463 #define _PW_TEST_STRNE(expect_or_assert, lhs, rhs) \
467 [](const auto& _pw_lhs, const auto& _pw_rhs) { \
468 return std::strcmp(_pw_lhs, _pw_rhs) != 0; \
472 // Alias Test as ::testing::Test for Googletest compatibility.
474 using Test = ::pw::unit_test::Test;
475 } // namespace testing