1.. _module-pw_unit_test: 2 3============ 4pw_unit_test 5============ 6.. pigweed-module:: 7 :name: pw_unit_test 8 9.. tab-set:: 10 11 .. tab-item:: mylib_test.cpp 12 13 .. code-block:: c++ 14 15 #include "mylib.h" 16 17 #include "pw_unit_test/framework.h" 18 19 namespace { 20 21 TEST(MyTestSuite, MyTestCase) { 22 pw::InlineString<32> expected = "(╯°□°)╯︵ ┻━┻"; 23 pw::InlineString<32> actual = mylib::flip_table(); 24 EXPECT_STREQ(expected.c_str(), actual.c_str()); 25 } 26 27 } 28 29 .. tab-item:: BUILD.bazel 30 31 .. code-block:: python 32 33 load("@pigweed//pw_unit_test:pw_cc_test.bzl", "pw_cc_test") 34 35 cc_library( 36 name = "mylib", 37 srcs = ["mylib.cc"], 38 hdrs = ["mylib.h"], 39 includes = ["."], 40 deps = ["@pigweed//pw_string"], 41 ) 42 43 pw_cc_test( 44 name = "mylib_test", 45 srcs = ["mylib_test.cc"], 46 deps = [ 47 "@pigweed//pw_unit_test", 48 ":mylib", 49 ], 50 ) 51 52 .. tab-item:: mylib.cc 53 54 .. code-block:: c++ 55 56 #include "mylib.h" 57 58 #include "pw_string/string.h" 59 60 namespace mylib { 61 62 pw::InlineString<32> flip_table() { 63 pw::InlineString<32> textmoji = "(╯°□°)╯︵ ┻━┻"; 64 return textmoji; 65 } 66 67 } 68 69 .. tab-item:: mylib.h 70 71 .. code-block:: c++ 72 73 #include "pw_string/string.h" 74 75 namespace mylib { 76 77 pw::InlineString<32> flip_table(); 78 79 } 80 81.. _GoogleTest: https://google.github.io/googletest/ 82 83``pw_unit_test`` provides a `GoogleTest`_-compatible unit testing framework for 84Pigweed-based projects. The default backend is a lightweight subset of 85GoogleTest that uses embedded-friendly primitives. 86 87.. grid:: 1 88 89 .. grid-item-card:: :octicon:`rocket` Quickstart 90 :link: module-pw_unit_test-quickstart 91 :link-type: ref 92 :class-item: sales-pitch-cta-primary 93 94 Set up your project for testing and learn testing basics. 95 96.. grid:: 2 97 98 .. grid-item-card:: :octicon:`list-unordered` Guides 99 :link: module-pw_unit_test-guides 100 :link-type: ref 101 :class-item: sales-pitch-cta-secondary 102 103 Learn how to do common tasks. 104 105 .. grid-item-card:: :octicon:`code-square` C++ API reference 106 :link: module-pw_unit_test-cpp 107 :link-type: ref 108 :class-item: sales-pitch-cta-secondary 109 110 Get detailed C++ API reference information. 111 112.. grid:: 2 113 114 .. grid-item-card:: :octicon:`code-square` Bazel API reference 115 :link: module-pw_unit_test-bazel 116 :link-type: ref 117 :class-item: sales-pitch-cta-secondary 118 119 Get detailed Bazel API reference information. 120 121 .. grid-item-card:: :octicon:`code-square` GN API reference 122 :link: module-pw_unit_test-gn 123 :link-type: ref 124 :class-item: sales-pitch-cta-secondary 125 126 Get detailed GN API reference information. 127 128.. grid:: 2 129 130 .. grid-item-card:: :octicon:`code-square` CMake API reference 131 :link: module-pw_unit_test-cmake 132 :link-type: ref 133 :class-item: sales-pitch-cta-secondary 134 135 Get detailed CMake API reference information. 136 137 .. grid-item-card:: :octicon:`code-square` Python API reference 138 :link: module-pw_unit_test-py 139 :link-type: ref 140 :class-item: sales-pitch-cta-secondary 141 142 Get detailed Python API reference information. 143 144.. _module-pw_unit_test-quickstart: 145 146---------- 147Quickstart 148---------- 149 150Set up your build system 151======================== 152.. tab-set:: 153 154 .. tab-item:: Bazel 155 156 Load the :ref:`module-pw_unit_test-pw_cc_test` rule and create a target 157 that depends on ``@pigweed//pw_unit_test`` as well as the code you want 158 to test: 159 160 .. code-block:: python 161 162 load("@pigweed//pw_unit_test:pw_cc_test.bzl", "pw_cc_test") 163 164 cc_library( 165 name = "mylib", 166 srcs = ["mylib.cc"], 167 hdrs = ["mylib.h"], 168 includes = ["."], 169 deps = ["..."], 170 ) 171 172 pw_cc_test( 173 name = "mylib_test", 174 srcs = ["mylib_test.cc"], 175 deps = [ 176 "@pigweed//pw_unit_test", 177 ":mylib", 178 ], 179 ) 180 181 This assumes that your Bazel ``WORKSPACE`` has a `repository 182 <https://bazel.build/concepts/build-ref#repositories>`_ named ``@pigweed`` 183 that points to the upstream Pigweed repository. 184 185 See also :ref:`module-pw_unit_test-bazel`. 186 187 .. tab-item:: GN 188 189 Import ``$dir_pw_unit_test/test.gni`` and create a ``pw_test`` rule that 190 depends on the code you want to test: 191 192 .. code-block:: python 193 194 import("$dir_pw_unit_test/test.gni") 195 196 pw_source_set("mylib") { 197 sources = [ "mylib.cc" ] 198 } 199 200 pw_test("mylib_test") { 201 sources = [ "mylib_test.cc" ] 202 deps = [ ":mylib" ] 203 } 204 205 See :ref:`module-pw_unit_test-gn` for more information. 206 207``pw_unit_test`` generates a simple ``main`` function for running tests on 208:ref:`target-host`. See :ref:`module-pw_unit_test-main` to learn how to 209create your own ``main`` function for running on-device tests. 210 211Write tests 212=========== 213Create test suites and test cases: 214 215.. code-block:: c++ 216 217 #include "mylib.h" 218 219 #include "pw_unit_test/framework.h" 220 221 namespace { 222 223 TEST(MyTestSuite, MyTestCase) { 224 pw::InlineString<32> expected = "(╯°□°)╯︵ ┻━┻"; 225 pw::InlineString<32> actual = app::flip_table(); 226 EXPECT_STREQ(expected.c_str(), actual.c_str()); 227 } 228 229 } // namespace 230 231``pw_unit_test`` provides a standard set of ``TEST``, ``EXPECT``, ``ASSERT`` 232and ``FAIL`` macros. The default backend, ``pw_unit_test:light``, offers an 233embedded-friendly implementation which prioritizes small code size. 234 235Alternativley, users can opt into a larger set of assertion macros, matchers, 236and more detailed error messages by using the ``pw_unit_test:googletest`` 237backend. See :ref:`module-pw_unit_test-backends`. 238 239See `GoogleTest Primer <https://google.github.io/googletest/primer.html>`_ for 240the basics of using GoogleTest. 241 242Run tests 243========= 244.. tab-set:: 245 246 .. tab-item:: Bazel 247 248 .. code-block:: console 249 250 $ bazel test //src:mylib_test 251 252 .. tab-item:: GN 253 254 Run the generated test binary: 255 256 .. code-block:: console 257 258 $ ./out/.../mylib_test 259 260.. _module-pw_unit_test-guides: 261 262------ 263Guides 264------ 265 266.. _module-pw_unit_test-backends: 267 268Choose a backend 269================ 270The default backend, ``pw_unit_test:light``, is a lightweight subset of 271GoogleTest that uses embedded-friendly primitives. It's also highly portable 272because it offloads the responsibility of test reporting and output to the 273underlying system, communicating its results through a common interface. This 274lets you write unit tests once and run them under many different environments. 275 276If the :ref:`subset <module-pw_unit_test-compatibility>` of GoogleTest that 277``pw_unit_test:light`` supports doesn't meet your needs, you can access the 278full upstream GoogleTest API through ``pw_unit_test:googletest``. See 279:ref:`module-pw_unit_test-upstream`. 280 281.. _module-pw_unit_test-main: 282 283Create a custom ``main`` function 284================================= 285For simple unit tests that run on :ref:`target-host` the workflow outlined in 286:ref:`module-pw_unit_test-quickstart` is all you need. Pigweed's build templates 287generate a simple ``main`` function to run the tests with. 288 289To do more complex testing, such as on-device testing: 290 2911. Create your own ``main`` function: 292 293 .. code-block:: c++ 294 295 #include "pw_unit_test/framework.h" 296 // pw_unit_test:light requires an event handler to be configured. 297 #include "pw_unit_test/simple_printing_event_handler.h" 298 299 void WriteString(std::string_view string, bool newline) { 300 printf("%s", string.data()); 301 if (newline) { 302 printf("\n"); 303 } 304 } 305 306 int main() { 307 // Make the binary compatible with pw_unit_test:googletest. Has no effect 308 // when using pw_unit_test:light. 309 testing::InitGoogleTest(); 310 // Set up the event handler for pw_unit_test:light. 311 pw::unit_test::SimplePrintingEventHandler handler(WriteString); 312 pw::unit_test::RegisterEventHandler(&handler); 313 return RUN_ALL_TESTS(); 314 } 315 316 See :ref:`module-pw_unit_test-event-handlers` for more information about 317 handling events. 318 3192. Set the build argument that instructs your build system to use your custom 320 ``main`` function: 321 322 * Bazel: :option:`@pigweed//pw_unit_test:main` 323 * GN: :option:`pw_unit_test_MAIN` 324 325.. _module-pw_unit_test-event-handlers: 326 327Create event handlers 328===================== 329.. _//pw_unit_test/public/pw_unit_test/event_handler.h: https://cs.opensource.google/pigweed/pigweed/+/main:pw_unit_test/public/pw_unit_test/event_handler.h 330 331The ``pw::unit_test::EventHandler`` class defines the interface through which 332``pw_unit_test:light`` communicates the results of its test runs. If you're 333using a :ref:`custom main function <module-pw_unit_test-main>` you need to 334register an event handler to receive test output from the framework. 335 336.. _module-pw_unit_test-predefined-event-handlers: 337 338Predefined event handlers 339------------------------- 340Pigweed provides some standard event handlers to simplify the process of 341getting started with ``pw_unit_test:light``. All event handlers provide for 342GoogleTest-style output using the shared 343:cpp:class:`pw::unit_test::GoogleTestStyleEventHandler` base. Example 344output: 345 346.. code-block:: 347 348 [==========] Running all tests. 349 [ RUN ] Status.Default 350 [ OK ] Status.Default 351 [ RUN ] Status.ConstructWithStatusCode 352 [ OK ] Status.ConstructWithStatusCode 353 [ RUN ] Status.AssignFromStatusCode 354 [ OK ] Status.AssignFromStatusCode 355 [ RUN ] Status.CompareToStatusCode 356 [ OK ] Status.CompareToStatusCode 357 [ RUN ] Status.Ok_OkIsTrue 358 [ OK ] Status.Ok_OkIsTrue 359 [ RUN ] Status.NotOk_OkIsFalse 360 [ OK ] Status.NotOk_OkIsFalse 361 [ RUN ] Status.KnownString 362 [ OK ] Status.KnownString 363 [ RUN ] Status.UnknownString 364 [ OK ] Status.UnknownString 365 [==========] Done running all tests. 366 [ PASSED ] 8 test(s). 367 368.. _module-pw_unit_test-subset: 369 370Run a subset of test suites 371=========================== 372.. _//pw_unit_test/light_public_overrides/pw_unit_test/framework_backend.h: https://cs.opensource.google/pigweed/pigweed/+/main:pw_unit_test/light_public_overrides/pw_unit_test/framework_backend.h 373 374To run only a subset of registered test suites, use the 375``pw::unit_test::SetTestSuitesToRun`` function. See 376`//pw_unit_test/light_public_overrides/pw_unit_test/framework_backend.h`_. 377 378This is useful when you've got a lot of test suites bundled up into a 379:ref:`single test binary <module-pw_unit_test-main>` and you only need 380to run some of them. 381 382.. _module-pw_unit_test-skip: 383 384Skip tests in Bazel 385=================== 386Use ``target_compatible_with`` in Bazel to skip tests. The following test is 387skipped when :ref:`using upstream GoogleTest <module-pw_unit_test-upstream>`: 388 389.. code-block:: 390 391 load("//pw_unit_test:pw_cc_test.bzl", "pw_cc_test") 392 393 pw_cc_test( 394 name = "no_upstream_test", 395 srcs = ["no_upstream_test.cc"], 396 target_compatible_with = select({ 397 "//pw_unit_test:light_setting": [], 398 "//conditions:default": ["@platforms//:incompatible"], 399 }), 400 } 401 402.. _module-pw_unit_test-static: 403 404Run tests in static libraries 405============================= 406To run tests in a static library, use the 407:c:macro:`PW_UNIT_TEST_LINK_FILE_CONTAINING_TEST` macro. 408 409Linkers usually ignore tests through static libraries (i.e. ``.a`` files) 410because test registration relies on the test instance's static constructor 411adding itself to a global list of tests. When linking against a static library, 412static constructors in an object file are ignored unless at least one entity 413in that object file is linked. 414 415.. _module-pw_unit_test-upstream: 416 417Use upstream GoogleTest 418======================= 419To use the upstream GoogleTest backend (``pw_unit_test:googletest``) instead 420of the default backend: 421 422.. _GoogleTestHandlerAdapter: https://cs.opensource.google/pigweed/pigweed/+/main:pw_unit_test/public/pw_unit_test/googletest_handler_adapter.h 423 4241. Clone the GoogleTest repository into your project. See 425 :ref:`module-pw_third_party_googletest`. 426 4272. :ref:`Create a custom main function <module-pw_unit_test-main>`. 428 4293. Combine `GoogleTestHandlerAdapter`_ with a :ref:`predefined event 430 handler <module-pw_unit_test-predefined-event-handlers>` to enable your 431 ``main`` function to work with upstream GoogleTest without modification. 432 433 .. code-block:: c++ 434 435 #include "pw_unit_test/framework.h" 436 #include "pw_unit_test/logging_event_handler.h" 437 438 int main() { 439 testing::InitGoogleTest(); 440 pw::unit_test::LoggingEventHandler logger; 441 pw::unit_test::RegisterEventHandler(&logger); 442 return RUN_ALL_TESTS(); 443 } 444 4454. If your tests needs GoogleTest functionality not included in the default 446 ``pw_unit_test:light`` backend, include the upstream GoogleTest headers 447 (e.g. ``gtest/gtest.h``) directly and guard your target definition to avoid 448 compiling with ``pw_unit_test:light`` (the default backend). 449 450.. _module-pw_unit_test-serial-runner: 451 452Run tests over serial 453===================== 454To accelerate automated unit test bringup for devices with plain-text logging, 455``pw_unit_test`` provides a serial-based test runner in Python that triggers a 456device flash and evaluates whether the test passed or failed based on the 457produced output. 458 459To set up a serial test runner in Python: 460 461.. _//pw_unit_test/py/pw_unit_test/serial_test_runner.py: https://cs.opensource.google/pigweed/pigweed/+/main:pw_unit_test/py/pw_unit_test/serial_test_runner.py 462 4631. Implement a ``SerialTestingDevice`` class for your device. See 464 `//pw_unit_test/py/pw_unit_test/serial_test_runner.py`_. 4652. Configure your device code to wait to run unit tests until 466 ``DEFAULT_TEST_START_CHARACTER`` is sent over the serial connection. 467 468.. _module-pw_unit_test-rpc: 469 470Run tests over RPC 471================== 472.. _//pw_unit_test/pw_unit_test_proto/unit_test.proto: https://cs.opensource.google/pigweed/pigweed/+/main:pw_unit_test/pw_unit_test_proto/unit_test.proto 473 474``pw_unit_test`` provides an RPC service which runs unit tests on demand and 475streams the results back to the client. The service is defined in 476`//pw_unit_test/pw_unit_test_proto/unit_test.proto`_. 477 478The RPC service is primarily intended for use with the default 479``pw_unit_test:light`` backend. It has some support for the upstream GoogleTest 480backend (``pw_unit_test:googletest``), however some features (such as test suite 481filtering) are missing. 482 483To set up RPC-based unit tests in your application: 484 4851. Depend on the relevant target for your build system: 486 487 * Bazel: ``@pigweed//pw_unit_test:rpc_service`` 488 * GN: ``$dir_pw_unit_test:rpc_service`` 489 4902. Create a ``pw::unit_test::UnitTestService`` instance. 491 4923. Register the instance with your RPC server. 493 494 .. code-block:: c++ 495 496 #include "pw_rpc/server.h" 497 #include "pw_unit_test/unit_test_service.h" 498 499 pw::rpc::Channel channels[] = { 500 pw::rpc::Channel::Create<1>(&my_output), 501 }; 502 pw::rpc::Server server(channels); 503 504 pw::unit_test::UnitTestService unit_test_service; 505 506 void RegisterServices() { 507 server.RegisterService(unit_test_services); 508 } 509 510 See :ref:`module-pw_rpc` for more guidance around setting up RPC. 511 5124. Run tests that have been flashed to a device by calling 513 ``pw_unit_test.rpc.run_tests()`` in Python. The argument should be an RPC 514 client services object that has the unit testing RPC service enabled. By 515 default, the results output via logging. The return value is a 516 ``TestRecord`` dataclass instance containing the results of the test run. 517 518 .. code-block:: python 519 520 import serial 521 522 from pw_hdlc import rpc 523 from pw_unit_test.rpc import run_tests 524 525 PROTO = Path( 526 os.environ['PW_ROOT'], 527 'pw_unit_test/pw_unit_test_proto/unit_test.proto' 528 ) 529 serial_device = serial.Serial(device, baud) 530 with rpc.SerialReader(serial_device) as reader: 531 with rpc.HdlcRpcClient( 532 reader, PROTO, rpc.default_channels(serial_device.write) 533 ) as client: 534 run_tests(client.rpcs()) 535 536.. _module-pw_unit_test-cpp: 537 538----------------- 539C++ API reference 540----------------- 541 542``pw_status`` Helpers 543===================== 544Both the light and GoogleTest backends of ``pw_unit_test`` expose some matchers 545for dealing with Pigweed ``pw::Status`` and ``pw::Result`` values. See 546:ref:`module-pw_unit_test-api-expect` and :ref:`module-pw_unit_test-api-assert` 547for details. 548 549.. _module-pw_unit_test-compatibility: 550 551``pw_unit_test:light`` API compatibility 552======================================== 553``pw_unit_test:light`` offers a number of primitives for test declaration, 554assertion, event handlers, and configuration. 555 556.. note:: 557 558 The ``googletest_test_matchers`` target which provides Pigweed-specific 559 ``StatusIs``, ``IsOkAndHolds`` isn't part of the ``pw_unit_test:light`` 560 backend. These matchers are only usable when including the full upstream 561 GoogleTest backend. 562 563Missing features include: 564 565* GoogleMock and matchers (e.g. :c:macro:`EXPECT_THAT`). 566* Death tests (e.g. :c:macro:`EXPECT_DEATH`). ``EXPECT_DEATH_IF_SUPPORTED`` 567 does nothing but silently passes. 568* Value-parameterized tests. 569* Stream messages (e.g. ``EXPECT_TRUE(...) << "My message"``) will compile, but 570 no message will be logged. 571 572See :ref:`module-pw_unit_test-upstream` for guidance on using the 573upstream GoogleTest backend (``pw_unit_test:googletest``) instead of 574``pw_unit_test:light``. 575 576.. _module-pw_unit_test-declare: 577 578Test declaration 579================ 580Note that ``TEST_F`` may allocate fixtures separately from the stack. 581Large variables should be stored in test fixture fields, 582rather than stack variables. This allows the test framework to statically ensure 583that enough space is available to store these variables. 584 585.. doxygendefine:: TEST 586.. doxygendefine:: GTEST_TEST 587.. doxygendefine:: TEST_F 588.. doxygendefine:: FRIEND_TEST 589 590.. _module-pw_unit_test-control: 591 592Test control 593============ 594 595.. doxygenfunction:: RUN_ALL_TESTS 596.. doxygendefine:: FAIL 597.. doxygendefine:: GTEST_FAIL 598.. doxygendefine:: SUCCEED 599.. doxygendefine:: GTEST_SUCCEED 600.. doxygendefine:: GTEST_SKIP 601.. doxygendefine:: ADD_FAILURE 602.. doxygendefine:: GTEST_HAS_DEATH_TEST 603.. doxygendefine:: EXPECT_DEATH_IF_SUPPORTED 604.. doxygendefine:: ASSERT_DEATH_IF_SUPPORTED 605 606.. _module-pw_unit_test-api-expect: 607 608Expectations 609============ 610When a test fails an expectation, the framework marks the test as a failure 611and then continues executing the test. They're useful when you want to 612verify multiple dimensions of the same feature and see all the errors at the 613same time. 614 615.. doxygendefine:: EXPECT_TRUE 616.. doxygendefine:: EXPECT_FALSE 617.. doxygendefine:: EXPECT_EQ 618.. doxygendefine:: EXPECT_NE 619.. doxygendefine:: EXPECT_GT 620.. doxygendefine:: EXPECT_GE 621.. doxygendefine:: EXPECT_LT 622.. doxygendefine:: EXPECT_LE 623.. doxygendefine:: EXPECT_NEAR 624.. doxygendefine:: EXPECT_FLOAT_EQ 625.. doxygendefine:: EXPECT_DOUBLE_EQ 626.. doxygendefine:: EXPECT_STREQ 627.. doxygendefine:: EXPECT_STRNE 628.. doxygendefine:: PW_TEST_EXPECT_OK 629 630.. _module-pw_unit_test-api-assert: 631 632Assertions 633========== 634Assertions work the same as expectations except they stop the execution of the 635test as soon as a failed condition is met. 636 637.. doxygendefine:: ASSERT_TRUE 638.. doxygendefine:: ASSERT_FALSE 639.. doxygendefine:: ASSERT_EQ 640.. doxygendefine:: ASSERT_NE 641.. doxygendefine:: ASSERT_GT 642.. doxygendefine:: ASSERT_GE 643.. doxygendefine:: ASSERT_LT 644.. doxygendefine:: ASSERT_LE 645.. doxygendefine:: ASSERT_NEAR 646.. doxygendefine:: ASSERT_FLOAT_EQ 647.. doxygendefine:: ASSERT_DOUBLE_EQ 648.. doxygendefine:: ASSERT_STREQ 649.. doxygendefine:: ASSERT_STRNE 650.. doxygendefine:: PW_TEST_ASSERT_OK 651.. doxygendefine:: PW_TEST_ASSERT_OK_AND_ASSIGN 652 653.. _module-pw_unit_test-api-event-handlers: 654 655Event handlers 656============== 657.. doxygenfunction:: pw::unit_test::RegisterEventHandler(EventHandler* event_handler) 658.. doxygenclass:: pw::unit_test::EventHandler 659 :members: 660.. doxygenclass:: pw::unit_test::GoogleTestHandlerAdapter 661.. doxygenclass:: pw::unit_test::GoogleTestStyleEventHandler 662.. doxygenclass:: pw::unit_test::SimplePrintingEventHandler 663.. doxygenclass:: pw::unit_test::LoggingEventHandler 664.. doxygenclass:: pw::unit_test::PrintfEventHandler 665.. doxygenclass:: pw::unit_test::MultiEventHandler 666.. doxygenclass:: pw::unit_test::TestRecordEventHandler 667 668.. _module-pw_unit_test-cpp-config: 669 670Configuration 671============= 672.. doxygenfile:: pw_unit_test/config.h 673 :sections: define 674 675.. _module-pw_unit_test-cpp-helpers: 676 677Helpers 678======= 679.. doxygendefine:: PW_UNIT_TEST_LINK_FILE_CONTAINING_TEST 680 681.. _module-pw_unit_test-py: 682 683-------------------- 684Constexpr unit tests 685-------------------- 686.. doxygenfile:: pw_unit_test/constexpr.h 687 :sections: detaileddescription 688 689API reference 690============= 691.. doxygendefine:: PW_CONSTEXPR_TEST 692 693.. block-submission: disable 694.. c:macro:: SKIP_CONSTEXPR_TESTS_DONT_SUBMIT 695 696 Define the ``SKIP_CONSTEXPR_TESTS_DONT_SUBMIT`` macro to temporarily disable 697 the ``constexpr`` portion of subsequent :c:macro:`PW_CONSTEXPR_TEST`\s. Use 698 this to view GoogleTest output, which is usually more informative than the 699 compiler's ``constexpr`` test failure output. 700 701 Defines of this macro should never be submitted. If a test shouldn't run at 702 compile time, use a plain ``TEST()``. 703 704 .. literalinclude:: constexpr_test.cc 705 :language: cpp 706 :start-after: [pw_unit_test-constexpr-skip] 707 :end-before: [pw_unit_test-constexpr-skip] 708.. block-submission: enable 709 710-------------------- 711Python API reference 712-------------------- 713.. _module-pw_unit_test-py-serial_test_runner: 714 715``pw_unit_test.serial_test_runner`` 716=================================== 717.. automodule:: pw_unit_test.serial_test_runner 718 :members: 719 DEFAULT_TEST_START_CHARACTER, 720 SerialTestingDevice, 721 run_device_test, 722 723.. _module-pw_unit_test-py-rpc: 724 725``pw_unit_test.rpc`` 726==================== 727.. automodule:: pw_unit_test.rpc 728 :members: EventHandler, run_tests, TestRecord 729 730.. _module-pw_unit_test-helpers: 731 732---------------------- 733Build helper libraries 734---------------------- 735The following helper libraries can simplify setup and are supported in all 736build systems. 737 738.. object:: simple_printing_event_handler 739 740 When running tests, output test results as plain text over ``pw_sys_io``. 741 742.. object:: simple_printing_main 743 744 Implements a ``main()`` function that simply runs tests using the 745 ``simple_printing_event_handler``. 746 747.. object:: logging_event_handler 748 749 When running tests, log test results as plain text using 750 :ref:`module-pw_log`. Make sure your target has set a ``pw_log`` backend. 751 752.. object:: logging_main 753 754 Implements a ``main()`` function that simply runs tests using the 755 ``logging_event_handler``. 756 757.. _module-pw_unit_test-bazel: 758 759------------------- 760Bazel API reference 761------------------- 762 763See also :ref:`module-pw_unit_test-helpers`. 764 765.. _module-pw_unit_test-pw_cc_test: 766 767``pw_cc_test`` 768============== 769.. _cc_test: https://bazel.build/reference/be/c-cpp#cc_test 770 771``pw_cc_test`` is a wrapper for `cc_test`_ that provides some defaults, such as 772a dependency on ``@pigweed//pw_unit_test:main``. It supports and passes through 773all the arguments recognized by ``cc_test``. 774 775.. _module-pw_unit_test-bazel-args: 776 777Label flags 778=========== 779.. option:: @pigweed//pw_unit_test:backend 780 781 The GoogleTest implementation to use for Pigweed unit tests. This library 782 provides ``gtest/gtest.h`` and related headers. Defaults to 783 ``@pigweed//pw_unit_test:light``, which implements a subset of GoogleTest. 784 785 Type: Bazel target label 786 787 Usage: Typically specified as part of the platform definition, but can also 788 be set manually on the command line. 789 790.. option:: @pigweed//pw_unit_test:main 791 792 Implementation of a main function for ``pw_cc_test`` unit test binaries. To 793 use upstream GoogleTest, set this to ``@com_google_googletest//:gtest_main``. 794 Note that this may not work on most embedded devices, see :bug:`310957361`. 795 796 Type: Bazel target label 797 798 Usage: Typically specified as part of the platform definition, but can also 799 be set manually on the command line. 800 801.. _module-pw_unit_test-gn: 802 803------------ 804GN reference 805------------ 806See also :ref:`module-pw_unit_test-helpers`. 807 808.. _module-pw_unit_test-pw_test: 809 810``pw_test`` 811=========== 812``pw_test`` defines a single unit test suite. 813 814Targets 815------- 816 817.. object:: <target_name> 818 819 The test suite within a single binary. The test code is linked against 820 the target set in the build arg ``pw_unit_test_MAIN``. 821 822.. object:: <target_name>.run 823 824 If ``pw_unit_test_AUTOMATIC_RUNNER`` is set, this target runs the test as 825 part of the build. 826 827.. object:: <target_name>.lib 828 829 The test sources without ``pw_unit_test_MAIN``. 830 831Arguments 832--------- 833All GN executable arguments are accepted and forwarded to the underlying 834``pw_executable``. 835 836.. option:: enable_if 837 838 Boolean indicating whether the test should be built. If false, replaces the 839 test with an empty target. Default true. 840 841.. _get_target_outputs: https://gn.googlesource.com/gn/+/main/docs/reference.md#func_get_target_outputs 842 843.. option:: source_gen_deps 844 845 List of target labels that generate source files used by this test. The 846 labels must meet the constraints of GN's `get_target_outputs`_, namely they must have been previously defined in the 847 current file. This argument is required if a test uses generated source files 848 and ``enable_if`` can evaluate to false. 849 850.. option:: test_main 851 852 Target label to add to the tests's dependencies to provide the ``main()`` 853 function. Defaults to ``pw_unit_test_MAIN``. Set to ``""`` if ``main()`` 854 is implemented in the test's ``sources``. 855 856.. option:: test_automatic_runner_args 857 858 Array of args to pass to :ref:`automatic test 859 runner <module-pw_unit_test-serial-runner>`. Defaults to 860 ``pw_unit_test_AUTOMATIC_RUNNER_ARGS``. 861 862.. option:: envvars 863 864 Array of ``key=value`` strings representing environment variables to set 865 when invoking the automatic test runner. 866 867Example 868------- 869 870.. code-block:: 871 872 import("$dir_pw_unit_test/test.gni") 873 874 pw_test("large_test") { 875 sources = [ "large_test.cc" ] 876 enable_if = device_has_1m_flash 877 } 878 879.. _module-pw_unit_test-pw_test_group: 880 881``pw_test_group`` 882================= 883``pw_test_group`` defines a collection of tests or other test groups. 884 885Targets 886------- 887.. object:: <target_name> 888 889 The test group itself. 890 891.. object:: <target_name>.run 892 893 If ``pw_unit_test_AUTOMATIC_RUNNER`` is set, this target runs all of the 894 tests in the group and all of its group dependencies individually. See 895 :ref:`module-pw_unit_test-serial-runner`. 896 897.. object:: <target_name>.lib 898 899 The sources of all of the tests in this group and their dependencies. 900 901.. object:: <target_name>.bundle 902 903 All of the tests in the group and its dependencies bundled into a single binary. 904 905.. object:: <target_name>.bundle.run 906 907 Automatic runner for the test bundle. 908 909Arguments 910--------- 911.. option:: tests 912 913 List of the ``pw_test`` targets in the group. 914 915.. option:: group_deps 916 917 List of other ``pw_test_group`` targets on which this one depends. 918 919.. option:: enable_if 920 921 Boolean indicating whether the group target should be created. If false, an 922 empty GN group is created instead. Default true. 923 924Example 925------- 926.. code-block:: 927 928 import("$dir_pw_unit_test/test.gni") 929 930 pw_test_group("tests") { 931 tests = [ 932 ":bar_test", 933 ":foo_test", 934 ] 935 } 936 937 pw_test("foo_test") { 938 # ... 939 } 940 941 pw_test("bar_test") { 942 # ... 943 } 944 945.. _module-pw_unit_test-pw_facade_test: 946 947``pw_facade_test`` 948================== 949Pigweed facade test templates allow individual unit tests to build under the 950current device target configuration while overriding specific build arguments. 951This allows these tests to replace a facade's backend for the purpose of testing 952the facade layer. 953 954Facade tests are disabled by default. To build and run facade tests, set the GN 955arg :option:`pw_unit_test_FACADE_TESTS_ENABLED` to ``true``. 956 957.. warning:: 958 Facade tests are costly because each facade test will trigger a re-build of 959 every dependency of the test. While this sounds excessive, it's the only 960 technically correct way to handle this type of test. 961 962.. warning:: 963 Some facade test configurations may not be compatible with your target. Be 964 careful when running a facade test on a system that heavily depends on the 965 facade being tested. 966 967.. _module-pw_unit_test-gn-args: 968 969GN build arguments 970================== 971.. option:: pw_unit_test_BACKEND <source_set> 972 973 The GoogleTest implementation to use for Pigweed unit tests. This library 974 provides ``gtest/gtest.h`` and related headers. Defaults to 975 ``pw_unit_test:light``, which implements a subset of GoogleTest. 976 977 Type: string (GN path to a source set) 978 979 Usage: toolchain-controlled only 980 981.. option:: pw_unit_test_MAIN <source_set> 982 983 Implementation of a main function for ``pw_test`` unit test binaries. 984 See :ref:`module-pw_unit_test-main`. 985 986 Type: string (GN path to a source set) 987 988 Usage: toolchain-controlled only 989 990.. option:: pw_unit_test_AUTOMATIC_RUNNER <executable> 991 992 Path to a test runner to automatically run unit tests after they are built. 993 See :ref:`module-pw_unit_test-serial-runner`. 994 995 If set, a ``pw_test`` target's ``<target_name>.run`` action invokes the 996 test runner specified by this argument, passing the path to the unit test to 997 run. If this is unset, the ``pw_test`` target's ``<target_name>.run`` step 998 will do nothing. 999 1000 Targets that don't support parallelized execution of tests (e.g. an 1001 on-device test runner that must flash a device and run the test in serial) 1002 should set ``pw_unit_test_POOL_DEPTH`` to ``1``. 1003 1004 Type: string (name of an executable on ``PATH``, or a path to an executable) 1005 1006 Usage: toolchain-controlled only 1007 1008.. option:: pw_unit_test_AUTOMATIC_RUNNER_ARGS <args> 1009 1010 An optional list of strings to pass as args to the test runner specified by 1011 ``pw_unit_test_AUTOMATIC_RUNNER``. 1012 1013 Type: list of strings (args to pass to ``pw_unit_test_AUTOMATIC_RUNNER``) 1014 1015 Usage: toolchain-controlled only 1016 1017.. option:: pw_unit_test_AUTOMATIC_RUNNER_TIMEOUT <timeout_seconds> 1018 1019 An optional timeout to apply when running the automatic runner. Timeout is 1020 in seconds. Defaults to empty which means no timeout. 1021 1022 Type: string (number of seconds to wait before killing test runner) 1023 1024 Usage: toolchain-controlled only 1025 1026.. option:: pw_unit_test_POOL_DEPTH <pool_depth> 1027 1028 The maximum number of unit tests that may be run concurrently for the 1029 current toolchain. Setting this to 0 disables usage of a pool, allowing 1030 unlimited parallelization. 1031 1032 Note: A single target with two toolchain configurations (e.g. ``release`` 1033 and ``debug``) uses two separate test runner pools by default. Set 1034 ``pw_unit_test_POOL_TOOLCHAIN`` to the same toolchain for both targets to 1035 merge the pools and force serialization. 1036 1037 Type: integer 1038 1039 Usage: toolchain-controlled only 1040 1041.. option:: pw_unit_test_POOL_TOOLCHAIN <toolchain> 1042 1043 The toolchain to use when referring to the ``pw_unit_test`` runner pool. 1044 When this is disabled, the current toolchain is used. This means that every 1045 toolchain will use its own pool definition. If two toolchains should share 1046 the same pool, this argument should be by one of the toolchains to the GN 1047 path of the other toolchain. 1048 1049 Type: string (GN path to a toolchain) 1050 1051 Usage: toolchain-controlled only 1052 1053.. option:: pw_unit_test_EXECUTABLE_TARGET_TYPE <template name> 1054 1055 The name of the GN target type used to build ``pw_unit_test`` executables. 1056 1057 Type: string (name of a GN template) 1058 1059 Usage: toolchain-controlled only 1060 1061.. option:: pw_unit_test_EXECUTABLE_TARGET_TYPE_FILE <gni file path> 1062 1063 The path to the ``.gni`` file that defines 1064 ``pw_unit_test_EXECUTABLE_TARGET_TYPE``. 1065 1066 If ``pw_unit_test_EXECUTABLE_TARGET_TYPE`` is not the default of 1067 ``pw_executable``, this ``.gni`` file is imported to provide the template 1068 definition. 1069 1070 Type: string (path to a .gni file) 1071 1072 Usage: toolchain-controlled only 1073 1074.. option:: pw_unit_test_FACADE_TESTS_ENABLED <boolean> 1075 1076 Controls whether to build and run facade tests. Facade tests add considerably 1077 to build time, so they are disabled by default. 1078 1079.. option:: pw_unit_test_TESTONLY <boolean> 1080 1081 Controls the ``testonly`` variable in ``pw_test``, ``pw_test_group``, and 1082 miscellaneous testing targets. This is useful if your test libraries (e.g. 1083 GoogleTest) used by pw_unit_test have the ``testonly`` flag set. False by 1084 default for backwards compatibility. 1085 1086.. _module-pw_unit_test-cmake: 1087 1088--------------- 1089CMake reference 1090--------------- 1091See also :ref:`module-pw_unit_test-helpers`. 1092 1093.. _module-pw_unit_test-pw_add_test: 1094 1095``pw_add_test`` 1096=============== 1097``pw_add_test`` declares a single unit test suite. 1098 1099.. tip:: 1100 Upstream Pigweed tests can be disabled in downstream projects by setting 1101 ``pw_unit_test_ENABLE_PW_ADD_TEST`` to ``OFF`` before adding the ``pigweed`` 1102 directory to an existing cmake build. 1103 1104 .. code-block:: cmake 1105 1106 set(pw_unit_test_ENABLE_PW_ADD_TEST OFF) 1107 add_subdirectory(path/to/pigweed pigweed) 1108 set(pw_unit_test_ENABLE_PW_ADD_TEST ON) 1109 1110 See also: :ref:`module-pw_build-existing-cmake-project`. 1111 1112Targets 1113------- 1114.. object:: {NAME} 1115 1116 Depends on ``${NAME}.run`` if ``pw_unit_test_AUTOMATIC_RUNNER`` is set, else 1117 it depends on ``${NAME}.bin``. 1118 1119.. object:: {NAME}.lib 1120 1121 Contains the provided test sources as a library target, which can then be 1122 linked into a test executable. 1123 1124.. object:: {NAME}.bin 1125 1126 A standalone executable which contains only the test sources specified in the 1127 ``pw_unit_test`` template. 1128 1129.. object:: {NAME}.run 1130 1131 Runs the unit test executable after building it if 1132 ``pw_unit_test_AUTOMATIC_RUNNER`` is set, else it fails to build. 1133 1134Required arguments 1135------------------ 1136.. option:: NAME 1137 1138 Name to use for the produced test targets specified above. 1139 1140Optional arguments 1141------------------ 1142.. option:: SOURCES 1143 1144 Source files for this library. 1145 1146.. option:: HEADERS 1147 1148 Header files for this library. 1149 1150.. option:: PRIVATE_DEPS 1151 1152 Private ``pw_target_link_targets`` arguments. 1153.. option:: PRIVATE_INCLUDES 1154 1155 Public ``target_include_directories`` argument. 1156 1157.. option:: PRIVATE_DEFINES 1158 1159 Private ``target_compile_definitions`` arguments. 1160 1161.. option:: PRIVATE_COMPILE_OPTIONS 1162 1163 Private ``target_compile_options`` arguments. 1164 1165.. option:: PRIVATE_LINK_OPTIONS 1166 1167 Private ``target_link_options`` arguments. 1168 1169Example 1170------- 1171 1172.. code-block:: 1173 1174 include($ENV{PW_ROOT}/pw_unit_test/test.cmake) 1175 1176 pw_add_test(my_module.foo_test 1177 SOURCES 1178 foo_test.cc 1179 PRIVATE_DEPS 1180 my_module.foo 1181 ) 1182 1183.. _module-pw_unit_test-pw_add_test_group: 1184 1185``pw_add_test_group`` 1186===================== 1187``pw_add_test_group`` defines a collection of tests or other test groups. 1188 1189Targets 1190------- 1191.. object:: {NAME} 1192 1193 Depends on ``${NAME}.run`` if ``pw_unit_test_AUTOMATIC_RUNNER`` is set, else 1194 it depends on ``${NAME}.bin``. 1195 1196.. object:: {NAME}.bundle 1197 1198 Depends on ``${NAME}.bundle.run`` if ``pw_unit_test_AUTOMATIC_RUNNER`` is 1199 set, else it depends on ``${NAME}.bundle.bin``. 1200 1201.. object:: {NAME}.lib 1202 1203 Depends on ``${NAME}.bundle.lib``. 1204 1205.. object:: {NAME}.bin 1206 1207 Depends on the provided ``TESTS``'s ``<test_dep>.bin`` targets. 1208 1209.. object:: {NAME}.run 1210 1211 Depends on the provided ``TESTS``'s ``<test_dep>.run`` targets if 1212 ``pw_unit_test_AUTOMATIC_RUNNER`` is set, else it fails to build. 1213 1214.. object:: {NAME}.bundle.lib 1215 1216 Contains the provided tests bundled as a library target, which can then be 1217 linked into a test executable. 1218 1219.. object:: {NAME}.bundle.bin 1220 1221 Standalone executable which contains the bundled tests. 1222 1223.. object:: {NAME}.bundle.run 1224 1225 Runs the ``{NAME}.bundle.bin`` test bundle executable after building it if 1226 ``pw_unit_test_AUTOMATIC_RUNNER`` is set, else it fails to build. 1227 1228Required arguments 1229------------------ 1230.. option:: NAME 1231 1232 The name of the executable target to be created. 1233 1234.. option:: TESTS 1235 1236 ``pw_add_test`` targets and ``pw_add_test_group`` bundles to be 1237 included in this test bundle. 1238 1239Example 1240------- 1241.. code-block:: 1242 1243 include($ENV{PW_ROOT}/pw_unit_test/test.cmake) 1244 1245 pw_add_test_group(tests 1246 TESTS 1247 bar_test 1248 foo_test 1249 ) 1250 1251 pw_add_test(foo_test 1252 # ... 1253 ) 1254 1255 pw_add_test(bar_test 1256 # ... 1257 ) 1258 1259.. _module-pw_unit_test-cmake-args: 1260 1261CMake build arguments 1262===================== 1263.. option:: pw_unit_test_BACKEND <target> 1264 1265 The GoogleTest implementation to use for Pigweed unit tests. This library 1266 provides ``gtest/gtest.h`` and related headers. Defaults to 1267 ``pw_unit_test.light``, which implements a subset of GoogleTest. 1268 1269 Type: string (CMake target name) 1270 1271 Usage: toolchain-controlled only 1272 1273.. option:: pw_unit_test_AUTOMATIC_RUNNER <executable> 1274 1275 Path to a test runner to automatically run unit tests after they're built. 1276 1277 If set, a ``pw_test`` target's ``${NAME}`` and ``${NAME}.run`` targets will 1278 invoke the test runner specified by this argument, passing the path to the 1279 unit test to run. If this is unset, the ``pw_test`` target's ``${NAME}`` will 1280 only build the unit test(s) and ``${NAME}.run`` will fail to build. 1281 1282 Type: string (name of an executable on the PATH, or path to an executable) 1283 1284 Usage: toolchain-controlled only 1285 1286.. option:: pw_unit_test_AUTOMATIC_RUNNER_ARGS <args> 1287 1288 An optional list of strings to pass as args to the test runner specified 1289 by ``pw_unit_test_AUTOMATIC_RUNNER``. 1290 1291 Type: list of strings (args to pass to pw_unit_test_AUTOMATIC_RUNNER) 1292 1293 Usage: toolchain-controlled only 1294 1295.. option:: pw_unit_test_AUTOMATIC_RUNNER_TIMEOUT_SECONDS <timeout_seconds> 1296 1297 An optional timeout to apply when running the automatic runner. Timeout is 1298 in seconds. Defaults to empty which means no timeout. 1299 1300 Type: string (number of seconds to wait before killing test runner) 1301 1302 Usage: toolchain-controlled only 1303 1304.. option:: pw_unit_test_ADD_EXECUTABLE_FUNCTION <function name> 1305 1306 The name of the CMake function used to build ``pw_unit_test`` executables. 1307 The provided function must take a ``NAME`` and a ``TEST_LIB`` argument which 1308 are the expected name of the executable target and the target which provides 1309 the unit test(s). 1310 1311 Type: string (name of a CMake function) 1312 1313 Usage: toolchain-controlled only 1314 1315.. option:: pw_unit_test_ADD_EXECUTABLE_FUNCTION_FILE <cmake file path> 1316 1317 The path to the ``.cmake`` file that defines 1318 ``pw_unit_test_ADD_EXECUTABLE_FUNCTION``. 1319 1320 Type: string (path to a ``.cmake`` file) 1321 1322 Usage: toolchain-controlled only 1323