Plugin API reference

tox objects

register

Manages the tox environment registry.

class tox.tox_env.register.ToxEnvRegister

Bases: object

tox environment registry.

property env_runners

The run environment types currently defined.

property default_env_runner

The default run environment type.

add_run_env(of_type)

Define a new run tox environment type.

Parameters:

of_type (type[RunToxEnv]) – the new run environment type

Return type:

None

add_package_env(of_type)

Define a new packaging tox environment type.

Parameters:

of_type (type[PackageToxEnv]) – the new packaging environment type

Return type:

None

runner(name)

Lookup a run tox environment type by name.

Parameters:

name (str) – the name of the runner type

Return type:

type[RunToxEnv]

Returns:

the type of the runner type

package(name)

Lookup a packaging tox environment type by name.

Parameters:

name (str) – the name of the packaging type

Return type:

type[PackageToxEnv]

Returns:

the type of the packaging type

tox.tox_env.register.REGISTER

the tox register

config

class tox.config.cli.parser.ArgumentParserWithEnvAndConfig(*args, **kwargs)

Bases: ArgumentParser

Argument parser which updates its defaults by checking the configuration files and environmental variables.

Parameters:
Variables:

file_config – the configuration the defaults are read from

fix_defaults()

Apply the environment variable and config file defaults to all arguments, sub-parsers included.

Return type:

None

fix_default(action)

Set the default of an argument from its environment variable or config file value, when one is set.

Parameters:

action (Action) – the argument to update

Raises:

RuntimeError – when a sub-parser was added without using the tox parser

Return type:

None

static get_type(action)

Get the type the values of an argument are converted to.

Parameters:

action (Action) – the argument

Return type:

type | Union

Returns:

the type of the argument values, a list type for arguments that accept many values

Raises:

TypeError – when the type of the argument cannot be determined

parse_args(args=None, namespace=None)
Overloads:
Overrides:

ArgumentParser.parse_args

class tox.config.cli.parser.ToxParser(*args, root=False, add_cmd=False, **kwargs)

Bases: ArgumentParserWithEnvAndConfig

Argument parser for tox.

Parameters:
Variables:
  • of_cmd (str | None) – the command this parser was added for, None for the top-level parser

  • inherit (frozenset[str]) – the option groups, core and env, this parser takes from its parent

  • handlers (dict[str, tuple[ToxParser, Callable[[State], int]]]) – the command and alias names mapped to their sub-parser and handler

classmethod base()

Create a root parser without the help option.

Return type:

Self

Returns:

the root parser

classmethod core()

Create the root parser of the tox command, which accepts sub-commands.

Return type:

Self

Returns:

the root parser

add_command(cmd, aliases, help_msg, handler, *, inherit=frozenset({'core', 'env'}))

Register a sub-command with its own parser and handler.

Parameters:
  • cmd (str) – the name of the sub-command

  • aliases (Sequence[str]) – other names the sub-command can be invoked with

  • help_msg (str) – the help text of the sub-command

  • handler (Callable[[State], int]) – the function that runs the sub-command

  • inherit (frozenset[str]) – the option groups the sub-command inherits from the root parser

Return type:

ArgumentParser

Returns:

the parser of the sub-command

Raises:

RuntimeError – when this parser does not accept sub-commands

add_argument_group(*args, **kwargs)
Return type:

_ArgumentGroup

Overrides:

ArgumentParser.add_argument_group

add_argument(*args, of_type=None, **kwargs)
add_argument(option_string, option_string, ..., name=value, ...)
Return type:

Action

Overrides:

ArgumentParser.add_argument

parse_known_args(args=None, namespace=None)
Overloads:
Overrides:

ArgumentParser.parse_known_args

class tox.config.cli.parser.Parsed(**kwargs)

Bases: Namespace

CLI options.

The annotations below declare the type each option has once its command registered it; an option belonging to another command is absent at runtime, so shared code paths read it via getattr with a fallback.

verbose

the number of -v flags passed

quiet

the number of -q flags passed

colored

yes when the output is colored, no otherwise

stderr_color

the color used for stderr output

exit_and_dump_after

seconds after which tox dumps its threads and exits, 0 disables it

config_file

the configuration file or folder passed with -c, if any

work_dir

the tox working directory, if one was given

root_dir

the project root directory, if one was given

override

the configuration overrides passed with --override

command

the name of the sub-command to run

remainder

the arguments passed after --

env

the environments selected with -e

labels

the environment labels selected with -m

factors

the environment factors selected with -f

skip_env

the regular expression of environments to exclude

default_runner

the tox run engine used when an environment does not name one

result_json

the file the JSON result report is written to, if any

no_capture

whether output capture is disabled

hash_seed

the value of PYTHONHASHSEED for the commands, None when it is not set

discover

the Python executables to try first during discovery

list_dependencies

whether the dependencies installed during environment setup are listed

recreate

whether environments are recreated before use

no_test

whether the test commands are skipped

package_only

whether only the package is built

install_pkg

the package to install instead of building the project, if any

fail_fast

whether execution stops after the first environment failure

develop

whether the package is installed in development mode

no_recreate_pkg

whether packaging environments are kept when recreate is set

skip_pkg_install

whether the package installation is skipped

skip_env_install

whether dependency and package installation is skipped

skip_missing_interpreters

whether missing interpreters are skipped, config defers to the configuration

parallel

the number of environments run in parallel

parallel_live

whether the output of parallel environments is shown live

parallel_no_spinner

whether the spinner is disabled in parallel mode

no_provision

whether provisioning is skipped and fails instead, or the path its metadata is written to

no_recreate_provision

whether the provisioning environment is kept when recreate is set

devenv_path

the directory of the development environment

force_dep

the dependency requirements forced into the environments

site_packages

whether the environments can see the system site packages

always_copy

whether the environments copy files instead of linking them

pre

whether pre-release versions are installed

property verbosity

The reporting verbosity: the -v count minus the -q count, never below zero.

property is_colored

True when the output is colored.

class tox.config.cli.parse.Options(parsed, pos_args, source, cmd_handlers, log_handler)

Bases: NamedTuple

The parsed command line options together with the state needed to run tox.

Parameters:
  • parsed (Parsed) – the parsed command line options

  • pos_args (Sequence[str] | None) – the positional arguments passed after --

  • source (Source) – the source the configuration is read from

  • cmd_handlers (dict[str, Callable[[State], int]]) – the handlers of the sub-commands, keyed by command name

  • log_handler (ToxHandler) – the handler that reports the log output

class tox.config.main.Config(config_source, options, root, pos_args, work_dir, extra_envs)

Bases: object

Main configuration object for tox.

