I’m using Docker to containerize a Python application and am looking for the best way to include unit tests in the container. I have copied the Dockerfile I’m using below.
FROM python:3.6.5
# working directory
WORKDIR /usr/src/app
# copy requirement file to working directory
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
ENTRYPOINT ["python", "./run.py"]
What is the best way to run unit tests in my Docker container? Should I build a separate image for them?
You can run unit tests in the same Docker image by adding the necessary commands to the Dockerfile. Here’s an updated version of the Dockerfile that runs unit tests before starting the application:
FROM python:3.6.5
# working directory
WORKDIR /usr/src/app
# copy requirement file to working directory
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
# run unit tests
RUN python -m unittest discover
ENTRYPOINT ["python", "./run.py"]
This will run all unit tests in the project before starting the application. If any of the tests fail, the Docker build will fail and you won’t be able to run the container.