1 // Copyright 2014 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
19 // otherContext is a Context that's not one of the types defined in context.go.
20 // This lets us test code paths that differ based on the underlying type of the
22 type otherContext struct {
26 func TestBackground(t *testing.T) {
29 t.Fatalf("Background returned nil")
33 t.Errorf("<-c.Done() == %v want nothing (it should block)", x)
36 if got, want := fmt.Sprint(c), "context.Background"; got != want {
37 t.Errorf("Background().String() = %q want %q", got, want)
41 func TestTODO(t *testing.T) {
44 t.Fatalf("TODO returned nil")
48 t.Errorf("<-c.Done() == %v want nothing (it should block)", x)
51 if got, want := fmt.Sprint(c), "context.TODO"; got != want {
52 t.Errorf("TODO().String() = %q want %q", got, want)
56 func TestWithCancel(t *testing.T) {
57 c1, cancel := WithCancel(Background())
59 if got, want := fmt.Sprint(c1), "context.Background.WithCancel"; got != want {
60 t.Errorf("c1.String() = %q want %q", got, want)
64 c2, _ := WithCancel(o)
65 contexts := []Context{c1, o, c2}
67 for i, c := range contexts {
68 if d := c.Done(); d == nil {
69 t.Errorf("c[%d].Done() == %v want non-nil", i, d)
71 if e := c.Err(); e != nil {
72 t.Errorf("c[%d].Err() == %v want nil", i, e)
77 t.Errorf("<-c.Done() == %v want nothing (it should block)", x)
83 time.Sleep(100 * time.Millisecond) // let cancelation propagate
85 for i, c := range contexts {
89 t.Errorf("<-c[%d].Done() blocked, but shouldn't have", i)
91 if e := c.Err(); e != Canceled {
92 t.Errorf("c[%d].Err() == %v want %v", i, e, Canceled)
97 func TestParentFinishesChild(t *testing.T) {
99 // parent -> cancelChild
100 // parent -> valueChild -> timerChild
101 parent, cancel := WithCancel(Background())
102 cancelChild, stop := WithCancel(parent)
104 valueChild := WithValue(parent, "key", "value")
105 timerChild, stop := WithTimeout(valueChild, 10000*time.Hour)
109 case x := <-parent.Done():
110 t.Errorf("<-parent.Done() == %v want nothing (it should block)", x)
111 case x := <-cancelChild.Done():
112 t.Errorf("<-cancelChild.Done() == %v want nothing (it should block)", x)
113 case x := <-timerChild.Done():
114 t.Errorf("<-timerChild.Done() == %v want nothing (it should block)", x)
115 case x := <-valueChild.Done():
116 t.Errorf("<-valueChild.Done() == %v want nothing (it should block)", x)
120 // The parent's children should contain the two cancelable children.
121 pc := parent.(*cancelCtx)
122 cc := cancelChild.(*cancelCtx)
123 tc := timerChild.(*timerCtx)
125 if len(pc.children) != 2 || !pc.children[cc] || !pc.children[tc] {
126 t.Errorf("bad linkage: pc.children = %v, want %v and %v",
131 if p, ok := parentCancelCtx(cc.Context); !ok || p != pc {
132 t.Errorf("bad linkage: parentCancelCtx(cancelChild.Context) = %v, %v want %v, true", p, ok, pc)
134 if p, ok := parentCancelCtx(tc.Context); !ok || p != pc {
135 t.Errorf("bad linkage: parentCancelCtx(timerChild.Context) = %v, %v want %v, true", p, ok, pc)
141 if len(pc.children) != 0 {
142 t.Errorf("pc.cancel didn't clear pc.children = %v", pc.children)
146 // parent and children should all be finished.
147 check := func(ctx Context, name string) {
151 t.Errorf("<-%s.Done() blocked, but shouldn't have", name)
153 if e := ctx.Err(); e != Canceled {
154 t.Errorf("%s.Err() == %v want %v", name, e, Canceled)
157 check(parent, "parent")
158 check(cancelChild, "cancelChild")
159 check(valueChild, "valueChild")
160 check(timerChild, "timerChild")
162 // WithCancel should return a canceled context on a canceled parent.
163 precanceledChild := WithValue(parent, "key", "value")
165 case <-precanceledChild.Done():
167 t.Errorf("<-precanceledChild.Done() blocked, but shouldn't have")
169 if e := precanceledChild.Err(); e != Canceled {
170 t.Errorf("precanceledChild.Err() == %v want %v", e, Canceled)
174 func TestChildFinishesFirst(t *testing.T) {
175 cancelable, stop := WithCancel(Background())
177 for _, parent := range []Context{Background(), cancelable} {
178 child, cancel := WithCancel(parent)
181 case x := <-parent.Done():
182 t.Errorf("<-parent.Done() == %v want nothing (it should block)", x)
183 case x := <-child.Done():
184 t.Errorf("<-child.Done() == %v want nothing (it should block)", x)
188 cc := child.(*cancelCtx)
189 pc, pcok := parent.(*cancelCtx) // pcok == false when parent == Background()
190 if p, ok := parentCancelCtx(cc.Context); ok != pcok || (ok && pc != p) {
191 t.Errorf("bad linkage: parentCancelCtx(cc.Context) = %v, %v want %v, %v", p, ok, pc, pcok)
196 if len(pc.children) != 1 || !pc.children[cc] {
197 t.Errorf("bad linkage: pc.children = %v, cc = %v", pc.children, cc)
206 if len(pc.children) != 0 {
207 t.Errorf("child's cancel didn't remove self from pc.children = %v", pc.children)
212 // child should be finished.
216 t.Errorf("<-child.Done() blocked, but shouldn't have")
218 if e := child.Err(); e != Canceled {
219 t.Errorf("child.Err() == %v want %v", e, Canceled)
222 // parent should not be finished.
224 case x := <-parent.Done():
225 t.Errorf("<-parent.Done() == %v want nothing (it should block)", x)
228 if e := parent.Err(); e != nil {
229 t.Errorf("parent.Err() == %v want nil", e)
234 func testDeadline(c Context, wait time.Duration, t *testing.T) {
236 case <-time.After(wait):
237 t.Fatalf("context should have timed out")
240 if e := c.Err(); e != DeadlineExceeded {
241 t.Errorf("c.Err() == %v want %v", e, DeadlineExceeded)
245 func TestDeadline(t *testing.T) {
247 const timeUnit = 500 * time.Millisecond
248 c, _ := WithDeadline(Background(), time.Now().Add(1*timeUnit))
249 if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) {
250 t.Errorf("c.String() = %q want prefix %q", got, prefix)
252 testDeadline(c, 2*timeUnit, t)
254 c, _ = WithDeadline(Background(), time.Now().Add(1*timeUnit))
256 testDeadline(o, 2*timeUnit, t)
258 c, _ = WithDeadline(Background(), time.Now().Add(1*timeUnit))
260 c, _ = WithDeadline(o, time.Now().Add(3*timeUnit))
261 testDeadline(c, 2*timeUnit, t)
264 func TestTimeout(t *testing.T) {
266 const timeUnit = 500 * time.Millisecond
267 c, _ := WithTimeout(Background(), 1*timeUnit)
268 if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) {
269 t.Errorf("c.String() = %q want prefix %q", got, prefix)
271 testDeadline(c, 2*timeUnit, t)
273 c, _ = WithTimeout(Background(), 1*timeUnit)
275 testDeadline(o, 2*timeUnit, t)
277 c, _ = WithTimeout(Background(), 1*timeUnit)
279 c, _ = WithTimeout(o, 3*timeUnit)
280 testDeadline(c, 2*timeUnit, t)
283 func TestCanceledTimeout(t *testing.T) {
285 const timeUnit = 500 * time.Millisecond
286 c, _ := WithTimeout(Background(), 2*timeUnit)
288 c, cancel := WithTimeout(o, 4*timeUnit)
290 time.Sleep(1 * timeUnit) // let cancelation propagate
294 t.Errorf("<-c.Done() blocked, but shouldn't have")
296 if e := c.Err(); e != Canceled {
297 t.Errorf("c.Err() == %v want %v", e, Canceled)
305 var k2 = key2(1) // same int as k1, different type
306 var k3 = key2(3) // same type as k2, different int
308 func TestValues(t *testing.T) {
309 check := func(c Context, nm, v1, v2, v3 string) {
310 if v, ok := c.Value(k1).(string); ok == (len(v1) == 0) || v != v1 {
311 t.Errorf(`%s.Value(k1).(string) = %q, %t want %q, %t`, nm, v, ok, v1, len(v1) != 0)
313 if v, ok := c.Value(k2).(string); ok == (len(v2) == 0) || v != v2 {
314 t.Errorf(`%s.Value(k2).(string) = %q, %t want %q, %t`, nm, v, ok, v2, len(v2) != 0)
316 if v, ok := c.Value(k3).(string); ok == (len(v3) == 0) || v != v3 {
317 t.Errorf(`%s.Value(k3).(string) = %q, %t want %q, %t`, nm, v, ok, v3, len(v3) != 0)
322 check(c0, "c0", "", "", "")
324 c1 := WithValue(Background(), k1, "c1k1")
325 check(c1, "c1", "c1k1", "", "")
327 if got, want := fmt.Sprint(c1), `context.Background.WithValue(1, "c1k1")`; got != want {
328 t.Errorf("c.String() = %q want %q", got, want)
331 c2 := WithValue(c1, k2, "c2k2")
332 check(c2, "c2", "c1k1", "c2k2", "")
334 c3 := WithValue(c2, k3, "c3k3")
335 check(c3, "c2", "c1k1", "c2k2", "c3k3")
337 c4 := WithValue(c3, k1, nil)
338 check(c4, "c4", "", "c2k2", "c3k3")
340 o0 := otherContext{Background()}
341 check(o0, "o0", "", "", "")
343 o1 := otherContext{WithValue(Background(), k1, "c1k1")}
344 check(o1, "o1", "c1k1", "", "")
346 o2 := WithValue(o1, k2, "o2k2")
347 check(o2, "o2", "c1k1", "o2k2", "")
349 o3 := otherContext{c4}
350 check(o3, "o3", "", "c2k2", "c3k3")
352 o4 := WithValue(o3, k3, nil)
353 check(o4, "o4", "", "c2k2", "")
356 func TestAllocs(t *testing.T) {
358 for _, test := range []struct {
365 desc: "Background()",
366 f: func() { Background() },
371 desc: fmt.Sprintf("WithValue(bg, %v, nil)", k1),
373 c := WithValue(bg, k1, nil)
380 desc: "WithTimeout(bg, 15*time.Millisecond)",
382 c, _ := WithTimeout(bg, 15*time.Millisecond)
389 desc: "WithCancel(bg)",
391 c, cancel := WithCancel(bg)
399 desc: "WithTimeout(bg, 100*time.Millisecond)",
401 c, cancel := WithTimeout(bg, 100*time.Millisecond)
410 if runtime.Compiler == "gccgo" {
411 // gccgo does not yet do escape analysis.
412 // TODO(iant): Remove this when gccgo does do escape analysis.
413 limit = test.gccgoLimit
415 if n := testing.AllocsPerRun(100, test.f); n > limit {
416 t.Errorf("%s allocs = %f want %d", test.desc, n, int(limit))
421 func TestSimultaneousCancels(t *testing.T) {
422 root, cancel := WithCancel(Background())
423 m := map[Context]CancelFunc{root: cancel}
425 // Create a tree of contexts.
426 for len(q) != 0 && len(m) < 100 {
429 for i := 0; i < 4; i++ {
430 ctx, cancel := WithCancel(parent)
435 // Start all the cancels in a random order.
436 var wg sync.WaitGroup
438 for _, cancel := range m {
439 go func(cancel CancelFunc) {
444 // Wait on all the contexts in a random order.
448 case <-time.After(1 * time.Second):
449 buf := make([]byte, 10<<10)
450 n := runtime.Stack(buf, true)
451 t.Fatalf("timed out waiting for <-ctx.Done(); stacks:\n%s", buf[:n])
454 // Wait for all the cancel functions to return.
455 done := make(chan struct{})
462 case <-time.After(1 * time.Second):
463 buf := make([]byte, 10<<10)
464 n := runtime.Stack(buf, true)
465 t.Fatalf("timed out waiting for cancel functions; stacks:\n%s", buf[:n])
469 func TestInterlockedCancels(t *testing.T) {
470 parent, cancelParent := WithCancel(Background())
471 child, cancelChild := WithCancel(parent)
479 case <-time.After(1 * time.Second):
480 buf := make([]byte, 10<<10)
481 n := runtime.Stack(buf, true)
482 t.Fatalf("timed out waiting for child.Done(); stacks:\n%s", buf[:n])
486 func TestLayersCancel(t *testing.T) {
487 testLayers(t, time.Now().UnixNano(), false)
490 func TestLayersTimeout(t *testing.T) {
491 testLayers(t, time.Now().UnixNano(), true)
494 func testLayers(t *testing.T, seed int64, testTimeout bool) {
496 errorf := func(format string, a ...interface{}) {
497 t.Errorf(fmt.Sprintf("seed=%d: %s", seed, format), a...)
500 timeout = 200 * time.Millisecond
510 for i := 0; i < minLayers || numTimers == 0 || len(cancels) == 0 || len(vals) == 0; i++ {
511 switch rand.Intn(3) {
514 ctx = WithValue(ctx, v, v)
515 vals = append(vals, v)
517 var cancel CancelFunc
518 ctx, cancel = WithCancel(ctx)
519 cancels = append(cancels, cancel)
521 var cancel CancelFunc
522 ctx, cancel = WithTimeout(ctx, timeout)
523 cancels = append(cancels, cancel)
527 checkValues := func(when string) {
528 for _, key := range vals {
529 if val := ctx.Value(key).(*value); key != val {
530 errorf("%s: ctx.Value(%p) = %p want %p", when, key, val, key)
536 errorf("ctx should not be canceled yet")
539 if s, prefix := fmt.Sprint(ctx), "context.Background."; !strings.HasPrefix(s, prefix) {
540 t.Errorf("ctx.String() = %q want prefix %q", s, prefix)
543 checkValues("before cancel")
547 case <-time.After(timeout + 100*time.Millisecond):
548 errorf("ctx should have timed out")
550 checkValues("after timeout")
552 cancel := cancels[rand.Intn(len(cancels))]
557 errorf("ctx should be canceled")
559 checkValues("after cancel")
563 func TestCancelRemoves(t *testing.T) {
564 checkChildren := func(when string, ctx Context, want int) {
565 if got := len(ctx.(*cancelCtx).children); got != want {
566 t.Errorf("%s: context has %d children, want %d", when, got, want)
570 ctx, _ := WithCancel(Background())
571 checkChildren("after creation", ctx, 0)
572 _, cancel := WithCancel(ctx)
573 checkChildren("with WithCancel child ", ctx, 1)
575 checkChildren("after cancelling WithCancel child", ctx, 0)
577 ctx, _ = WithCancel(Background())
578 checkChildren("after creation", ctx, 0)
579 _, cancel = WithTimeout(ctx, 60*time.Minute)
580 checkChildren("with WithTimeout child ", ctx, 1)
582 checkChildren("after cancelling WithTimeout child", ctx, 0)