-
Notifications
You must be signed in to change notification settings - Fork 657
Expand file tree
/
Copy pathcontext_test.go
More file actions
84 lines (69 loc) · 1.95 KB
/
context_test.go
File metadata and controls
84 lines (69 loc) · 1.95 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
package utilities
import (
"context"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestContextKeyString(t *testing.T) {
require.Equal(t, "gotrue api context key request_id", contextKey("request_id").String())
require.Equal(t, "gotrue api context key ", contextKey("").String())
}
func TestRequestIDRoundtrip(t *testing.T) {
t.Run("set then read", func(t *testing.T) {
ctx := WithRequestID(context.Background(), "abc-123")
require.Equal(t, "abc-123", GetRequestID(ctx))
})
t.Run("missing key returns empty string", func(t *testing.T) {
require.Equal(t, "", GetRequestID(context.Background()))
})
t.Run("set replaces previous value", func(t *testing.T) {
ctx := WithRequestID(context.Background(), "first")
ctx = WithRequestID(ctx, "second")
require.Equal(t, "second", GetRequestID(ctx))
})
t.Run("derived context inherits value", func(t *testing.T) {
ctx := WithRequestID(context.Background(), "parent-id")
child, cancel := context.WithCancel(ctx)
defer cancel()
require.Equal(t, "parent-id", GetRequestID(child))
})
}
func TestWaitForCleanup(t *testing.T) {
t.Run("returns when wait group is done", func(t *testing.T) {
var wg sync.WaitGroup
wg.Add(1)
go func() {
time.Sleep(10 * time.Millisecond)
wg.Done()
}()
done := make(chan struct{})
go func() {
defer close(done)
WaitForCleanup(context.Background(), &wg)
}()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("WaitForCleanup did not return after wg.Done()")
}
})
t.Run("returns when context is cancelled before wait group is done", func(t *testing.T) {
var wg sync.WaitGroup
wg.Add(1)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
WaitForCleanup(ctx, &wg)
}()
cancel()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("WaitForCleanup did not return after context cancellation")
}
wg.Done()
})
}