-
Notifications
You must be signed in to change notification settings - Fork 6
257 lines (221 loc) · 10.9 KB
/
generate-tests.yml
File metadata and controls
257 lines (221 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
name: Auto Generate Cover+Test
on:
workflow_dispatch:
inputs:
override_files:
description: 'Opcional: arquivos .kt específicos (separados por espaço). Vazio = escaneia tudo sem cobertura.'
required: false
default: ''
pull_request:
types: [closed]
permissions:
contents: write
pull-requests: write
jobs:
generate-tests:
name: Generate Unit Tests with Claude
runs-on: ubuntu-latest
if: |
github.event_name == 'workflow_dispatch' ||
(
github.event.pull_request.merged == true &&
github.event.pull_request.base.ref == 'main' &&
github.event.pull_request.user.login != 'github-actions[bot]'
)
steps:
# ── 1. Checkout ───────────────────────────────────────────────────────────
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ github.event_name == 'workflow_dispatch' && github.sha || github.event.pull_request.merge_commit_sha }}
fetch-depth: 0
# ── 3. Verifica se há arquivos .kt modificados ───────────────────────────
- name: Check for Kotlin file changes
id: kt_guard
run: |
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
echo "has_kotlin=true" >> "$GITHUB_OUTPUT"
echo "workflow_dispatch — pulando verificação de .kt"
else
KT=$(git diff --name-only ${{ github.event.pull_request.base.sha }}...HEAD | grep '\.kt$' || true)
if [ -n "$KT" ]; then
echo "has_kotlin=true" >> "$GITHUB_OUTPUT"
echo "Arquivos .kt detectados:"
echo "$KT"
else
echo "has_kotlin=false" >> "$GITHUB_OUTPUT"
echo "Nenhum arquivo .kt modificado. Pulando geração de testes."
fi
fi
# ── 4. Python ─────────────────────────────────────────────────────────────
- name: Set up Python
if: steps.kt_guard.outputs.has_kotlin == 'true'
uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Install Python dependencies
if: steps.kt_guard.outputs.has_kotlin == 'true'
run: pip install anthropic
# ── 5. Escaneia craftd-core buscando arquivos sem cobertura ──────────────
- name: Find uncovered Kotlin files in craftd-core
if: steps.kt_guard.outputs.has_kotlin == 'true'
id: changed
run: |
OVERRIDE="${{ github.event.inputs.override_files }}"
# Conta total de arquivos fonte
TOTAL=$(find android_kmp/craftd-core/src \
\( -path "*/commonMain/kotlin/*.kt" -o -path "*/androidMain/kotlin/*.kt" \) \
| grep -v "Test\.kt" | wc -l | tr -d ' ')
if [ -n "$OVERRIDE" ]; then
# Modo manual com arquivos específicos
UNCOVERED=$(echo "$OVERRIDE" | tr ' ' '\n' | grep -v "^$" || true)
UNCOVERED_COUNT=$(echo "$UNCOVERED" | grep -v "^$" | wc -l | tr -d ' ')
echo "Modo override — arquivos informados manualmente:"
elif [ "${{ github.event_name }}" = "pull_request" ]; then
# Modo automático (PR mergeado) — apenas .kt modificados no PR sem teste ainda
echo "Modo PR — apenas arquivos .kt modificados neste PR sem cobertura..."
UNCOVERED=""
while IFS= read -r SRC; do
# Só considera arquivos dentro do craftd-core
if echo "$SRC" | grep -q "android_kmp/craftd-core/src/"; then
TEST=$(echo "$SRC" \
| sed 's|src/commonMain/kotlin/|src/test/java/|' \
| sed 's|src/androidMain/kotlin/|src/test/java/|' \
| sed 's|\.kt$|Test.kt|')
if [ ! -f "$TEST" ]; then
UNCOVERED="$UNCOVERED"$'\n'"$SRC"
fi
fi
done < <(git diff --name-only ${{ github.event.pull_request.base.sha }}...HEAD | grep '\.kt$' | grep -v "Test\.kt" | sort)
UNCOVERED=$(echo "$UNCOVERED" | grep -v "^$" || true)
UNCOVERED_COUNT=$(echo "$UNCOVERED" | grep -v "^$" | wc -l | tr -d ' ')
else
# Modo workflow_dispatch sem override — scan completo
echo "Scan completo — buscando todos os arquivos sem cobertura em craftd-core..."
UNCOVERED=""
while IFS= read -r SRC; do
TEST=$(echo "$SRC" \
| sed 's|src/commonMain/kotlin/|src/test/java/|' \
| sed 's|src/androidMain/kotlin/|src/test/java/|' \
| sed 's|\.kt$|Test.kt|')
if [ ! -f "$TEST" ]; then
UNCOVERED="$UNCOVERED"$'\n'"$SRC"
fi
done < <(find android_kmp/craftd-core/src \
\( -path "*/commonMain/kotlin/*.kt" -o -path "*/androidMain/kotlin/*.kt" \) \
| grep -v "Test\.kt" | sort)
UNCOVERED=$(echo "$UNCOVERED" | grep -v "^$" || true)
UNCOVERED_COUNT=$(echo "$UNCOVERED" | grep -v "^$" | wc -l | tr -d ' ')
fi
echo "$UNCOVERED"
COVERED_BEFORE=$((TOTAL - UNCOVERED_COUNT))
COVERED_AFTER=$((COVERED_BEFORE + UNCOVERED_COUNT))
if [ "$TOTAL" -gt "0" ]; then
PCT_BEFORE=$(( (COVERED_BEFORE * 100) / TOTAL ))
PCT_AFTER=$(( (COVERED_AFTER * 100) / TOTAL ))
else
PCT_BEFORE=0
PCT_AFTER=0
fi
echo "total=$TOTAL" >> "$GITHUB_OUTPUT"
echo "covered_before=$COVERED_BEFORE" >> "$GITHUB_OUTPUT"
echo "covered_after=$COVERED_AFTER" >> "$GITHUB_OUTPUT"
echo "pct_before=$PCT_BEFORE" >> "$GITHUB_OUTPUT"
echo "pct_after=$PCT_AFTER" >> "$GITHUB_OUTPUT"
if [ -z "$UNCOVERED" ]; then
echo "has_changes=false" >> "$GITHUB_OUTPUT"
echo "Nenhum arquivo sem cobertura. Nada a fazer."
else
echo "has_changes=true" >> "$GITHUB_OUTPUT"
printf "files<<EOF\n%s\nEOF\n" "$UNCOVERED" >> "$GITHUB_OUTPUT"
fi
# ── 6. Chama Claude API para gerar os testes ─────────────────────────────
- name: Generate unit tests with Claude API
if: steps.kt_guard.outputs.has_kotlin == 'true' && steps.changed.outputs.has_changes == 'true'
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
CHANGED_FILES: ${{ steps.changed.outputs.files }}
run: python .github/scripts/generate_tests.py
# ── 7. Verifica se arquivos foram gerados ─────────────────────────────────
- name: Check generated files
if: steps.kt_guard.outputs.has_kotlin == 'true' && steps.changed.outputs.has_changes == 'true'
id: check
run: |
COUNT=$(find android_kmp/craftd-core/src/test -name "*Test.kt" 2>/dev/null | wc -l | tr -d ' ')
echo "count=$COUNT" >> "$GITHUB_OUTPUT"
echo "Found $COUNT test file(s)"
if [ "$COUNT" -gt "0" ]; then
echo "has_tests=true" >> "$GITHUB_OUTPUT"
NAMES=$(find android_kmp/craftd-core/src/test -name "*Test.kt" \
| xargs -I{} basename {} \
| paste -sd ", ")
echo "covered_names=$NAMES" >> "$GITHUB_OUTPUT"
echo "Files: $NAMES"
else
echo "has_tests=false" >> "$GITHUB_OUTPUT"
fi
# ── 8. Cria branch com nome incremental e commita os testes ──────────────
- name: Commit generated tests
if: steps.check.outputs.has_tests == 'true'
id: commit
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
# Autentica o push com GH_PAT via URL do remote
git remote set-url origin https://x-access-token:${{ secrets.GH_PAT }}@github.com/CodandoTV/CraftD.git
# Determina nome do branch com auto-incremento: cover/test, cover/test-1, cover/test-2 ...
BASE="cover/test"
BRANCH="$BASE"
N=1
while git ls-remote --exit-code --heads origin "$BRANCH" > /dev/null 2>&1; do
BRANCH="${BASE}-${N}"
N=$((N + 1))
done
echo "Branch escolhido: $BRANCH"
git checkout -b "$BRANCH"
git add --force android_kmp/craftd-core/src/test/
git commit -m "test: add unit tests for craftd-core (auto-generated via Claude)"
git push origin "$BRANCH"
echo "branch=$BRANCH" >> "$GITHUB_OUTPUT"
# ── 9. Abre PR com os testes gerados e evolução de cobertura ─────────────
- name: Open Pull Request with generated tests
if: steps.check.outputs.has_tests == 'true'
env:
GH_TOKEN: ${{ secrets.GH_PAT }}
run: |
PR_NUMBER="${{ github.event_name == 'workflow_dispatch' && 'manual' || github.event.pull_request.number }}"
BRANCH="${{ steps.commit.outputs.branch }}"
COVERED="${{ steps.check.outputs.covered_names }}"
TOTAL="${{ steps.changed.outputs.total }}"
COV_BEFORE="${{ steps.changed.outputs.covered_before }}"
COV_AFTER="${{ steps.changed.outputs.covered_after }}"
PCT_BEFORE="${{ steps.changed.outputs.pct_before }}"
PCT_AFTER="${{ steps.changed.outputs.pct_after }}"
gh pr create \
--base "main" \
--head "$BRANCH" \
--title "[Auto] Add unit tests for craftd-core" \
--body "$(cat <<EOF
## Auto-generated Unit Tests
Este PR foi gerado automaticamente pelo workflow **Auto Generate Cover+Test** usando a Claude API.
### Evolução de cobertura
| | Arquivos | Cobertura |
|---|---|---|
| Antes | ${COV_BEFORE} / ${TOTAL} | ${PCT_BEFORE}% |
| Depois | ${COV_AFTER} / ${TOTAL} | ${PCT_AFTER}% |
### Arquivos cobertos
\`\`\`
${COVERED}
\`\`\`
### Como funciona
1. Um PR tocou arquivos em \`android_kmp/craftd-core\`
2. Após o CI passar, o workflow escaneou todos os arquivos sem cobertura
3. Claude gerou testes **JUnit4 + MockK** para cada arquivo
4. Este PR foi criado automaticamente com o resultado
### Checklist de revisão
- [ ] Testes compilam sem erros (\`./gradlew testDebugUnitTest\`)
- [ ] Testes cobrem os principais caminhos de lógica
- [ ] Edge cases tratados (null, vazio, JSON inválido)
> Triggered by PR #${PR_NUMBER}
EOF
)"