-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathdb_test.go
127 lines (109 loc) · 2.38 KB
/
db_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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
// Copyright 2022 Tailscale Inc & Contributors
// SPDX-License-Identifier: BSD-3-Clause
package golink
import (
"path"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
)
// Test saving, loading, and deleting links for SQLiteDB.
func Test_SQLiteDB_SaveLoadDeleteLinks(t *testing.T) {
db, err := NewSQLiteDB(path.Join(t.TempDir(), "links.db"))
if err != nil {
t.Error(err)
}
links := []*Link{
{Short: "short", Long: "long"},
{Short: "Foo.Bar", Long: "long"},
}
for _, link := range links {
if err := db.Save(link); err != nil {
t.Error(err)
}
got, err := db.Load(link.Short)
if err != nil {
t.Error(err)
}
if !cmp.Equal(got, link) {
t.Errorf("db save and load got %v, want %v", *got, *link)
}
}
got, err := db.LoadAll()
if err != nil {
t.Error(err)
}
sortLinks := cmpopts.SortSlices(func(a, b *Link) bool {
return a.Short < b.Short
})
if !cmp.Equal(got, links, sortLinks) {
t.Errorf("db.LoadAll got %v, want %v", got, links)
}
for _, link := range links {
if err := db.Delete(link.Short); err != nil {
t.Error(err)
}
}
got, err = db.LoadAll()
if err != nil {
t.Error(err)
}
want := []*Link(nil)
if !cmp.Equal(got, want) {
t.Errorf("db.LoadAll got %v, want %v", got, want)
}
}
// Test saving, loading, and deleting stats for SQLiteDB.
func Test_SQLiteDB_SaveLoadDeleteStats(t *testing.T) {
db, err := NewSQLiteDB(path.Join(t.TempDir(), "links.db"))
if err != nil {
t.Error(err)
}
// preload some links
links := []*Link{
{Short: "a"},
{Short: "B-c"},
}
for _, link := range links {
if err := db.Save(link); err != nil {
t.Error(err)
}
}
// Stats to record and then retrieve.
// Stats to store do not need to be their canonical short name,
// but returned stats always should be.
stats := []ClickStats{
{"a": 1},
{"b-c": 1},
{"a": 1, "bc": 2},
}
want := ClickStats{
"a": 2,
"B-c": 3,
}
for _, s := range stats {
if err := db.SaveStats(s); err != nil {
t.Error(err)
}
}
got, err := db.LoadStats()
if err != nil {
t.Error(err)
}
if !cmp.Equal(got, want) {
t.Errorf("db.LoadStats got %v, want %v", got, want)
}
for k := range want {
if err := db.DeleteStats(k); err != nil {
t.Error(err)
}
}
got, err = db.LoadStats()
if err != nil {
t.Error(err)
}
want = ClickStats{}
if !cmp.Equal(got, want) {
t.Errorf("db.LoadStats got %v, want %v", got, want)
}
}