Parameters:
  • config_source (Source) – the source the configuration is read from

  • options (Parsed) – the parsed command line options

  • root (Path) – the project root directory, where the configuration file is

  • pos_args (Sequence[str] | None) – the positional arguments passed after --

  • work_dir (Path) – the directory where tox keeps its own files

  • extra_envs (Iterable[str]) – the environments to add to the configured ones

Variables:

memory_seed_loaders (defaultdict[str, list[MemoryLoader]]) – the in-memory loaders that seed the environments by name

reject_package_discovery()

Stop discovery when a setting cannot resolve yet.

Raises:

HandledError – if package discovery is active

Return type:

None

property in_package_discovery

Whether the current lookup is choosing a package mode.

property core

The core configuration, loaded on first access.

property src_path

The location of the tox configuration source.

property work_dir

The working directory for this project.

property options

The parsed command line options.

property overrides

The configuration overrides keyed by their target namespace.

package_discovery()

Resolve core settings without caching values or defining environments.

Yields:

None – control while discovery mode is active

pos_args(to_path, *, program_first=False)

Get the positional arguments passed after --, with path arguments made relative to a directory.

Parameters:
  • to_path (Path | None) – the directory the path arguments are made relative to, None to keep them as they are

  • program_first (bool) – whether the program comes before the positional arguments

Return type:

tuple[str, ...] | None

Returns:

the positional arguments, or None when none were passed

sections()

Iterate over the sections of the configuration source.

Yields:

Section – the sections, in the order the source defines them

factor_labels(env_name)

Get the factor labels defined for an environment.

Parameters:

env_name (str | None) – the environment name, None for the core configuration

Return type:

dict[str, FactorGroup]

Returns:

the factor labels, empty when the source does not define factor labels

get_env(item, package=False, loaders=None)

Return the configuration for a given tox environment (will create if not exist yet).

Parameters:
  • item (str) – the name of the environment is

  • package (bool) – a flag indicating if the environment is of type packaging or not (only used for creation)

  • loaders (Sequence[Loader[Any]] | None) – loaders to use for this configuration (only used for creation)

Return type:

EnvConfigSet

Returns:

the tox environments config

get_section_config(section, base, of_type, for_env, loaders=None)

Get the configuration set of a section, creating and caching it on first use.

Parameters:
  • section (Section) – the section to load

  • base (list[str] | None) – the base sections the configuration inherits from

  • of_type (type[T]) – the configuration set type to create

  • for_env (str | None) – the environment name, None for the core configuration

  • loaders (Sequence[Loader[Any]] | None) – extra loaders to read values from, appended after the source loaders

Return type:

T

Returns:

the configuration set of the section

clear_env(name)

Forget the configuration loaded for an environment, so it is loaded again when next used.

Parameters:

name (str) – the name of the environment

Return type:

None

class tox.config.loader.section.Section(prefix, name)

Bases: object

tox configuration section.

Parameters:
  • prefix (str | None) – the prefix that groups the keys of the section

  • name (str) – the name of the section

SEP = ':'

string used to separate the prefix and the section in the key

classmethod from_key(key)

Create a section from a section key.

Parameters:

key (str) – the section key

Return type:

Self

Returns:

the constructed section

property key

The section key: the prefix and the name joined by the separator, the prefix left out when unset.

property prefix

The prefix of the section, None when it has none.

property name

The name of the section.

class tox.config.loader.api.ConfigLoadArgs(chain, name, env_name)

Bases: object

Arguments that help loading a configuration value.

copy()
Return type:

ConfigLoadArgs

Returns:

create a copy of the object

class tox.config.sets.ConfigSet(conf, section, env_name)

Bases: ABC

A set of configuration that belong together (such as a tox environment settings, core tox settings).

Parameters:
  • conf (Config) – the global tox configuration

  • section (Section) – the section that holds the raw values of this set

  • env_name (str | None) – the tox environment name, or None for the core set

loaders

active configuration loaders, can alter to change configuration values

abstractmethod register_config()

Register the configuration keys this set provides.

Return type:

None

load(item, chain=None)

Get the config value for a given key (will materialize in case of dynamic config).

Parameters:
  • item (str) – the config key

  • chain (list[str] | None) – a chain of configuration keys already loaded for this load operation (used to detect circles)

Return type:

Any

Returns:

the configuration value

property name

The name of the section this set reads its configuration from.

property env_name

The name of the environment this set belongs to, None for the core configuration.

__iter__()
Return type:

Iterator[str]

Returns:

iterate through the defined config keys (primary keys used)

__contains__(item)

Check if a configuration key is within the config set.

Parameters:

item (str) – the configuration value

Return type:

bool

Returns:

a boolean indicating the truthiness of the statement

get_configs()

Iterate over the config definitions, one per config.

Yields:

ConfigDefinition[Any] – the definition of each config, keyed by its first key

mark_finalized()

Mark the set as final, after which no further configuration can be added.

Return type:

None

add_config(keys, of_type, default, desc, post_process=None, factory=None)

Add configuration value.

Overloads:
Parameters:
  • keys (str | Sequence[str]) – the keys under what to register the config (first is primary key)

  • of_type (type[V] | Union) – the type of the config value

  • default (Callable[[Config, str | None], V] | V | None) – the default value of the config value

  • desc (str) – a help message describing the configuration

  • post_process (Callable[[V], V] | None) – a callback to post-process the configuration value after it has been loaded

  • factory (Callable[[object], Any] | None) – factory method used to build contained objects (if of_type is a container type it should perform the contained item creation, otherwise creates objects that match the type)

Returns:

the new dynamic config definition

Raises:

RuntimeError – when the set has been marked final

add_constant(keys, desc, value)

Add a constant value.

Parameters:
  • keys (str | Sequence[str]) – the keys under what to register the config (first is primary key)

  • desc (str) – a help message describing the configuration

  • value (V) – the config value to use

Return type:

ConfigConstantDefinition[V]

Returns:

the new constant config value

Raises:

RuntimeError – when the set has been marked final

is_constant(item)

Check whether a configuration key is a constant.

Parameters:

item (str) – the configuration key

Return type:

bool

Returns:

whether the key holds a constant value

get(item, of_type)

Get the config value for a given key, verified to be of the declared type.

Unlike load() and [] — which return Any — the value is checked against of_type at runtime (container types by their unsubscripted origin, so list[str] checks list) and returned as that type.

Added in version 4.59.

Parameters:
  • item (str) – the config key

  • of_type (type[V]) – the type the config value was registered with

Return type:

V

Returns:

the configuration value

Raises:

TypeError – when the value is not of the requested type

get_optional(item, of_type)

Get the config value for a key that may be unset, verified to be of the declared type or None.

Use this over get() for keys registered with a None default, such as min_version.

Added in version 4.62.

Parameters:
  • item (str) – the config key

  • of_type (type[V]) – the type the config value was registered with

Return type:

V | None

Returns:

the configuration value, or None when unset

Raises:

TypeError – when the value is neither of the requested type nor None

