【问题标题】:How can I set a minimum unit test coverage with GitLab CI?如何使用 GitLab CI 设置最小单元测试覆盖率?
【发布时间】:2022-11-10 09:46:23
【问题描述】:

我有一个托管在 GitLab 上的项目,该项目已经具有有效的 CI 配置。我想添加“最小代码覆盖率”的概念。

我想要的是强制一个正的增量(合并请求的代码覆盖率必须大于目标分支的覆盖率,除非它已经是 100%)。

我会接受“最低 80% 覆盖率”的规则,但我相信我可以做得更好。

我在文档中找不到任何内容,除了关键字coverage 抓取覆盖范围以显示在主页上。

我想要.gitlab-ci.yml 中的类似内容:

check_coverage:
  stage: test
  rules:
    - if: '$CI_OPEN_MERGE_REQUESTS && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH'
  script:
    - compare-coverage.sh $CI_CURRENT_COVERAGE $CI_TARGET_COVERAGE # something that fails if delta < 0

我怎样才能做到这一点?

【问题讨论】:

    标签: gitlab gitlab-ci code-coverage


    【解决方案1】:

    我是这样做的:

    # .gitlab-ci.yml
    image: python:3.9
    
    stages:
      - tests
      - min-coverage
    
    variables:
      MIN_COVERAGE: 80  # set the threshold at 80%
    
    unit-test:
      stage: tests
      before_script:
        - pip install pytest pytest-cov
      script:
        - coverage run -m pytest
        - coverage json
        - coverage report -m
      artifacts:
        paths:
          - coverage.json
      coverage: '/TOTAL.+ ([0-9]{1,3}%)/'
    
    min-coverage-test:
      stage: min-coverage
      before_script:
        - apt-get update && apt-get install jq -y
      script:
        - jsonStr="$(cat $CI_PROJECT_DIR/coverage.json)"
        - coverage="$(echo $jsonStr | jq .totals.percent_covered)"
        - if (( $(echo "$coverage < $MIN_COVERAGE" |bc -l) )) ; then echo "$coverage% of code coverage below threshold of $MIN_COVERAGE%" && exit 1 ; else exit 0 ; fi
    

    【讨论】:

    • 对于浮点数:使用 (( $(echo "$coverage &lt; $MIN_COVERAGE" |bc -l) )); 参见 [stackoverflow.com/a/31087503/1381657]
    • 感谢@r_j 的分享。我会更新我的帖子
    猜你喜欢
    • 2022-06-11
    • 2018-05-12
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 2022-06-24
    • 2018-10-18
    • 2015-06-03
    • 1970-01-01
    相关资源
    最近更新 更多