-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd_test.go
92 lines (80 loc) · 2 KB
/
add_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
package main
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"testing"
)
func setupForCommandTest(t *testing.T) (io.Reader, func()) {
old := repo
repo = &Repository{
Bookmark: &jsonBookmarkRepository{},
}
f, err := ioutil.TempFile("", "")
if err != nil {
t.Fatalf("failed to create temp file: %s", err)
}
InitDB(f.Name())
return f, func() {
repo = old
f.Close()
}
}
func TestAddCommand(t *testing.T) {
dummyUI := &baseUI{
writer: new(bytes.Buffer),
errWriter: new(bytes.Buffer),
reader: new(bytes.Buffer),
}
cmd := &AddCommand{
ui: dummyUI,
}
cases := map[string]struct {
in []string
hasErr bool
}{
"can add the URL of Google as named 'google'": {[]string{"https://google.com", "google"}, false},
"cannot add the URL of Google as named 'google'": {[]string{"google", "https://google.com"}, true},
"shortage of args": {[]string{"https://google.com"}, true},
}
for n, c := range cases {
t.Run(n, func(t *testing.T) {
out, cleanup := setupForCommandTest(t)
defer cleanup()
code := cmd.Run(c.in)
if c.hasErr {
if code == 0 {
t.Error("expected abnormal status code, but got normal code")
}
return
} else {
if code != 0 {
t.Errorf("expected normal status code, but got abnormal code: %d", code)
}
}
var db DB
if err := json.NewDecoder(out).Decode(&db); err != nil {
t.Fatalf("failed to decode test result: %s", err)
}
if len(db.Bookmarks) != 1 {
t.Errorf("expected one bookmark is saved, but %d", len(db.Bookmarks))
}
})
}
// Duplicate URL check
b := []string{"https://google.com", "google"}
t.Run("cannot add duplication named URL", func(t *testing.T) {
_, cleanup := setupForCommandTest(t)
defer cleanup()
code := cmd.Run(b)
if code != 0 {
t.Error("expected success once adding bookmark, but failed")
} else {
code := cmd.Run(b)
if code == 0 {
t.Error("expected failed secound adding bookmark becasue of duplication, but success")
}
}
})
}