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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
|
// Tests for the Miniflux client against an httptest fake. Inline fixture
// JSON mirrors a real GET /v1/entries response shape (extra API fields
// included to prove they're harmlessly ignored).
package miniflux
import (
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
const entriesFixture = `{
"total": 2,
"entries": [
{
"id": 41001,
"user_id": 3,
"feed_id": 77,
"status": "read",
"hash": "abc123",
"title": "Why headline-only models are fine actually",
"url": "https://example.com/posts/headline-models",
"comments_url": "",
"published_at": "2024-03-02T10:15:00Z",
"created_at": "2024-03-02T11:00:00Z",
"changed_at": "2024-03-05T08:30:00Z",
"content": "<p>Article body here.</p>",
"author": "Jane Doe",
"share_code": "",
"starred": true,
"reading_time": 4,
"enclosures": null,
"feed": {
"id": 77,
"user_id": 3,
"feed_url": "https://example.com/feed.xml",
"site_url": "https://example.com",
"title": "Example Blog",
"checked_at": "2024-03-05T09:00:00Z",
"etag_header": "",
"last_modified_header": "",
"parsing_error_message": "",
"parsing_error_count": 0
}
},
{
"id": 41002,
"user_id": 3,
"feed_id": 102,
"status": "unread",
"hash": "def456",
"title": "Sixty days of RSS triage: a field report",
"url": "https://blog.other.example/triage-report",
"comments_url": "",
"published_at": "2024-03-04T14:05:00Z",
"created_at": "2024-03-04T15:20:00Z",
"changed_at": "2024-03-04T15:20:00Z",
"content": "<p>Another body.</p>",
"author": "",
"share_code": "",
"starred": false,
"reading_time": 9,
"enclosures": null,
"feed": {
"id": 102,
"user_id": 3,
"feed_url": "https://blog.other.example/rss",
"site_url": "https://blog.other.example",
"title": "Other Blog",
"checked_at": "2024-03-05T09:00:00Z",
"etag_header": "",
"last_modified_header": "",
"parsing_error_message": "",
"parsing_error_count": 0
}
}
]
}`
// fakeServer records the last request's method, path, auth header, content
// type, body and query, then replies with the fixture (or a set status).
// Accepts anything under /v1/ (entries, feeds, per-feed updates).
type fakeServer struct {
t *testing.T
status int
body string
gotHeader string
gotMethod string
gotPath string
gotContentType string
gotRequestBody string
gotQuery map[string]string
sawRequest bool
}
func (f *fakeServer) handler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
f.sawRequest = true
f.gotHeader = r.Header.Get("X-Auth-Token")
f.gotMethod = r.Method
f.gotPath = r.URL.Path
f.gotContentType = r.Header.Get("Content-Type")
f.gotQuery = map[string]string{}
for k, v := range r.URL.Query() {
f.gotQuery[k] = v[0]
}
if r.Body != nil {
b, _ := io.ReadAll(r.Body)
f.gotRequestBody = string(b)
}
if !strings.HasPrefix(r.URL.Path, "/v1/") {
f.t.Errorf("unexpected path: %s", r.URL.Path)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(f.status)
_, _ = w.Write([]byte(f.body))
}
}
func newFakeClient(t *testing.T, f *fakeServer) *Client {
t.Helper()
srv := httptest.NewServer(f.handler())
t.Cleanup(srv.Close)
return NewClientWithHTTP(Config{BaseURL: srv.URL, Token: "test-token-123"}, srv.Client())
}
func TestEntriesDecodesFixture(t *testing.T) {
f := &fakeServer{t: t, status: http.StatusOK, body: entriesFixture}
client := newFakeClient(t, f)
set, err := client.Entries(Filters{})
if err != nil {
t.Fatalf("Entries: %v", err)
}
if !f.sawRequest {
t.Fatal("fake server saw no request")
}
if f.gotHeader != "test-token-123" {
t.Errorf("X-Auth-Token = %q, want test-token-123", f.gotHeader)
}
if set.Total != 2 {
t.Errorf("Total = %d, want 2", set.Total)
}
if len(set.Entries) != 2 {
t.Fatalf("len(Entries) = %d, want 2", len(set.Entries))
}
e := set.Entries[0]
if e.ID != 41001 {
t.Errorf("entry[0].ID = %d, want 41001", e.ID)
}
if e.Title != "Why headline-only models are fine actually" {
t.Errorf("entry[0].Title = %q", e.Title)
}
if !e.Starred {
t.Error("entry[0].Starred = false, want true")
}
if e.Status != "read" {
t.Errorf("entry[0].Status = %q, want read", e.Status)
}
if e.Feed.ID != 77 || e.Feed.Title != "Example Blog" {
t.Errorf("entry[0].Feed = %+v", e.Feed)
}
if e.PublishedAt.IsZero() || e.ChangedAt.IsZero() {
t.Errorf("entry[0] times not parsed: %v / %v", e.PublishedAt, e.ChangedAt)
}
}
func TestEntriesSendsFilters(t *testing.T) {
f := &fakeServer{t: t, status: http.StatusOK, body: `{"total":0,"entries":[]}`}
client := newFakeClient(t, f)
starred := true
_, err := client.Entries(Filters{
Starred: &starred,
Status: "read",
FeedID: 77,
ChangedAfter: 1700000000,
PublishedAfter: 1700000000,
AfterEntryID: 40999,
Limit: 200,
Offset: 400,
})
if err != nil {
t.Fatalf("Entries: %v", err)
}
want := map[string]string{
"starred": "true",
"status": "read",
"feed_id": "77",
"changed_after": "1700000000",
"published_after": "1700000000",
"after_entry_id": "40999",
"limit": "200",
"offset": "400",
}
for k, v := range want {
if f.gotQuery[k] != v {
t.Errorf("query %s = %q, want %q", k, f.gotQuery[k], v)
}
}
}
func TestEntriesZeroFiltersSendNoParams(t *testing.T) {
f := &fakeServer{t: t, status: http.StatusOK, body: `{"total":0,"entries":[]}`}
client := newFakeClient(t, f)
if _, err := client.Entries(Filters{}); err != nil {
t.Fatalf("Entries: %v", err)
}
if len(f.gotQuery) != 0 {
t.Errorf("zero Filters sent params: %v", f.gotQuery)
}
}
func TestEntriesHTTPError(t *testing.T) {
f := &fakeServer{t: t, status: http.StatusUnauthorized, body: `{"error_message":"bad token"}`}
client := newFakeClient(t, f)
_, err := client.Entries(Filters{})
if err == nil {
t.Fatal("expected error on 401, got nil")
}
if !strings.Contains(err.Error(), "401") {
t.Errorf("error should name the status: %v", err)
}
}
func TestEntriesBadJSON(t *testing.T) {
f := &fakeServer{t: t, status: http.StatusOK, body: `not json`}
client := newFakeClient(t, f)
if _, err := client.Entries(Filters{}); err == nil {
t.Fatal("expected decode error, got nil")
}
}
const feedsFixture = `[
{
"id": 77,
"user_id": 3,
"feed_url": "https://example.com/feed.xml",
"site_url": "https://example.com",
"title": "Example Blog",
"disabled": false,
"category": {"id": 1, "title": "Tech", "user_id": 3}
},
{
"id": 102,
"user_id": 3,
"feed_url": "https://daily.example/rss",
"site_url": "https://daily.example",
"title": "Some Daily",
"disabled": true,
"category": {"id": 2, "title": "News", "user_id": 3}
}
]`
func TestFeedsDecodesFixture(t *testing.T) {
f := &fakeServer{t: t, status: http.StatusOK, body: feedsFixture}
client := newFakeClient(t, f)
feeds, err := client.Feeds()
if err != nil {
t.Fatalf("Feeds: %v", err)
}
if !f.sawRequest {
t.Fatal("fake server saw no request")
}
if f.gotHeader != "test-token-123" {
t.Errorf("X-Auth-Token = %q, want test-token-123", f.gotHeader)
}
if len(feeds) != 2 {
t.Fatalf("len(feeds) = %d, want 2", len(feeds))
}
if feeds[0].ID != 77 || feeds[0].Title != "Example Blog" || feeds[0].SiteURL != "https://example.com" {
t.Errorf("feeds[0] = %+v", feeds[0])
}
if feeds[0].Disabled {
t.Error("feeds[0].Disabled = true, want false")
}
if !feeds[1].Disabled {
t.Error("feeds[1].Disabled = false, want true")
}
if feeds[0].Category.Title != "Tech" || feeds[1].Category.Title != "News" {
t.Errorf("categories = %q / %q, want Tech / News",
feeds[0].Category.Title, feeds[1].Category.Title)
}
}
// The politeness write must be a PUT to the feed's own URL, authenticated,
// JSON-typed, and whose body is exactly the two fetch fields — the property
// that keeps MakeFeedPolite from touching anything else on the feed.
func TestMakeFeedPoliteSendsOnlyTheTwoFields(t *testing.T) {
f := &fakeServer{t: t, status: http.StatusNoContent}
client := newFakeClient(t, f)
if err := client.MakeFeedPolite(77); err != nil {
t.Fatalf("MakeFeedPolite: %v", err)
}
if !f.sawRequest {
t.Fatal("fake server saw no request")
}
if f.gotMethod != http.MethodPut {
t.Errorf("method = %q, want PUT", f.gotMethod)
}
if f.gotPath != "/v1/feeds/77" {
t.Errorf("path = %q, want /v1/feeds/77", f.gotPath)
}
if f.gotHeader != "test-token-123" {
t.Errorf("X-Auth-Token = %q, want test-token-123", f.gotHeader)
}
if f.gotContentType != "application/json" {
t.Errorf("Content-Type = %q, want application/json", f.gotContentType)
}
wantBody := `{"crawler":false,"ignore_http_cache":false}`
if f.gotRequestBody != wantBody {
t.Errorf("request body = %q, want %q", f.gotRequestBody, wantBody)
}
}
// All 2xx are success: reads get 200, 204 (empty body) covers some PUTs,
// and — live-observed on reader.samsci.com — Miniflux answers feed updates
// with 201 + the updated feed JSON, even though nothing was created. The
// first live polite run failed on exactly that; this test guards against
// reintroducing it.
func TestMakeFeedPoliteAcceptsAll2xx(t *testing.T) {
for _, status := range []int{http.StatusOK, http.StatusCreated, http.StatusNoContent} {
f := &fakeServer{t: t, status: status, body: `{"id":77,"crawler":false,"ignore_http_cache":false}`}
client := newFakeClient(t, f)
if err := client.MakeFeedPolite(77); err != nil {
t.Fatalf("status %d: %v", status, err)
}
}
}
func TestMakeFeedPoliteHTTPError(t *testing.T) {
f := &fakeServer{t: t, status: http.StatusNotFound}
client := newFakeClient(t, f)
err := client.MakeFeedPolite(999)
if err == nil {
t.Fatal("expected error on 404, got nil")
}
if !strings.Contains(err.Error(), "404") {
t.Errorf("error should name the status: %v", err)
}
if !strings.Contains(err.Error(), "/v1/feeds/999") {
t.Errorf("error should name the resource: %v", err)
}
}
// flakyTransport fails its first `failures` RoundTrips at the transport
// level (no HTTP status — think DNS read timeouts, resets), then delegates
// to the inner transport. Counts every attempt.
type flakyTransport struct {
failures int
inner http.RoundTripper
attempts int
}
func (f *flakyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
f.attempts++
if f.failures > 0 {
f.failures--
return nil, &net.OpError{Op: "dial", Net: "tcp", Err: fmt.Errorf("simulated blip")}
}
return f.inner.RoundTrip(req)
}
// installFlake wraps the client's transport with a flaky one and shrinks
// the retry waits so tests don't sleep real seconds.
func installFlake(t *testing.T, client *Client, failures int) *flakyTransport {
t.Helper()
client.retryWait = []time.Duration{time.Millisecond, time.Millisecond}
inner := client.httpClient.Transport
if inner == nil {
inner = http.DefaultTransport
}
flake := &flakyTransport{failures: failures, inner: inner}
client.httpClient.Transport = flake
return flake
}
// Transport blips (live-observed: DNS read timeout on a flaky resolver) are
// retried, and the retried request must still carry the full body — a
// drained reader re-sent would deliver an empty PATCH.
func TestTransportBlipsRetriedWithBodyIntact(t *testing.T) {
f := &fakeServer{t: t, status: http.StatusCreated}
client := newFakeClient(t, f)
flake := installFlake(t, client, 2)
if err := client.MakeFeedPolite(77); err != nil {
t.Fatalf("MakeFeedPolite after two blips: %v", err)
}
if flake.attempts != 3 {
t.Errorf("attempts = %d, want 3 (two blips + one success)", flake.attempts)
}
wantBody := `{"crawler":false,"ignore_http_cache":false}`
if f.gotRequestBody != wantBody {
t.Errorf("retried PUT body = %q, want %q (body must be re-armed per attempt)", f.gotRequestBody, wantBody)
}
}
// The retry loop is not a hang: it gives up after len(retryWait) extra
// attempts and the final error still names the request.
func TestTransportFailuresGiveUp(t *testing.T) {
f := &fakeServer{t: t, status: http.StatusOK, body: `{"total":0,"entries":[]}`}
client := newFakeClient(t, f)
client.retryWait = []time.Duration{time.Millisecond}
inner := client.httpClient.Transport
if inner == nil {
inner = http.DefaultTransport
}
flake := &flakyTransport{failures: 99, inner: inner}
client.httpClient.Transport = flake
_, err := client.Entries(Filters{})
if err == nil {
t.Fatal("expected error after persistent blips, got nil")
}
if !strings.Contains(err.Error(), "/v1/entries") {
t.Errorf("error should name the request: %v", err)
}
if flake.attempts != 2 {
t.Errorf("attempts = %d, want 2 (one try + one retry)", flake.attempts)
}
}
func TestConfigFromEnv(t *testing.T) {
t.Run("primary vars", func(t *testing.T) {
t.Setenv("MINIFLUX_URL", "https://flux.example")
t.Setenv("MINIFLUX_TOKEN", "tok-primary")
cfg, err := ConfigFromEnv()
if err != nil {
t.Fatalf("ConfigFromEnv: %v", err)
}
if cfg.BaseURL != "https://flux.example" || cfg.Token != "tok-primary" {
t.Errorf("cfg = %+v", cfg)
}
})
t.Run("fallback vars", func(t *testing.T) {
t.Setenv("MFLUX_URL", "https://flux.example")
t.Setenv("MFLUX_TOKEN", "tok-fallback")
cfg, err := ConfigFromEnv()
if err != nil {
t.Fatalf("ConfigFromEnv: %v", err)
}
if cfg.Token != "tok-fallback" {
t.Errorf("Token = %q, want tok-fallback", cfg.Token)
}
})
t.Run("primary beats fallback", func(t *testing.T) {
t.Setenv("MINIFLUX_TOKEN", "tok-primary")
t.Setenv("MFLUX_TOKEN", "tok-fallback")
t.Setenv("MINIFLUX_URL", "https://flux.example")
cfg, err := ConfigFromEnv()
if err != nil {
t.Fatalf("ConfigFromEnv: %v", err)
}
if cfg.Token != "tok-primary" {
t.Errorf("Token = %q, want tok-primary", cfg.Token)
}
})
t.Run("missing URL errors naming both vars", func(t *testing.T) {
t.Setenv("MINIFLUX_TOKEN", "tok")
_, err := ConfigFromEnv()
if err == nil {
t.Fatal("expected error, got nil")
}
if !strings.Contains(err.Error(), "MINIFLUX_URL") || !strings.Contains(err.Error(), "MFLUX_URL") {
t.Errorf("error should name both URL vars: %v", err)
}
})
t.Run("missing token errors naming both vars", func(t *testing.T) {
t.Setenv("MINIFLUX_URL", "https://flux.example")
_, err := ConfigFromEnv()
if err == nil {
t.Fatal("expected error, got nil")
}
if !strings.Contains(err.Error(), "MINIFLUX_TOKEN") || !strings.Contains(err.Error(), "MFLUX_TOKEN") {
t.Errorf("error should name both token vars: %v", err)
}
})
}
// Compile-time assertion: EntrySet round-trips through encoding/json (a
// guard against tag typos drifting from the API's field names).
func TestEntrySetJSONRoundTrip(t *testing.T) {
var set EntrySet
if err := json.Unmarshal([]byte(entriesFixture), &set); err != nil {
t.Fatalf("fixture does not decode into EntrySet: %v", err)
}
b, err := json.Marshal(set)
if err != nil {
t.Fatalf("marshal: %v", err)
}
var back EntrySet
if err := json.Unmarshal(b, &back); err != nil {
t.Fatalf("re-decode: %v", err)
}
if back.Total != set.Total || len(back.Entries) != len(set.Entries) {
t.Error("round trip mismatch")
}
}
|