Setting up coverage
As of Bazel 6, the Python toolchains and bootstrap logic supports providingcoverage information using thecoverage library.
As ofrules_python version0.18.1, builtin coverage support can be enabledwhen configuring toolchains.
Enablingrules_python coverage support
Enabling the coverage support bundled withrules_python just requires setting anargument when registering toolchains.
For Bzlmod:
python.toolchain("@python3_9_toolchains//:all",configure_coverage_tool=True,)
For WORKSPACE configuration:
python_register_toolchains(register_coverage_tool=True,)
Note
This will implicitly add the version ofcoverage bundled withrules_python to the dependencies ofpy_test rules whenbazelcoverage isrun. If a target already transitively depends on a different version ofcoverage, then the behavior is undefined – it is undefined which version comesfirst in the import path. If you find yourself in this situation, then you’llneed to manually configure coverage (see below).
Manually configuring coverage
To manually configure coverage support, you’ll need to set thepy_runtime.coverage_tool attribute. This attribute is a target that specifiesthe coverage entry point file and, optionally, client libraries that are addedtopy_test targets. Typically, this would be afilegroup that looked like:
filegroup(name="coverage",srcs=["coverage_main.py"],data=["coverage_lib1.py",...])
Usingfilegroup isn’t required, nor are including client libraries. Theimportant behaviors of the target are:
It provides a single output file OR it provides an executable output; thisoutput is treated as the coverage entry point.
If it provides runfiles, then
runfiles.filesare included intopy_test.