3. 使用GitLab CI运行单元测试
任务目标
为Python项目编写.gitlab-ci.yml配置文件,使得每次代码推送到GitLab仓库时,自动触发CI流水线并运行pytest单元测试。通过本案例,你将掌握GitLab CI最基本的流水线定义方式。
环境准备
本案例需要以下环境,任选其一即可:
- 一个可用的GitLab实例(本地部署或gitlab.com),且项目已开启Shared Runners或已注册特定Runner;
- 本地Python 3.8+环境(用于在推送前验证测试可通过)。
项目结构
在项目根目录下准备以下文件:
my-python-project/
├── .gitlab-ci.yml
├── requirements.txt
├── calculator.py
└── tests/
└── test_calculator.py
完整实现
calculator.py — 被测模块:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
tests/test_calculator.py — 测试用例:
from calculator import add, subtract
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
def test_subtract():
assert subtract(5, 3) == 2
assert subtract(0, 4) == -4
requirements.txt — 依赖声明:
pytest==7.4.0
.gitlab-ci.yml — CI流水线配置(核心文件):
stages:
- test
test-job:
stage: test
image: python:3.10-slim
script:
- pip install -r requirements.txt
- pytest tests/ -v
only:
- main
- merge_requests
运行与验证
本地验证(推送前):
pip install -r requirements.txt
pytest tests/ -v
预期输出:两个测试用例均通过(2 passed)。
推送并触发CI:
git add .
git commit -m "Add GitLab CI config"
git push origin main
验证方法:
- 推送后进入GitLab项目页面 → CI/CD → Pipelines,应看到一条新的流水线记录;
- 点击该流水线,观察
test-job任务状态; - 任务执行成功后,点击任务查看日志,应能看到
pytest输出2 passed; - 若流水线失败,展开日志查看具体报错(常见为依赖安装失败或测试断言失败)。
关键说明
image指定CI运行环境为Python 3.10精简镜像,无需额外安装Python;only限定流水线仅在推送到main分支或创建/更新合并请求时触发,避免其他分支提交产生无效构建;- 若项目使用私有依赖源,需在
pip install前增加PIP_INDEX_URL环境变量配置,本案例不涉及。