Skip to main content
Version: 2.22

python_tests


Generate a python_test target for each file in the sources field.

Backend: pants.backend.python


batch_compatibility_tag

str | None
default: None

An arbitrary value used to mark the test files belonging to this target as valid for batched execution.

It's sometimes safe to run multiple python_tests within a single test runner process, and doing so can give significant wins by allowing reuse of expensive test setup / teardown logic. To opt into this behavior, set this field to an arbitrary non-empty string on all the python_test targets that are safe/compatible to run in the same process.

If this field is left unset on a target, the target is assumed to be incompatible with all others and will run in a dedicated pytest process.

If this field is set on a target, and its value is different from the value on some other test python_test, then the two targets are explicitly incompatible and are guaranteed to not run in the same pytest process.

If this field is set on a target, and its value is the same as the value on some other python_test, then the two targets are explicitly compatible and may run in the same test runner process. Compatible tests may not end up in the same test runner batch if:

  • There are "too many" compatible tests in a partition, as determined by the [test].batch_size config parameter, or
  • Compatible tests have some incompatibility in Pants metadata (i.e. different resolves or extra_env_vars).

When tests with the same batch_compatibility_tag have incompatibilities in some other Pants metadata, they will be automatically split into separate batches. This way you can set a high-level batch_compatibility_tag using __defaults__ and then have tests continue to work as you tweak BUILD metadata on specific targets.

dependencies

Iterable[str] | None
default: None

Addresses to other targets that this target depends on, e.g. ['helloworld/subdir:lib', 'helloworld/main.py:lib', '3rdparty:reqs#django'].

This augments any dependencies inferred by Pants, such as by analyzing your imports. Use pants dependencies or pants peek on this target to get the final result.

See https://www.pantsbuild.org/2.22/docs/using-pants/key-concepts/targets-and-build-files for more about how addresses are formed, including for generated targets. You can also run pants list :: to find all addresses in your project, or pants list dir to find all addresses defined in that directory.

If the target is in the same BUILD file, you can leave off the BUILD file path, e.g. :tgt instead of helloworld/subdir:tgt. For generated first-party addresses, use ./ for the file path, e.g. ./main.py:tgt; for all other generated targets, use :tgt#generated_name.

You may exclude dependencies by prefixing with !, e.g. ['!helloworld/subdir:lib', '!./sibling.txt']. Ignores are intended for false positives with dependency inference; otherwise, simply leave off the dependency from the BUILD file.

description

str | None
default: None

A human-readable description of the target.

Use pants list --documented :: to see all targets with descriptions.

environment

str | None
default: '__local__'

Specify which environment target to consume environment-sensitive options from.

Once environments are defined in [environments-preview].names, you can specify the environment for this target by its name. Any fields that are defined in that environment will override the values from options set by pants.toml, command line values, or environment variables.

You can specify multiple valid environments by using parametrize. If __local__ is specified, Pants will fall back to the local_environment defined for the current platform, or no environment if no such environment exists.

extra_env_vars

Iterable[str] | None
default: None

Additional environment variables to include in test processes.

Entries are strings in the form ENV_VAR=value to use explicitly; or just ENV_VAR to copy the value of a variable in Pants's own environment.

This will be merged with and override values from [test].extra_env_vars.

interpreter_constraints

Iterable[str] | None
default: None

The Python interpreters this code is compatible with.

Each element should be written in pip-style format, e.g. CPython==2.7.* or CPython>=3.6,<4. You can leave off CPython as a shorthand, e.g. >=2.7 will be expanded to CPython>=2.7.

Specify more than one element to OR the constraints, e.g. ['PyPy==3.7.*', 'CPython==3.7.*'] means either PyPy 3.7 or CPython 3.7.

If the field is not set, it will default to the option [python].interpreter_constraints.

See https://www.pantsbuild.org/2.22/docs/python/overview/interpreter-compatibility for how these interpreter constraints are merged with the constraints of dependencies.

overrides

Dict[Union[str, Tuple[str, ...]], Dict[str, Any]] | None
default: None

Override the field values for generated python_test targets.

Expects a dictionary of relative file paths and globs to a dictionary for the overrides. You may either use a string for a single path / glob, or a string tuple for multiple paths / globs. Each override is a dictionary of field names to the overridden value.

For example:

overrides={
"foo_test.py": {"timeout": 120},
"bar_test.py": {"timeout": 200},
("foo_test.py", "bar_test.py"): {"tags": ["slow_tests"]},
}

File paths and globs are relative to the BUILD file's directory. Every overridden file is validated to belong to this target's sources field.

If you'd like to override a field's value for every python_test target generated by this target, change the field directly on this target rather than using the overrides field.

You can specify the same file name in multiple keys, so long as you don't override the same field more than one time for the file.

resolve

str | None
default: None

The resolve from [python].resolves to use.

If not defined, will default to [python].default_resolve.

All dependencies must share the same value for their resolve field.

run_goal_use_sandbox

bool | None
default: None

Whether to use a sandbox when running this target. Defaults to [python].default_run_goal_use_sandbox.

If true, runs of this target with the run goal will copy the needed first-party sources into a temporary sandbox and run from there.

If false, runs of this target with the run goal will use the in-repo sources directly.

Note that this field only applies when running a target with the run goal. No other goals (such as test, if applicable) consult this field.

