all repos

onasty @ efd970430597e242aa15c24f868fc0e7103b45ac

a one-time notes service

onasty/e2e/e2e_utils_test.go(view raw)

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
package e2e_test

import (
	"bytes"
	"encoding/json"
	"io"
	"net/http"
	"net/http/httptest"

	"github.com/gofrs/uuid/v5"
	"github.com/olexsmir/onasty/internal/jwtutil"
)

// jsonify marshalls v into json and returns it as []byte
func (e *AppTestSuite) jsonify(v any) []byte {
	r, err := json.Marshal(v)
	e.require.NoError(err)
	return r
}

// readBodyAndUnjsonify reads body of [httptest.ResponseRecorder] and unmarshalls it into res
//
// Example:
//
//	var res struct { message string `json:"message"` }
//	readBodyAndUnjsonify(httpResp.Body, &res)
func (e *AppTestSuite) readBodyAndUnjsonify(b *bytes.Buffer, res any) {
	respData, err := io.ReadAll(b)
	e.require.NoError(err)

	err = json.Unmarshal(respData, &res)
	e.require.NoError(err)
}

// httpRequest sends http request to the server and returns [httptest.ResponseRecorder]
// content-type always set to application/json
func (e *AppTestSuite) httpRequest(
	method, url string,
	body []byte,
	accessToken ...string,
) *httptest.ResponseRecorder {
	req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
	e.require.NoError(err)

	req.Header.Set("Content-type", "application/json")

	if len(accessToken) == 1 {
		req.Header.Set("Authorization", "Bearer "+accessToken[0])
	}

	resp := httptest.NewRecorder()
	e.router.ServeHTTP(resp, req)

	return resp
}

// uuid generates a new UUID and returns it as a string
func (e *AppTestSuite) uuid() string {
	u, err := uuid.NewV4()
	e.require.NoError(err)
	return u.String()
}

// parseJwtToken gets payload from the jwt token
func (e *AppTestSuite) parseJwtToken(t string) jwtutil.Payload {
	r, err := e.jwtTokenizer.Parse(t)
	e.require.NoError(err)
	return r
}