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: Optional[List[VolumeFlag]] = None, shared: bool = False, _vol_name: str = '', host_path: 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
. Thecontainer*
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 viahost_path
.
- 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
isNone
).
- 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
orDerivedContainer
.- 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 throughshlex.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 byshlex.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 theargs
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 isNone
, then the timeout will be inferred from the container image’sHEALTHCHECK
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.
- 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 testinfraconnection
to the running container.- container: Union[Container, DerivedContainer]¶
the container data class that has been used in this test
- 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 awith
statement.
- container_runtime: OciRuntimeBase¶
The container runtime via which the container will be launched
- static from_pytestconfig(container: Union[Container, DerivedContainer], container_runtime: OciRuntimeBase, pytestconfig: Config, container_name: str = '') ContainerLauncher ¶
Constructor of
ContainerLauncher
that obtains the attributesrootdir
,extra_build_args
andextra_run_args
from the pytest configuration object.
- class pytest_container.container.ContainerVolume(container_path: str, flags: Optional[List[VolumeFlag]] = None, 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: Optional[List[VolumeFlag]] = None, shared: bool = False, _vol_name: str = '')¶
Base class for container volumes.
- flags: Optional[List[VolumeFlag]] = None¶
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 if flags isNone
, unlessContainerVolumeBase.shared
isTrue
, thenVolumeFlag.SELINUX_SHARED
is added.If flags is a list (even an empty one), then no flags are added.
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 ofContainer
orDerivedContainer
).- 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.
- 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 isNone
and the base image has aHEALTHCHECK
defined, then thedocker
image format will be used instead. Specifying an image format disables the auto-detection and uses the supplied value.
- 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 thewith
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: _pytest.mark.ParameterSet) Tuple[Union[Container, DerivedContainer], Optional[Collection[Union[_pytest.mark.MarkDecorator, _pytest.mark.Mark]]]]
Extracts the
Container
orDerivedContainer
and the corresponding marks from a pytest.param and returns both.If
param
is either aContainer
or aDerivedContainer
, then param is returned directly and the second return value isNone
.
- pytest_container.container.container_from_pytest_param(param: Union[ParameterSet, Container, DerivedContainer]) Union[Container, DerivedContainer] ¶
Extracts the
Container
orDerivedContainer
from a pytest.param or just returns the value directly, if it is either aContainer
or aDerivedContainer
.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
orDerivedContainer
) 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. itsurl
orcontainer_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.
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
andpod_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
- 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.
- static from_pytestconfig(pod: Pod, pytestconfig: Config, pod_name: str = '') PodLauncher ¶
Constructor of
PodLauncher
that obtains the attributesrootdir
,extra_build_args
,extra_run_args
andextra_pod_create_args
from the pytest configuration object.
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.
- 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
andDerivedContainer
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 incontainers
.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
andpytestconfig
are the pytest fixtures andcontainer_runtime
is an instance of a child class ofOciRuntimeBase
. For further details, seebuild()
.- 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 fixturerootdir_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 incontainerfile_template
.
- containerfile_template: str¶
Template string of a
Containerfile
where all containers fromcontainers
are inserted when retrieved viacontainerfile
.
- containers: Dict[str, Union[Container, DerivedContainer, str, ParameterSet]]¶
A dictionary mapping the container names used in
containerfile_template
toContainer
orDerivedContainer
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
intotmp_path
and prepares all containers incontainers
in the givenrootdir
. 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 suppliedruntime
. This function requiresprepare_build()
to be run beforehand.- 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 ofContainerInspect
.
- 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 ofContainerInspect
.
- 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 ofContainerInspect
.
- 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
- 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
- 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], workingdir: Path, healthcheck: Optional[HealthCheck] = None)¶
Container configuration obtained from the
Config
attribute in the inspect of a container. It features the most useful attributes and those that are common to both podman and docker.- healthcheck: Optional[HealthCheck] = None¶
optional healthcheck defined for the underlying 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.
- mounts: List[Union[BindMount, VolumeMount]]¶
volumes or bind mounts mounted in this container
- network: ContainerNetworkSettings¶
Current network settings of this 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].
- 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.
- 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: ContainerHealth = ContainerHealth.NO_HEALTH_CHECK)¶
State of the container, it is populated from the
State
attribute in the inspect of a container.- health: ContainerHealth = ''¶
status of the last health check run for this container image
- 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
.
- class pytest_container.inspect.Mount(source: str, destination: str, rw: bool)¶
Base class for mount points
- 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
orSOCK_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 optionallyprotocol
as well and pass it via the parameterforwarded_ports
to either thepytest_container.container.Container
orpytest_container.container.DerivedContainer
:>>> Container(url="my-webserver", forwarded_ports=[PortForwarding(container_port=8000)])
- 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.
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*
andpod*
fixtures and can be retrieved viaget_extra_run_args()
,get_extra_build_args()
andget_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
inpytest_addoption
. To actually set the log level, you need to callset_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 isTrue
.
- 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 inconftest.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 inconftest.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 inconftest.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 ofContainerData
. 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 ofContainerData
. 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 ofPodData
. 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.
The logging module¶
The logging module handles everything related to logging (unsurprisingly).