diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 6eb5bb4..acd87e5 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -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("")) | .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'
diff --git a/README.md b/README.md
index 79540e4..b9cd313 100644
--- a/README.md
+++ b/README.md
@@ -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 |
diff --git a/build.gradle b/build.gradle
index 60d4e68..b2d4486 100644
--- a/build.gradle
+++ b/build.gradle
@@ -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'
}
@@ -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')
diff --git a/scripts/resumo-cobertura.mjs b/scripts/resumo-cobertura.mjs
new file mode 100644
index 0000000..ee924c2
--- /dev/null
+++ b/scripts/resumo-cobertura.mjs
@@ -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 = ''
+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(
+ //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(//g, '')
+ const total = contadores(semPackages)
+ const pacotes = [...xml.matchAll(/([\s\S]*?)<\/package>/g)].map(
+ ([, nome, corpo]) => {
+ const semClasses = corpo
+ .replace(//g, '')
+ .replace(//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'),
+ )
+}