-
Notifications
You must be signed in to change notification settings - Fork 0
/
testutils.go
87 lines (69 loc) · 2.03 KB
/
testutils.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
package testutils
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/babolivier/ident/common"
"github.com/babolivier/ident/common/config"
"github.com/babolivier/ident/common/constants"
"github.com/babolivier/ident/common/database"
"github.com/gorilla/mux"
"github.com/matrix-org/gomatrix"
"github.com/matrix-org/util"
"github.com/stretchr/testify/require"
)
var testConfig *config.Config
func NewTestConfig(t *testing.T) *config.Config {
if testConfig != nil {
return testConfig
}
var err error
testConfig, err = config.ParseConfig([]byte(constants.TestConfigYAML))
require.Nil(t, err, err)
return testConfig
}
func NewTestDB(t *testing.T) *database.Database {
cfg := NewTestConfig(t)
db, err := database.NewDatabase(cfg.Database.Driver, cfg.Database.ConnString)
require.Nil(t, err, err)
return db
}
func NewTestServer(
cfg *config.Config, db *database.Database,
setupRouting func(*mux.Router, *config.Config, *database.Database),
) *httptest.Server {
// Create the router and register the handler for the status check route.
router := mux.NewRouter().UseEncodedPath().PathPrefix(constants.APIPrefix).Subrouter()
setupRouting(router, cfg, db)
router.NotFoundHandler = common.MakeAPI(func(r *http.Request) util.JSONResponse {
return util.JSONResponse{
Code: 404,
JSON: gomatrix.RespError{
ErrCode: "M_NOT_FOUND",
Err: "Unrecognised request",
},
}
})
return httptest.NewServer(router)
}
func TestWithTestServer(
t *testing.T,
testFunc func(t *testing.T, cfg *config.Config, db *database.Database, s *httptest.Server),
setupRouting func(*mux.Router, *config.Config, *database.Database),
) {
cfg := NewTestConfig(t)
db := NewTestDB(t)
s := NewTestServer(cfg, db, setupRouting)
defer s.Close()
testFunc(t, cfg, db, s)
}
func TestWithTmpFiles(t *testing.T, testFunc func(t *testing.T), files map[string]string) {
for name, content := range files {
err := ioutil.WriteFile(name, []byte(content), 0655)
require.Nil(t, err, err)
defer os.Remove(name)
}
testFunc(t)
}