simplify test names of example code
[barcat.git] / t / examples.t
index 19c1377821983d7715e1aa62adde46a3c6cc43ed..0b5e77855b86f7dd1163044957b3898003b8384b 100755 (executable)
@@ -1,20 +1,54 @@
 #!/usr/bin/env perl
 use 5.014;
 use warnings;
+use re '/ms';
 use Test::More;
 
+my %CMDARGS = (
+       ping => '-c 1',
+       curl => '-sS',
+       'cat \Klog/' => '/var/log/apache2/',
+);
+
 my $filename = 'barcat';
 open my $input, '<', $filename
        or die "Cannot read documentation from $filename script\n";
 
 local $/ = "\n\n";
 while (readline $input) {
+       # find code snippets in the appropriate section
        /^=head1 EXAMPLES/ ... /^=head1/ or next;
        /^\h/ or next;
        chomp;
 
-       my ($name) = /[\h(]*([^|]+)/;
-       ok(qx($_), $name);
+       # compose an identifier from significant parts
+       do {
+               s/^\h+//;             # indentation
+               s/\\\n\s*//g;         # line continuations
+               s/^[(\h]+//;          # subshell
+               s/^echo\ .*?\|\s*//;  # preceding input
+               s/\|.*//;             # subsequent pipes
+               s/^cat\ //;           # local file
+               s/^curl\ // and do {  # remote url
+                       s/\ -.+//g;                 # download options
+                       s{//[^/\s]+/\K\S*(?=/)}{};  # subdirectories
+                       s{^https?://}{};            # http protocol
+               };
+       } for my $name = $_;
+
+       # prepare shell command to execute
+       my $cmd = $_;
+       while (my ($subcmd, $args) = each %CMDARGS) {
+               $subcmd .= " \\K", $args .= ' ' unless $subcmd =~ m/\\K/;
+               $cmd =~ s/\b$subcmd/$args/;
+       }
+       $cmd =~ s/'/'\\''/g, $cmd = "  bash -c 'set -o pipefail\n$cmd'";
+
+       # run and report unexpected results
+       ok(eval {
+               qx($cmd) or return;
+               return $? == 0;
+       }, $name) or diag($cmd);
 }
 
 done_testing();