Pigweed
 
Loading...
Searching...
No Matches
framework_backend.h
1// Copyright 2020 The Pigweed Authors
2//
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
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
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
13// the License.
14#pragma once
15
16// IWYU pragma: private, include "pw_unit_test/framework.h"
17
18#if defined(GTEST_TEST)
19#error \
20 "GTEST_TEST is already defined. Make sure googletest headers are not " \
21 "included when using the pw_unit_test light backend."
22#endif // GTEST_TEST
23
24#include <cstddef>
25#include <cstdint>
26#include <cstring>
27#include <new>
28#include <string_view>
29
30#include "pw_bytes/alignment.h"
31#include "pw_polyfill/standard.h"
32#include "pw_preprocessor/compiler.h"
33#include "pw_preprocessor/util.h"
34#include "pw_span/span.h"
35#include "pw_status/status.h"
37#include "pw_unit_test/config.h"
38#include "pw_unit_test/event_handler.h"
39
42#define GTEST_TEST(test_suite_name, test_name) \
43 _PW_TEST_SUITE_NAMES_MUST_BE_UNIQUE(void /* TEST */, test_suite_name); \
44 _PW_TEST(test_suite_name, test_name, ::pw::unit_test::internal::Test)
45
55#if !(defined(GTEST_DONT_DEFINE_TEST) && GTEST_DONT_DEFINE_TEST)
56#define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name)
57#endif // !GTEST_DONT_DEFINE_TEST
58
64#define TEST_F(test_fixture, test_name) \
65 _PW_TEST_SUITE_NAMES_MUST_BE_UNIQUE(int /* TEST_F */, test_fixture); \
66 _PW_TEST(test_fixture, test_name, test_fixture)
67
77#define FRIEND_TEST(test_suite_name, test_name) \
78 friend class test_suite_name##_##test_name##_Test
79
84#define EXPECT_TRUE(expr) _PW_TEST_EXPECT(_PW_TEST_BOOL(expr, true))
85
90#define EXPECT_FALSE(expr) _PW_TEST_EXPECT(_PW_TEST_BOOL(expr, false))
91
105#define EXPECT_EQ(lhs, rhs) _PW_TEST_EXPECT(_PW_TEST_OP(lhs, rhs, ==))
106
116
119#define EXPECT_NE(lhs, rhs) _PW_TEST_EXPECT(_PW_TEST_OP(lhs, rhs, !=))
120
126#define EXPECT_GT(lhs, rhs) _PW_TEST_EXPECT(_PW_TEST_OP(lhs, rhs, >))
127
133#define EXPECT_GE(lhs, rhs) _PW_TEST_EXPECT(_PW_TEST_OP(lhs, rhs, >=))
134
140#define EXPECT_LT(lhs, rhs) _PW_TEST_EXPECT(_PW_TEST_OP(lhs, rhs, <))
141
147#define EXPECT_LE(lhs, rhs) _PW_TEST_EXPECT(_PW_TEST_OP(lhs, rhs, <=))
148
156#define EXPECT_NEAR(lhs, rhs, epsilon) \
157 _PW_TEST_EXPECT(_PW_TEST_NEAR(lhs, rhs, epsilon))
158
165#define EXPECT_FLOAT_EQ(lhs, rhs) \
166 _PW_TEST_EXPECT( \
167 _PW_TEST_NEAR(lhs, rhs, 4 * std::numeric_limits<float>::epsilon()))
168
175#define EXPECT_DOUBLE_EQ(lhs, rhs) \
176 _PW_TEST_EXPECT( \
177 _PW_TEST_NEAR(lhs, rhs, 4 * std::numeric_limits<double>::epsilon()))
178
184#define EXPECT_STREQ(lhs, rhs) _PW_TEST_EXPECT(_PW_TEST_C_STR(lhs, rhs, ==))
185
191#define EXPECT_STRNE(lhs, rhs) _PW_TEST_EXPECT(_PW_TEST_C_STR(lhs, rhs, !=))
192
195#define ASSERT_TRUE(expr) _PW_TEST_ASSERT(_PW_TEST_BOOL(expr, true))
196
199#define ASSERT_FALSE(expr) _PW_TEST_ASSERT(_PW_TEST_BOOL(expr, false))
200
203#define ASSERT_EQ(lhs, rhs) _PW_TEST_ASSERT(_PW_TEST_OP(lhs, rhs, ==))
204
207#define ASSERT_NE(lhs, rhs) _PW_TEST_ASSERT(_PW_TEST_OP(lhs, rhs, !=))
208
211#define ASSERT_GT(lhs, rhs) _PW_TEST_ASSERT(_PW_TEST_OP(lhs, rhs, >))
212
215#define ASSERT_GE(lhs, rhs) _PW_TEST_ASSERT(_PW_TEST_OP(lhs, rhs, >=))
216
219#define ASSERT_LT(lhs, rhs) _PW_TEST_ASSERT(_PW_TEST_OP(lhs, rhs, <))
220
223#define ASSERT_LE(lhs, rhs) _PW_TEST_ASSERT(_PW_TEST_OP(lhs, rhs, <=))
224
227#define ASSERT_NEAR(lhs, rhs, epsilon) \
228 _PW_TEST_ASSERT(_PW_TEST_NEAR(lhs, rhs, epsilon))
229
232#define ASSERT_FLOAT_EQ(lhs, rhs) \
233 _PW_TEST_ASSERT( \
234 _PW_TEST_NEAR(lhs, rhs, 4 * std::numeric_limits<float>::epsilon()))
235
238#define ASSERT_DOUBLE_EQ(lhs, rhs) \
239 _PW_TEST_ASSERT( \
240 _PW_TEST_NEAR(lhs, rhs, 4 * std::numeric_limits<double>::epsilon()))
241
244#define ASSERT_STREQ(lhs, rhs) _PW_TEST_ASSERT(_PW_TEST_C_STR(lhs, rhs, ==))
245
248#define ASSERT_STRNE(lhs, rhs) _PW_TEST_ASSERT(_PW_TEST_C_STR(lhs, rhs, !=))
249
252#define ADD_FAILURE() \
253 ::pw::unit_test::internal::ReturnHelper() = \
254 ::pw::unit_test::internal::Framework::Get().CurrentTestExpectSimple( \
255 "(line is not executed)", "(line was executed)", __LINE__, false)
256
260#define GTEST_FAIL() return ADD_FAILURE()
261
265#define GTEST_SKIP() \
266 return ::pw::unit_test::internal::ReturnHelper() = \
267 ::pw::unit_test::internal::Framework::Get().CurrentTestSkip( \
268 __LINE__)
269
275#if !(defined(GTEST_DONT_DEFINE_FAIL) && GTEST_DONT_DEFINE_FAIL)
276#define FAIL() GTEST_FAIL()
277#endif // !GTEST_DONT_DEFINE_FAIL
278
282#define GTEST_SUCCEED() \
283 ::pw::unit_test::internal::Framework::Get().CurrentTestExpectSimple( \
284 "(success)", "(success)", __LINE__, true)
285
292#if !(defined(GTEST_DONT_DEFINE_SUCCEED) && GTEST_DONT_DEFINE_SUCCEED)
293#define SUCCEED() GTEST_SUCCEED()
294#endif // !GTEST_DONT_DEFINE_SUCCEED
295
303int RUN_ALL_TESTS();
304
307#define GTEST_HAS_DEATH_TEST 0
308
311#define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \
312 if (0) { \
313 static_cast<void>(statement); \
314 static_cast<void>(regex); \
315 } \
316 static_assert(true, "Macros must be terminated with a semicolon")
317
320#define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \
321 EXPECT_DEATH_IF_SUPPORTED(statement, regex)
322
323namespace pw {
324namespace string {
325
326// This function is used to print unknown types that are used in EXPECT or
327// ASSERT statements in tests.
328//
329// You can add support for displaying custom types by defining a ToString
330// template specialization. For example:
331//
332// namespace pw {
333//
334// template <>
335// StatusWithSize ToString<MyType>(const MyType& value,
336// span<char> buffer) {
337// return string::Format("<MyType|%d>", value.id);
338// }
339//
340// } // namespace pw
341//
342// See the documentation in pw_string/string_builder.h for more information.
343template <typename T>
344StatusWithSize UnknownTypeToString(const T& value, span<char> buffer) {
345 StringBuilder sb(buffer);
346 sb << '<' << sizeof(value) << "-byte object at 0x" << &value;
347
348 // How many bytes of the object to print.
349 //
350 // WARNING: Printing the contents of an object may be undefined behavior!
351 // Accessing uninitialized memory is undefined behavior, and objects
352 // sometimes contain uninitialized regions, such as padding bytes or
353 // unallocated storage (e.g. std::optional). kPrintMaybeUninitializedBytes
354 // MUST stay at 0, except when changed locally to help with debugging.
355 constexpr size_t kPrintMaybeUnintializedBytes = 0;
356
357 constexpr size_t kBytesToPrint =
358 std::min(sizeof(value), kPrintMaybeUnintializedBytes);
359
360 if (kBytesToPrint != 0u) {
361 sb << " |";
362
363 // reinterpret_cast to std::byte is permitted by C++'s type aliasing
364 // rules.
365 const std::byte* bytes = reinterpret_cast<const std::byte*>(&value);
366
367 for (size_t i = 0; i < kBytesToPrint; ++i) {
368 sb << ' ' << bytes[i];
369 }
370
371 // If there's just one more byte, output it. Otherwise, output ellipsis.
372 if (sizeof(value) == kBytesToPrint + 1) {
373 sb << ' ' << bytes[sizeof(value) - 1];
374 } else if (sizeof(value) > kBytesToPrint) {
375 sb << " …";
376 }
377 }
378
379 sb << '>';
380 return sb.status_with_size();
381}
382
383} // namespace string
384
385namespace unit_test {
386namespace internal {
387
388class Test;
389class TestInfo;
390
391// Types of SetUpTestSuite() and TearDownTestSuite() functions.
392using SetUpTestSuiteFunc = void (*)();
393using TearDownTestSuiteFunc = void (*)();
394
395// Used to tag arguments to EXPECT_STREQ/EXPECT_STRNE so they are treated like
396// C strings rather than pointers.
398 const char* const c_str;
399};
400
401constexpr size_t MaxPaddingNeededToRaiseAlignment(size_t current_align,
402 size_t new_align) {
403 if (new_align < current_align) {
404 return 0;
405 }
406 return new_align - current_align;
407}
408
409// GoogleTest supports stream-style messages, but pw_unit_test does not. This
410// class accepts and ignores C++ <<-style logs.
412 public:
413 constexpr FailureMessageAdapter() = default;
414
415 template <typename T>
416 constexpr const FailureMessageAdapter& operator<<(const T&) const {
417 return *this;
418 }
419};
420
421// Used to ignore a stream-style message in an assert, which returns. This
422// uses a similar approach as upstream GoogleTest, but drops any messages.
424 public:
425 constexpr ReturnHelper() = default;
426
427 // Return void so that assigning to ReturnHelper converts the log expression
428 // to void without blocking the stream-style log with a closing parenthesis.
429 // NOLINTNEXTLINE(misc-unconventional-assign-operator)
430 constexpr void operator=(const FailureMessageAdapter&) const {}
431};
432
433// Singleton test framework class responsible for managing and running test
434// cases. This implementation is internal to Pigweed test; free functions
435// wrapping its functionality are exposed as the public interface.
437 public:
438 constexpr Framework()
439 : current_test_(nullptr),
440 current_result_(TestResult::kSuccess),
441 run_tests_summary_{.passed_tests = 0,
442 .failed_tests = 0,
443 .skipped_tests = 0,
444 .disabled_tests = 0},
445 exit_status_(0),
446 event_handler_(nullptr),
447 memory_pool_() {}
448
449 static Framework& Get() { return framework_; }
450
451 // Registers a single test case with the framework. The framework owns the
452 // registered unit test. Called during static initialization.
453 void RegisterTest(TestInfo* test) const;
454
455 // Sets the handler to which the framework dispatches test events. During a
456 // test run, the framework owns the event handler.
457 inline void RegisterEventHandler(EventHandler* event_handler) {
458 event_handler_ = event_handler;
459 }
460
461 // Runs all registered test cases, returning a status of 0 if all succeeded
462 // or nonzero if there were any failures. Test events that occur during the
463 // run are sent to the registered event handler, if any.
464 int RunAllTests();
465
466 // Only run test suites whose names are included in the provided list during
467 // the next test run.
468 void SetTestSuitesToRun(span<std::string_view> test_suites) {
469 test_suites_to_run_ = test_suites;
470 }
471
472 bool ShouldRunTest(const TestInfo& test_info) const;
473
474 // Whether the current test is skipped.
475 bool IsSkipped() const { return current_result_ == TestResult::kSkipped; }
476
477 // Whether the current test has failed.
478 bool HasFailure() const { return current_result_ == TestResult::kFailure; }
479
480 // Constructs an instance of a unit test class and runs the test.
481 //
482 // Tests are constructed within a static memory pool at run time instead of
483 // being statically allocated to avoid blowing up the size of the test
484 // binary in cases where users have large test fixtures (e.g. containing
485 // buffers) reused many times. Instead, only a small, fixed-size TestInfo
486 // struct is statically allocated per test case, with a run() function that
487 // references this method instantiated for its test class.
488 template <typename TestInstance>
489 static void CreateAndRunTest(const TestInfo& test_info) {
490 static_assert(
491 sizeof(TestInstance) +
492 MaxPaddingNeededToRaiseAlignment(
493 alignof(decltype(memory_pool_)), alignof(TestInstance)) <=
494 sizeof(memory_pool_),
495 "The test memory pool is too small for this test. Either increase "
496 "PW_UNIT_TEST_CONFIG_MEMORY_POOL_SIZE or decrease the size of your "
497 "test fixture.");
498
499 Framework& framework = Get();
500 framework.StartTest(test_info);
501
502 // Reset the memory pool to a marker value to help detect use of
503 // uninitialized memory.
504 std::memset(&framework.memory_pool_, 0xa5, sizeof(framework.memory_pool_));
505
506 framework.SetUpTestSuiteIfNeeded(TestInstance::SetUpTestSuite);
507
508 // Construct the test object within the static memory pool. The StartTest
509 // function has already been called by the TestInfo at this point.
510 void* aligned_pool =
511 AlignUp(&framework.memory_pool_, alignof(TestInstance));
512 TestInstance* test_instance = new (aligned_pool) TestInstance();
513 test_instance->PigweedTestRun();
514
515 // Manually call the destructor as it is not called automatically for
516 // objects constructed using placement new.
517 test_instance->~TestInstance();
518
519 framework.TearDownTestSuiteIfNeeded(TestInstance::TearDownTestSuite);
520
521 framework.EndCurrentTest();
522 }
523
524 template <typename Expectation, typename Lhs, typename Rhs, typename Epsilon>
525 [[nodiscard]] bool CurrentTestExpectWithEpsilon(Expectation expectation,
526 const Lhs& lhs,
527 const Rhs& rhs,
528 const Epsilon& epsilon,
529 const char* expression,
530 int line) {
531 const bool success = expectation(lhs, rhs, epsilon);
532 if (!success) {
533 CurrentTestExpectSimple(expression,
534 MakeString<config::kExpectationBufferSizeBytes>(
535 ConvertForPrint(lhs),
536 " within ",
537 ConvertForPrint(epsilon),
538 " of ",
539 ConvertForPrint(rhs))
540 .c_str(),
541 line,
542 success);
543 }
544 return success;
545 }
546
547 // Runs an expectation function for the currently active test case.
548 template <typename Expectation, typename Lhs, typename Rhs>
549 [[nodiscard]] bool CurrentTestExpect(Expectation expectation,
550 const Lhs& lhs,
551 const Rhs& rhs,
552 const char* expectation_string,
553 const char* expression,
554 int line) {
555 const bool success = expectation(lhs, rhs);
556 if (!success) {
557 CurrentTestExpectSimple(
558 expression,
559 MakeString<config::kExpectationBufferSizeBytes>(ConvertForPrint(lhs),
560 ' ',
561 expectation_string,
562 ' ',
563 ConvertForPrint(rhs))
564 .c_str(),
565 line,
566 success);
567 }
568 return success;
569 }
570
571 // Skips the current test and dispatches an event for it.
572 ::pw::unit_test::internal::FailureMessageAdapter CurrentTestSkip(int line);
573
574 // Dispatches an event indicating the result of an expectation.
576 const char* expression,
577 const char* evaluated_expression,
578 int line,
579 bool success);
580
581 private:
582 // Convert char* to void* so that they are printed as pointers instead of
583 // strings in EXPECT_EQ and other macros. EXPECT_STREQ wraps its pointers in
584 // a CStringArg so its pointers are treated like C strings.
585 static constexpr const void* ConvertForPrint(const char* str) { return str; }
586
587 static constexpr const void* ConvertForPrint(char* str) { return str; }
588
589 static constexpr const char* ConvertForPrint(CStringArg value) {
590 return value.c_str;
591 }
592
593 template <typename T>
594 static constexpr T ConvertForPrint(T&& value) {
595 return std::forward<T>(value);
596 }
597
598 // If current_test_ will be first of its suite, call set_up_ts
599 void SetUpTestSuiteIfNeeded(SetUpTestSuiteFunc set_up_ts) const;
600
601 // If current_test_ was the last of its suite, call tear_down_ts
602 void TearDownTestSuiteIfNeeded(TearDownTestSuiteFunc tear_down_ts) const;
603
604 // Sets current_test_ and dispatches an event indicating that a test
605 // started.
606 void StartTest(const TestInfo& test);
607
608 // Dispatches event indicating that a test finished and clears
609 // current_test_.
610 void EndCurrentTest();
611
612 // Singleton instance of the framework class.
613 static Framework framework_;
614
615 // Linked list of all registered test cases. This is static as it tests are
616 // registered using static initialization.
617 static TestInfo* tests_;
618
619 // The current test case which is running.
620 const TestInfo* current_test_;
621
622 // Overall result of the current test case (pass/fail/skip).
623 TestResult current_result_;
624
625 // Overall result of the ongoing test run, which covers multiple tests.
626 RunTestsSummary run_tests_summary_;
627
628 // Program exit status returned by RunAllTests for GoogleTest compatibility.
629 int exit_status_;
630
631 // Handler to which to dispatch test events.
632 EventHandler* event_handler_;
633
634 span<std::string_view> test_suites_to_run_;
635
636 alignas(std::max_align_t) std::byte memory_pool_[config::kMemoryPoolSize];
637};
638
639// Information about a single test case, including a pointer to a function
640// which constructs and runs the test class. These are statically allocated
641// instead of the test classes, as test classes can be very large.
642class TestInfo {
643 public:
644 TestInfo(const char* const test_suite_name,
645 const char* const test_name,
646 const char* const file_name,
647 void (*run_func)(const TestInfo&))
648 : test_case_{
649 .suite_name = test_suite_name,
650 .test_name = test_name,
651 .file_name = file_name,
652 }, run_(run_func) {
653 Framework::Get().RegisterTest(this);
654 }
655
656 // The name of the suite to which the test case belongs, the name of the
657 // test case itself, and the path to the file in which the test case is
658 // located.
659 const TestCase& test_case() const { return test_case_; }
660
661 bool enabled() const;
662
663 void run() const { run_(*this); }
664
665 TestInfo* next() const { return next_; }
666 void set_next(TestInfo* next) { next_ = next; }
667
668 private:
669 TestCase test_case_;
670
671 // Function which runs the test case. Refers to Framework::CreateAndRunTest
672 // instantiated for the test case's class.
673 void (*run_)(const TestInfo&);
674
675 // TestInfo structs are registered with the test framework and stored as a
676 // linked list.
677 TestInfo* next_ = nullptr;
678};
679
680// Base class for all test cases or custom test fixtures.
681// Every unit test created using the TEST or TEST_F macro defines a class that
682// inherits from this (or a subclass of this).
683//
684// For example, given the following test definition:
685//
686// TEST(MyTest, SaysHello) {
687// ASSERT_STREQ(SayHello(), "Hello, world!");
688// }
689//
690// A new class is defined for the test, e.g. MyTest_SaysHello_Test. This class
691// inherits from the Test class and implements its PigweedTestBody function
692// with the block provided to the TEST macro.
693class Test {
694 public:
695 Test(const Test&) = delete;
696 Test& operator=(const Test&) = delete;
697
698 virtual ~Test() = default;
699
700 static void SetUpTestSuite() {}
701 static void TearDownTestSuite() {}
702
703 static bool HasFailure() { return Framework::Get().HasFailure(); }
704
705 // Runs the unit test.
706 void PigweedTestRun() {
707 SetUp();
708 // TODO(deymo): Skip the test body if there's a fatal error in SetUp().
709 if (!Framework::Get().IsSkipped()) {
710 PigweedTestBody();
711 }
712 TearDown();
713 }
714
715 protected:
716 Test() = default;
717
718 // Called immediately before executing the test body.
719 //
720 // Setup and cleanup can typically be done in the test fixture's constructor
721 // and destructor, but there are cases where SetUp/TearDown must be used
722 // instead. See the Google Test documentation for more information.
723 virtual void SetUp() {}
724
725 // Called immediately after executing the test body.
726 virtual void TearDown() {}
727
728 private:
729 friend class internal::Framework;
730
731 // The user-provided body of the test case. Populated by the TEST macro.
732 virtual void PigweedTestBody() = 0;
733};
734
735// Checks that a test suite name is valid.
736constexpr bool HasNoUnderscores(const char* suite) {
737 const char* disabled_prefix = "DISABLED_";
738
739 for (; *suite != '\0'; ++suite) {
740 if (*suite == *disabled_prefix) {
741 disabled_prefix += 1;
742 } else {
743 disabled_prefix = "";
744 if (*suite == '_') {
745 return false;
746 }
747 }
748 }
749 return true;
750}
751
752} // namespace internal
753
754inline void SetTestSuitesToRun(span<std::string_view> test_suites) {
755 internal::Framework::Get().SetTestSuitesToRun(test_suites);
756}
757
758} // namespace unit_test
759} // namespace pw
760
761inline int RUN_ALL_TESTS() {
762 return ::pw::unit_test::internal::Framework::Get().RunAllTests();
763}
764
765#define _PW_TEST(test_suite_name, test_name, parent_class) \
766 static_assert(sizeof(#test_suite_name) > 1, \
767 "The test suite name must not be empty"); \
768 static_assert(::pw::unit_test::internal::HasNoUnderscores(#test_suite_name), \
769 "The test suite name (" #test_suite_name \
770 ") cannot contain underscores"); \
771 static_assert(sizeof(#test_name) > 1, "The test name must not be empty"); \
772 \
773 _PW_TEST_CLASS(test_suite_name, \
774 test_name, \
775 test_suite_name##_##test_name##_Test, \
776 parent_class)
777
778#define _PW_TEST_CLASS(suite, name, class_name, parent_class) \
779 class class_name final : public parent_class { \
780 private: \
781 void PigweedTestBody() override; \
782 }; \
783 \
784 extern "C" { \
785 \
786 /* Silence ASAN to avoid errors in the initialization order checker */ \
787 /* caused by the intentional use of dynamic initializers which modify */ \
788 /* other globals */ \
789 PW_NO_SANITIZE("address") \
790 /* Declare the TestInfo as non-const since const variables do not work */ \
791 /* with the PW_UNIT_TEST_LINK_FILE_CONTAINING_TEST macro. */ \
792 /* NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) */ \
793 ::pw::unit_test::internal::TestInfo _pw_unit_test_Info_##suite##_##name( \
794 #suite, \
795 #name, \
796 __FILE__, \
797 ::pw::unit_test::internal::Framework::CreateAndRunTest<class_name>); \
798 \
799 } /* extern "C" */ \
800 \
801 void class_name::PigweedTestBody()
802
803#define _PW_TEST_ASSERT(expectation) \
804 if (!(expectation)) \
805 return ::pw::unit_test::internal::ReturnHelper() = \
806 ::pw::unit_test::internal::FailureMessageAdapter()
807
808#define _PW_TEST_EXPECT(expectation) \
809 if (!(expectation)) \
810 ::pw::unit_test::internal::FailureMessageAdapter()
811
812#define _PW_TEST_BOOL(expr, value) \
813 ::pw::unit_test::internal::Framework::Get().CurrentTestExpect( \
814 [](bool _pw_lhs, bool _pw_rhs) { return _pw_lhs == _pw_rhs; }, \
815 static_cast<bool>(expr), \
816 value, \
817 "is", \
818 #expr " is " #value, \
819 __LINE__)
820
821#define _PW_TEST_OP(lhs, rhs, op) \
822 ::pw::unit_test::internal::Framework::Get().CurrentTestExpect( \
823 [](const auto& _pw_lhs, const auto& _pw_rhs) { \
824 return _pw_lhs op _pw_rhs; \
825 }, \
826 (lhs), \
827 (rhs), \
828 #op, \
829 #lhs " " #op " " #rhs, \
830 __LINE__)
831
832#define _PW_TEST_NEAR(lhs, rhs, epsilon) \
833 ::pw::unit_test::internal::Framework::Get().CurrentTestExpectWithEpsilon( \
834 [](const auto& _pw_lhs, const auto& _pw_rhs, const auto& _pw_epsilon) { \
835 return std::abs(_pw_lhs - _pw_rhs) <= _pw_epsilon; \
836 }, \
837 (lhs), \
838 (rhs), \
839 (epsilon), \
840 #lhs " within " #epsilon " of " #rhs, \
841 __LINE__)
842
843#define _PW_TEST_C_STR(lhs, rhs, op) \
844 ::pw::unit_test::internal::Framework::Get().CurrentTestExpect( \
845 [](const auto& _pw_lhs, const auto& _pw_rhs) { \
846 auto cmp = [](const char* l, const char* r) -> int { \
847 if (!l || !r) { \
848 return l != r; \
849 } \
850 return std::strcmp(l, r); \
851 }; \
852 return cmp(_pw_lhs.c_str, _pw_rhs.c_str) op 0; \
853 }, \
854 ::pw::unit_test::internal::CStringArg{lhs}, \
855 ::pw::unit_test::internal::CStringArg{rhs}, \
856 #op, \
857 #lhs " " #op " " #rhs, \
858 __LINE__)
859
860// Checks that test suite names between TEST and TEST_F declarations are unique.
861// This works by declaring a function named for the test suite. The function
862// takes no arguments but is declared with different return types in the TEST
863// and TEST_F macros. If a TEST and TEST_F use the same test suite name, the
864// function declarations conflict, resulting in a compilation error.
865//
866// This catches most conflicts, but a runtime check is ultimately needed since
867// tests may be declared in different translation units.
868#if !defined(__clang__) && !defined(__GNUC___) && __GNUC__ <= 8
869// For some reason GCC8 is unable to ignore -Wredundant-decls here.
870#define _PW_TEST_SUITE_NAMES_MUST_BE_UNIQUE(return_type, test_suite)
871#else // All other compilers.
872#define _PW_TEST_SUITE_NAMES_MUST_BE_UNIQUE(return_type, test_suite) \
873 PW_MODIFY_DIAGNOSTICS_PUSH(); \
874 PW_MODIFY_DIAGNOSTIC(ignored, "-Wredundant-decls"); \
875 extern "C" return_type /* use extern "C" to escape namespacing */ \
876 PwUnitTestSuiteNamesMustBeUniqueBetweenTESTandTEST_F_##test_suite(void); \
877 PW_MODIFY_DIAGNOSTICS_POP()
878#endif // GCC8 or older.
879
880namespace testing {
881
882// Alias Test as ::testing::Test for GoogleTest compatibility.
884
885// Provide a no-op init routine for GoogleTest compatibility.
886inline void InitGoogleTest(int*, char**) {}
887
888} // namespace testing
Definition: event_handler.h:115
Definition: framework_backend.h:411
Definition: framework_backend.h:436
Definition: framework_backend.h:423
Definition: framework_backend.h:693
Definition: framework_backend.h:642
Provides basic helpers for reading and writing UTF-8 encoded strings.
Definition: alignment.h:27
constexpr size_t AlignUp(uintptr_t value, size_t alignment)
Returns the value rounded up to the nearest multiple of alignment.
Definition: alignment.h:52
pw::StringBuilder facilitates creating formatted strings in a fixed-sized buffer or in a pw::InlineSt...
Definition: event_handler.h:52
Definition: event_handler.h:27
Definition: framework_backend.h:397