### Install Project Dependencies with Poetry Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Command to install project dependencies using Poetry. This is the initial step for setting up a development environment for the project. ```bash poetry install ``` -------------------------------- ### Custom Container Wrapper Class for Readiness and Client Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md This example illustrates using a custom `wrapper_class` with the `container` fixture factory to add custom logic. The `Container` class extends `wrappers.Container` and overrides the `ready()` method for more sophisticated readiness checks (including a random element). It also adds a `client()` helper method to easily create an HTTP connection to the container's exposed port, simplifying test client setup. ```python # test_fixture_wrappers.py import ipaddress import json import random from http.client import HTTPConnection import pytest from pytest_docker_tools import build, container from pytest_docker_tools import wrappers class Container(wrappers.Container): def ready(self): # This is called until it returns True - its a great hook for e.g. # waiting until a log message appears or a pid file is created etc if super().ready(): return random.choice([True, False]) return False def client(self): port = self.ports['8080/tcp'][0] return HTTPConnection(f'localhost:{port}') fakedns_image = build( path='examples/resolver-service/dns', ) fakedns = container( image='{fakedns_image.id}', environment={ 'DNS_EXAMPLE_COM__A': '127.0.0.1', } ) apiserver_image = build( path='examples/resolver-service/api', ) apiserver = container( image='{apiserver_image.id}', ports={ '8080/tcp': None, }, dns=['{fakedns.ips.primary}'], wrapper_class=Container, ) def test_container_wrapper_class(apiserver): client = apiserver.client() client.request('GET', '/') response = client.getresponse() assert response.status == 200 result = json.loads(response.read()) ipaddress.ip_address(result['result']) ``` -------------------------------- ### Create Docker Volume with Initial Content Source: https://context7.com/jc2k/pytest-docker-tools/llms.txt Demonstrates how to create a Docker volume and pre-seed it with specific files and directory structures. This is useful for setting up databases or service data before a container starts. It uses the `volume` fixture factory provided by pytest-docker-tools. ```python from pytest_docker_tools import volume, container minio_image = fetch(repository='minio/minio:latest') minio_volume = volume( initial_content={ 'bucket-1': None, # Create empty directory 'bucket-2/example.txt': b'Test file content', 'bucket-2/data.json': b'{"key": "value"}', } ) minio = container( image='{minio_image.id}', command=['server', '/data'], volumes={ '{minio_volume.name}': {'bind': '/data'}, }, environment={ 'MINIO_ACCESS_KEY': 'minio', 'MINIO_SECRET_KEY': 'minio123', }, ports={'9000/tcp': None}, ) postgres_image = fetch(repository='postgres:13') postgres_volume = volume(name='postgres-data') postgres = container( image='{postgres_image.id}', environment={ 'POSTGRES_PASSWORD': 'secret', 'POSTGRES_DB': 'testdb', }, volumes={ '{postgres_volume.name}': {'bind': '/var/lib/postgresql/data'}, }, ports={'5432/tcp': None}, ) def test_volume_is_seeded(minio): # Retrieve files from container files = minio.get_files('/data') # Verify seeded content assert files['data/bucket-2/example.txt'] == b'Test file content' assert files['data/bucket-1'] is None # Directory, not file # Get text files text_files = minio.get_text('/data') assert text_files['data/bucket-2/example.txt'] == 'Test file content' def test_postgres_with_volume(postgres): # Data persists in volume across container restarts assert postgres.status == "running" port = postgres.ports['5432/tcp'][0] assert port is not None ``` -------------------------------- ### Manage Docker Container Lifecycle with pytest Fixture Source: https://context7.com/jc2k/pytest-docker-tools/llms.txt Creates a pytest fixture to manage a Docker container's lifecycle. It automatically starts the container before tests and removes it afterward, supporting all docker-py container.run() parameters. The container is monitored for readiness and will wait until fully started before tests begin. Dependencies can be expressed via string interpolation. ```python from pytest_docker_tools import build, container, fetch from http.client import HTTPConnection import pytest # Fetch a base image redis_image = fetch(repository='redis:latest') # Create a container from the fetched image redis = container( image='{redis_image.id}', ports={ '6379/tcp': None, # Maps to ephemeral high port on host }, scope='function', # New container per test (default) timeout=30, # Wait up to 30 seconds for container to be ready ) # Build a custom image and create container with dependencies fakedns_image = build(path='examples/resolver-service/dns') fakedns = container( image='{fakedns_image.id}', environment={ 'DNS_EXAMPLE_COM__A': '127.0.0.1', } ) apiserver_image = build(path='examples/resolver-service/api') apiserver = container( image='{apiserver_image.id}', ports={'8080/tcp': None}, dns=['{fakedns.ips.primary}'], # Reference another container's IP ) @pytest.fixture def apiclient(apiserver): # Access the ephemeral port assigned by Docker port = apiserver.ports['8080/tcp'][0] return HTTPConnection(f'localhost:{port}') def test_container_running(redis): # Container is running when test starts assert redis.status == "running" # Access container logs logs = redis.logs() assert 'Redis is starting' in logs # Get the dynamically assigned port host_port = redis.ports['6379/tcp'][0] assert host_port != 6379 # It's an ephemeral high port # Access IP address ip_address = redis.ips.primary # Use get_addr() helper for environment-aware addressing ip, port = redis.get_addr('6379/tcp') def test_api_server(apiclient): import json apiclient.request('GET', '/') response = apiclient.getresponse() assert response.status == 200 assert json.loads(response.read()) == {'result': '127.0.0.1'} ``` -------------------------------- ### Fixture Parameterization and Overloading for Configurations Source: https://context7.com/jc2k/pytest-docker-tools/llms.txt Illustrates advanced pytest fixture usage for testing multiple configurations. This example shows how to define different container fixtures (e.g., fakedns_localhost, fakedns_alternate) with varying environment variables, allowing tests to easily switch between configurations without redefining dependent fixtures. ```python # conftest.py from pytest_docker_tools import build, container from http.client import HTTPConnection import pytest fakedns_image = build(path='examples/resolver-service/dns') # Define multiple DNS configurations fakedns_localhost = container( image='{fakedns_image.id}', environment={'DNS_EXAMPLE_COM__A': '127.0.0.1'} ) fakedns_alternate = container( image='{fakedns_image.id}', environment={'DNS_EXAMPLE_COM__A': '192.168.192.168'} ) ``` -------------------------------- ### Parallel Redis Testing with pytest-xdist (Python) Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Demonstrates parallel execution of Redis tests using `pytest-docker-tools` and `pytest-xdist`. It defines a Redis container fixture and runs 100 instances in parallel across multiple workers. This setup requires `pytest-xdist` to be installed. ```python import pytest from pytest_docker_tools import container, fetch my_redis_image = fetch(repository='redis:latest') my_redis = container( image='{my_redis_image.id}', ) @pytest.mark.parametrize("i", list(range(100))) def test_xdist(i, my_redis): assert my_redis.status == "running" ``` -------------------------------- ### Build and Run Docker Containers with pytest-docker-tools Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md This example demonstrates how to use `pytest_docker_tools` to build Docker images and define containers as fixtures. It shows how to configure environment variables, map ports, and set DNS for containers, making them available for use in pytest tests. The `apiserver` container relies on the `fakedns` container for DNS resolution. ```python # conftest.py from http.client import HTTPConnection import pytest from pytest_docker_tools import build, container fakedns_image = build( path='examples/resolver-service/dns', ) fakedns = container( image='{fakedns_image.id}', environment={ 'DNS_EXAMPLE_COM__A': '{example_com_a}', } ) apiserver_image = build( path='examples/resolver-service/api', ) apiserver = container( image='{apiserver_image.id}', ports={ '8080/tcp': None, }, dns=['{fakedns.ips.primary}'] ) @pytest.fixture def apiclient(apiserver): port = apiserver.ports['8080/tcp'][0] return HTTPConnection(f'localhost:{port}') @pytest.fixture def example_com_a(): return '127.0.0.1' ``` -------------------------------- ### Parameterize Fixtures for Multiple Configurations Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md This example demonstrates fixture parameterization using `pytest`. By defining a fixture that accepts parameters and using `request.getfixturevalue`, you can run tests against multiple configurations of a container. Here, the `fakedns` fixture is parameterized to test against two different DNS configurations (`fakedns_localhost` and `fakedns_alternate`), ensuring the `apiserver` works correctly with each. ```python # conftest.py from http.client import HTTPConnection import pytest from pytest_docker_tools import build, container fakedns_image = build( path='examples/resolver-service/dns', ) fakedns_localhost = container( image='{fakedns_image.id}', environment={ 'DNS_EXAMPLE_COM__A': '127.0.0.1', } ) fakedns_alternate = container( image='{fakedns_image.id}', environment={ 'DNS_EXAMPLE_COM__A': '192.168.192.168', } ) @pytest.fixture(scope='function', params=['fakedns_localhost', 'fakedns_alternate']) def fakedns(request): return request.getfixturevalue(request.param) apiserver_image = build( path='examples/resolver-service/api', ) apiserver = container( image='{apiserver_image.id}', ports={ '8080/tcp': None, }, dns=['{fakedns.ips.primary}'] ) @pytest.fixture def apiclient(apiserver): port = apiserver.ports['8080/tcp'][0] return HTTPConnection(f'localhost:{port}') ``` ```python # test_smoketest.py import ipaddress import json def test_api_server(apiclient): apiclient.request('GET', '/') response = apiclient.getresponse() assert response.status == 200 result = json.loads(response.read()) ipaddress.ip_address(result['result']) ``` -------------------------------- ### container - Docker Container Fixture Factory Source: https://context7.com/jc2k/pytest-docker-tools/llms.txt Creates a pytest fixture that manages a Docker container's lifecycle. It automatically starts the container before tests and removes it afterward, supporting various docker-py parameters and readiness checks. ```APIDOC ## container - Docker Container Fixture Factory ### Description Manages a Docker container's lifecycle within pytest fixtures. It handles starting, monitoring for readiness, and cleaning up containers, supporting all `docker-py` container.run() parameters. ### Method Fixture Factory ### Endpoint N/A (Fixture Factory) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pytest_docker_tools import container my_container = container( image='my-image:latest', ports={'80/tcp': None}, environment={'MY_VAR': 'my_value'}, scope='function', timeout=60 ) ``` ### Response #### Success Response (Fixture Object) - **status** (string) - The current status of the Docker container. - **logs** (string) - Captured logs from the Docker container. - **ports** (dict) - A dictionary mapping container ports to host ports. - **ips** (object) - An object containing IP addresses associated with the container. - **get_addr**(port_mapping) (function) - Helper to get the host IP and port for a given container port mapping. #### Response Example ```json { "status": "running", "logs": "Container logs...", "ports": { "80/tcp": [32768] }, "ips": { "primary": "172.17.0.2" } } ``` ``` -------------------------------- ### Get Container Address with Port Mapping Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Shows how to use the `get_addr` helper method on a container object to retrieve the correct IP address and port for accessing a service. This is crucial for handling network differences between development and CI environments, especially when ports are mapped to the host. ```python from pytest_docker_tools import container apiserver = container( image='{apiserver_image.id}', ports={'8080/tcp': None} ) def test_connect_my_service(apiserver): ip, port = apiserver.get_addr('8080/tcp') # ... connect to ip:port ... ``` -------------------------------- ### Reference Docker Image Fixture Dynamically in Container Definition Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Demonstrates referencing a Docker image fixture's ID dynamically within a container definition. The `fetch` factory is used to get the image, and its ID is then used for the container's image. ```python from pytest_docker_tools import container, fetch cache_image = fetch(repository='memcached:latest') cache = container( name='my_cache_container', image='{cache_image.id}', environment={ 'foo': 'bar', 'mode': 'prod' } ) ``` -------------------------------- ### Test Microservice Using Docker Container Fixture in Python Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md This example shows how to write pytest tests that utilize the `apiserver` fixture defined using `pytest-docker-tools`. The tests demonstrate connecting to the exposed port of the running API server container and verifying its functionality. It also includes a test that restarts the container and re-verifies connectivity, showcasing the ability to interact with and manage container state within tests. ```python # test_smoketest.py import socket def test_my_frobulator(apiserver): sock = socket.socket() sock.connect(('127.0.0.1', apiserver.ports['8080/tcp'][0])) def test_my_frobulator_works_after_restart(apiserver): apiserver.restart() sock = socket.socket() sock.connect(('127.0.0.1', apiserver.ports['8080/tcp'][0])) ``` -------------------------------- ### Creating API Client Fixtures with Docker Containers Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Shows how to define a pytest fixture for an API client that depends on Docker containers. This fixture encapsulates the setup logic for connecting to a service running inside a Docker container, simplifying test code by allowing direct use of the client. It uses `pytest_docker_tools.build` and `pytest_docker_tools.container` to set up the necessary services. ```python # conftest.py from http.client import HTTPConnection import pytest from pytest_docker_tools import build, container fakedns_image = build( path='examples/resolver-service/dns', ) fakedns = container( image='{fakedns_image.id}', environment={ 'DNS_EXAMPLE_COM__A': '127.0.0.1', } ) apiserver_image = build( path='examples/resolver-service/api', ) apiserver = container( image='{apiserver_image.id}', ports={ '8080/tcp': None, }, dns=['{fakedns.ips.primary}'] ) @pytest.fixture def apiclient(apiserver): port = apiserver.ports['8080/tcp'][0] return HTTPConnection(f'localhost:{port}') # test_the_test_client.py import json def test_api_server(apiclient): apiclient.request('GET', '/') response = apiclient.getresponse() assert response.status == 200 result = json.loads(response.read()) assert result['result'] == '127.0.0.1' ``` -------------------------------- ### Inspect Container Logs Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Provides an example of how to retrieve and inspect the logs generated by a Docker container using the 'logs()' method on the container object. The test asserts that a specific string is present within the container's output logs, useful for verifying application behavior or startup messages. ```python from pytest_docker_tools import container, fetch redis_image = fetch(repository='redis:latest') redis = container( image='{redis_image.id}', ports={'6379/tcp': None}, ) def test_logs(redis): assert 'oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo' in redis.logs() ``` -------------------------------- ### Override Fixtures in Test Modules Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md This example shows how to override a fixture defined in `conftest.py` within a specific test module. By redefining the `example_com_a` fixture in `test_smoketest_alternate.py`, the tests in that module will use the new value, demonstrating how to customize container configurations for individual test suites without affecting other tests. ```python # test_smoketest_alternate.py import json import pytest @pytest.fixture def example_com_a(): return '192.168.192.168' def test_api_server(apiclient): apiclient.request('GET', '/') response = apiclient.getresponse() assert response.status == 200 result = json.loads(response.read()) assert result['result'] == '192.168.192.168' ``` -------------------------------- ### Overriding Docker Fixtures in Pytest Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Illustrates fixture overloading in pytest-docker-tools, allowing specific Docker container fixtures to be redefined within a test module. This is useful for testing edge cases or alternative configurations without altering the main `conftest.py`. The example shows redefining a DNS container fixture to test different IP address responses. ```python # conftest.py from http.client import HTTPConnection import pytest from pytest_docker_tools import build, container fakedns_image = build( path='examples/resolver-service/dns', ) fakedns = container( image='{fakedns_image.id}', environment={ 'DNS_EXAMPLE_COM__A': '127.0.0.1', } ) apiserver_image = build( path='examples/resolver-service/api', ) apiserver = container( image='{apiserver_image.id}', ports={ '8080/tcp': None, }, dns=['{fakedns.ips.primary}'] ) @pytest.fixture def apiclient(apiserver): port = apiserver.ports['8080/tcp'][0] return HTTPConnection(f'localhost:{port}') # test_smoketest_alternate.py import json from pytest_docker_tools import container fakedns = container( image='{fakedns_image.id}', environment={ 'DNS_EXAMPLE_COM__A': '192.168.192.168', } ) def test_api_server(apiclient): apiclient.request('GET', '/') response = apiclient.getresponse() assert response.status == 200 result = json.loads(response.read()) assert result['result'] == '192.168.192.168' ``` -------------------------------- ### Test API Server Response Using Docker Client Fixture in Python Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md This Python test snippet demonstrates how to use a custom `apiclient` fixture, which itself depends on the `apiserver` fixture from `pytest-docker-tools`. The test makes a GET request to the root path of the API server and asserts that the response status is 200 and the JSON payload matches the expected output. This highlights how `pytest-docker-tools` facilitates integration testing by managing dependencies between services. ```python # test_smoketest.py import json def test_api_server(apiclient): apiclient.request('GET', '/') response = apiclient.getresponse() assert response.status == 200 assert json.loads(response.read()) == {'result': '127.0.0.1'} ``` -------------------------------- ### Seed a Docker Volume with Initial Content Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Shows how to initialize a Docker volume with specific content using the `initial_content` argument of the `volume()` fixture factory. This allows pre-populating volumes with data, such as buckets and files for services like Minio. The content is provided as a dictionary where keys are paths and values are the content. ```python from pytest_docker_tools import container, fetch, volume minio_image = fetch(repository='minio/minio:latest') minio_volume = volume( initial_content={ 'bucket-1': None, 'bucket-2/example.txt': b'Test file 1', } ) minio = container( image='{minio_image.id}', command=['server', '/data'], volumes={ '{minio_volume.name}': {'bind': '/data'}, }, environment={ 'MINIO_ACCESS_KEY': 'minio', 'MINIO_SECRET_KEY': 'minio123', }, ) def test_volume_is_seeded(minio): files = minio.get_files('/data') assert files['data/bucket-2/example.txt'] == b'Test file 1' assert files['data/bucket-1'] == None ``` -------------------------------- ### Fetch and Build Docker Images with pytest-docker-tools Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Demonstrates how to use the 'fetch' fixture factory to pull Docker images from a repository and the 'build' fixture factory to build images from local source code. These factories simplify Docker image management within pytest tests. ```python from pytest_docker_tools import build, image, fetch my_image = fetch(repository='redis:latest') my_image_2 = build( path='db' ) ``` -------------------------------- ### Access Primary IP Address of a Container Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Shows how to retrieve the primary IP address of a container attached to a single network. The 'redis.ips.primary' property provides easy access to this IP. The example uses 'ipaddress.ip_address' to validate that the retrieved value is a correct IP address. ```python import ipaddress # Assuming 'redis' container is defined with a network attachment in conftest.py def test_get_service_ip(redis): # This will raise a ValueError if not a valid ip ipaddress.ip_address(redis.ips.primary) ``` -------------------------------- ### Memcached Session Scope Test (Python) Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Tests memcached functionality using a session-scoped container. It establishes a socket connection, sends SET and GET commands, and asserts the response. This snippet requires a running memcached service accessible via the provided port. ```python import socket def test_session_1(memcache_session): sock = socket.socket() sock.connect(('127.0.0.1', memcache_session.ports['11211/tcp'][0])) sock.sendall(b'set mykey 0 600 4\r\ndata\r\n') sock.sendall(b'get mykey\r\n') assert sock.recv(1024) == b'STORED\r\nVALUE mykey 0 4\r\ndata\r\nEND\r\n' sock.close() def test_session_2(memcache_session): sock = socket.socket() sock.connect(('127.0.0.1', memcache_session.ports['11211/tcp'][0])) sock.sendall(b'set mykey 0 600 4\r\ndata\r\n') sock.sendall(b'get mykey\r\n') assert sock.recv(1024) == b'STORED\r\nVALUE mykey 0 4\r\ndata\r\nEND\r\n' sock.close() ``` -------------------------------- ### Creating and Using Docker Networks with pytest-docker-tools Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Shows how to create a dedicated Docker network for tests using the 'network' fixture factory. It also demonstrates how to link containers to this network and use fetched images within the defined network environment. ```python from pytest_docker_tools import container, fetch, network frontend_network = network() redis_image = fetch(repository='redis:latest') redis = container( image='{redis_image.id}', network='{frontend_network.name}', ) ``` -------------------------------- ### Create Docker Volume Fixture Source: https://context7.com/jc2k/pytest-docker-tools/llms.txt Creates a Docker volume fixture that can be optionally pre-populated with initial content. It supports all docker-py volume creation parameters and allows seeding volumes with files and directories via an `initial_content` dictionary. The default scope is function, ensuring a new volume for each test. ```python from pytest_docker_tools import container, fetch, volume # Create an empty volume data_volume = volume( scope='function', # New volume per test (default) ) ``` -------------------------------- ### Build and Use Container from Dockerfile in Code Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Demonstrates creating a Docker image directly from a Dockerfile defined as a byte string in Python code, using the 'build' fixture. Subsequently, a container is created using this dynamically built image. The test verifies that the container is in a 'running' state. ```python import io from pytest_docker_tools import build, container dockerfile = io.BytesIO(b""" FROM alpine:3.12 RUN apk --no-cache add python3 CMD ["tail", "-f", "/dev/null"] """) image = build(fileobj=dockerfile) container = container(image='{image.id}') def test_container_starts(container): assert container.status == "running" ``` -------------------------------- ### Executing Docker Build Commands for Stages Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md This bash snippet demonstrates the underlying Docker commands executed when using the 'stages' parameter in the `build` fixture factory. It shows how to build and tag specific build stages of a Docker image. ```bash docker build --target builder --tag localhost/myproject:builder . docker build --tag localhost/myproject:latest . ``` -------------------------------- ### Container Wrapper Methods for Testing Source: https://context7.com/jc2k/pytest-docker-tools/llms.txt Introduces the Container wrapper object, which is returned by the `container` fixture. This object provides convenient methods for interacting with running Docker containers, such as checking readiness, retrieving logs, executing commands, extracting files, and accessing exposed ports. It's essential for writing robust integration tests. ```python from pytest_docker_tools import build, container from pytest_docker_tools import wrappers import random # Example usage of container wrapper methods would follow here. # These methods might include: # - container_instance.wait_for_log(pattern) # - container_instance.run_command(command) # - container_instance.get_files(path) # - container_instance.get_text(path) # - container_instance.ports['/tcp'][0] # - container_instance.status ``` -------------------------------- ### Build and Define Docker Container with Dependencies Source: https://context7.com/jc2k/pytest-docker-tools/llms.txt Builds a Docker image for an API server and then defines a container named 'apiserver'. This container depends on the built image and configures port mapping and DNS settings, utilizing a parameterized fixture for DNS resolution. The '{apiserver_image.id}' and '{fakedns.ips.primary}' syntax demonstrates dependency resolution and interpolation. ```python from pytest_docker_tools import build, container apiserver_image = build(path='examples/resolver-service/api') apiserver = container( image='{apiserver_image.id}', ports={'8080/tcp': None}, dns=['{fakedns.ips.primary}'] # Uses parameterized fixture ) ``` -------------------------------- ### Run Linters and Tests with Poetry Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Command to execute linters and tests for the project using Poetry. This script ensures code quality and test coverage. ```bash poetry run ./scripts/tests.sh ``` -------------------------------- ### Custom Container Wrapper with Advanced Methods Source: https://context7.com/jc2k/pytest-docker-tools/llms.txt Defines a custom container wrapper class inheriting from wrappers.Container, adding a custom 'ready' method for more specific readiness checks (e.g., checking logs) and a 'client' method to easily create HTTP connections to the container. This allows for more tailored container management within tests. ```python from pytest_docker_tools import build, container, wrappers # Custom wrapper class with additional methods class CustomContainer(wrappers.Container): def ready(self): # Custom readiness check (called repeatedly until returns True) if super().ready(): # Add custom logic, e.g., check for log message logs = self.logs() return 'Server started' in logs return False def client(self): # Custom helper method from http.client import HTTPConnection port = self.ports['8080/tcp'][0] return HTTPConnection(f'localhost:{port}') apiserver_image = build(path='examples/resolver-service/api') apiserver = container( image='{apiserver_image.id}', ports={'8080/tcp': None}, wrapper_class=CustomContainer, ) nginx_image = build(path='./nginx') nginx = container( image='{nginx_image.id}', ports={'80/tcp': None}, ) def test_container_wrapper_methods(nginx): # Basic properties assert nginx.id is not None assert nginx.name is not None assert nginx.status == "running" # Access environment variables env_vars = nginx.env assert isinstance(env_vars, dict) # Execute command inside container exit_code, output = nginx.exec_run('nginx -v') assert exit_code == 0 assert b'nginx' in output # Get container logs logs = nginx.logs() assert isinstance(logs, str) # Retrieve files from container files = nginx.get_files('/etc/nginx') assert 'etc/nginx/nginx.conf' in files # Get text files text_files = nginx.get_text('/etc/nginx/nginx.conf') # Restart container and wait for readiness nginx.restart(timeout=10) assert nginx.status == "running" # Get IP address ip = nginx.ips.primary assert ip is not None # Get ephemeral port ports = nginx.ports['80/tcp'] assert len(ports) == 1 # Environment-aware addressing (works in CI containers too) ip, port = nginx.get_addr('80/tcp') def test_custom_wrapper_class(apiserver): # Use custom method from wrapper client = apiserver.client() client.request('GET', '/') response = client.getresponse() assert response.status == 200 ``` -------------------------------- ### build - Docker Image Build Fixture Factory Source: https://context7.com/jc2k/pytest-docker-tools/llms.txt Builds a Docker image from a Dockerfile, returning a session-scoped fixture. It supports various `docker-py` images.build() parameters and caching for efficiency. ```APIDOC ## build - Docker Image Build Fixture Factory ### Description Builds a Docker image from a Dockerfile, typically providing a session-scoped fixture that is cached across tests. Supports `docker-py` images.build() parameters and multi-stage builds. ### Method Fixture Factory ### Endpoint N/A (Fixture Factory) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from pytest_docker_tools import build my_image = build( path='./my-dockerfile-directory', tag='my-custom-image:latest', dockerfile='Dockerfile.dev', buildargs={'NODE_VERSION': '18'}, stages={'builder': 'my-image:builder'} ) ``` ### Response #### Success Response (Image Object) - **id** (string) - The ID of the built Docker image. - **tags** (list) - A list of tags associated with the Docker image. #### Response Example ```json { "id": "sha256:abcdef123456...", "tags": ["my-custom-image:latest"] } ``` ``` -------------------------------- ### Container with Dependencies on Fetched Images Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Shows how to create a container that depends on an image previously fetched using the 'fetch' fixture. This ensures the image is available before the container is created. It also demonstrates how to reference the fetched image ID using string interpolation. The container status is checked in a test function. ```python from pytest_docker_tools import container, fetch redis_image = fetch(repository='redis:latest') redis = container(image='{redis_image.id}') def test_container_starts(redis): assert redis.status == "running" ``` -------------------------------- ### Use fxtr Helper to Reference Non-String Fixture for Container Environment Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Illustrates using the `fxtr` helper function from `pytest_docker_tools` to reference a non-string fixture for the `environment` argument of a Docker container, simplifying fixture referencing. ```python import pytest from pytest_docker_tools import container, fetch, fxtr cache_image = fetch(repository='memcached:latest') @pytest.fixture() def memcached_env(): yield {'foo': 'bar', 'mode': 'prod'} cache = container( name='my_cache_container', image='{cache_image.id}', environment=fxtr('memcached_env') ) ``` -------------------------------- ### Define Docker Build and Container Fixtures in Python Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md This snippet demonstrates how to use `pytest_docker_tools` to define fixtures for building Docker images and creating containers. It shows how to specify the build path for an image, configure environment variables for a container, map ports, and set DNS resolution using other fixtures. The fixtures are defined in `conftest.py` and can be injected into test functions. ```python # conftest.py from http.client import HTTPConnection import pytest from pytest_docker_tools import build, container fakedns_image = build( path='examples/resolver-service/dns', ) fakedns = container( image='{fakedns_image.id}', environment={ 'DNS_EXAMPLE_COM__A': '127.0.0.1', } ) apiserver_image = build( path='examples/resolver-service/api', ) apiserver = container( image='{apiserver_image.id}', ports={ '8080/tcp': None, }, dns=['{fakedns.ips.primary}'] ) @pytest.io.fixture def apiclient(apiserver): port = apiserver.ports['8080/tcp'][0] return HTTPConnection(f'localhost:{port}') ``` -------------------------------- ### Create a Docker Volume with pytest-docker-tools Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Demonstrates how to create a Docker volume with a lifecycle tied to pytest tests using the `volume()` fixture factory. This is useful for ensuring container data is isolated and managed by the test suite. It supports parameters from docker-py's volume create method. ```python from pytest_docker_tools import volume backend_storage = volume() ``` -------------------------------- ### Build Docker Image with pytest Fixture Factory Source: https://context7.com/jc2k/pytest-docker-tools/llms.txt Builds a Docker image from a Dockerfile using a session-scoped pytest fixture. It supports all docker-py images.build() parameters, including path, dockerfile, buildargs, and target. The image is built once per pytest session and cached. Multi-stage builds are supported by tagging intermediate stages. ```python from pytest_docker_tools import build, container import io # Build from a directory containing a Dockerfile my_image = build( path='./my-service', tag='localhost/myproject:latest', buildargs={'VERSION': '1.0.0'}, rm=True, # Remove intermediate containers (default) scope='session', # Build once per test session (default) ) # Build multi-stage image with tagged stages my_image_multistage = build( path='./my-service', tag='localhost/myproject:latest', stages={ 'builder': 'localhost/myproject:builder', 'dependencies': 'localhost/myproject:dependencies', } ) ``` -------------------------------- ### Create Docker Network Fixture Source: https://context7.com/jc2k/pytest-docker-tools/llms.txt Creates a Docker network fixture for connecting containers, supporting various docker-py network creation parameters. By default, a new network is created for each test and removed afterward, ensuring network isolation. Custom configurations for subnets and gateways are also supported. ```python from pytest_docker_tools import container, fetch, network import ipaddress # Create a custom network backend_network = network( driver='bridge', scope='function', # New network per test (default) ) # Create network with custom configuration frontend_network = network( driver='bridge', ipam={ 'Config': [{ 'Subnet': '172.20.0.0/16', 'Gateway': '172.20.0.1', }] } ) redis_image = fetch(repository='redis:latest') # Attach containers to the network redis = container( image='{redis_image.id}', network='{backend_network.name}', ) app_image = fetch(repository='python:3.9-slim') app = container( image='{app_image.id}', network='{backend_network.name}', command=['python3', '-m', 'http.server', '8000'], ports={'8000/tcp': None}, ) def test_network_isolation(backend_network, redis): # Verify container is on the network assert redis.ips.primary is not None ipaddress.ip_address(redis.ips.primary) def test_container_ip_by_network(backend_network, redis): # Access IP by specific network ip = redis.ips[backend_network] ipaddress.ip_address(ip) assert ip is not None def test_containers_can_communicate(redis, app): # Both containers on same network can communicate exit_code, output = app.exec_run(f'ping -c 1 {redis.ips.primary}') assert exit_code == 0 ``` -------------------------------- ### Define Docker Container Resource with Parameters Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Defines a Docker container resource using the `container` factory from `pytest_docker_tools`. It specifies the container name, image, and environment variables. ```python from pytest_docker_tools import container cache = container( name='my_cache_container', image='1838567e84867e8498695403067879', environment={ 'foo': 'bar', 'mode': 'prod' } ) ``` -------------------------------- ### Fetch Docker Image from Registry Source: https://context7.com/jc2k/pytest-docker-tools/llms.txt Fetches a Docker image from a registry, supporting various parameters like repository and tag. This fixture is session-scoped, meaning the image is pulled only once per test session if it doesn't exist locally. It facilitates creating containers from fetched images. ```python from pytest_docker_tools import fetch, container import socket # Fetch specific tagged version memcache_image = fetch(repository='memcached:1.6-alpine') # Fetch latest version redis_image = fetch(repository='redis:latest') # Create containers from fetched images memcache = container( image='{memcache_image.id}', ports={'11211/tcp': None}, ) redis = container( image='{redis_image.id}', ports={'6379/tcp': None}, ) def test_memcache_connection(memcache): # Connect to memcache on ephemeral port sock = socket.socket() port = memcache.ports['11211/tcp'][0] sock.connect(('127.0.0.1', port)) # Send memcache commands sock.sendall(b'set mykey 0 600 4\r\ndata\r\n') sock.sendall(b'get mykey\r\n') response = sock.recv(1024) assert b'VALUE mykey 0 4\r\ndata\r\nEND\r\n' in response sock.close() def test_redis_connection(redis): import socket sock = socket.socket() port = redis.ports['6379/tcp'][0] sock.connect(('127.0.0.1', port)) # Redis PING command sock.sendall(b'*1\r\n$4\r\nPING\r\n') response = sock.recv(1024) assert b'+PONG' in response sock.close() ``` -------------------------------- ### Tagging Docker Image Stages for Caching with pytest-docker-tools Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Illustrates how to tag Docker images and their build stages using the 'build' fixture factory to improve caching efficiency with `docker image prune`. This ensures that tagged images, including multi-stage builds, are not accidentally removed. ```python from pytest_docker_tools import build, image, fetch my_image = build( path='db', tag='localhost/myproject:latest', stages={ 'builder': 'localhost/myproject:builder' } ) ``` -------------------------------- ### Access Docker Client Instance in Pytest Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Illustrates how to obtain an instance of the official Docker client within a pytest test using the `docker_client` fixture. This allows for direct interaction with the Docker API. Care must be taken as resources created this way are not automatically removed, and xdist compatibility needs consideration. ```python def test_container_created(docker_client, fakedns): for c in docker_client.containers.list(ignore_removed=True): if c.id == fakedns.id: # Looks like we managed to start one! break else: assert False, 'Looks like we failed to start a container' ``` -------------------------------- ### HTTP Client Fixture for API Server Testing Source: https://context7.com/jc2k/pytest-docker-tools/llms.txt Creates an 'apiclient' fixture that establishes an HTTP connection to the 'apiserver' container. It dynamically determines the host port from the 'apiserver' fixture and creates an HTTP connection object. This fixture simplifies making requests to the API server within tests. ```python from http.client import HTTPConnection @pytest.fixture def apiclient(apiserver): port = apiserver.ports['8080/tcp'][0] return HTTPConnection(f'localhost:{port}') ``` -------------------------------- ### Conditional Docker Image Source (Env Var or Build) Source: https://context7.com/jc2k/pytest-docker-tools/llms.txt Creates a Docker image fixture that can either use an image ID from an environment variable or build the image from a local Dockerfile. This allows for testing against pre-built images in CI or locally built images during development. It uses the `image_or_build` fixture factory. ```python from pytest_docker_tools import image_or_build, container import os # Use IMAGE_ID from environment if available, otherwise build from source my_service_image = image_or_build( environ_key='IMAGE_ID', # Look for this environment variable path='./my-service', # Build from this path if env var not set tag='localhost/my-service:dev', ) my_service = container( image='{my_service_image.id}', ports={'8080/tcp': None}, ) def test_service_with_conditional_image(my_service): # Test works whether image was built or pulled assert my_service.status == "running" # Run with pre-built image: # IMAGE_ID=my-registry/my-service:v1.2.3 pytest test_service.py # Run with local build: # pytest test_service.py ``` -------------------------------- ### Reference Non-String Fixture for Container Environment Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Shows how to reference a non-string fixture (a dictionary) for the `environment` argument of a Docker container. This is achieved by either importing the fixture or using the `fxtr` helper. ```python import pytest from pytest_docker_tools import container, fetch, fxtr cache_image = fetch(repository='memcached:latest') @pytest.fixture() def memcached_env(): yield {'foo': 'bar', 'mode': 'prod'} cache = container( name='my_cache_container', image='{cache_image.id}', environment=memcached_env ) ``` -------------------------------- ### Conditionally Use Local Build or Existing Docker Image Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Demonstrates the `image_or_build` utility, which intelligently selects between building a Docker image from a specified path or using an existing image identified by an environment variable. This is useful for testing locally built images versus pre-existing images on CI platforms. ```python from pytest_docker_tools import image_or_build image = image_or_build( environ_key='IMAGE_ID', path='examples/resolver-service/dns', ) def test_image(image): assert image.attrs['Os'] == 'linux' ``` -------------------------------- ### Create a Docker Container using an Image Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md This snippet demonstrates the basic usage of the 'container' fixture factory to create a Docker container from a specified image. The container is automatically managed (created and deleted) by pytest. The default scope is 'function', meaning a new container is created for each test function. ```python from pytest_docker_tools import container my_microservice_backend = container(image='redis:latest') ``` -------------------------------- ### Build Docker Image from in-memory Dockerfile Source: https://context7.com/jc2k/pytest-docker-tools/llms.txt Builds a Docker image directly from a Dockerfile provided as a file-like object in memory. This is useful for creating temporary images without needing a physical Dockerfile. It returns an image object that can be used to create containers. ```python from pytest_docker_tools import build, container import io dockerfile = io.BytesIO(b""" FROM alpine:3.12 RUN apk --no-cache add python3 CMD ["tail", "-f", "/dev/null"] """) inline_image = build(fileobj=dockerfile, rm=True) inline_container = container(image='{inline_image.id}') def test_image_built(my_image): # Image is built before test runs assert my_image.id is not None assert my_image.attrs['Os'] == 'linux' def test_container_from_built_image(inline_container): # Container created from inline-built image assert inline_container.status == "running" # Execute command inside container exit_code, output = inline_container.exec_run('python3 --version') assert exit_code == 0 assert b'Python 3' in output ``` -------------------------------- ### Configure Container Creation Timeout Source: https://github.com/jc2k/pytest-docker-tools/blob/main/README.md Illustrates how to set a custom timeout for container creation using the 'timeout' parameter in the 'container' factory. If the container does not become ready within the specified duration, the test will fail. This is useful for controlling how long pytest waits for container initialization. ```python from pytest_docker_tools import container, fetch redis_image = fetch(repository='redis:latest') redis = container(image='{redis_image.id}', timeout=30) def test_container_starts(redis): assert redis.status == "running" ``` -------------------------------- ### Test API Server with Parameterized DNS Configurations Source: https://context7.com/jc2k/pytest-docker-tools/llms.txt Tests the 'apiserver' functionality using the 'apiclient' fixture. This test executes twice due to the parameterized 'fakedns' fixture, validating that the API server responds correctly and that the returned IP address is valid. It uses standard Python libraries for HTTP requests and IP address validation. ```python # test_parameterized.py import ipaddress import json def test_api_server(apiclient): # This test runs TWICE - once for each fakedns configuration apiclient.request('GET', '/') response = apiclient.getresponse() assert response.status == 200 result = json.loads(response.read()) # Validates it's a valid IP (either 127.0.0.1 or 192.168.192.168) ipaddress.ip_address(result['result']) ```