How to Use pytest with Docker: Simple Guide
To use
pytest with Docker, create a Dockerfile that installs Python, your app dependencies, and pytest. Then, build the Docker image and run the container to execute your tests inside it, ensuring a clean and consistent environment.Syntax
Here is the basic syntax to run pytest inside a Docker container:
FROM python:3.x: Use an official Python base image.WORKDIR /app: Set the working directory inside the container.COPY . /app: Copy your project files into the container.RUN pip install -r requirements.txt: Install dependencies including pytest.CMD ["pytest"]: Run pytest when the container starts.
Dockerfile
FROM python:3.10 WORKDIR /app COPY . /app RUN pip install -r requirements.txt CMD ["pytest"]
Example
This example shows a simple Dockerfile and a pytest test file. It demonstrates how to build the Docker image and run tests inside the container.
Dockerfile and Python
# Dockerfile FROM python:3.10 WORKDIR /app COPY . /app RUN pip install pytest CMD ["pytest"] # test_sample.py def test_addition(): assert 1 + 1 == 2 # Commands to build and run # docker build -t pytest-docker . # docker run --rm pytest-docker
Output
============================= test session starts ==============================
collected 1 item
test_sample.py . [100%]
============================== 1 passed in 0.01s ===============================
Common Pitfalls
Common mistakes when using pytest with Docker include:
- Not copying test files into the container, so pytest finds no tests.
- Forgetting to install pytest or dependencies inside the container.
- Running pytest outside the container instead of inside, losing environment consistency.
- Not cleaning up containers after tests, causing clutter.
Always verify your Dockerfile copies all necessary files and installs pytest.
Dockerfile
# Wrong Dockerfile snippet (missing pytest install) FROM python:3.10 WORKDIR /app COPY . /app RUN pip install -r requirements.txt CMD ["pytest"] # Correct Dockerfile snippet FROM python:3.10 WORKDIR /app COPY . /app RUN pip install -r requirements.txt pytest CMD ["pytest"]
Quick Reference
Tips for using pytest with Docker:
- Use official Python images for reliability.
- Keep your Dockerfile simple and focused on testing.
- Mount volumes if you want to run tests on local code changes without rebuilding.
- Use
--rmflag withdocker runto remove containers after tests. - Consider using Docker Compose for complex test environments.
Key Takeaways
Build a Docker image that installs pytest and your dependencies to run tests inside a container.
Always copy your test files into the Docker image so pytest can find and run them.
Run pytest inside Docker to ensure consistent test environments across machines.
Use the --rm flag with docker run to keep your system clean after tests.
Mount volumes for faster test iteration without rebuilding the image.