| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package baggage |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"testing" |
| 9 |
|
| 10 |
"github.com/stretchr/testify/assert" |
| 11 |
"github.com/stretchr/testify/require" |
| 12 |
) |
| 13 |
|
| 14 |
func TestContextWithList(t *testing.T) { |
| 15 |
ctx := t.Context() |
| 16 |
l := List{"foo": {Value: "1"}} |
| 17 |
|
| 18 |
nCtx := ContextWithList(ctx, l) |
| 19 |
assert.Equal(t, baggageState{list: l}, nCtx.Value(baggageKey)) |
| 20 |
assert.Nil(t, ctx.Value(baggageKey)) |
| 21 |
} |
| 22 |
|
| 23 |
func TestClearContextOfList(t *testing.T) { |
| 24 |
l := List{"foo": {Value: "1"}} |
| 25 |
|
| 26 |
ctx := t.Context() |
| 27 |
ctx = context.WithValue(ctx, baggageKey, l) |
| 28 |
|
| 29 |
nCtx := ContextWithList(ctx, nil) |
| 30 |
nL, ok := nCtx.Value(baggageKey).(baggageState) |
| 31 |
require.True(t, ok, "wrong type stored in context") |
| 32 |
assert.Nil(t, nL.list) |
| 33 |
assert.Equal(t, l, ctx.Value(baggageKey)) |
| 34 |
} |
| 35 |
|
| 36 |
func TestListFromContext(t *testing.T) { |
| 37 |
ctx := t.Context() |
| 38 |
assert.Nil(t, ListFromContext(ctx)) |
| 39 |
|
| 40 |
l := List{"foo": {Value: "1"}} |
| 41 |
ctx = context.WithValue(ctx, baggageKey, baggageState{list: l}) |
| 42 |
assert.Equal(t, l, ListFromContext(ctx)) |
| 43 |
} |
| 44 |
|
| 45 |
func TestContextWithSetHook(t *testing.T) { |
| 46 |
var called bool |
| 47 |
f := func(ctx context.Context, _ List) context.Context { |
| 48 |
called = true |
| 49 |
return ctx |
| 50 |
} |
| 51 |
|
| 52 |
ctx := t.Context() |
| 53 |
ctx = ContextWithSetHook(ctx, f) |
| 54 |
assert.False(t, called, "SetHookFunc called when setting hook") |
| 55 |
ctx = ContextWithList(ctx, nil) |
| 56 |
assert.True(t, called, "SetHookFunc not called when setting List") |
| 57 |
|
| 58 |
// Ensure resetting the hook works. |
| 59 |
called = false |
| 60 |
ctx = ContextWithSetHook(ctx, f) |
| 61 |
assert.False(t, called, "SetHookFunc called when re-setting hook") |
| 62 |
ContextWithList(ctx, nil) |
| 63 |
assert.True(t, called, "SetHookFunc not called when re-setting List") |
| 64 |
} |
| 65 |
|
| 66 |
func TestContextWithGetHook(t *testing.T) { |
| 67 |
var called bool |
| 68 |
f := func(_ context.Context, list List) List { |
| 69 |
called = true |
| 70 |
return list |
| 71 |
} |
| 72 |
|
| 73 |
ctx := t.Context() |
| 74 |
ctx = ContextWithGetHook(ctx, f) |
| 75 |
assert.False(t, called, "GetHookFunc called when setting hook") |
| 76 |
_ = ListFromContext(ctx) |
| 77 |
assert.True(t, called, "GetHookFunc not called when getting List") |
| 78 |
|
| 79 |
// Ensure resetting the hook works. |
| 80 |
called = false |
| 81 |
ctx = ContextWithGetHook(ctx, f) |
| 82 |
assert.False(t, called, "GetHookFunc called when re-setting hook") |
| 83 |
_ = ListFromContext(ctx) |
| 84 |
assert.True(t, called, "GetHookFunc not called when re-getting List") |
| 85 |
} |