context_test.gno

2.49 Kb ยท 96 lines
 1package context
 2
 3import "testing"
 4
 5func TestContextExample(t *testing.T) {
 6	type favContextKey string
 7
 8	k := favContextKey("language")
 9	ctx := WithValue(Empty(), k, "Gno")
10
11	if v := ctx.Value(k); v != nil {
12		if v.(string) != "Gno" {
13			t.Errorf("language value should be Gno, but is %s", v)
14		}
15	} else {
16		t.Errorf("language key value was not found")
17	}
18
19	if v := ctx.Value(favContextKey("color")); v != nil {
20		t.Errorf("color key was found")
21	}
22}
23
24// otherContext is a Context that's not one of the types defined in context.go.
25// This lets us test code paths that differ based on the underlying type of the
26// Context.
27type otherContext struct {
28	Context
29}
30
31type (
32	key1 int
33	key2 int
34)
35
36// func (k key2) String() string { return fmt.Sprintf("%[1]T(%[1]d)", k) }
37
38var (
39	k1 = key1(1)
40	k2 = key2(1) // same int as k1, different type
41	k3 = key2(3) // same type as k2, different int
42)
43
44func TestValues(t *testing.T) {
45	check := func(c Context, nm, v1, v2, v3 string) {
46		if v, ok := c.Value(k1).(string); ok == (len(v1) == 0) || v != v1 {
47			t.Errorf(`%s.Value(k1).(string) = %q, %t want %q, %t`, nm, v, ok, v1, len(v1) != 0)
48		}
49		if v, ok := c.Value(k2).(string); ok == (len(v2) == 0) || v != v2 {
50			t.Errorf(`%s.Value(k2).(string) = %q, %t want %q, %t`, nm, v, ok, v2, len(v2) != 0)
51		}
52		if v, ok := c.Value(k3).(string); ok == (len(v3) == 0) || v != v3 {
53			t.Errorf(`%s.Value(k3).(string) = %q, %t want %q, %t`, nm, v, ok, v3, len(v3) != 0)
54		}
55	}
56
57	c0 := Empty()
58	check(c0, "c0", "", "", "")
59
60	t.Skip() // XXX: depends on https://github.com/gnolang/gno/issues/2386
61
62	c1 := WithValue(Empty(), k1, "c1k1")
63	check(c1, "c1", "c1k1", "", "")
64
65	/*if got, want := c1.String(), `context.Empty.WithValue(context_test.key1, c1k1)`; got != want {
66		t.Errorf("c.String() = %q want %q", got, want)
67	}*/
68
69	c2 := WithValue(c1, k2, "c2k2")
70	check(c2, "c2", "c1k1", "c2k2", "")
71
72	/*if got, want := fmt.Sprint(c2), `context.Empty.WithValue(context_test.key1, c1k1).WithValue(context_test.key2(1), c2k2)`; got != want {
73		t.Errorf("c.String() = %q want %q", got, want)
74	}*/
75
76	c3 := WithValue(c2, k3, "c3k3")
77	check(c3, "c2", "c1k1", "c2k2", "c3k3")
78
79	c4 := WithValue(c3, k1, nil)
80	check(c4, "c4", "", "c2k2", "c3k3")
81
82	o0 := otherContext{Empty()}
83	check(o0, "o0", "", "", "")
84
85	o1 := otherContext{WithValue(Empty(), k1, "c1k1")}
86	check(o1, "o1", "c1k1", "", "")
87
88	o2 := WithValue(o1, k2, "o2k2")
89	check(o2, "o2", "c1k1", "o2k2", "")
90
91	o3 := otherContext{c4}
92	check(o3, "o3", "", "c2k2", "c3k3")
93
94	o4 := WithValue(o3, k3, nil)
95	check(o4, "o4", "", "c2k2", "")
96}