]> Sergey Matveev's repositories - public-inbox.git/blob - t/imapd.t
test_common: require_mods bundles
[public-inbox.git] / t / imapd.t
1 #!perl -w
2 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
3 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # end-to-end IMAP tests, see unit tests in t/imap.t, too
5 use strict;
6 use Test::More;
7 use Time::HiRes ();
8 use PublicInbox::TestCommon;
9 use PublicInbox::Config;
10 use PublicInbox::Spawn qw(which);
11 require_mods(qw(-imapd Mail::IMAPClient));
12 my $imap_client = 'Mail::IMAPClient';
13 my $can_compress = $imap_client->can('compress');
14 if ($can_compress) { # hope this gets fixed upstream, soon
15         require PublicInbox::IMAPClient;
16         $imap_client = 'PublicInbox::IMAPClient';
17 }
18
19 require_ok 'PublicInbox::IMAP';
20 my $first_range = '0';
21
22 my $level = 'basic';
23 SKIP: {
24         require_mods('Search::Xapian', 1);
25         $level = 'medium';
26 };
27
28 my @V = (1);
29 push(@V, 2) if require_git('2.6', 1);
30
31 my ($tmpdir, $for_destroy) = tmpdir();
32 my $home = "$tmpdir/home";
33 BAIL_OUT "mkdir: $!" unless (mkdir($home) and mkdir("$home/.public-inbox"));
34 my @ibx;
35 open my $cfgfh, '>', "$home/.public-inbox/config" or BAIL_OUT;
36 print $cfgfh <<EOM or BAIL_OUT;
37 [publicinboxmda]
38         spamcheck = none
39 EOM
40 my $eml;
41 for my $V (@V) {
42         my $ibx = create_inbox("i$V", tmpdir => "$tmpdir/i$V", version => $V,
43                                 indexlevel => $level, sub {
44                 my ($im) = @_;
45                 $im->add($eml //= eml_load('t/utf8.eml')) or BAIL_OUT;
46         });
47         push @ibx, $ibx;
48         $ibx->{newsgroup} = "inbox.i$V";
49         print $cfgfh <<EOF or BAIL_OUT;
50 [publicinbox "i$V"]
51         inboxdir = $ibx->{inboxdir}
52         address = $ibx->{-primary_address};
53         newsgroup = inbox.i$V
54         url = http://example.com/i$V
55 EOF
56 }
57 close $cfgfh or BAIL_OUT;
58 local $ENV{HOME} = $home;
59 my $sock = tcp_server();
60 my $err = "$tmpdir/stderr.log";
61 my $out = "$tmpdir/stdout.log";
62 my $cmd = [ '-imapd', '-W0', "--stdout=$out", "--stderr=$err" ];
63 my $td = start_script($cmd, undef, { 3 => $sock }) or BAIL_OUT("-imapd: $?");
64 my ($ihost, $iport) = tcp_host_port($sock);
65 my %mic_opt = ( Server => $ihost, Port => $iport, Uid => 1 );
66 my $mic = $imap_client->new(%mic_opt);
67 my $pre_login_capa = $mic->capability;
68 is(grep(/\AAUTH=ANONYMOUS\z/, @$pre_login_capa), 1,
69         'AUTH=ANONYMOUS advertised pre-login');
70
71 $mic->User('lorelei');
72 $mic->Password('Hunter2');
73 ok($mic->login && $mic->IsAuthenticated, 'LOGIN works');
74 my $post_login_capa = $mic->capability;
75 ok(join("\n", @$pre_login_capa) ne join("\n", @$post_login_capa),
76         'got different capabilities post-login');
77
78 $mic_opt{Authmechanism} = 'ANONYMOUS';
79 $mic_opt{Authcallback} = sub { '' };
80 $mic = $imap_client->new(%mic_opt);
81 ok($mic && $mic->login && $mic->IsAuthenticated, 'AUTHENTICATE ANONYMOUS');
82 my $post_auth_anon_capa = $mic->capability;
83 is_deeply($post_auth_anon_capa, $post_login_capa,
84         'auth anon has same capabilities');
85 my $e;
86 ok($mic->noop, 'NOOP');
87 ok($mic->noop, 'NOOP (again)'); # for warnings
88 ok(!$mic->examine('foo') && ($e = $@), 'EXAMINE non-existent');
89 like($e, qr/\bNO\b/, 'got a NO on EXAMINE for non-existent');
90 ok(!$mic->select('foo') && ($e = $@), 'EXAMINE non-existent');
91 like($e, qr/\bNO\b/, 'got a NO on EXAMINE for non-existent');
92 my $mailbox1 = "inbox.i1.$first_range";
93 ok($mic->select('inbox.i1'), 'SELECT on parent succeeds');
94 ok($mic->noop, 'NOOP while selected');
95 ok($mic->noop, 'NOOP again while selected'); # check warnings later
96 ok($mic->select($mailbox1), 'SELECT succeeds');
97 ok($mic->examine($mailbox1), 'EXAMINE succeeds');
98 my @raw = $mic->status($mailbox1, qw(Messages uidnext uidvalidity));
99 is(scalar(@raw), 2, 'got status response');
100 like($raw[0], qr/\A\*\x20STATUS\x20inbox\.i1\.$first_range\x20
101         \(MESSAGES\x20\d+\x20UIDNEXT\x20\d+\x20UIDVALIDITY\x20\d+\)\r\n/sx);
102 like($raw[1], qr/\A\S+ OK /, 'finished status response');
103
104 my @orig_list = @raw = $mic->list;
105 like($raw[0], qr/^\* LIST \(.*?\) "\." INBOX/,
106         'got an inbox');
107 like($raw[-1], qr/^\S+ OK /, 'response ended with OK');
108 is(scalar(@raw), scalar(@V) * 2 + 2, 'default LIST response');
109 @raw = $mic->list('', 'inbox.i1');
110 is(scalar(@raw), 2, 'limited LIST response');
111 like($raw[0], qr/^\* LIST \(.*?\) "\." INBOX/,
112                 'got an inbox.i1');
113 like($raw[-1], qr/^\S+ OK /, 'response ended with OK');
114
115 my $ret = $mic->search('all') or BAIL_OUT "SEARCH FAIL $@";
116 is_deeply($ret, [ 1 ], 'search all works');
117 $ret = $mic->search('uid 1') or BAIL_OUT "SEARCH FAIL $@";
118 is_deeply($ret, [ 1 ], 'search UID 1 works');
119 $ret = $mic->search('uid 1:1') or BAIL_OUT "SEARCH FAIL $@";
120 is_deeply($ret, [ 1 ], 'search UID 1:1 works');
121 $ret = $mic->search('uid 1:*') or BAIL_OUT "SEARCH FAIL $@";
122 is_deeply($ret, [ 1 ], 'search UID 1:* works');
123 $ret = $mic->search('DELETED') or BAIL_OUT "SEARCH FAIL $@";
124 is_deeply($ret, [], 'searching for DELETED returns nothing');
125
126 SKIP: {
127         skip 'Xapian missing', 8 if $level eq 'basic';
128         my $x = $mic->search(qw(smaller 99999));
129         is_deeply($x, [1], 'SMALLER works with Xapian (hit)');
130         $x = $mic->search(qw(smaller 9));
131         is_deeply($x, [], 'SMALLER works with Xapian (miss)');
132
133         $x = $mic->search(qw(larger 99999));
134         is_deeply($x, [], 'LARGER works with Xapian (miss)');
135         $x = $mic->search(qw(larger 9));
136         is_deeply($x, [1], 'LARGER works with Xapian (hit)');
137
138         $x = $mic->search(qw(HEADER Message-ID testmessage@example.com));
139         is_deeply($x, [1], 'HEADER Message-ID works');
140
141         $x = $mic->search(qw(DRAFT HEADER Message-ID testmessage@example.com));
142         is_deeply($x, [], 'impossible (DRAFT) key filters out match');
143
144         $x = $mic->search(qw(HEADER Message-ID miss));
145         is_deeply($x, [], 'HEADER Message-ID can miss');
146
147         my @q = qw[OR HEADER Message-ID testmessage@example.com
148                         (OR FROM Ryan (OR TO Joe CC Scott))];
149         $x = $mic->search(join(' ', @q));
150         is_deeply($x, [1], 'nested query works');
151 }
152
153 is_deeply(scalar $mic->flags('1'), [], '->flags works');
154 {
155         # RFC 3501 section 6.4.8 states:
156         # Also note that a UID range of 559:* always includes the
157         # UID of the last message in the mailbox, even if 559 is
158         # higher than any assigned UID value.
159         my $exp = $mic->fetch_hash(1, 'UID');
160         $ret = $mic->fetch_hash('559:*', 'UID');
161         is_deeply($ret, $exp, 'beginning range too big');
162         {
163                 my @w; # Mail::IMAPClient hits a warning via overload
164                 local $SIG{__WARN__} = sub { push @w, @_ };
165                 $ret = $mic->fetch_hash(my $r = '559:558', 'UID');
166                 is_deeply($ret, {}, "out-of-range UID FETCH $r");
167                 @w = grep(!/\boverload\.pm\b/, @w);
168                 is_deeply(\@w, [], 'no unexpected warning');
169         }
170         $ret = $mic->fetch_hash(my $r = '558:559', 'UID');
171         is_deeply($ret, {}, "out-of-range UID FETCH $r");
172 }
173
174 for my $r ('1:*', '1') {
175         $ret = $mic->fetch_hash($r, 'RFC822') or BAIL_OUT "FETCH $@";
176         is_deeply([keys %$ret], [1]);
177         like($ret->{1}->{RFC822}, qr/\r\n\r\nThis is a test/, 'read full');
178
179         # ensure Mail::IMAPClient behaves
180         my $str = $mic->message_string($r) or BAIL_OUT "->message_string: $@";
181         is($str, $ret->{1}->{RFC822}, '->message_string works as expected');
182
183         my $sz = $mic->fetch_hash($r, 'RFC822.size') or BAIL_OUT "FETCH $@";
184         is($sz->{1}->{'RFC822.SIZE'}, length($ret->{1}->{RFC822}),
185                 'RFC822.SIZE');
186
187         $ret = $mic->fetch_hash($r, 'RFC822.HEADER') or BAIL_OUT "FETCH $@";
188         is_deeply([keys %$ret], [1]);
189         like($ret->{1}->{'RFC822.HEADER'},
190                 qr/^Message-ID: <testmessage\@example\.com>/ms, 'read header');
191
192         $ret = $mic->fetch_hash($r, 'INTERNALDATE') or BAIL_OUT "FETCH $@";
193         is($ret->{1}->{'INTERNALDATE'}, '01-Jan-1970 00:00:00 +0000',
194                 'internaldate matches');
195         ok(!$mic->fetch_hash($r, 'INFERNALDATE'), 'bogus attribute fails');
196
197         my $envelope = $mic->get_envelope($r) or BAIL_OUT("get_envelope: $@");
198         is($envelope->{bcc}, 'NIL', 'empty bcc');
199         is($envelope->{messageid}, '<testmessage@example.com>', 'messageid');
200         is(scalar @{$envelope->{to}}, 1, 'one {to} header');
201         # *sigh* too much to verify...
202         #use Data::Dumper; diag Dumper($envelope);
203
204         $ret = $mic->fetch_hash($r, 'FLAGS') or BAIL_OUT "FETCH $@";
205         is_deeply($ret->{1}->{FLAGS}, '', 'no flags');
206
207         $ret = $mic->fetch_hash($r, 'BODY[1]') or BAIL_OUT "FETCH $@";
208         like($ret->{1}->{'BODY[1]'}, qr/\AThis is a test message/, 'BODY[1]');
209
210         $ret = $mic->fetch_hash($r, 'BODY[1]<1>') or BAIL_OUT "FETCH $@";
211         like($ret->{1}->{'BODY[1]<1>'}, qr/\Ahis is a test message/,
212                         'BODY[1]<1>');
213
214         $ret = $mic->fetch_hash($r, 'BODY[1]<2.3>') or BAIL_OUT "FETCH $@";
215         is($ret->{1}->{'BODY[1]<2>'}, "is ", 'BODY[1]<2.3>');
216         $ret = $mic->bodypart_string($r, 1, 3, 2) or
217                                         BAIL_OUT "bodypart_string $@";
218         is($ret, "is ", 'bodypart string');
219
220         $ret = $mic->fetch_hash($r, 'BODY[HEADER.FIELDS.NOT (Message-ID)]')
221                 or BAIL_OUT "FETCH $@";
222         $ret = $ret->{1}->{'BODY[HEADER.FIELDS.NOT (MESSAGE-ID)]'};
223         unlike($ret, qr/message-id/i, 'Message-ID excluded');
224         like($ret, qr/\r\n\r\n\z/s, 'got header end');
225
226         $ret = $mic->fetch_hash($r, 'BODY[HEADER.FIELDS (Message-ID)]')
227                 or BAIL_OUT "FETCH $@";
228         is($ret->{1}->{'BODY[HEADER.FIELDS (MESSAGE-ID)]'},
229                 'Message-ID: <testmessage@example.com>'."\r\n\r\n",
230                 'got only Message-ID');
231
232         my $bs = $mic->get_bodystructure($r) or BAIL_OUT("bodystructure: $@");
233         ok($bs, 'got a bodystructure');
234         is(lc($bs->bodytype), 'text', '->bodytype');
235         is(lc($bs->bodyenc), '8bit', '->bodyenc');
236 }
237 ok($mic->has_capability('COMPRESS') ||
238         $mic->has_capability('COMPRESS=DEFLATE'), 'deflate cap');
239 SKIP: {
240         skip 'Mail::IMAPClient too old for ->compress', 2 if !$can_compress;
241         my $c = $imap_client->new(%mic_opt);
242         ok($c && $c->compress, 'compress enabled');
243         ok($c->examine($mailbox1), 'EXAMINE succeeds after COMPRESS');
244         $ret = $c->search('uid 1:*') or BAIL_OUT "SEARCH FAIL $@";
245         is_deeply($ret, [ 1 ], 'search UID 1:* works after compression');
246 }
247
248 ok($mic->logout, 'logout works');
249
250 my $have_inotify = eval { require Linux::Inotify2; 1 };
251
252 for my $ibx (@ibx) {
253         my $name = $ibx->{name};
254         my $ng = $ibx->{newsgroup};
255         my $mic = $imap_client->new(%mic_opt);
256         ok($mic && $mic->login && $mic->IsAuthenticated, "authed $name");
257         my $mb = "$ng.$first_range";
258         my $uidnext = $mic->uidnext($mb); # we'll fetch BODYSTRUCTURE on this
259         ok($uidnext, 'got uidnext for later fetch');
260         ok($mic->has_capability('IDLE'), "IDLE capa $name");
261         ok(!$mic->idle, "IDLE fails w/o SELECT/EXAMINE $name");
262         ok($mic->examine($mb), "EXAMINE $ng succeeds");
263         ok(my $idle_tag = $mic->idle, "IDLE succeeds on $ng");
264         my $im = $ibx->importer(0);
265         $im->add(eml_load 't/data/message_embed.eml') or BAIL_OUT;
266         $im->done;
267         my $t0 = Time::HiRes::time();
268         ok(my @res = $mic->idle_data(11), "IDLE succeeds on $ng");
269         is(grep(/\A\* [0-9] EXISTS\b/, @res), 1, 'got EXISTS message');
270         ok((Time::HiRes::time() - $t0) < 10, 'IDLE client notified');
271
272         my (@ino_info, $ino_fdinfo);
273         SKIP: {
274                 skip 'no inotify support', 1 unless $have_inotify;
275                 skip 'missing /proc/$PID/fd', 1 if !-d "/proc/$td->{pid}/fd";
276                 my @ino = grep {
277                         readlink($_) =~ /\binotify\b/
278                 } glob("/proc/$td->{pid}/fd/*");
279                 is(scalar(@ino), 1, 'only one inotify FD');
280                 my $ino_fd = (split('/', $ino[0]))[-1];
281                 $ino_fdinfo = "/proc/$td->{pid}/fdinfo/$ino_fd";
282                 if (open my $fh, '<', $ino_fdinfo) {
283                         local $/ = "\n";
284                         @ino_info = grep(/^inotify wd:/, <$fh>);
285                         ok(scalar(@ino_info), 'inotify has watches');
286                 } else {
287                         skip "$ino_fdinfo missing: $!", 1;
288                 }
289         };
290
291         # ensure IDLE persists across HUP, w/o extra watches or FDs
292         $td->kill('HUP') or BAIL_OUT "failed to kill -imapd: $!";
293         for my $n (1..2) { # kick the event loop so we know HUP is done
294                 my $m = $imap_client->new(%mic_opt);
295                 ok($m->login && $m->IsAuthenticated && $m->logout,
296                         "connection $n works after HUP");
297         }
298
299         $im->add(eml_load 't/data/0001.patch') or BAIL_OUT;
300         $im->done;
301         $t0 = Time::HiRes::time();
302         ok(@res = $mic->idle_data(11), "IDLE succeeds on $ng after HUP");
303         is(grep(/\A\* [0-9] EXISTS\b/, @res), 1, 'got EXISTS message');
304         ok((Time::HiRes::time() - $t0) < 10, 'IDLE client notified');
305         ok($mic->done($idle_tag), 'IDLE DONE');
306         my $bs = $mic->get_bodystructure($uidnext);
307         ok($bs, 'BODYSTRUCTURE ok for deeply nested');
308         $ret = $mic->fetch_hash($uidnext, 'BODY') or BAIL_OUT "FETCH $@";
309         ok($ret->{$uidnext}->{BODY}, 'got something in BODY');
310
311         # this matches dovecot behavior
312         $ret = $mic->fetch_hash($uidnext, 'BODY[1]') or BAIL_OUT "FETCH $@";
313         is($ret->{$uidnext}->{'BODY[1]'},
314                 "testing embedded message harder\r\n", 'BODY[1]');
315         $ret = $mic->fetch_hash($uidnext, 'BODY[2]') or BAIL_OUT "FETCH $@";
316         like($ret->{$uidnext}->{'BODY[2]'},
317                 qr/\ADate: Sat, 18 Apr 2020 22:20:20 /, 'BODY[2]');
318
319         $ret = $mic->fetch_hash($uidnext, 'BODY[2.1.1]') or BAIL_OUT "FETCH $@";
320         is($ret->{$uidnext}->{'BODY[2.1.1]'},
321                 "testing embedded message\r\n", 'BODY[2.1.1]');
322
323         $ret = $mic->fetch_hash($uidnext, 'BODY[2.1.2]') or BAIL_OUT "FETCH $@";
324         like($ret->{$uidnext}->{'BODY[2.1.2]'}, qr/\AFrom: /,
325                 'BODY[2.1.2] tip matched');
326         like($ret->{$uidnext}->{'BODY[2.1.2]'},
327                  # trailing CRLF may vary depending on MIME parser
328                  qr/done_testing;(?:\r\n){1,2}\z/,
329                 'BODY[2.1.2] tail matched');
330
331         $ret = $mic->fetch_hash("1:$uidnext", 'BODY[2.HEADER]') or
332                                                 BAIL_OUT "2.HEADER $@";
333         like($ret->{$uidnext}->{'BODY[2.HEADER]'},
334                 qr/\ADate: Sat, 18 Apr 2020 22:20:20 /,
335                 '2.HEADER of message/rfc822');
336
337         $ret = $mic->fetch_hash($uidnext, 'BODY[2.MIME]') or
338                 BAIL_OUT "2.MIME $@";
339         is($ret->{$uidnext}->{'BODY[2.MIME]'}, <<EOF, 'BODY[2.MIME]');
340 Content-Type: message/rfc822\r
341 Content-Disposition: attachment; filename="embed2x\.eml"\r
342 \r
343 EOF
344
345         my @hits = $mic->search('SENTON' => '18-Apr-2020');
346         is_deeply(\@hits, [ $uidnext ], 'search with date condition works');
347         ok($mic->examine($ng), 'EXAMINE on dummy');
348         @hits = $mic->search('SENTSINCE' => '18-Apr-2020');
349         is_deeply(\@hits, [], 'search on dummy with condition works');
350         ok(!$mic->search('SENTSINCE' => '18-Abr-2020'), 'bad month fails');
351         $mic->Uid(0);
352         my $ret = $mic->fetch_hash(2, 'RFC822');
353         is_deeply($ret, {},
354                 'MSN FETCH on empty dummy will not trigger warnings, later');
355 }; # for @ibx
356
357 # message sequence numbers :<
358 is($mic->Uid(0), 0, 'disable UID on '.ref($mic));
359 ok($mic->reconnect, 'reconnected');
360 $ret = $mic->fetch_hash('1,2:3', 'RFC822') or BAIL_OUT "FETCH $@";
361 is(scalar keys %$ret, 3, 'got all 3 messages with comma-separated sequence');
362 $ret = $mic->fetch_hash('1:*', 'RFC822') or BAIL_OUT "FETCH $@";
363 is(scalar keys %$ret, 3, 'got all 3 messages');
364
365 SKIP: {
366         # do any clients use non-UID IMAP SEARCH?
367         skip 'Xapian missing', 3 if $level eq 'basic';
368         my $x = $mic->search('all');
369         is_deeply($x, [1, 2, 3], 'MSN SEARCH works before rm');
370         $x = $mic->search(qw(header subject embedded));
371         is_deeply($x, [2], 'MSN SEARCH on Subject works before rm');
372         $x = $mic->search('FROM scraper@example.com');
373         is_deeply($x, [], "MSN SEARCH miss won't trigger warnings");
374 }
375
376 {
377         my $rdr = { 0 => \($ret->{1}->{RFC822}) };
378         my $env = { HOME => $ENV{HOME} };
379         my @cmd = qw(-learn rm --all);
380         run_script(\@cmd, $env, $rdr) or BAIL_OUT('-learn rm');
381 }
382
383 SKIP: {
384         # do any clients use non-UID IMAP SEARCH?  We only ensure
385         # MSN "SEARCH" can return a result which can be retrieved
386         # via MSN "FETCH"
387         skip 'Xapian missing', 3 if $level eq 'basic';
388         my $x = $mic->search(qw(header subject embedded));
389         is(scalar(@$x), 1, 'MSN SEARCH on Subject works after rm');
390         SKIP: {
391                 skip 'previous test failed', 1 if !scalar(@$x);
392                 $x = $mic->message_string($x->[0]);
393                 is($x, $ret->{2}->{RFC822}, 'message 2 unchanged');
394         }
395         $x = $mic->search(qw(text embedded));
396         is(scalar(@$x), 1, 'MSN SEARCH on TEXT works after rm');
397 }
398
399 # FIXME? no EXPUNGE response, yet
400 my $r2 = $mic->fetch_hash('1:*', 'BODY.PEEK[]') or BAIL_OUT "FETCH $@";
401 is(scalar keys %$r2, 2, 'did not get all 3 messages');
402 is($r2->{2}->{'BODY[]'}, $ret->{2}->{RFC822}, 'message 2 unchanged');
403 is($r2->{3}->{'BODY[]'}, $ret->{3}->{RFC822}, 'message 3 unchanged');
404 $r2 = $mic->fetch_hash(2, 'BODY.PEEK[HEADER.FIELDS (message-id)]')
405                         or BAIL_OUT "FETCH $@";
406 is($r2->{2}->{'BODY[HEADER.FIELDS (MESSAGE-ID)]'},
407         'Message-ID: <20200418222508.GA13918@dcvr>'."\r\n\r\n",
408         'BODY.PEEK[HEADER.FIELDS ...] drops .PEEK');
409
410 {
411         my @new_list = $mic->list;
412         # tag differs in [-1]
413         like($orig_list[-1], qr/\A\S+ OK List done\r\n/, 'orig LIST');
414         like($new_list[-1], qr/\A\S+ OK List done\r\n/, 'new LIST');
415         pop @new_list;
416         pop @orig_list;
417         # TODO: not sure if sort order matters, imapd_refresh_finalize
418         # doesn't sort, hopefully clients don't care...
419         @new_list = sort @new_list;
420         @orig_list = sort @orig_list;
421         is_deeply(\@new_list, \@orig_list, 'LIST identical');
422 }
423 ok($mic->close, 'CLOSE works');
424 ok(!$mic->close, 'CLOSE not idempotent');
425 ok($mic->logout, 'logged out');
426
427 {
428         my $c = tcp_connect($sock);
429         $c->autoflush(1);
430         like(<$c>, qr/\* OK/, 'got a greeting');
431         print $c "\r\n";
432         like(<$c>, qr/\A\* BAD Error in IMAP command/, 'empty line');
433         print $c "tagonly\r\n";
434         like(<$c>, qr/\Atagonly BAD Error in IMAP command/, 'tag-only line');
435 }
436
437 SKIP: {
438         use_ok 'PublicInbox::InboxIdle';
439         require_git('1.8.5', 1) or
440                 skip('git 1.8.5+ needed for --urlmatch', 4);
441         my $old_env = { HOME => $ENV{HOME} };
442         my $home = "$tmpdir/watch_home";
443         mkdir $home or BAIL_OUT $!;
444         mkdir "$home/.public-inbox" or BAIL_OUT $!;
445         local $ENV{HOME} = $home;
446         my $name = 'watchimap';
447         my $addr = "i1\@example.com";
448         my $url = "http://example.com/i1";
449         my $inboxdir = "$tmpdir/watchimap";
450         my $cmd = ['-init', '-V2', '-Lbasic', $name, $inboxdir, $url, $addr];
451         my $imapurl = "imap://$ihost:$iport/inbox.i1.0";
452         run_script($cmd) or BAIL_OUT("init $name");
453         xsys(qw(git config), "--file=$home/.public-inbox/config",
454                         "publicinbox.$name.watch",
455                         $imapurl) == 0 or BAIL_OUT "git config $?";
456         my $cfg = PublicInbox::Config->new;
457         PublicInbox::DS->Reset;
458         my $ii = PublicInbox::InboxIdle->new($cfg);
459         my $cb = sub { PublicInbox::DS->SetPostLoopCallback(sub {}) };
460         my $obj = bless \$cb, 'PublicInbox::TestCommon::InboxWakeup';
461         $cfg->each_inbox(sub { $_[0]->subscribe_unlock('ident', $obj) });
462         my $watcherr = "$tmpdir/watcherr";
463         open my $err_wr, '>>', $watcherr or BAIL_OUT $!;
464         open my $err, '<', $watcherr or BAIL_OUT $!;
465         my $w = start_script(['-watch'], undef, { 2 => $err_wr });
466
467         diag 'waiting for initial fetch...';
468         PublicInbox::DS->EventLoop;
469         diag 'inbox unlocked on initial fetch, waiting for IDLE';
470
471         tick until (grep(/I: \S+ idling/, <$err>));
472         open my $fh, '<', 't/iso-2202-jp.eml' or BAIL_OUT $!;
473         $old_env->{ORIGINAL_RECIPIENT} = $addr;
474         ok(run_script([qw(-mda --no-precheck)], $old_env, { 0 => $fh }),
475                 'delivered a message for IDLE to kick -watch');
476         diag 'waiting for IMAP IDLE wakeup';
477         PublicInbox::DS->SetPostLoopCallback(undef);
478         PublicInbox::DS->EventLoop;
479         diag 'inbox unlocked on IDLE wakeup';
480
481         # try again with polling
482         xsys(qw(git config), "--file=$home/.public-inbox/config",
483                 'imap.PollInterval', 0.11) == 0
484                 or BAIL_OUT "git config $?";
485         $w->kill('HUP');
486         diag 'waiting for -watch reload + initial fetch';
487         tick until (grep(/I: will check/, <$err>));
488
489         open $fh, '<', 't/psgi_attach.eml' or BAIL_OUT $!;
490         ok(run_script([qw(-mda --no-precheck)], $old_env, { 0 => $fh }),
491                 'delivered a message for -watch PollInterval');
492
493         diag 'waiting for PollInterval wakeup';
494         PublicInbox::DS->SetPostLoopCallback(undef);
495         PublicInbox::DS->EventLoop;
496         diag 'inbox unlocked (poll)';
497         $w->kill;
498         $w->join;
499         is($?, 0, 'no error in exited -watch process');
500
501         $cfg->each_inbox(sub { shift->unsubscribe_unlock('ident') });
502         $ii->close;
503         PublicInbox::DS->Reset;
504         seek($err, 0, 0);
505         my @err = grep(!/^(?:I:|#)/, <$err>);
506         is(@err, 0, 'no warnings/errors from -watch'.join(' ', @err));
507
508         if ($ENV{TEST_KILL_IMAPD}) { # not sure how reliable this test can be
509                 xsys(qw(git config), "--file=$home/.public-inbox/config",
510                         qw(--unset imap.PollInterval)) == 0
511                         or BAIL_OUT "git config $?";
512                 truncate($err_wr, 0) or BAIL_OUT $!;
513                 my @t0 = times;
514                 $w = start_script(['-watch'], undef, { 2 => $err_wr });
515                 seek($err, 0, 0);
516                 tick until (grep(/I: \S+ idling/, <$err>));
517                 diag 'killing imapd, waiting for CPU spins';
518                 my $delay = 0.11;
519                 $td->kill(9);
520                 tick $delay;
521                 $w->kill;
522                 $w->join;
523                 is($?, 0, 'no error in exited -watch process');
524                 my @t1 = times;
525                 my $c = $t1[2] + $t1[3] - $t0[2] - $t0[3];
526                 my $thresh = (0.9 * $delay);
527                 diag "c=$c, threshold=$thresh";
528                 ok($c < $thresh, 'did not burn much CPU');
529                 is_deeply([grep(/ line \d+$/m, <$err>)], [],
530                                 'no backtraces from errors');
531         }
532 }
533
534 $td->kill;
535 $td->join;
536 is($?, 0, 'no error in exited process') if !$ENV{TEST_KILL_IMAPD};
537 open my $fh, '<', $err or BAIL_OUT("open $err failed: $!");
538 my $eout = do { local $/; <$fh> };
539 unlike($eout, qr/wide/i, 'no Wide character warnings');
540 unlike($eout, qr/uninitialized/i, 'no uninitialized warnings');
541
542 done_testing;