github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2012/simple/webfront/server_test.go (about) 1 // +build OMIT 2 3 /* 4 Copyright 2011 Google Inc. 5 6 Licensed under the Apache License, Version 2.0 (the "License"); 7 you may not use this file except in compliance with the License. 8 You may obtain a copy of the License at 9 10 http://www.apache.org/licenses/LICENSE-2.0 11 12 Unless required by applicable law or agreed to in writing, software 13 distributed under the License is distributed on an "AS IS" BASIS, 14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 See the License for the specific language governing permissions and 16 limitations under the License. 17 */ 18 19 package main 20 21 import ( 22 "bytes" 23 "encoding/json" 24 "io/ioutil" 25 "net/http" 26 "net/http/httptest" 27 "os" 28 "testing" 29 "time" 30 ) 31 32 func testHandler(w http.ResponseWriter, r *http.Request) { 33 w.Write([]byte("OK")) 34 } 35 36 func TestServer(t *testing.T) { 37 dummy := httptest.NewServer(http.HandlerFunc(testHandler)) 38 defer dummy.Close() 39 40 ruleFile := writeRules([]*Rule{ 41 {Host: "example.com", Forward: dummy.Listener.Addr().String()}, 42 {Host: "example.org", Serve: "testdata"}, 43 }) 44 defer os.Remove(ruleFile) 45 46 s, err := NewServer(ruleFile, time.Hour) 47 if err != nil { 48 t.Fatal(err) 49 } 50 // continued next slide 51 // STOP OMIT 52 53 // TESTS START OMIT 54 // continued from previous slide 55 56 var tests = []struct { 57 url string 58 code int 59 body string 60 }{ 61 {"http://example.com/", 200, "OK"}, 62 {"http://foo.example.com/", 200, "OK"}, 63 {"http://example.org/", 200, "contents of index.html\n"}, 64 {"http://example.net/", 404, "Not found.\n"}, 65 {"http://fooexample.com/", 404, "Not found.\n"}, 66 } 67 68 // continued next slide 69 // STOP OMIT 70 71 // RANGE START OMIT 72 // continued from previous slide 73 74 for _, test := range tests { 75 req, _ := http.NewRequest("GET", test.url, nil) 76 rw := httptest.NewRecorder() 77 rw.Body = new(bytes.Buffer) 78 s.ServeHTTP(rw, req) 79 if g, w := rw.Code, test.code; g != w { 80 t.Errorf("%s: code = %d, want %d", test.url, g, w) 81 } 82 if g, w := rw.Body.String(), test.body; g != w { 83 t.Errorf("%s: body = %q, want %q", test.url, g, w) 84 } 85 } 86 } 87 88 func writeRules(rules []*Rule) (name string) { 89 f, err := ioutil.TempFile("", "webfront-rules") 90 if err != nil { 91 panic(err) 92 } 93 defer f.Close() 94 err = json.NewEncoder(f).Encode(rules) 95 if err != nil { 96 panic(err) 97 } 98 return f.Name() 99 }