Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,61 @@ jobs:
path: |
build/reports/tests/test
build/reports/cucumber

- name: Publicar cobertura
if: always()
uses: actions/upload-artifact@v4
with:
name: cobertura-jacoco
path: |
build/reports/jacoco/test/jacocoTestReport.xml
build/reports/jacoco/test/html
if-no-files-found: ignore
retention-days: 7

resumo:
if: ${{ !cancelled() && github.event_name == 'pull_request' }}
needs: build
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
steps:
- uses: actions/checkout@v4

- uses: actions/setup-node@v4
with:
node-version: 24

- name: Baixar a cobertura
uses: actions/download-artifact@v4
with:
name: cobertura-jacoco
path: build/reports/jacoco/test
continue-on-error: true

- name: Montar o resumo
env:
COMMIT_DO_PR: ${{ github.event.pull_request.head.sha }}
run: |
node scripts/resumo-cobertura.mjs > resumo.md
cat resumo.md >> "$GITHUB_STEP_SUMMARY"

- name: Comentar no PR
continue-on-error: true
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPOSITORIO: ${{ github.repository }}
PR: ${{ github.event.pull_request.number }}
run: |
id=$(gh api "repos/$REPOSITORIO/issues/$PR/comments" --paginate \
--jq '.[] | select(.body | contains("<!-- resumo-cobertura-back -->")) | .id' | head -1)
if [ -n "$id" ]; then
gh api --method PATCH "repos/$REPOSITORIO/issues/comments/$id" -F body=@resumo.md
else
gh api --method POST "repos/$REPOSITORIO/issues/$PR/comments" -F body=@resumo.md
fi

imagem:
needs: build
if: github.ref == 'refs/heads/main'
Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,11 @@ tipo e de feriado vêm de `GET /api/referencias`.

O relatório dos cenários fica em `build/reports/cucumber/cucumber.html`.

A cobertura é medida pelo JaCoCo (sem o pacote `OTO.demo` e a classe `OtoProjectApplication`).
`./gradlew test` já gera o relatório, em `build/reports/jacoco/test/html/index.html` (XML em
`build/reports/jacoco/test/jacocoTestReport.xml`). `./gradlew check` falha se as linhas ficarem
abaixo de 97% ou os branches abaixo de 92%. Nos pull requests o CI comenta a cobertura total e por pacote.

## Organização do código

| Pacote | Conteúdo |
Expand Down
44 changes: 44 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
plugins {
id 'java'
id 'jacoco'
id 'org.springframework.boot' version '4.1.1'
id 'io.spring.dependency-management' version '1.1.7'
}
Expand Down Expand Up @@ -63,8 +64,51 @@ tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8'
}

jacoco {
toolVersion = '0.8.13'
}

// O populador de dados de demonstração nunca é executado por teste, e a classe main só delega ao Spring.
def foraDaCobertura = ['OTO/demo/**', 'OTO/OtoProjectApplication.class']

tasks.named('jacocoTestReport') {
dependsOn tasks.named('test')
reports {
xml.required = true
html.required = true
}
classDirectories.setFrom(files(classDirectories.files.collect {
fileTree(dir: it, exclude: foraDaCobertura)
}))
}

tasks.named('jacocoTestCoverageVerification') {
classDirectories.setFrom(files(classDirectories.files.collect {
fileTree(dir: it, exclude: foraDaCobertura)
}))
violationRules {
rule {
limit {
counter = 'LINE'
value = 'COVEREDRATIO'
minimum = 0.97
}
limit {
counter = 'BRANCH'
value = 'COVEREDRATIO'
minimum = 0.92
}
}
}
}

tasks.named('check') {
dependsOn tasks.named('jacocoTestCoverageVerification')
}

