github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/plugin/cb/middleware_test.go (about) 1 package cb 2 3 import ( 4 "net/http" 5 "net/http/httptest" 6 "testing" 7 8 "github.com/hellofresh/janus/pkg/test" 9 "github.com/stretchr/testify/assert" 10 ) 11 12 func TestMiddleware(t *testing.T) { 13 t.Parallel() 14 15 tests := []struct { 16 scenario string 17 function func(*testing.T, *http.Request, *httptest.ResponseRecorder) 18 }{ 19 { 20 scenario: "with wrong predicate given", 21 function: testWrongPredicate, 22 }, 23 { 24 scenario: "when the upstream respond successfully", 25 function: testSuccessfulUpstreamRetry, 26 }, 27 { 28 scenario: "when the upstream fails to respond", 29 function: testFailedUpstreamRetry, 30 }, 31 } 32 33 for _, test := range tests { 34 t.Run(test.scenario, func(t *testing.T) { 35 r := httptest.NewRequest(http.MethodGet, "/", nil) 36 w := httptest.NewRecorder() 37 test.function(t, r, w) 38 }) 39 } 40 } 41 42 func testWrongPredicate(t *testing.T, r *http.Request, w *httptest.ResponseRecorder) { 43 cfg := Config{ 44 Name: "example", 45 Predicate: "this is wrong", 46 } 47 mw := NewCBMiddleware(cfg) 48 49 mw(http.HandlerFunc(test.Ping)).ServeHTTP(w, r) 50 51 assert.Equal(t, http.StatusOK, w.Code) 52 } 53 54 func testSuccessfulUpstreamRetry(t *testing.T, r *http.Request, w *httptest.ResponseRecorder) { 55 mw := NewCBMiddleware(Config{Name: "example"}) 56 57 mw(http.HandlerFunc(test.Ping)).ServeHTTP(w, r) 58 59 assert.Equal(t, http.StatusOK, w.Code) 60 } 61 62 func testFailedUpstreamRetry(t *testing.T, r *http.Request, w *httptest.ResponseRecorder) { 63 mw := NewCBMiddleware(Config{Name: "example"}) 64 65 mw(test.FailWith(http.StatusBadGateway)).ServeHTTP(w, r) 66 67 assert.Equal(t, http.StatusBadGateway, w.Code) 68 }