API documentation

The container module

The container module contains all classes for abstracting the details of launching containers away. These classes are used to parametrize test cases using the fixtures provided by this plugin.

class pytest_container.container.BindMount(container_path: str, flags: ~typing.List[~pytest_container.container.VolumeFlag] = <factory>, shared: bool = False, _vol_name: str = '', host_path: ~typing.Optional[str] = None)

A volume mounted into a container from the host using bind mounts.

This class describes a bind mount of a host directory into a container. In the most minimal configuration, all you need to specify is the path in the container via container_path. The container* fixtures will then create a temporary directory on the host for you that will be used as the mount point. Alternatively, you can also specify the path on the host yourself via host_path.

host_path: Optional[str] = None

Path on the host that will be mounted if absolute. if relative, it refers to a volume to be auto-created. When omitted, a temporary directory will be created and the path will be saved in this attribute.

class pytest_container.container.BindMountCreator(volume: BindMount, _tmpdir: Optional[TemporaryDirectory[str]] = None)

Context Manager that creates temporary directories for bind mounts (if necessary, i.e. when BindMount.host_path is None).

volume: BindMount

The bind mount which host path should be created

class pytest_container.container.Container(url: str = '', container_id: str = '', entry_point: ~pytest_container.container.EntrypointSelection = EntrypointSelection.AUTO, custom_entry_point: ~typing.Optional[str] = None, extra_launch_args: ~typing.List[str] = <factory>, extra_entrypoint_args: ~typing.List[str] = <factory>, healthcheck_timeout: ~typing.Optional[~datetime.timedelta] = None, extra_environment_variables: ~typing.Optional[~typing.Dict[str, str]] = None, singleton: bool = False, forwarded_ports: ~typing.List[~pytest_container.inspect.PortForwarding] = <factory>, volume_mounts: ~typing.List[~typing.Union[~pytest_container.container.ContainerVolume, ~pytest_container.container.BindMount]] = <factory>, _is_local: bool = False)

This class stores information about the Container Image under test.

property baseurl: Optional[str]

The registry url on which this container is based on, if one exists. Otherwise None is returned.

get_base() Container

Returns the Base of this Container Image. If the container has no base, then self is returned.

prepare_container(container_runtime: OciRuntimeBase, rootdir: Path, extra_build_args: Optional[List[str]] = None) None

Prepares the container so that it can be launched.

pull_container(container_runtime: OciRuntimeBase) None

Pulls the container with the given url using the currently selected container runtime

class pytest_container.container.ContainerBase(url: str = '', container_id: str = '', entry_point: ~pytest_container.container.EntrypointSelection = EntrypointSelection.AUTO, custom_entry_point: ~typing.Optional[str] = None, extra_launch_args: ~typing.List[str] = <factory>, extra_entrypoint_args: ~typing.List[str] = <factory>, healthcheck_timeout: ~typing.Optional[~datetime.timedelta] = None, extra_environment_variables: ~typing.Optional[~typing.Dict[str, str]] = None, singleton: bool = False, forwarded_ports: ~typing.List[~pytest_container.inspect.PortForwarding] = <factory>, volume_mounts: ~typing.List[~typing.Union[~pytest_container.container.ContainerVolume, ~pytest_container.container.BindMount]] = <factory>, _is_local: bool = False)

Base class for defining containers to be tested. Not to be used directly, instead use Container or DerivedContainer.

container_id: str = ''

id of the container if it is not available via a registry URL

custom_entry_point: Optional[str] = None

custom entry point for this container (i.e. neither its default, nor /bin/bash)

entry_point: EntrypointSelection = 1

Defines which entrypoint of the container is used. By default either custom_entry_point will be used (if defined) or the container’s entrypoint or cmd. If neither of the two is set, then /bin/bash will be used.

extra_entrypoint_args: List[str]

List of additional arguments that are passed to the CMD or entrypoint. These arguments are inserted after the docker/podman run -d $image on launching the image. The list must be properly escaped, e.g. by passing the string through shlex.split. The arguments must not cause the container to exit early. It must remain active in the background, otherwise this library will not function properly.

extra_environment_variables: Optional[Dict[str, str]] = None

additional environment variables that should be injected into the container

extra_launch_args: List[str]

List of additional flags that will be inserted after docker/podman run -d and before the image name (i.e. these arguments are not passed to the entrypoint or CMD). The list must be properly escaped, e.g. as created by shlex.split.

property filelock_filename: str

Filename of a lockfile unique to the container image under test.

It is a hash of the properties of this class excluding all values that are set after the container is launched. Thereby, this filename can be used to acquire a lock blocking any action using this specific container image across threads/processes.

