0
0
PyTesttesting~5 mins

Docker-based test execution in PyTest

Choose your learning style9 modes available
Introduction

Docker lets you run tests in a clean, controlled space. This helps avoid problems from different computers or setups.

You want to run tests on any computer without setup issues.
You need to test software that depends on specific versions of tools or libraries.
You want to share your tests with teammates and be sure they run the same way.
You want to automate tests in a continuous integration system.
You want to keep your main computer clean from test dependencies.
Syntax
PyTest
docker run [OPTIONS] IMAGE [COMMAND]

docker run starts a container from an image.

You can add options like -v to share folders or -it for interactive mode.

Examples
This runs pytest inside a Python 3.12 container. It shares your current folder with the container and runs tests there.
PyTest
docker run -v $(pwd):/app -w /app python:3.12 pytest test_sample.py
This runs all tests in the current folder and removes the container after finishing.
PyTest
docker run --rm -v $(pwd):/tests -w /tests python:3.12 pytest
Sample Program

This simple test checks if 1 + 1 equals 2. The Docker command runs pytest inside a Python 3.12 container, using your current folder.

PyTest
# test_sample.py

def test_addition():
    assert 1 + 1 == 2

# Run command:
# docker run --rm -v $(pwd):/app -w /app python:3.12 pytest test_sample.py
OutputSuccess
Important Notes

Always share your test folder with the container using -v so tests can access your files.

Use --rm to clean up containers after tests finish.

Make sure the Docker image has all needed tools for your tests.

Summary

Docker helps run tests in a clean, repeatable environment.

You run tests inside containers using docker run with volume sharing.

This avoids setup problems and makes tests portable.