github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/engine/access/rest/middleware/common_query_params_test.go (about) 1 package middleware 2 3 import ( 4 "net/http" 5 "net/http/httptest" 6 "strings" 7 "testing" 8 9 "github.com/gorilla/mux" 10 "github.com/stretchr/testify/require" 11 ) 12 13 // TestCommonQueryParamMiddlewares test the two common query param middleware - expand and select 14 func TestCommonQueryParamMiddlewares(t *testing.T) { 15 16 testFunc := func(expandList, selectList []string) { 17 18 th := &testHandler{ 19 t: t, 20 expectedExpandList: expandList, 21 expectedSelectList: selectList, 22 } 23 24 // setup the router to use the test handler and the QueryExpandable and QuerySelect 25 r := mux.NewRouter() 26 r.Handle("/", th.getTestHandler()) 27 r.Use(QueryExpandable()) 28 r.Use(QuerySelect()) 29 30 // create request 31 req := httptest.NewRequest("GET", "/", nil) 32 query := req.URL.Query() 33 // add query params as per test case 34 if len(expandList) > 0 { 35 query.Add(ExpandQueryParam, strings.Join(expandList, ",")) 36 } 37 if len(selectList) > 0 { 38 query.Add(selectQueryParam, strings.Join(selectList, ",")) 39 } 40 req.URL.RawQuery = query.Encode() 41 42 // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response. 43 rr := httptest.NewRecorder() 44 45 // send the request 46 r.ServeHTTP(rr, req) 47 if status := rr.Code; status != http.StatusOK { 48 t.Errorf("handler returned wrong status code: got %v want %v", 49 status, http.StatusOK) 50 } 51 } 52 53 testcases := []struct { 54 expandList []string 55 selectList []string 56 }{ 57 { 58 expandList: nil, 59 selectList: nil, 60 }, 61 { 62 expandList: []string{"abcd"}, 63 selectList: nil, 64 }, 65 { 66 expandList: []string{"abcd", "xyz"}, 67 selectList: nil, 68 }, 69 { 70 expandList: nil, 71 selectList: []string{"abcd"}, 72 }, 73 { 74 expandList: nil, 75 selectList: []string{"abcd", "xyz"}, 76 }, 77 { 78 expandList: []string{"abcd"}, 79 selectList: []string{"abcd"}, 80 }, 81 { 82 expandList: []string{"abcd", "xyz"}, 83 selectList: []string{"abcd", "xyz"}, 84 }, 85 } 86 for _, t := range testcases { 87 testFunc(t.expandList, t.selectList) 88 } 89 } 90 91 type testHandler struct { 92 expectedExpandList []string 93 expectedSelectList []string 94 t *testing.T 95 } 96 97 func (th *testHandler) getTestHandler() http.Handler { 98 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 99 100 actualExpandList, expandListPopulated := GetFieldsToExpand(r) 101 require.Equal(th.t, len(th.expectedExpandList) != 0, expandListPopulated) 102 require.ElementsMatch(th.t, th.expectedExpandList, actualExpandList) 103 104 actualSelectList, selectListPopulated := GetFieldsToSelect(r) 105 require.Equal(th.t, len(th.expectedSelectList) != 0, selectListPopulated) 106 require.ElementsMatch(th.t, th.expectedSelectList, actualSelectList) 107 108 w.WriteHeader(http.StatusOK) 109 }) 110 }