github.com/google/go-safeweb@v0.0.0-20231219055052-64d8cfc90fbb/safehttp/defaults/defaults_test.go (about) 1 // Copyright 2020 Google LLC 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 // https://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 defaults 16 17 import ( 18 "bytes" 19 "io/ioutil" 20 "net/http/httptest" 21 "testing" 22 23 "github.com/google/go-safeweb/safehttp" 24 "github.com/google/safehtml" 25 ) 26 27 func TestServeMuxConfig(t *testing.T) { 28 t.Run("can load in prod mode", func(t *testing.T) { 29 const resp = "response" 30 cfg, _ := ServeMuxConfig([]string{"test.host.example"}, "test-xsrf-key") 31 mux := cfg.Mux() 32 mux.Handle("/test", "GET", safehttp.HandlerFunc(func(w safehttp.ResponseWriter, r *safehttp.IncomingRequest) safehttp.Result { 33 form, err := r.URL().Query() 34 if err != nil { 35 t.Errorf("Cannot parse GET form: %v", err) 36 } 37 b := form.Bool("test", false) 38 if !b { 39 t.Error("test parameter, got false, want true") 40 } 41 return w.Write(safehtml.HTMLEscaped(resp)) 42 })) 43 w := httptest.NewRecorder() 44 r := httptest.NewRequest("GET", "https://test.host.example/test?test=true", nil) 45 mux.ServeHTTP(w, r) 46 if w.Result().StatusCode != 200 { 47 t.Errorf("Status: got %d, want 200", w.Result().StatusCode) 48 } 49 got, err := ioutil.ReadAll(w.Result().Body) 50 if err != nil { 51 t.Errorf("Read body: got %v", err) 52 } 53 if !bytes.Equal(got, []byte(resp)) { 54 t.Errorf("body: got %q, want %q", got, resp) 55 } 56 }) 57 }