Вот минимальный рабочий пример тестов, запущенных с pytest-django
на этапе сборки контейнера.
тестовый скрипт
# test_server.py
import requests
def test_about_page(live_server):
response = requests.get(live_server.url + '/about')
response.raise_for_status()
Обратите внимание, что я использовал прибор live_server
, который запускает отдельный экземпляр сервера в другом потоке. Затем я могу получить доступ к адресу через live_server.url
в тесте.
Аналогично, изменения, которые необходимо внести в ваш тест, будут:
import requests
def test_demo(live_server):
response = requests.get(live_server.url + "/demo")
assert (response.status_code == 200)
образец Dockerfile
FROM ubuntu:latest
RUN apt update && apt install git python3-pip -y \
&& pip3 install pytest-django django requests
RUN git clone https://github.com/Microsoft/project-python-django-webapp
ADD test_server.py project-python-django-webapp
WORKDIR project-python-django-webapp
RUN pytest -v --ds=python_webapp_django.settings
Здесь не происходит никакой магии - я использовал пример проекта Django, найденного на Github , для запуска теста.
сборка контейнера
Сборка контейнера запускает сервер django и выполняет тест, завершаясь при успешном тестировании:
$ docker build -t so/example .
Sending build context to Docker daemon 3.072kB
Step 1/6 : FROM ubuntu:latest
---> 113a43faa138
Step 2/6 : RUN apt update && apt install git python3-pip -y && pip3 install pytest-django django requests
---> Using cache
---> fd7adbe53cc8
Step 3/6 : RUN git clone https://github.com/Microsoft/project-python-django-webapp
---> Using cache
---> df514c1343c9
Step 4/6 : ADD test_server.py project-python-django-webapp
---> 118f74e43370
Step 5/6 : WORKDIR project-python-django-webapp
Removing intermediate container f81db838a81d
---> c3d35262f37c
Step 6/6 : RUN pytest -v --ds=python_webapp_django.settings
---> Running in e6292f2ac3e8
============================= test session starts ==============================
platform linux -- Python 3.6.5, pytest-3.6.3, py-1.5.4, pluggy-0.6.0 -- /usr/bin/python3
cachedir: .pytest_cache
Django settings: python_webapp_django.settings (from command line option)
rootdir: /project-python-django-webapp, inifile:
plugins: django-3.3.2
collecting ... collected 1 item
test_server.py::test_index PASSED [100%]
=========================== 1 passed in 1.13 seconds ===========================
Removing intermediate container e6292f2ac3e8
---> c78c589b6d74
Successfully built c78c589b6d74
Successfully tagged so/example:latest