-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileSystemStore_test.go
124 lines (90 loc) · 2.47 KB
/
FileSystemStore_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
package poker
import (
"io/ioutil"
"os"
"testing"
)
func createTempFile(t *testing.T, initialData string) (*os.File, func()) {
t.Helper()
tmpfile, err := ioutil.TempFile("", "db")
if err != nil {
t.Fatalf("could not create temp file %v", err)
}
tmpfile.Write([]byte(initialData))
removeFile := func() {
os.Remove(tmpfile.Name())
}
return tmpfile, removeFile
}
func TestFileSystemStore(t *testing.T) {
t.Run("League sorted", func(t *testing.T) {
database, cleanDatabase := createTempFile(t, `[
{"Name": "Cleo", "Wins": 10},
{"Name": "Chris", "Wins": 33}]`)
defer cleanDatabase()
store, err := NewFileSystemPlayerStore(database)
assertNoError(t, err)
got := store.GetLeague()
want := []Player{
{"Chris", 33},
{"Cleo", 10},
}
assertLeague(t, got, want)
// read again
got = store.GetLeague()
assertLeague(t, got, want)
})
t.Run("get player score", func(t *testing.T) {
database, cleanDatabase := createTempFile(t, `[
{"Name": "Cleo", "Wins": 10},
{"Name": "Chris", "Wins": 33}]`)
defer cleanDatabase()
store, err := NewFileSystemPlayerStore(database)
assertNoError(t, err)
got := store.GetPlayerScore("Chris")
want := 33
assertScoreEquals(t, got, want)
})
t.Run("store wins for existing players", func(t *testing.T) {
database, cleanDatabase := createTempFile(t, `[
{"Name": "Cleo", "Wins": 10},
{"Name": "Chris", "Wins": 33}]`)
defer cleanDatabase()
store, err := NewFileSystemPlayerStore(database)
assertNoError(t, err)
store.RecordWin("Chris")
got := store.GetPlayerScore("Chris")
want := 34
assertScoreEquals(t, got, want)
})
t.Run("store wins for existing players", func(t *testing.T) {
database, cleanDatabase := createTempFile(t, `[
{"Name": "Cleo", "Wins": 10},
{"Name": "Chris", "Wins": 33}]`)
defer cleanDatabase()
store, err := NewFileSystemPlayerStore(database)
assertNoError(t, err)
store.RecordWin("Pepper")
got := store.GetPlayerScore("Pepper")
want := 1
assertScoreEquals(t, got, want)
})
t.Run("works with an empty file", func(t *testing.T) {
database, cleanDatabase := createTempFile(t, "")
defer cleanDatabase()
_, err := NewFileSystemPlayerStore(database)
assertNoError(t, err)
})
}
func assertScoreEquals(t *testing.T, got, want int) {
t.Helper()
if got != want {
t.Errorf("got %d want %d", got, want)
}
}
func assertNoError(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatalf("didnt expect an error but got one, %v", err)
}
}