我有一个简单的 Python 应用程序,它被 Docker 化了,其结构为:
/src
- server.py
- test_server.py
Dockerfile
requirements.txt
这是一个使用Linux为基础的Docker基础镜像,并使用FastAPI公开了server.py
的端点。
为了完整起见,server.py
看起来像这样:
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
number: int
app = FastAPI(title="Sum one", description="Get a number, add one to it", version="0.1.0")
@app.post("/compute")
async def compute(input: Item):
return {'result': input.number + 1}
测试应该使用pytest进行(参考https://fastapi.tiangolo.com/tutorial/testing/),需使用test_server.py
文件:
from fastapi.testclient import TestClient
from server import app
import json
client = TestClient(app)
def test_endpoint():
"""test endpoint"""
response = client.post("/compute", json={"number": 1})
values = json.loads(response.text)
assert values["result"] == 2
Dockerfile
看起来像这样:
FROM tiangolo/uvicorn-gunicorn:python3.7
COPY . /app
RUN pip install -r requirements.txt
WORKDIR /app/src
EXPOSE 8000
CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]
目前,如果我想在容器内的本地计算机上运行测试,一种方法是:
- 构建Docker容器
- 运行容器,通过
docker ps
获取其名称 - 运行
docker exec -it <mycontainer> bash
并执行pytest
以查看测试通过情况。
现在,我想在推送镜像到我的Docker注册表并触发发布流程之前,在Azure DevOps (Server) 中运行测试。如果这听起来没问题,如何正确地做呢?
到目前为止,我希望在构建管线中添加“PyTest”步骤能够神奇地工作:
我目前正在使用Linux代理,但该步骤失败了:
失败并不令人惊讶,因为(我认为)容器在构建后未运行,因此pytest也无法在其中运行 :(
解决此问题的另一种方法是在Dockerfile中包含pytest命令,并在发布管线中处理测试。但我想将测试与最终推送到注册表和部署的容器分离。
是否有标准方法在Azure DevOps中在Docker容器内运行pytest并获得图形报告?
Dockerfile
内容吗? - JPG