The former mode is more hermetic, and is closer to building and running the source as it were packaged in a pex_binary. Additionally, it may be necessary if your sources depend transitively on "generated" files which will be materialized in the sandbox in a source root, but are not in-repo.

The latter mode is similar to creating, activating, and using a virtual environment when running your files. It may also be necessary if the source being run writes files into the repo and computes their location relative to the executed files. Django's makemigrations command is an example of such a process.

runtime_package_dependencies

Iterable[str] | None
default: None

Addresses to targets that can be built with the pants package goal and whose resulting artifacts should be included in the test run.

Pants will build the artifacts as if you had run pants package. It will include the results in your test's chroot, using the same name they would normally have, but without the --distdir prefix (e.g. dist/).

You can include anything that can be built by pants package, e.g. a pex_binary, python_aws_lambda_function, or an archive.

skip_add_trailing_comma

bool
default: False
backend: pants.backend.experimental.python.lint.add_trailing_comma

If true, don't run add-trailing-comma on this target's code.

skip_autoflake

bool
default: False
backend: pants.backend.python.lint.autoflake

If true, don't run Autoflake on this target's code.

skip_bandit

bool
default: False
backend: pants.backend.python.lint.bandit

If true, don't run Bandit on this target's code.

skip_black

bool
default: False
backend: pants.backend.python.lint.black

If true, don't run Black on this target's code.

skip_docformatter

bool
default: False
backend: pants.backend.python.lint.docformatter

If true, don't run Docformatter on this target's code.

skip_flake8

bool
default: False
backend: pants.backend.python.lint.flake8

If true, don't run Flake8 on this target's code.

skip_isort

bool
default: False
backend: pants.backend.python.lint.isort

If true, don't run isort on this target's code.

skip_mypy

bool
default: False
backend: pants.backend.python.typecheck.mypy

If true, don't run MyPy on this target's code.

skip_pydocstyle

bool
default: False
backend: pants.backend.python.lint.pydocstyle

If true, don't run pydocstyle on this target's code.

skip_pylint

bool
default: False
backend: pants.backend.python.lint.pylint

If true, don't run Pylint on this target's code.

skip_pyright

bool
default: False
backend: pants.backend.experimental.python.typecheck.pyright

If true, don't run Pyright on this target's code.

skip_pytype

bool
default: False
backend: pants.backend.experimental.python.typecheck.pytype

If true, don't run pytype on this target's code.

skip_pyupgrade

bool
default: False
backend: pants.backend.python.lint.pyupgrade

If true, don't run pyupgrade on this target's code.

skip_ruff

bool
default: False
backend: pants.backend.experimental.python.lint.ruff

If True, do not run any Ruff tools on this target's code.

skip_ruff_check

bool
default: False
backend: pants.backend.experimental.python.lint.ruff

If true, don't run the ruff checker on this target's code.

skip_ruff_format

bool
default: False
backend: pants.backend.experimental.python.lint.ruff.format

If true, don't run the ruff formatter on this target's code.

skip_tests

bool
default: False

If true, don't run this target's tests.

skip_yapf

bool
default: False
backend: pants.backend.python.lint.yapf

If true, don't run yapf on this target's code.

sources

Iterable[str] | None
default: ('test_*.py', '*_test.py', 'tests.py')

A list of files and globs that belong to this target.

Paths are relative to the BUILD file's directory. You can ignore files/globs by prefixing them with !.

Example: sources=['test_*.py', '*_test.py', 'tests.py']

stevedore_namespaces

Iterable[str] | None
default: None
backend: pants.backend.experimental.python.framework.stevedore

List the stevedore namespaces required by this target.

Code for all entry_points on python_distribution targets with these namespaces will be added as dependencies so that they are available on PYTHONPATH during tests. Note that this is only a subset of the python_distributions dependencies, so the entry_points only need to be defined on one python_distribution even if the test only needs some of the entry_points namespaces on it.

Plus, an entry_points.txt file will be generated in the sandbox so that each of the python_distributions appear to be "installed". The entry_points.txt file will only include the namespaces requested on this field. Without this, stevedore would not be able to look up plugins in the setuptools entry_points metadata.

NOTE: Each python_distribution must opt-in to being included in this repo-wide inference by tagging the namespaces with stevedore_namespace("my.stevedore.extension").

The stevedore namespace format (my.stevedore.extension) is similar to a Python namespace.

tags

Iterable[str] | None
default: None

Arbitrary strings to describe a target.

For example, you may tag some test targets with 'integration_test' so that you could run pants --tag='integration_test' test :: to only run on targets with that tag.

timeout

int | None
default: None

A timeout (in seconds) used by each test file belonging to this target.

If unset, will default to [test].timeout_default; if that option is also unset, then the test will never time out. Will never exceed [test].timeout_maximum. Only applies if the option --test-timeouts is set to true (the default).

xdist_concurrency

int | None
default: None

Maximum number of CPUs to allocate to run each test file belonging to this target.

Tests are spread across multiple CPUs using pytest-xdist (https://pytest-xdist.readthedocs.io/en/latest/index.html). Use of pytest-xdist must be enabled using the [pytest].xdist_enabled option for this field to have an effect.

If pytest-xdist is enabled and this field is unset, Pants will attempt to derive the concurrency for test sources by counting the number of tests in each file.

Set this field to 0 to explicitly disable use of pytest-xdist for a target.