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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
|
package main
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"strings"
"testing"
)
func setupTestServer(t *testing.T) (*DB, *httptest.Server) {
t.Helper()
dir := t.TempDir()
dbPath := filepath.Join(dir, "test.db")
db, err := OpenDB(dbPath)
if err != nil {
t.Fatalf("OpenDB failed: %v", err)
}
journals := []Journal{
{FullName: "Journal of Applied Physics", Abbreviation: "J APPL PHYS"},
{FullName: "Nature Medicine", Abbreviation: "NAT MED"},
{FullName: "Physical Review Letters", Abbreviation: "PHYS REV LETT"},
{FullName: "Nature Biotechnology", Abbreviation: "NAT BIOTECHNOL"},
{FullName: "Nature & Science", Abbreviation: "NAT SCI"},
{FullName: "C++ Weekly", Abbreviation: "C WEEKLY"},
{FullName: "Physical Review (Letters)", Abbreviation: "PHYS REV LETT"},
{FullName: "Proceedings of the National Academy of Sciences", Abbreviation: "PROC NAT ACAD SCI"},
}
if err := db.InsertJournals(journals); err != nil {
t.Fatalf("InsertJournals failed: %v", err)
}
mux := http.NewServeMux()
mux.HandleFunc("/", handleRoot())
mux.HandleFunc("/api/search", handleSearch(db, 1000))
mux.HandleFunc("/api/health", handleHealth(db, 1000))
server := httptest.NewServer(mux)
t.Cleanup(func() {
server.Close()
db.Close()
})
return db, server
}
func get(t *testing.T, url string) *http.Response {
t.Helper()
resp, err := http.Get(url)
if err != nil {
t.Fatalf("GET %s failed: %v", url, err)
}
return resp
}
func readBody(t *testing.T, resp *http.Response) string {
t.Helper()
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("reading body: %v", err)
}
return string(b)
}
func decodeJournals(t *testing.T, body string) []Journal {
t.Helper()
var results []Journal
if err := json.Unmarshal([]byte(body), &results); err != nil {
t.Fatalf("json decode failed: %v\nbody: %s", err, body)
}
return results
}
func TestGetRoot(t *testing.T) {
_, server := setupTestServer(t)
resp := get(t, server.URL+"/")
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Errorf("expected 200, got %d", resp.StatusCode)
}
ct := resp.Header.Get("Content-Type")
if !strings.Contains(ct, "text/html") {
t.Errorf("expected text/html content type, got %s", ct)
}
body := readBody(t, resp)
if !strings.Contains(body, "Journal Abbreviations") {
t.Error("expected page title in HTML body")
}
}
func TestGetRootNotFound(t *testing.T) {
_, server := setupTestServer(t)
resp := get(t, server.URL+"/nonexistent")
defer resp.Body.Close()
if resp.StatusCode != 404 {
t.Errorf("expected 404 for /nonexistent, got %d", resp.StatusCode)
}
}
func TestSearchByFullName(t *testing.T) {
_, server := setupTestServer(t)
resp := get(t, server.URL+"/api/search?q=physics")
body := readBody(t, resp)
results := decodeJournals(t, body)
found := false
for _, j := range results {
if j.FullName == "Journal of Applied Physics" {
found = true
if j.Abbreviation != "J APPL PHYS" {
t.Errorf("expected abbreviation 'J APPL PHYS', got %q", j.Abbreviation)
}
}
}
if !found {
t.Error("expected to find 'Journal of Applied Physics' when searching 'physics'")
}
}
func TestSearchByAbbreviation(t *testing.T) {
_, server := setupTestServer(t)
resp := get(t, server.URL+"/api/search?q=NAT+MED")
body := readBody(t, resp)
results := decodeJournals(t, body)
found := false
for _, j := range results {
if j.FullName == "Nature Medicine" {
found = true
}
}
if !found {
t.Errorf("expected to find 'Nature Medicine' when searching abbreviation 'NAT MED', got %d results", len(results))
}
}
func TestSearchCaseInsensitive(t *testing.T) {
_, server := setupTestServer(t)
lowerResp := get(t, server.URL+"/api/search?q=nature+medicine")
lowerBody := readBody(t, lowerResp)
lowerResults := decodeJournals(t, lowerBody)
upperResp := get(t, server.URL+"/api/search?q=NATURE+MEDICINE")
upperBody := readBody(t, upperResp)
upperResults := decodeJournals(t, upperBody)
if len(lowerResults) == 0 {
t.Error("lowercase search returned no results")
}
if len(upperResults) == 0 {
t.Error("uppercase search returned no results")
}
if len(lowerResults) != len(upperResults) {
t.Errorf("case insensitive: lower=%d results, upper=%d results", len(lowerResults), len(upperResults))
}
}
func TestSearchMultipleMatches(t *testing.T) {
_, server := setupTestServer(t)
resp := get(t, server.URL+"/api/search?q=nature")
body := readBody(t, resp)
results := decodeJournals(t, body)
if len(results) < 2 {
t.Errorf("expected at least 2 results for 'nature', got %d", len(results))
}
names := map[string]bool{}
for _, j := range results {
names[j.FullName] = true
}
if !names["Nature Medicine"] {
t.Error("expected 'Nature Medicine' in results")
}
if !names["Nature Biotechnology"] {
t.Error("expected 'Nature Biotechnology' in results")
}
}
func TestSearchNoResults(t *testing.T) {
_, server := setupTestServer(t)
resp := get(t, server.URL+"/api/search?q=zzzzznonexistent")
body := readBody(t, resp)
if resp.StatusCode != 200 {
t.Errorf("expected 200 for no-results query, got %d", resp.StatusCode)
}
results := decodeJournals(t, body)
if len(results) != 0 {
t.Errorf("expected 0 results for nonexistent query, got %d", len(results))
}
}
func TestSearchMissingQuery(t *testing.T) {
_, server := setupTestServer(t)
resp := get(t, server.URL+"/api/search")
body := readBody(t, resp)
if resp.StatusCode != 400 {
t.Errorf("expected 400 for missing q param, got %d", resp.StatusCode)
}
if !strings.Contains(body, "missing query") {
t.Errorf("expected error message about missing query, got: %s", body)
}
}
func TestSearchWrongMethod(t *testing.T) {
_, server := setupTestServer(t)
resp, err := http.Post(server.URL+"/api/search?q=test", "text/plain", nil)
if err != nil {
t.Fatalf("POST request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != 405 {
t.Errorf("expected 405 for POST, got %d", resp.StatusCode)
}
}
func TestSearchLimitParameter(t *testing.T) {
_, server := setupTestServer(t)
resp := get(t, server.URL+"/api/search?q=nature&limit=1")
body := readBody(t, resp)
results := decodeJournals(t, body)
if len(results) > 1 {
t.Errorf("expected at most 1 result with limit=1, got %d", len(results))
}
}
func TestSearchInvalidLimit(t *testing.T) {
_, server := setupTestServer(t)
resp := get(t, server.URL+"/api/search?q=nature&limit=abc")
body := readBody(t, resp)
if resp.StatusCode != 200 {
t.Errorf("expected 200 with invalid limit (should default), got %d", resp.StatusCode)
}
results := decodeJournals(t, body)
if len(results) == 0 {
t.Error("invalid limit should default to 50 and still return results")
}
}
func TestSearchSpecialChars(t *testing.T) {
_, server := setupTestServer(t)
for _, q := range []string{"Nature & Science", "C++"} {
resp := get(t, server.URL+"/api/search?q="+url.QueryEscape(q))
body := readBody(t, resp)
if resp.StatusCode != 200 {
t.Errorf("search for %q returned %d", q, resp.StatusCode)
}
results := decodeJournals(t, body)
if len(results) == 0 {
t.Errorf("expected results for %q", q)
}
}
}
func TestHealthEndpoint(t *testing.T) {
_, server := setupTestServer(t)
resp := get(t, server.URL+"/api/health")
body := readBody(t, resp)
if resp.StatusCode != 200 {
t.Errorf("expected 200, got %d", resp.StatusCode)
}
var result map[string]interface{}
if err := json.Unmarshal([]byte(body), &result); err != nil {
t.Fatalf("json decode failed: %v", err)
}
if result["status"] != "ok" {
t.Errorf("expected status 'ok', got %v", result["status"])
}
if result["db_loaded"] != true {
t.Errorf("expected db_loaded true, got %v", result["db_loaded"])
}
count, ok := result["total_journals"].(float64)
if !ok || count < 1 {
t.Errorf("expected total_journals >= 1, got %v", result["total_journals"])
}
}
func TestHealthWrongMethod(t *testing.T) {
_, server := setupTestServer(t)
resp, err := http.Post(server.URL+"/api/health", "text/plain", nil)
if err != nil {
t.Fatalf("POST request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != 405 {
t.Errorf("expected 405 for POST to health, got %d", resp.StatusCode)
}
}
func TestSearchResponseIsJSONArray(t *testing.T) {
_, server := setupTestServer(t)
resp := get(t, server.URL+"/api/search?q=nature")
body := readBody(t, resp)
ct := resp.Header.Get("Content-Type")
if !strings.Contains(ct, "application/json") {
t.Errorf("expected application/json, got %s", ct)
}
if !strings.HasPrefix(strings.TrimSpace(body), "[") {
t.Errorf("expected JSON array response, got: %s", body[:min(len(body), 50)])
}
}
func TestSearchResultStructure(t *testing.T) {
_, server := setupTestServer(t)
resp := get(t, server.URL+"/api/search?q=Nature+Medicine")
body := readBody(t, resp)
results := decodeJournals(t, body)
if len(results) == 0 {
t.Fatal("expected at least one result")
}
j := results[0]
if j.ID == 0 {
t.Error("expected non-zero ID")
}
if j.FullName == "" {
t.Error("expected non-empty FullName")
}
if j.Abbreviation == "" {
t.Error("expected non-empty Abbreviation")
}
}
func TestRateLimiting(t *testing.T) {
dir := t.TempDir()
dbPath := filepath.Join(dir, "test.db")
db, err := OpenDB(dbPath)
if err != nil {
t.Fatalf("OpenDB failed: %v", err)
}
journals := []Journal{
{FullName: "Test Journal", Abbreviation: "TEST J"},
}
if err := db.InsertJournals(journals); err != nil {
t.Fatalf("InsertJournals failed: %v", err)
}
mux := http.NewServeMux()
mux.HandleFunc("/api/search", handleSearch(db, 3))
srv := httptest.NewServer(mux)
t.Cleanup(func() {
srv.Close()
db.Close()
})
tooManyCount := 0
for i := 0; i < 10; i++ {
resp := get(t, srv.URL+"/api/search?q=test")
resp.Body.Close()
if resp.StatusCode == 429 {
tooManyCount++
}
}
if tooManyCount == 0 {
t.Error("expected at least one 429 response when rate limit is 3/min and we made 10 rapid requests")
}
}
|