c5648ad06c1b2bec403a211146811662282b1f7e
[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 \Khttpd/' => '/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 scriptlets in the appropriate section
26         /^=head1 EXAMPLES/ ... /^=head1/ or next;
27         /^\h/ or next;  # indented code snippet
28         /\A\h*>/ and next;  # psql prompt
29         chomp;
30
31         # compose an identifier from significant parts
32         do {
33                 s/^\h+//;             # indentation
34                 s/\\\n\s*//g;         # line continuations
35                 s/^[(\h]+//;          # subshell
36                 s/^echo\ .*?\|\s*//;  # preceding input
37                 s/\|.*//;             # subsequent pipes
38                 s/^cat\ //;           # local file
39                 s/^curl\ // and do {  # remote url
40                         s/\ -.+//g;                 # download options
41                         s{//[^/\s]+/\K\S*(?=/)}{};  # subdirectories
42                         s{^https?://}{};            # http protocol
43                 };
44         } for my $name = $_;
45
46         # prepare shell command to execute
47         my $cmd = $_;
48         while (my ($subcmd, $args) = each %CMDARGS) {
49                 $subcmd .= " \\K", $args .= ' ' unless $subcmd =~ m/\\K/;
50                 $cmd =~ s/\b$subcmd/$args/;
51         }
52         my @cmd = (bash => -c => "set -o pipefail\n$cmd");
53
54         # run and report unexpected results
55         ok(eval {
56                 run(\@cmd, \undef, \my $output, \my $error);
57                 die("error message:\n    $error\n") if $error;
58                 $? == 0 or die "exit status ", $? >> 8, "\n";
59                 length $output or die "empty output\n";
60                 return 1;
61         }, $name) or diag("Failed command\n@cmd\nfrom $filename line $.: $@");
62 }
63
64 done_testing();