|
| 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 noopHandler() http.HandlerFunc { |
| 26 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 27 | + // noop |
| 28 | + }) |
| 29 | +} |
| 30 | + |
| 31 | +func TestWithContentType(t *testing.T) { |
| 32 | + mux := http.NewServeMux() |
| 33 | + mux.Handle("/text", WithContentType(noopHandler(), "text/plain")) |
| 34 | + mux.Handle("/json", WithContentType(noopHandler(), "application/json")) |
| 35 | + tests := []struct { |
| 36 | + description string |
| 37 | + path string |
| 38 | + expectedMimeType string |
| 39 | + }{ |
| 40 | + {"/text should return a plain text response", "/text", "text/plain"}, |
| 41 | + {"/json should return a json response", "/json", "application/json"}, |
| 42 | + } |
| 43 | + for _, test := range tests { |
| 44 | + path := "http://example.com" + test.path |
| 45 | + t.Run(path, func(t *testing.T) { |
| 46 | + req, err := http.NewRequest("GET", path, nil) |
| 47 | + if err != nil { |
| 48 | + t.Fatalf("unexpected error: %v", err) |
| 49 | + } |
| 50 | + w := httptest.NewRecorder() |
| 51 | + mux.ServeHTTP(w, req) |
| 52 | + if nosniffHeader := w.Header().Get("X-Content-Type-Options"); nosniffHeader != "nosniff" { |
| 53 | + t.Errorf("expected nosniff header to be set, got %v", nosniffHeader) |
| 54 | + } |
| 55 | + if mimeTypeHeader := w.Header().Get("Content-Type"); mimeTypeHeader != test.expectedMimeType { |
| 56 | + t.Errorf("expected %v, got %v", test.expectedMimeType, mimeTypeHeader) |
| 57 | + } |
| 58 | + }) |
| 59 | + } |
| 60 | +} |
0 commit comments