Repository navigation
Expand file tree
/
Copy pathwalk_context_test.go
More file actions
100 lines (84 loc) · 2.13 KB
/
Copy pathwalk_context_test.go
File metadata and controls
100 lines (84 loc) · 2.13 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
package structwalker
import (
"context"
"errors"
"reflect"
"testing"
)
type ctxKey struct{}
func TestWalkContext_StopsWhenCancelled(t *testing.T) {
type S struct {
A, B, C string
}
ctx, cancel := context.WithCancel(context.Background())
var seen []string
w := New()
w.HandleAll(func(fc FieldContext) error {
seen = append(seen, fc.Path)
cancel()
return nil
})
err := w.WalkContext(ctx, &S{})
if !errors.Is(err, context.Canceled) {
t.Errorf("got %v, want context.Canceled", err)
}
if len(seen) != 1 {
t.Errorf("handlers ran on %v after cancellation", seen)
}
}
func TestWalkContext_OneWalkerManyContexts(t *testing.T) {
type S struct {
Name string
}
w := New()
w.HandleAll(func(FieldContext) error { return nil })
done, cancel := context.WithCancel(context.Background())
cancel()
if err := w.WalkContext(done, &S{}); !errors.Is(err, context.Canceled) {
t.Errorf("got %v, want context.Canceled", err)
}
if err := w.WalkContext(context.Background(), &S{}); err != nil {
t.Errorf("a finished context leaked into the next walk: %v", err)
}
if err := w.Walk(&S{}); err != nil {
t.Errorf("Walk: %v", err)
}
}
func TestFieldContext_Context(t *testing.T) {
type Inner struct {
Name string
}
type S struct {
Inner Inner
}
ctx := context.WithValue(context.Background(), ctxKey{}, "request-1")
var got []any
w := New()
w.HandleAll(func(fc FieldContext) error {
got = append(got, fc.Context().Value(ctxKey{}))
return nil
})
if err := w.WalkValueContext(ctx, reflect.ValueOf(&S{})); err != nil {
t.Fatal(err)
}
if len(got) != 2 || got[0] != "request-1" || got[1] != "request-1" {
t.Errorf("got %v", got)
}
if (FieldContext{}).Context() == nil {
t.Error("Context must not return nil")
}
}
func TestWalkContext_CancellationBeatsCollectedErrors(t *testing.T) {
type S struct {
A, B string
}
ctx, cancel := context.WithCancel(context.Background())
w := New(WithErrorMode(CollectErrors))
w.HandleAll(func(FieldContext) error {
cancel()
return errors.New("invalid")
})
if err := w.WalkContext(ctx, &S{}); !errors.Is(err, context.Canceled) {
t.Errorf("got %v, want context.Canceled", err)
}
}