This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Get t/uni/cache.t working under minitest
[perl5.git] / t / op / stat.t
1 #!./perl
2
3 BEGIN {
4     chdir 't' if -d 't';
5     @INC = '../lib';
6     require './test.pl';        # for which_perl() etc
7 }
8
9 use Config;
10
11 my ($Null, $Curdir);
12 if(eval {require File::Spec; 1}) {
13     $Null = File::Spec->devnull;
14     $Curdir = File::Spec->curdir;
15 } else {
16     die $@ unless is_miniperl();
17     $Curdir = '.';
18     diag("miniperl failed to load File::Spec, error is:\n$@");
19     diag("\ncontinuing, assuming '.' for current directory. Some tests will be skipped.");
20 }
21
22
23 plan tests => 113;
24
25 my $Perl = which_perl();
26
27 $ENV{LC_ALL}   = 'C';           # Forge English error messages.
28 $ENV{LANGUAGE} = 'C';           # Ditto in GNU.
29
30 $Is_Amiga   = $^O eq 'amigaos';
31 $Is_Cygwin  = $^O eq 'cygwin';
32 $Is_Darwin  = $^O eq 'darwin';
33 $Is_Dos     = $^O eq 'dos';
34 $Is_MSWin32 = $^O eq 'MSWin32';
35 $Is_NetWare = $^O eq 'NetWare';
36 $Is_OS2     = $^O eq 'os2';
37 $Is_Solaris = $^O eq 'solaris';
38 $Is_VMS     = $^O eq 'VMS';
39 $Is_MPRAS   = $^O =~ /svr4/ && -f '/etc/.relid';
40 $Is_Android = $^O =~ /android/;
41
42 $Is_Dosish  = $Is_Dos || $Is_OS2 || $Is_MSWin32 || $Is_NetWare;
43
44 $Is_UFS     = $Is_Darwin && (() = `df -t ufs . 2>/dev/null`) == 2;
45
46 if ($Is_Cygwin && !is_miniperl) {
47   require Win32;
48   Win32->import;
49 }
50
51 my($DEV, $INO, $MODE, $NLINK, $UID, $GID, $RDEV, $SIZE,
52    $ATIME, $MTIME, $CTIME, $BLKSIZE, $BLOCKS) = (0..12);
53
54 my $tmpfile = tempfile();
55 my $tmpfile_link = tempfile();
56
57 chmod 0666, $tmpfile;
58 unlink_all $tmpfile;
59 open(FOO, ">$tmpfile") || DIE("Can't open temp test file: $!");
60 close FOO;
61
62 open(FOO, ">$tmpfile") || DIE("Can't open temp test file: $!");
63
64 my($nlink, $mtime, $ctime) = (stat(FOO))[$NLINK, $MTIME, $CTIME];
65
66 # The clock on a network filesystem might be different from the
67 # system clock.
68 my $Filesystem_Time_Offset = abs($mtime - time); 
69
70 #nlink should if link support configured in Perl.
71 SKIP: {
72     skip "No link count - Hard link support not built in.", 1
73         unless $Config{d_link};
74
75     is($nlink, 1, 'nlink on regular file');
76 }
77
78 SKIP: {
79   skip "mtime and ctime not reliable", 2
80     if $Is_MSWin32 or $Is_NetWare or $Is_Cygwin or $Is_Dos or $Is_Darwin;
81
82   ok( $mtime,           'mtime' );
83   is( $mtime, $ctime,   'mtime == ctime' );
84 }
85
86
87 # Cygwin seems to have a 3 second granularity on its timestamps.
88 my $funky_FAT_timestamps = $Is_Cygwin;
89 sleep 3 if $funky_FAT_timestamps;
90
91 print FOO "Now is the time for all good men to come to.\n";
92 close(FOO);
93
94 sleep 2;
95
96 my $has_link = 1;
97 my $inaccurate_atime = 0;
98 if (defined &Win32::IsWinNT && Win32::IsWinNT()) {
99     if (Win32::FsType() ne 'NTFS') {
100         $has_link            = 0;
101         $inaccurate_atime    = 1;
102     }
103 }
104
105 SKIP: {
106     skip "No link on this filesystem", 6 unless $has_link;
107     unlink $tmpfile_link;
108     my $lnk_result = eval { link $tmpfile, $tmpfile_link };
109     skip "link() unimplemented", 6 if $@ =~ /unimplemented/;
110
111     is( $@, '',         'link() implemented' );
112     ok( $lnk_result,    'linked tmp testfile' );
113     ok( chmod(0644, $tmpfile),             'chmoded tmp testfile' );
114
115     my($nlink, $mtime, $ctime) = (stat($tmpfile))[$NLINK, $MTIME, $CTIME];
116
117     SKIP: {
118         skip "No link count", 1 if $Config{dont_use_nlink};
119         skip "Cygwin9X fakes hard links by copying", 1
120           if $Config{myuname} =~ /^cygwin_(?:9\d|me)\b/i;
121
122         is($nlink, 2,     'Link count on hard linked file' );
123     }
124
125     SKIP: {
126         skip_if_miniperl("File::Spec not built for minitest", 2);
127         my $cwd = File::Spec->rel2abs($Curdir);
128         skip "Solaris tmpfs has different mtime/ctime link semantics", 2
129                                      if $Is_Solaris and $cwd =~ m#^/tmp# and
130                                         $mtime && $mtime == $ctime;
131         skip "AFS has different mtime/ctime link semantics", 2
132                                      if $cwd =~ m#$Config{'afsroot'}/#;
133         skip "AmigaOS has different mtime/ctime link semantics", 2
134                                      if $Is_Amiga;
135         # Win32 could pass $mtime test but as FAT and NTFS have
136         # no ctime concept $ctime is ALWAYS == $mtime
137         # expect netware to be the same ...
138         skip "No ctime concept on this OS", 2
139                                      if $Is_MSWin32 || 
140                                         ($Is_Darwin && $Is_UFS);
141
142         if( !ok($mtime, 'hard link mtime') ||
143             !isnt($mtime, $ctime, 'hard link ctime != mtime') ) {
144             print STDERR <<DIAG;
145 # Check if you are on a tmpfs of some sort.  Building in /tmp sometimes
146 # has this problem.  Building on the ClearCase VOBS filesystem may also
147 # cause this failure.
148 #
149 # Darwin's UFS doesn't have a ctime concept, and thus is expected to fail
150 # this test.
151 DIAG
152         }
153     }
154
155 }
156
157 # truncate and touch $tmpfile.
158 open(F, ">$tmpfile") || DIE("Can't open temp test file: $!");
159 ok(-z \*F,     '-z on empty filehandle');
160 ok(! -s \*F,   '   and -s');
161 close F;
162
163 ok(-z $tmpfile,     '-z on empty file');
164 ok(! -s $tmpfile,   '   and -s');
165
166 open(F, ">$tmpfile") || DIE("Can't open temp test file: $!");
167 print F "hi\n";
168 close F;
169
170 open(F, "<$tmpfile") || DIE("Can't open temp test file: $!");
171 ok(!-z *F,     '-z on empty filehandle');
172 ok( -s *F,   '   and -s');
173 close F;
174
175 ok(! -z $tmpfile,   '-z on non-empty file');
176 ok(-s $tmpfile,     '   and -s');
177
178
179 # Strip all access rights from the file.
180 ok( chmod(0000, $tmpfile),     'chmod 0000' );
181
182 SKIP: {
183     skip "-r, -w and -x have different meanings on VMS", 3 if $Is_VMS;
184
185     SKIP: {
186         # Going to try to switch away from root.  Might not work.
187         my $olduid = $>;
188         eval { $> = 1; };
189         skip "Can't test if an admin user in miniperl", 2,
190           if $Is_Cygwin && is_miniperl();
191         skip "Can't test -r or -w meaningfully if you're superuser", 2
192           if ($Is_Cygwin ? Win32::IsAdminUser : $> == 0);
193
194         SKIP: {
195             skip "Can't test -r meaningfully?", 1 if $Is_Dos;
196             ok(!-r $tmpfile,    "   -r");
197         }
198
199         ok(!-w $tmpfile,    "   -w");
200
201         # switch uid back (may not be implemented)
202         eval { $> = $olduid; };
203     }
204
205     ok(! -x $tmpfile,   '   -x');
206 }
207
208
209
210 ok(chmod(0700,$tmpfile),    'chmod 0700');
211 ok(-r $tmpfile,     '   -r');
212 ok(-w $tmpfile,     '   -w');
213
214 SKIP: {
215     skip "-x simply determines if a file ends in an executable suffix", 1
216       if $Is_Dosish;
217
218     ok(-x $tmpfile,     '   -x');
219 }
220
221 ok(  -f $tmpfile,   '   -f');
222 ok(! -d $tmpfile,   '   !-d');
223
224 # Is this portable?
225 ok(  -d '.',          '-d cwd' );
226 ok(! -f '.',          '!-f cwd' );
227
228
229 SKIP: {
230     unlink($tmpfile_link);
231     my $symlink_rslt = eval { symlink $tmpfile, $tmpfile_link };
232     skip "symlink not implemented", 3 if $@ =~ /unimplemented/;
233
234     is( $@, '',     'symlink() implemented' );
235     ok( $symlink_rslt,      'symlink() ok' );
236     ok(-l $tmpfile_link,    '-l');
237 }
238
239 ok(-o $tmpfile,     '-o');
240
241 ok(-e $tmpfile,     '-e');
242
243 unlink($tmpfile_link);
244 ok(! -e $tmpfile_link,  '   -e on unlinked file');
245
246 SKIP: {
247     skip "No character, socket or block special files", 6
248       if $Is_MSWin32 || $Is_NetWare || $Is_Dos;
249     skip "/dev isn't available to test against", 6
250       unless -d '/dev' && -r '/dev' && -x '/dev';
251     skip "Skipping: unexpected ls output in MP-RAS", 6
252       if $Is_MPRAS;
253
254     # VMS problem:  If GNV or other UNIX like tool is installed, then
255     # sometimes Perl will find /bin/ls, and will try to run it.
256     # But since Perl on VMS does not know to run it under Bash, it will
257     # try to run the DCL verb LS.  And if the VMS product Language
258     # Sensitive Editor is installed, or some other LS verb, that will
259     # be run instead.  So do not do this until we can teach Perl
260     # when to use BASH on VMS.
261     skip "ls command not available to Perl in OpenVMS right now.", 6
262       if $Is_VMS;
263
264     delete $ENV{CLICOLOR_FORCE};
265     my $LS  = $Config{d_readlink} && !$Is_Android ? "ls -lL" : "ls -l";
266     my $CMD = "$LS /dev 2>/dev/null";
267     my $DEV = qx($CMD);
268
269     skip "$CMD failed", 6 if $DEV eq '';
270
271     my @DEV = do { my $dev; opendir($dev, "/dev") ? readdir($dev) : () };
272
273     skip "opendir failed: $!", 6 if @DEV == 0;
274
275     # /dev/stdout might be either character special or a named pipe,
276     # or a symlink, or a socket, depending on which OS and how are
277     # you running the test, so let's censor that one away.
278     # Similar remarks hold for stderr.
279     $DEV =~ s{^[cpls].+?\sstdout$}{}m;
280     @DEV =  grep { $_ ne 'stdout' } @DEV;
281     $DEV =~ s{^[cpls].+?\sstderr$}{}m;
282     @DEV =  grep { $_ ne 'stderr' } @DEV;
283
284     # /dev/printer is also naughty: in IRIX it shows up as
285     # Srwx-----, not srwx------.
286     $DEV =~ s{^.+?\sprinter$}{}m;
287     @DEV =  grep { $_ ne 'printer' } @DEV;
288
289     # If running as root, we will see .files in the ls result,
290     # and readdir() will see them always.  Potential for conflict,
291     # so let's weed them out.
292     $DEV =~ s{^.+?\s\..+?$}{}m;
293     @DEV =  grep { ! m{^\..+$} } @DEV;
294
295     # Irix ls -l marks sockets with 'S' while 's' is a 'XENIX semaphore'.
296     if ($^O eq 'irix') {
297         $DEV =~ s{^S(.+?)}{s$1}mg;
298     }
299
300     my $try = sub {
301         my @c1 = eval qq[\$DEV =~ /^$_[0].*/mg];
302         my @c2 = eval qq[grep { $_[1] "/dev/\$_" } \@DEV];
303         my $c1 = scalar @c1;
304         my $c2 = scalar @c2;
305         is($c1, $c2, "ls and $_[1] agreeing on /dev ($c1 $c2)");
306     };
307
308 {
309     $try->('b', '-b');
310     $try->('c', '-c');
311     $try->('s', '-S');
312 }
313
314 ok(! -b $Curdir,    '!-b cwd');
315 ok(! -c $Curdir,    '!-c cwd');
316 ok(! -S $Curdir,    '!-S cwd');
317
318 }
319
320 SKIP: {
321     my($cnt, $uid);
322     $cnt = $uid = 0;
323
324     # Find a set of directories that's very likely to have setuid files
325     # but not likely to be *all* setuid files.
326     my @bin = grep {-d && -r && -x} qw(/sbin /usr/sbin /bin /usr/bin);
327     skip "Can't find a setuid file to test with", 3 unless @bin;
328
329     for my $bin (@bin) {
330         opendir BIN, $bin or die "Can't opendir $bin: $!";
331         while (defined($_ = readdir BIN)) {
332             $_ = "$bin/$_";
333             $cnt++;
334             $uid++ if -u;
335             last if $uid && $uid < $cnt;
336         }
337     }
338     closedir BIN;
339
340     skip "No setuid programs", 3 if $uid == 0;
341
342     isnt($cnt, 0,    'found some programs');
343     isnt($uid, 0,    '  found some setuid programs');
344     ok($uid < $cnt,  "    they're not all setuid");
345 }
346
347
348 # To assist in automated testing when a controlling terminal (/dev/tty)
349 # may not be available (at, cron  rsh etc), the PERL_SKIP_TTY_TEST env var
350 # can be set to skip the tests that need a tty.
351 SKIP: {
352     skip "These tests require a TTY", 4 if $ENV{PERL_SKIP_TTY_TEST};
353
354     my $TTY = "/dev/tty";
355
356     SKIP: {
357         skip "Test uses unixisms", 2 if $Is_MSWin32 || $Is_NetWare;
358         skip "No TTY to test -t with", 2 unless -e $TTY;
359
360         open(TTY, $TTY) ||
361           warn "Can't open $TTY--run t/TEST outside of make.\n";
362         ok(-t TTY,  '-t');
363         ok(-c TTY,  'tty is -c');
364         close(TTY);
365     }
366     ok(! -t TTY,    '!-t on closed TTY filehandle');
367
368     {
369         local $TODO = 'STDIN not a tty when output is to pipe' if $Is_VMS;
370         ok(-t,          '-t on STDIN');
371     }
372 }
373
374 SKIP: {
375     skip "No null device to test with", 1 unless -e $Null;
376     skip "We know Win32 thinks '$Null' is a TTY", 1 if $Is_MSWin32;
377
378     open(NULL, $Null) or DIE("Can't open $Null: $!");
379     ok(! -t NULL,   'null device is not a TTY');
380     close(NULL);
381 }
382
383
384 # These aren't strictly "stat" calls, but so what?
385 my $statfile = './op/stat.t';
386 ok(  -T $statfile,    '-T');
387 ok(! -B $statfile,    '!-B');
388 ok(-B $Perl,      '-B');
389 ok(! -T $Perl,    '!-T');
390
391 open(FOO,$statfile);
392 SKIP: {
393     eval { -T FOO; };
394     skip "-T/B on filehandle not implemented", 15 if $@ =~ /not implemented/;
395
396     is( $@, '',     '-T on filehandle causes no errors' );
397
398     ok(-T FOO,      '   -T');
399     ok(! -B FOO,    '   !-B');
400
401     $_ = <FOO>;
402     like($_, qr/perl/, 'after readline');
403     ok(-T FOO,      '   still -T');
404     ok(! -B FOO,    '   still -B');
405     close(FOO);
406
407     open(FOO,$statfile);
408     $_ = <FOO>;
409     like($_, qr/perl/,      'reopened and after readline');
410     ok(-T FOO,      '   still -T');
411     ok(! -B FOO,    '   still !-B');
412
413     ok(seek(FOO,0,0),   'after seek');
414     ok(-T FOO,          '   still -T');
415     ok(! -B FOO,        '   still !-B');
416
417     # It's documented this way in perlfunc *shrug*
418     () = <FOO>;
419     ok(eof FOO,         'at EOF');
420     ok(-T FOO,          '   still -T');
421     ok(-B FOO,          '   now -B');
422 }
423 close(FOO);
424
425
426 SKIP: {
427     skip "No null device to test with", 2 unless -e $Null;
428
429     ok(-T $Null,  'null device is -T');
430     ok(-B $Null,  '    and -B');
431 }
432
433
434 # and now, a few parsing tests:
435 $_ = $tmpfile;
436 ok(-f,      'bare -f   uses $_');
437 ok(-f(),    '     -f() "');
438
439 unlink $tmpfile or print "# unlink failed: $!\n";
440
441 # bug id 20011101.069
442 my @r = \stat($Curdir);
443 is(scalar @r, 13,   'stat returns full 13 elements');
444
445 stat $0;
446 eval { lstat _ };
447 like( $@, qr/^The stat preceding lstat\(\) wasn't an lstat/,
448     'lstat _ croaks after stat' );
449 eval { lstat *_ };
450 like( $@, qr/^The stat preceding lstat\(\) wasn't an lstat/,
451     'lstat *_ croaks after stat' );
452 eval { lstat \*_ };
453 like( $@, qr/^The stat preceding lstat\(\) wasn't an lstat/,
454     'lstat \*_ croaks after stat' );
455 eval { -l _ };
456 like( $@, qr/^The stat preceding -l _ wasn't an lstat/,
457     '-l _ croaks after stat' );
458
459 lstat $0;
460 eval { lstat _ };
461 is( "$@", "", "lstat _ ok after lstat" );
462 eval { -l _ };
463 is( "$@", "", "-l _ ok after lstat" );
464
465 eval { lstat "test.pl" };
466 {
467     open my $fh, "test.pl";
468     stat *$fh{IO};
469     eval { lstat _ }
470 }
471 like $@, qr/^The stat preceding lstat\(\) wasn't an lstat at /,
472 'stat $ioref resets stat type';
473
474 {
475     open(FOO, ">$tmpfile") || DIE("Can't open temp test file: $!");
476     my @statbuf = stat FOO;
477     stat "test.pl";
478     my @lstatbuf = lstat *FOO{IO};
479     is "@lstatbuf", "@statbuf", 'lstat $ioref reverts to regular fstat';
480     close(FOO);
481     unlink $tmpfile or print "# unlink failed: $!\n";
482 }
483   
484 SKIP: {
485     skip "No lstat", 2 unless $Config{d_lstat};
486
487     # bug id 20020124.004
488     # If we have d_lstat, we should have symlink()
489     my $linkname = 'stat-' . rand =~ y/.//dr;
490     my $target = $Perl;
491     $target =~ s/;\d+\z// if $Is_VMS; # symlinks don't like version numbers
492     symlink $target, $linkname or die "# Can't symlink $0: $!";
493     lstat $linkname;
494     -T _;
495     eval { lstat _ };
496     like( $@, qr/^The stat preceding lstat\(\) wasn't an lstat/,
497         'lstat croaks after -T _' );
498     eval { -l _ };
499     like( $@, qr/^The stat preceding -l _ wasn't an lstat/,
500         '-l _ croaks after -T _' );
501     unlink $linkname or print "# unlink $linkname failed: $!\n";
502 }
503
504 SKIP: {
505     skip "Too much clock skew between system and filesystem", 5
506         if ($Filesystem_Time_Offset > 5);
507     print "# Zzz...\n";
508     sleep($Filesystem_Time_Offset+1);
509     my $f = 'tstamp.tmp';
510     unlink $f;
511     ok (open(S, "> $f"), 'can create tmp file');
512     close S or die;
513     my @a = stat $f;
514     print "# time=$^T, stat=(@a)\n";
515     my @b = (-M _, -A _, -C _);
516     print "# -MAC=(@b)\n";
517     ok( (-M _) < 0, 'negative -M works');
518   SKIP:
519     {
520         skip "Access timestamps inaccurate", 1 if $inaccurate_atime;
521         ok( (-A _) < 0, 'negative -A works');
522     }
523     ok( (-C _) < 0, 'negative -C works');
524     ok(unlink($f), 'unlink tmp file');
525 }
526
527 # [perl #4253]
528 {
529     ok(open(F, ">", $tmpfile), 'can create temp file');
530     close F;
531     chmod 0077, $tmpfile;
532     my @a = stat($tmpfile);
533     my $s1 = -s _;
534     -T _;
535     my $s2 = -s _;
536     is($s1, $s2, q(-T _ doesn't break the statbuffer));
537     SKIP: {
538         my $root_uid = $Is_Cygwin ? 18 : 0;
539         skip "No lstat", 1 unless $Config{d_lstat};
540         skip "uid=0", 1 if $< == $root_uid or $> == $root_uid;
541         skip "Can't check if admin user in miniperl", 1
542           if $^O =~ /^(cygwin|MSWin32|msys)$/ && is_miniperl();
543         skip "Readable by group/other means readable by me on $^O", 1 if $^O eq 'VMS'
544           or ($^O =~ /^(cygwin|MSWin32|msys)$/ and Win32::IsAdminUser());
545         lstat($tmpfile);
546         -T _;
547         ok(eval { lstat _ },
548            q(-T _ doesn't break lstat for unreadable file));
549     }
550     unlink $tmpfile;
551 }
552
553 SKIP: {
554     skip "No dirfd()", 9 unless $Config{d_dirfd} || $Config{d_dir_dd_fd};
555     ok(opendir(DIR, "."), 'Can open "." dir') || diag "Can't open '.':  $!";
556     ok(stat(DIR), "stat() on dirhandle works"); 
557     ok(-d -r _ , "chained -x's on dirhandle"); 
558     ok(-d DIR, "-d on a dirhandle works");
559
560     # And now for the ambiguous bareword case
561     {
562         no warnings 'deprecated';
563         ok(open(DIR, "TEST"), 'Can open "TEST" dir')
564             || diag "Can't open 'TEST':  $!";
565     }
566     my $size = (stat(DIR))[7];
567     ok(defined $size, "stat() on bareword works");
568     is($size, -s "TEST", "size returned by stat of bareword is for the file");
569     ok(-f _, "ambiguous bareword uses file handle, not dir handle");
570     ok(-f DIR);
571     closedir DIR or die $!;
572     close DIR or die $!;
573 }
574
575 {
576     # RT #8244: *FILE{IO} does not behave like *FILE for stat() and -X() operators
577     ok(open(F, ">", $tmpfile), 'can create temp file');
578     my @thwap = stat *F{IO};
579     ok(@thwap, "stat(*F{IO}) works");    
580     ok( -f *F{IO} , "single file tests work with *F{IO}");
581     close F;
582     unlink $tmpfile;
583
584     #PVIO's hold dirhandle information, so let's test them too.
585
586     SKIP: {
587         skip "No dirfd()", 9 unless $Config{d_dirfd} || $Config{d_dir_dd_fd};
588         ok(opendir(DIR, "."), 'Can open "." dir') || diag "Can't open '.':  $!";
589         ok(stat(*DIR{IO}), "stat() on *DIR{IO} works");
590         ok(-d _ , "The special file handle _ is set correctly"); 
591         ok(-d -r *DIR{IO} , "chained -x's on *DIR{IO}");
592
593         # And now for the ambiguous bareword case
594         {
595             no warnings 'deprecated';
596             ok(open(DIR, "TEST"), 'Can open "TEST" dir')
597                 || diag "Can't open 'TEST':  $!";
598         }
599         my $size = (stat(*DIR{IO}))[7];
600         ok(defined $size, "stat() on *THINGY{IO} works");
601         is($size, -s "TEST",
602            "size returned by stat of *THINGY{IO} is for the file");
603         ok(-f _, "ambiguous *THINGY{IO} uses file handle, not dir handle");
604         ok(-f *DIR{IO});
605         closedir DIR or die $!;
606         close DIR or die $!;
607     }
608 }
609
610 # [perl #71002]
611 {
612     local $^W = 1;
613     my $w;
614     local $SIG{__WARN__} = sub { warn shift; ++$w };
615     stat 'prepeinamehyparcheiarcheiometoonomaavto';
616     stat _;
617     is $w, undef, 'no unopened warning from stat _';
618 }
619
620 END {
621     chmod 0666, $tmpfile;
622     unlink_all $tmpfile;
623 }