-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommit_v090_test.go
More file actions
532 lines (501 loc) · 16.7 KB
/
commit_v090_test.go
File metadata and controls
532 lines (501 loc) · 16.7 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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
package repomap
import (
"context"
"strings"
"testing"
)
// --- D. Per-edge evidence ---
// Test_D_Evidence_MultiFile verifies that a multi-file group populates the
// Evidence array with at least one entry matching the expected edge weight.
func Test_D_Evidence_MultiFile(t *testing.T) {
t.Parallel()
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
root := initTestRepo(t,
map[string]string{
"go.mod": "module fixture\ngo 1.22\n",
"pkg/foo.go": "package pkg\nfunc Foo() {}\n",
"pkg/foo_test.go": "package pkg\nimport \"testing\"\nfunc TestFoo(t *testing.T) {}\n",
},
map[string]string{
"pkg/foo.go": "package pkg\nfunc Foo() {}\nfunc Bar() {}\n",
"pkg/foo_test.go": "package pkg\nimport \"testing\"\nfunc TestFoo(t *testing.T) {}\nfunc TestBar(t *testing.T) {}\n",
},
)
got, err := AnalyzeCommit(context.Background(), AnalyzeOptions{Root: root})
if err != nil {
t.Fatalf("AnalyzeCommit: %v", err)
}
// Find the group containing the test-pair.
var group *CommitGroup
for i := range got.Groups {
if containsAll(got.Groups[i].Files, "pkg/foo.go", "pkg/foo_test.go") {
group = &got.Groups[i]
break
}
}
if group == nil {
t.Fatalf("test-pair group not found; groups=%+v", got.Groups)
}
if len(group.Evidence) == 0 {
t.Fatalf("Evidence is empty for multi-file group; want at least one entry")
}
// At least one evidence entry should be a test-pair with weight 1.0.
foundTestPair := false
for _, ev := range group.Evidence {
if ev.Reason == "test-pair" && ev.Weight == 1.0 {
foundTestPair = true
}
// Both files in evidence must be valid paths.
if ev.A == "" || ev.B == "" {
t.Errorf("evidence entry has empty path: %+v", ev)
}
}
if !foundTestPair {
t.Errorf("no test-pair evidence with weight 1.0 found; evidence=%+v", group.Evidence)
}
}
// Test_D_Evidence_Singleton verifies that singleton groups have empty Evidence
// (no edges connect a group of one file).
func Test_D_Evidence_Singleton(t *testing.T) {
t.Parallel()
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
root := initTestRepo(t,
map[string]string{
"go.mod": "module fixture\ngo 1.22\n",
"README.md": "# readme\n",
},
map[string]string{
"README.md": "# readme\n\nupdated\n",
},
)
got, err := AnalyzeCommit(context.Background(), AnalyzeOptions{Root: root})
if err != nil {
t.Fatalf("AnalyzeCommit: %v", err)
}
for _, g := range got.Groups {
if len(g.Files) == 1 && len(g.Evidence) > 0 {
t.Errorf("singleton group %q has non-empty evidence: %+v", g.ID, g.Evidence)
}
}
}
// --- A. Multi-language ImportPath derivation ---
// Test_A_ImportPath_PHP verifies PHP namespace extraction from regex parser.
func Test_A_ImportPath_PHP(t *testing.T) {
t.Parallel()
src := []byte("<?php\nnamespace App\\Http\\Controllers;\nclass UserController {}\n")
ip := derivePHPNamespace(strings.Split(string(src), "\n"))
if ip != `App\Http\Controllers` {
t.Errorf("PHP namespace = %q, want %q", ip, `App\Http\Controllers`)
}
}
// Test_A_ImportPath_Java verifies Java package extraction from source lines.
func Test_A_ImportPath_Java(t *testing.T) {
t.Parallel()
lines := []string{
"package com.example.service;",
"public class UserService {}",
}
ip := deriveJavaPackage(lines)
if ip != "com.example.service" {
t.Errorf("Java package = %q, want %q", ip, "com.example.service")
}
}
// Test_A_ImportPath_Python_Script verifies that a Python file with no
// __init__.py ancestor returns "" (script file).
func Test_A_ImportPath_Python_Script(t *testing.T) {
t.Parallel()
// tmpDir has no __init__.py so derivation must return "".
dir := t.TempDir()
ip := derivePythonPackage(dir+"/script.py", dir)
if ip != "" {
t.Errorf("Python script ImportPath = %q, want empty", ip)
}
}
// Test_A_ImportPath_Python_Package verifies that a Python file in a package
// (with __init__.py) gets the dotted module path.
func Test_A_ImportPath_Python_Package(t *testing.T) {
t.Parallel()
root := t.TempDir()
writeFixture(t, root, "myapp/__init__.py", "")
writeFixture(t, root, "myapp/services/__init__.py", "")
writeFixture(t, root, "myapp/services/user.py", "")
ip := derivePythonPackage(root+"/myapp/services/user.py", root)
// Should be "myapp.services" (directory containing the file, which has __init__.py)
if ip == "" {
t.Errorf("Python package ImportPath is empty, want non-empty dotted path")
}
if !strings.Contains(ip, "myapp") {
t.Errorf("Python package ImportPath = %q, want it to contain 'myapp'", ip)
}
}
// Test_A_ImportPath_Rust verifies Rust crate path derivation from Cargo.toml.
func Test_A_ImportPath_Rust(t *testing.T) {
t.Parallel()
root := t.TempDir()
writeFixture(t, root, "Cargo.toml", "[package]\nname = \"mylib\"\nversion = \"0.1.0\"\n")
writeFixture(t, root, "src/lib.rs", "pub fn hello() {}")
ip := deriveRustCratePath(root+"/src/lib.rs", root)
if ip == "" {
t.Errorf("Rust crate path is empty, want non-empty")
}
if !strings.HasPrefix(ip, "mylib") {
t.Errorf("Rust crate path = %q, want prefix 'mylib'", ip)
}
}
// Test_A_ImportPath_TypeScript verifies TS package-relative path derivation.
func Test_A_ImportPath_TypeScript(t *testing.T) {
t.Parallel()
root := t.TempDir()
writeFixture(t, root, "package.json", `{"name":"my-app","version":"1.0.0"}`)
writeFixture(t, root, "src/utils/helper.ts", "export function help() {}")
ip := deriveTSPackagePath(root+"/src/utils/helper.ts", root)
if ip == "" {
t.Errorf("TS package path is empty, want non-empty")
}
if !strings.HasPrefix(ip, "my-app") {
t.Errorf("TS package path = %q, want prefix 'my-app'", ip)
}
}
// Test_A_SymbolDepEdge_NonGo verifies that two PHP files where one declares
// a namespace and the other has that namespace in its import path produce a
// symbol-dep edge in buildEdges.
func Test_A_SymbolDepEdge_NonGo(t *testing.T) {
t.Parallel()
// Build a minimal gitState with two PHP files that share an import.
// fileA declares "App\Services" and fileB imports it.
fsA := &FileSymbols{
Path: "app/Services/UserService.php",
Language: "php",
ImportPath: `App\Services`,
}
fsB := &FileSymbols{
Path: "app/Http/UserController.php",
Language: "php",
Imports: []string{`App\Services`},
}
symbols := map[string]*FileSymbols{
fsA.Path: fsA,
fsB.Path: fsB,
}
gs := &gitState{
Files: []fileChange{
{Path: fsA.Path, Language: "php", Type: "feat"},
{Path: fsB.Path, Language: "php", Type: "feat"},
},
}
edges := buildEdges(gs, symbols)
found := false
for _, e := range edges {
if e.Reason == "symbol-dep" {
found = true
if e.Weight != WeightSymbolDep {
t.Errorf("symbol-dep weight for PHP = %v, want %v (WeightSymbolDep)", e.Weight, WeightSymbolDep)
}
}
}
if !found {
t.Errorf("no symbol-dep edge found for PHP files with matching import paths; edges=%+v", edges)
}
}
// Test_A_SymbolDepEdge_Go verifies Go files still get WeightSymbolDep (0.8).
func Test_A_SymbolDepEdge_Go(t *testing.T) {
t.Parallel()
fsA := &FileSymbols{
Path: "internal/db/db.go",
Language: "go",
ImportPath: "github.com/example/app/internal/db",
}
fsB := &FileSymbols{
Path: "cmd/server/main.go",
Language: "go",
Imports: []string{"github.com/example/app/internal/db"},
}
symbols := map[string]*FileSymbols{
fsA.Path: fsA,
fsB.Path: fsB,
}
gs := &gitState{
Files: []fileChange{
{Path: fsA.Path, Language: "go", Type: "feat"},
{Path: fsB.Path, Language: "go", Type: "feat"},
},
}
edges := buildEdges(gs, symbols)
found := false
for _, e := range edges {
if e.Reason == "symbol-dep" {
found = true
if e.Weight != WeightSymbolDep {
t.Errorf("symbol-dep weight for Go = %v, want %v (WeightSymbolDep)", e.Weight, WeightSymbolDep)
}
}
}
if !found {
t.Errorf("no symbol-dep edge found for Go files with matching import paths; edges=%+v", edges)
}
}
// --- B. Signature-aware symbol deltas ---
// Test_B_Modified_DetectedOnSigChange verifies that a function whose signature
// changes (but name stays the same) appears in Modified, not Added/Removed.
func Test_B_Modified_DetectedOnSigChange(t *testing.T) {
t.Parallel()
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
root := initTestRepo(t,
map[string]string{
"go.mod": "module fixture\ngo 1.22\n",
"util.go": "package main\nfunc Process(x int) int { return x }\n",
},
map[string]string{
// Signature changed: added a second parameter.
"util.go": "package main\nfunc Process(x int, y int) int { return x + y }\n",
},
)
got, err := AnalyzeCommit(context.Background(), AnalyzeOptions{Root: root})
if err != nil {
t.Fatalf("AnalyzeCommit: %v", err)
}
// Find the group for util.go.
for _, g := range got.Groups {
if containsAll(g.Files, "util.go") {
// The suggested message should mention "modify" for Process.
if !strings.Contains(g.SuggestedMsg, "modify") {
t.Errorf("SuggestedMsg = %q, want it to contain 'modify'", g.SuggestedMsg)
}
return
}
}
t.Errorf("no group found for util.go; groups=%+v", got.Groups)
}
// Test_B_BulletList_WhenMoreThanThreeDeltas verifies multi-line bullet format.
func Test_B_BulletList_WhenMoreThanThreeDeltas(t *testing.T) {
t.Parallel()
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
root := initTestRepo(t,
map[string]string{
"go.mod": "module fixture\ngo 1.22\n",
"svc.go": "package main\nfunc A() {}\nfunc B() {}\n",
},
map[string]string{
// 4 new symbols (C, D, E, F) → total=4 > 3, triggers bullet list.
"svc.go": "package main\nfunc A() {}\nfunc B() {}\nfunc C() {}\nfunc D() {}\nfunc E() {}\nfunc F() {}\n",
},
)
got, err := AnalyzeCommit(context.Background(), AnalyzeOptions{Root: root})
if err != nil {
t.Fatalf("AnalyzeCommit: %v", err)
}
for _, g := range got.Groups {
if containsAll(g.Files, "svc.go") {
if !strings.Contains(g.SuggestedMsg, "\n- ") {
t.Errorf("SuggestedMsg = %q, want bullet-list format (containing '\\n- ')", g.SuggestedMsg)
}
return
}
}
t.Errorf("no group for svc.go; groups=%+v", got.Groups)
}
// --- C. Breaking-change detection ---
// Test_C_Breaking_ExportedRemoval verifies feat! promotion when an exported
// function is removed.
func Test_C_Breaking_ExportedRemoval(t *testing.T) {
t.Parallel()
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
root := initTestRepo(t,
map[string]string{
"go.mod": "module fixture\ngo 1.22\n",
"api.go": "package main\nfunc PublicAPI() {}\nfunc Helper() {}\n",
},
map[string]string{
// PublicAPI removed — should trigger breaking.
"api.go": "package main\nfunc Helper() {}\n",
},
)
got, err := AnalyzeCommit(context.Background(), AnalyzeOptions{Root: root})
if err != nil {
t.Fatalf("AnalyzeCommit: %v", err)
}
for _, g := range got.Groups {
if containsAll(g.Files, "api.go") {
if !g.Breaking {
t.Errorf("group.Breaking = false, want true (exported func removed)")
}
if !strings.HasPrefix(g.SuggestedMsg, "feat!") && !strings.HasPrefix(g.SuggestedMsg, "fix!") {
t.Errorf("SuggestedMsg = %q, want feat!/fix! prefix", g.SuggestedMsg)
}
return
}
}
t.Errorf("no group for api.go; groups=%+v", got.Groups)
}
// Test_C_Breaking_UnexportedRemoval verifies that removing an unexported
// function does NOT trigger breaking.
func Test_C_Breaking_UnexportedRemoval(t *testing.T) {
t.Parallel()
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
root := initTestRepo(t,
map[string]string{
"go.mod": "module fixture\ngo 1.22\n",
"intern.go": "package main\nfunc helper() {}\nfunc anotherHelper() {}\n",
},
map[string]string{
// helper removed — unexported, must NOT trigger breaking.
"intern.go": "package main\nfunc anotherHelper() {}\n",
},
)
got, err := AnalyzeCommit(context.Background(), AnalyzeOptions{Root: root})
if err != nil {
t.Fatalf("AnalyzeCommit: %v", err)
}
for _, g := range got.Groups {
if containsAll(g.Files, "intern.go") {
if g.Breaking {
t.Errorf("group.Breaking = true, want false (unexported func removed)")
}
if strings.HasPrefix(g.SuggestedMsg, "feat!") || strings.HasPrefix(g.SuggestedMsg, "fix!") {
t.Errorf("SuggestedMsg = %q has breaking prefix, want plain feat/fix", g.SuggestedMsg)
}
return
}
}
t.Errorf("no group for intern.go; groups=%+v", got.Groups)
}
// Test_C_BreakingCount verifies that BreakingCount is incremented per breaking group.
func Test_C_BreakingCount(t *testing.T) {
t.Parallel()
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
root := initTestRepo(t,
map[string]string{
"go.mod": "module fixture\ngo 1.22\n",
"api.go": "package main\nfunc PublicAPI() {}\n",
},
map[string]string{
"api.go": "package main\n// PublicAPI removed\n",
},
)
got, err := AnalyzeCommit(context.Background(), AnalyzeOptions{Root: root})
if err != nil {
t.Fatalf("AnalyzeCommit: %v", err)
}
if got.BreakingCount < 1 {
t.Errorf("BreakingCount = %d, want >= 1", got.BreakingCount)
}
}
// Test_EdgeWeights_ClusteringContract pins the invariant that every
// cluster-forming edge weight exceeds DefaultConfidenceCutoff, and every
// refine-only weight is below it. Bumping a weight or the cutoff in
// isolation must break this test loudly instead of silently disabling
// clustering for one edge type (as nearly happened with the pre-merge
// WeightSymbolDepDerived = 0.6 variant).
func Test_EdgeWeights_ClusteringContract(t *testing.T) {
t.Parallel()
clusterForming := map[string]float64{
"test-pair": WeightTestPair,
"symbol-dep": WeightSymbolDep,
}
refineOnly := map[string]float64{
"co-change": WeightCoChange,
"sibling": WeightSibling,
}
for name, w := range clusterForming {
if w < DefaultConfidenceCutoff {
t.Errorf("%s weight %v < cutoff %v — edge cannot form a cluster", name, w, DefaultConfidenceCutoff)
}
}
for name, w := range refineOnly {
if w >= DefaultConfidenceCutoff {
t.Errorf("%s weight %v >= cutoff %v — refine-only edge would form clusters", name, w, DefaultConfidenceCutoff)
}
}
}
// --- E. Parse-failure guard ---
// Test_E_ParseFailure_NoBogusRemoval pins the invariant that an empty
// post-symbols result for a file that still exists on disk does NOT produce
// a bogus all-removed delta or flip Breaking=true. Mirrors the bug where
// a transiently-malformed file (mid-write by a formatter hook) caused
// every HEAD symbol to be reported as removed.
func Test_E_ParseFailure_NoBogusRemoval(t *testing.T) {
t.Parallel()
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
root := initTestRepo(t,
map[string]string{
"go.mod": "module fixture\ngo 1.22\n",
"api.go": "package main\nfunc PublicAPI() {}\nfunc Helper() {}\n",
},
map[string]string{
"api.go": "package main\nfunc PublicAPI() {}\nfunc Helper() {}\nfunc Added() {}\n",
},
)
files := []fileChange{
{Path: "api.go", Language: "go", Status: "M", IndexStatus: "."},
}
// Simulate a parse failure: parseDirtyFiles only inserts on successful
// non-nil parse, so an absent key is the real-world parse-failure signal.
postSymbols := map[string]*FileSymbols{}
deltas, skipped := computeSymbolDeltas(context.Background(), root, files, postSymbols)
if d, ok := deltas[files[0].Path]; ok {
if len(d.Removed) > 0 {
t.Errorf("delta.Removed = %v, want empty (parse-failure guard should suppress removals)", d.Removed)
}
if d.Breaking {
t.Errorf("delta.Breaking = true, want false (parse failure must not flip Breaking)")
}
}
foundSkipped := false
for _, p := range skipped {
if p == "api.go" {
foundSkipped = true
break
}
}
if !foundSkipped {
t.Errorf("skipped = %v, want to contain %q (parse-failure guard should report the path)", skipped, "api.go")
}
}
// Test_E_ParseFailure_DeletedFileStillRemoves verifies the guard does NOT
// trigger for genuinely deleted files: a file with Status="D" and no post
// content should still produce removed-symbol deltas as before, so legitimate
// deletions still surface in commit messages.
func Test_E_ParseFailure_DeletedFileStillRemoves(t *testing.T) {
t.Parallel()
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
root := initTestRepo(t,
map[string]string{
"go.mod": "module fixture\ngo 1.22\n",
"gone.go": "package main\nfunc Removed() {}\n",
},
map[string]string{},
)
files := []fileChange{
{Path: "gone.go", Language: "go", Status: "D", IndexStatus: "."},
}
postSymbols := map[string]*FileSymbols{}
deltas, skipped := computeSymbolDeltas(context.Background(), root, files, postSymbols)
for _, p := range skipped {
if p == "gone.go" {
t.Errorf("skipped contains %q but file was deleted (Status=D); guard must not trigger for deletions", p)
}
}
if d, ok := deltas["gone.go"]; ok {
if len(d.Removed) == 0 {
t.Errorf("delta.Removed for deleted file = empty, want non-empty (genuine deletions must still emit removed list); delta=%+v", d)
}
}
}