github.com/xmidt-org/webpa-common@v1.11.9/xhttp/xcontext/populate_test.go (about) 1 package xcontext 2 3 import ( 4 "context" 5 "fmt" 6 "net/http" 7 "net/http/httptest" 8 "testing" 9 10 gokithttp "github.com/go-kit/kit/transport/http" 11 "github.com/stretchr/testify/assert" 12 "github.com/stretchr/testify/require" 13 "github.com/xmidt-org/webpa-common/xhttp" 14 ) 15 16 func testPopulateNoDecoration(t *testing.T) { 17 var ( 18 assert = assert.New(t) 19 require = require.New(t) 20 21 next http.Handler = xhttp.Constant{} 22 23 constructor = Populate() 24 ) 25 26 require.NotNil(constructor) 27 assert.Equal(next, constructor(next)) 28 } 29 30 func testPopulate(t *testing.T, funcCount int) { 31 var ( 32 assert = assert.New(t) 33 require = require.New(t) 34 35 funcCalled = make([]bool, funcCount) 36 funcs = make([]gokithttp.RequestFunc, funcCount) 37 38 nextCalled = false 39 next = http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) { 40 nextCalled = true 41 42 for i := 0; i < funcCount; i++ { 43 assert.Equal(fmt.Sprintf("value-%d", i), request.Context().Value(fmt.Sprintf("key-%d", i))) 44 } 45 }) 46 47 response = httptest.NewRecorder() 48 request = httptest.NewRequest("GET", "/", nil) 49 ) 50 51 for i := 0; i < funcCount; i++ { 52 i := i 53 funcs[i] = func(ctx context.Context, actual *http.Request) context.Context { 54 funcCalled[i] = true 55 assert.Equal(request, actual) 56 return context.WithValue(ctx, fmt.Sprintf("key-%d", i), fmt.Sprintf("value-%d", i)) 57 } 58 } 59 60 constructor := Populate(funcs...) 61 require.NotNil(constructor) 62 decorated := constructor(next) 63 require.NotNil(decorated) 64 65 decorated.ServeHTTP(response, request) 66 assert.True(nextCalled) 67 } 68 69 func TestPopulate(t *testing.T) { 70 t.Run("NoDecoration", testPopulateNoDecoration) 71 72 for _, funcCount := range []int{0, 1, 2, 5} { 73 t.Run(fmt.Sprintf("FuncCount=%d", funcCount), func(t *testing.T) { 74 testPopulate(t, funcCount) 75 }) 76 } 77 }