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