|
| 1 | +/* |
| 2 | +Copyright 2024 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 responsewriter |
| 18 | + |
| 19 | +import ( |
| 20 | + "net/http" |
| 21 | + "testing" |
| 22 | +) |
| 23 | + |
| 24 | +func TestInMemoryResponseWriter(t *testing.T) { |
| 25 | + w := NewInMemoryResponseWriter() |
| 26 | + |
| 27 | + h := w.Header() |
| 28 | + h.Set("Content-Type", "application/json") |
| 29 | + |
| 30 | + w.WriteHeader(http.StatusCreated) |
| 31 | + |
| 32 | + _, err := w.Write([]byte(`{"message": "hello"}`)) |
| 33 | + if err != nil { |
| 34 | + t.Errorf("Write() returned an error: %v", err) |
| 35 | + } |
| 36 | + |
| 37 | + if w.RespCode() != http.StatusCreated { |
| 38 | + t.Errorf("RespCode() returned unexpected code: %d, want %d", w.RespCode(), http.StatusCreated) |
| 39 | + } |
| 40 | + |
| 41 | + if string(w.Data()) != `{"message": "hello"}` { |
| 42 | + t.Errorf("Data() returned unexpected body: %s, want %s", string(w.Data()), `{"message": "hello"}`) |
| 43 | + } |
| 44 | + |
| 45 | + expectedString := "ResponseCode: 201, Body: {\"message\": \"hello\"}, Header: map[Content-Type:[application/json]]" |
| 46 | + if w.String() != expectedString { |
| 47 | + t.Errorf("String() returned unexpected output: %s, want %s", w.String(), expectedString) |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +func TestInMemoryResponseWriter_DefaultHeader(t *testing.T) { |
| 52 | + w := NewInMemoryResponseWriter() |
| 53 | + |
| 54 | + _, err := w.Write([]byte(`{"message": "hello"}`)) |
| 55 | + if err != nil { |
| 56 | + t.Errorf("Write() returned an error: %v", err) |
| 57 | + } |
| 58 | + |
| 59 | + // should be StatusOK (200) by default |
| 60 | + if w.RespCode() != http.StatusOK { |
| 61 | + t.Errorf("RespCode() returned unexpected code: %d, want %d", w.RespCode(), http.StatusOK) |
| 62 | + } |
| 63 | +} |
0 commit comments