Ubuntu环境下GitLab测试实施指南
在Ubuntu上进行GitLab测试,核心是通过GitLab Runner执行.gitlab-ci.yml配置的自动化测试流程,覆盖从代码提交到测试结果反馈的全链路。以下是详细步骤:
若尚未部署GitLab,需先完成基础安装(以Ubuntu 22.04为例):
sudo apt update && sudo apt install -y curl openssh-server ca-certificates postfix(postfix配置选“Internet Site”)。curl -sS https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.deb.sh | sudo bash。sudo apt install gitlab-ce。/etc/gitlab/gitlab.rb中的external_url(如http://your-server-ip),运行sudo gitlab-ctl reconfigure初始化,sudo gitlab-ctl start启动服务。external_url,使用初始管理员账号root(密码5iveL!fe)登录,后续可添加用户/组。GitLab Runner是执行测试任务的代理,需单独安装并注册到GitLab项目:
curl https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh | sudo bash && sudo apt install gitlab-runner。docker run -d --name gitlab-runner --restart always -v /srv/gitlab-runner/config:/etc/gitlab-runner gitlab/gitlab-runner:latest。sudo gitlab-runner register,按提示输入:
http://your-server-ip);ubuntu-test-runner);test,用于筛选任务);shell或docker,docker需挂载/var/run/docker.sock)。在项目根目录创建.gitlab-ci.yml,定义测试流程的核心逻辑(以Python项目为例):
stages:
- test # 定义测试阶段
test_job:
stage: test
image: python:3.9 # 使用Python 3.9镜像
script:
- pip install -r requirements.txt # 安装依赖
- pytest tests/ --cov=./ # 运行pytest单元测试并生成覆盖率报告
rules:
- if: '$CI_PIPELINE_SOURCE == "push" || $CI_PIPELINE_SOURCE == "merge_request_event"' # 触发条件:代码推送或MR事件
when: always # 总是执行
artifacts:
reports:
cobertura: coverage.xml # 上传覆盖率报告(可选)
关键说明:
stages:定义流程阶段(如test),任务按阶段顺序执行;image:指定测试环境的Docker镜像(如python、node、maven);script:测试执行的具体命令(如pytest、mvn test);rules:控制任务触发条件(如仅在推送或MR时执行);artifacts:上传测试报告(如JUnit、Cobertura),便于在GitLab界面查看。将配置文件推送到GitLab仓库,Runner会自动触发CI/CD管道:
git add .gitlab-ci.yml
git commit -m "Add GitLab CI/CD configuration for testing"
git push origin main # 推送到main分支(或指定分支)
也可手动触发:进入GitLab项目→CI/CD→Pipelines→点击“Run pipeline”,选择分支和变量。
test_job,查看实时日志(包含测试命令输出、错误堆栈)和测试结果(如pytest的通过/失败用例数)。artifacts(如coverage.xml),可点击“Browse files”→“artifacts”下载或在线查看覆盖率报告。pip缓存):cache:
key: ${CI_COMMIT_REF_SLUG} # 按分支缓存
paths:
- .cache/pip/ # pip缓存目录
test_job:
stage: test
parallel: 4 # 拆分为4个并行作业
script:
- pytest tests/unit/test_*.py # 每个作业执行部分测试文件
通过以上步骤,可在Ubuntu环境下实现GitLab自动化测试,确保代码变更后快速验证质量,提升开发效率。