如何在GitLab CI/CD流水线中使用Docker Compose运行API端点测试
这个需求完全可以实现,核心需要解决两个核心问题:一是服务启动后的就绪等待逻辑,二是测试结果与流水线、服务部署的状态绑定。以下是可直接落地的修改方案:
1. 修改docker-compose.yml配置
首先将compose版本升级到支持健康检查的3.8版本,给数据库、应用服务增加健康检查规则,同时配置测试服务的启动依赖条件:
version: "3.8" services: app: build: context: ./app dockerfile: Dockerfile ports: - "81:80" volumes: - ./app:/app/app depends_on: postgres: condition: service_healthy # 应用健康检查,可根据实际情况替换为你的健康检查接口 healthcheck: test: ["CMD", "curl", "-f", "http://localhost:80/"] interval: 2s timeout: 5s retries: 10 tests: build: context: ./tests dockerfile: Dockerfile # 测试服务依赖应用完全健康后再启动 depends_on: app: condition: service_healthy environment: # 传入测试用的HOST变量 - HOST=http://app:80 # 测试启动命令,根据你的测试框架调整,这里假设用pytest command: pytest /tests/test_select.py -v postgres: image: postgres:12-alpine ports: - "5432" environment: - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASS} - POSTGRES_DB=${POSTGRES_DB} volumes: - ./app/data:/var/lib/postgresql/data # 数据库健康检查,确保库可以正常连接 healthcheck: test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"] interval: 2s timeout: 5s retries: 10
2. 测试代码优化(可选,增强稳定性)
可以在测试逻辑中增加重试机制,避免偶发的网络波动导致测试失败,示例如下:
import requests from time import sleep def test_select(): url = f"{HOST}/select/" # 最多重试5次,每次间隔1秒 for _ in range(5): try: response = requests.get(url, timeout=3) if response.status_code == 200: break except requests.exceptions.RequestException: pass sleep(1) else: # 重试全部失败直接断言错误 assert False, "应用接口连续5次请求失败" status_code = response.status_code result_len = len(response.json().get("result")) assert status_code == 200 assert result_len != 0
如果使用pytest框架,也可以直接安装pytest-rerunfailures插件,在测试命令中加--reruns 3参数实现自动重试。
3. 调整.gitlab-ci.yml配置
拆分CI阶段,测试不通过则不会进入正式部署阶段:
stages: - build - test - deploy # 构建所有服务镜像 build: stage: build script: - sudo mkdir -p /home/app/ - sudo cp -r $PWD/* /home/app/ - cd /home/app/ - docker-compose build # 执行测试,测试失败则流水线自动终止 test: stage: test script: - cd /home/app/ - docker-compose run --rm tests after_script: # 测试完成后清理临时启动的服务 - cd /home/app/ - docker-compose down -v # 测试通过后正式启动服务 deploy: stage: deploy script: - cd /home/app/ - docker-compose up -d app postgres
补充说明
如果你的应用镜像没有预装curl,无法使用健康检查的curl命令,可以替换为wget或者在测试服务中引入wait-for-it脚本等待应用端口就绪,效果一致。
内容的提问来源于stack exchange,提问作者Z.Chorlev
相关产品推荐
相关产品推荐

