github.com/kyma-project/kyma-environment-broker@v0.0.1/internal/middleware/region_test.go (about) 1 package middleware_test 2 3 import ( 4 "context" 5 "net/http" 6 "net/http/httptest" 7 "testing" 8 9 "github.com/kyma-project/kyma-environment-broker/internal/middleware" 10 11 "github.com/gorilla/mux" 12 "github.com/stretchr/testify/assert" 13 "github.com/stretchr/testify/require" 14 ) 15 16 func TestRequestRegionKey(t *testing.T) { 17 // given 18 const ( 19 ctxParentKeyA = "key-A" 20 ctxParentValueA = "value-A" 21 fixRequestRegion = "request-region-A" 22 ) 23 24 req, err := http.NewRequest(http.MethodGet, "http://url.dev/endpoint/"+fixRequestRegion, nil) 25 require.NoError(t, err) 26 27 parentCtx := context.WithValue(context.Background(), ctxParentKeyA, ctxParentValueA) 28 req = req.WithContext(parentCtx) 29 30 var gotCtx context.Context 31 spyHandler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { 32 gotCtx = req.Context() 33 }) 34 35 router := mux.NewRouter() 36 regionMiddleware := middleware.AddRegionToContext("default-region") 37 router.Use(regionMiddleware) 38 router.Path("/endpoint/{region}").Handler(spyHandler) 39 40 // when 41 router.ServeHTTP(httptest.NewRecorder(), req) 42 gotRegion, foundRegion := middleware.RegionFromContext(gotCtx) 43 44 // then 45 assert.Equal(t, ctxParentValueA, gotCtx.Value(ctxParentKeyA)) 46 47 assert.True(t, foundRegion) 48 assert.Equal(t, fixRequestRegion, gotRegion) 49 } 50 51 func TestRequestRegionKeyDefault(t *testing.T) { 52 // given 53 const ( 54 ctxParentKeyA = "key-A" 55 ctxParentValueA = "value-A" 56 fixDefaultRegion = "default-region" 57 ) 58 59 clientReq, err := http.NewRequest(http.MethodGet, "http://url.dev/endpoint-without-region", nil) 60 require.NoError(t, err) 61 62 parentCtx := context.WithValue(context.Background(), ctxParentKeyA, ctxParentValueA) 63 clientReq = clientReq.WithContext(parentCtx) 64 65 var gotCtx context.Context 66 spyHandler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { 67 gotCtx = req.Context() 68 }) 69 70 regionMiddleware := middleware.AddRegionToContext(fixDefaultRegion) 71 router := mux.NewRouter() 72 router.Use(regionMiddleware) 73 router.Path("/endpoint-without-region").Handler(spyHandler) 74 75 // when 76 router.ServeHTTP(httptest.NewRecorder(), clientReq) 77 gotRegion, foundRegion := middleware.RegionFromContext(gotCtx) 78 79 // then 80 assert.Equal(t, ctxParentValueA, gotCtx.Value(ctxParentKeyA)) 81 82 assert.True(t, foundRegion) 83 assert.Equal(t, fixDefaultRegion, gotRegion) 84 } 85 86 func TestRequestRegionKeyNotFound(t *testing.T) { 87 // when 88 gotValue, found := middleware.RegionFromContext(context.Background()) 89 90 // then 91 assert.Empty(t, gotValue) 92 assert.False(t, found) 93 }