-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathmain_test.go
More file actions
278 lines (216 loc) · 7 KB
/
Copy pathmain_test.go
File metadata and controls
278 lines (216 loc) · 7 KB
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
package main
import (
"database/sql"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"testing"
"time"
"github.com/go-testfixtures/testfixtures/v3"
"github.com/gofiber/fiber/v2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
)
const UUID_REGEXP = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
var (
app *fiber.App
db *sql.DB
dbDriver string
goodToken = "Bearer v2.local.TwwHUQEi8hr2Eo881_Bs5vK9dHOR5BgEU24QRf-U7VmUwI1yOEA6mFT0EsXioMkFT_T-jjrtIJ_Nv8f6hR6ifJXUOuzWEkm9Ijq1mqSjQatD3aDqKMyjjBA"
badToken = "Bearer v2.local.UngfrCDNwGUw4pff2oBNoyxYvOErcbVVqLndl6nzONafUCzktaOeMSmoI7B0h62zoxXXLqTm_Phl"
)
type TestCase struct {
description string
// Test input
query string
body string
headers map[string][]string
setupFunc func(t *testing.T)
// Expected output
expectedCode int
expectedBody string
expectedContentType string
validateFunc func(t *testing.T, response map[string]interface{})
}
func init() {
// Test on SQLite by default if DATABASE_DSN is not set
if _, exists := os.LookupEnv("DATABASE_DSN"); !exists {
_ = os.Setenv("DATABASE_DSN", "file:./test.db")
_ = os.Remove("./test.db")
}
_ = os.Setenv("ENVIRONMENT", "test")
// echo -n 'test-paseto-key-dont-use-in-prod' | base64
_ = os.Setenv("PASETO_KEY", "dGVzdC1wYXNldG8ta2V5LWRvbnQtdXNlLWluLXByb2Q=")
dsn := os.Getenv("DATABASE_DSN")
switch {
case strings.HasPrefix(dsn, "postgres:"):
dbDriver = "postgres"
default:
dbDriver = "sqlite3"
}
var err error
db, err = sql.Open(dbDriver, dsn)
if err != nil {
log.Fatal(err)
}
// This is needed, otherwise we get a database-locked error
// TODO: investigate the root cause
if dbDriver == "sqlite3" {
_, _ = db.Exec("PRAGMA journal_mode=WAL;")
}
// Setup the app as it is done in the main function
app, _ = Setup()
}
func TestMain(m *testing.M) {
code := m.Run()
os.Exit(code)
}
// newTestRequest wraps http.NewRequest and sets the Host header
// required by fasthttp >= 1.70.
func newTestRequest(method, url string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequest(method, url, body) //nolint:noctx
if err != nil {
return nil, err
}
req.Host = "localhost"
return req, nil
}
func loadFixtures(t *testing.T) {
t.Helper()
fixtures, err := testfixtures.New(
testfixtures.Database(db),
testfixtures.Dialect(dbDriver),
testfixtures.Directory("test/testdata/fixtures/"),
)
require.NoError(t, err, "failed to create test fixtures")
err = fixtures.Load()
require.NoError(t, err, "failed to load test fixtures")
}
func runTestCases(t *testing.T, tests []TestCase) {
for _, test := range tests {
description := test.description
if description == "" {
description = test.query
}
t.Run(description, func(t *testing.T) {
loadFixtures(t)
if test.setupFunc != nil {
test.setupFunc(t)
}
query := strings.Split(test.query, " ")
u, err := url.Parse(query[1])
if err != nil {
assert.Fail(t, err.Error())
}
req, err := newTestRequest(query[0], query[1], strings.NewReader(test.body))
if err != nil {
assert.Fail(t, err.Error())
}
if test.headers != nil {
req.Header = test.headers
}
req.URL.RawQuery = u.Query().Encode()
res, err := app.Test(req, -1)
assert.Nil(t, err)
assert.Equal(t, test.expectedCode, res.StatusCode)
body, err := io.ReadAll(res.Body)
assert.Nil(t, err)
if test.validateFunc != nil {
var bodyMap map[string]interface{}
err = json.Unmarshal(body, &bodyMap)
require.NoError(t, err, "failed to unmarshal response body:\n%s", body)
test.validateFunc(t, bodyMap)
if t.Failed() {
log.Printf("\nAPI response:\n%s\n", body)
}
} else {
assert.Equal(t, test.expectedBody, string(body))
}
assert.Equal(t, test.expectedContentType, res.Header.Get("Content-Type"))
})
}
}
// assertUUID checks that val is a string matching the UUID format.
func assertUUID(t *testing.T, val interface{}) {
t.Helper()
s, ok := val.(string)
require.True(t, ok, "expected string UUID, got %T: %v", val, val)
match, err := regexp.MatchString(UUID_REGEXP, s)
require.NoError(t, err)
assert.True(t, match, "expected UUID format, got %q", s)
}
// assertRFC3339 checks that val is a string in RFC3339 format and returns the parsed time.
func assertRFC3339(t *testing.T, val interface{}) time.Time {
t.Helper()
s, ok := val.(string)
require.True(t, ok, "expected RFC3339 string, got %T: %v", val, val)
parsed, err := time.Parse(time.RFC3339, s)
assert.NoError(t, err, "expected RFC3339 timestamp, got %q", s)
return parsed
}
// assertTimestamps checks that the map has valid RFC3339 createdAt and updatedAt fields.
func assertTimestamps(t *testing.T, m map[string]interface{}) {
t.Helper()
assertRFC3339(t, m["createdAt"])
assertRFC3339(t, m["updatedAt"])
}
// assertOnlyKeys checks that the map contains no keys outside the allowed set.
func assertOnlyKeys(t *testing.T, m map[string]interface{}, keys ...string) {
t.Helper()
for key := range m {
assert.Contains(t, keys, key, "unexpected key %q in response", key)
}
}
// assertListResponse extracts the data array from a paginated response.
func assertListResponse(t *testing.T, response map[string]interface{}) []map[string]interface{} {
t.Helper()
require.IsType(t, []interface{}{}, response["data"], "response.data should be an array")
raw := response["data"].([]interface{})
items := make([]map[string]interface{}, len(raw))
for i, item := range raw {
require.IsType(t, map[string]interface{}{}, item, "data[%d] should be an object", i)
items[i] = item.(map[string]interface{})
}
return items
}
// assertPaginationLinks checks prev and next links in a paginated response.
// Pass nil for prev/next to assert they are absent, or a string to assert the exact value.
func assertPaginationLinks(t *testing.T, response map[string]interface{}, expectedPrev, expectedNext interface{}) {
t.Helper()
require.IsType(t, map[string]interface{}{}, response["links"])
links := response["links"].(map[string]interface{})
assert.Equal(t, expectedPrev, links["prev"])
assert.Equal(t, expectedNext, links["next"])
}
// placeholder returns the SQL placeholder for the current db driver.
func placeholder(n int) string {
if dbDriver == "sqlite3" {
return "?"
}
return fmt.Sprintf("$%d", n)
}
// dbValue reads the value of column from the row matching whereCol=whereVal in the given table.
func dbValue(t *testing.T, table, column, whereCol, whereVal string) string {
t.Helper()
var val string
query := fmt.Sprintf("SELECT %s FROM %s WHERE %s = %s", column, table, whereCol, placeholder(1))
err := db.QueryRow(query, whereVal).Scan(&val)
require.NoError(t, err)
return val
}
// dbCount queries the count of rows matching column=value in the given table.
func dbCount(t *testing.T, table, column, value string) int {
t.Helper()
n, err := strconv.Atoi(dbValue(t, table, "COUNT(*)", column, value))
require.NoError(t, err)
return n
}