0
0
PyTesttesting~15 mins

Docker-based test execution in PyTest - Build an Automation Script

Choose your learning style9 modes available
Run pytest tests inside a Docker container
Preconditions (3)
Step 1: Create a Dockerfile that installs Python and pytest
Step 2: Copy the project files into the Docker image
Step 3: Build the Docker image with a tag 'pytest-test-image'
Step 4: Run a container from the image executing 'pytest' command
Step 5: Observe the test output in the console
✅ Expected Result: Tests run inside the Docker container and pytest output shows all tests passing or failing as expected
Automation Requirements - pytest
Assertions Needed:
Verify that pytest command runs successfully inside the container
Verify that test results are output to the console
Best Practices:
Use a Dockerfile to define the test environment
Use explicit commands to build and run the Docker container
Keep the Docker image lightweight by using official Python base images
Mount the project directory as a volume for easy test code updates
Automated Solution
PyTest
import subprocess
import sys


def test_run_pytest_in_docker():
    # Build the Docker image
    build_cmd = [
        "docker", "build", "-t", "pytest-test-image", "."
    ]
    build_process = subprocess.run(build_cmd, capture_output=True, text=True)
    assert build_process.returncode == 0, f"Docker build failed: {build_process.stderr}"

    # Run the Docker container to execute pytest
    run_cmd = [
        "docker", "run", "--rm", "pytest-test-image"
    ]
    run_process = subprocess.run(run_cmd, capture_output=True, text=True)
    print(run_process.stdout)
    assert run_process.returncode == 0, f"Pytest failed inside Docker: {run_process.stdout}\n{run_process.stderr}"


if __name__ == "__main__":
    test_run_pytest_in_docker()

This script automates running pytest tests inside a Docker container.

First, it builds a Docker image named pytest-test-image using the Dockerfile in the current directory. It checks if the build succeeded by verifying the return code.

Next, it runs a container from this image, which executes pytest tests. The output is captured and printed to the console.

Assertions check that both the Docker build and the pytest run complete successfully. If any step fails, the test fails with an error message showing the problem.

This approach ensures tests run in a clean, isolated environment defined by the Dockerfile.

Common Mistakes - 4 Pitfalls
Not checking the return code of the Docker build or run commands
Hardcoding absolute paths inside the Dockerfile or run command
Not printing or capturing the pytest output
Using a large base image without reason
Bonus Challenge

Now add data-driven testing by running pytest inside Docker with three different Python versions: 3.10, 3.11, and 3.12

Show Hint