Observação
GitHub Code Quality está atualmente em prévia pública e sujeito a alterações. Durante prévia pública, Code Quality não será cobrado, embora as verificações de Code Quality consumirão GitHub Actions minutos.
Nos procedimentos a seguir, você gerará um relatório de cobertura no formato Cobertura XML a partir do seu conjunto de testes, fará upload dele para GitHub e visualizará os resultados da cobertura em seus pull requests.
Pré-requisitos
- Code Quality está habilitado para seu repositório.
- Seu repositório possui uma suíte de testes executada em GitHub Actions.
- Sua estrutura de teste pode produzir um relatório de cobertura no formato Cobertura XML .
Etapa 1: gerar um relatório de cobertura Cobertura XML
Configure seu framework de testes para gerar um relatório de cobertura no formato Cobertura XML. A cobertura de código funciona com qualquer linguagem de programação que possa produzir esse formato.
- Identifique a ferramenta de cobertura do seu idioma na tabela abaixo.
- Adicione o comando ou a configuração apropriada ao fluxo de trabalho de CI para que um arquivo XML do Cobertura seja gerado sempre que os testes forem executados.
| Linguagem | Estrutura/Ferramenta | Como gerar Cobertura XML |
|---|---|---|
| Python | pytest + pytest-cov | pytest --cov=. --cov-report=xml |
| Java | JaCoCo | Usar o cover2cover.py script ou o plug-in JaCoCo-to-Cobertura Gradle/Maven |
| JavaScript/TypeScript | Istambul/ nyc | nyc report --reporter=cobertura |
| Ruby | SimpleCov | Adicionar SimpleCov::Formatter::CoberturaFormatter |
| Go | go test + gocover-cobertura | go test -coverprofile=cover.out && gocover-cobertura < cover.out > coverage.xml |
Dica
Se o seu framework não estiver listado acima, verifique na documentação dele se há suporte para saída no formato Cobertura. Muitas ferramentas têm suporte nativo a esse formato ou podem converter de outros formatos para o XML Cobertura.
Etapa 2: Carregar o relatório de cobertura
Depois que seus testes gerarem um relatório Cobertura XML, faça upload dele para GitHub para que os resultados de cobertura apareçam nos pull requests.
-
Abra o arquivo de fluxo de trabalho ci do repositório (por exemplo,
.github/workflows/ci.yml). -
Adicione a seguinte etapa após a etapa que executa seus testes e gere o relatório de cobertura:
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- 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 -
Substitua os seguintes valores:
COVERAGE-FILE-PATH.xml: o caminho para o relatório XML do Cobertura (por exemplo,coverage.xmloutarget/site/jacoco/cobertura.xml).LANGUAGE: o idioma principal do código que está sendo coberto (por exemplo,Python,Java,JavaScript).LABEL: um rótulo opcional para identificar este relatório de cobertura (por exemplo,code-coverage/pytest).
-
Confirme e envie por push a alteração do fluxo de trabalho.
Exemplo de fluxo de trabalho completo
Este exemplo executa Python testes com pytest-cov e carrega o relatório de cobertura:
# 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]` 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
name: Code CoverageThis 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-covReplace 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=xmlAdapt 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/pytestThis step replaces any third-party coverage upload (Codecov, Coveralls, etc.). After this runs, the github-code-quality[bot] 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]` 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
Etapa 3: Exibir os resultados de cobertura em pull requests
- Abra uma solicitação de pull (ou envie por push para uma existente) que dispare o fluxo de trabalho configurado.
- Após a conclusão do fluxo de trabalho, procure um comentário de
github-code-quality[bot]no pull request. O comentário inclui:- A porcentagem de cobertura agregada da ramificação da solicitação de pull em comparação com a ramificação padrão.
- Um detalhamento por arquivo mostrando quais arquivos ganharam ou perderam a cobertura.
Próximas Etapas
- Interpretar resultados: Entenda as métricas de cobertura e os detalhamentos por arquivo em suas solicitações de pull. Consulte Interpretando os resultados da qualidade do código do seu repositório.