Debian Codegraph @

modules/caddyhttp/staticresp_test.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package caddyhttp
16
17 import (
18 "context"
19 "io"
20 "net/http"
21 "net/http/httptest"
22 "strconv"
23 "testing"
24
25 "github.com/caddyserver/caddy/v2"
26 )
27
28 func TestStaticResponseHandler(t *testing.T) {
29 r := fakeRequest()
30 w := httptest.NewRecorder()
31
32 s := StaticResponse{
33 StatusCode: WeakString(strconv.Itoa(http.StatusNotFound)),
34 Headers: http.Header{
35 "X-Test": []string{"Testing"},
36 },
37 Body: "Text",
38 Close: true,
39 }
40
41 err := s.ServeHTTP(w, r, nil)
42 if err != nil {
43 t.Errorf("did not expect an error, but got: %v", err)
44 }
45
46 resp := w.Result()
47 respBody, _ := io.ReadAll(resp.Body)
48
49 if resp.StatusCode != http.StatusNotFound {
50 t.Errorf("expected status %d but got %d", http.StatusNotFound, resp.StatusCode)
51 }
52 if resp.Header.Get("X-Test") != "Testing" {
53 t.Errorf("expected x-test header to be 'testing' but was '%s'", resp.Header.Get("X-Test"))
54 }
55 if string(respBody) != "Text" {
56 t.Errorf("expected body to be 'test' but was '%s'", respBody)
57 }
58 }
59
60 func fakeRequest() *http.Request {
61 r, _ := http.NewRequest("GET", "/", nil)
62 repl := caddy.NewReplacer()
63 ctx := context.WithValue(r.Context(), caddy.ReplacerCtxKey, repl)
64 r = r.WithContext(ctx)
65 return r
66 }