1. 概述
在软件开发中,测试是不可或缺的一环,它确保代码在部署到生产环境前能按预期工作。虽然 GitLab CI 这样的持续集成平台通常用于在远程服务器上自动化测试流程,但在某些场景下,我们希望能在本地运行这些测试,以加快开发和调试速度。
本文将介绍 如何使用 GitLab CI 在本地运行测试,并介绍三种主流工具:gitlab-ci-local
、GitLab Emulator
和 GitLab Runner
。
2. 使用 gitlab-ci-local
gitlab-ci-local
是一个可以让我们在本地运行 GitLab CI 任务和流水线的工具,非常适合本地调试。
2.1. 安装配置
以一个简单的 .gitlab-ci.yml
文件为例:
unit_test:
image: python:latest
script:
- echo "running tests ..."
该配置定义了一个名为 unit_test
的任务,使用 python:latest
镜像执行测试脚本。
在 macOS 上安装 gitlab-ci-local
:
brew install gitlab-ci-local
验证安装:
gitlab-ci-local --version
输出类似:
4.56.2
2.2. 本地运行测试
列出 .gitlab-ci.yml
中定义的任务:
gitlab-ci-local --list
输出示例:
name description stage when allow_failure needs
unit_test test on_success false
运行指定任务:
gitlab-ci-local unit_test
输出示例:
unit_test starting python:latest (test)
unit_test copied to docker volumes in 395 ms
unit_test $ echo "running tests ..."
unit_test > running tests ...
PASS unit_test
✅ 成功运行本地测试任务。
3. 使用 GitLab Emulator
GitLab Emulator
是另一个本地模拟 GitLab CI/CD 任务的工具。
3.1. 安装 gle
从源码安装:
git clone https://gitlab.com/cunity/gitlab-emulator.git && cd gitlab-emulator
./install-venv.sh
source ~/.gle/venv/bin/activate
验证安装:
gle --version
输出示例:
16.3.2
3.2. 本地运行测试
进入项目目录并列出任务:
cd demo && gle --list
输出:
unit_test
运行测试任务:
gle unit_test
输出日志显示任务成功执行,包括拉取镜像、启动容器、执行命令等过程。
✅ 成功通过 GitLab Emulator
模拟 CI 流程。
4. 使用 GitLab Runner
GitLab Runner
是 GitLab 官方提供的执行器,也可用于本地测试。
4.1. 安装 Runner
由于新版 gitlab-runner
已不支持 exec
命令,我们需安装特定版本(如 13.3.0):
sudo curl --output /usr/local/bin/gitlab-runner \
https://gitlab-runner-downloads.s3.amazonaws.com/v13.3.0/binaries/gitlab-runner-darwin-amd64
验证版本:
gitlab-runner --version | grep Version
输出:
Version: 13.3.0
4.2. 本地运行测试
执行指定任务:
gitlab-runner exec docker unit_test
输出示例:
Using docker image python:latest ...
$ echo "running tests ..."
running tests ...
Job succeeded
✅ 成功使用 gitlab-runner
本地运行 CI 任务。
5. 总结
本文介绍了三种在本地运行 GitLab CI 测试的方法:
工具名称 | 特点说明 |
---|---|
gitlab-ci-local |
简洁易用,适合快速运行本地任务 |
GitLab Emulator |
支持完整 CI/CD 行为模拟,适合复杂调试 |
GitLab Runner |
官方工具,真实还原 CI 行为,但需注意版本兼容性 |
📌 踩坑提醒:
gitlab-runner
新版本已移除exec
命令,建议使用 13.3.0 版本;gitlab-ci-local
和GitLab Emulator
都依赖 Docker,确保本地已安装并运行;- 本地运行 CI 任务时,镜像拉取可能较慢,建议提前
docker pull
缓存。
通过这些工具,我们可以更高效地进行本地测试与调试,避免频繁提交触发远程 CI,提升开发效率。