all repos

onasty @ 8b28667bae704dff8778a1d61152d17efcac002f

a one-time notes service

onasty/e2e/e2e_utils_test.go (view raw)

Smirnov Oleksandr Smirnov Oleksandr
ss2316544@gmail.com
refactor: fix annoyances (#97)..., 1 year ago
1
package e2e_test
2
3
import (
4
	"bytes"
5
	"encoding/json"
6
	"io"
7
	"net/http"
8
	"net/http/httptest"
9
10
	"github.com/gofrs/uuid/v5"
11
	"github.com/olexsmir/onasty/internal/jwtutil"
12
)
13
14
// jsonify marshalls v into json and returns it as []byte
15
func (e *AppTestSuite) jsonify(v any) []byte {
16
	r, err := json.Marshal(v)
17
	e.require.NoError(err)
18
	return r
19
}
20
21
// readBodyAndUnjsonify reads body of [httptest.ResponseRecorder] and unmarshalls it into res
22
//
23
// Example:
24
//
25
//	var res struct { message string `json:"message"` }
26
//	readBodyAndUnjsonify(httpResp.Body, &res)
27
func (e *AppTestSuite) readBodyAndUnjsonify(b *bytes.Buffer, res any) {
28
	respData, err := io.ReadAll(b)
29
	e.require.NoError(err)
30
31
	err = json.Unmarshal(respData, &res)
32
	e.require.NoError(err)
33
}
34
35
// httpRequest sends http request to the server and returns [httptest.ResponseRecorder]
36
// content-type always set to application/json
37
func (e *AppTestSuite) httpRequest(
38
	method, url string,
39
	body []byte,
40
	accessToken ...string,
41
) *httptest.ResponseRecorder {
42
	req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
43
	e.require.NoError(err)
44
45
	req.Header.Set("Content-type", "application/json")
46
47
	if len(accessToken) == 1 {
48
		req.Header.Set("Authorization", "Bearer "+accessToken[0])
49
	}
50
51
	resp := httptest.NewRecorder()
52
	e.router.ServeHTTP(resp, req)
53
54
	return resp
55
}
56
57
// uuid generates a new UUID and returns it as a string
58
func (e *AppTestSuite) uuid() string {
59
	u, err := uuid.NewV4()
60
	e.require.NoError(err)
61
	return u.String()
62
}
63
64
// parseJwtToken gets payload from the jwt token
65
func (e *AppTestSuite) parseJwtToken(t string) jwtutil.Payload {
66
	r, err := e.jwtTokenizer.Parse(t)
67
	e.require.NoError(err)
68
	return r
69
}