unused()
Return type:

list[str]

Returns:

Return a list of keys present in the config source but not used

primary_key(key)

Get the primary key for a config key.

Parameters:

key (str) – the config key

Return type:

str

Returns:

the key that’s considered the primary for the input key

class tox.config.sets.CoreConfigSet(conf, section, root, src_path)

Bases: ConfigSet

Configuration set for the core tox config.

Parameters:
  • conf (Config) – the global tox configuration

  • section (Section) – the core section of the configuration

  • root (Path) – the directory of the project root

  • src_path (Path) – the path to the configuration file

register_config()

Register the configuration keys this set provides.

Return type:

None

Overrides:

ConfigSet.register_config

package_root_for_discovery()

Resolve the package root without populating live configuration caches.

Return type:

Path | None

Returns:

the package root, or None if it cannot resolve before environment setup

class tox.config.sets.EnvConfigSet(conf, section, env_name)

Bases: ConfigSet

Configuration set for a tox environment.

Parameters:
  • conf (Config) – the global tox configuration

  • section (Section) – the section that holds the environment settings

  • env_name (str) – the name of the tox environment

Variables:
default_set_env_loader
exported_set_env_loader
register_config()

Register the configuration keys this set provides.

Return type:

None

Overrides:

ConfigSet.register_config

set_env_lines(chain)

Get the set_env setting as lines, loading it first.

Parameters:

chain (list[str]) – the chain of configuration keys the load belongs to

Return type:

str

Returns:

the environment variables as KEY=VALUE lines

class tox.config.of_type.ConfigDefinition[T](keys, desc)

Bases: ABC, Generic[T]

Abstract base class for configuration definitions.

Parameters:
  • keys (Iterable[str]) – the configuration keys, the first one is the name, the others are aliases

  • desc (str) – the help text describing the configuration

abstractmethod overwrite(value)

Force the configuration to the given value, replacing any constant or already loaded one.

Parameters:

value (T) – the new value

Return type:

None

class tox.config.of_type.ConfigDynamicDefinition[T](keys, desc, of_type, default, post_process=None, factory=None)

Bases: ConfigDefinition[T]

A configuration definition that comes from a source (such as in memory, an ini file, a toml file, etc.).

Parameters:
  • keys (Iterable[str]) – the configuration keys, the first one is the name, the others are aliases

  • desc (str) – the help text describing the configuration

  • of_type (type[T] | Union) – the type the loaded value is converted to

  • default (Callable[[Config, str | None], T] | T | None) – the value, or a callable computing it, used when the configuration is not set

  • post_process (Callable[[T], T] | None) – a callable applied to the converted value

  • factory (Callable[[object], T] | None) – the callable that builds the objects of the type, for container and custom types

overwrite(value)

Force the configuration to the given value, replacing any constant or already loaded one.

Parameters:

value (T) – the new value

Return type:

None

Overrides:

ConfigDefinition.overwrite

class tox.config.of_type.ConfigConstantDefinition[T](keys, desc, value)

Bases: ConfigDefinition[T]

A configuration definition whose value is defined upfront (such as the tox environment name).

Parameters:
  • keys (Iterable[str]) – the configuration keys, the first one is the name, the others are aliases

  • desc (str) – the help text describing the configuration

  • value (Callable[[], T] | T) – the value the configuration is fixed to

overwrite(value)

Force the configuration to the given value, replacing any constant or already loaded one.

Parameters:

value (T) – the new value

Return type:

None

Overrides:

ConfigDefinition.overwrite

class tox.config.source.api.Source(path)

Bases: ABC

Source is able to return a configuration value (for either the core or per environment source).

Parameters:

path (Path) – the path of the configuration file

Variables:

FILENAME – the name of the configuration file

FILENAME = ''
path

the path to the configuration source

get_loaders(section, base, override_map, conf)

Return a loader that loads settings from a given section name.

Parameters:
Yields:

Loader[Any] – the loaders to use

abstractmethod transform_section(section)

Transform a section before it is used, for example to add a prefix.

Parameters:

section (Section) – the section to transform

Return type:

Section

Returns:

the transformed section

abstractmethod get_loader(section, override_map)

Get the loader that reads the values of a section.

Parameters:
Return type:

Loader[Any] | None

Returns:

the loader, or None when the source has no values for the section

abstractmethod get_base_sections(base, in_section)

Get the base sections a section inherits from.

Parameters:
  • base (list[str]) – the names of the base sections

  • in_section (Section) – the section that inherits from them

Return type:

Iterator[Section]

Returns:

the base sections

abstractmethod sections()

Return a loader that loads the core configuration values.

Return type:

Iterator[Section]

Returns:

the core loader from this source

abstractmethod envs(core_conf)
Parameters:

core_conf (CoreConfigSet) – the core configuration set

Return type:

Iterator[str]

Returns:

a list of environments defined within this source

abstractmethod get_tox_env_section(item)

Get the section of a tox environment.

Parameters:

item (str) – the name of the tox environment

Return type:

tuple[Section, list[str], list[str]]

Returns:

the section, followed by the base sections for test and for package environments

abstractmethod get_core_section()
Return type:

Section

Returns:

the core section

class tox.config.source.api.FactorLabelSource(*args, **kwargs)

Bases: Protocol

A configuration source that defines factor labels for each environment.

factor_labels(env_name)

Get the factor labels defined for an environment.

Parameters:

env_name (str | None) – the environment name, None for the core configuration

Return type:

dict[str, FactorGroup]

Returns:

the factor labels

class tox.config.loader.api.Override(value)

Bases: object

An override for config definitions.

Parameters:

value (str) – the [namespace.]key[+]=value text of the override

Variables:
  • append – whether the value is appended to a list instead of replacing it

  • namespace – the dotted section path the key belongs to

  • key – the name of the configuration key the override applies to

final class tox.config.set_env.SetEnvReference(config, args, shape)

Bases: object

Keep overrides pending until the consuming environment has registered its keys.

Parameters:
  • config (SetEnv) – the set_env the value is written to

  • args (ConfigLoadArgs) – the load arguments the value is resolved with

  • shape (Literal['string', 'table', 'array']) – the form the value was written in, a string, a table or an array

class tox.config.set_env.SetEnvEntry

Bases: TypedDict

A single set_env value in structured (TOML) form.

Variables:
  • value (str | MatchExpression) – the value, a string or a replace table, the marker applies to

  • marker (NotRequired[str]) – the environment marker that decides whether the value applies

class tox.config.set_env.SetEnv(raw, name, env_name, root, *, substituted=False)

Bases: object

The environment variables of a tox environment, as set by its set_env setting.

Parameters:
Variables:
  • changed – whether a variable was set or removed after the setting was loaded

  • shape (Final[Literal['string', 'table', 'array']]) – the form the setting was written in, a string, a table or an array

