1+ # !/usr/bin/perl -w
2+
3+ # Copyright (c) 2018, cPanel, LLC.
4+ # All rights reserved.
5+ # http://cpanel.net
6+ #
7+ # This is free software; you can redistribute it and/or modify it under the
8+ # same terms as Perl itself. See L<perlartistic>.
9+
10+ use strict;
11+ use warnings;
12+
13+ use Test2::Bundle::Extended;
14+ use Test2::Tools::Explain;
15+ use Test2::Plugin::NoWarnings;
16+
17+ use Overload::FileCheck qw( CHECK_IS_FALSE CHECK_IS_TRUE FALLBACK_TO_REAL_OP) ;
18+
19+ use File::Temp qw{ tempfile tempdir } ;
20+
21+ my %STATS ;
22+
23+ # non existing but mocked
24+ my $FILENAME ;
25+ my $FAKE_DIR ;
26+
27+ {
28+ my ( $fh , $filename ) = tempfile();
29+ $STATS {' file' } = [ stat ($filename ) ];
30+ unlink $filename ;
31+
32+ $FILENAME = " $filename " ;
33+
34+ my $dir = tempdir( CLEANUP => 1 );
35+
36+ $STATS {' dir' } = [ stat (" $dir " ) ];
37+
38+ $STATS {' perl' } = [ stat ($^X) ];
39+
40+ $FAKE_DIR = " $dir /not/there" ;
41+ }
42+
43+ my $current_test = " $0 " ;
44+
45+ our $call_my_stat ;
46+
47+ ok !-e $FILENAME , " filename does not exist" ;
48+ ok !-d $FAKE_DIR , " directory does not exis" ;
49+
50+ ok !$call_my_stat , ' start - without mock' ;
51+
52+ # note: we are just mocking stat here...
53+ ok Overload::FileCheck::mock_all_from_stat( \&my_stat ), " mock_all_from_stat succees" ;
54+
55+ is [ stat ( $FILENAME ) ], $STATS {' file' }, " stats for file" ;
56+ ok $call_my_stat , " stat is now mocked" ;
57+ ok -e $FILENAME , " -e filename" ;
58+ ok -f $FILENAME , " -f filename" ;
59+
60+ ok -e $FILENAME && -f _, " -e filename && -f _" ;
61+
62+ is -l $FILENAME || -e $FILENAME , 1, q[ -l $f || -e $f] ;
63+ is -l $FILENAME || -e _, 1, q[ -l $f || -e _] ;
64+
65+ is [ stat (' /empty' ) ], [], " stat /empty" ;
66+
67+ is -l q[ /empty] || -e q[ /empty] , undef , q[ -l /empty || -e /empty] ;
68+ is -l q[ /empty] || -e _, undef , q[ -l /empty || -e _] ;
69+
70+ # --- END ---
71+ ok Overload::FileCheck::unmock_all_file_checks(), " unmock all" ;
72+ done_testing;
73+
74+ exit ;
75+
76+ sub my_stat {
77+ my ( $opname , $file_or_handle ) = @_ ;
78+
79+ note " === my_stat is called. Type: " , $opname , " File: " , $file_or_handle ;
80+ ++$call_my_stat ;
81+
82+ my $f = $file_or_handle ; # alias to use a shorter name later...
83+
84+ return $STATS {' file' } if $f eq $FILENAME ;
85+ return $STATS {' dir' } if $f eq $FAKE_DIR ;
86+
87+ return [] if $f eq ' /empty' ;
88+
89+ return FALLBACK_TO_REAL_OP();
90+ }
91+
92+ sub stat_for_a_directory {
93+ return $STATS {' dir' };
94+ }
95+
96+ sub stat_for_a_binary {
97+ return $STATS {' perl' };
98+ }
99+
100+ sub stat_for_a_tty {
101+ return $STATS {' tty' };
102+ }
103+
104+ 1;
0 commit comments