Ubuntu環境下GitLab自動化測試實施方法
GitLab Runner是執行CI/CD作業的核心組件,需先在Ubuntu服務器上安裝。常用包管理器安裝(以Ubuntu 22.04為例):
# 添加GitLab Runner倉庫并安裝
curl -L --output gitlab-runner.deb https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh && \
sudo dpkg -i gitlab-runner.deb && \
sudo apt-get update && \
sudo apt-get install gitlab-runner
安裝完成后,啟動Runner服務并設置開機自啟:
sudo systemctl start gitlab-runner && \
sudo systemctl enable gitlab-runner
注冊Runner與GitLab項目綁定,獲取項目URL和Token(路徑:GitLab項目→Settings→CI/CD→Runners):
sudo gitlab-runner register
按提示輸入信息:
https://gitlab.com)ubuntu-test-runner)ubuntu、docker,用于篩選作業)docker或shell,docker可實現環境隔離)在項目根目錄創建.gitlab-ci.yml,定義測試流程的核心邏輯(以Java+Maven項目為例):
stages:
- build
- test
- report
variables:
MAVEN_OPTS: "-Dmaven.repo.local=.m2/repository"
cache:
paths:
- .m2/repository/ # 緩存Maven依賴,加速后續構建
build_job:
stage: build
script:
- echo "Compiling code..."
- mvn clean compile
artifacts:
paths:
- target/ # 傳遞編譯產物給后續階段
test_job:
stage: test
script:
- echo "Running unit tests..."
- mvn test
artifacts:
reports:
junit: target/surefire-reports/*.xml # 生成JUnit格式測試報告
deploy_job:
stage: deploy
script:
- echo "Deploying to production..."
only:
- main # 僅main分支觸發部署
根據項目技術棧編寫測試用例,例如:
src/test/java目錄;tests/目錄;__tests__/目錄。為提升測試結果可讀性,可將測試報告集成到GitLab界面。例如,JUnit報告(適用于Java/Maven):
test_job:
stage: test
script:
- mvn test
artifacts:
reports:
junit: target/surefire-reports/*.xml # 自動解析并展示在CI/CD界面
Playwright測試報告(適用于Web端):
test_with_playwright:
stage: test
image: mcr.microsoft.com/playwright/python:v1.42.1 # 使用Playwright官方鏡像
script:
- pip install playwright
- playwright install
- pytest tests/ --headed --timeout=30000 # 執行測試
artifacts:
paths:
- playwright-report/ # 保存HTML報告
when: always # 無論測試通過與否都上傳報告
將代碼推送到GitLab倉庫(如main分支),Runner會自動檢測.gitlab-ci.yml并執行定義的作業。也可通過Webhook實現實時觸發(路徑:項目→Settings→Webhooks)。
在GitLab項目頁面→CI/CD→Pipelines,點擊對應流水線可查看:
test_job)查看詳細日志;parallel關鍵字拆分測試任務,縮短執行時間;test_job:
stage: test
script:
- echo "Running tests in parallel..."
parallel: 4 # 拆分為4個并行任務
test_job:
stage: test
image: python:3.9 # 使用指定Python版本的Docker鏡像
script:
- pip install -r requirements.txt
- pytest
cache:
key: ${CI_COMMIT_REF_SLUG} # 按分支緩存
paths:
- node_modules/ # Node.js依賴
- .m2/repository/ # Maven依賴
通過以上步驟,可在Ubuntu環境下實現GitLab自動化測試,覆蓋代碼提交→構建→測試→報告的全流程,提升開發效率和代碼質量。