3 # Tests for the command-line switches:
4 # -0, -c, -l, -s, -m, -M, -V, -v, -h, -i, -E and all unknown
5 # Some switches have their own tests, see MANIFEST.
10 require Config; import Config;
13 BEGIN { require "./test.pl"; require "./loc_tools.pl"; }
19 # due to a bug in VMS's piping which makes it impossible for runperl()
20 # to emulate echo -n (ie. stdin always winds up with a newline), these
21 # tests almost totally fail.
22 $TODO = "runperl() unable to emulate echo -n due to pipe bug" if $^O eq 'VMS';
26 END { unlink_all @tmpfiles }
31 switches => [ '-0', ],
32 stdin => 'foo\0bar\0baz\0',
33 prog => 'print qq(<$_>) while <>',
35 is( $r, "<foo\0><bar\0><baz\0>", "-0" );
38 switches => [ '-l', '-0', '-p' ],
39 stdin => 'foo\0bar\0baz\0',
42 is( $r, "foo\nbar\nbaz\n", "-0 after a -l" );
45 switches => [ '-0', '-l', '-p' ],
46 stdin => 'foo\0bar\0baz\0',
49 is( $r, "foo\0bar\0baz\0", "-0 before a -l" );
52 switches => [ sprintf("-0%o", ord 'x') ],
53 stdin => 'fooxbarxbazx',
54 prog => 'print qq(<$_>) while <>',
56 is( $r, "<foox><barx><bazx>", "-0 with octal number" );
59 switches => [ '-00', '-p' ],
60 stdin => 'abc\ndef\n\nghi\njkl\nmno\n\npq\n',
61 prog => 's/\n/-/g;$_.=q(/)',
63 is( $r, 'abc-def--/ghi-jkl-mno--/pq-/', '-00 (paragraph mode)' );
66 switches => [ '-0777', '-p' ],
67 stdin => 'abc\ndef\n\nghi\njkl\nmno\n\npq\n',
68 prog => 's/\n/-/g;$_.=q(/)',
70 is( $r, 'abc-def--ghi-jkl-mno--pq-/', '-0777 (slurp mode)' );
73 switches => [ '-066' ],
74 prog => 'BEGIN { print qq{($/)} } print qq{[$/]}',
76 is( $r, "(\066)[\066]", '$/ set at compile-time' );
80 my $filename = tempfile();
82 local $TODO = ''; # this one works on VMS
84 open my $f, ">$filename" or skip( "Can't write temp file $filename: $!" );
86 BEGIN { print "block 1\n"; }
87 CHECK { print "block 2\n"; }
88 INIT { print "block 3\n"; }
90 END { print "block 5\n"; }
92 close $f or die "Could not close: $!";
95 progfile => $filename,
98 # Because of the stderr redirection, we can't tell reliably the order
99 # in which the output is given
101 $r =~ /$filename syntax OK/
102 && $r =~ /\bblock 1\b/
103 && $r =~ /\bblock 2\b/
104 && $r !~ /\bblock 3\b/
105 && $r !~ /\bblock 4\b/
106 && $r !~ /\bblock 5\b/,
112 skip 'locales not available', 1 unless locales_enabled('LC_ALL');
114 my $tempdir = tempfile;
115 mkdir $tempdir, 0700 or die "Can't mkdir '$tempdir': $!";
117 local $ENV{'LC_ALL'} = 'C'; # Keep the test simple: expect English
118 local $ENV{LANGUAGE} = 'C';
119 setlocale(LC_ALL, "C");
121 # Win32 won't let us open the directory, so we never get to die with
122 # EISDIR, which happens after open.
124 import Errno qw(EACCES EISDIR);
126 local $! = $^O eq 'MSWin32' ? &EACCES : &EISDIR; "$!"
129 runperl( switches => [ '-c' ], args => [ $tempdir ], stderr => 1),
130 qr/Can't open perl script.*$tempdir.*\Q$error/s,
131 "RT \#61362: Cannot syntax-check a directory"
133 rmdir $tempdir or die "Can't rmdir '$tempdir': $!";
139 switches => [ sprintf("-l%o", ord 'x') ],
140 prog => 'print for qw/foo bar/'
142 is( $r, 'fooxbarx', '-l with octal number' );
147 switches => [ '-s' ],
148 prog => 'for (qw/abc def ghi/) {print defined $$_ ? $$_ : q(-)}',
149 args => [ '--', '-abc=2', '-def', ],
151 is( $r, '21-', '-s switch parsing' );
153 $filename = tempfile();
155 open my $f, ">$filename" or skip( "Can't write temp file $filename: $!" );
158 BEGIN { print $x,$y; exit }
160 close $f or die "Could not close: $!";
162 progfile => $filename,
163 args => [ '-x=foo -y' ],
165 is( $r, 'foo1', '-s on the shebang line' );
168 # Bug ID 20011106.084 (#7876)
169 $filename = tempfile();
171 open my $f, ">$filename" or skip( "Can't write temp file $filename: $!" );
174 BEGIN { print $x; exit }
176 close $f or die "Could not close: $!";
178 progfile => $filename,
179 args => [ '-x=foo' ],
181 is( $r, 'foo', '-sn on the shebang line' );
184 # Tests for -m and -M
186 my $package = tempfile();
187 $filename = "$package.pm";
189 open my $f, ">$filename" or skip( "Can't write temp file $filename: $!",4 );
190 print $f <<"SWTESTPM";
192 sub import { print map "<\$_>", \@_ }
195 close $f or die "Could not close: $!";
197 switches => [ "-I.", "-M$package" ],
200 is( $r, "<$package>", '-M' );
202 switches => [ "-I.", "-M$package=foo" ],
205 is( $r, "<$package><foo>", '-M with import parameter' );
207 switches => [ "-m$package" ],
212 local $TODO = ''; # this one works on VMS
216 switches => [ "-I.", "-m$package=foo,bar" ],
219 is( $r, "<$package><foo><bar>", '-m with import parameters' );
220 push @tmpfiles, $filename;
223 local $TODO = ''; # these work on VMS
225 is( runperl( switches => [ '-MTie::Hash' ], stderr => 1, prog => 1 ),
226 '', "-MFoo::Bar allowed" );
228 like( runperl( switches => [ "-M:$package" ], stderr => 1,
229 prog => 'die q{oops}' ),
230 qr/Invalid module name [\w:]+ with -M option\b/,
231 "-M:Foo not allowed" );
233 like( runperl( switches => [ '-mA:B:C' ], stderr => 1,
234 prog => 'die q{oops}' ),
235 qr/Invalid module name [\w:]+ with -m option\b/,
236 "-mFoo:Bar not allowed" );
238 like( runperl( switches => [ '-m-A:B:C' ], stderr => 1,
239 prog => 'die q{oops}' ),
240 qr/Invalid module name [\w:]+ with -m option\b/,
241 "-m-Foo:Bar not allowed" );
243 like( runperl( switches => [ '-m-' ], stderr => 1,
244 prog => 'die q{oops}' ),
245 qr/Module name required with -m option\b/,
248 like( runperl( switches => [ '-M-=' ], stderr => 1,
249 prog => 'die q{oops}' ),
250 qr/Module name required with -M option\b/,
252 } # disable TODO on VMS
254 is runperl(stderr => 1, prog => '#!perl -m'),
255 qq 'Too late for "-m" option at -e line 1.\n', '#!perl -m';
256 is runperl(stderr => 1, prog => '#!perl -M'),
257 qq 'Too late for "-M" option at -e line 1.\n', '#!perl -M';
262 local $TODO = ''; # these ones should work on VMS
264 # basic perl -V should generate significant output.
265 # we don't test actual format too much since it could change
266 like( runperl( switches => ['-V'] ), qr/(\n.*){20}/,
267 '-V generates 20+ lines' );
269 like( runperl( switches => ['-V'] ),
270 qr/\ASummary of my perl5 .*configuration:/,
273 # lookup a known config var
274 chomp( $r=runperl( switches => ['-V:osname'] ) );
275 is( $r, "osname='$^O';", 'perl -V:osname');
277 # lookup a nonexistent var
278 chomp( $r=runperl( switches => ['-V:this_var_makes_switches_test_fail'] ) );
279 is( $r, "this_var_makes_switches_test_fail='UNKNOWN';",
280 'perl -V:unknown var');
283 # platforms that don't like this quoting can either skip this test
284 # or fix test.pl _quote_args
285 $r = runperl( switches => ['"-V:i\D+size"'] );
286 # should be unlike( $r, qr/^$|not found|UNKNOWN/ );
287 like( $r, qr/^(?!.*(not found|UNKNOWN))./, 'perl -V:re got a result' );
289 # make sure each line we got matches the re
290 ok( !( grep !/^i\D+size=/, split /^/, $r ), '-V:re correct' );
296 local $TODO = ''; # these ones should work on VMS
297 # There may be build configs where this test will fail; DG/UX was one,
298 # but we no longer support it. Maybe we should remove these special cases?
301 skip "Win32 miniperl produces a default archname in -v", 1
302 if $^O eq 'MSWin32' && is_miniperl;
303 my $v = sprintf "%vd", $^V;
304 my $ver = $Config{PERL_VERSION};
305 my $rel = $Config{PERL_SUBVERSION};
306 like( runperl( switches => ['-v'] ),
307 qr/This is perl 5, version \Q$ver\E, subversion \Q$rel\E \(v\Q$v\E(?:[-*\w]+| \([^)]+\))?\) built for \Q$Config{archname}\E.+Copyright.+Larry Wall.+Artistic License.+GNU General Public License/s,
315 local $TODO = ''; # these ones should work on VMS
317 like( runperl( switches => ['-h'] ),
318 qr/Usage: .+(?i:perl(?:$Config{_exe})?).+switches.+programfile.+arguments/,
323 # Tests for switches which do not exist
325 foreach my $switch (split //, "ABbGgHJjKkLNOoPQqRrYyZz123456789_")
327 local $TODO = ''; # these ones should work on VMS
329 like( runperl( switches => ["-$switch"], stderr => 1,
330 prog => 'die q{oops}' ),
331 qr/\QUnrecognized switch: -$switch (-h will show valid options)./,
332 "-$switch correctly unknown" );
335 like( runperl( stderr => 1, prog => "#!perl -$switch" ),
336 qr/^Unrecognized switch: -$switch \(-h will show valid (?x:
337 )options\) at -e line 1\./,
338 "-$switch unrecognised on #! line" );
341 # Tests for unshebangable switches
342 for (qw( e f x E S V )) {
345 prog => "#!perl -$_",
347 is $r, "Can't emulate -$_ on #! line at -e line 1.\n","-$_ on #! line";
354 local $TODO = ''; # these ones should work on VMS
356 sub do_i_unlink { unlink_all("tmpswitches", "tmpswitches.bak") }
358 open(FILE, ">tmpswitches") or die "$0: Failed to create 'tmpswitches': $!";
359 my $yada = <<__EOF__;
367 END { do_i_unlink() }
369 runperl( switches => ['-pi.bak'], prog => 's/foo/bar/', args => ['tmpswitches'] );
371 open(FILE, "tmpswitches") or die "$0: Failed to open 'tmpswitches': $!";
372 chomp(my @file = <FILE>);
375 open(BAK, "tmpswitches.bak") or die "$0: Failed to open 'tmpswitches.bak': $!";
376 chomp(my @bak = <BAK>);
380 "bar yada dada:bada bar bing:king kong bar",
383 "foo yada dada:bada foo bing:king kong foo",
387 switches => ['-i.bak -p'],
394 "-i used with no filenames on the command line, reading from STDIN.\n",
395 "warning when no files given"
398 switches => ['-i.bak -p'],
402 args => ['tmpswitches'],
404 is($out2, "", "no warning when files given");
406 open my $f, ">", "tmpswitches" or die "$0: failed to create 'tmpswitches': $!";
407 print $f "foo\nbar\n";
410 # a backup extension is no longer required on any platform
412 switches => [ '-i', '-p' ],
413 prog => 's/foo/quux/',
415 args => [ 'tmpswitches' ],
417 is($out3, "", "no warnings/errors without backup extension");
418 open $f, "<", "tmpswitches" or die "$0: cannot open 'tmpswitches': $!";
419 chomp(my @out4 = <$f>);
421 is(join(":", @out4), "quux:bar", "correct output without backup extension");
423 eval { require File::Spec; 1 }
424 or skip "Cannot load File::Spec - miniperl?", 20;
426 my $tmpinplace = tempfile();
430 File::Path::rmtree($tmpinplace)
431 if $tmpinplace && -d $tmpinplace;
434 # test.pl's tempfile() doesn't create the file so we can
437 or die "Cannot create $tmpinplace: $!";
439 my $work = File::Spec->catfile($tmpinplace, "foo");
441 # exit or die should leave original content in file
442 for my $inplace (qw/-i -i.bak/) {
443 for my $prog ("die", "exit 1") {
444 open my $fh, ">", $work or die "$0: failed to open '$work': $!";
446 close $fh or die "Failed to close: $!";
448 switches => [ $inplace, '-n' ],
449 prog => "print q(foo\n); $prog",
453 open my $in, "<", $work or die "$0: failed to open '$work': $!";
454 my $data = do { local $/; <$in> };
456 is ($data, $yada, "check original content still in file");
457 unlink $work, "$work.bak";
461 # test that path parsing is correct
462 open $f, ">", $work or die "Cannot create $work: $!";
463 print $f "foo\nbar\n";
468 switches => [ "-i", "-p" ],
469 prog => 's/foo/bar/',
473 is ($out4, "", "no errors or warnings");
474 open $f, "<", $work or die "Cannot open $work: $!";
475 chomp(my @file4 = <$f>);
477 is(join(":", @file4), "bar:bar", "check output");
481 # this needs to match how ARGV_USE_ATFUNCTIONS is defined in doio.c
482 skip "Not enough *at functions", 3
483 unless $Config{d_unlinkat} && $Config{d_renameat} && $Config{d_fchmodat}
484 && ($Config{d_dirfd} || $Config{d_dir_dd_fd})
486 && $Config{ccflags} !~ /-DNO_USE_ATFUNCTIONS\b/;
487 my ($osvers) = ($Config{osvers} =~ /^(\d+(?:\.\d+)?)/);
488 skip "NetBSD 6 libc defines at functions, but they're incomplete", 3
489 if $^O eq "netbsd" && $osvers < 7;
491 @ARGV = ("tmpinplace/foo");
499 $code =~ s/tmpinplace/$tmpinplace/;
500 fresh_perl_is($code, "ok\n", { },
501 "chdir while in-place editing");
502 ok(open(my $fh, "<", $work), "open out file");
503 is(scalar <$fh>, "xx\n", "file successfully saved after chdir");
509 skip "Need threads and full perl", 3
510 if !$Config{useithreads} || is_miniperl();
515 @ARGV = ("tmpinplace/foo");
518 threads->create(sub { })->join;
523 $code =~ s/tmpinplace/$tmpinplace/;
524 fresh_perl_is($code, "ok\n", { stderr => 1 },
525 "threads while in-place editing");
526 ok(open(my $fh, "<", $work), "open out file");
527 is(scalar <$fh>, "yy\n", "file successfully saved after chdir");
533 skip "Need fork", 3 if !$Config{d_fork};
534 open my $fh, ">", $work
535 or die "Cannot open $work: $!";
536 # we want only a single line for this test, otherwise
537 # it attempts to close the file twice
539 close $fh or die "Cannot close $work: $!";
542 @ARGV = ("tmpinplace/foo");
546 if (defined $pid && !$pid) {
548 close ARGVOUT or die "Cannot close in child\n"; # this shouldn't do ARGVOUT magic
553 close ARGVOUT or die "Cannot close in parent\n"; # this should
557 $code =~ s/tmpinplace/$tmpinplace/;
558 fresh_perl_is($code, "ok\n", { stderr => 1 },
559 "fork while in-place editing");
560 ok(open($fh, "<", $work), "open out file");
561 is(scalar <$fh>, "yy\n", "file successfully saved after fork");
566 # test we handle the rename to the backup failing
568 # make it fail by creating a .bak file with a version than which no higher can be created
569 # can't make a directory because foo.bak and foo^.bak.DIR do not conflict.
570 open my $fh, '>', "$work.bak;32767" or die "Cannot make mask backup file: $!";
571 close $fh or die "Failed to close: $!";
574 # make it fail by creating a directory of the backup name
575 mkdir "$work.bak" or die "Cannot make mask backup directory: $!";
578 @ARGV = ("tmpinplace/foo");
585 $code =~ s/tmpinplace/$tmpinplace/;
586 fresh_perl_like($code, qr/Can't rename/, { stderr => 1 }, "fail backup rename");
588 1 while unlink "$work.bak";
591 rmdir "$work.bak" or die "Cannot remove mask backup directory: $!";
596 # test with absolute paths, this was failing on FreeBSD 11ish due
597 # to a bug in renameat()
598 my $abs_work = File::Spec->rel2abs($work);
599 fresh_perl_is(<<'CODE', "",
604 { stderr => 1, args => [ $abs_work ], switches => [ "-i" ] },
608 # we now use temp files for in-place editing, make sure we didn't leave
609 # any behind in the above test
610 opendir my $d, $tmpinplace or die "Cannot opendir $tmpinplace: $!";
611 my @names = grep !/^\.\.?$/ && $_ ne 'foo' && $_ ne 'foo.', readdir $d;
613 is(scalar(@names), 0, "no extra files")
614 or diag "Found @names, expected none";
616 # the following tests might leave work files behind
618 # this test can leave the work file in the directory, since making
619 # the directory non-writable also prevents removing the work file
622 # test we handle the rename of the work to the original failing
623 # make it fail by removing write perms from the directory
624 # but first check that doesn't prevent writing
625 chmod 0500, $tmpinplace;
626 my $check = File::Spec->catfile($tmpinplace, "check");
627 my $canwrite = open my $fh, ">", $check;
629 chmod 0700, $tmpinplace or die "Cannot make $tmpinplace writable again: $!";
630 skip "Cannot make $tmpinplace read only", 1
633 @ARGV = ("tmpinplace/foo");
636 chmod 0500, "tmpinplace";
641 $code =~ s/tmpinplace/$tmpinplace/g;
642 fresh_perl_like($code, qr/failed to rename/, { stderr => 1 }, "fail final rename");
643 chmod 0700, $tmpinplace or die "Cannot make $tmpinplace writable again: $!";
648 # this needs to reverse match how ARGV_USE_ATFUNCTIONS is defined in doio.c
649 skip "Testing without *at functions", 1
650 if $Config{d_unlinkat} && $Config{d_renameat} && $Config{d_fchmodat}
651 && ($Config{d_dirfd} || $Config{d_dir_dd_fd})
653 && $Config{ccflags} !~ /-DNO_USE_ATFUNCTIONS\b/;
655 @ARGV = ("tmpinplace/foo");
663 $code =~ s/tmpinplace/$tmpinplace/;
664 fresh_perl_like($code, qr/^Cannot complete in-place edit of \Q$tmpinplace\E\/foo: .* - line 5, <> line \d+\./, { },
665 "chdir while in-place editing (no at-functions)");
670 opendir $d, $tmpinplace or die "Cannot opendir $tmpinplace: $!";
671 @names = grep !/^\.\.?$/ && !/foo$/aai, readdir $d;
674 # clean up in case the above failed
675 unlink map File::Spec->catfile($tmpinplace, $_), @names;
683 $TODO = ''; # the -E tests work on VMS
686 switches => [ '-E', '"say q(Hello, world!)"']
688 is( $r, "Hello, world!\n", "-E say" );
692 switches => [ '-E', '"no warnings q{experimental::smartmatch}; undef ~~ undef and say q(Hello, world!)"']
694 is( $r, "Hello, world!\n", "-E ~~" );
697 switches => [ '-E', '"no warnings q{experimental::smartmatch}; given(undef) {when(undef) { say q(Hello, world!)"}}']
699 is( $r, "Hello, world!\n", "-E given" );
702 switches => [ '-nE', q("} END { say q/affe/") ],
705 is( $r, "affe\n", '-E works outside of the block created by -n' );
708 switches => [ '-E', q("*{'bar'} = sub{}; print 'Hello, world!',qq|\n|;")]
710 is( $r, "Hello, world!\n", "-E does not enable strictures" );
714 $filename = tempfile();
716 open my $f, ">$filename" or skip( "Can't write temp file $filename: $!" );
721 close $f or die "Could not close: $!";
723 progfile => $filename,
725 like( $r, qr/ok/, 'Spaces on the #! line (#30660)' );