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"""Helpers and utilities multiple tests re-use.""" 15 16load("@bazel_skylib//lib:structs.bzl", "structs") 17load("//python/private:util.bzl", "IS_BAZEL_6_OR_HIGHER") # buildifier: disable=bzl-visibility 18 19# Use this with is_windows() 20WINDOWS_ATTR = {"windows": attr.label(default = "@platforms//os:windows")} 21 22def _create_tests(tests, **kwargs): 23 test_names = [] 24 for func in tests: 25 test_name = _test_name_from_function(func) 26 func(name = test_name, **kwargs) 27 test_names.append(test_name) 28 return test_names 29 30def _test_name_from_function(func): 31 """Derives the name of the given rule implementation function. 32 33 Args: 34 func: the function whose name to extract 35 36 Returns: 37 The name of the given function. Note it will have leading and trailing 38 "_" stripped -- this allows passing a private function and having the 39 name of the test not start with "_". 40 """ 41 42 # Starlark currently stringifies a function as "<function NAME>", so we use 43 # that knowledge to parse the "NAME" portion out. 44 # NOTE: This is relying on an implementation detail of Bazel 45 func_name = str(func) 46 func_name = func_name.partition("<function ")[-1] 47 func_name = func_name.rpartition(">")[0] 48 func_name = func_name.partition(" ")[0] 49 return func_name.strip("_") 50 51def _struct_with(s, **kwargs): 52 struct_dict = structs.to_dict(s) 53 struct_dict.update(kwargs) 54 return struct(**struct_dict) 55 56def _is_bazel_6_or_higher(): 57 return IS_BAZEL_6_OR_HIGHER 58 59def _is_windows(env): 60 """Tell if the target platform is windows. 61 62 This assumes the `WINDOWS_ATTR` attribute was added. 63 64 Args: 65 env: The test env struct 66 Returns: 67 True if the target is Windows, False if not. 68 """ 69 constraint = env.ctx.attr.windows[platform_common.ConstraintValueInfo] 70 return env.ctx.target_platform_has_constraint(constraint) 71 72util = struct( 73 create_tests = _create_tests, 74 struct_with = _struct_with, 75 is_bazel_6_or_higher = _is_bazel_6_or_higher, 76 is_windows = _is_windows, 77) 78