main
 1package context
 2
 3import (
 4	"context"
 5	"testing"
 6	"time"
 7
 8	"github.com/stretchr/testify/assert"
 9)
10
11func TestWith(t *testing.T) {
12	t.Run("With", func(t *testing.T) {
13		t.Run("injects the value into context", func(t *testing.T) {
14			key := Key[int]("ticket")
15
16			value := 42
17			ctx := key.With(context.Background(), value)
18
19			assert.Equal(t, value, ctx.Value(key))
20		})
21	})
22
23	t.Run("From", func(t *testing.T) {
24		t.Run("returns the value for the key", func(t *testing.T) {
25			key := Key[time.Time]("secret")
26			now := time.Now()
27
28			ctx := key.With(context.Background(), now)
29
30			assert.Equal(t, now, key.From(ctx))
31		})
32
33		t.Run("returns the zero value", func(t *testing.T) {
34			key := Key[int]("not-found")
35
36			assert.Equal(t, 0, key.From(context.Background()))
37		})
38	})
39}