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