xref: /aosp_15_r20/external/pigweed/pw_unit_test/pw_cc_test.bzl (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1# Copyright 2024 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"""Rules for declaring unit tests."""
15
16def pw_cc_test(**kwargs):
17    """Wrapper for cc_test providing some defaults.
18
19    Specifically, this wrapper,
20
21    *  Adds a dep on the pw_assert backend.
22    *  Adds a dep on //pw_unit_test:simple_printing_main
23
24    In addition, a .lib target is created that's a cc_library with the same
25    kwargs. Such library targets can be used as dependencies of firmware images
26    bundling multiple tests. The library target has alwayslink = 1, to support
27    dynamic registration (ensure the tests are baked into the image even though
28    there are no references to them, so that they can be found by RUN_ALL_TESTS
29    at runtime).
30
31    Args:
32      **kwargs: Passed to cc_test.
33    """
34
35    # TODO: b/234877642 - Remove this implicit dependency once we have a better
36    # way to handle the facades without introducing a circular dependency into
37    # the build.
38    kwargs["deps"] = kwargs.get("deps", []) + [str(Label("//pw_build:default_link_extra_lib"))]
39
40    # Depend on the backend. E.g. to pull in gtest.h include paths.
41    kwargs["deps"] = kwargs["deps"] + [str(Label("//pw_unit_test:backend"))]
42
43    # Save the base set of deps minus pw_unit_test:main for the .lib target.
44    original_deps = kwargs["deps"]
45
46    # Add the unit test main label flag dep.
47    test_main = kwargs.pop("test_main", str(Label("//pw_unit_test:main")))
48    kwargs["deps"] = original_deps + [test_main]
49
50    native.cc_test(**kwargs)
51
52    kwargs["alwayslink"] = 1
53
54    # pw_cc_test deps may include testonly targets.
55    kwargs["testonly"] = True
56
57    # Remove any kwargs that cc_library would not recognize.
58    for arg in (
59        "additional_linker_inputs",
60        "args",
61        "env",
62        "env_inherit",
63        "flaky",
64        "local",
65        "malloc",
66        "shard_count",
67        "size",
68        "stamp",
69        "timeout",
70    ):
71        kwargs.pop(arg, "")
72
73    # Reset the deps for the .lib target.
74    kwargs["deps"] = original_deps
75    native.cc_library(name = kwargs.pop("name") + ".lib", **kwargs)
76