use_replacer(value, args)

Use a replacer to expand the values of the environment variables.

Parameters:
Return type:

None

load(item, args=None)

Get the value of an environment variable.

Parameters:
  • item (str) – the name of the environment variable

  • args (ConfigLoadArgs | None) – the args of the configuration load, a new set is created when None

Return type:

str

Returns:

the value of the environment variable

lines()

Get the environment variables as KEY=VALUE lines, in the form they are written in the configuration.

Return type:

str

Returns:

the lines, separated by newlines

raw(args, *, resolve=True)

Preserve lazy values and markers when another section includes this configuration.

Parameters:
  • args (ConfigLoadArgs) – the load arguments the values are resolved with

  • resolve (bool) – whether pending replacements are resolved first

Return type:

dict[str, SetEnvEntry]

Returns:

the entries keyed by name, each holding its value and optional marker

export(values)

Set tox’s own variables over the configured ones, resolved on first read.

They come from settings that may read set_env through {env:...}, so reading them here would recurse.

Parameters:

values (Mapping[str, Callable[[], str]]) – the tox variables to export, each mapped to a callable producing its value

Return type:

None

extend(other)

Appended blocks override base keys; explicit keys in the same override win.

Parameters:

other (SetEnv) – the configuration whose blocks are appended to this one

Return type:

None

update(param, *, override=True)

Set environment variables from a mapping.

Parameters:
  • param (Mapping[str, str] | SetEnv) – the variables to set, another set env is read through its loader

  • override (bool) – whether to replace the variables that are already set explicitly

Return type:

None

class tox.config.set_env.Replacer(*args, **kwargs)

Bases: Protocol

Expand the replacements in the value of an environment variable.

class tox.config.loader.replacer.MatchExpression(expr, term_pos=None, *, host=False, literal=False)

Bases: object

An expression that is handled specially by the Replacer.

Parameters:
  • expr (Sequence[Sequence[str | MatchExpression]]) – the parsed parts of the expression

  • term_pos (int | None) – the position in the source text where the expression ends

  • host (bool) – whether the expression comes from a host variable

  • literal (bool) – whether the expression is kept as written

classmethod parse_and_split_to_terminator(value, terminator='', split=None)

Tokenize value to up terminator character.

If split is given, multiple arguments will be returned.

Returns list of arguments (list of str or MatchExpression) and final character position examined in value.

This function recursively calls itself via _next_replace_expression.

Parameters:
  • value (str) – the text to tokenize

  • terminator (str) – the character that ends the tokenized text

  • split (str | None) – the character that separates multiple arguments

Return type:

tuple[Sequence[Sequence[str | MatchExpression]], int]

Returns:

the parsed arguments and the position where tokenizing stopped

Raises:

MatchError – when the text does not form a valid expression

class tox.config.loader.replacer.MatchError

Bases: Exception

Couldn’t find end terminator in MatchExpression.

class tox.config.loader.api.Loader[T](section, overrides)

Bases: Convert[T]

Loader loads configuration values and converts it.

Parameters:
  • section (Section) – the section the values are read from

  • overrides (list[Override]) – A list of overrides to be applied.

Variables:

parent (Loader[Any] | None) – the loader this one was derived from, if any

abstractmethod found_keys()

A list of configuration keys found within the configuration.

Return type:

set[str]

Returns:

the keys found within the configuration

property section

Return the section of the configuration from where the values are extracted.

load(key, of_type, factory, conf, args, all_keys=())

Load a value (raw and then convert).

Parameters:
  • key (str) – the key under it lives

  • of_type (type[V] | Union) – the type to convert to

  • factory (Callable[[object], V] | None) – factory method to build the object

  • conf (Config | None) – the configuration object of this tox session (needed to manifest the value)

  • args (ConfigLoadArgs) – the config load arguments

  • all_keys (Iterable[str]) – all alias keys for this config entry (to collect overrides from any alias)

Return type:

V

Returns:

the converted type

Raises:
  • KeyError – when the key is not present in any source, or, as AppendOverridesError, when the source does not set the key but has only key+=value overrides for it

  • ValueError – when the value cannot be converted to the requested type

abstractmethod load_raw(key, conf, env_name)

Load the raw object from the config store.

Parameters:
  • key (str) – the key under what we want the configuration

  • conf (Config | None) – the global config object

  • env_name (str | None) – load for env name

Return type:

T

Returns:

the raw value of the key, before conversion

build(key, of_type, factory, conf, raw, args)

Materialize the raw configuration value from the loader.

Parameters:
  • key (str) – the config key

  • of_type (type[V] | Union) – the config type

  • factory (Callable[[object], V] | None) – factory method to build the object

  • conf (Config | None) – the global config

  • raw (T) – the value as read from the store, before conversion to of_type

  • args (ConfigLoadArgs) – env args

Return type:

V

Returns:

the object built from the raw value

substitute(value, conf, args, *, of_type)

Apply this loader’s replacements to a raw string.

Parameters:
  • value (str) – the raw string

  • conf (Config) – the global config

  • args (ConfigLoadArgs) – env args

  • of_type (type[V] | Union) – the setting type used to select its substitution rules

Return type:

str

Returns:

the string with every substitution this loader understands resolved

set_env_reference(raw, overrides, conf, args)

Wrap a raw value in a reference that loads it as a set_env value.

Parameters:
  • raw (T) – the value as written in the configuration, set_env table or string

  • overrides (list[Override]) – the overrides to apply

  • conf (Config) – the global config

  • args (ConfigLoadArgs) – env args

Return type:

SetEnvReference

Returns:

the set env reference

Raises:

ValueError – when the reference is circular

class tox.config.loader.memory.MemoryLoader(**kwargs)

Bases: Loader[object]

Loads configuration directly from data in memory.

Parameters:

kwargs (Any) – the configuration values, keyed by name

Variables:

raw (dict[str, Any]) – the configuration values as set in memory

load_raw(key, conf, env_name)

Load the raw object from the config store.

Parameters:
  • key (str) – the key under what we want the configuration

  • conf (Config | None) – the global config object

  • env_name (str | None) – load for env name

Return type:

object

Returns:

the raw value of the key, before conversion

Overrides:

Loader.load_raw

found_keys()

A list of configuration keys found within the configuration.

Return type:

set[str]

Returns:

the keys found within the configuration

Overrides:

Loader.found_keys

static to_bool(value)

Convert to boolean.

Parameters:

value (Any) – the value to convert

Return type:

bool

Returns:

a boolean representation of the value

Overrides:

Convert.to_bool

static to_str(value)

Convert to string.

Parameters:

value (Any) – the value to convert

Return type:

str

Returns:

a string representation of the value

Overrides:

Convert.to_str

static to_list(value, of_type)

Convert to list.

Parameters:
  • value (Any) – the value to convert

  • of_type (type[Any]) – the type of elements in the list

