|
| 1 | +package pipeline |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/stretchr/testify/assert" |
| 9 | +) |
| 10 | + |
| 11 | +func TestContext(t *testing.T) { |
| 12 | + tests := map[string]struct { |
| 13 | + givenKey interface{} |
| 14 | + givenValue interface{} |
| 15 | + expectedValue interface{} |
| 16 | + expectedFound bool |
| 17 | + }{ |
| 18 | + "GivenNonExistentKey_ThenExpectNilAndFalse": { |
| 19 | + givenKey: nil, |
| 20 | + expectedValue: nil, |
| 21 | + }, |
| 22 | + "GivenKeyWithNilValue_ThenExpectNilAndTrue": { |
| 23 | + givenKey: "key", |
| 24 | + givenValue: nil, |
| 25 | + expectedValue: nil, |
| 26 | + expectedFound: true, |
| 27 | + }, |
| 28 | + "GivenKeyWithValue_ThenExpectValueAndTrue": { |
| 29 | + givenKey: "key", |
| 30 | + givenValue: "value", |
| 31 | + expectedValue: "value", |
| 32 | + expectedFound: true, |
| 33 | + }, |
| 34 | + } |
| 35 | + for name, tc := range tests { |
| 36 | + t.Run(name, func(t *testing.T) { |
| 37 | + ctx := VariableContext(context.Background()) |
| 38 | + if tc.givenKey != nil { |
| 39 | + AddToContext(ctx, tc.givenKey, tc.givenValue) |
| 40 | + } |
| 41 | + result, found := ValueFromContext(ctx, tc.givenKey) |
| 42 | + assert.Equal(t, tc.expectedValue, result, "value") |
| 43 | + assert.Equal(t, tc.expectedFound, found, "value found") |
| 44 | + }) |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +func TestContextPanics(t *testing.T) { |
| 49 | + assert.PanicsWithError(t, "context was not set up with VariableContext()", func() { |
| 50 | + AddToContext(context.Background(), "key", "value") |
| 51 | + }, "AddToContext") |
| 52 | + assert.PanicsWithError(t, "context was not set up with VariableContext()", func() { |
| 53 | + ValueFromContext(context.Background(), "key") |
| 54 | + }, "ValueFromContext") |
| 55 | +} |
| 56 | + |
| 57 | +func ExampleVariableContext() { |
| 58 | + ctx := VariableContext(context.Background()) |
| 59 | + p := NewPipeline().WithSteps( |
| 60 | + NewStepFromFunc("store value", func(ctx context.Context) error { |
| 61 | + AddToContext(ctx, "key", "value") |
| 62 | + return nil |
| 63 | + }), |
| 64 | + NewStepFromFunc("retrieve value", func(ctx context.Context) error { |
| 65 | + value, _ := ValueFromContext(ctx, "key") |
| 66 | + fmt.Println(value) |
| 67 | + return nil |
| 68 | + }), |
| 69 | + ) |
| 70 | + p.RunWithContext(ctx) |
| 71 | + // Output: value |
| 72 | +} |
0 commit comments