github.com/google/go-safeweb@v0.0.0-20231219055052-64d8cfc90fbb/tests/integration/devmode/devmode_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 devmode_test 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/go-safeweb/safehttp/defaults" 25 "github.com/google/safehtml" 26 ) 27 28 func TestDevMode(t *testing.T) { 29 t.Run("can load in dev mode", func(t *testing.T) { 30 safehttp.UseLocalDev() 31 if !safehttp.IsLocalDev() { 32 t.Errorf("IsLocalDev(): got false, want true") 33 } 34 const resp = "response" 35 cfg, _ := defaults.ServeMuxConfig([]string{"test.host.example"}, "test-xsrf-key") 36 mux := cfg.Mux() 37 mux.Handle("/test", "GET", safehttp.HandlerFunc(func(w safehttp.ResponseWriter, r *safehttp.IncomingRequest) safehttp.Result { 38 form, err := r.URL().Query() 39 if err != nil { 40 t.Errorf("Cannot parse GET form: %v", err) 41 } 42 b := form.Bool("test", false) 43 if !b { 44 t.Error("test parameter, got false, want true") 45 } 46 w.AddCookie(safehttp.NewCookie("test", "insecure")) 47 return w.Write(safehtml.HTMLEscaped(resp)) 48 })) 49 w := httptest.NewRecorder() 50 r := httptest.NewRequest("GET", "https://test.host.example/test?test=true", nil) 51 mux.ServeHTTP(w, r) 52 if w.Result().StatusCode != 200 { 53 t.Errorf("Status: got %d, want 200", w.Result().StatusCode) 54 } 55 got, err := ioutil.ReadAll(w.Result().Body) 56 if err != nil { 57 t.Errorf("Read body: got %v", err) 58 } 59 if !bytes.Equal(got, []byte(resp)) { 60 t.Errorf("body: got %q, want %q", got, resp) 61 } 62 cs := w.Result().Cookies() 63 if len(cs) == 0 { 64 t.Errorf("got no cookies, wanted cookies") 65 } 66 for _, c := range cs { 67 if c.Secure { 68 t.Errorf("got secure cookie %q, should have not been secure", c.Raw) 69 } 70 } 71 }) 72 }