Return type:

Iterator[Any]

Returns:

a list representation of the value

Overrides:

Convert.to_list

static to_set(value, of_type)

Convert to set.

Parameters:
  • value (Any) – the value to convert

  • of_type (type[Any]) – the type of elements in the set

Return type:

Iterator[Any]

Returns:

a set representation of the value

Overrides:

Convert.to_set

static to_dict(value, of_type)

Convert to dictionary.

Parameters:
  • value (Any) – the value to convert

  • of_type (tuple[type[Any], type[Any]]) – a tuple indicating the type of the key and the value

Return type:

Iterator[tuple[Any, Any]]

Returns:

a iteration of key-value pairs that gets populated into a dict

Overrides:

Convert.to_dict

static to_path(value)

Convert to path.

Parameters:

value (Any) – the value to convert

Return type:

Path

Returns:

path representation of the value

Overrides:

Convert.to_path

static to_command(value)

Convert to a command to execute.

Parameters:

value (Any) – the value to convert

Return type:

Command

Returns:

command representation of the value

Overrides:

Convert.to_command

static to_env_list(value)

Convert to a tox EnvList.

Parameters:

value (Any) – the value to convert

Return type:

EnvList

Returns:

a list of tox environments from the value

Overrides:

Convert.to_env_list

class tox.config.loader.convert.Convert[T]

Bases: ABC, Generic[T]

A class that converts a raw type to a given tox (python) type.

to(raw, of_type, factory)

Convert given raw type to python type.

Parameters:
  • raw (T) – the raw type

  • of_type (type[V] | Union) – python type

  • factory (Callable[[object], V] | None) – factory method to build the object

Return type:

V

Returns:

the converted type

abstractmethod static to_list(value, of_type)

Convert to list.

Parameters:
  • value (T) – the value to convert

  • of_type (type) – the type of elements in the list

Return type:

Iterator[T]

Returns:

a list representation of the value

abstractmethod static to_set(value, of_type)

Convert to set.

Parameters:
  • value (T) – the value to convert

  • of_type (type) – the type of elements in the set

Return type:

Iterator[T]

Returns:

a set representation of the value

abstractmethod static to_dict(value, of_type)

Convert to dictionary.

Parameters:
  • value (T) – the value to convert

  • of_type (tuple[type, type]) – a tuple indicating the type of the key and the value

Return type:

Iterator[tuple[T, T]]

Returns:

a iteration of key-value pairs that gets populated into a dict

abstractmethod static to_path(value)

Convert to path.

Parameters:

value (T) – the value to convert

Return type:

Path

Returns:

path representation of the value

abstractmethod static to_bool(value)

Convert to boolean.

Parameters:

value (T) – the value to convert

Return type:

bool

Returns:

a boolean representation of the value

abstractmethod static to_command(value)

Convert to a command to execute.

Parameters:

value (T) – the value to convert

Return type:

Command

Returns:

command representation of the value

abstractmethod static to_env_list(value)

Convert to a tox EnvList.

Parameters:

value (T) – the value to convert

Return type:

EnvList

Returns:

a list of tox environments from the value

abstractmethod static to_str(value)

Convert to string.

Parameters:

value (T) – the value to convert

Return type:

str

Returns:

a string representation of the value

class tox.config.types.EnvList(envs)

Bases: object

A tox environment list.

__iter__()
Return type:

Iterator[str]

Returns:

iterator that goes through the defined env-list

class tox.config.types.Command(args)

Bases: object

A command to execute.

ignore_exit_code

a flag indicating if the exit code should be ignored

invert_exit_code

a flag for flipped exit code (non-zero = success, 0 = error)

args

the command line arguments

property raw_args

The arguments with the exit code prefix, - to ignore the exit code or ! to invert it.

property shell

A shell representation of the command, platform dependent.

class tox.config.types.FactorGroup(*, values, default=None, env_values=dict())

Bases: object

default stands in wherever an environment name carries none of values.

Parameters:
  • values (list[str]) – the factor values of the group

  • default (str | None) – the value used when no factor is active

  • env_values (dict[str, str]) – the value the group takes in each environment its matrix generated

values
default
env_values
tox.config.loader.convert.Factory

Callable that converts a raw value to the target type, or None when no conversion is needed.

environments

class tox.tox_env.api.ToxEnv(create_args)

Bases: ABC

A tox environment.

journal

handler to the tox reporting system

conf

the config set to use for this environment

core

the core tox config set

options

CLI options

log_handler

handler to the tox reporting system

abstractmethod static id()

The identifier of the tox environment type, used to select it in the configuration.

Return type:

str

Returns:

the identifier

abstract property installer

The installer that installs the packages of the environment.

register_config()

Register the configuration keys every tox environment has, such as its name and labels.

Return type:

None

property name

The name of the tox environment, such as py313.

abstract property executor

The executor that runs the commands of the environment.

setup()

Setup the tox environment.

Return type:

None

abstract property runs_on_platform

The platform the environment runs on, such as unix or win32.

property env_dir

The environment folder of the tox environment.

property cache

The cache of the environment, which stores the state of its last setup.

property env_tmp_dir

The temp folder of the tox environment.

property env_log_dir

The log folder of the tox environment.

teardown()

Tear the environment down, once, and notify the plugins that it is torn down.

Return type:

None

execute(cmd, stdin, show=None, cwd=None, run_id='', executor=None, *, capture=False)

Execute a command and wait for its outcome.

Parameters:
  • cmd (Sequence[Path | str]) – executable and arguments

  • stdin (StdinSource) – permitted standard input source

  • show (bool | None) – whether to display output, or None to follow verbosity

  • cwd (Path | None) – working directory, or None for the project root

  • run_id (str) – label for command logs

  • executor (Execute | None) – executor override, or None for this environment’s executor

  • capture (bool) – capture output even in no-capture mode

Return type:

Outcome

Returns:

completed command outcome

Raises:
execute_async(cmd, stdin, show=None, cwd=None, run_id='', executor=None, *, capture=False)

Run a command while exposing its execution status.

Parameters:
  • cmd (Sequence[Path | str]) – executable and arguments

  • stdin (StdinSource) – permitted standard input source

  • show (bool | None) – whether to display output, or None to follow verbosity

  • cwd (Path | None) – working directory, or None for the project root

  • run_id (str) – label for command logs

  • executor (Execute | None) – executor override, or None for this environment’s executor

  • capture (bool) – capture output even in no-capture mode

Raises:
Yields:

ExecuteStatus – context manager yielding the command’s execution status

property environment_variables

The environment variables the commands of the environment run with.

interrupt()

Interrupt the execution of a tox environment.

Return type:

None

allow_post_commands_after_interrupt(enabled)

Context manager to allow commands_post execution after interrupt when enabled.

Parameters:

