xref: /aosp_15_r20/external/bazelbuild-rules_testing/lib/private/label_subject.bzl (revision d605057434dcabba796c020773aab68d9790ff9f)
1# Copyright 2023 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"""# LabelSubject"""
16
17load("@bazel_skylib//lib:types.bzl", "types")
18load(":check_util.bzl", "common_subject_is_in")
19load(":truth_common.bzl", "to_list")
20
21def _label_subject_new(label, meta):
22    """Creates a new `LabelSubject` for asserting `Label` objects.
23
24    Method: LabelSubject.new
25
26    Args:
27        label: ([`Label`]) the label to check against.
28        meta: ([`ExpectMeta`]) the metadata about the call chain.
29
30    Returns:
31        [`LabelSubject`].
32    """
33
34    # buildifier: disable=uninitialized
35    public = struct(
36        # keep sorted start
37        equals = lambda *a, **k: _label_subject_equals(self, *a, **k),
38        is_in = lambda *a, **k: _label_subject_is_in(self, *a, **k),
39        # keep sorted end
40    )
41    self = struct(actual = label, meta = meta)
42    return public
43
44def _label_subject_equals(self, other):
45    """Asserts the label is equal to `other`.
46
47    Method: LabelSubject.equals
48
49    Args:
50        self: implicitly added.
51        other: ([`Label`] | [`str`]) the expected value. If a `str` is passed, it
52            will be converted to a `Label` using the `Label` function.
53    """
54    if types.is_string(other):
55        other = Label(other)
56    if self.actual == other:
57        return
58    self.meta.add_failure(
59        "expected: {}".format(other),
60        "actual: {}".format(self.actual),
61    )
62
63def _label_subject_is_in(self, any_of):
64    """Asserts that the label is any of the provided values.
65
66    Args:
67        self: implicitly added.
68        any_of: ([`collection`] of ([`Label`] | [`str`])) If strings are
69            provided, they must be parsable by `Label`.
70    """
71    any_of = [
72        Label(v) if types.is_string(v) else v
73        for v in to_list(any_of)
74    ]
75    common_subject_is_in(self, any_of)
76
77# We use this name so it shows up nice in docs.
78# buildifier: disable=name-conventions
79LabelSubject = struct(
80    new = _label_subject_new,
81    equals = _label_subject_equals,
82    is_in = _label_subject_is_in,
83)
84