test return status of example commands and pipes
[barcat.git] / t / examples.t
1 #!/usr/bin/env perl
2 use 5.014;
3 use warnings;
4 use Test::More;
5
6 my %CMDARGS = (
7         ping => '-c 1',
8         curl => '-sS',
9         'cat \Klog/' => '/var/log/apache2/',
10 );
11
12 my $filename = 'barcat';
13 open my $input, '<', $filename
14         or die "Cannot read documentation from $filename script\n";
15
16 local $/ = "\n\n";
17 while (readline $input) {
18         # find code snippets in the appropriate section
19         /^=head1 EXAMPLES/ ... /^=head1/ or next;
20         /^\h/ or next;
21         chomp;
22
23         my ($name) = /[\h(]*([^|]+)/;
24
25         # prepare shell command to execute
26         my $cmd = $_;
27         while (my ($subcmd, $args) = each %CMDARGS) {
28                 $subcmd .= " \\K", $args .= ' ' unless $subcmd =~ m/\\K/;
29                 $cmd =~ s/\b$subcmd/$args/;
30         }
31         $cmd =~ s/'/'\\''/g, $cmd = "bash -c 'set -o pipefail\n$cmd'";
32
33         # run and report unexpected results
34         ok(eval {
35                 qx($cmd) or return;
36                 return $? == 0;
37         }, $name);
38 }
39
40 done_testing();