enabled (bool) – whether commands_post may run after an interrupt

Yields:

None – nothing, commands_post runs inside the block

display_context(suspend)

Context manager that suspends the display of the environment output, when asked to.

Parameters:

suspend (bool) – whether to suspend the display

Yields:

None, the block runs with the display in the requested state

close_and_read_out_err()

Close the suspended output and read what it captured.

Return type:

tuple[bytes, bytes] | None

Returns:

the captured standard output and standard error, or None when nothing was suspended

class tox.tox_env.api.ToxEnvCreateArgs(conf, core, options, journal, log_handler)

Bases: NamedTuple

Arguments to pass on when creating a tox environment.

Parameters:
  • conf (EnvConfigSet) – the configuration of the environment

  • core (CoreConfigSet) – the core configuration of tox

  • options (Parsed) – the parsed command line options

  • journal (EnvJournal) – the journal the environment records its results in

  • log_handler (ToxHandler) – the handler that reports the output of the environment

class tox.tox_env.runner.RunToxEnv(create_args)

Bases: ToxEnv, ABC

The base of the tox environments that run commands.

Parameters:

create_args (ToxEnvCreateArgs) – the arguments the environment is created with

Variables:

package_env (PackageToxEnv | None) – the packaging environment the run environment uses, None when it uses none

property environment_variables

The environment variables the commands of the environment run with.

Overrides:

ToxEnv.environment_variables

register_config()

Register the configuration keys every tox environment has, such as its name and labels.

Return type:

None

Overrides:

ToxEnv.register_config

property package_envs

The packaging environments the run environment uses, followed by the ones they depend on.

interrupt()

Interrupt the execution of a tox environment.

Return type:

None

Overrides:

ToxEnv.interrupt

get_package_env_types()

Get the packaging environment types the run environment uses.

Return type:

tuple[str, str] | None

Returns:

the names of the packaging environment type and its name, or None when there is none

mark_active()

Mark the run environment as active in its packaging environments.

Return type:

None

class tox.tox_env.package.PackageToxEnv(create_args)

Bases: ToxEnv, ABC

The base of the tox environments that build a package to install into the run environments.

Parameters:

create_args (ToxEnvCreateArgs) – the arguments the environment is created with

register_config()

Register the configuration keys every tox environment has, such as its name and labels.

Return type:

None

Overrides:

ToxEnv.register_config

abstractmethod perform_packaging(for_env)

Build the packages of the environment.

Parameters:

for_env (EnvConfigSet) – the configuration of the run environment the packages are for

Return type:

list[Package]

Returns:

the packages that were built

register_run_env(run_env)

Register a run environment that uses the packages of this environment.

Parameters:

run_env (RunToxEnv) – the run environment

Yields:

tuple[str, str] – the package types and the names of the run environment settings the packages are read from

mark_active_run_env(run_env)

Mark a run environment as active, so the packages are kept until it is torn down.

Parameters:

run_env (RunToxEnv) – the run environment

Return type:

None

teardown_env(conf)

Tear the packaging environment down, once no run environment uses it.

Parameters:

conf (EnvConfigSet) – the configuration of the run environment that is torn down

Return type:

None

abstractmethod child_pkg_envs(run_conf)

Get the packaging environments the packaging environment of a run environment depends on.

Parameters:

run_conf (EnvConfigSet) – the configuration of the run environment

Return type:

Iterator[PackageToxEnv]

Returns:

the packaging environments

class tox.tox_env.package.Package

Bases: object

package.

journal

class tox.journal.env.EnvJournal(enabled, name)

Bases: object

Report the status of a tox environment.

Parameters:
  • enabled (bool) – whether the journal records anything

  • name (str) – the name of the tox environment

__setitem__(key, value)

Add a new entry under key into the event journal.

Parameters:
Return type:

None

__bool__()
Return type:

bool

Returns:

a flag indicating if the event journal is on or not

property content

The env journal content, merging the explicit keys and the execution commands.

add_execute(outcome, run_id)

Add a command execution to the journal.

Parameters:
  • outcome (Outcome) – the execution outcome

  • run_id (str) – the execution id

Return type:

None

report

Handler.name

A standard handler stores its name for lookup. Tox reports the active environment name instead and ignores assignments to this attribute.

class tox.report.ToxHandler(level, is_colored, out_err)

Bases: StreamHandler

Controls tox output.

Parameters:
  • level (int) – the minimum level of the messages to show

  • is_colored (bool) – whether the messages are colored

  • out_err (tuple[TextIOWrapper, TextIOWrapper]) – the standard output and error streams to write to

property stdout

The current standard output.

property name

The current tox environment name.

Setter accepts:

str | None

Overrides:

Handler.name

with_context(name)

Set a new tox environment context.

Parameters:

name (str) – the name of the tox environment

Yields:

None – nothing, the messages in the block are tagged with the name

property stderr

The current standard error.

update_verbosity(verbosity)

Set the verbosity of the log output.

Parameters:

verbosity (int) – the verbosity, the higher the more output

Return type:

None

class tox.report.HandledError

Bases: RuntimeError

Error that has been handled so no need for stack trace.

execute

class tox.execute.request.ExecuteRequest(cmd, cwd, env, stdin, run_id, allow=None, *, capture=False)

Bases: object

Defines a commands execution request.

cmd

the command to run

cwd

the working directory to use

env

the environment variables to use

stdin

the type of standard input interaction allowed

run_id

an id to identify this run

property shell_cmd

The command to run as a shell command.

property shell_cmd_redacted

The command with URL userinfo and secret-looking inline flag values masked.

class tox.execute.request.StdinSource(*values)

Bases: Enum

Where the standard input of a command comes from.

OFF = 0

input disabled

USER = 1

input via the standard input

API = 2

input via programmatic access

static user_only()
Return type:

StdinSource

Returns:

USER if the standard input is tty type else OFF

class tox.execute.api.Outcome(request, show_on_standard, exit_code, out, err, start, end, cmd, metadata, start_error=None)

Bases: object

Result of a command execution.

Variables:

OK – the exit code of a successful command

OK = 0
FAILED = 1

exit code reported when a ! command exits with OK

request

the execution request

show_on_standard

a flag indicating if the execution was shown on stdout/stderr

exit_code

the exit code for the execution

out

the standard output of the execution

err

the standard error of the execution

start

a timer sample for the start of the execution

end

a timer sample for the end of the execution

cmd

the command as executed

metadata

additional metadata attached to the execution

start_error

the error that kept the command from starting, None once it started

property elapsed

The time the execution took, in seconds.

assert_success()

Assert that the execution succeeded.

Return type:

None

log_run_done(lvl)

Log that the run was done.

Parameters:

lvl (int) – the level on what to log as interpreted by logging.log()

Return type:

None

assert_failure()

Assert that the execution failed.

Return type:

None

