-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathtestutils_test.go
executable file
·114 lines (88 loc) · 2.21 KB
/
testutils_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
package hare
import (
"errors"
"fmt"
"os"
"os/exec"
"strconv"
"testing"
"github.com/jameycribbs/hare/datastores/disk"
"github.com/jameycribbs/hare/datastores/ram"
)
type Contact struct {
ID int `json:"id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Age int `json:"age"`
}
func (c *Contact) GetID() int {
return c.ID
}
func (c *Contact) SetID(id int) {
c.ID = id
}
func (c *Contact) AfterFind(db *Database) error {
*c = Contact(*c)
return nil
}
func runTestFns(t *testing.T, testFns []func(*Database) func(*testing.T)) {
for i, fn := range testFns {
tstNum := strconv.Itoa(i)
testSetup(t)
diskDS, err := disk.New("./testdata", ".json")
if err != nil {
t.Fatal(err)
}
diskDB, err := New(diskDS)
if err != nil {
t.Fatal(err)
}
defer diskDB.Close()
t.Run(fmt.Sprintf("disk/%s", tstNum), fn(diskDB))
ramDS, err := ram.New(seedData())
if err != nil {
t.Fatal(err)
}
ramDB, err := New(ramDS)
if err != nil {
t.Fatal(err)
}
defer ramDB.Close()
t.Run(fmt.Sprintf("ram/%s", tstNum), fn(ramDB))
testTeardown(t)
}
}
func checkErr(t *testing.T, wantErr error, gotErr error) {
if !errors.Is(gotErr, wantErr) {
t.Errorf("want %v; got %v", wantErr, gotErr)
}
}
func testSetup(t *testing.T) {
testRemoveFiles(t)
cmd := exec.Command("cp", "./testdata/contacts.bak", "./testdata/contacts.json")
if err := cmd.Run(); err != nil {
t.Fatal(err)
}
}
func testTeardown(t *testing.T) {
testRemoveFiles(t)
}
func testRemoveFiles(t *testing.T) {
filesToRemove := []string{"contacts.json", "newtable.json"}
for _, f := range filesToRemove {
err := os.Remove("./testdata/" + f)
if err != nil && !os.IsNotExist(err) {
t.Fatal(err)
}
}
}
func seedData() map[string]map[int]string {
tblMap := make(map[string]map[int]string)
contactsMap := make(map[int]string)
contactsMap[1] = `{"id":1,"first_name":"John","last_name":"Doe","age":37}`
contactsMap[2] = `{"id":2,"first_name":"Abe","last_name":"Lincoln","age":52}`
contactsMap[3] = `{"id":3,"first_name":"Bill","last_name":"Shakespeare","age":18}`
contactsMap[4] = `{"id":4,"first_name":"Helen","last_name":"Keller","age":25}`
tblMap["contacts"] = contactsMap
return tblMap
}