-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.go
More file actions
219 lines (201 loc) · 6.76 KB
/
Copy pathmain_test.go
File metadata and controls
219 lines (201 loc) · 6.76 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
package main
// Tests for admin endpoints in main.go.
// These tests use an in-memory SQLite database and exercise the admin
// handlers directly via httptest.
//
// Conventions:
// - Each bug fix is driven by a failing test written first (RED),
// then the smallest possible change to flip it to GREEN.
// - Tests are table-driven where it clarifies multiple scenarios.
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/go-chi/chi/v5"
_ "modernc.org/sqlite"
)
func testDBName(t *testing.T) string {
t.Helper()
// Temp file (not :memory:) avoids the "out of memory" error some
// modernc.org/sqlite builds emit for shared in-memory caches.
path := filepath.Join(os.TempDir(),
fmt.Sprintf("bookmarks_test_%s_%d.db", t.Name(), time.Now().UnixNano()))
return fmt.Sprintf("file:%s?_foreign_keys=on&_journal_mode=WAL&_busy_timeout=5000", path)
}
// newTestServer wires up a *server backed by a fresh in-memory SQLite.
// It creates the users, nodes, and audit_log tables the admin endpoints
// need without going through the full upgrade system.
func newTestServer(t *testing.T) (*server, *sql.DB) {
t.Helper()
dsn := testDBName(t)
dbPath := strings.TrimPrefix(strings.TrimSuffix(dsn, "?_foreign_keys=on&_journal_mode=WAL&_busy_timeout=5000"), "file:")
db, err := sql.Open("sqlite", dsn)
if err != nil {
t.Fatalf("open in-memory sqlite: %v", err)
}
db.SetMaxOpenConns(1)
if _, err := db.Exec("PRAGMA foreign_keys = ON"); err != nil {
t.Fatalf("enable foreign keys: %v", err)
}
mustExec(t, db, `
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password TEXT NOT NULL,
token TEXT,
nickname TEXT,
avatar TEXT,
email TEXT,
is_active INTEGER NOT NULL DEFAULT 1,
is_admin INTEGER NOT NULL DEFAULT 0,
api_key TEXT,
last_login_at DATETIME,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
`)
mustExec(t, db, `
CREATE TABLE nodes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL DEFAULT 0,
parent_id INTEGER,
type TEXT NOT NULL CHECK (type IN ('folder', 'bookmark')),
title TEXT NOT NULL,
url TEXT,
favicon_url TEXT,
remark TEXT NOT NULL DEFAULT '',
visibility TEXT NOT NULL DEFAULT 'private',
position INTEGER NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
`)
mustExec(t, db, `
CREATE TABLE audit_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
username TEXT NOT NULL DEFAULT '',
action TEXT NOT NULL,
target_type TEXT NOT NULL DEFAULT '',
target_id INTEGER NOT NULL DEFAULT 0,
detail TEXT NOT NULL DEFAULT '',
ip_address TEXT NOT NULL DEFAULT '',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
`)
srv := &server{db: db, httpClient: http.DefaultClient}
t.Cleanup(func() {
_ = db.Close()
_ = os.Remove(dbPath)
_ = os.Remove(dbPath + "-wal")
_ = os.Remove(dbPath + "-shm")
})
return srv, db
}
func mustExec(t *testing.T, db *sql.DB, stmt string, args ...any) {
t.Helper()
if _, err := db.Exec(stmt, args...); err != nil {
t.Fatalf("exec %q: %v", stmt, err)
}
}
// insertTestUser inserts a users row and stores a stable token of the
// form "tok-<username>" so callers can authenticate by passing it as
// the Authorization header. nickname defaults to the username so
// handleGetUsers can scan it as a non-null string.
func insertTestUser(t *testing.T, db *sql.DB, username string, isAdmin bool) int64 {
t.Helper()
admin := 0
if isAdmin {
admin = 1
}
token := "tok-" + username
res, err := db.ExecContext(context.Background(),
`INSERT INTO users (username, password, nickname, email, is_admin, is_active, token) VALUES (?, ?, ?, ?, ?, 1, ?)`,
username, "x", username, username+"@example.com", admin, token)
if err != nil {
t.Fatalf("insert user: %v", err)
}
id, err := res.LastInsertId()
if err != nil {
t.Fatalf("LastInsertId: %v", err)
}
return id
}
// userTokenFor returns the canonical token stored for a user created via
// insertTestUser. Tests pass it in the Authorization header so the real
// tokenAuthMiddleware accepts the request.
func userTokenFor(username string) string { return "tok-" + username }
// withUserID returns a context carrying a user id, matching the
// shape main.go uses after the token-auth middleware sets it.
func withUserID(ctx context.Context, userID int64) context.Context {
return context.WithValue(ctx, userContextKey, userID)
}
// jsonRequest builds an *http.Request with a JSON body (or nil for GET/DELETE).
func jsonRequest(t *testing.T, method, path string, body any) *http.Request {
t.Helper()
var reader io.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
t.Fatalf("marshal body: %v", err)
}
reader = bytes.NewReader(b)
}
r := httptest.NewRequest(method, path, reader)
if body != nil {
r.Header.Set("Content-Type", "application/json")
}
return r
}
// newRecorder executes the handler under test and returns the recorder.
func runHandler(srv *server, h http.HandlerFunc, r *http.Request) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
h(rec, r)
return rec
}
// newAdminRouter returns a chi router that mounts only the admin endpoints
// with the same middleware stack as main.go. Tests use this to assert
// end-to-end status codes without spinning up a real HTTP listener.
func newAdminRouter(srv *server) http.Handler {
r := chi.NewRouter()
r.Use(srv.tokenAuthMiddlewareChi)
r.Use(srv.adminMiddlewareChi)
r.Get("/admin/stats", srv.handleAdminStats)
r.Get("/admin/users/{userId}/tree", srv.handleAdminGetUserTree)
r.Put("/admin/nodes/{id}", srv.handleAdminUpdateNode)
r.Delete("/admin/nodes/{id}", srv.handleAdminDeleteNode)
r.Get("/admin/audit-log", srv.handleGetAuditLog)
r.Post("/admin/folders", srv.handleAdminCreateFolder)
r.Post("/admin/bookmarks", srv.handleAdminCreateBookmark)
r.Put("/admin/nodes/reorder", srv.handleAdminReorderNodes)
return r
}
// do runs an HTTP request through the router and returns the response.
func do(t *testing.T, h http.Handler, r *http.Request) *httptest.ResponseRecorder {
t.Helper()
rec := httptest.NewRecorder()
h.ServeHTTP(rec, r)
return rec
}
// decodeJSON unmarshals a response body into target and fails the test
// on any decode error.
func decodeJSON(t *testing.T, rec *httptest.ResponseRecorder, target any) {
t.Helper()
if err := json.NewDecoder(rec.Body).Decode(target); err != nil {
t.Fatalf("decode json (status=%d, body=%q): %v", rec.Code, rec.Body.String(), err)
}
}
// contains reports whether sub is contained in s.
func contains(s, sub string) bool {
return strings.Contains(s, sub)
}