|
| 1 | +/* |
| 2 | +Copyright 2019 The Kubernetes Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package filters |
| 18 | + |
| 19 | +import ( |
| 20 | + "net/http" |
| 21 | + "net/http/httptest" |
| 22 | + "testing" |
| 23 | +) |
| 24 | + |
| 25 | +func TestCacheControl(t *testing.T) { |
| 26 | + tests := []struct { |
| 27 | + name string |
| 28 | + path string |
| 29 | + |
| 30 | + startingHeader string |
| 31 | + expectedHeader string |
| 32 | + }{ |
| 33 | + { |
| 34 | + name: "simple", |
| 35 | + path: "/api/v1/namespaces", |
| 36 | + expectedHeader: "no-cache, private", |
| 37 | + }, |
| 38 | + { |
| 39 | + name: "openapi", |
| 40 | + path: "/openapi/v2", |
| 41 | + expectedHeader: "no-cache, private", |
| 42 | + }, |
| 43 | + { |
| 44 | + name: "already-set", |
| 45 | + path: "/api/v1/namespaces", |
| 46 | + startingHeader: "nonsense", |
| 47 | + expectedHeader: "nonsense", |
| 48 | + }, |
| 49 | + } |
| 50 | + |
| 51 | + for _, test := range tests { |
| 52 | + t.Run(test.name, func(t *testing.T) { |
| 53 | + handler := http.HandlerFunc(func(http.ResponseWriter, *http.Request) { |
| 54 | + //do nothing |
| 55 | + }) |
| 56 | + wrapped := WithCacheControl(handler) |
| 57 | + |
| 58 | + testRequest, err := http.NewRequest(http.MethodGet, test.path, nil) |
| 59 | + if err != nil { |
| 60 | + t.Fatal(err) |
| 61 | + } |
| 62 | + w := httptest.NewRecorder() |
| 63 | + if len(test.startingHeader) > 0 { |
| 64 | + w.Header().Set("Cache-Control", test.startingHeader) |
| 65 | + } |
| 66 | + |
| 67 | + wrapped.ServeHTTP(w, testRequest) |
| 68 | + actual := w.Header().Get("Cache-Control") |
| 69 | + |
| 70 | + if actual != test.expectedHeader { |
| 71 | + t.Fatal(actual) |
| 72 | + } |
| 73 | + }) |
| 74 | + } |
| 75 | + |
| 76 | +} |
0 commit comments