Skip to content

Commit 0d3a405

Browse files
committed
feat(toolchain): Python testing toolchain
Inspired by https://github.com/trybka/scraps/blob/master/cc_test.md This PR extends Test Runner enviroment to provide a coveragerc enviroment variable COVERAGE_RC, allowing user to provide coverage resource in what ever format
1 parent 797cbe8 commit 0d3a405

14 files changed

+312
-10
lines changed

examples/bzlmod/.coveragerc

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
[report]
2+
include_namespace_packages=True
3+
skip_covered=True
4+
[run]
5+
relative_files=True
6+
branch=True

examples/bzlmod/BUILD.bazel

+2
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ load("@python_3_9//:defs.bzl", py_test_with_transition = "py_test")
1111
load("@python_versions//3.10:defs.bzl", compile_pip_requirements_3_10 = "compile_pip_requirements")
1212
load("@rules_python//python:defs.bzl", "py_binary", "py_library", "py_test")
1313

14+
exports_files([".coveragerc"])
15+
1416
# This stanza calls a rule that generates targets for managing pip dependencies
1517
# with pip-compile for a particular python version.
1618
compile_pip_requirements_3_10(

examples/bzlmod/MODULE.bazel

+7-1
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@ python.toolchain(
3636
configure_coverage_tool = True,
3737
python_version = "3.10",
3838
)
39+
python.converage(
40+
name = "coverage",
41+
coveragerc = ".coveragerc",
42+
)
3943

4044
# One can override the actual toolchain versions that are available, which can be useful
4145
# when optimizing what gets downloaded and when.
@@ -89,7 +93,9 @@ python.single_version_platform_override(
8993
# See the tests folder for various examples on using multiple Python versions.
9094
# The names "python_3_9" and "python_3_10" are autmatically created by the repo
9195
# rules based on the `python_version` arg values.
92-
use_repo(python, "python_3_10", "python_3_9", "python_versions", "pythons_hub")
96+
use_repo(python, "coverage_py_test_toolchain", "python_3_10", "python_3_9", "python_versions", "pythons_hub")
97+
98+
register_toolchains("@coverage_py_test_toolchain//:all")
9399

94100
# EXPERIMENTAL: This is experimental and may be removed without notice
95101
uv = use_extension("@rules_python//python/uv:extensions.bzl", "uv")

examples/bzlmod/tests/BUILD.bazel

+6
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,12 @@ py_test(
4848
deps = ["//libs/my_lib"],
4949
)
5050

51+
py_test(
52+
name = "coverage_rc_is_set_test",
53+
srcs = ["coverage_rc_is_set_test.py"],
54+
main = "coverage_rc_is_set_test.py",
55+
)
56+
5157
py_test_3_9(
5258
name = "my_lib_3_9_test",
5359
srcs = ["my_lib_test.py"],
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Copyright 2024 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+
import os
15+
import tempfile
16+
import unittest
17+
18+
19+
class TestEnvironmentVariables(unittest.TestCase):
20+
def test_coverage_rc_file_exists(self):
21+
# Assert that the environment variable is set and points to a valid file
22+
coverage_rc_path = os.environ.get("COVERAGE_RC")
23+
self.assertTrue(
24+
os.path.isfile(coverage_rc_path),
25+
"COVERAGE_RC does not point to a valid file",
26+
)
27+
28+
# Read the content of the file and assert it matches the expected content
29+
expected_content = (
30+
"[report]\n"
31+
"include_namespace_packages=True\n"
32+
"skip_covered=True\n"
33+
"[run]\n"
34+
"relative_files=True\n"
35+
"branch=True\n"
36+
)
37+
38+
with open(coverage_rc_path, "r") as file:
39+
file_content = file.read()
40+
41+
self.assertEqual(
42+
file_content,
43+
expected_content,
44+
"COVERAGE_RC file content does not match the expected content",
45+
)
46+
47+
48+
if __name__ == "__main__":
49+
unittest.main()

python/BUILD.bazel

+5
Original file line numberDiff line numberDiff line change
@@ -363,3 +363,8 @@ exports_files([
363363
current_py_toolchain(
364364
name = "current_py_toolchain",
365365
)
366+
367+
toolchain_type(
368+
name = "py_test_toolchain_type",
369+
visibility = ["//visibility:public"],
370+
)

python/extensions/python_test.bzl

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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+
"""Python toolchain module extensions for use with bzlmod.
16+
17+
::::{topic} Basic usage
18+
19+
The simplest way to configure the toolchain with `rules_python` is as follows.
20+
21+
```starlark
22+
python_test = use_extension("@rules_python//python/extensions:python_test.bzl", "python_test")
23+
python_test.configure(
24+
coveragerc = ".coveragerc",
25+
)
26+
use_repo(python_test, "py_test_toolchain")
27+
register_toolchains("@py_test_toolchain//:all")
28+
```
29+
30+
:::{seealso}
31+
For more in-depth documentation see the {obj}`python.toolchain`.
32+
:::
33+
::::
34+
35+
"""
36+
37+
load("//python/private:python_test.bzl", _python_test = "python_test")
38+
39+
python_test = _python_test

python/private/py_executable.bzl

+19-4
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ load(
6060
load(
6161
":toolchain_types.bzl",
6262
"EXEC_TOOLS_TOOLCHAIN_TYPE",
63+
"PY_TEST_TOOLCHAIN_TYPE",
6364
TOOLCHAIN_TYPE = "TARGET_TOOLCHAIN_TYPE",
6465
)
6566

@@ -254,6 +255,7 @@ def py_executable_base_impl(ctx, *, semantics, is_test, inherited_environment =
254255
inherited_environment = inherited_environment,
255256
semantics = semantics,
256257
output_groups = exec_result.output_groups,
258+
is_test = is_test,
257259
)
258260

259261
def _get_build_info(ctx, cc_toolchain):
@@ -819,7 +821,8 @@ def _create_providers(
819821
inherited_environment,
820822
runtime_details,
821823
output_groups,
822-
semantics):
824+
semantics,
825+
is_test):
823826
"""Creates the providers an executable should return.
824827
825828
Args:
@@ -851,21 +854,32 @@ def _create_providers(
851854
Returns:
852855
A list of modern providers.
853856
"""
857+
858+
default_runfiles = runfiles_details.default_runfiles
859+
extra_test_env = {}
860+
861+
if is_test:
862+
py_test_toolchain = ctx.exec_groups["test"].toolchains[PY_TEST_TOOLCHAIN_TYPE]
863+
if py_test_toolchain:
864+
coverage_rc = py_test_toolchain.py_test_info.coverage_rc
865+
extra_test_env = {"COVERAGE_RC": coverage_rc.files.to_list()[0].path}
866+
default_runfiles = default_runfiles.merge(ctx.runfiles(files = coverage_rc.files.to_list()))
867+
854868
providers = [
855869
DefaultInfo(
856870
executable = executable,
857871
files = default_outputs,
858872
default_runfiles = _py_builtins.make_runfiles_respect_legacy_external_runfiles(
859873
ctx,
860-
runfiles_details.default_runfiles,
874+
default_runfiles,
861875
),
862876
data_runfiles = _py_builtins.make_runfiles_respect_legacy_external_runfiles(
863877
ctx,
864878
runfiles_details.data_runfiles,
865879
),
866880
),
867881
create_instrumented_files_info(ctx),
868-
_create_run_environment_info(ctx, inherited_environment),
882+
_create_run_environment_info(ctx, inherited_environment, extra_test_env),
869883
PyExecutableInfo(
870884
main = main_py,
871885
runfiles_without_exe = runfiles_details.runfiles_without_exe,
@@ -937,7 +951,7 @@ def _create_providers(
937951
providers.extend(extra_providers)
938952
return providers
939953

940-
def _create_run_environment_info(ctx, inherited_environment):
954+
def _create_run_environment_info(ctx, inherited_environment, extra_test_env):
941955
expanded_env = {}
942956
for key, value in ctx.attr.env.items():
943957
expanded_env[key] = _py_builtins.expand_location_and_make_variables(
@@ -946,6 +960,7 @@ def _create_run_environment_info(ctx, inherited_environment):
946960
expression = value,
947961
targets = ctx.attr.data,
948962
)
963+
expanded_env.update(extra_test_env)
949964
return RunEnvironmentInfo(
950965
environment = expanded_env,
951966
inherited_environment = inherited_environment,

python/private/py_test_rule_bazel.bzl

+4
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
"""Rule implementation of py_test for Bazel."""
1515

1616
load("@bazel_skylib//lib:dicts.bzl", "dicts")
17+
load("//python/private:toolchain_types.bzl", "PY_TEST_TOOLCHAIN_TYPE")
1718
load(":attributes.bzl", "AGNOSTIC_TEST_ATTRS")
1819
load(":common.bzl", "maybe_add_test_execution_info")
1920
load(
@@ -52,4 +53,7 @@ py_test = create_executable_rule(
5253
implementation = _py_test_impl,
5354
attrs = dicts.add(AGNOSTIC_TEST_ATTRS, _BAZEL_PY_TEST_ATTRS),
5455
test = True,
56+
exec_groups = {
57+
"test": exec_group(toolchains = [config_common.toolchain_type(PY_TEST_TOOLCHAIN_TYPE, mandatory = False)]),
58+
},
5559
)

python/private/py_test_toolchain.bzl

+93
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# Copyright 2024 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+
"""
16+
Simple toolchain which overrides env and exec requirements.
17+
"""
18+
19+
load(":text_util.bzl", "render")
20+
load(
21+
":toolchain_types.bzl",
22+
"PY_TEST_TOOLCHAIN_TYPE",
23+
)
24+
25+
PytestProvider = provider(
26+
fields = [
27+
"coverage_rc",
28+
],
29+
)
30+
31+
def _py_test_toolchain_impl(ctx):
32+
return [
33+
platform_common.ToolchainInfo(
34+
py_test_info = PytestProvider(
35+
coverage_rc = ctx.attr.coverage_rc,
36+
),
37+
),
38+
]
39+
40+
py_test_toolchain = rule(
41+
implementation = _py_test_toolchain_impl,
42+
attrs = {
43+
"coverage_rc": attr.label(
44+
allow_single_file = True,
45+
),
46+
},
47+
)
48+
_TOOLCHAIN_TEMPLATE = """
49+
load("@rules_python//python/private:py_test_toolchain.bzl", "py_test_toolchain")
50+
py_test_toolchain(
51+
name = "{name}_toolchain",
52+
coverage_rc = "{coverage_rc}",
53+
)
54+
55+
toolchain(
56+
name = "{name}",
57+
target_compatible_with = [],
58+
exec_compatible_with = [],
59+
toolchain = "{name}_toolchain",
60+
toolchain_type = "{toolchain_type}",
61+
)
62+
"""
63+
64+
def _toolchains_repo_impl(repository_ctx):
65+
build_content = _TOOLCHAIN_TEMPLATE.format(
66+
name = "py_test_toolchain",
67+
toolchain_type = repository_ctx.attr.toolchain_type,
68+
coverage_rc = repository_ctx.attr.coverage_rc,
69+
)
70+
repository_ctx.file("BUILD.bazel", build_content)
71+
72+
py_test_toolchain_repo = repository_rule(
73+
_toolchains_repo_impl,
74+
doc = "Generates a toolchain hub repository",
75+
attrs = {
76+
"toolchain_type": attr.string(doc = "Toolchain type", mandatory = True),
77+
"coverage_rc": attr.label(
78+
allow_single_file = True,
79+
doc = "The coverage rc file",
80+
mandatory = True,
81+
),
82+
},
83+
)
84+
85+
def register_py_test_toolchain(coverage_rc, register_toolchains = True):
86+
# Need to create a repository rule for this to work.
87+
py_test_toolchain_repo(
88+
name = "py_test_toolchain",
89+
coverage_rc = coverage_rc,
90+
toolchain_type = str(PY_TEST_TOOLCHAIN_TYPE),
91+
)
92+
if register_toolchains:
93+
native.toolchain(name = "py_test_toolchain")

python/private/py_toolchain_suite.bzl

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ load(
2020
":toolchain_types.bzl",
2121
"EXEC_TOOLS_TOOLCHAIN_TYPE",
2222
"PY_CC_TOOLCHAIN_TYPE",
23+
"PY_TEST_TOOLCHAIN_TYPE",
2324
"TARGET_TOOLCHAIN_TYPE",
2425
)
2526

0 commit comments

Comments
 (0)