如何配置GitLab根据TestCafe元标签和变量运行全量/子集测试
实现GitLab流水线按TestCafe元标签控制测试执行
步骤1:修改测试运行器,支持元标签过滤
更新你的test-runner.js,根据SMOKE_TESTS环境变量决定是否应用元标签过滤:
const createTestCafe = require('testcafe'); let testcafe = null; createTestCafe('localhost', 1337, 1338) .then(tc => { testcafe = tc; const runner = testcafe.createRunner(); // 当SMOKE_TESTS为true时,仅运行带有virtual-test-pack=true元标签的测试 const filterOptions = process.env.SMOKE_TESTS === 'true' ? { meta: { 'virtual-test-pack': 'true' } } : {}; return runner .src(process.env.TESTS.split(',')) // 支持多测试文件 .filter(filterOptions) .browsers('chrome:headless') // 根据实际需求调整浏览器 .reporter('xunit', './reports/xunit.xml') .run({ videoPath: './artifacts/videos', takeOnFails: true }); }) .then(failedCount => { console.log(`Tests failed: ${failedCount}`); testcafe.close(); process.exit(failedCount); }) .catch(err => { console.error('Test runner error:', err); testcafe?.close(); process.exit(1); });
步骤2:更新package.json脚本(无需大幅修改)
保持现有脚本结构,测试运行器会自动处理过滤逻辑:
{ "scripts": { "ci:cop:login": "start-server-and-test start-server http://localhost:xxxx/mgmt/health 'SUITE=Cop/Login TESTS=tests/cop/login.test.ts node test-runner.js'", "ci:cop:logout": "start-server-and-test start-server http://localhost:xxxx/mgmt/health 'SUITE=Cop/Logout TESTS=tests/cop/logout.test.ts node test-runner.js'" } }
步骤3:配置GitLab CI流水线,实现条件化任务执行
通过模板和规则实现智能流水线:
stages: - device-healthcheck - cop-tests - pos-tests variables: SMOKE_TESTS: value: "false" options: - "false" - "true" .integration-test: allow_failure: true image: xxx before_script: - https_proxy=http://webproxy:xxx - yarn config set strict-ssl false - yarn config set caFile /usr/local/share/xxx/xxx.io-root-ca-xxx.crt - yarn install - mkdir -p ./reports ./artifacts/videos script: - yarn config set strict-ssl false - yarn config set caFile /usr/local/share/xxx/xxx.io-root-ca-xxx.crt - yarn run ${TEST_SUITE:='test'} - ls -R ./reports || echo "No reports found" - cp -r ./reports /cwd/ artifacts: reports: junit: reports/xunit.xml paths: - artifacts/videos/*.mp4 when: always # 冒烟测试任务模板:无论SMOKE_TESTS值如何都运行 .smoke-job: rules: - if: $SMOKE_TESTS == "true" when: always - if: $SMOKE_TESTS == "false" when: always # 非冒烟测试任务模板:仅在全量测试时运行 .non-smoke-job: rules: - if: $SMOKE_TESTS == "false" when: always - if: $SMOKE_TESTS == "true" when: never # 具体测试任务 cop-login: stage: cop-tests variables: TEST_SUITE: "ci:cop:login" needs: ["cop-healthcheck"] extends: [.integration-test, .smoke-job] cop-logout: stage: cop-tests variables: TEST_SUITE: "ci:cop:logout" needs: ["cop-healthcheck"] extends: [.integration-test, .smoke-job] # 示例:非冒烟测试任务(仅全量测试时运行) cop-checkout: stage: cop-tests variables: TEST_SUITE: "ci:cop:checkout" needs: ["cop-healthcheck"] extends: [.integration-test, .non-smoke-job]
效果说明
- 当
SMOKE_TESTS设为true时:- 仅标记为
.smoke-job的任务会出现在流水线中 - 这些任务仅运行带有
virtual-test-pack=true元标签的测试
- 仅标记为
- 当
SMOKE_TESTS设为false时:- 所有任务都会运行
- 每个任务执行全部测试用例
内容的提问来源于stack exchange,提问作者BruceyBandit
相关产品推荐
相关产品推荐

