This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
join() with an empty list and undef separator may not warn in the future
[perl5.git] / t / op / filetest.t
1 #!./perl
2
3 # There are few filetest operators that are portable enough to test.
4 # See pod/perlport.pod for details.
5
6 BEGIN {
7     chdir 't' if -d 't';
8     @INC = '../lib';
9     require './test.pl';
10 }
11
12 plan(tests => 53 + 27*14);
13
14 # Tests presume we are in t/op directory and that file 'TEST' is found
15 # therein.
16 is(-d 'op', 1, "-d: directory correctly identified");
17 is(-f 'TEST', 1, "-f: plain file correctly identified");
18 isnt(-f 'op', 1, "-f: directory is not a plain file");
19 isnt(-d 'TEST', 1, "-d: plain file is not a directory");
20 is(-r 'TEST', 1, "-r: file readable by effective uid/gid not found");
21
22 # Make a read only file. This happens to be empty, so we also use it later.
23 my $ro_empty_file = tempfile();
24
25 {
26     open my $fh, '>', $ro_empty_file or die "open $fh: $!";
27     close $fh or die "close $fh: $!";
28 }
29
30 chmod 0555, $ro_empty_file or die "chmod 0555, '$ro_empty_file' failed: $!";
31
32 SKIP: {
33     my $restore_root;
34     if ($> == 0) {
35         # root can read and write anything, so switch uid (may not be
36         # implemented)
37         eval '$> = 1';
38
39         skip("Can't drop root privs to test read-only files") if $> == 0;
40         note("Dropped root privs to test read-only files. \$> == $>");
41         ++$restore_root;
42     }
43
44     isnt(-w $ro_empty_file, 1, "-w: file writable by effective uid/gid");
45
46     if ($restore_root) {
47         # If the previous assignment to $> worked, so should this:
48         $> = 0;
49         note("Restored root privs after testing read-only files. \$> == $>");
50     }
51 }
52
53 # these would fail for the euid 1
54 # (unless we have unpacked the source code as uid 1...)
55 is(-r 'op', 1, "-r: directory readable by effective uid/gid");
56 is(-w 'op', 1, "-w: directory writable by effective uid/gid");
57 is(-x 'op', 1, "-x: executable by effective uid/gid"); # Hohum.  Are directories -x everywhere?
58
59 is( "@{[grep -r, qw(foo io noo op zoo)]}", "io op",
60     "-r: found directories readable by effective uid/gid" );
61
62 # Test stackability of filetest operators
63
64 is(defined( -f -d 'TEST' ), 1, "-f and -d stackable: plain file found");
65 isnt(-f -d _, 1, "-f and -d stackable: no plain file found");
66 isnt(defined( -e 'zoo' ), 1, "-e: file does not exist");
67 isnt(defined( -e -d 'zoo' ), 1, "-e and -d: neither file nor directory exists");
68 isnt(defined( -f -e 'zoo' ), 1, "-f and -e: not a plain file and does not exist");
69 is(-f -e 'TEST', 1, "-f and -e: plain file and exists");
70 is(-e -f 'TEST', 1, "-e and -f: exists and is plain file");
71 is(defined(-d -e 'TEST'), 1, "-d and -e: file at least exists");
72 is(defined(-e -d 'TEST'), 1, "-e and -d: file at least exists");
73 isnt( -f -d 'op', 1, "-f and -d: directory found but is not a plain file");
74 is(-x -d -x 'op', 1, "-x, -d and -x again: directory exists and is executable");
75 my ($size) = (stat 'TEST')[7];
76 cmp_ok($size, '>', 1, 'TEST is longer than 1 byte');
77 is( (-s -f 'TEST'), $size, "-s returns real size" );
78 is(-f -s 'TEST', 1, "-f and -s: plain file with non-zero size");
79
80 # now with an empty file
81 is(-f $ro_empty_file, 1, "-f: plain file found");
82 is(-s $ro_empty_file, 0, "-s: file has 0 bytes");
83 is(-f -s $ro_empty_file, 0, "-f and -s: plain file with 0 bytes");
84 is(-s -f $ro_empty_file, 0, "-s and -f: file with 0 bytes is plain file");
85
86 # stacked -l
87 eval { -l -e "TEST" };
88 like $@, qr/^The stat preceding -l _ wasn't an lstat at /,
89   'stacked -l non-lstat error with warnings off';
90 {
91  local $^W = 1;
92  eval { -l -e "TEST" };
93  like $@, qr/^The stat preceding -l _ wasn't an lstat at /,
94   'stacked -l non-lstat error with warnings on';
95 }
96 # Make sure -l is using the previous stat buffer, and not using the previ-
97 # ous op’s return value as a file name.
98 # t/TEST can be a symlink under -Dmksymlinks, so use our temporary file.
99 SKIP: {
100  use Perl::OSType 'os_type';
101  if (os_type ne 'Unix') { skip "Not Unix", 3 }
102  chomp(my $ln = `which ln`);
103  if ( ! -e $ln ) { skip "No ln"   , 3 }
104  lstat $ro_empty_file;
105  `ln -s $ro_empty_file 1`;
106  isnt(-l -e _, 1, 'stacked -l uses previous stat, not previous retval');
107  unlink 1;
108
109  # Since we already have our skip block set up, we might as well put this
110  # test here, too:
111  # -l always treats a non-bareword argument as a file name
112  system 'ln', '-s', $ro_empty_file, \*foo;
113  local $^W = 1;
114  my @warnings;
115  local $SIG{__WARN__} = sub { push @warnings, @_ };
116  is(-l \*foo, 1, '-l \*foo is a file name');
117  ok($warnings[0] =~ /-l on filehandle foo/, 'warning for -l $handle');
118  unlink \*foo;
119 }
120 # More -l $handle warning tests
121 {
122  local $^W = 1;
123  my @warnings;
124  local $SIG{__WARN__} = sub { push @warnings, @_ };
125  () = -l \*{"\x{3c6}oo"};
126  like($warnings[0], qr/-l on filehandle \x{3c6}oo/,
127   '-l $handle warning is utf8-clean');
128  () = -l *foo;
129  like($warnings[1], qr/-l on filehandle foo/,
130   '-l $handle warning occurs for globs, not just globrefs');
131  tell foo; # vivify the IO slot
132  () = -l *foo{IO};
133     # (element [3] because tell also warns)
134  like($warnings[3], qr/-l on filehandle at/,
135   '-l $handle warning occurs for iorefs as well');
136
137
138 # test that _ is a bareword after filetest operators
139
140 -f 'TEST';
141 is(-f _, 1, "_ is bareword after filetest operator");
142 sub _ { "this is not a file name" }
143 is(-f _, 1, "_ is bareword after filetest operator");
144
145 my $over;
146 {
147     package OverFtest;
148
149     use overload 
150         fallback => 1,
151         -X => sub { 
152             $over = [qq($_[0]), $_[1]];
153             "-$_[1]"; 
154         };
155 }
156 {
157     package OverString;
158
159     # No fallback. -X should fall back to string overload even without
160     # it.
161     use overload q/""/ => sub { $over = 1; "TEST" };
162 }
163 {
164     package OverBoth;
165
166     use overload
167         q/""/   => sub { "TEST" },
168         -X      => sub { "-$_[1]" };
169 }
170 {
171     package OverNeither;
172
173     # Need fallback. Previous versions of perl required 'fallback' to do
174     # -X operations on an object with no "" overload.
175     use overload 
176         '+' => sub { 1 },
177         fallback => 1;
178 }
179
180 my $ft = bless [], "OverFtest";
181 my $ftstr = qq($ft);
182 my $str = bless [], "OverString";
183 my $both = bless [], "OverBoth";
184 my $neither = bless [], "OverNeither";
185 my $nstr = qq($neither);
186
187 open my $gv, "<", "TEST";
188 bless $gv, "OverString";
189 open my $io, "<", "TEST";
190 $io = *{$io}{IO};
191 bless $io, "OverString";
192
193 my $fcntl_not_available;
194 eval { require Fcntl } or $fcntl_not_available = 1;
195
196 for my $op (split //, "rwxoRWXOezsfdlpSbctugkTMBAC") {
197     $over = [];
198     my $rv = eval "-$op \$ft";
199     isnt( $rv, undef,               "overloaded -$op succeeds" )
200         or diag( $@ );
201     is( $over->[0], $ftstr,         "correct object for overloaded -$op" );
202     is( $over->[1], $op,            "correct op for overloaded -$op" );
203     is( $rv,        "-$op",         "correct return value for overloaded -$op");
204
205     my ($exp, $is) = (1, "is");
206     if (
207         !$fcntl_not_available and (
208         $op eq "u" and not eval { Fcntl::S_ISUID() } or
209         $op eq "g" and not eval { Fcntl::S_ISGID() } or
210         $op eq "k" and not eval { Fcntl::S_ISVTX() }
211         )
212     ) {
213         ($exp, $is) = (0, "not");
214     }
215
216     $over = 0;
217     $rv = eval "-$op \$str";
218     is($@, "",                      "-$op succeeds with string overloading");
219     is( $rv, eval "-$op 'TEST'",    "correct -$op on string overload" );
220     is( $over,      $exp,           "string overload $is called for -$op" );
221
222     ($exp, $is) = $op eq "l" ? (1, "is") : (0, "not");
223
224     $over = 0;
225     eval "-$op \$gv";
226     is( $over,      $exp,   "string overload $is called for -$op on GLOB" );
227
228     # IO refs always get string overload called. This might be a bug.
229     $op eq "t" || $op eq "T" || $op eq "B"
230         and ($exp, $is) = (1, "is");
231
232     $over = 0;
233     eval "-$op \$io";
234     is( $over,      $exp,   "string overload $is called for -$op on IO");
235
236     $rv = eval "-$op \$both";
237     is( $rv,        "-$op",         "correct -$op on string/-X overload" );
238
239     $rv = eval "-$op \$neither";
240     is($@, "",                      "-$op succeeds with random overloading");
241     is( $rv, eval "-$op \$nstr",    "correct -$op with random overloading" );
242
243     is( eval "-r -$op \$ft", "-r",      "stacked overloaded -$op" );
244     is( eval "-$op -r \$ft", "-$op",    "overloaded stacked -$op" );
245 }
246
247 # -l stack corruption: this bug occurred from 5.8 to 5.14
248 {
249  push my @foo, "bar", -l baz;
250  is $foo[0], "bar", '-l bareword does not corrupt the stack';
251 }
252
253 # -l and fatal warnings
254 stat "test.pl";
255 eval { use warnings FATAL => io; -l cradd };
256 isnt(stat _, 1,
257      'fatal warnings do not prevent -l HANDLE from setting stat status');
258
259 # File test ops should not call get-magic on the topmost SV on the stack if
260 # it belongs to another op.
261 {
262   my $w;
263   sub oon::TIESCALAR{bless[],'oon'}
264   sub oon::FETCH{$w++}
265   tie my $t, 'oon';
266   push my @a, $t, -t;
267   is $w, 1, 'file test does not call FETCH on stack item not its own';
268 }
269
270 # -T and -B
271
272 my $Perl = which_perl();
273
274 SKIP: {
275     skip "no -T on filehandles", 8 unless eval { -T STDERR; 1 };
276
277     # Test that -T HANDLE sets the last stat type
278     -l "perl.c";   # last stat type is now lstat
279     -T STDERR;     # should set it to stat, since -T does a stat
280     eval { -l _ }; # should die, because the last stat type is not lstat
281     like $@, qr/^The stat preceding -l _ wasn't an lstat at /,
282         '-T HANDLE sets the stat type';
283
284     # statgv should be cleared when freed
285     fresh_perl_is
286         'open my $fh, "test.pl"; -r $fh; undef $fh; open my $fh2, '
287         . "q\0$Perl\0; print -B _",
288         '',
289         { switches => ['-l'] },
290         'PL_statgv should not point to freed-and-reused SV';
291
292     # or coerced into a non-glob
293     fresh_perl_is
294         'open Fh, "test.pl"; -r($h{i} = *Fh); $h{i} = 3; undef %h;'
295         . 'open my $fh2, ' . "q\0" . which_perl() . "\0; print -B _",
296         '',
297         { switches => ['-l'] },
298         'PL_statgv should not point to coerced-freed-and-reused GV';
299
300     # -T _ should work after stat $ioref
301     open my $fh, 'test.pl';
302     stat $Perl; # a binary file
303     stat *$fh{IO};
304     is(-T _, 1, '-T _ works after stat $ioref');
305
306     # and after -r $ioref
307     -r *$fh{IO};
308     is(-T _, 1, '-T _ works after -r $ioref');
309
310     # -T _ on closed filehandle should still reset stat info
311     stat $fh;
312     close $fh;
313     -T _;
314     isnt(stat _, 1, '-T _ on closed filehandle resets stat info');
315
316     lstat "test.pl";
317     -T $fh; # closed
318     eval { lstat _ };
319     like $@, qr/^The stat preceding lstat\(\) wasn't an lstat at /,
320         '-T on closed handle resets last stat type';
321
322     # Fatal warnings should not affect the setting of errno.
323     $! = 7;
324     -T cradd;
325     my $errno = $!;
326     $! = 7;
327     eval { use warnings FATAL => unopened; -T cradd };
328     my $errno2 = $!;
329     is $errno2, $errno,
330         'fatal warnings do not affect errno after -T BADHADNLE';
331 }
332
333 is runperl(prog => '-T _', switches => ['-w'], stderr => 1), "",
334   'no uninit warnings from -T with no preceding stat';
335
336 SKIP: {
337     my $rand_file_name = 'filetest-' . rand =~ y/.//dr;
338     if (-e $rand_file_name) { skip "File $rand_file_name exists", 1 }
339     stat 'test.pl';
340     -T $rand_file_name;
341     isnt(stat _, 1, '-T "nonexistent" resets stat success status');
342 }
343
344 # Unsuccessful filetests on filehandles should leave stat buffers in the
345 # same state whether fatal warnings are on or off.
346 {
347     stat "test.pl";
348     # This GV has no IO
349     -r *phlon;
350     my $failed_stat1 = stat _;
351
352     stat "test.pl";
353     eval { use warnings FATAL => unopened; -r *phlon };
354     my $failed_stat2 = stat _;
355
356     is $failed_stat2, $failed_stat1,
357         'failed -r($gv_without_io) with and w/out fatal warnings';
358
359     stat "test.pl";
360     -r cength;  # at compile time autovivifies IO, but with no fp
361     $failed_stat1 = stat _;
362
363     stat "test.pl";
364     eval { use warnings FATAL => unopened; -r cength };
365     $failed_stat2 = stat _;
366     
367     is $failed_stat2, $failed_stat1,
368         'failed -r($gv_with_io_but_no_fp) with and w/out fatal warnings';
369