forwarded_ports: List[PortForwarding]

forwarded ports of this container

get_launch_cmd(container_runtime: OciRuntimeBase, extra_run_args: Optional[List[str]] = None) List[str]

Returns the command to launch this container image.

Parameters:

extra_run_args – optional list of arguments that are added to the launch command directly after the run -d.

Returns:

The command to launch the container image described by this class instance as a list of strings that can be fed directly to subprocess.Popen as the args parameter.

healthcheck_timeout: Optional[timedelta] = None

Time for the container to become healthy (the timeout is ignored when the container image defines no HEALTHCHECK or when the timeout is below zero). When the value is None, then the timeout will be inferred from the container image’s HEALTHCHECK directive.

property local_image: bool

Returns true if this image has been build locally and has not been pulled from a registry.

singleton: bool = False

Indicate whether there must never be more than one running container of this type at all times (e.g. because it opens a shared port).

url: str = ''

Full url to this container via which it can be pulled

If your container image is not available via a registry and only locally, then you can use the following syntax: containers-storage:$local_name

volume_mounts: List[Union[ContainerVolume, BindMount]]

optional list of volumes that should be mounted in this container

class pytest_container.container.ContainerBaseABC

Abstract base class defining the methods that must be implemented by the classes fed to the *container* fixtures.

abstract property baseurl: Optional[str]

The registry url on which this container is based on, if one exists. Otherwise None is returned.

abstract get_base() Union[Container, DerivedContainer]

Returns the Base of this Container Image. If the container has no base, then self is returned.

abstract prepare_container(container_runtime: OciRuntimeBase, rootdir: Path, extra_build_args: Optional[List[str]]) None

Prepares the container so that it can be launched.

class pytest_container.container.ContainerData(image_url_or_id: str, container_id: str, connection: Any, container: Union[Container, DerivedContainer], forwarded_ports: List[PortForwarding], _container_runtime: OciRuntimeBase)

Class returned by the *container* fixtures to the test function. It contains information about the launched container and the testinfra connection to the running container.

connection: Any

the testinfra connection to the running container

container: Union[Container, DerivedContainer]

the container data class that has been used in this test

container_id: str

ID of the started container

forwarded_ports: List[PortForwarding]

any ports that are exposed by this container

image_url_or_id: str

url to the container image on the registry or the id of the local image if the container has been build locally

property inspect: ContainerInspect

Inspect the launched container and return the result of $runtime inspect $ctr_id.

class pytest_container.container.ContainerLauncher(container: ~typing.Union[~pytest_container.container.Container, ~pytest_container.container.DerivedContainer], container_runtime: ~pytest_container.runtime.OciRuntimeBase, rootdir: ~pathlib.Path, extra_build_args: ~typing.List[str] = <factory>, extra_run_args: ~typing.List[str] = <factory>, container_name: str = '', _expose_ports: bool = True, _new_port_forwards: ~typing.List[~pytest_container.inspect.PortForwarding] = <factory>, _container_id: ~typing.Optional[str] = None, _stack: ~contextlib.ExitStack = <factory>, _cidfile: str = <factory>)

Helper context manager to setup, start and teardown a container including all of its resources. It is used by the *container* fixtures.

container: Union[Container, DerivedContainer]

The container that will be launched

property container_data: ContainerData

The ContainerData instance corresponding to the running container. This property is only valid after the context manager has been “entered” via a with statement.

container_name: str = ''

optional name of this container

container_runtime: OciRuntimeBase

The container runtime via which the container will be launched

extra_build_args: List[str]

additional arguments to pass to the container build commands

extra_run_args: List[str]

additional arguments to pass to the container run commands

launch_container() None

This function performs the actual heavy lifting of launching the container, creating all the volumes, port bindings, etc.pp.

rootdir: Path

root directory of the pytest testsuite

class pytest_container.container.ContainerVolume(container_path: str, flags: ~typing.List[~pytest_container.container.VolumeFlag] = <factory>, shared: bool = False, _vol_name: str = '')

A container volume created by the container runtime for persisting files outside of (ephemeral) containers.

property volume_id: str

Unique ID of the volume. It is automatically set when the volume is created by VolumeCreator.

class pytest_container.container.ContainerVolumeBase(container_path: str, flags: ~typing.List[~pytest_container.container.VolumeFlag] = <factory>, shared: bool = False, _vol_name: str = '')

Base class for container volumes.

property cli_arg: str

Command line argument to mount this volume.

container_path: str

Path inside the container where this volume will be mounted

flags: List[VolumeFlag]

Flags for mounting this volume.

