github.com/mssola/todo@v0.0.0-20181029153210-d25348dc3f48/lib/views_test.go (about) 1 // Copyright (C) 2014-2017 Miquel Sabaté Solà <mikisabate@gmail.com> 2 // 3 // This Source Code Form is subject to the terms of the Mozilla Public 4 // License, v. 2.0. If a copy of the MPL was not distributed with this 5 // file, You can obtain one at http://mozilla.org/MPL/2.0/. 6 7 package lib 8 9 import ( 10 "html/template" 11 "net/http/httptest" 12 "os" 13 "path/filepath" 14 "strings" 15 "testing" 16 "time" 17 ) 18 19 func TestView(t *testing.T) { 20 ViewsDir = "views" 21 22 if view("path") != "views/path.tpl" { 23 t.Fatal("Wrong path value expected: views/path.tpl") 24 } 25 if view("path/sub") != "views/path/sub.tpl" { 26 t.Fatal("Wrong path value expected: views/path/sub.tpl") 27 } 28 if view("/path/sub") != "views/path/sub.tpl" { 29 t.Fatal("Wrong path value expected: views/path/sub.tpl") 30 } 31 } 32 33 func TestRender(t *testing.T) { 34 wd, err := os.Getwd() 35 if err != nil { 36 t.Fatal(err.Error()) 37 } 38 39 if filepath.Base(wd) == "lib" { 40 wd = filepath.Dir(wd) 41 } 42 43 if err := os.Chdir(wd); err != nil { 44 t.Fatalf("Could not change directory") 45 } 46 47 w := httptest.NewRecorder() 48 Render(w, "topics/show", nil) 49 50 body := w.Body.String() 51 if !strings.HasPrefix(body, "<!DOCTYPE html>") { 52 t.Fatalf("Not an HTML document?") 53 } 54 55 if !strings.Contains(body, "<form action=\"/topics\" method=\"POST\"") { 56 t.Fatalf("There should be a POST /topics form") 57 } 58 } 59 60 func TestHelpers(t *testing.T) { 61 // fmtDate 62 date := viewHelpers()["fmtDate"].(func(time.Time) string) 63 d := time.Date(2014, time.March, 12, 12, 59, 12, 123, time.UTC) 64 if dt := date(d); dt != "12/03/2014" { 65 t.Fatalf("Wrong value %v, expected 12/03/2014", dt) 66 } 67 68 // inc 69 inc := viewHelpers()["inc"].(func(int) int) 70 if i := inc(0); i != 1 { 71 t.Fatalf("Wrong value %v, expected 1", i) 72 } 73 74 // noescape 75 noescape := viewHelpers()["noescape"].(func(string) template.HTML) 76 if html := noescape("<a>"); html != "<a>" { 77 t.Fatalf("Wrong value %v, expected <a>", html) 78 } 79 }