github.com/google/go-safeweb@v0.0.0-20231219055052-64d8cfc90fbb/examples/echo/echo_test.go (about) 1 // Copyright 2022 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 main 16 17 import ( 18 "fmt" 19 "net/http/httptest" 20 "regexp" 21 "testing" 22 "time" 23 24 "github.com/google/go-safeweb/safehttp" 25 ) 26 27 func TestEcho(t *testing.T) { 28 tests := []struct { 29 name string 30 req string 31 want string 32 wantErr bool 33 }{ 34 { 35 name: "no error", 36 req: "?message=<h1>h4x0r</h1>", 37 want: "<h1>h4x0r</h1>", 38 wantErr: false, 39 }, 40 { 41 name: "empty message", 42 req: "?message=", 43 want: "", 44 wantErr: true, 45 }, { 46 name: "invalid query parameters", 47 req: "?message=;something;", 48 want: "", 49 wantErr: true, 50 }, 51 } 52 53 for _, tt := range tests { 54 mb := safehttp.NewServeMuxConfig(nil) 55 mux := mb.Mux() 56 mux.Handle("/", safehttp.MethodGet, safehttp.HandlerFunc(echo)) 57 58 req := httptest.NewRequest(safehttp.MethodGet, fmt.Sprintf("http://foo.com/%s", tt.req), nil) 59 rw := httptest.NewRecorder() 60 mux.ServeHTTP(rw, req) 61 62 if rw.Code != int(safehttp.StatusOK) && !tt.wantErr { 63 t.Errorf("echo() status = %v, wantErr = %v", rw.Code, tt.wantErr) 64 } 65 66 if body := rw.Body.String(); !tt.wantErr && body != tt.want { 67 t.Errorf("body got: %q want: %q", body, tt.want) 68 } 69 } 70 } 71 72 func TestUptime(t *testing.T) { 73 tests := []struct { 74 name string 75 req string 76 wantErr bool 77 }{ 78 { 79 name: "no error", 80 req: "", 81 wantErr: false, 82 }, 83 { 84 name: "invalid query parameters", 85 req: "?message=;something;", 86 wantErr: true, 87 }, 88 } 89 90 rgx := regexp.MustCompile("^<h1>Uptime: (.*)</h1>$") 91 92 for _, tt := range tests { 93 mb := safehttp.NewServeMuxConfig(nil) 94 mux := mb.Mux() 95 start = time.Date(1991, time.September, 17, 00, 00, 00, 00, time.UTC) 96 mux.Handle("/", safehttp.MethodGet, safehttp.HandlerFunc(uptime)) 97 98 req := httptest.NewRequest(safehttp.MethodGet, fmt.Sprintf("http://foo.com/%s", tt.req), nil) 99 rw := httptest.NewRecorder() 100 mux.ServeHTTP(rw, req) 101 102 if rw.Code != int(safehttp.StatusOK) && !tt.wantErr { 103 t.Errorf("uptime() status = %v, wantErr = %v", rw.Code, tt.wantErr) 104 } 105 106 if !tt.wantErr { 107 matched := rgx.Match(rw.Body.Bytes()) 108 if !matched { 109 t.Errorf("body got: %q want: %q", rw.Body.String(), "<h1>Uptime: X</h1>") 110 } 111 } 112 } 113 }