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