]> Sergey Matveev's repositories - public-inbox.git/blob - t/lei.t
lei q: demangle and quiet curl output
[public-inbox.git] / t / lei.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 use strict;
5 use v5.10.1;
6 use Test::More;
7 use PublicInbox::TestCommon;
8 use PublicInbox::Config;
9 use File::Path qw(rmtree);
10 use Fcntl qw(SEEK_SET);
11 use PublicInbox::Spawn qw(which);
12 require_git 2.6;
13 require_mods(qw(json DBD::SQLite Search::Xapian));
14 my $opt = { 1 => \(my $out = ''), 2 => \(my $err = '') };
15 my ($home, $for_destroy) = tmpdir();
16 my $err_filter;
17 my @onions = qw(http://hjrcffqmbrq6wope.onion/meta/
18         http://czquwvybam4bgbro.onion/meta/
19         http://ou63pmih66umazou.onion/meta/);
20 my $json = ref(PublicInbox::Config->json)->new->utf8->canonical;
21 my $lei = sub {
22         my ($cmd, $env, $xopt) = @_;
23         $out = $err = '';
24         if (!ref($cmd)) {
25                 ($env, $xopt) = grep { (!defined) || ref } @_;
26                 $cmd = [ grep { defined && !ref } @_ ];
27         }
28         my $res = run_script(['lei', @$cmd], $env, $xopt // $opt);
29         $err_filter and
30                 $err = join('', grep(!/$err_filter/, split(/^/m, $err)));
31         $res;
32 };
33
34 delete local $ENV{XDG_DATA_HOME};
35 delete local $ENV{XDG_CONFIG_HOME};
36 local $ENV{GIT_COMMITTER_EMAIL} = 'lei@example.com';
37 local $ENV{GIT_COMMITTER_NAME} = 'lei user';
38 local $ENV{XDG_RUNTIME_DIR} = "$home/xdg_run";
39 local $ENV{HOME} = $home;
40 local $ENV{FOO} = 'BAR';
41 mkdir "$home/xdg_run", 0700 or BAIL_OUT "mkdir: $!";
42 my $home_trash = [ "$home/.local", "$home/.config" ];
43 my $cleanup = sub { rmtree([@$home_trash, @_]) };
44 my $config_file = "$home/.config/lei/config";
45 my $store_dir = "$home/.local/share/lei";
46
47 my $test_help = sub {
48         ok(!$lei->(), 'no args fails');
49         is($? >> 8, 1, '$? is 1');
50         is($out, '', 'nothing in stdout');
51         like($err, qr/^usage:/sm, 'usage in stderr');
52
53         for my $arg (['-h'], ['--help'], ['help'], [qw(daemon-pid --help)]) {
54                 ok($lei->($arg), "lei @$arg");
55                 like($out, qr/^usage:/sm, "usage in stdout (@$arg)");
56                 is($err, '', "nothing in stderr (@$arg)");
57         }
58
59         for my $arg ([''], ['--halp'], ['halp'], [qw(daemon-pid --halp)]) {
60                 ok(!$lei->($arg), "lei @$arg");
61                 is($? >> 8, 1, '$? set correctly');
62                 isnt($err, '', 'something in stderr');
63                 is($out, '', 'nothing in stdout');
64         }
65         ok($lei->(qw(init -h)), 'init -h');
66         like($out, qr! \Q$home\E/\.local/share/lei/store\b!,
67                 'actual path shown in init -h');
68         ok($lei->(qw(init -h), { XDG_DATA_HOME => '/XDH' }),
69                 'init with XDG_DATA_HOME');
70         like($out, qr! /XDH/lei/store\b!, 'XDG_DATA_HOME in init -h');
71         is($err, '', 'no errors from init -h');
72
73         ok($lei->(qw(config -h)), 'config-h');
74         like($out, qr! \Q$home\E/\.config/lei/config\b!,
75                 'actual path shown in config -h');
76         ok($lei->(qw(config -h), { XDG_CONFIG_HOME => '/XDC' }),
77                 'config with XDG_CONFIG_HOME');
78         like($out, qr! /XDC/lei/config\b!, 'XDG_CONFIG_HOME in config -h');
79         is($err, '', 'no errors from config -h');
80 };
81
82 my $ok_err_info = sub {
83         my ($msg) = @_;
84         is(grep(!/^I:/, split(/^/, $err)), 0, $msg) or
85                 diag "$msg: err=$err";
86 };
87
88 my $test_init = sub {
89         $cleanup->();
90         ok($lei->('init'), 'init w/o args');
91         $ok_err_info->('after init w/o args');
92         ok($lei->('init'), 'idempotent init w/o args');
93         $ok_err_info->('after idempotent init w/o args');
94
95         ok(!$lei->('init', "$home/x"), 'init conflict');
96         is(grep(/^E:/, split(/^/, $err)), 1, 'got error on conflict');
97         ok(!-e "$home/x", 'nothing created on conflict');
98         $cleanup->();
99
100         ok($lei->('init', "$home/x"), 'init conflict resolved');
101         $ok_err_info->('init w/ arg');
102         ok($lei->('init', "$home/x"), 'init idempotent w/ path');
103         $ok_err_info->('init idempotent w/ arg');
104         ok(-d "$home/x", 'created dir');
105         $cleanup->("$home/x");
106
107         ok(!$lei->('init', "$home/x", "$home/2"), 'too many args fails');
108         like($err, qr/too many/, 'noted excessive');
109         ok(!-e "$home/x", 'x not created on excessive');
110         for my $d (@$home_trash) {
111                 my $base = (split(m!/!, $d))[-1];
112                 ok(!-d $d, "$base not created");
113         }
114         is($out, '', 'nothing in stdout on init failure');
115 };
116
117 my $test_config = sub {
118         $cleanup->();
119         ok($lei->(qw(config a.b c)), 'config set var');
120         is($out.$err, '', 'no output on var set');
121         ok($lei->(qw(config -l)), 'config -l');
122         is($err, '', 'no errors on listing');
123         is($out, "a.b=c\n", 'got expected output');
124         ok(!$lei->(qw(config -f), "$home/.config/f", qw(x.y z)),
125                         'config set var with -f fails');
126         like($err, qr/not supported/, 'not supported noted');
127         ok(!-f "$home/config/f", 'no file created');
128 };
129
130 my $setup_publicinboxes = sub {
131         state $done = '';
132         return if $done eq $home;
133         use PublicInbox::InboxWritable;
134         for my $V (1, 2) {
135                 run_script([qw(-init), "-V$V", "t$V",
136                                 '--newsgroup', "t.$V",
137                                 "$home/t$V", "http://example.com/t$V",
138                                 "t$V\@example.com" ]) or BAIL_OUT "init v$V";
139         }
140         my $cfg = PublicInbox::Config->new;
141         my $seen = 0;
142         $cfg->each_inbox(sub {
143                 my ($ibx) = @_;
144                 my $im = PublicInbox::InboxWritable->new($ibx)->importer(0);
145                 my $V = $ibx->version;
146                 my @eml = (glob('t/*.eml'), 't/data/0001.patch');
147                 for (@eml) {
148                         next if $_ eq 't/psgi_v2-old.eml'; # dup mid
149                         $im->add(eml_load($_)) or BAIL_OUT "v$V add $_";
150                         $seen++;
151                 }
152                 $im->done;
153                 if ($V == 1) {
154                         run_script(['-index', $ibx->{inboxdir}]) or
155                                 BAIL_OUT 'index v1';
156                 }
157         });
158         $done = $home;
159         $seen || BAIL_OUT 'no imports';
160 };
161
162 my $test_external_remote = sub {
163         my ($url, $k) = @_;
164 SKIP: {
165         my $nr = 4;
166         skip "$k unset", $nr if !$url;
167         which('curl') or skip 'no curl', $nr;
168         which('torsocks') or skip 'no torsocks', $nr if $url =~ m!\.onion/!;
169         $lei->('ls-external');
170         for my $e (split(/^/ms, $out)) {
171                 $e =~ s/\s+boost.*//s;
172                 $lei->('forget-external', '-q', $e) or
173                         fail "error forgetting $e: $err"
174         }
175         $lei->('add-external', $url);
176         my $mid = '20140421094015.GA8962@dcvr.yhbt.net';
177         ok($lei->('q', "m:$mid"), "query $url");
178         is($err, '', "no errors on $url");
179         my $res = $json->decode($out);
180         is($res->[0]->{'m'}, "<$mid>", "got expected mid from $url");
181         ok($lei->('q', "m:$mid", 'd:..20101002'), 'no results, no error');
182         is($err, '', 'no output on 404, matching local FS behavior');
183         is($out, "[null]\n", 'got null results');
184         $lei->('forget-external', $url);
185 } # /SKIP
186 }; # /sub
187
188 my $test_external = sub {
189         $setup_publicinboxes->();
190         $cleanup->();
191         $lei->('ls-external');
192         is($out.$err, '', 'ls-external no output, yet');
193         ok(!-e $config_file && !-e $store_dir,
194                 'nothing created by ls-external');
195
196         ok(!$lei->('add-external', "$home/nonexistent"),
197                 "fails on non-existent dir");
198         $lei->('ls-external');
199         is($out.$err, '', 'ls-external still has no output');
200         my $cfg = PublicInbox::Config->new;
201         $cfg->each_inbox(sub {
202                 my ($ibx) = @_;
203                 ok($lei->(qw(add-external -q), $ibx->{inboxdir}),
204                         'added external');
205                 is($out.$err, '', 'no output');
206         });
207         ok(-s $config_file && -e $store_dir,
208                 'add-external created config + store');
209         my $lcfg = PublicInbox::Config->new($config_file);
210         $cfg->each_inbox(sub {
211                 my ($ibx) = @_;
212                 is($lcfg->{"external.$ibx->{inboxdir}.boost"}, 0,
213                         "configured boost on $ibx->{name}");
214         });
215         $lei->('ls-external');
216         like($out, qr/boost=0\n/s, 'ls-external has output');
217         ok($lei->(qw(add-external -q https://EXAMPLE.com/ibx)), 'add remote');
218         is($err, '', 'no warnings after add-external');
219         $lei->('ls-external');
220         like($out, qr!https://example\.com/ibx/!s, 'added canonical URL');
221         is($err, '', 'no warnings on ls-external');
222         ok($lei->(qw(forget-external -q https://EXAMPLE.com/ibx)),
223                 'forget');
224         $lei->('ls-external');
225         unlike($out, qr!https://example\.com/ibx/!s, 'removed canonical URL');
226
227         ok(!$lei->(qw(q s:prefix -o /dev/null -f maildir)), 'bad maildir');
228         like($err, qr!/dev/null exists and is not a directory!,
229                 'error shown');
230         is($? >> 8, 1, 'errored out with exit 1');
231
232         ok(!$lei->(qw(q s:prefix -f mboxcl2 -o), $home), 'bad mbox');
233         like($err, qr!\Q$home\E exists and is not a writable file!,
234                 'error shown');
235         is($? >> 8, 1, 'errored out with exit 1');
236
237         ok(!$lei->(qw(q s:prefix -o /dev/stdout -f Mbox2)), 'bad format');
238         like($err, qr/bad mbox --format=mbox2/, 'error shown');
239         is($? >> 8, 1, 'errored out with exit 1');
240
241         # note, on a Bourne shell users should be able to use either:
242         #       s:"use boolean prefix"
243         #       "s:use boolean prefix"
244         # or use single quotes, it should not matter.  Users only need
245         # to know shell quoting rules, not Xapian quoting rules.
246         # No double-quoting should be imposed on users on the CLI
247         $lei->('q', 's:use boolean prefix');
248         like($out, qr/search: use boolean prefix/, 'phrase search got result');
249         my $res = $json->decode($out);
250         is(scalar(@$res), 2, 'only 2 element array (1 result)');
251         is($res->[1], undef, 'final element is undef'); # XXX should this be?
252         is(ref($res->[0]), 'HASH', 'first element is hashref');
253         $lei->('q', '--pretty', 's:use boolean prefix');
254         my $pretty = $json->decode($out);
255         is_deeply($res, $pretty, '--pretty is identical after decode');
256
257         for my $fmt (qw(ldjson ndjson jsonl)) {
258                 $lei->('q', '-f', $fmt, 's:use boolean prefix');
259                 is($out, $json->encode($pretty->[0])."\n", "-f $fmt");
260         }
261
262         require IO::Uncompress::Gunzip;
263         for my $sfx ('', '.gz') {
264                 my $f = "$home/mbox$sfx";
265                 $lei->('q', '-o', "mboxcl2:$f", 's:use boolean prefix');
266                 my $cat = $sfx eq '' ? sub {
267                         open my $mb, '<', $f or fail "no mbox: $!";
268                         <$mb>
269                 } : sub {
270                         my $z = IO::Uncompress::Gunzip->new($f, MultiStream=>1);
271                         <$z>;
272                 };
273                 my @s = grep(/^Subject:/, $cat->());
274                 is(scalar(@s), 1, "1 result in mbox$sfx");
275                 $lei->('q', '-a', '-o', "mboxcl2:$f", 's:see attachment');
276                 is($err, '', 'no errors from augment');
277                 @s = grep(/^Subject:/, my @wtf = $cat->());
278                 is(scalar(@s), 2, "2 results in mbox$sfx");
279
280                 $lei->('q', '-a', '-o', "mboxcl2:$f", 's:nonexistent');
281                 is($err, '', "no errors on no results ($sfx)");
282
283                 my @s2 = grep(/^Subject:/, $cat->());
284                 is_deeply(\@s2, \@s,
285                         "same 2 old results w/ --augment and bad search $sfx");
286
287                 $lei->('q', '-o', "mboxcl2:$f", 's:nonexistent');
288                 my @res = $cat->();
289                 is_deeply(\@res, [], "clobber w/o --augment $sfx");
290         }
291         ok(!$lei->('q', '-o', "$home/mbox", 's:nope'),
292                         'fails if mbox format unspecified');
293         ok(!$lei->(qw(q --no-local s:see)), '--no-local');
294         is($? >> 8, 1, 'proper exit code');
295         like($err, qr/no local or remote.+? to search/, 'no inbox');
296         my %e = (
297                 TEST_LEI_EXTERNAL_HTTPS => 'https://public-inbox.org/meta/',
298                 TEST_LEI_EXTERNAL_ONION => $onions[int(rand(scalar(@onions)))],
299         );
300         for my $k (keys %e) {
301                 my $url = $ENV{$k} // '';
302                 $url = $e{$k} if $url eq '1';
303                 $test_external_remote->($url, $k);
304         }
305 };
306
307 my $test_lei_common = sub {
308         $test_help->();
309         $test_config->();
310         $test_init->();
311         $test_external->();
312 };
313
314 if ($ENV{TEST_LEI_ONESHOT}) {
315         require_ok 'PublicInbox::LEI';
316         # force sun_path[108] overflow, ($lei->() filters out this path)
317         my $xrd = "$home/1shot-test".('.sun_path' x 108);
318         local $ENV{XDG_RUNTIME_DIR} = $xrd;
319         $err_filter = qr!\Q$xrd!;
320         $test_lei_common->();
321 } else {
322 SKIP: { # real socket
323         eval { require Socket::MsgHdr; 1 } // do {
324                 require PublicInbox::Spawn;
325                 PublicInbox::Spawn->can('send_cmd4');
326         } // skip 'Socket::MsgHdr or Inline::C missing or unconfigured', 115;
327         local $ENV{XDG_RUNTIME_DIR} = "$home/xdg_run";
328         my $sock = "$ENV{XDG_RUNTIME_DIR}/lei/5.seq.sock";
329         my $err_log = "$ENV{XDG_RUNTIME_DIR}/lei/errors.log";
330
331         ok($lei->('daemon-pid'), 'daemon-pid');
332         is($err, '', 'no error from daemon-pid');
333         like($out, qr/\A[0-9]+\n\z/s, 'pid returned') or BAIL_OUT;
334         chomp(my $pid = $out);
335         ok(kill(0, $pid), 'pid is valid');
336         ok(-S $sock, 'sock created');
337
338         $test_lei_common->();
339         is(-s $err_log, 0, 'nothing in errors.log');
340         open my $efh, '>>', $err_log or BAIL_OUT $!;
341         print $efh "phail\n" or BAIL_OUT $!;
342         close $efh or BAIL_OUT $!;
343
344         ok($lei->('daemon-pid'), 'daemon-pid');
345         chomp(my $pid_again = $out);
346         is($pid, $pid_again, 'daemon-pid idempotent');
347         like($err, qr/phail/, 'got mock "phail" error previous run');
348
349         ok($lei->(qw(daemon-kill)), 'daemon-kill');
350         is($out, '', 'no output from daemon-kill');
351         is($err, '', 'no error from daemon-kill');
352         for (0..100) {
353                 kill(0, $pid) or last;
354                 tick();
355         }
356         ok(-S $sock, 'sock still exists');
357         ok(!kill(0, $pid), 'pid gone after stop');
358
359         ok($lei->(qw(daemon-pid)), 'daemon-pid');
360         chomp(my $new_pid = $out);
361         ok(kill(0, $new_pid), 'new pid is running');
362         ok(-S $sock, 'sock still exists');
363
364         for my $sig (qw(-0 -CHLD)) {
365                 ok($lei->('daemon-kill', $sig), "handles $sig");
366         }
367         is($out.$err, '', 'no output on innocuous signals');
368         ok($lei->('daemon-pid'), 'daemon-pid');
369         chomp $out;
370         is($out, $new_pid, 'PID unchanged after -0/-CHLD');
371
372         if ('socket inaccessible') {
373                 chmod 0000, $sock or BAIL_OUT "chmod 0000: $!";
374                 ok($lei->('help'), 'connect fail, one-shot fallback works');
375                 like($err, qr/\bconnect\(/, 'connect error noted');
376                 like($out, qr/^usage: /, 'help output works');
377                 chmod 0700, $sock or BAIL_OUT "chmod 0700: $!";
378         }
379         unlink $sock or BAIL_OUT "unlink($sock) $!";
380         for (0..100) {
381                 kill('CHLD', $new_pid) or last;
382                 tick();
383         }
384         ok(!kill(0, $new_pid), 'daemon exits after unlink');
385         # success over socket, can't test without
386 }; # SKIP
387 } # else
388
389 done_testing;