Note that some flags are mutually exclusive and potentially not supported by all container runtimes. The VolumeFlag.SELINUX_PRIVATE flag will be added by default to the flags unless ContainerVolumeBase.shared is True.

shared: bool = False

Define whether this volume should can be shared between containers. Defaults to False.

This affects only the addition of SELinux flags to flags.

class pytest_container.container.DerivedContainer(url: str = '', container_id: str = '', entry_point: ~pytest_container.container.EntrypointSelection = EntrypointSelection.AUTO, custom_entry_point: ~typing.Optional[str] = None, extra_launch_args: ~typing.List[str] = <factory>, extra_entrypoint_args: ~typing.List[str] = <factory>, healthcheck_timeout: ~typing.Optional[~datetime.timedelta] = None, extra_environment_variables: ~typing.Optional[~typing.Dict[str, str]] = None, singleton: bool = False, forwarded_ports: ~typing.List[~pytest_container.inspect.PortForwarding] = <factory>, volume_mounts: ~typing.List[~typing.Union[~pytest_container.container.ContainerVolume, ~pytest_container.container.BindMount]] = <factory>, _is_local: bool = False, base: ~typing.Union[~pytest_container.container.Container, ~pytest_container.container.DerivedContainer, str] = '', containerfile: str = '', image_format: ~typing.Optional[~pytest_container.container.ImageFormat] = None, add_build_tags: ~typing.List[str] = <factory>)

Class for storing information about the Container Image under test, that is build from a Containerfile/Dockerfile from a different image (can be any image from a registry or an instance of Container or DerivedContainer).

add_build_tags: List[str]

Additional build tags/names that should be added to the container once it has been built

base: Union[Container, DerivedContainer, str] = ''
property baseurl: Optional[str]

The registry url on which this container is based on, if one exists. Otherwise None is returned.

containerfile: str = ''

The Containerfile that is used to build this container derived from base.

get_base() Union[Container, DerivedContainer]

Return the base of this derived container.

image_format: Optional[ImageFormat] = None

An optional image format when building images with buildah. It is ignored when the container runtime is docker. The oci image format is used by default. If the image format is None and the base image has a HEALTHCHECK defined, then the docker image format will be used instead. Specifying an image format disables the auto-detection and uses the supplied value.

prepare_container(container_runtime: OciRuntimeBase, rootdir: Path, extra_build_args: Optional[List[str]] = None) None

Prepares the container so that it can be launched.

