• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Setting up coverage
2
3As of Bazel 6, the Python toolchains and bootstrap logic supports providing
4coverage information using the `coverage` library.
5
6As of `rules_python` version `0.18.1`, builtin coverage support can be enabled
7when configuring toolchains.
8
9## Enabling `rules_python` coverage support
10
11Enabling the coverage support bundled with `rules_python` just requires setting an
12argument when registerting toolchains.
13
14For Bzlmod:
15
16```starlark
17python.toolchain(
18    "@python3_9_toolchains//:all",
19    configure_coverage_tool = True,
20)
21```
22
23For WORKSPACE configuration:
24
25```starlark
26python_register_toolchains(
27   register_coverage_tool = True,
28)
29```
30
31NOTE: This will implicitly add the version of `coverage` bundled with
32`rules_python` to the dependencies of `py_test` rules when `bazel coverage` is
33run. If a target already transitively depends on a different version of
34`coverage`, then behavior is undefined -- it is undefined which version comes
35first in the import path. If you find yourself in this situation, then you'll
36need to manually configure coverage (see below).
37
38## Manually configuring coverage
39
40To manually configure coverage support, you'll need to set the
41`py_runtime.coverage_tool` attribute. This attribute is a target that specifies
42the coverage entry point file and, optionally, client libraries that are added
43to `py_test` targets. Typically, this would be a `filegroup` that looked like:
44
45```starlark
46filegroup(
47  name = "coverage",
48  srcs = ["coverage_main.py"],
49  data = ["coverage_lib1.py", ...]
50)
51```
52
53Using `filegroup` isn't required, nor are including client libraries. The
54important behaviors of the target are:
55
56*   It provides a single output file OR it provides an executable output; this
57    output is treated as the coverage entry point.
58*   If it provides runfiles, then `runfiles.files` are included into `py_test`.
59