Skip to main content

Настройка покрытия кодами для вашего репозитория

Загружайте отчёты о покрытии тестов, чтобы видеть результаты покрытия напрямую через pull requests, помогая рецензентам выявлять непроверенный код перед объединением.

Кто может использовать эту функцию?

Владельцы репозиториев, владельцы организаций и пользователи с административной ролью

GitHub Team или GitHub Enterprise Cloud

Примечание.

GitHub Code Quality в настоящее время находится в Публичный предварительный просмотр и может быть изменен. Во время Публичный предварительный просмотр, Code Quality не будут оплачиваться, хотя Code Quality сканирование займет GitHub Actions минут.

В следующих процедурах вы сгенерируете отчёт о покрытии Cobertura XML из вашего тестового пакета, загружаете его в GitHub, и просматриваете результаты покрытия в ваших pull requests.

Необходимые условия

  • Code Quality включена для вашего репозитория.
  • В вашем репозитории есть тестовый набор, который работает в GitHub Actions.
  • Ваш тестовый фреймворк может создать отчёт о покрытии в формате Cobertura XML .

Шаг 1: Сгенерируйте отчёт по покрытию Cobertura XML

Настройте ваш тестовый фреймворк так, чтобы он выводил отчёт о покрытии в формате Cobertura XML. Покрытие кода работает с любым языком программирования, способным создавать такой формат.

  1. Определите инструмент покрытия вашего языка из таблицы ниже.
  2. Добавьте соответствующую команду или конфигурацию в рабочий процесс CI, чтобы каждый раз при выполнении тестов генерировался файл Cobertura XML.
LanguageФреймворк / ИнструментКак сгенерировать Cobertura XML
Pythonpytest + pytest-covpytest --cov=. --cov-report=xml
JavaJaCoCoИспользуйте cover2cover.py скрипт или плагин JaCoCo-to-Cobertura Gradle/Maven
JavaScript/TypeScriptСтамбул / nycnyc report --reporter=cobertura
RubySimpleCovДобавить SimpleCov::Formatter::CoberturaFormatter
Впередgo test + gocover-coberturago test -coverprofile=cover.out && gocover-cobertura < cover.out > coverage.xml

Совет

Если ваш фреймворк не указан выше, проверьте документацию по поддержке вывода Cobertura. Многие инструменты либо поддерживают его напрямую, либо могут конвертировать в Cobertura XML из других форматов.

Шаг 2: Загрузите отчёт о покрытии

После того как ваши тесты сгенерируют отчёт Cobertura XML, загрузите его так GitHub , чтобы результаты покрытия отображались в pull requests.

  1. Откройте файл CI-рабочего процесса вашего репозитория (например, .github/workflows/ci.yml).

  2. Добавьте следующий шаг после этапа, который запускает ваши тесты и формирует отчёт о покрытии:

    YAML
    - name: Upload coverage report
      if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
      uses: actions/upload-code-coverage@v1
      with:
        file: COVERAGE-FILE-PATH.xml
        language: LANGUAGE
        label: LABEL
    
  3. Измените следующие значения:

    • COVERAGE-FILE-PATH.xml: Путь к вашему отчёту Cobertura XML (например coverage.xml , или target/site/jacoco/cobertura.xml).
    • LANGUAGE: Основной язык используемого кода (например, Python, Java, JavaScript).
    • LABEL: Необязательная метка для обозначения этого отчёта о покрытии (например, code-coverage/pytest).
  4. Коммит и продвигай изменение рабочего процесса.

Полный пример рабочего процесса

Этот пример запускает Python тестов с pytest-cov и загружает отчет о покрытии:

YAML
name: Code Coverage

This workflow runs your test suite, generates a Cobertura XML coverage report, and uploads it to GitHub. Once this workflow is committed, coverage results appear automatically on every pull request.

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

Run on pushes to the default branch (to establish the baseline) and on pull requests (to compare against it). Code Quality compares PR branch coverage to the default branch, so both triggers are needed.

permissions:
  contents: read
  code-quality: write
jobs:
  test:
    runs-on: ubuntu-latest
    steps:

The code-quality: write permission is required to upload coverage data. No other elevated permissions are needed.

      - uses: actions/checkout@v6
        with:
          ref: ${{ github.event.pull_request.head.sha || github.sha }}

Check out the PR head commit (not the merge commit) so coverage line numbers map correctly to the diff.

      - uses: actions/setup-python@v5
        with:
          python-version: "3.x"
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt
          pip install pytest pytest-cov

Replace this step with whatever language setup your project uses (Node.js, Java, Go, etc.). The upload action works with any language that produces a Cobertura XML report.

      - name: Run tests with coverage
        run: pytest --cov=. --cov-report=xml

Adapt this step for your test framework. The key requirement is producing a Cobertura XML file. For other languages, see the framework table earlier in this article.

      - name: Upload coverage report
        if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
        uses: actions/upload-code-coverage@v1
        with:
          file: coverage.xml
          language: Python
          label: code-coverage/pytest

This step replaces any third-party coverage upload (Codecov, Coveralls, etc.). After this runs, the github-code-quality[бот] bot posts a coverage summary directly on the pull request.

# This workflow runs your test suite, generates a Cobertura XML coverage report, and uploads it to GitHub. Once this workflow is committed, coverage results appear automatically on every pull request.
name: Code Coverage

# Run on pushes to the default branch (to establish the baseline) and on pull requests (to compare against it). Code Quality compares PR branch coverage to the default branch, so both triggers are needed.
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

# The `code-quality: write` permission is required to upload coverage data. No other elevated permissions are needed.
permissions:
  contents: read
  code-quality: write

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      # Check out the PR head commit (not the merge commit) so coverage line numbers map correctly to the diff.
      - uses: actions/checkout@v6
        with:
          ref: ${{ github.event.pull_request.head.sha || github.sha }}

      # Replace this step with whatever language setup your project uses (Node.js, Java, Go, etc.). The upload action works with any language that produces a Cobertura XML report.
      - uses: actions/setup-python@v5
        with:
          python-version: "3.x"

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt
          pip install pytest pytest-cov

      # Adapt this step for your test framework. The key requirement is producing a Cobertura XML file. For other languages, see the framework table earlier in this article.
      - name: Run tests with coverage
        run: pytest --cov=. --cov-report=xml

      # This step replaces any third-party coverage upload (Codecov, Coveralls, etc.). After this runs, the `github-code-quality[бот]` bot posts a coverage summary directly on the pull request.
      - name: Upload coverage report
        if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
        uses: actions/upload-code-coverage@v1
        with:
          file: coverage.xml
          language: Python
          label: code-coverage/pytest

Шаг 3: Просмотр результатов покрытия по pull requests

  1. Откройте pull request (или push к существующему), который запускает настроенный вами рабочий процесс.
  2. После завершения рабочего процесса ищите комментарий в github-code-quality[бот] pull request. Комментарий включает:
    • Совокупный процент покрытия ветки pull request по сравнению с стандартной.
    • Разбивка по файлам, показывающая, какие файлы получили или потеряли покрытие.

Дальнейшие действия

  • Интерпретировать результаты: Понимайте метрики покрытия и разбивку по файлам в ваших pull requests. См . раздел AUTOTITLE.