forked from tailscale/golink
-
Notifications
You must be signed in to change notification settings - Fork 2
/
db_test.go
97 lines (83 loc) · 1.83 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
// 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 and loading links for SQLiteDB
func Test_SQLiteDB_SaveLoadLinks(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)
}
}
// Test saving and loading stats for SQLiteDB
func Test_SQLiteDB_SaveLoadStats(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)
}
}