-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathhelper_test.go
105 lines (93 loc) · 2.55 KB
/
helper_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
package main
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/prometheus/common/log"
"github.com/stretchr/testify/assert"
)
const (
applicationJSON = "application/json"
urlEncoded = "application/x-www-form-urlencoded"
)
// Mock structs for the purpose fo testing
type Mock struct {
db Backend
secondary Backend
server *httptest.Server
}
func createTestNote(mock Mock, password string) (Note, Note, int, error) {
expected := Note{
Content: "note body beer",
Password: password,
Subject: "test",
Tags: "tag1 tag2",
}
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(expected)
resp, err := http.Post(mock.server.URL+"/api/note/create", applicationJSON, b)
if err != nil {
return expected, Note{}, 0, err
}
content, err := ioutil.ReadAll(resp.Body)
got := Note{}
json.Unmarshal(content, &got)
return expected, got, resp.StatusCode, err
}
func copyFile(fromPath, toPath string) error {
from, err := os.Open(fromPath)
if err != nil {
return err
}
defer from.Close()
to, err := os.OpenFile(toPath, os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
return err
}
defer to.Close()
_, err = io.Copy(to, from)
if err != nil {
return err
}
return nil
}
func setup(t *testing.T) Mock {
tempDir, err := ioutil.TempDir(os.TempDir(), "notable-testing")
if !assert.Nil(t, err, "Error creating temp dir") {
return Mock{}
}
db, err = openBoltDB(filepath.Join(tempDir, "notes.db"), false)
assert.Nil(t, err)
idx, err = getIndex(db.dbFilePath() + ".idx")
assert.Nil(t, err)
// Because the secondary needs to be on separate filesystem that
// has some sync mechanism (dropbox, syncthing, keybase, etc) we
// need a copy of the file. Bolt won't allow a secondary readonly
// against the _same_ file.
secondaryPath := filepath.Join(tempDir, "secondary.db")
err = copyFile(db.dbFilePath(), secondaryPath)
assert.Nil(t, err)
// Open the secondary (knowing it's name is different)
dbSecondary, err := openBoltDB(secondaryPath, true)
assert.Nil(t, err)
// Now fake the secondary path, so it reads/writes via journal
// files named like they would in the wild (prefixed by db.Path)
dbSecondary.Secondary.Path = db.dbFilePath()
return Mock{
db: db,
secondary: dbSecondary,
server: httptest.NewServer(getRouter(new(messenger), new(messenger))),
}
}
func tearDown(mock Mock) {
defer mock.server.Close()
mock.db.close()
tempDir := filepath.Dir(mock.db.dbFilePath())
log.Warnf("Deleted temp db dir path=%q err=%v", tempDir, os.RemoveAll(tempDir))
}