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