github.com/cockroachdb/tools@v0.0.0-20230222021103-a6d27438930d/godoc/redirect/redirect_test.go (about) 1 // Copyright 2015 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package redirect 6 7 import ( 8 "net/http" 9 "net/http/httptest" 10 "testing" 11 ) 12 13 type redirectResult struct { 14 status int 15 path string 16 } 17 18 func errorResult(status int) redirectResult { 19 return redirectResult{status, ""} 20 } 21 22 func TestRedirects(t *testing.T) { 23 var tests = map[string]redirectResult{ 24 "/foo": errorResult(404), 25 } 26 27 mux := http.NewServeMux() 28 Register(mux) 29 ts := httptest.NewServer(mux) 30 defer ts.Close() 31 32 for path, want := range tests { 33 if want.path != "" && want.path[0] == '/' { 34 // All redirects are absolute. 35 want.path = ts.URL + want.path 36 } 37 38 req, err := http.NewRequest("GET", ts.URL+path, nil) 39 if err != nil { 40 t.Errorf("(path: %q) unexpected error: %v", path, err) 41 continue 42 } 43 44 resp, err := http.DefaultTransport.RoundTrip(req) 45 if err != nil { 46 t.Errorf("(path: %q) unexpected error: %v", path, err) 47 continue 48 } 49 resp.Body.Close() // We only care about the headers, so close the body immediately. 50 51 if resp.StatusCode != want.status { 52 t.Errorf("(path: %q) got status %d, want %d", path, resp.StatusCode, want.status) 53 } 54 55 if want.status != 301 && want.status != 302 { 56 // Not a redirect. Just check status. 57 continue 58 } 59 60 out, _ := resp.Location() 61 if got := out.String(); got != want.path { 62 t.Errorf("(path: %q) got %s, want %s", path, got, want.path) 63 } 64 } 65 }