Debian Codegraph @

src/test/perl/PostgreSQL/Test/Utils.pm

raw
1
2 # Copyright (c) 2021-2025, PostgreSQL Global Development Group
3
4 =pod
5
6 =head1 NAME
7
8 PostgreSQL::Test::Utils - helper module for writing PostgreSQL's C<prove> tests.
9
10 =head1 SYNOPSIS
11
12 use PostgreSQL::Test::Utils;
13
14 # Test basic output of a command
15 program_help_ok('initdb');
16 program_version_ok('initdb');
17 program_options_handling_ok('initdb');
18
19 # Test option combinations
20 command_fails(['initdb', '--invalid-option'],
21 'command fails with invalid option');
22 my $tempdir = PostgreSQL::Test::Utils::tempdir;
23 command_ok('initdb', '--pgdata' => $tempdir);
24
25 # Miscellanea
26 print "on Windows" if $PostgreSQL::Test::Utils::windows_os;
27 ok(check_mode_recursive($stream_dir, 0700, 0600),
28 "check stream dir permissions");
29 PostgreSQL::Test::Utils::system_log('pg_ctl', 'kill', 'QUIT', $slow_pid);
30
31 =head1 DESCRIPTION
32
33 C<PostgreSQL::Test::Utils> contains a set of routines dedicated to environment setup for
34 a PostgreSQL regression test run and includes some low-level routines
35 aimed at controlling command execution, logging and test functions.
36
37 =cut
38
39 # This module should never depend on any other PostgreSQL regression test
40 # modules.
41
42 package PostgreSQL::Test::Utils;
43
44 use strict;
45 use warnings FATAL => 'all';
46
47 use Carp;
48 use Config;
49 use Cwd;
50 use Exporter 'import';
51 use Fcntl qw(:mode :seek);
52 use File::Basename;
53 use File::Compare;
54 use File::Find;
55 use File::Spec;
56 use File::stat qw(stat);
57 use File::Temp ();
58 use IPC::Run;
59 use POSIX qw(locale_h);
60 use PostgreSQL::Test::SimpleTee;
61
62 # We need a version of Test::More recent enough to support subtests
63 use Test::More 0.98;
64
65 our @EXPORT = qw(
66 generate_ascii_string
67 slurp_dir
68 slurp_file
69 append_to_file
70 string_replace_file
71 check_mode_recursive
72 chmod_recursive
73 check_pg_config
74 compare_files
75 dir_symlink
76 scan_server_header
77 system_or_bail
78 system_log
79 run_log
80 run_command
81 pump_until
82
83 command_ok
84 command_fails
85 command_exit_is
86 program_help_ok
87 program_version_ok
88 program_options_handling_ok
89 command_like
90 command_like_safe
91 command_fails_like
92 command_ok_or_fails_like
93 command_checks_all
94
95 tar_portability_options
96
97 $windows_os
98 $is_msys2
99 $use_unix_sockets
100 );
101
102 our ($windows_os, $is_msys2, $use_unix_sockets, $timeout_default,
103 $tmp_check, $log_path, $test_logfile);
104
105 BEGIN
106 {
107
108 # Set to untranslated messages, to be able to compare program output
109 # with expected strings.
110 delete $ENV{LANGUAGE};
111 delete $ENV{LC_ALL};
112 $ENV{LC_MESSAGES} = 'C';
113 setlocale(LC_ALL, "");
114
115 # This list should be kept in sync with pg_regress.c.
116 my @envkeys = qw (
117 PGCHANNELBINDING
118 PGCLIENTENCODING
119 PGCONNECT_TIMEOUT
120 PGDATA
121 PGDATABASE
122 PGGSSDELEGATION
123 PGGSSENCMODE
124 PGGSSLIB
125 PGHOSTADDR
126 PGKRBSRVNAME
127 PGPASSFILE
128 PGPASSWORD
129 PGREQUIREPEER
130 PGREQUIRESSL
131 PGSERVICE
132 PGSERVICEFILE
133 PGSSLCERT
134 PGSSLCRL
135 PGSSLCRLDIR
136 PGSSLKEY
137 PGSSLMAXPROTOCOLVERSION
138 PGSSLMINPROTOCOLVERSION
139 PGSSLMODE
140 PGSSLROOTCERT
141 PGSSLSNI
142 PGTARGETSESSIONATTRS
143 PGUSER
144 PGPORT
145 PGHOST
146 PG_COLOR
147 );
148 delete @ENV{@envkeys};
149
150 $ENV{PGAPPNAME} = basename($0);
151
152 # Must be set early
153 $windows_os = $Config{osname} eq 'MSWin32' || $Config{osname} eq 'msys';
154 # Check if this environment is MSYS2.
155 $is_msys2 =
156 $windows_os
157 && -x '/usr/bin/uname'
158 && `uname -or` =~ /^[2-9].*Msys/;
159
160 if ($windows_os)
161 {
162 require Win32API::File;
163 Win32API::File->import(qw(createFile OsFHandleOpen CloseHandle));
164 }
165
166 # Specifies whether to use Unix sockets for test setups. On
167 # Windows we don't use them by default since it's not universally
168 # supported, but it can be overridden if desired.
169 $use_unix_sockets =
170 (!$windows_os || defined $ENV{PG_TEST_USE_UNIX_SOCKETS});
171
172 $timeout_default = $ENV{PG_TEST_TIMEOUT_DEFAULT};
173 $timeout_default = 180
174 if not defined $timeout_default or $timeout_default eq '';
175 }
176
177 =pod
178
179 =head1 EXPORTED VARIABLES
180
181 =over
182
183 =item C<$windows_os>
184
185 Set to true when running under Windows, except on Cygwin.
186
187 =item C<$is_msys2>
188
189 Set to true when running under MSYS2.
190
191 =back
192
193 =cut
194
195 INIT
196 {
197 # See https://github.com/cpan-authors/IPC-Run/commit/fc9288c for how this
198 # reduces idle time. Remove this when IPC::Run 20231003.0 is too old to
199 # matter (when all versions that matter provide the optimization).
200 $SIG{CHLD} = sub { }
201 unless defined $SIG{CHLD};
202
203 # Return EPIPE instead of killing the process with SIGPIPE. An affected
204 # test may still fail, but it's more likely to report useful facts.
205 $SIG{PIPE} = 'IGNORE';
206
207 # Determine output directories, and create them. The base paths are the
208 # TESTDATADIR / TESTLOGDIR environment variables, which are normally set
209 # by the invoking Makefile.
210 $tmp_check = $ENV{TESTDATADIR} ? "$ENV{TESTDATADIR}" : "tmp_check";
211 $log_path = $ENV{TESTLOGDIR} ? "$ENV{TESTLOGDIR}" : "log";
212
213 mkdir $tmp_check;
214 mkdir $log_path;
215
216 # Open the test log file, whose name depends on the test name.
217 $test_logfile = basename($0);
218 $test_logfile =~ s/\.[^.]+$//;
219 $test_logfile = "$log_path/regress_log_$test_logfile";
220 open my $testlog, '>', $test_logfile
221 or die "could not open STDOUT to logfile \"$test_logfile\": $!";
222
223 # Hijack STDOUT and STDERR to the log file
224 open(my $orig_stdout, '>&', \*STDOUT) or die $!;
225 open(my $orig_stderr, '>&', \*STDERR) or die $!;
226 open(STDOUT, '>&', $testlog) or die $!;
227 open(STDERR, '>&', $testlog) or die $!;
228
229 # The test output (ok ...) needs to be printed to the original STDOUT so
230 # that the 'prove' program can parse it, and display it to the user in
231 # real time. But also copy it to the log file, to provide more context
232 # in the log.
233 my $builder = Test::More->builder;
234 my $fh = $builder->output;
235 tie *$fh, "PostgreSQL::Test::SimpleTee", $orig_stdout, $testlog;
236 $fh = $builder->failure_output;
237 tie *$fh, "PostgreSQL::Test::SimpleTee", $orig_stderr, $testlog;
238
239 # Enable auto-flushing for all the file handles. Stderr and stdout are
240 # redirected to the same file, and buffering causes the lines to appear
241 # in the log in confusing order.
242 autoflush STDOUT 1;
243 autoflush STDERR 1;
244 autoflush $testlog 1;
245 }
246
247 END
248 {
249
250 # Test files have several ways of causing prove_check to fail:
251 # 1. Exit with a non-zero status.
252 # 2. Call ok(0) or similar, indicating that a constituent test failed.
253 # 3. Deviate from the planned number of tests.
254 #
255 # Preserve temporary directories after (1) and after (2).
256 $File::Temp::KEEP_ALL = 1 unless $? == 0 && all_tests_passing();
257 }
258
259 =pod
260
261 =head1 ROUTINES
262
263 =over
264
265 =item all_tests_passing()
266
267 Return 1 if all the tests run so far have passed. Otherwise, return 0.
268
269 =cut
270
271 sub all_tests_passing
272 {
273 foreach my $status (Test::More->builder->summary)
274 {
275 return 0 unless $status;
276 }
277 return 1;
278 }
279
280 =pod
281
282 =item tempdir(prefix)
283
284 Securely create a temporary directory inside C<$tmp_check>, like C<mkdtemp>,
285 and return its name. The directory will be removed automatically at the
286 end of the tests, unless the environment variable PG_TEST_NOCLEAN is provided.
287
288 If C<prefix> is given, the new directory is templated as C<${prefix}_XXXX>.
289 Otherwise the template is C<tmp_test_XXXX>.
290
291 =cut
292
293 sub tempdir
294 {
295 my ($prefix) = @_;
296 $prefix = "tmp_test" unless defined $prefix;
297 return File::Temp::tempdir(
298 $prefix . '_XXXX',
299 DIR => $tmp_check,
300 CLEANUP => not defined $ENV{'PG_TEST_NOCLEAN'});
301 }
302
303 =pod
304
305 =item tempdir_short()
306
307 As above, but the directory is outside the build tree so that it has a short
308 name, to avoid path length issues.
309
310 =cut
311
312 sub tempdir_short
313 {
314
315 return File::Temp::tempdir(
316 CLEANUP => not defined $ENV{'PG_TEST_NOCLEAN'});
317 }
318
319 =pod
320
321 =item has_wal_read_bug()
322
323 Returns true if $tmp_check is subject to a sparc64+ext4 bug that causes WAL
324 readers to see zeros if another process simultaneously wrote the same offsets.
325 Consult this in tests that fail frequently on affected configurations. The
326 bug has made streaming standbys fail to advance, reporting corrupt WAL. It
327 has made COMMIT PREPARED fail with "could not read two-phase state from WAL".
328 Non-WAL PostgreSQL reads haven't been affected, likely because those readers
329 and writers have buffering systems in common. See
330 https://postgr.es/m/[email protected] for details.
331
332 =cut
333
334 sub has_wal_read_bug
335 {
336 return
337 $Config{osname} eq 'linux'
338 && $Config{archname} =~ /^sparc/
339 && !run_log([ qw(df -x ext4), $tmp_check ], '&>' => '/dev/null');
340 }
341
342 =pod
343
344 =item system_log(@cmd)
345
346 Run (via C<system()>) the command passed as argument; the return
347 value is passed through.
348
349 =cut
350
351 sub system_log
352 {
353 print("# Running: " . join(" ", @_) . "\n");
354 return system(@_);
355 }
356
357 =pod
358
359 =item system_or_bail(@cmd)
360
361 Run (via C<system()>) the command passed as argument, and returns
362 if the command is successful.
363 On failure, abandon further tests and exit the program.
364
365 =cut
366
367 sub system_or_bail
368 {
369 if (system_log(@_) != 0)
370 {
371 if ($? == -1)
372 {
373 BAIL_OUT(
374 sprintf(
375 "failed to execute command \"%s\": $!", join(" ", @_)));
376 }
377 elsif ($? & 127)
378 {
379 BAIL_OUT(
380 sprintf(
381 "command \"%s\" died with signal %d",
382 join(" ", @_),
383 $? & 127));
384 }
385 else
386 {
387 BAIL_OUT(
388 sprintf(
389 "command \"%s\" exited with value %d",
390 join(" ", @_),
391 $? >> 8));
392 }
393 }
394 }
395
396 =pod
397
398 =item run_log(@cmd)
399
400 Run the given command via C<IPC::Run::run()>, noting it in the log.
401 The return value from the command is passed through.
402
403 =cut
404
405 sub run_log
406 {
407 print("# Running: " . join(" ", @{ $_[0] }) . "\n");
408 return IPC::Run::run(@_);
409 }
410
411 =pod
412
413 =item run_command(cmd)
414
415 Run (via C<IPC::Run::run()>) the command passed as argument.
416 The return value from the command is ignored.
417 The return value is C<($stdout, $stderr)>.
418
419 =cut
420
421 sub run_command
422 {
423 my ($cmd) = @_;
424 my ($stdout, $stderr);
425 my $result = IPC::Run::run $cmd, '>' => \$stdout, '2>' => \$stderr;
426 chomp($stdout);
427 chomp($stderr);
428 return ($stdout, $stderr);
429 }
430
431 =pod
432
433 =item pump_until(proc, timeout, stream, until)
434
435 Pump until string is matched on the specified stream, or timeout occurs.
436
437 =cut
438
439 sub pump_until
440 {
441 my ($proc, $timeout, $stream, $until) = @_;
442 $proc->pump_nb();
443 while (1)
444 {
445 last if $$stream =~ /$until/;
446 if ($timeout->is_expired)
447 {
448 diag(
449 "pump_until: timeout expired when searching for \"$until\" with stream: \"$$stream\""
450 );
451 return 0;
452 }
453 if (not $proc->pumpable())
454 {
455 diag(
456 "pump_until: process terminated unexpectedly when searching for \"$until\" with stream: \"$$stream\""
457 );
458 return 0;
459 }
460 $proc->pump();
461 }
462 return 1;
463 }
464
465 =pod
466
467 =item generate_ascii_string(from_char, to_char)
468
469 Generate a string made of the given range of ASCII characters.
470
471 =cut
472
473 sub generate_ascii_string
474 {
475 my ($from_char, $to_char) = @_;
476 my $res;
477
478 for my $i ($from_char .. $to_char)
479 {
480 $res .= sprintf("%c", $i);
481 }
482 return $res;
483 }
484
485 =pod
486
487 =item slurp_dir(dir)
488
489 Return the complete list of entries in the specified directory.
490
491 =cut
492
493 sub slurp_dir
494 {
495 my ($dir) = @_;
496 opendir(my $dh, $dir)
497 or croak "could not opendir \"$dir\": $!";
498 my @direntries = readdir $dh;
499 closedir $dh;
500 return @direntries;
501 }
502
503 =pod
504
505 =item slurp_file(filename [, $offset])
506
507 Return the full contents of the specified file, beginning from an
508 offset position if specified.
509
510 =cut
511
512 sub slurp_file
513 {
514 my ($filename, $offset) = @_;
515 local $/;
516 my $contents;
517 my $fh;
518
519 # On windows open file using win32 APIs, to allow us to set the
520 # FILE_SHARE_DELETE flag ("d" below), otherwise other accesses to the file
521 # may fail.
522 if ($Config{osname} ne 'MSWin32')
523 {
524 open($fh, '<', $filename)
525 or croak "could not read \"$filename\": $!";
526 }
527 else
528 {
529 my $fHandle = createFile($filename, "r", "rwd")
530 or croak "could not open \"$filename\": $^E";
531 OsFHandleOpen($fh = IO::Handle->new(), $fHandle, 'r')
532 or croak "could not read \"$filename\": $^E\n";
533 }
534
535 if (defined($offset))
536 {
537 seek($fh, $offset, SEEK_SET)
538 or croak "could not seek \"$filename\": $!";
539 }
540
541 $contents = <$fh>;
542 close $fh;
543
544 return $contents;
545 }
546
547 =pod
548
549 =item append_to_file(filename, str)
550
551 Append a string at the end of a given file. (Note: no newline is appended at
552 end of file.)
553
554 =cut
555
556 sub append_to_file
557 {
558 my ($filename, $str) = @_;
559 open my $fh, ">>", $filename
560 or croak "could not write \"$filename\": $!";
561 print $fh $str;
562 close $fh;
563 return;
564 }
565
566 =pod
567
568 =item string_replace_file(filename, find, replace)
569
570 Find and replace string of a given file.
571
572 =cut
573
574 sub string_replace_file
575 {
576 my ($filename, $find, $replace) = @_;
577 open(my $in, '<', $filename) or croak $!;
578 my $content = '';
579 while (<$in>)
580 {
581 $_ =~ s/$find/$replace/;
582 $content = $content . $_;
583 }
584 close $in;
585 open(my $out, '>', $filename) or croak $!;
586 print $out $content;
587 close($out);
588
589 return;
590 }
591
592 =pod
593
594 =item check_mode_recursive(dir, expected_dir_mode, expected_file_mode, ignore_list)
595
596 Check that all file/dir modes in a directory match the expected values,
597 ignoring files in C<ignore_list> (basename only).
598
599 =cut
600
601 sub check_mode_recursive
602 {
603 my ($dir, $expected_dir_mode, $expected_file_mode, $ignore_list) = @_;
604
605 # Result defaults to true
606 my $result = 1;
607
608 find(
609 {
610 follow_fast => 1,
611 wanted => sub {
612 # Is file in the ignore list?
613 foreach my $ignore ($ignore_list ? @{$ignore_list} : [])
614 {
615 if ("$dir/$ignore" eq $File::Find::name)
616 {
617 return;
618 }
619 }
620
621 # Allow ENOENT. A running server can delete files, such as
622 # those in pg_stat. Other stat() failures are fatal.
623 my $file_stat = stat($File::Find::name);
624 unless (defined($file_stat))
625 {
626 my $is_ENOENT = $!{ENOENT};
627 my $msg = "unable to stat $File::Find::name: $!";
628 if ($is_ENOENT)
629 {
630 warn $msg;
631 return;
632 }
633 else
634 {
635 die $msg;
636 }
637 }
638
639 my $file_mode = S_IMODE($file_stat->mode);
640
641 # Is this a file?
642 if (S_ISREG($file_stat->mode))
643 {
644 if ($file_mode != $expected_file_mode)
645 {
646 print(
647 *STDERR,
648 sprintf("$File::Find::name mode must be %04o\n",
649 $expected_file_mode));
650
651 $result = 0;
652 return;
653 }
654 }
655
656 # Else a directory?
657 elsif (S_ISDIR($file_stat->mode))
658 {
659 if ($file_mode != $expected_dir_mode)
660 {
661 print(
662 *STDERR,
663 sprintf("$File::Find::name mode must be %04o\n",
664 $expected_dir_mode));
665
666 $result = 0;
667 return;
668 }
669 }
670
671 # Else something we can't handle
672 else
673 {
674 die "unknown file type for $File::Find::name";
675 }
676 }
677 },
678 $dir);
679
680 return $result;
681 }
682
683 =pod
684
685 =item chmod_recursive(dir, dir_mode, file_mode)
686
687 C<chmod> recursively each file and directory within the given directory.
688
689 =cut
690
691 sub chmod_recursive
692 {
693 my ($dir, $dir_mode, $file_mode) = @_;
694
695 find(
696 {
697 follow_fast => 1,
698 wanted => sub {
699 my $file_stat = stat($File::Find::name);
700
701 if (defined($file_stat))
702 {
703 chmod(
704 S_ISDIR($file_stat->mode) ? $dir_mode : $file_mode,
705 $File::Find::name
706 ) or die "unable to chmod $File::Find::name";
707 }
708 }
709 },
710 $dir);
711 return;
712 }
713
714 =pod
715
716 =item scan_server_header(header_path, regexp)
717
718 Returns an array that stores all the matches of the given regular expression
719 within the PostgreSQL installation's C<header_path>. This can be used to
720 retrieve specific value patterns from the installation's header files.
721
722 =cut
723
724 sub scan_server_header
725 {
726 my ($header_path, $regexp) = @_;
727
728 my ($stdout, $stderr);
729 my $result = IPC::Run::run [ 'pg_config', '--includedir-server' ],
730 '>' => \$stdout,
731 '2>' => \$stderr
732 or die "could not execute pg_config";
733 chomp($stdout);
734 $stdout =~ s/\r$//;
735
736 open my $header_h, '<', "$stdout/$header_path" or die "$!";
737
738 my @match = undef;
739 while (<$header_h>)
740 {
741 my $line = $_;
742
743 if (@match = $line =~ /^$regexp/)
744 {
745 last;
746 }
747 }
748
749 close $header_h;
750 die "could not find match in header $header_path\n"
751 unless @match;
752 return @match;
753 }
754
755 =pod
756
757 =item check_pg_config(regexp)
758
759 Return the number of matches of the given regular expression
760 within the installation's C<pg_config.h>.
761
762 =cut
763
764 sub check_pg_config
765 {
766 my ($regexp) = @_;
767 my ($stdout, $stderr);
768 my $result = IPC::Run::run [ 'pg_config', '--includedir' ],
769 '>' => \$stdout,
770 '2>' => \$stderr
771 or die "could not execute pg_config";
772 chomp($stdout);
773 $stdout =~ s/\r$//;
774
775 open my $pg_config_h, '<', "$stdout/pg_config.h" or die "$!";
776 my $match = (grep { /^$regexp/ } <$pg_config_h>);
777 close $pg_config_h;
778 return $match;
779 }
780
781 =pod
782
783 =item compare_files(file1, file2, testname)
784
785 Check that two files match, printing the difference if any.
786
787 C<line_comp_function> is an optional CODE reference to a line comparison
788 function, passed down as-is to File::Compare::compare_text.
789
790 =cut
791
792 sub compare_files
793 {
794 my ($file1, $file2, $testname, $line_comp_function) = @_;
795
796 # If nothing is given, all lines should be equal.
797 $line_comp_function = sub { $_[0] ne $_[1] }
798 unless defined $line_comp_function;
799
800 my $compare_res =
801 File::Compare::compare_text($file1, $file2, $line_comp_function);
802 is($compare_res, 0, $testname);
803
804 # Provide more context if the files do not match.
805 if ($compare_res != 0)
806 {
807 my ($stdout, $stderr) =
808 run_command([ 'diff', '-u', $file1, $file2 ]);
809 print "=== diff of $file1 and $file2\n";
810 print "=== stdout ===\n";
811 print $stdout;
812 print "=== stderr ===\n";
813 print $stderr;
814 print "=== EOF ===\n";
815 }
816
817 return;
818 }
819
820 =pod
821
822 =item dir_symlink(oldname, newname)
823
824 Portably create a symlink for a directory. On Windows this creates a junction
825 point. Elsewhere it just calls perl's builtin symlink.
826
827 =cut
828
829 sub dir_symlink
830 {
831 my $oldname = shift;
832 my $newname = shift;
833 if ($windows_os)
834 {
835 $oldname =~ s,/,\\,g;
836 $newname =~ s,/,\\,g;
837 my $cmd = qq{mklink /j "$newname" "$oldname"};
838 if ($Config{osname} eq 'msys')
839 {
840 # need some indirection on msys
841 $cmd = qq{echo '$cmd' | \$COMSPEC /Q};
842 }
843 system($cmd) == 0 or die;
844 }
845 else
846 {
847 symlink $oldname, $newname or die $!;
848 }
849 die "No $newname" unless -e $newname;
850 }
851
852 =pod
853
854 =back
855
856 =head1 Test::More-LIKE METHODS
857
858 =over
859
860 =item command_ok(cmd, test_name)
861
862 Check that the command runs (via C<run_log>) successfully.
863
864 =cut
865
866 sub command_ok
867 {
868 local $Test::Builder::Level = $Test::Builder::Level + 1;
869 my ($cmd, $test_name) = @_;
870 my $result = run_log($cmd);
871 ok($result, $test_name);
872 return;
873 }
874
875 =pod
876
877 =item command_fails(cmd, test_name)
878
879 Check that the command fails (when run via C<run_log>).
880
881 =cut
882
883 sub command_fails
884 {
885 local $Test::Builder::Level = $Test::Builder::Level + 1;
886 my ($cmd, $test_name) = @_;
887 my $result = run_log($cmd);
888 ok(!$result, $test_name);
889 return;
890 }
891
892 =pod
893
894 =item command_exit_is(cmd, expected, test_name)
895
896 Check that the command exit code matches the expected exit code.
897
898 =cut
899
900 sub command_exit_is
901 {
902 local $Test::Builder::Level = $Test::Builder::Level + 1;
903 my ($cmd, $expected, $test_name) = @_;
904 print("# Running: " . join(" ", @{$cmd}) . "\n");
905 my $h = IPC::Run::start $cmd;
906 $h->finish();
907
908 # Normally, if the child called exit(N), IPC::Run::result() returns N. On
909 # Windows, with IPC::Run v20220807.0 and earlier, full_results() is the
910 # method that returns N (https://github.com/toddr/IPC-Run/issues/161).
911 my $result =
912 ($Config{osname} eq "MSWin32" && $IPC::Run::VERSION <= 20220807.0)
913 ? ($h->full_results)[0]
914 : $h->result(0);
915 is($result, $expected, $test_name);
916 return;
917 }
918
919 =pod
920
921 =item program_help_ok(cmd)
922
923 Check that the command supports the C<--help> option.
924
925 =cut
926
927 sub program_help_ok
928 {
929 local $Test::Builder::Level = $Test::Builder::Level + 1;
930 my ($cmd) = @_;
931 my ($stdout, $stderr);
932 print("# Running: $cmd --help\n");
933 my $result = IPC::Run::run [ $cmd, '--help' ],
934 '>' => \$stdout,
935 '2>' => \$stderr;
936 ok($result, "$cmd --help exit code 0");
937 isnt($stdout, '', "$cmd --help goes to stdout");
938 is($stderr, '', "$cmd --help nothing to stderr");
939
940 # This value isn't set in stone, it reflects the current
941 # convention in use. Most output actually tries to aim for 80.
942 my $max_line_length = 95;
943 my @long_lines = grep { length > $max_line_length } split /\n/, $stdout;
944 is(scalar @long_lines, 0, "$cmd --help maximum line length")
945 or diag("These lines are too long (>$max_line_length):\n",
946 join("\n", @long_lines));
947
948 return;
949 }
950
951 =pod
952
953 =item program_version_ok(cmd)
954
955 Check that the command supports the C<--version> option.
956
957 =cut
958
959 sub program_version_ok
960 {
961 local $Test::Builder::Level = $Test::Builder::Level + 1;
962 my ($cmd) = @_;
963 my ($stdout, $stderr);
964 print("# Running: $cmd --version\n");
965 my $result = IPC::Run::run [ $cmd, '--version' ],
966 '>' => \$stdout,
967 '2>' => \$stderr;
968 ok($result, "$cmd --version exit code 0");
969 isnt($stdout, '', "$cmd --version goes to stdout");
970 is($stderr, '', "$cmd --version nothing to stderr");
971 return;
972 }
973
974 =pod
975
976 =item program_options_handling_ok(cmd)
977
978 Check that a command with an invalid option returns a non-zero
979 exit code and error message.
980
981 =cut
982
983 sub program_options_handling_ok
984 {
985 local $Test::Builder::Level = $Test::Builder::Level + 1;
986 my ($cmd) = @_;
987 my ($stdout, $stderr);
988 print("# Running: $cmd --not-a-valid-option\n");
989 my $result = IPC::Run::run [ $cmd, '--not-a-valid-option' ],
990 '>' => \$stdout,
991 '2>' => \$stderr;
992 ok(!$result, "$cmd with invalid option nonzero exit code");
993 isnt($stderr, '', "$cmd with invalid option prints error message");
994 return;
995 }
996
997 =pod
998
999 =item command_like(cmd, expected_stdout, test_name)
1000
1001 Check that the command runs successfully and the output
1002 matches the given regular expression.
1003
1004 =cut
1005
1006 sub command_like
1007 {
1008 local $Test::Builder::Level = $Test::Builder::Level + 1;
1009 my ($cmd, $expected_stdout, $test_name) = @_;
1010 my ($stdout, $stderr);
1011 print("# Running: " . join(" ", @{$cmd}) . "\n");
1012 my $result = IPC::Run::run $cmd, '>' => \$stdout, '2>' => \$stderr;
1013 ok($result, "$test_name: exit code 0");
1014 is($stderr, '', "$test_name: no stderr");
1015 like($stdout, $expected_stdout, "$test_name: matches");
1016 return;
1017 }
1018
1019 =pod
1020
1021 =item command_like_safe(cmd, expected_stdout, test_name)
1022
1023 Check that the command runs successfully and the output
1024 matches the given regular expression. Doesn't assume that the
1025 output files are closed.
1026
1027 =cut
1028
1029 sub command_like_safe
1030 {
1031 local $Test::Builder::Level = $Test::Builder::Level + 1;
1032
1033 # Doesn't rely on detecting end of file on the file descriptors,
1034 # which can fail, causing the process to hang, notably on Msys
1035 # when used with 'pg_ctl start'
1036 my ($cmd, $expected_stdout, $test_name) = @_;
1037 my ($stdout, $stderr);
1038 my $stdoutfile = File::Temp->new();
1039 my $stderrfile = File::Temp->new();
1040 print("# Running: " . join(" ", @{$cmd}) . "\n");
1041 my $result = IPC::Run::run $cmd, '>' => $stdoutfile, '2>' => $stderrfile;
1042 $stdout = slurp_file($stdoutfile);
1043 $stderr = slurp_file($stderrfile);
1044 ok($result, "$test_name: exit code 0");
1045 is($stderr, '', "$test_name: no stderr");
1046 like($stdout, $expected_stdout, "$test_name: matches");
1047 return;
1048 }
1049
1050 =pod
1051
1052 =item command_fails_like(cmd, expected_stderr, test_name)
1053
1054 Check that the command fails and the error message matches
1055 the given regular expression.
1056
1057 =cut
1058
1059 sub command_fails_like
1060 {
1061 local $Test::Builder::Level = $Test::Builder::Level + 1;
1062 my ($cmd, $expected_stderr, $test_name) = @_;
1063 my ($stdout, $stderr);
1064 print("# Running: " . join(" ", @{$cmd}) . "\n");
1065 my $result = IPC::Run::run $cmd, '>' => \$stdout, '2>' => \$stderr;
1066 ok(!$result, "$test_name: exit code not 0");
1067 like($stderr, $expected_stderr, "$test_name: matches");
1068 return;
1069 }
1070
1071 =pod
1072
1073 =item command_ok_or_fails_like(cmd, expected_stdout, expected_stderr, test_name)
1074
1075 Check that the command either succeeds or fails with an error that matches the
1076 given regular expressions.
1077
1078 =cut
1079
1080 sub command_ok_or_fails_like
1081 {
1082 local $Test::Builder::Level = $Test::Builder::Level + 1;
1083 my ($cmd, $expected_stdout, $expected_stderr, $test_name) = @_;
1084 my ($stdout, $stderr);
1085 print("# Running: " . join(" ", @{$cmd}) . "\n");
1086 my $result = IPC::Run::run $cmd, '>' => \$stdout, '2>' => \$stderr;
1087 if (!$result)
1088 {
1089 like($stdout, $expected_stdout, "$test_name: stdout matches");
1090 like($stderr, $expected_stderr, "$test_name: stderr matches");
1091 }
1092 return $result;
1093 }
1094
1095 =pod
1096
1097 =item command_checks_all(cmd, ret, out, err, test_name)
1098
1099 Run a command and check its status and outputs.
1100 Arguments:
1101
1102 =over
1103
1104 =item C<cmd>: Array reference of command and arguments to run
1105
1106 =item C<ret>: Expected exit code
1107
1108 =item C<out>: Expected stdout from command
1109
1110 =item C<err>: Expected stderr from command
1111
1112 =item C<test_name>: test name
1113
1114 =back
1115
1116 =cut
1117
1118 sub command_checks_all
1119 {
1120 local $Test::Builder::Level = $Test::Builder::Level + 1;
1121
1122 my ($cmd, $expected_ret, $out, $err, $test_name) = @_;
1123
1124 # run command
1125 my ($stdout, $stderr);
1126 print("# Running: " . join(" ", @{$cmd}) . "\n");
1127 IPC::Run::run($cmd, '>' => \$stdout, '2>' => \$stderr);
1128
1129 # See http://perldoc.perl.org/perlvar.html#%24CHILD_ERROR
1130 my $ret = $?;
1131 die "command exited with signal " . ($ret & 127)
1132 if $ret & 127;
1133 $ret = $ret >> 8;
1134
1135 # check status
1136 ok($ret == $expected_ret,
1137 "$test_name status (got $ret vs expected $expected_ret)");
1138
1139 # check stdout
1140 for my $re (@$out)
1141 {
1142 like($stdout, $re, "$test_name stdout /$re/");
1143 }
1144
1145 # check stderr
1146 for my $re (@$err)
1147 {
1148 like($stderr, $re, "$test_name stderr /$re/");
1149 }
1150
1151 return;
1152 }
1153
1154 =pod
1155
1156 =item tar_portability_options(tar)
1157
1158 Check for non-default options we need to give to tar to create
1159 a tarfile we can decode (i.e., no "pax" extensions).
1160 Not needed in tests that only use tar to read tarfiles.
1161
1162 Returns options as an array.
1163
1164 =cut
1165
1166 sub tar_portability_options
1167 {
1168 local $Test::Builder::Level = $Test::Builder::Level + 1;
1169
1170 my ($tar) = @_;
1171
1172 my @tar_p_flags = ();
1173
1174 return @tar_p_flags if (!defined $tar || $tar eq '');
1175
1176 # GNU tar typically produces gnu-format archives, which we can read fine.
1177 # But some platforms configure it to default to posix/pax format, and
1178 # apparently they enable --sparse too. Override that.
1179 #
1180 # ustar format supports UIDs only up to 2^21 - 1 (2097151). Override
1181 # owner/group to avoid failures on systems where the running user's UID/GID
1182 # exceeds that limit.
1183 my $devnull = File::Spec->devnull();
1184 if (system(
1185 "$tar --format=ustar --owner=0 --group=0 -cf $devnull $devnull 2>$devnull"
1186 ) == 0)
1187 {
1188 # GNU tar (Linux), BSD tar (FreeBSD, NetBSD, macOS, Windows)
1189 push(@tar_p_flags, "--format=ustar", "--owner=0", "--group=0");
1190 }
1191 elsif (system("$tar -F ustar -cf $devnull $devnull 2>$devnull") == 0)
1192 {
1193 # OpenBSD tar
1194 push(@tar_p_flags, "-F", "ustar");
1195 }
1196 return @tar_p_flags;
1197 }
1198
1199 =pod
1200
1201 =back
1202
1203 =cut
1204
1205 1;