在构建 docker 时运行 Pytest

Runnnig Pytest while building docker compose up

我的项目结构如下所示。

app/
    docker-compose.yml
    test_some_pytest.py # this have some pytest code.
    tests.Dockerfile

我的 tests.Dockerfile 看起来如下。

from python:3.4-alpine
RUN python --version
RUN pip --version
COPY . /APP
WORKDIR /APP
RUN pip install pytest
RUN ["pytest"]

docker-compose.yml如下。

services
  tests:
    build:
      context: .
      dockerfile: tests.Dockerfile

当我运行docker-compose up --build tests。 pytest 也 运行 但可能在其他地方。它显示以下输出。

.
.
.
Removing intermediate container 96f9a8ba43d2
 ---> 82c89715d4c0
Step 7/7 : RUN ["pytest"]
 ---> Running in c30ee497e5f5
============================= test session starts ==============================
platform linux -- Python 3.4.10, pytest-4.6.11, py-1.10.0, pluggy-0.13.1
rootdir: /python-test-calculator
collected 0 items

========================= no tests ran in 0.00 seconds =========================
The command 'pytest' returned a non-zero code: 5
ERROR: Service 'tests' failed to build : Build failed

如果我完全按照写的方式使用你的tests.Dockerfile,下面的docker-compose.yaml

version: "3"

services:
  tests:
    build:
      context: .
      dockerfile: tests.Dockerfile

以及以下test_some_pytest.py

def test_something():
    assert True

它成功 运行s pytest 当我 运行 docker-compose build:

$ docker-compose build
Building tests

[...]

Step 7/7 : RUN ["pytest"]
 ---> Running in 8d8a1f44913f
============================= test session starts ==============================
platform linux -- Python 3.4.10, pytest-4.6.11, py-1.10.0, pluggy-0.13.1
rootdir: /APP
collected 1 item

test_some_pytest.py .                                                    [100%]

=========================== 1 passed in 0.01 seconds ===========================
Removing intermediate container 8d8a1f44913f
 ---> 055afd5b1f8d
Successfully built 055afd5b1f8d
Successfully tagged docker_tests:latest

从上面的输出可以看出pytest发现并成功运行1次测试