out_err()
Return type:

tuple[str, str]

Returns:

a tuple of the standard output and standard error

class tox.execute.api.ExecuteOptions(env)

Bases: object

The options that control how a command execution is stopped and whether its output is captured.

Parameters:

env (ToxEnv) – the environment the command runs in

property suicide_timeout

Seconds to wait for the process to exit on its own before sending SIGINT.

property interrupt_timeout

Seconds to wait after SIGINT before sending SIGTERM.

property terminate_timeout

Seconds to wait after SIGTERM before sending SIGKILL.

property no_capture

Whether the output is shown as it is produced, instead of only being captured.

classmethod register_conf(env)

Register the configuration keys that control how the execution is stopped.

Parameters:

env (ToxEnv) – the environment to register the keys in

Return type:

None

class tox.execute.api.Execute(colored)

Bases: ABC

Abstract API for execution of a tox environment.

Parameters:

colored (bool) – whether the output is colored

call(request, show, out_err, env)

Run a request, and yield the status of the execution while it runs.

Parameters:
  • request (ExecuteRequest) – the request to run

  • show (bool) – whether to show the output while the request runs

  • out_err (tuple[TextIOWrapper, TextIOWrapper]) – the standard output and standard error streams to write to

  • env (ToxEnv) – the environment the request runs in

Yields:

ExecuteStatus – the status of the execution

abstractmethod build_instance(request, options, out, err)

Build the instance that runs a request.

Parameters:
  • request (ExecuteRequest) – the request to run

  • options (ExecuteOptions) – the options of the execution

  • out (SyncWrite) – the stream the standard output is written to

  • err (SyncWrite) – the stream the standard error is written to

Return type:

ExecuteInstance

Returns:

the instance that runs the request

classmethod register_conf(env)

Register the configuration keys of the execution options.

Parameters:

env (ToxEnv) – the environment to register the keys in

Return type:

None

class tox.execute.api.ExecuteStatus(options, out, err)

Bases: ABC

The state of a command execution while it runs, and its outcome once it is done.

Parameters:
  • options (ExecuteOptions) – the options of the execution

  • out (SyncWrite) – the stream the standard output is written to

  • err (SyncWrite) – the stream the standard error is written to

Variables:

outcome (Outcome | None) – the outcome of the execution, None until it is done

outcome
abstract property exit_code

The exit code of the command, None while it runs.

property start_error

The error that kept the command from starting, None once it started.

property out

The standard output collected so far.

property err

The standard error collected so far.

property metadata

Metadata about the execution, empty unless the executor provides some.

abstractmethod wait(timeout=None)

Wait for the command to finish.

Parameters:

timeout (float | None) – the seconds to wait, wait without a limit when None

Return type:

int | None

Returns:

the exit code, or None when the command did not finish in time

abstractmethod write_stdin(content)

Write content to the standard input of the command.

Parameters:

content (str) – the content to write

Return type:

None

abstractmethod interrupt()

Interrupt the command.

Return type:

None

set_out_err(out, err)

Replace the streams the output of the command is written to.

Parameters:
  • out (SyncWrite) – the new standard output stream

  • err (SyncWrite) – the new standard error stream

Return type:

tuple[SyncWrite, SyncWrite]

Returns:

the previous standard output and standard error streams

class tox.execute.api.FinishedExecuteStatus(options, out, err, exit_code)

Bases: ExecuteStatus

Report a fixed exit code for a command that finished or never started, without running a process.

Parameters:
  • options (ExecuteOptions) – the execution options of the command

  • out (SyncWrite) – the sink for the standard output

  • err (SyncWrite) – the sink for the standard error

  • exit_code (int | None) – the exit code to report, None if there is none

property exit_code

The exit code of the command, None while it runs.

Overrides:

ExecuteStatus.exit_code

wait(timeout=None)

Wait for the command to finish.

Parameters:

timeout (float | None) – the seconds to wait, wait without a limit when None

Return type:

int | None

Returns:

the exit code, or None when the command did not finish in time

Overrides:

ExecuteStatus.wait

write_stdin(content)

Cannot write.

Parameters:

content (str) – the text that would be written to the standard input

Return type:

None

Overrides:

ExecuteStatus.write_stdin

interrupt()

Interrupt the command.

Return type:

None

Overrides:

ExecuteStatus.interrupt

class tox.execute.api.ExecuteInstance(request, options, out, err)

Bases: ABC

An instance of a command execution.

Parameters:
property out_handler

The callback that receives the standard output of the command.

property err_handler

The callback that receives the standard error of the command.

abstract property cmd

The command line to run.

class tox.execute.stream.SyncWrite(name, target, color=None)

Bases: object

Make sure data collected is synced in-memory and to the target stream on every newline and time period.

Used to propagate executed commands output to the standard output/error streams visible to the user.

Parameters:
  • name (str) – the name of the stream, used in the timer thread name

  • target (IO[bytes] | None) – the stream the content is synced to, or None to only collect it

  • color (str | None) – the color the content is shown in

Variables:
  • REFRESH_RATE – the seconds between two syncs to the target stream

  • timer – the timer that syncs the content on the refresh period

REFRESH_RATE = 0.1
colored()

Wrap the content written inside the block in the color of the stream, when a color is set.

Yields:

None, the block runs with the color applied

property text

The collected content decoded as UTF-8, keeping the bytes that are not valid UTF-8.

property content

The collected content, as raw bytes.

handler(content)

A callback called whenever content is written.

Parameters:

content (bytes) – the bytes that were written

Return type:

int

Returns:

the number of bytes handled

installer

tox.tox_env.installer.InstallArguments = tox.tox_env.python.pip.req_file.PythonDeps | tox.tox_env.python.pylock.Pylock | collections.abc.Sequence[packaging.requirements.Requirement | tox.tox_env.package.Package]

Argument types tox itself passes to Installer.install() and the tox_on_install hook.

class tox.tox_env.python.pip.req.file.EnvironmentProvider(*args, **kwargs)

Bases: Protocol

Callable that provides the environment variables that requirements can expand.

class tox.tox_env.python.pip.req.file.RequirementsFile(path, constraint, environment_provider=None)

Bases: object

A requirements file, with the requirements, options and constraints it declares.

Parameters:
  • path (Path) – the path of the requirements file

  • constraint (bool) – whether the file lists constraints, rather than requirements

  • environment_provider (EnvironmentProvider | None) – the provider of the environment variables the file can expand

class tox.tox_env.python.pip.req_file.PythonDeps(raw, root, environment_provider=None)

The dependencies of a tox environment, as set by its deps setting.

class tox.tox_env.python.pylock.Pylock(*, path, extras=frozenset({}), groups=frozenset({}), marker_env=dict())

Bases: object

A pylock.toml lock file, from which the requirements are installed.

