-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscope_test.go
More file actions
1478 lines (1268 loc) · 37.6 KB
/
scope_test.go
File metadata and controls
1478 lines (1268 loc) · 37.6 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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package samurai
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"runtime"
"strings"
"sync"
"testing"
)
func TestScopeBasicVariables(t *testing.T) {
Run(t, func(s *Scope) {
var counter int
s.Test("setup", func(_ context.Context, w W) {
counter = 42
}, func(s *Scope) {
s.Test("Check", func(_ context.Context, w W) {
if counter != 42 {
w.Testing().Errorf("expected 42, got %d", counter)
}
})
})
})
}
func TestScopeParallelIsolation(t *testing.T) {
Run(t, func(s *Scope) {
var value int // Each path gets its own copy (builder re-runs per path)
s.Test("setup", func(_ context.Context, w W) {
// value starts at 0 for every path — proves no cross-path leakage
if value != 0 {
w.Testing().Errorf("expected value=0 before setup, got %d", value)
}
value = 100
}, func(s *Scope) {
s.Test("Path1", func(_ context.Context, w W) {
// value was set to 100 by parent setup for THIS path's execution
if value != 100 {
w.Testing().Errorf("Path1: expected value=100, got %d", value)
}
value = 1 // mutation only visible to this path
})
s.Test("Path2", func(_ context.Context, w W) {
// value is still 100, not 1 — Path1's mutation didn't leak
if value != 100 {
w.Testing().Errorf("Path2: expected value=100, got %d", value)
}
value = 2
})
s.Test("Path3", func(_ context.Context, w W) {
if value != 100 {
w.Testing().Errorf("Path3: expected value=100, got %d", value)
}
value = 3
})
})
})
}
func TestScopeNestedVariables(t *testing.T) {
Run(t, func(s *Scope) {
var db string
s.Test("setup database", func(_ context.Context, w W) {
db = "test-db"
}, func(s *Scope) {
var user string
s.Test("create user", func(_ context.Context, w W) {
user = db + "-user"
}, func(s *Scope) {
s.Test("Check", func(_ context.Context, w W) {
if user != "test-db-user" {
w.Testing().Errorf("expected test-db-user, got %s", user)
}
})
})
})
})
}
func TestScopeNoDoubleExecution(t *testing.T) {
var execCount int
var mu sync.Mutex
Run(t, func(s *Scope) {
s.Test("setup", func(_ context.Context, w W) {
mu.Lock()
execCount++
mu.Unlock()
}, func(s *Scope) {
s.Test("A", func(_ context.Context, _ W) {})
s.Test("B", func(_ context.Context, _ W) {})
})
}, Sequential())
// Root's Test should execute twice (once for path A, once for path B)
// NOT during discovery + execution = would be 4
if execCount != 2 {
t.Errorf("expected 2 executions, got %d", execCount)
}
}
func TestScopeWithReset(t *testing.T) {
var resetOrder []string
var mu sync.Mutex
Run(t, func(s *Scope) {
var resource string
s.Test("open resource", func(_ context.Context, w W) {
resource = "opened"
w.Cleanup(func() {
mu.Lock()
resetOrder = append(resetOrder, "root-reset")
mu.Unlock()
})
}, func(s *Scope) {
s.Test("use resource", func(_ context.Context, w W) {
w.Cleanup(func() {
mu.Lock()
resetOrder = append(resetOrder, "child-reset")
mu.Unlock()
})
}, func(s *Scope) {
s.Test("it", func(_ context.Context, w W) {
if resource != "opened" {
w.Testing().Error("expected resource to be opened")
}
})
})
})
}, Sequential())
// Cleanups run in LIFO order within each scope, inner scopes first
if len(resetOrder) != 2 {
t.Errorf("expected 2 resets, got %d", len(resetOrder))
}
if len(resetOrder) == 2 && (resetOrder[0] != "child-reset" || resetOrder[1] != "root-reset") {
t.Errorf("expected [child-reset, root-reset], got %v", resetOrder)
}
}
func TestScopeDeeplyNested(t *testing.T) {
Run(t, func(s *Scope) {
var level1 string
s.Test("Level1", func(_ context.Context, w W) {
level1 = "L1"
}, func(s *Scope) {
var level2 string
s.Test("Level2", func(_ context.Context, w W) {
level2 = level1 + "-L2"
}, func(s *Scope) {
var level3 string
s.Test("Level3", func(_ context.Context, w W) {
level3 = level2 + "-L3"
}, func(s *Scope) {
s.Test("Level4", func(_ context.Context, w W) {
expected := "L1-L2-L3"
if level3 != expected {
w.Testing().Errorf("expected %s, got %s", expected, level3)
}
})
})
})
})
})
}
func TestScopeMultipleBranches(t *testing.T) {
Run(t, func(s *Scope) {
var prefix string
s.Test("setup", func(_ context.Context, w W) {
prefix = "root"
}, func(s *Scope) {
s.Test("A", func(_ context.Context, w W) {
expected := "root"
if prefix != expected {
w.Testing().Errorf("A: expected prefix=%s, got %s", expected, prefix)
}
})
s.Test("B leaf", func(_ context.Context, w W) {
// just consume prefix — setup set it to "root"
if prefix != "root" {
w.Testing().Errorf("B: expected prefix=root, got %s", prefix)
}
})
})
})
}
func TestScopeMultipleBranchesV2(t *testing.T) {
Run(t, func(s *Scope) {
var prefix string
s.Test("setup", func(_ context.Context, w W) {
prefix = "root"
}, func(s *Scope) {
s.Test("A", func(_ context.Context, w W) {
if prefix != "root" {
w.Testing().Errorf("A: expected prefix=root, got %s", prefix)
}
})
s.Test("B setup", func(_ context.Context, w W) {
// bValue computed inside fn
}, func(s *Scope) {
s.Test("B1", func(_ context.Context, w W) {
bValue := prefix + "-B"
if bValue != "root-B" {
w.Testing().Errorf("B1: expected root-B, got %s", bValue)
}
})
s.Test("B2", func(_ context.Context, w W) {
bValue := prefix + "-B"
if bValue != "root-B" {
w.Testing().Errorf("B2: expected root-B, got %s", bValue)
}
})
s.Test("B3", func(_ context.Context, w W) {
bValue := prefix + "-B"
if bValue != "root-B" {
w.Testing().Errorf("B3: expected root-B, got %s", bValue)
}
})
})
})
})
}
func TestScopeHighConcurrency(t *testing.T) {
const numPaths = 100
Run(t, func(s *Scope) {
var pathValue int
for i := range numPaths {
name := fmt.Sprintf("Path%03d", i)
expected := i
s.Test(name, func(_ context.Context, w W) {
pathValue = expected
// Yield to encourage scheduler interleaving
runtime.Gosched()
if pathValue != expected {
w.Testing().Errorf("%s: expected %d, got %d", name, expected, pathValue)
}
})
}
})
}
func TestScopeSequential(t *testing.T) {
var order []string
var mu sync.Mutex
Run(t, func(s *Scope) {
s.Test("First", func(_ context.Context, w W) {
mu.Lock()
order = append(order, "first")
mu.Unlock()
})
s.Test("Second", func(_ context.Context, w W) {
mu.Lock()
order = append(order, "second")
mu.Unlock()
})
s.Test("Third", func(_ context.Context, w W) {
mu.Lock()
order = append(order, "third")
mu.Unlock()
})
}, Sequential())
// With Sequential(), order should be deterministic
if len(order) != 3 {
t.Errorf("expected 3 items, got %d", len(order))
}
if order[0] != "first" || order[1] != "second" || order[2] != "third" {
t.Errorf("unexpected order: %v", order)
}
}
func TestScopeContextAccess(t *testing.T) {
Run(t, func(s *Scope) {
s.Test("CheckContext", func(ctx context.Context, w W) {
if ctx == nil {
w.Testing().Error("context should not be nil")
}
if w.Testing() == nil {
t.Error("testing.T should not be nil")
}
// Context should be live (not canceled) during test execution
if err := ctx.Err(); err != nil {
w.Testing().Errorf("context should not be canceled during test, got: %v", err)
}
})
})
}
func TestScopeTestWithChildren(t *testing.T) {
Run(t, func(s *Scope) {
var db string
var user string
s.Test("setup db", func(_ context.Context, w W) {
db = "test-db"
}, func(s *Scope) {
s.Test("user exists", func(_ context.Context, w W) {
user = db + "-user"
}, func(s *Scope) {
s.Test("can update email", func(_ context.Context, w W) {
expected := "test-db-user"
if user != expected {
w.Testing().Errorf("expected %s, got %s", expected, user)
}
})
s.Test("can delete", func(_ context.Context, w W) {
if user == "" {
w.Testing().Error("user should exist")
}
})
})
s.Test("can query all", func(_ context.Context, w W) {
if db != "test-db" {
w.Testing().Errorf("expected test-db, got %s", db)
}
})
})
})
}
func TestScopeThenTestShortcut(t *testing.T) {
var executed []string
var mu sync.Mutex
Run(t, func(s *Scope) {
s.Test("setup", func(_ context.Context, w W) {
mu.Lock()
executed = append(executed, "root")
mu.Unlock()
}, func(s *Scope) {
s.Test("Leaf1", func(_ context.Context, w W) {
mu.Lock()
executed = append(executed, "leaf1")
mu.Unlock()
})
s.Test("Leaf2", func(_ context.Context, w W) {
mu.Lock()
executed = append(executed, "leaf2")
mu.Unlock()
})
})
}, Sequential())
// Should have executed root twice (once per leaf) + each leaf once
// Path 1: setup -> leaf1
// Path 2: setup -> leaf2
if len(executed) != 4 {
t.Errorf("expected 4 executions, got %d: %v", len(executed), executed)
}
}
// --- Validation tests ---
func TestScopeDuplicateSiblingNamesFatal(t *testing.T) {
_, err := collectScopedPaths(func(s *Scope) {
s.Test("same", func(_ context.Context, _ W) {})
s.Test("same", func(_ context.Context, _ W) {}) // duplicate!
})
if err == nil {
t.Fatal("expected validation error for duplicate sibling names")
}
}
func TestScopeDuplicateNameNestedFatal(t *testing.T) {
_, err := collectScopedPaths(func(s *Scope) {
s.Test("parent", func(_ context.Context, _ W) {}, func(s *Scope) {
s.Test("same", func(_ context.Context, _ W) {})
s.Test("same", func(_ context.Context, _ W) {}) // duplicate in nested scope!
})
})
if err == nil {
t.Fatal("expected validation error for duplicate sibling names in nested scope")
}
}
func TestScopeEmptyBuilderFatal(t *testing.T) {
_, err := collectScopedPaths(func(s *Scope) {
// empty builder - no Test calls
})
if err == nil {
t.Fatal("expected validation error for empty builder")
}
}
func TestScopeTestWithEmptyBuilderFatal(t *testing.T) {
_, err := collectScopedPaths(func(s *Scope) {
s.Test("parent", func(_ context.Context, _ W) {}, func(s *Scope) {
// builder with no tests inside
})
})
if err == nil {
t.Fatal("expected validation error for Test with empty builder")
}
}
// Standalone Test (no children) is valid — it's a self-contained leaf test
func TestScopeStandaloneTest(t *testing.T) {
var executed bool
Run(t, func(s *Scope) {
s.Test("standalone", func(_ context.Context, w W) {
executed = true
})
}, Sequential())
if !executed {
t.Error("standalone Test should have executed")
}
}
// Multiple standalone Tests are valid — they are siblings
func TestScopeMultipleStandaloneTests(t *testing.T) {
var count int
var mu sync.Mutex
Run(t, func(s *Scope) {
s.Test("A", func(_ context.Context, w W) {
mu.Lock()
count++
mu.Unlock()
})
s.Test("B", func(_ context.Context, w W) {
mu.Lock()
count++
mu.Unlock()
})
s.Test("C", func(_ context.Context, w W) {
mu.Lock()
count++
mu.Unlock()
})
}, Sequential())
if count != 3 {
t.Errorf("expected 3 executions, got %d", count)
}
}
// --- Edge case tests ---
func TestScopeLeafHasCleanup(t *testing.T) {
var cleanupRan bool
Run(t, func(s *Scope) {
s.Test("leaf with cleanup", func(_ context.Context, w W) {
w.Cleanup(func() {
cleanupRan = true
})
})
}, Sequential())
if !cleanupRan {
t.Error("cleanup should have run for leaf test")
}
}
// --- Panic recovery test ---
// testPanicCleanupSubprocess is the in-subprocess test for TestScopePanicRecovery.
func testPanicCleanupSubprocess(t *testing.T) {
Run(t, func(s *Scope) {
s.Test("setup", func(_ context.Context, w W) {
w.Cleanup(func() {
fmt.Println("CLEANUP_RAN")
})
}, func(s *Scope) {
s.Test("it panics", func(_ context.Context, w W) {
panic("intentional panic")
})
})
}, Sequential())
}
func TestScopePanicRecovery(t *testing.T) {
if os.Getenv("TEST_PANIC_CLEANUP") == "1" {
testPanicCleanupSubprocess(t)
return
}
cmd := exec.Command(os.Args[0], "-test.run=^TestScopePanicRecovery$", "-test.v")
cmd.Env = append(os.Environ(), "TEST_PANIC_CLEANUP=1")
out, err := cmd.CombinedOutput()
output := string(out)
if len(output) == 0 && err != nil {
t.Fatalf("subprocess produced no output (failed to run?): %v", err)
}
// The subprocess should fail (the inner test panics and is marked failed)
if !strings.Contains(output, "panic: intentional panic") {
t.Errorf("expected panic to be reported, output:\n%s", output)
}
// Verify the cleanup actually ran despite the panic
if !strings.Contains(output, "CLEANUP_RAN") {
t.Errorf("cleanup should have run after panic, output:\n%s", output)
}
}
// --- Test-panic cleanup test ---
func testTestPanicCleanupSubprocess(t *testing.T) {
Run(t, func(s *Scope) {
s.Test("panicking setup", func(_ context.Context, w W) {
w.Cleanup(func() {
fmt.Println("TEST_CLEANUP_RAN")
})
panic("test panic")
}, func(s *Scope) {
s.Test("unreachable", func(_ context.Context, _ W) {})
})
}, Sequential())
}
func TestScopeTestPanicCleanup(t *testing.T) {
if os.Getenv("TEST_TEST_PANIC_CLEANUP") == "1" {
testTestPanicCleanupSubprocess(t)
return
}
cmd := exec.Command(os.Args[0], "-test.run=^TestScopeTestPanicCleanup$", "-test.v")
cmd.Env = append(os.Environ(), "TEST_TEST_PANIC_CLEANUP=1")
out, err := cmd.CombinedOutput()
output := string(out)
if len(output) == 0 && err != nil {
t.Fatalf("subprocess produced no output (failed to run?): %v", err)
}
if !strings.Contains(output, "panic: test panic") {
t.Errorf("expected Test panic to be reported, output:\n%s", output)
}
if !strings.Contains(output, "TEST_CLEANUP_RAN") {
t.Errorf("cleanup registered before Test panic should have run, output:\n%s", output)
}
}
// --- Nil function and empty name validation tests ---
func TestScopeTestNilFnPanic(t *testing.T) {
defer func() { requireSamuraiPanic(t, recover()) }()
s := &Scope{mode: modeDiscovery}
s.Test("x", nil)
}
func TestScopeTestEmptyNamePanic(t *testing.T) {
defer func() { requireSamuraiPanic(t, recover()) }()
s := &Scope{mode: modeDiscovery}
s.Test("", func(_ context.Context, _ W) {})
}
func TestScopeTestMultipleBuildersError(t *testing.T) {
defer func() { requireSamuraiPanic(t, recover()) }()
s := &Scope{mode: modeDiscovery}
b := func(s *Scope) {}
s.Test("x", func(_ context.Context, _ W) {}, b, b)
}
func TestScopeTestNilBuilderArgError(t *testing.T) {
defer func() { requireSamuraiPanic(t, recover()) }()
s := &Scope{mode: modeDiscovery}
s.Test("x", func(_ context.Context, _ W) {}, nil)
}
func testCleanupNilSubprocess(t *testing.T) {
Run(t, func(s *Scope) {
s.Test("setup", func(_ context.Context, w W) {
w.Cleanup(nil)
}, func(s *Scope) {
s.Test("x", func(_ context.Context, _ W) {})
})
}, Sequential())
}
func TestScopeCleanupNilPanic(t *testing.T) {
if os.Getenv("TEST_CLEANUP_NIL") == "1" {
testCleanupNilSubprocess(t)
return
}
cmd := exec.Command(os.Args[0], "-test.run=^TestScopeCleanupNilPanic$", "-test.v")
cmd.Env = append(os.Environ(), "TEST_CLEANUP_NIL=1")
out, err := cmd.CombinedOutput()
output := string(out)
if len(output) == 0 && err != nil {
t.Fatalf("subprocess produced no output (failed to run?): %v", err)
}
if !strings.Contains(output, "Cleanup called with nil function") {
t.Errorf("expected Cleanup nil panic to be reported, output:\n%s", output)
}
}
func TestScopeDiscoveryPanicRecovery(t *testing.T) {
_, err := collectScopedPaths(func(s *Scope) {
panic("boom during discovery")
})
if err == nil {
t.Fatal("expected error from discovery panic")
}
if !strings.Contains(err.Error(), "boom during discovery") {
t.Errorf("expected panic message in error, got: %v", err)
}
}
// --- Top-level t.Parallel() auto-call tests ---
// TestRunMarksTopLevelParallel verifies that samurai.Run marks the top-level
// *testing.T as parallel unless Sequential() is passed. The test uses Go's
// own invariant — calling t.Parallel() twice on the same *testing.T panics
// with "t.Parallel called multiple times" — as a deterministic oracle.
func TestRunMarksTopLevelParallel(t *testing.T) {
defer func() {
r := recover()
if r == nil {
t.Error("expected panic from second t.Parallel() — samurai did not mark top-level t parallel")
return
}
if !strings.Contains(fmt.Sprint(r), "t.Parallel called multiple times") {
t.Errorf("unexpected panic: %v", r)
}
}()
Run(t, func(s *Scope) {
s.Test("x", func(_ context.Context, _ W) {})
})
// samurai.Run has already called t.Parallel() internally — a second call
// must panic. If it does not, samurai failed to parallelize the top-level.
t.Parallel()
}
// TestRunSequentialDoesNotMarkTopLevelParallel verifies that Sequential()
// suppresses the auto-parallel call on the top-level t. The explicit
// t.Parallel() below must succeed (no panic) — proving samurai left the
// top-level t alone.
func TestRunSequentialDoesNotMarkTopLevelParallel(t *testing.T) {
Run(t, func(s *Scope) {
s.Test("x", func(_ context.Context, _ W) {})
}, Sequential())
// Must succeed — Sequential() means samurai did NOT mark t parallel.
t.Parallel()
}
// --- Conflicting options test ---
func TestScopeConflictingOptionsLastWins(t *testing.T) {
var order []string
var mu sync.Mutex
Run(t, func(s *Scope) {
s.Test("First", func(_ context.Context, w W) {
mu.Lock()
order = append(order, "first")
mu.Unlock()
})
s.Test("Second", func(_ context.Context, w W) {
mu.Lock()
order = append(order, "second")
mu.Unlock()
})
}, Sequential(), Parallel(), Sequential()) // last wins: Sequential
if len(order) != 2 {
t.Fatalf("expected 2 items, got %d", len(order))
}
if order[0] != "first" || order[1] != "second" {
t.Errorf("expected sequential order [first, second], got %v", order)
}
}
// --- Scope sealed after builder returns ---
func TestScopeSealedAfterBuilder(t *testing.T) {
var captured *Scope
Run(t, func(s *Scope) {
captured = s
s.Test("ok", func(_ context.Context, _ W) {})
}, Sequential())
// After Run returns, calling Test on the captured scope should panic.
t.Run("Test", func(t *testing.T) {
defer func() { requireSamuraiPanic(t, recover()) }()
captured.Test("x", func(_ context.Context, _ W) {})
})
}
// --- Reject names containing / ---
func TestScopeTestSlashInNamePanic(t *testing.T) {
defer func() { requireSamuraiPanic(t, recover()) }()
s := &Scope{mode: modeDiscovery}
s.Test("foo/bar", func(_ context.Context, _ W) {})
}
// --- Run with nil builder ---
func TestRunNilBuilderPanic(t *testing.T) {
defer func() { requireSamuraiPanic(t, recover()) }()
Run(t, nil)
}
// --- Builder structure divergence between discovery and execution ---
func testStructureDivergenceSubprocess(t *testing.T) {
callCount := 0
Run(t, func(s *Scope) {
callCount++
if callCount == 1 {
// Discovery phase: declare child "A"
s.Test("A", func(_ context.Context, _ W) {})
} else {
// Execution phase: declare child "B" instead — different structure!
s.Test("B", func(_ context.Context, _ W) {})
}
}, Sequential())
}
func TestStructureDivergence(t *testing.T) {
if os.Getenv("TEST_STRUCTURE_DIVERGENCE") == "1" {
testStructureDivergenceSubprocess(t)
return
}
cmd := exec.Command(os.Args[0], "-test.run=^TestStructureDivergence$", "-test.v")
cmd.Env = append(os.Environ(), "TEST_STRUCTURE_DIVERGENCE=1")
out, err := cmd.CombinedOutput()
output := string(out)
if len(output) == 0 && err != nil {
t.Fatalf("subprocess produced no output (failed to run?): %v", err)
}
// The subprocess should panic with a samuraiErr about path not found
if !strings.Contains(output, "not found in scope") {
t.Errorf("expected structure divergence error, output:\n%s", output)
}
}
// --- Discovery panic recovery includes scope name ---
func TestDiscoveryPanicIncludesScopeName(t *testing.T) {
_, err := collectScopedPaths(func(s *Scope) {
s.Test("outer", func(_ context.Context, _ W) {}, func(s *Scope) {
s.Test("problematic-scope", func(_ context.Context, _ W) {}, func(s *Scope) {
panic("kaboom in child")
})
})
})
if err == nil {
t.Fatal("expected error from discovery panic in nested scope")
}
errMsg := err.Error()
if !strings.Contains(errMsg, "problematic-scope") {
t.Errorf("error should identify the scope that panicked, got: %v", errMsg)
}
if !strings.Contains(errMsg, "kaboom in child") {
t.Errorf("error should include the panic message, got: %v", errMsg)
}
}
// --- RunWith tests ---
type testContext struct {
*BaseContext
label string
}
func newTestContext(w W) *testContext {
return &testContext{BaseContext: w, label: "custom"}
}
func TestRunWithBasic(t *testing.T) {
RunWith(t, newTestContext, func(s *TestScope[*testContext]) {
var value int
s.Test("setup", func(_ context.Context, c *testContext) {
value = 42
}, func(s *TestScope[*testContext]) {
s.Test("receives factory value", func(_ context.Context, c *testContext) {
if c.Testing() == nil {
t.Fatal("expected non-nil testing.T in testContext")
}
if c.label != "custom" {
c.Testing().Errorf("expected label=custom, got %s", c.label)
}
if value != 42 {
c.Testing().Errorf("expected 42, got %d", value)
}
})
})
})
}
func TestRunWithFactoryPerPath(t *testing.T) {
var factoryCalls int
var mu sync.Mutex
factory := func(w W) *testContext {
mu.Lock()
factoryCalls++
mu.Unlock()
return &testContext{BaseContext: w, label: "custom"}
}
RunWith(t, factory, func(s *TestScope[*testContext]) {
s.Test("setup", func(_ context.Context, c *testContext) {
// setup
}, func(s *TestScope[*testContext]) {
s.Test("A", func(_ context.Context, c *testContext) {})
s.Test("B", func(_ context.Context, c *testContext) {})
})
}, Sequential())
// Factory is called once per path (once per executeScope call).
// Path A: setup/A = 1 factory call
// Path B: setup/B = 1 factory call
// Total: 2 calls
if factoryCalls != 2 {
t.Errorf("expected 2 factory calls (one per path), got %d", factoryCalls)
}
}
func TestRunWithSharedState(t *testing.T) {
type statefulCtx struct {
*BaseContext
value string
}
RunWith(t, func(w W) *statefulCtx {
return &statefulCtx{BaseContext: w}
}, func(s *TestScope[*statefulCtx]) {
s.Test("set value", func(_ context.Context, c *statefulCtx) {
c.value = "hello"
}, func(s *TestScope[*statefulCtx]) {
s.Test("child sees value", func(_ context.Context, c *statefulCtx) {
if c.value != "hello" {
c.Testing().Errorf("expected \"hello\", got %q", c.value)
}
})
})
})
}
func TestRunWithFactoryCleanupRunsLast(t *testing.T) {
var order []string
var mu sync.Mutex
addOrder := func(s string) {
mu.Lock()
order = append(order, s)
mu.Unlock()
}
RunWith(t, func(w W) *testContext {
w.Cleanup(func() { addOrder("factory") })
return &testContext{BaseContext: w, label: "custom"}
}, func(s *TestScope[*testContext]) {
s.Test("parent", func(_ context.Context, c *testContext) {
c.Cleanup(func() { addOrder("parent") })
}, func(s *TestScope[*testContext]) {
s.Test("child", func(_ context.Context, c *testContext) {
c.Cleanup(func() { addOrder("child") })
})
})
}, Sequential())
expected := []string{"child", "parent", "factory"}
if len(order) != len(expected) {
t.Fatalf("expected %d cleanups, got %d: %v", len(expected), len(order), order)
}
for i, v := range expected {
if order[i] != v {
t.Errorf("cleanup[%d]: expected %q, got %q (full: %v)", i, v, order[i], order)
}
}
}
func TestRunWithDeeplyNestedSharedState(t *testing.T) {
type accumCtx struct {
*BaseContext
items []string
}
RunWith(t, func(w W) *accumCtx {
return &accumCtx{BaseContext: w}
}, func(s *TestScope[*accumCtx]) {
s.Test("L1", func(_ context.Context, c *accumCtx) {
c.items = append(c.items, "L1")
}, func(s *TestScope[*accumCtx]) {
s.Test("L2", func(_ context.Context, c *accumCtx) {
c.items = append(c.items, "L2")
}, func(s *TestScope[*accumCtx]) {
s.Test("L3", func(_ context.Context, c *accumCtx) {
c.items = append(c.items, "L3")
}, func(s *TestScope[*accumCtx]) {
s.Test("L4", func(_ context.Context, c *accumCtx) {
expected := "L1,L2,L3"
got := strings.Join(c.items, ",")
if got != expected {
c.Testing().Errorf("expected %q, got %q", expected, got)
}
})
})
})
})
})
}
func TestRunWithCleanup(t *testing.T) {
var cleanupOrder []string
var mu sync.Mutex
RunWith(t, newTestContext, func(s *TestScope[*testContext]) {
s.Test("setup", func(_ context.Context, c *testContext) {
c.Cleanup(func() {
mu.Lock()
cleanupOrder = append(cleanupOrder, "root-cleanup")
mu.Unlock()
})
}, func(s *TestScope[*testContext]) {
s.Test("child", func(_ context.Context, c *testContext) {
c.Cleanup(func() {
mu.Lock()
cleanupOrder = append(cleanupOrder, "child-cleanup")
mu.Unlock()
})
})
})
}, Sequential())
if len(cleanupOrder) != 2 {
t.Fatalf("expected 2 cleanups, got %d: %v", len(cleanupOrder), cleanupOrder)
}
if cleanupOrder[0] != "child-cleanup" || cleanupOrder[1] != "root-cleanup" {
t.Errorf("expected [child-cleanup, root-cleanup], got %v", cleanupOrder)
}
}
func TestRunWithDeeplyNested(t *testing.T) {
RunWith(t, newTestContext, func(s *TestScope[*testContext]) {
var l1 string
s.Test("L1", func(_ context.Context, c *testContext) {
l1 = "L1"
if c.label != "custom" {
c.Testing().Errorf("expected label=custom at L1, got %s", c.label)
}
}, func(s *TestScope[*testContext]) {
var l2 string
s.Test("L2", func(_ context.Context, c *testContext) {
l2 = l1 + "-L2"
}, func(s *TestScope[*testContext]) {
var l3 string
s.Test("L3", func(_ context.Context, c *testContext) {
l3 = l2 + "-L3"
}, func(s *TestScope[*testContext]) {
s.Test("L4", func(_ context.Context, c *testContext) {
expected := "L1-L2-L3"