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 31:::{note} 32This will implicitly add the version of `coverage` bundled with 33`rules_python` to the dependencies of `py_test` rules when `bazel coverage` is 34run. If a target already transitively depends on a different version of 35`coverage`, then behavior is undefined -- it is undefined which version comes 36first in the import path. If you find yourself in this situation, then you'll 37need to manually configure coverage (see below). 38::: 39 40## Manually configuring coverage 41 42To manually configure coverage support, you'll need to set the 43`py_runtime.coverage_tool` attribute. This attribute is a target that specifies 44the coverage entry point file and, optionally, client libraries that are added 45to `py_test` targets. Typically, this would be a `filegroup` that looked like: 46 47```starlark 48filegroup( 49 name = "coverage", 50 srcs = ["coverage_main.py"], 51 data = ["coverage_lib1.py", ...] 52) 53``` 54 55Using `filegroup` isn't required, nor are including client libraries. The 56important behaviors of the target are: 57 58* It provides a single output file OR it provides an executable output; this 59 output is treated as the coverage entry point. 60* If it provides runfiles, then `runfiles.files` are included into `py_test`. 61