class pytest_container.container.EntrypointSelection(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Choices how the entrypoint of a container is picked.

AUTO = 1

If custom_entry_point is set, then that value is used. Otherwise the container images entrypoint or cmd is used if it defines one, or else /bin/bash is used.

BASH = 2

/bin/bash is used as the entry point

IMAGE = 3

The images’ entrypoint or the default from the container runtime is used

class pytest_container.container.ImageFormat(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Image formats supported by buildah.

DOCKER = 'docker'

Docker’s default image format that supports additional properties, like HEALTHCHECK

OCIv1 = 'oci'

The default OCIv1 image format.

class pytest_container.container.VolumeCreator(volume: ContainerVolume, container_runtime: OciRuntimeBase)

Context Manager to create and remove a ContainerVolume.

This context manager creates a volume using the supplied container_runtime When the with block is entered and removes it once it is exited.

container_runtime: OciRuntimeBase

The container runtime, via which the volume is created & destroyed

volume: ContainerVolume

The volume to be created

class pytest_container.container.VolumeFlag(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Supported flags for mounting container volumes.

CHOWN_USER = 'U'

chown the content of the volume for rootless runs

NOEXEC = 'noexec'

ensure the volume is mounted as noexec (data only)

OVERLAY = 'O'

The volume is mounted as a temporary storage using overlay-fs (only supported by podman)

READ_ONLY = 'ro'

The volume is mounted read-only

READ_WRITE = 'rw'

The volume is mounted read-write (default)

SELINUX_PRIVATE = 'Z'

The volume is relabeled so that only a single container can access it

SELINUX_SHARED = 'z'

The volume is relabeled so that it can be shared by two containers

pytest_container.container.container_and_marks_from_pytest_param(ctr_or_param: Container) Tuple[Container, Literal[None]]
pytest_container.container.container_and_marks_from_pytest_param(ctr_or_param: DerivedContainer) Tuple[DerivedContainer, Literal[None]]
pytest_container.container.container_and_marks_from_pytest_param(ctr_or_param: ParameterSet) Tuple[Union[Container, DerivedContainer], Optional[Collection[Union[MarkDecorator, Mark]]]]

Extracts the Container or DerivedContainer and the corresponding marks from a pytest.param and returns both.

If param is either a Container or a DerivedContainer, then param is returned directly and the second return value is None.

pytest_container.container.container_from_pytest_param(param: Union[ParameterSet, Container, DerivedContainer]) Union[Container, DerivedContainer]

Extracts the Container or DerivedContainer from a pytest.param or just returns the value directly, if it is either a Container or a DerivedContainer.

Deprecated since version 0.4.0: This will be removed in 0.5.0. use container_and_marks_from_pytest_param instead

pytest_container.container.container_to_pytest_param(container: ContainerBase, marks: Optional[Union[Collection[MarkDecorator], MarkDecorator]] = None) ParameterSet

Converts a subclass of ContainerBase (Container or DerivedContainer) into a pytest.param with the given marks and sets the id of the parameter to the pretty printed version of the container (i.e. its url or container_id)

pytest_container.container.create_host_port_port_forward(port_forwards: List[PortForwarding]) List[PortForwarding]

Given a list of port_forwards, this function finds random free ports on the host system to which the container ports can be bound and returns a new list of appropriately configured PortForwarding instances.

pytest_container.container.get_volume_creator(volume: ContainerVolume, runtime: OciRuntimeBase) VolumeCreator
pytest_container.container.get_volume_creator(volume: BindMount, runtime: OciRuntimeBase) BindMountCreator

Returns the appropriate volume creation context manager for the given volume.

Generate a filelock for finding free ports on the host.

The pod module

Module for managing podman pods.

class pytest_container.pod.Pod(containers: ~typing.List[~typing.Union[~pytest_container.container.DerivedContainer, ~pytest_container.container.Container]], forwarded_ports: ~typing.List[~pytest_container.inspect.PortForwarding] = <factory>)

A pod is a collection of containers that share the same network and port forwards. Currently only podman supports creating pods.

Caution: port forwards of the individual containers are ignored and only the port forwards in the pod class are taken into account!

containers: List[Union[DerivedContainer, Container]]

containers belonging to the pod

forwarded_ports: List[PortForwarding]

ports exposed by the pod

class pytest_container.pod.PodData(pod: Pod, container_data: List[ContainerData], pod_id: str, infra_container_id: str, forwarded_ports: List[PortForwarding])

Class that is returned by the pod and pod_per_test fixtures. It contains all necessary information about the created pod and the containers running inside it.

container_data: List[ContainerData]

The ContainerData instances of each container in the pod.

forwarded_ports: List[PortForwarding]

ports exposed by this pod

infra_container_id: str

unique id/hash of the infra container of the pod

pod: Pod

The actual pod that has been launched

pod_id: str

unique id/hash of the running pod

class pytest_container.pod.PodLauncher(pod: ~pytest_container.pod.Pod, rootdir: ~pathlib.Path, pod_name: str = '', extra_build_args: ~typing.List[str] = <factory>, extra_run_args: ~typing.List[str] = <factory>, extra_pod_create_args: ~typing.List[str] = <factory>, _launchers: ~typing.List[~pytest_container.container.ContainerLauncher] = <factory>, _new_port_forwards: ~typing.List[~pytest_container.inspect.PortForwarding] = <factory>, _pod_id: ~typing.Optional[str] = None, _infra_container_id: ~typing.Optional[str] = None, _stack: ~contextlib.ExitStack = <factory>)

A context manager that creates, starts and destroys a pod with all of its containers.

extra_build_args: List[str]

additional arguments to pass to the container build commands

extra_pod_create_args: List[str]

additional arguments to pass to the pod create command

extra_run_args: List[str]

additional arguments to pass to the container run commands

launch_pod() None

Creates the actual pod, establishes the port bindings and launches all containers in the pod.

pod: Pod

the pod that should be created and launched including all of its containers

property pod_data: PodData

Returns the PodData corresponding to this podman pod.

pod_name: str = ''

optional name of the pod

rootdir: Path

root directory of the pytest testsuite

pytest_container.pod.infra_container_id_from_pod_inspect(inspect_output: bytes) str

Given the output of podman pod inspect $id, return the id of the infra container.

pytest_container.pod.pod_from_pytest_param(param: Union[ParameterSet, Pod]) Pod

Extracts the Pod from a pytest.param or just returns the value directly, if it is a Pod.

The build module

The build module contains helper classes for building from git repositories via GitRepositoryBuild and to perform multistage containerfile builds via MultiStageBuild.

class pytest_container.build.GitRepositoryBuild(marks: Any = None, repository_url: str = '', repository_tag: Optional[str] = None, build_command: str = '')

Test information storage for running builds using an external git repository. It is a required parameter for the container_git_clone and host_git_clone fixtures.

build_command: str = ''

The command to run a “build” of the git repository inside a working copy. It can be left empty on purpose.

property clone_command: str

Command to clone the repository at the appropriate tag

property repo_name: str

Name of the directory to which the repository will be checked out

repository_tag: Optional[str] = None

an optional tag at which the repository should be checked out instead of using the default branch

repository_url: str = ''

url of the git repository, can end with .git

property test_command: str

The full test command, including build_command and a cd into the correct folder.

class pytest_container.build.MultiStageBuild(containerfile_template: str, containers: Dict[str, Union[Container, DerivedContainer, str, ParameterSet]])

Helper class to perform multi-stage container builds using the Container and DerivedContainer classes.

This class is essentially just a very simple helper that will replace all variables in containerfile_template with the correct container ids, urls or names from the containers in containers.

For example the following class:

MultiStageBuild(
    containers={
        "builder": Container(url="registry.opensuse.org/opensuse/busybox:latest"),
        "runner1": "docker.io/alpine",
    },
    containerfile_template=r'''FROM $builder as builder

FROM $runner1 as runner1
''',
)

would yield the following Containerfile:

FROM registry.opensuse.org/opensuse/busybox:latest as builder

FROM docker.io/alpine as runner1

The resulting object can either be used to retrieve the rendered Containerfile or to build the containers:

id_of_runner1 = MULTI_STAGE_BUILD.build(
    tmp_path, pytestconfig, container_runtime, "runner1"
)

Where tmp_path and pytestconfig are the pytest fixtures and container_runtime is an instance of a child class of OciRuntimeBase. For further details, see build().

build(tmp_path: Path, rootdir_or_pytestconfig: Union[Path, Config], runtime: OciRuntimeBase, target: Optional[str] = None, extra_build_args: Optional[List[str]] = None) str

Perform the complete multistage build to an optional target.

Parameters:
  • tmp_path – temporary directory into which the Containerfile is written and where the build is performed. This value can be provided via the tmp_path pytest fixture

  • rootdir_or_pytestconfig – root directory of the current test suite or a pytestconfig fixture object. This value is used to prepare the containers in containers.

  • runtime – the container runtime to be used to perform the build. It can be retrieved using the pytest_container.plugin.container_runtime() fixture.

  • target – an optional target to which the build will be run, see the upstream documentation for more information. Note that no verification of the Containerfile is performed prior to the build. I.e. specifying an invalid target will fail your build.

Returns:

Id of the target container or of the last one (when no target was supplied) that was build

property containerfile: str

The rendered Containerfile from the template supplied in containerfile_template.

containerfile_template: str

Template string of a Containerfile where all containers from containers are inserted when retrieved via containerfile.

containers: Dict[str, Union[Container, DerivedContainer, str, ParameterSet]]

A dictionary mapping the container names used in containerfile_template to Container or DerivedContainer objects or strings or any of the previous classes wrapped inside a pytest.param.

prepare_build(tmp_path: Path, container_runtime: OciRuntimeBase, rootdir: Path, extra_build_args: Optional[List[str]] = None) None

Prepares the multistage build: it writes the rendered Containerfile into tmp_path and prepares all containers in containers in the given rootdir. Optional additional build arguments can be passed to the preparation of the containers

static run_build_step(tmp_path: Path, runtime: OciRuntimeBase, target: Optional[str] = None, extra_build_args: Optional[List[str]] = None) str

Run the multistage build in the given tmp_path using the supplied runtime. This function requires prepare_build() to be run beforehands.

Parameters:
  • tmp_path – the path in which the build was prepared.

  • runtime – the container runtime which will be used to perform the build

  • target

    an optional target to which the build will be run, see the upstream documentation for more information

Returns:

Id of the final container that has been built

The runtime module

This module contains the container runtime classes abstracting away the implementation details of container runtimes like docker or podman.

class pytest_container.runtime.DockerRuntime

The container runtime using docker for building and running containers.

inspect_container(container_id: str) ContainerInspect

Inspect the container with the provided container_id and return the parsed output from the container runtime as an instance of ContainerInspect.

property supports_healthcheck_inherit_from_base: bool

Indicates whether the container runtime supports that derived images will inherit the healthcheck from the base image.

property version: Version

Returns the version of docker installed on this system

class pytest_container.runtime.OciRuntimeABC

The abstract base class defining the interface of a container runtime.

get_container_health(container_id: str) ContainerHealth

Inspects the running container with the supplied id and returns its current health.

abstract inspect_container(container_id: str) ContainerInspect

Inspect the container with the provided container_id and return the parsed output from the container runtime as an instance of ContainerInspect.

abstract property supports_healthcheck_inherit_from_base: bool

Indicates whether the container runtime supports that derived images will inherit the healthcheck from the base image.

abstract property version: Version

The version of the container runtime.

class pytest_container.runtime.OciRuntimeBase(build_command: ~typing.List[str] = <factory>, runner_binary: str = '', _runtime_functional: bool = False)

Base class of the Container Runtimes.

static get_image_id_from_iidfile(iidfile_path: str) str

Returns the image id/hash from the iidfile that has been created by the container runtime to store the image id after a build.

get_image_size(image_or_id_or_container: Union[str, pytest_container.container.Container, pytest_container.container.DerivedContainer]) float

Returns the container’s size in bytes given an image id, a Container or a py:class:~pytest_container.container.DerivedContainer.

class pytest_container.runtime.PodmanRuntime

The container runtime using podman for running containers and buildah for building containers.

inspect_container(container_id: str) ContainerInspect

Inspect the container with the provided container_id and return the parsed output from the container runtime as an instance of ContainerInspect.

property supports_healthcheck_inherit_from_base: bool

Indicates whether the container runtime supports that derived images will inherit the healthcheck from the base image.

property version: Version

Returns the version of podman installed on the system

class pytest_container.runtime.ToParamMixin(marks: Any = None)

Mixin class that gives child classes the ability to convert themselves into a pytest.param with self.__str__() as the default id and optional marks

marks: Any = None
to_pytest_param() ParameterSet

Convert this class into a pytest.param

class pytest_container.runtime.Version(major: int = 0, minor: int = 0, patch: Optional[int] = None, build: str = '', release: Optional[str] = None)

Representation of a version of the form $major.$minor.$patch[-|+]$release build $build.

This class supports basic comparison, e.g.:

>>> Version(1, 0) > Version(0, 1)
True
>>> Version(1, 0) == Version(1, 0, 0)
True
>>> Version(5, 2, 6, "foobar") == Version(5, 2, 6)
False

Note that the patch and release fields are optional and that the release and build are not taken into account for less or greater than comparisons only for equality or inequality. I.e.:

>>> Version(1, 0, release="16") > Version(1, 0)
False
>>> Version(1, 0, release="16") == Version(1, 0)
False

Additionally you can also pretty print it:

>>> Version(0, 6)
0.6
>>> Version(0, 6, 1)
0.6.1
>>> Version(0, 6, 1, "asdf")
0.6.1 build asdf
build: str = ''
major: int = 0
minor: int = 0
static parse(version_string: str) Version

Parses a version string and returns a constructed Version from that.

patch: Optional[int] = None
release: Optional[str] = None
pytest_container.runtime.get_selected_runtime() OciRuntimeBase

Returns the container runtime that the user selected.

It defaults to podman and selects docker if podman & buildah are not present. If podman and docker are both present, then docker is returned if the environment variable CONTAINER_RUNTIME is set to docker.

If neither docker nor podman are available, then a ValueError is raised.

The inspect module

This module contains the class definitions that represent the output of $runtime inspect $ctr_id.

class pytest_container.inspect.BindMount(source: str, destination: str, rw: bool)

A bind mounted directory

class pytest_container.inspect.Config(user: str, tty: bool, cmd: List[str], entrypoint: List[str], env: Dict[str, str], image: str, labels: Dict[str, str], stop_signal: Union[int, str], healthcheck: Optional[pytest_container.inspect.HealthCheck] = None)
cmd: List[str]

command defined in this container

entrypoint: List[str]

the entrypoint of this container

env: Dict[str, str]

environment variables set in the container image

healthcheck: Optional[HealthCheck] = None

optional healthcheck defined for the underlying container image

image: str

name of image used to launch this container

labels: Dict[str, str]

labels of the container

stop_signal: Union[int, str]

Signal that will be sent to the container when it is stopped. If the container does not terminate, SIGKILL will be used afterwards.

tty: bool

true if this container has a TTY attached

user: str

User defined in the container image

class pytest_container.inspect.ContainerHealth(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Possible states of a container’s health using the HEALTHCHECK property of a container image.

HEALTHY = 'healthy'

the container is healthy

NO_HEALTH_CHECK = ''

the container has no health check defined

STARTING = 'starting'

the health check did not complete yet or did not fail often enough

UNHEALTHY = 'unhealthy'

the healthcheck failed

class pytest_container.inspect.ContainerInspect(id: str, name: str, path: str, args: List[str], state: ContainerState, image_hash: str, config: Config, network: ContainerNetworkSettings, mounts: List[Union[BindMount, VolumeMount]])

Common subset of the information exposed via podman inspect and docker inspect.

args: List[str]

arguments passed to path

config: Config

general configuration of the container (mostly inherited from the used image)

id: str

The container’s ID

image_hash: str

hash digest of the image

mounts: List[Union[BindMount, VolumeMount]]

volumes or bind mounts mounted in this container

name: str

the container’s name

network: ContainerNetworkSettings

Current network settings of this container

path: str

program that has been launched inside the container

state: ContainerState

current state of the container

class pytest_container.inspect.ContainerInspectHealthCheck

Dictionary created by loading the json output of podman inspect $img_id | jq '.[0]["Healthcheck] or docker inspect $img_id | jq '.[0]["Config"]["Healthcheck].

Interval: int
Retries: int
StartPeriod: int
Test: List[str]
Timeout: int
class pytest_container.inspect.ContainerNetworkSettings(ports: ~typing.List[~pytest_container.inspect.PortForwarding] = <factory>, ip_address: ~typing.Optional[str] = None)

Network specific settings of a container.

ip_address: Optional[str] = None

IP Address of the container, if it has one

ports: List[PortForwarding]

list of ports forwarded from the container to the host

class pytest_container.inspect.ContainerState(status: str, running: bool, paused: bool, restarting: bool, oom_killed: bool, dead: bool, pid: int, health: pytest_container.inspect.ContainerHealth = <ContainerHealth.NO_HEALTH_CHECK: ''>)
dead: bool

True if the container is dead

health: ContainerHealth = ''

status of the last health check run for this container image

oom_killed: bool

True if the container is has been killed by a Out Of Memory condition

paused: bool

True if the container has been paused

pid: int

process id of the main container process

restarting: bool

True if the container is restarting

running: bool

True if the container is running

status: str

status of the container, e.g. running, stopped, etc.

class pytest_container.inspect.HealthCheck(start_period: timedelta = datetime.timedelta(0), interval: timedelta = datetime.timedelta(seconds=30), timeout: timedelta = datetime.timedelta(seconds=30), retries: int = 3)

The HEALTHCHECK of a container image.

static from_container_inspect(inspect_json: ContainerInspectHealthCheck) HealthCheck

Convert the json-loaded output of podman inspect $ctr or docker inspect $ctr into a HealthCheck.

interval: timedelta = datetime.timedelta(seconds=30)

healthcheck command is run every interval

property max_wait_time: timedelta

The maximum time to wait until a container can become healthy

retries: int = 3

how often the healthcheck command is retried

start_period: timedelta = datetime.timedelta(0)

startup period of the container during which healthcheck failures will not count towards the failure count

timeout: timedelta = datetime.timedelta(seconds=30)

timeout of the healthcheck command after which it is considered unsuccessful

class pytest_container.inspect.Mount(source: str, destination: str, rw: bool)

Base class for mount points

destination: str

mount point in the container

rw: bool

is this mount read-write?

source: str

source folder on the host (if present)

class pytest_container.inspect.NetworkProtocol(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Network protocols supporting port forwarding.

property SOCK_CONST: int

Returns the appropriate socket type constant (SOCK_STREAM or SOCK_DGRAM) for the current protocol.

TCP = 'tcp'

Transmission Control Protocol

UDP = 'udp'

User Datagram Protocol

class pytest_container.inspect.PortForwarding(container_port: int, protocol: NetworkProtocol = NetworkProtocol.TCP, host_port: int = -1, bind_ip: str = '')

Representation of a port forward from a container to the host.

To expose a port of a container automatically, create an instance of this class, set the attribute container_port and optionally protocol as well and pass it via the parameter forwarded_ports to either the pytest_container.container.Container or pytest_container.container.DerivedContainer:

>>> Container(url="my-webserver", forwarded_ports=[PortForwarding(container_port=8000)])
bind_ip: str = ''

The IP address to which to bind. By default, it will be ‘::’ (all addresses).

container_port: int

The port which shall be exposed by the container.

property forward_cli_args: List[str]

Returns a list of command line arguments for the container launch command to automatically expose this port forwarding.

host_port: int = -1

The port as which the port from container_port is exposed on the host. This value is automatically set by the *container_* fixtures, so there’s no need for the user to modify it

protocol: NetworkProtocol = 'tcp'

The protocol which the exposed port is using. Defaults to TCP.

class pytest_container.inspect.VolumeMount(source: str, destination: str, rw: bool, name: str, driver: str)

A volume mount

driver: str

driver that is backing this volume

name: str

name/hash of this volume

The helpers module

The helpers module contains various functions for adding & retrieving command line flags from pytest and for automatically parametrizing tests using the auto_container* fixtures.

pytest_container.helpers.add_extra_run_and_build_args_options(parser: Parser) None

Add the command line flags --extra-run-args, --extra-build-args and --extra-pod-create-args to the pytest parser.

The parameters of these flags are used by the *container* and pod* fixtures and can be retrieved via get_extra_run_args(), get_extra_build_args() and get_extra_pod_create_args() respectively.

pytest_container.helpers.add_logging_level_options(parser: Parser) None

Add the command line parameter --pytest-container-log-level to the pytest parser. The user can then configure the log level of this pytest plugin.

This function needs to be called in your conftest.py in pytest_addoption. To actually set the log level, you need to call set_logging_level_from_cli_args() as well.

pytest_container.helpers.auto_container_parametrize(metafunc: Metafunc) None

Helper function to automatically parametrize the auto_container_* fixtures.

Use it by adding the following code snippet to conftest.py:

from pytest_container import auto_container_parametrize

def pytest_generate_tests(metafunc):
    auto_container_parametrize(metafunc)
pytest_container.helpers.get_always_pull_option() bool

Returns whether images should be always pulled before launching the container or whether the container runtime can use the locally cached image. This setting is controlled via the environment variable PULL_ALWAYS. If the environment variable is unset, then the default is True.

pytest_container.helpers.get_extra_build_args(pytestconfig: Config) List[str]

Get any extra arguments for buildah bud or docker build that were passed via the CLI flag --extra-build-args.

This requires that add_extra_run_and_build_args_options() was called in conftest.py.

pytest_container.helpers.get_extra_pod_create_args(pytestconfig: Config) List[str]

Get all extra arguments for podman pod create that were passed via the CLI flag --extra-pod-create-args.

This requires that add_extra_run_and_build_args_options() was called in conftest.py.

pytest_container.helpers.get_extra_run_args(pytestconfig: Config) List[str]

Get any extra arguments for podman run or docker run that were passed via the CLI flag --extra-run-args.

This requires that add_extra_run_and_build_args_options() was called in conftest.py.

pytest_container.helpers.set_logging_level_from_cli_args(config: Config) None

Sets the internal logging level of this plugin to the value supplied by the cli argument --pytest-container-log-level.

This function has to be called before all tests get executed, but after the parser option has been added. A good place is for example the pytest_configure hook which has to be added to conftest.py.

The plugin module

The plugin module contains all fixtures that are provided by pytest_container.

pytest_container.plugin.auto_container(request: SubRequest, container_runtime: OciRuntimeBase, pytestconfig: Config) Generator[ContainerData, None, None]

This fixture parametrizes the test function once for each container image defined in the module level variable CONTAINER_IMAGES of the current test module and yield an instance of ContainerData. This fixture will reuse the same container for all tests of the same session.

pytest_container.plugin.auto_container_per_test(request: SubRequest, container_runtime: OciRuntimeBase, pytestconfig: Config) Generator[ContainerData, None, None]

Same as auto_container() but it will launch individual containers for each test function.

pytest_container.plugin.container(request: SubRequest, container_runtime: OciRuntimeBase, pytestconfig: Config) Generator[ContainerData, None, None]

Fixture that expects to be parametrized with an instance of a subclass of ContainerBase with indirect=True. It will launch the container and yield an instance of ContainerData. This fixture will reuse the same container for all tests of the same session.

pytest_container.plugin.container_per_test(request: SubRequest, container_runtime: OciRuntimeBase, pytestconfig: Config) Generator[ContainerData, None, None]

Same as container() but it will launch individual containers for each test function.

pytest_container.plugin.container_runtime() OciRuntimeBase

pytest fixture that returns the currently selected container runtime according to the rules outlined here.

pytest_container.plugin.pod(request: SubRequest, container_runtime: OciRuntimeBase, pytestconfig: Config) Generator[PodData, None, None]

Fixture that has to be parametrized with an instance of Pod with indirect=True. It creates the pod, launches all of its containers and yields an instance of PodData. The fixture automatically skips the test when the current container runtime is not podman. The pod created by this fixture is shared by all test functions.

pytest_container.plugin.pod_per_test(request: SubRequest, container_runtime: OciRuntimeBase, pytestconfig: Config) Generator[PodData, None, None]

Same as pod(), except that it creates a pod for each test function.

The logging module

The logging module handles everything related to logging (unsurprisingly).

pytest_container.logging.set_internal_logging_level(level: Union[str, int] = 20) None

Set the verbosity of the internal logger to the specified level.