• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2019 The Bazel Authors. All rights reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#    http://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,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""A test verifying other targets build as part of a `bazel test`"""
16
17load("//lib:new_sets.bzl", "sets")
18
19def _empty_test_impl(ctx):
20    extension = ".bat" if ctx.attr.is_windows else ".sh"
21    content = "exit 0" if ctx.attr.is_windows else "#!/usr/bin/env bash\nexit 0"
22    executable = ctx.actions.declare_file(ctx.label.name + extension)
23    ctx.actions.write(
24        output = executable,
25        is_executable = True,
26        content = content,
27    )
28
29    return [DefaultInfo(
30        files = depset([executable]),
31        executable = executable,
32        runfiles = ctx.runfiles(files = ctx.files.data),
33    )]
34
35_empty_test = rule(
36    implementation = _empty_test_impl,
37    attrs = {
38        "data": attr.label_list(allow_files = True),
39        "is_windows": attr.bool(mandatory = True),
40    },
41    test = True,
42)
43
44def build_test(name, targets, **kwargs):
45    """Test rule checking that other targets build.
46
47    This works not by an instance of this test failing, but instead by
48    the targets it depends on failing to build, and hence failing
49    the attempt to run this test.
50
51    Typical usage:
52
53    ```
54      load("@bazel_skylib//rules:build_test.bzl", "build_test")
55      build_test(
56          name = "my_build_test",
57          targets = [
58              "//some/package:rule",
59          ],
60      )
61    ```
62
63    Args:
64      name: The name of the test rule.
65      targets: A list of targets to ensure build.
66      **kwargs: The <a href="https://docs.bazel.build/versions/main/be/common-definitions.html#common-attributes-tests">common attributes for tests</a>.
67    """
68    if len(targets) == 0:
69        fail("targets must be non-empty", "targets")
70    if kwargs.get("data", None):
71        fail("data is not supported on a build_test()", "data")
72
73    # Remove any duplicate test targets.
74    targets = sets.to_list(sets.make(targets))
75
76    # Use a genrule to ensure the targets are built (works because it forces
77    # the outputs of the other rules on as data for the genrule)
78
79    # Split into batches to hopefully avoid things becoming so large they are
80    # too much for a remote execution set up.
81    batch_size = max(1, len(targets) // 100)
82
83    # Pull a few args over from the test to the genrule.
84    args_to_reuse = ["compatible_with", "restricted_to", "tags"]
85    genrule_args = {k: kwargs.get(k) for k in args_to_reuse if k in kwargs}
86
87    # Pass an output from the genrules as data to a shell test to bundle
88    # it all up in a test.
89    test_data = []
90
91    for idx, batch in enumerate([targets[i:i + batch_size] for i in range(0, len(targets), batch_size)]):
92        full_name = "{name}_{idx}__deps".format(name = name, idx = idx)
93        test_data.append(full_name)
94        native.genrule(
95            name = full_name,
96            srcs = batch,
97            outs = [full_name + ".out"],
98            testonly = 1,
99            visibility = ["//visibility:private"],
100            cmd = "touch $@",
101            cmd_bat = "type nul > $@",
102            **genrule_args
103        )
104
105    _empty_test(
106        name = name,
107        data = test_data,
108        size = kwargs.pop("size", "small"),  # Default to small for test size
109        is_windows = select({
110            "@bazel_tools//src/conditions:host_windows": True,
111            "//conditions:default": False,
112        }),
113        **kwargs
114    )
115