xref: /aosp_15_r20/external/bazelbuild-rules_testing/lib/unit_test.bzl (revision d605057434dcabba796c020773aab68d9790ff9f)
1# Copyright 2022 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"""# Unit test
15
16Support for testing generic Starlark code, i.e. code that doesn't require
17the analysis phase or instantiate rules.
18"""
19
20# We have to load the private impl to avoid a circular dependency
21load("//lib/private:analysis_test.bzl", "analysis_test")
22
23_TARGET = Label("//lib:_stub_target_for_unit_tests")
24
25def unit_test(name, impl, attrs = {}):
26    """Creates a test for generic Starlark code (i.e. non-rule/macro specific).
27
28    Unless you need custom attributes passed to the test, you probably don't need
29    this and can, instead, pass your test function directly to `test_suite.tests`.
30
31    See also: analysis_test, for testing analysis time behavior, such as rules.
32
33    Args:
34        name: (str) the name of the test
35        impl: (callable) the function implementing the test's asserts. It takes
36            a single position arg, `env`, which is information about the
37            test environment (see analysis_test docs).
38        attrs: (dict of str to str) additional attributes to make available to
39            the test.
40    """
41    analysis_test(
42        name = name,
43        impl = lambda env, target: impl(env),
44        target = _TARGET,
45        attrs = attrs,
46    )
47