pytest-container

raw JSON →
0.4.4 verified Mon Apr 27 auth: no python

Pytest fixtures for writing container-based tests with support for OCI containers (Docker/Podman). Version 0.4.4 provides decorators and fixtures to manage container lifecycle. Active development, monthly releases.

pip install pytest-container
error AttributeError: module 'pytest_container' has no attribute 'container'
cause The `container` fixture is not automatically injected; it must be imported.
fix
Add from pytest_container import container at the top of your test file.
error Fixture 'container' not found
cause The `container` fixture is not available because it hasn't been imported or the plugin not installed.
fix
Ensure pytest-container is installed (pip install pytest-container) and import the fixture: from pytest_container import container.
breaking Version 0.4.x changed the fixture from `container` to require explicit import. Old code using `pytest_container` as a plugin may break if fixture is not imported.
fix Add `from pytest_container import container` at the top of your test file.
gotcha The `container` fixture works only if the test class has a `CONTAINER_IMAGE` attribute or uses `@pytest.mark.parametrize`. Otherwise, the fixture raises an error.
fix Define a `CONTAINER_IMAGE` class attribute or use `container` fixture with a parametrized image.
deprecated The `container_request` fixture is deprecated in 0.4.x. Use the `container` fixture instead.
fix Replace `container_request` with `container` in your test functions.

Basic usage: use the container fixture or define a custom DerivedContainer class.

from pytest_container import container, DerivedContainer

def test_container(container):
    # container is a pytest fixture that starts a container
    # inspect container object
    assert container.connection.run("echo hello").stdout.strip() == "hello"

# Define custom container image
class TestWithCustomImage:
    CONTAINER_IMAGE = DerivedContainer(
        base="registry.opensuse.org/opensuse/tumbleweed:latest",
        containerfile="""
RUN zypper -n in python3
        """
    )
    def test_custom(self, container):
        assert container.connection.run("python3 --version").rc == 0