-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch_test.go
More file actions
406 lines (367 loc) · 11.2 KB
/
Copy pathfetch_test.go
File metadata and controls
406 lines (367 loc) · 11.2 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
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
package emap
import (
"strings"
"sync/atomic"
"testing"
"time"
)
// ── Pure parser tests ────────────────────────────────────────────────
func TestParseFetchResponseExtractsAllFields(t *testing.T) {
headers := []byte("To: alice@example.com\r\nFrom: bob@example.com\r\nSubject: Hello\r\nDate: Thu, 27 Feb 2026 12:34:56 +0000\r\n\r\n")
body := []byte("Click https://example.com/verify?token=ABC123 to confirm")
literals := [][]byte{headers, body}
line := "* 7 FETCH (UID 42 INTERNALDATE \"27-Feb-2026 12:34:56 +0000\" BODY[HEADER.FIELDS (TO FROM SUBJECT DATE)] \x00L0\x00 BODY[TEXT] \x00L1\x00)"
r, ok := parseFetchResponse(line, literals)
if !ok {
t.Fatal("parseFetchResponse returned not-ok")
}
if r.seq != 7 {
t.Errorf("seq = %d, want 7", r.seq)
}
if r.uid != 42 {
t.Errorf("uid = %d, want 42", r.uid)
}
if r.internalDate.IsZero() {
t.Error("internalDate not parsed")
}
if string(r.headers) != string(headers) {
t.Errorf("headers mismatch:\ngot: %q\nwant: %q", r.headers, headers)
}
if string(r.body) != string(body) {
t.Errorf("body mismatch:\ngot: %q\nwant: %q", r.body, body)
}
}
func TestParseFetchResponseSkipsNonFetchLines(t *testing.T) {
if _, ok := parseFetchResponse("* OK [UIDNEXT 100]", nil); ok {
t.Fatal("expected non-FETCH line to be rejected")
}
if _, ok := parseFetchResponse("A1 OK FETCH completed", nil); ok {
t.Fatal("expected tagged response to be rejected")
}
}
func TestParseHeaderFieldsBareAndAngleAddresses(t *testing.T) {
raw := []byte("To: \"Alice\" <alice@example.com>\r\nFrom: noreply@vendor.com\r\nSubject: Verify\r\nDate: Thu, 27 Feb 2026 12:34:56 +0000\r\n\r\n")
to, from, subject, date := parseHeaderFields(raw)
if to != "alice@example.com" {
t.Errorf("to = %q, want bare alice@example.com", to)
}
if from != "noreply@vendor.com" {
t.Errorf("from = %q", from)
}
if subject != "Verify" {
t.Errorf("subject = %q", subject)
}
if date.IsZero() {
t.Error("date not parsed")
}
}
// ── Integration: FETCH wired through the session loop ───────────────
func TestFetchDeliversNewMailToSubscriber(t *testing.T) {
prev := IdleRoundDuration
IdleRoundDuration = 30 * time.Second
defer func() { IdleRoundDuration = prev }()
srv := newFakeServer()
srv.script = func(fc *fakeConn) {
handleIdleBringUpWithUIDNext(fc, 100)
// Round 1: emit EXISTS → triggers FETCH
handleIdleRound(fc, []string{"* 5 EXISTS\r\n"})
// FETCH returns one mail addressed to our subscriber
handleFetchCommand(fc, []fakeMail{{
UID: 100,
To: "alice+task1@example.com",
From: "no-reply@vendor.com",
Subject: "Verify your account",
Body: "Code: 123456",
}})
// Subsequent rounds: heartbeat-only
for {
if !handleIdleRound(fc, nil) {
return
}
}
}
m := NewManager(time.Hour).withDial(srv.dialer())
defer m.Shutdown()
sub, err := m.Subscribe(sampleCred("inbox@example.com"), Filter{
To: "alice+task1@example.com",
})
if err != nil {
t.Fatal(err)
}
defer sub.Close()
select {
case msg, ok := <-sub.Ch:
if !ok {
t.Fatal("subscription channel closed")
}
if msg.UID != 100 {
t.Errorf("UID = %d, want 100", msg.UID)
}
if msg.To != "alice+task1@example.com" {
t.Errorf("To = %q", msg.To)
}
if msg.From != "no-reply@vendor.com" {
t.Errorf("From = %q", msg.From)
}
if !strings.Contains(msg.Body, "Code: 123456") {
t.Errorf("Body = %q", msg.Body)
}
case <-time.After(2 * time.Second):
t.Fatal("subscriber never received the message")
}
}
func TestFetchFiltersByToHeader(t *testing.T) {
prev := IdleRoundDuration
IdleRoundDuration = 30 * time.Second
defer func() { IdleRoundDuration = prev }()
srv := newFakeServer()
srv.script = func(fc *fakeConn) {
handleIdleBringUpWithUIDNext(fc, 100)
handleIdleRound(fc, []string{"* 5 EXISTS\r\n"})
// Two mails — one for alice, one for bob.
handleFetchCommand(fc, []fakeMail{
{UID: 100, To: "alice@example.com", From: "x@y", Subject: "x", Body: "x"},
{UID: 101, To: "bob@example.com", From: "x@y", Subject: "x", Body: "x"},
})
for {
if !handleIdleRound(fc, nil) {
return
}
}
}
m := NewManager(time.Hour).withDial(srv.dialer())
defer m.Shutdown()
aliceSub, err := m.Subscribe(sampleCred("inbox@example.com"), Filter{To: "alice@example.com"})
if err != nil {
t.Fatal(err)
}
defer aliceSub.Close()
// alice should receive UID 100, NOT 101
select {
case msg := <-aliceSub.Ch:
if msg.UID != 100 {
t.Fatalf("alice expected UID 100, got %d", msg.UID)
}
case <-time.After(2 * time.Second):
t.Fatal("alice never received mail")
}
// No second message for alice
select {
case msg := <-aliceSub.Ch:
t.Fatalf("alice received unexpected second message UID %d", msg.UID)
case <-time.After(100 * time.Millisecond):
}
}
func TestSinceUIDSkipsBacklogOnConnect(t *testing.T) {
// Server reports UIDNEXT = 1_000_000 — meaning ~1M existing messages.
// Our session must NOT FETCH any of them at connect, only on subsequent
// EXISTS events.
srv := newFakeServer()
var fetches atomic.Int32
srv.script = func(fc *fakeConn) {
handleIdleBringUpWithUIDNext(fc, 1_000_000)
// Loop reading commands. Count any FETCH (there should be 0).
for {
tag, rest, err := fc.readCommand()
if err != nil {
return
}
up := strings.ToUpper(rest)
switch {
case up == "IDLE":
if fc.srv != nil {
fc.srv.idleStarts.Add(1)
}
_ = fc.write("+ idling\r\n")
_ = fc.conn.SetReadDeadline(time.Now().Add(2 * time.Second))
line, err := fc.r.ReadString('\n')
_ = fc.conn.SetReadDeadline(time.Time{})
if err != nil {
return
}
if !strings.EqualFold(strings.TrimSpace(line), "DONE") {
return
}
_ = fc.write(tag + " OK IDLE completed\r\n")
case strings.HasPrefix(up, "UID FETCH") || strings.HasPrefix(up, "FETCH"):
fetches.Add(1)
_ = fc.write(tag + " OK FETCH completed\r\n")
case up == "LOGOUT":
_ = fc.write(tag + " OK bye\r\n")
return
}
}
}
m := NewManager(time.Hour).withDial(srv.dialer())
defer m.Shutdown()
sub, err := m.Subscribe(sampleCred("inbox@example.com"), Filter{})
if err != nil {
t.Fatal(err)
}
defer sub.Close()
// Verify sinceUID was initialized to UIDNEXT-1 = 999_999.
s := sessionFor(t, m, sampleCred("inbox@example.com"))
if got := s.sinceUID.Load(); got != 999_999 {
t.Errorf("sinceUID = %d, want 999_999", got)
}
if !s.sinceUIDInitialized.Load() {
t.Error("sinceUIDInitialized should be true after UIDNEXT")
}
// Wait a bit; verify no FETCH was issued (no EXISTS happened).
time.Sleep(150 * time.Millisecond)
if got := fetches.Load(); got != 0 {
t.Fatalf("expected 0 FETCH commands on connect, got %d", got)
}
}
func TestSinceUIDRefusesFetchWhenServerOmitsUIDNext(t *testing.T) {
// Some non-conformant servers don't return UIDNEXT. We must NOT
// attempt UID FETCH 1:* in that case — that would drag the entire
// inbox down. Test verifies fetchNewMessages bails out cleanly.
prev := IdleRoundDuration
IdleRoundDuration = 30 * time.Second
defer func() { IdleRoundDuration = prev }()
srv := newFakeServer()
var fetches atomic.Int32
srv.script = func(fc *fakeConn) {
handleIdleBringUpWithUIDNext(fc, 0) // 0 = don't emit UIDNEXT
// First round emits EXISTS → session WOULD normally FETCH.
handleIdleRound(fc, []string{"* 1 EXISTS\r\n"})
// Count any FETCH attempt (should not happen).
for {
tag, rest, err := fc.readCommand()
if err != nil {
return
}
up := strings.ToUpper(rest)
switch {
case strings.HasPrefix(up, "UID FETCH") || strings.HasPrefix(up, "FETCH"):
fetches.Add(1)
_ = fc.write(tag + " OK FETCH completed\r\n")
case up == "IDLE":
if fc.srv != nil {
fc.srv.idleStarts.Add(1)
}
_ = fc.write("+ idling\r\n")
_ = fc.conn.SetReadDeadline(time.Now().Add(1 * time.Second))
line, err := fc.r.ReadString('\n')
_ = fc.conn.SetReadDeadline(time.Time{})
if err != nil {
return
}
if !strings.EqualFold(strings.TrimSpace(line), "DONE") {
return
}
_ = fc.write(tag + " OK IDLE completed\r\n")
case up == "LOGOUT":
_ = fc.write(tag + " OK bye\r\n")
return
}
}
}
m := NewManager(time.Hour).withDial(srv.dialer())
defer m.Shutdown()
sub, err := m.Subscribe(sampleCred("inbox@example.com"), Filter{})
if err != nil {
t.Fatal(err)
}
defer sub.Close()
s := sessionFor(t, m, sampleCred("inbox@example.com"))
if s.sinceUIDInitialized.Load() {
t.Fatal("sinceUIDInitialized should be false when server omits UIDNEXT")
}
// Wait for EXISTS to land and the loop to evaluate handlePendingFetch.
time.Sleep(200 * time.Millisecond)
if got := fetches.Load(); got != 0 {
t.Fatalf("expected 0 FETCH attempts when UIDNEXT missing, got %d", got)
}
}
func TestFetchUpdatesSinceUID(t *testing.T) {
prev := IdleRoundDuration
IdleRoundDuration = 30 * time.Second
defer func() { IdleRoundDuration = prev }()
srv := newFakeServer()
srv.script = func(fc *fakeConn) {
handleIdleBringUpWithUIDNext(fc, 100)
handleIdleRound(fc, []string{"* 5 EXISTS\r\n"})
handleFetchCommand(fc, []fakeMail{
{UID: 100, To: "a@x", From: "b@y", Subject: "s", Body: "b"},
{UID: 102, To: "a@x", From: "b@y", Subject: "s", Body: "b"},
{UID: 101, To: "a@x", From: "b@y", Subject: "s", Body: "b"}, // out-of-order
})
for {
if !handleIdleRound(fc, nil) {
return
}
}
}
m := NewManager(time.Hour).withDial(srv.dialer())
defer m.Shutdown()
sub, err := m.Subscribe(sampleCred("inbox@example.com"), Filter{})
if err != nil {
t.Fatal(err)
}
defer sub.Close()
// Drain three messages, then check watermark.
for i := 0; i < 3; i++ {
select {
case <-sub.Ch:
case <-time.After(2 * time.Second):
t.Fatalf("missed message %d", i)
}
}
s := sessionFor(t, m, sampleCred("inbox@example.com"))
if got := s.sinceUID.Load(); got != 102 {
t.Fatalf("sinceUID = %d, want 102 (max of fetched UIDs)", got)
}
}
// readFetchLine round-trip — feed it a hand-built FETCH wire response and
// verify the placeholder substitution + literal capture.
func TestReadFetchLineCapturesMultipleLiterals(t *testing.T) {
srv := newFakeServer()
srv.script = func(fc *fakeConn) {
handleIdleBringUpWithUIDNext(fc, 1)
handleFetchCommand(fc, []fakeMail{{
UID: 1,
To: "a@x",
From: "b@y",
Subject: "s",
Body: "Body with ) parens and \"quotes\" and {fake} markers",
}})
for {
if _, _, err := fc.readCommand(); err != nil {
return
}
}
}
c, err := srv.dialer()("h", 993, true)
if err != nil {
t.Fatal(err)
}
defer c.Close()
if err := c.login("a", "p"); err != nil {
t.Fatal(err)
}
if err := c.capability(); err != nil {
t.Fatal(err)
}
if err := c.selectFolder("INBOX"); err != nil {
t.Fatal(err)
}
resps, err := c.execFetch("UID FETCH 1:* (UID INTERNALDATE BODY.PEEK[HEADER.FIELDS (TO FROM SUBJECT DATE)] BODY.PEEK[TEXT])")
if err != nil {
t.Fatal(err)
}
if len(resps) != 1 {
t.Fatalf("expected 1 response, got %d", len(resps))
}
r := resps[0]
if r.uid != 1 {
t.Errorf("uid = %d", r.uid)
}
if !strings.Contains(string(r.body), "{fake}") {
t.Errorf("body literal not preserved verbatim: %q", r.body)
}
if !strings.Contains(string(r.body), ") parens") {
t.Errorf("paren in body not preserved: %q", r.body)
}
}