0 package db
1
2 import (
3 "testing"
4 "runtime"
5 "errors"
6 "strings"
7 "os"
8 )
9
10 func funcName(t *testing.T) string {
11 fpcs := make([]uintptr, 1)
12
13 n := runtime.Callers(2, fpcs)
14 if n == 0 {
15 t.Fatal("function name: no caller")
16 }
17
18 caller := runtime.FuncForPC(fpcs[0] - 1)
19 if caller == nil {
20 t.Fatal("function name: caller is nil")
21 }
22
23 name := caller.Name()
24 return name[strings.LastIndex(name, ".") + 1:]
25 }
26
27 const validPassword = "pa$w0rd"
28 const invalidUsername = "0user"
29
30 var initialized bool
31 func initDB(t *testing.T) {
32 if initialized {
33 return
34 }
35 initialized = true
36 os.Remove("test.db")
37
38 if err := Init("sqlite3", "test.db", true); err != nil {
39 t.Fatal(err)
40 }
41 }
42
43 func TestDB(t *testing.T) {
44 initDB(t)
45 }
46
47 func TestRegistration(t *testing.T) {
48
49 initDB(t)
50
51 username := funcName(t)
52 if err := Register(username, validPassword); err != nil {
53 t.Fatal(err)
54 }
55
56 if err := Register(username, validPassword); err == nil {
57 t.Fatal(err)
58 }
59
60 if err := Register(invalidUsername, validPassword); err == nil {
61 t.Fatal(err)
62 }
63 }
64
65 func TestSession(t *testing.T) {
66
67 initDB(t)
68
69 username := funcName(t)
70 if err := Register(username, validPassword); err != nil {
71 t.Fatal(err)
72 }
73
74 signature := username + "_signature"
75 user, err := FetchUser(username, signature)
76 if err != nil {
77 t.Fatal(err)
78 }
79 if err := AddUserSession(signature, user); err != nil {
80 t.Fatal(err)
81 }
82 if err := AddUserSession(signature, user); err == nil {
83 t.Fatal(errors.New(
84 "should not be able to add the same signature"))
85 }
86 }
87