capture error messages from examples
[barcat.git] / t / examples.t
1 #!/usr/bin/env perl
2 use 5.014;
3 use warnings;
4 use re '/ms';
5 use IPC::Run 'run';
6
7 use Test::More;
8 { # silence fail diagnostics because of single caller
9         no warnings 'redefine';
10         sub Test::Builder::_ok_debug {}
11 }
12
13 my %CMDARGS = (
14         ping => '-c 1',
15         curl => '-sS',
16         'cat \Klog/' => '/var/log/apache2/',
17 );
18
19 my $filename = 'barcat';
20 open my $input, '<', $filename
21         or die "Cannot read documentation from $filename script\n";
22
23 local $/ = "\n\n";
24 while (readline $input) {
25         # find code snippets in the appropriate section
26         /^=head1 EXAMPLES/ ... /^=head1/ or next;
27         /^\h/ or next;
28         chomp;
29
30         # compose an identifier from significant parts
31         do {
32                 s/^\h+//;             # indentation
33                 s/\\\n\s*//g;         # line continuations
34                 s/^[(\h]+//;          # subshell
35                 s/^echo\ .*?\|\s*//;  # preceding input
36                 s/\|.*//;             # subsequent pipes
37                 s/^cat\ //;           # local file
38                 s/^curl\ // and do {  # remote url
39                         s/\ -.+//g;                 # download options
40                         s{//[^/\s]+/\K\S*(?=/)}{};  # subdirectories
41                         s{^https?://}{};            # http protocol
42                 };
43         } for my $name = $_;
44
45         # prepare shell command to execute
46         my $cmd = $_;
47         while (my ($subcmd, $args) = each %CMDARGS) {
48                 $subcmd .= " \\K", $args .= ' ' unless $subcmd =~ m/\\K/;
49                 $cmd =~ s/\b$subcmd/$args/;
50         }
51         my @cmd = (bash => -c => "set -o pipefail\n$cmd");
52
53         # run and report unexpected results
54         ok(eval {
55                 run(\@cmd, \undef, \my $output, \my $error);
56                 die("error message:\n    $error\n") if $error;
57                 $? == 0 or die "exit status ", $? >> 8, "\n";
58                 length $output or die "empty output\n";
59                 return 1;
60         }, $name) or diag("Failed command\n@cmd\nfrom $filename line $.: $@");
61 }
62
63 done_testing();