tasks.named('test') {
useJUnitPlatform()
finalizedBy tasks.named('jacocoTestReport')
// Só alguns cenários: ./gradlew test --tests OTO.aceitacao.CucumberTest -Ptags=@smoke
if (project.hasProperty('tags')) {
systemProperty 'cucumber.filter.tags', project.property('tags')
Expand Down
94 changes: 94 additions & 0 deletions scripts/resumo-cobertura.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// Monta o resumo de cobertura do JaCoCo em Markdown para comentar no PR.
// Uso: node scripts/resumo-cobertura.mjs > resumo.md
// Lê build/reports/jacoco/test/jacocoTestReport.xml (ou o caminho passado como argumento).

import { existsSync, readFileSync } from 'node:fs'

const MARCADOR = '<!-- resumo-cobertura-back -->'
const ARQUIVO = process.argv[2] ?? 'build/reports/jacoco/test/jacocoTestReport.xml'

const MEDIDAS = [
['LINE', 'Linhas'],
['BRANCH', 'Branches'],
['METHOD', 'Métodos'],
['INSTRUCTION', 'Instruções'],
]

function decimal(valor, casas) {
return valor.toFixed(casas).replace('.', ',')
}

function percentual({ coberto, perdido }) {
const total = coberto + perdido
return total === 0 ? 100 : (coberto / total) * 100
}

function contadores(trecho) {
const mapa = {}
for (const [, tipo, perdido, coberto] of trecho.matchAll(
/<counter type="(\w+)" missed="(\d+)" covered="(\d+)"\/>/g,
)) {
mapa[tipo] = { perdido: Number(perdido), coberto: Number(coberto) }
}
return mapa
}

function celula(contador) {
if (!contador) return '-'
return `${decimal(percentual(contador), 2)}%`
}

function lerRelatorio(xml) {
const semPackages = xml.replace(/<package [\s\S]*?<\/package>/g, '')
const total = contadores(semPackages)
const pacotes = [...xml.matchAll(/<package name="([^"]*)">([\s\S]*?)<\/package>/g)].map(
([, nome, corpo]) => {
const semClasses = corpo
.replace(/<class [\s\S]*?<\/class>/g, '')
.replace(/<sourcefile [\s\S]*?<\/sourcefile>/g, '')
return { nome: nome.replaceAll('/', '.'), medidas: contadores(semClasses) }
},
)
return { total, pacotes }
}

function rodape() {
const { GITHUB_SERVER_URL, GITHUB_REPOSITORY, GITHUB_RUN_ID, COMMIT_DO_PR, GITHUB_SHA } =
process.env
if (!GITHUB_RUN_ID) return ''
const execucao = `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}`
return `\n_Commit \`${(COMMIT_DO_PR || GITHUB_SHA)?.slice(0, 7)}\`. [Relatório HTML completo no artefato \`cobertura-jacoco\` da execução](${execucao})._`
}

const cabecalho = [MARCADOR, '## Cobertura de testes (JaCoCo)', '']

if (!existsSync(ARQUIVO)) {
console.log([...cabecalho, '_Cobertura não disponível nesta execução._', rodape()].join('\n'))
} else {
const { total, pacotes } = lerRelatorio(readFileSync(ARQUIVO, 'utf8'))
const linhasTotal = MEDIDAS.map(([tipo, nome]) => {
const c = total[tipo]
return c
? `| ${nome} | ${celula(c)} | ${c.coberto} de ${c.coberto + c.perdido} |`
: `| ${nome} | - | - |`
})
const linhasPacotes = pacotes
.sort((a, b) => a.nome.localeCompare(b.nome))
.map(({ nome, medidas }) => `| \`${nome}\` | ${MEDIDAS.map(([tipo]) => celula(medidas[tipo])).join(' | ')} |`)

console.log(
[
...cabecalho,
'| Medida | Cobertura | Cobertos |',
'| --- | ---: | ---: |',
...linhasTotal,
'',
'### Por pacote',
'',
`| Pacote | ${MEDIDAS.map(([, nome]) => nome).join(' | ')} |`,
`| --- | ${MEDIDAS.map(() => '---:').join(' | ')} |`,
...linhasPacotes,
rodape(),
].join('\n'),
)
}
Loading