Parameters:
  • path (Path) – the path of the lock file

  • extras (frozenset[str]) – the extras to install from the lock file

  • groups (frozenset[str]) – the dependency groups to install from the lock file

  • marker_env (dict[str, str]) – the environment markers to resolve the lock file with

class tox.tox_env.installer.Installer[EnvT_co: ToxEnv, ArgsT = PythonDeps | Pylock | Sequence[Requirement | Package]](tox_env)

Bases: ABC, Generic[EnvT_co, ArgsT]

Install packages into a tox environment; ArgsT is what install() accepts.

Parameters:

tox_env (EnvT_co) – the environment to install the packages into

abstractmethod installed()
Return type:

list[str]

Returns:

a list of packages installed (JSON dump-able)

abstractmethod install(arguments, section, of_type)

Install the given arguments in the environment.

Parameters:
  • arguments (ArgsT) – the arguments to install

  • section (str) – the configuration section the arguments come from

  • of_type (str) – the type of the arguments, such as deps or requirements

Return type:

None

session

class tox.session.state.State(options, args)

Bases: object

Runtime state holder.

Parameters:
  • options (Options) – the parsed command line options and the command handlers

  • args (Sequence[str]) – the command line arguments tox was started with

Variables:

conf – the configuration of this run

property envs

Access to the tox environments, selected on first access.

class tox.session.env_select.CliEnv(value=None)

Bases: object

The user’s selection of tox test environments via -e or env_list config.

It is in one of three forms:

  • A list of specific environments, instantiated with a string that is a comma-separated list of the environment names. (These may have spaces on either side of the commas which are removed.) As a sequence this will be a sequence of those names.

The other two forms are:

  • “ALL” which is all environments defined by the tox configuration. This is instantiated with ALL either alone or as any element of a comma-separated list; any other environment names are ignored. is_all() will be true and as a sequence it will be empty. This prints in string representation as ALL.

  • The default environments as chosen by tox configuration. This is instantiated with None as the parameter, is_default_list() will be true, and as a sequence this will be empty. This prints in string representation as <env_list>.

Parameters:

value (list[str] | str | None) – the selection as given on the command line or in the configuration

property is_all

Whether all environments were requested with ALL.

property is_default_list

Whether no environments were requested, so the default list applies.

class tox.session.env_select.EnvSelector(state)

Bases: object

Select the environments of a run from the command line, the configuration and the environment.

Parameters:

state (State) – the state of the run

Variables:

on_empty_fallback_py – whether to fall back to the py environment when none is selected

iter(*, only_active=True, package=False)

Get tox environments.

Parameters:
  • only_active (bool) – active environments are marked to be executed in the current target

  • package (bool) – return package environments

Yields:

str – an iteration of tox environments

unavailable_envs()

Get dict of unavailable environment names to runner names.

Return type:

dict[str, str]

Returns:

dict mapping environment name to runner name

ensure_only_run_env_is_active()

Ensure that no packaging environment is selected to run.

Raises:

tox.report.HandledError – when a packaging environment is selected

Return type:

None

class tox.tox_env.info.Info(path)

Bases: object

Stores metadata about the tox environment.

Parameters:

path (Path) – the directory of the environment

compare(value, section, sub_section=None)

Compare new information with the existing one and update if differs.

Parameters:
  • value (Any) – the value stored

  • section (str) – the primary key of the information

  • sub_section (str | None) – the secondary key of the information

Yields:

tuple[bool, Any | None] – a tuple where the first value is if it differs and the second is the old value

reset()

Forget the stored information, so it is written again on the next save.

Return type:

None

testing

A pytest plugin useful to test tox itself (and its plugins).

class tox.pytest.ToxProject(files, base, path, capfd, monkeypatch, mocker)

Bases: object

A tox project that is created on disk for a test, from the files it is given.

Parameters:
  • files (dict[str, Any]) – the files of the project, nested by directory

  • base (Path | None) – a directory to copy into the project first, None to copy nothing

  • path (Path) – the directory of the project

  • capfd (CaptureFixture[str]) – the capture fixture of the test

  • monkeypatch (MonkeyPatch) – the monkeypatch fixture of the test

  • mocker (MockerFixture) – the mocker fixture of the test

property structure

The files of the project, nested by directory, as they are on disk.

patch_execute(handle=None)

Patch the execution of the environments, so requests are handled by a function.

Parameters:

handle (Callable[[ExecuteRequest], int | None] | None) – the function that handles a request and returns its exit code, None for the default

Return type:

MagicMock

Returns:

the mock of the execution

run(*args, from_cwd=None, raise_on_config_fail=True)

Run tox in the project, with the given command line arguments.

Parameters:
  • args (str) – the command line arguments

  • from_cwd (Path | None) – the directory to run from, the project directory when None

  • raise_on_config_fail (bool) – whether to raise when showing the configuration fails

Return type:

ToxRunOutcome

Returns:

the outcome of the run

Raises:

RuntimeError – when the run did not set an exit code

chdir(to=None)

Change the working directory for the duration of the block.

Parameters:

to (Path | None) – the directory to change to, the project directory when None

Yields:

None, the block runs in the directory

class tox.pytest.ToxProjectCreator(*args, **kwargs)

Bases: Protocol

Callable that creates a tox project for a test, from its files.

class tox.pytest.ToxRunOutcome(cmd, cwd, code, out, err, state)

Bases: object

The outcome of running tox in a test project.

Parameters:
  • cmd (Sequence[str]) – the command line arguments tox was run with

  • cwd (Path) – the directory tox was run in

  • code (int) – the exit code of the run

  • out (str) – the standard output of the run

  • err (str) – the standard error of the run

  • state (State | None) – the state of the run, None when it was not captured

property shell_cmd

The command line tox was run with, as a string a shell runs.

env_conf(name)

Get the configuration of an environment of the run.

Parameters:

name (str) – the name of the environment

Return type:

EnvConfigSet

Returns:

the configuration of the environment

property state

The state of the run, which is not available when it was not captured.

Raises:

RuntimeError – when the state was not captured

assert_success()

Assert that the run succeeded.

Return type:

None

property success

Whether the run succeeded.

assert_failed(code=None)

Assert that the run failed.

Parameters:

code (int | None) – the exit code the run is expected to fail with, any non-zero exit code when None

Return type:

None

assert_out_err(out, err, *, dedent=True, regex=False)

Assert the standard output and standard error of the run.

Parameters:
  • out (str) – the expected standard output

  • err (str) – the expected standard error

  • dedent (bool) – whether to remove the common indentation of the expected texts first

  • regex (bool) – whether the expected texts are regular expressions

Return type:

None

static matches(pattern, text, flags=0)

Assert that a text matches a pattern.

Parameters:
  • pattern (str) – the expected pattern

  • text (str) – the text to check

  • flags (int) – the regular expression flags to match with

Return type:

None