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