/
test_utils.go
287 lines (254 loc) · 7.86 KB
/
test_utils.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package testutils
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"net/url"
"os"
"testing"
"time"
"github.com/cozy/cozy-stack/model/instance"
"github.com/cozy/cozy-stack/model/instance/lifecycle"
"github.com/cozy/cozy-stack/model/oauth"
"github.com/cozy/cozy-stack/model/stack"
"github.com/cozy/cozy-stack/pkg/assets/dynamic"
"github.com/cozy/cozy-stack/pkg/config/config"
"github.com/cozy/cozy-stack/pkg/consts"
"github.com/cozy/cozy-stack/pkg/couchdb"
"github.com/cozy/cozy-stack/pkg/utils"
"github.com/labstack/echo/v4"
"github.com/ncw/swift/swifttest"
"github.com/spf13/viper"
)
// This flag avoid starting the stack twice.
var stackStarted bool
// Fatal prints a message and immediately exit the process
func Fatal(msg ...interface{}) {
fmt.Println(msg...)
os.Exit(1)
}
// NeedCouchdb kill the process if there is no couchdb running
func NeedCouchdb() {
if _, err := couchdb.CheckStatus(); err != nil {
Fatal("This test need couchdb to run.")
}
}
// TODO can be used as a reminder to do something in the future. The test that
// calls TODO will fail after the limit date, which is an efficient way to not
// forget about it.
func TODO(t *testing.T, date string, args ...interface{}) {
now := time.Now()
limit, err := time.Parse("2006-01-02", date)
if err != nil {
t.Errorf("Invalid date for TODO: %s", err)
} else if now.After(limit) {
t.Error(args...)
}
}
// TestSetup is a wrapper around a testing.M which handles
// setting up instance, client, VFSContext, testserver
// and cleaning up after itself
type TestSetup struct {
testingM *testing.M
name string
host string
inst *instance.Instance
ts *httptest.Server
cleanup func()
}
// NewSetup returns a new TestSetup
// name is used to prevent bug when tests are run in parallel
func NewSetup(testingM *testing.M, name string) *TestSetup {
setup := TestSetup{
name: name,
testingM: testingM,
host: name + "_" + utils.RandomString(10) + ".cozy.local",
cleanup: func() {},
}
return &setup
}
// CleanupAndDie cleanup the TestSetup, prints a message and close the process
func (c *TestSetup) CleanupAndDie(msg ...interface{}) {
c.cleanup()
Fatal(msg...)
}
// Cleanup cleanup the TestSetup
func (c *TestSetup) Cleanup() {
c.cleanup()
}
// SetupSwiftTest can be used to start an in-memory Swift server for tests.
func (c *TestSetup) SetupSwiftTest() error {
swiftSrv, err := swifttest.NewSwiftServer("localhost")
if err != nil {
fmt.Printf("failed to create swift server %s", err)
}
viper.Set("swift.username", "swifttest")
viper.Set("swift.api_key", "swifttest")
viper.Set("swift.auth_url", swiftSrv.AuthURL)
swiftURL := &url.URL{
Scheme: "swift",
Host: "localhost",
RawQuery: "UserName=swifttest&Password=swifttest&AuthURL=" + url.QueryEscape(swiftSrv.AuthURL),
}
err = config.InitSwiftConnection(config.Fs{
URL: swiftURL,
})
viper.Set("fs.url", swiftURL.String())
if err != nil {
c.CleanupAndDie("Could not init swift connection.", err)
}
err = config.GetSwiftConnection().ContainerCreate(dynamic.DynamicAssetsContainerName, nil)
if err != nil {
c.CleanupAndDie("Could not create dynamic container.", err)
}
return nil
}
// AddCleanup adds a function to be run when the test is finished.
func (c *TestSetup) AddCleanup(f func() error) {
next := c.cleanup
c.cleanup = func() {
err := f()
if err != nil {
fmt.Println("Error while cleanup", err)
}
next()
}
}
// GetTmpDirectory creates a temporary directory
// The directory will be removed on container cleanup
func (c *TestSetup) GetTmpDirectory() string {
tempdir, err := ioutil.TempDir("", "cozy-stack")
if err != nil {
c.CleanupAndDie("Could not create temporary directory.", err)
}
c.AddCleanup(func() error { return os.RemoveAll(tempdir) })
return tempdir
}
// GetTestInstance creates an instance with a random host
// The instance will be removed on container cleanup
func (c *TestSetup) GetTestInstance(opts ...*lifecycle.Options) *instance.Instance {
if c.inst != nil {
return c.inst
}
var err error
if !stackStarted {
_, err = stack.Start(stack.NoGops, stack.NoDynAssets)
if err != nil {
c.CleanupAndDie("Error while starting job system", err)
}
stackStarted = true
}
if len(opts) == 0 {
opts = []*lifecycle.Options{{}}
}
if opts[0].Domain == "" {
opts[0].Domain = c.host
} else {
c.host = opts[0].Domain
}
err = lifecycle.Destroy(c.host)
if err != nil && err != instance.ErrNotFound {
c.CleanupAndDie("Error while destroying instance", err)
}
i, err := lifecycle.Create(opts[0])
if err != nil {
c.CleanupAndDie("Cannot create test instance", err)
}
c.AddCleanup(func() error { err := lifecycle.Destroy(i.Domain); return err })
c.inst = i
return i
}
// GetTestClient creates an oauth client and associated token
func (c *TestSetup) GetTestClient(scopes string) (*oauth.Client, string) {
inst := c.GetTestInstance()
client := oauth.Client{
RedirectURIs: []string{"http://localhost/oauth/callback"},
ClientName: "client-" + c.host,
SoftwareID: "github.com/cozy/cozy-stack/testing/" + c.name,
}
client.Create(inst)
token, err := c.inst.MakeJWT(consts.AccessTokenAudience,
client.ClientID, scopes, "", time.Now())
if err != nil {
c.CleanupAndDie("Cannot create oauth token", err)
}
return &client, token
}
// stupidRenderer is a renderer for echo that does nothing.
// It is used just to avoid the error "Renderer not registered" for rendering
// error pages.
type stupidRenderer struct{}
func (sr *stupidRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
return nil
}
// GetTestServer start a testServer with a single group on prefix
// The server will be closed on container cleanup
func (c *TestSetup) GetTestServer(prefix string, routes func(*echo.Group),
mws ...func(*echo.Echo) *echo.Echo) *httptest.Server {
return c.GetTestServerMultipleRoutes(map[string]func(*echo.Group){prefix: routes}, mws...)
}
// GetTestServerMultipleRoutes starts a testServer and creates a group for each
// pair of (prefix, routes) given.
// The server will be closed on container cleanup.
func (c *TestSetup) GetTestServerMultipleRoutes(mpr map[string]func(*echo.Group), mws ...func(*echo.Echo) *echo.Echo) *httptest.Server {
handler := echo.New()
for prefix, routes := range mpr {
group := handler.Group(prefix, func(next echo.HandlerFunc) echo.HandlerFunc {
return func(context echo.Context) error {
context.Set("instance", c.inst)
return next(context)
}
})
routes(group)
}
for _, mw := range mws {
handler = mw(handler)
}
handler.Renderer = &stupidRenderer{}
ts := httptest.NewServer(handler)
c.AddCleanup(func() error { ts.Close(); return nil })
c.ts = ts
return ts
}
// Run runs the underlying testing.M and cleanup
func (c *TestSetup) Run() int {
value := c.testingM.Run()
c.cleanup()
return value
}
// CookieJar is a http.CookieJar which always returns all cookies.
// NOTE golang stdlib uses cookies for the URL (ie the testserver),
// not for the host (ie the instance), so we do it manually
type CookieJar struct {
Jar *cookiejar.Jar
URL *url.URL
}
// Cookies implements http.CookieJar interface
func (j *CookieJar) Cookies(u *url.URL) (cookies []*http.Cookie) {
return j.Jar.Cookies(j.URL)
}
// SetCookies implements http.CookieJar interface
func (j *CookieJar) SetCookies(u *url.URL, cookies []*http.Cookie) {
j.Jar.SetCookies(j.URL, cookies)
}
// GetCookieJar returns a cookie jar valable for test
// the jar discard the url passed to Cookies and SetCookies and always use
// the setup instance URL instead.
func (c *TestSetup) GetCookieJar() http.CookieJar {
instance := c.GetTestInstance()
instanceURL, err := url.Parse("https://" + instance.Domain + "/auth")
if err != nil {
c.CleanupAndDie("Cant create cookie jar url", err)
}
j, err := cookiejar.New(nil)
if err != nil {
c.CleanupAndDie("Cant create cookie jar", err)
}
return &CookieJar{
Jar: j,
URL: instanceURL,
}
}