/
routing_test.go
72 lines (56 loc) · 1.6 KB
/
routing_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright (C) 2014-2017 Miquel Sabaté Solà <mikisabate@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package main
import (
"log"
"net/http"
"net/http/httptest"
"testing"
"github.com/docker/distribution/uuid"
"github.com/mssola/todo/app"
"github.com/mssola/todo/lib"
)
// Initialize the database before running an unit test.
func initTestDB() {
lib.InitSession()
lib.ViewsDir = "../views"
app.InitDB()
if err := app.Db.TruncateTables(); err != nil {
log.Fatalf("Could not initialize DB: %v", err)
}
}
// Use this in the end of every unit test.
func closeTestDB() {
_ = app.Db.TruncateTables()
app.CloseDB()
}
func TestUserLogged(t *testing.T) {
initTestDB()
defer closeTestDB()
req, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatalf("Request was not successful: %v", err)
}
if val := userLogged(req, nil); val {
t.Fatalf("Expected to be false: %v", val)
}
w := httptest.NewRecorder()
lib.SetCookie(w, req, "userId", "1")
if val := userLogged(req, nil); val {
t.Fatalf("Expected to be false: %v", val)
}
u := &app.User{ID: uuid.Generate().String(), Name: "user", PasswordHash: "1234"}
app.Db.Insert(u)
var user app.User
if err := app.Db.SelectOne(&user, "select * from users"); err != nil {
t.Fatalf("Expected to be nil: %v", err)
}
w = httptest.NewRecorder()
lib.SetCookie(w, req, "userId", user.ID)
if val := userLogged(req, nil); !val {
t.Fatalf("Expected to be true: %v", val)
}
}