2

我试图在 gitlab 阶段拆分我的 pytest,以减少运行它们所需的时间。但是,我很难获得完整的报道报告。由于我们的数据库设置方式,我无法使用 pytest-xdist 或 pytest-parallel。

Build:
  stage: Build
  script:
    - *setup-build
    - *build
    - touch banana.xml   # where I write the code coverage collected by pytest-cov
    - *push
  artifacts:
    paths:
    - banana.xml
    reports:
      cobertura: banana.xml

Unit Test:
  stage: Test
  script:
    - *setup-build
    - *pull
    - docker-compose run $DOCKER_IMG_NAME pytest -m unit --cov-report xml:banana.xml --cov=app --cov-append;
  needs:
    - Build

Validity Test:
  stage: Test
  script:
    - *setup-build
    - *pull
    - docker-compose run $DOCKER_IMG_NAME pytest -m validity --cov-report xml:banana.xml --cov=app --cov-append;
  needs:
    - Build

在这两个阶段运行(构建 - 1 个作业,测试 - 2 个作业)之后,我去从 Gitlab 下载香蕉.xml 文件,但其中没有任何内容,即使作业说Coverage XML written to file banana.xml

在 gitlab 管道阶段拆分标记测试时,我是否遗漏了如何将总覆盖率写入工件文件?

4

1 回答 1

3

如果您想合并几个不同作业的覆盖率报告,您将必须添加另一个阶段,该阶段将在您的测试之后运行。这是我的一个工作示例:

# You need to define the Test stage before the Coverage stage
stages:
  - Test
  - Coverage

# Your first test job
unit_test:
  stage: Test
  script:
    - COVERAGE_FILE=.coverage.unit coverage run --rcfile=.coveragerc -m pytest ./unit
  artifacts:
    paths:
      - .coverage.unit

# Your second test job which will run in parallel
validity_test:
  stage: Test
  script:
    - COVERAGE_FILE=.coverage.validity coverage run --rcfile=.coveragerc -m pytest ./validity
  artifacts:
    paths:
      - .coverage.validity

# Your coverage job, which will combine the coverage data from the two tests jobs and generate a report
coverage:
  stage: Coverage
  script:
    - coverage combine --rcfile=.coveragerc
    - coverage report
    - coverage xml -o coverage.xml
  coverage: '/\d+\%\s*$/'
  artifacts:
    reports:
      cobertura: coverage.xml

您还需要.coveragerc在存储库中创建一个包含以下内容的文件,以指定 coverage.py 需要使用相对文件路径,因为您的测试在不同的 gitlab 运行器上运行,因此它们的完整路径不匹配:

[run]
  relative_files = True
  source =
  ./

注意:在您的情况下,最好coverage直接使用该命令(coverage run -m pytest而不是pytest),因为它提供了更多选项,并且无论如何它都是 pytest 在后台使用的。


您文件中的问题是您从创建一个空文件开始,尝试从中生成报告(由于文件为空,因此不会生成任何内容),然后将其传递给两个测试作业,这两个作业都覆盖它与他们的本地覆盖率报告分开,然后永远不要使用它。

您需要以相反的方式进行操作,如我的示例所示:首先运行测试,然后在稍后阶段获取测试覆盖率数据,并从中生成报告。

于 2021-10-20T16:44:31.330 回答