Debian Codegraph @

README

raw
1 NAME
2 Test::MockFile - Allows tests to validate code that can interact with
3 files without touching the file system.
4
5 VERSION
6 Version 0.029
7
8 SYNOPSIS
9 Intercepts file system calls for specific files so unit testing can take
10 place without any files being altered on disk.
11
12 This is useful for small tests
13 <https://testing.googleblog.com/2010/12/test-sizes.html> where file
14 interaction is discouraged.
15
16 A strict mode is even provided (and turned on by default) which can
17 throw a die when files are accessed during your tests!
18
19 # Loaded before Test::MockFile so uses the core perl functions without any hooks.
20 use Module::I::Dont::Want::To::Alter;
21
22 # strict mode by default
23 use Test::MockFile ();
24
25 # non-strict mode
26 use Test::MockFile qw< nostrict >;
27
28 # Be sure to assign the output of mocks, they disappear when they go out of scope
29 my $foobar = Test::MockFile->file( "/foo/bar", "contents\ngo\nhere" );
30 open my $fh, '<', '/foo/bar' or die; # Does not actually open the file on disk
31 say '/foo/bar exists' if -e $fh;
32 close $fh;
33
34 say '/foo/bar is a file' if -f '/foo/bar';
35 say '/foo/bar is THIS BIG: ' . -s '/foo/bar';
36
37 my $foobaz = Test::MockFile->file('/foo/baz'); # File starts out missing
38 my $opened = open my $baz_fh, '<', '/foo/baz'; # File reports as missing so fails
39 say '/foo/baz does not exist yet' if !-e '/foo/baz';
40
41 open $baz_fh, '>', '/foo/baz' or die; # open for writing
42 print {$baz_fh} "first line\n";
43
44 open $baz_fh, '>>', '/foo/baz' or die; # open for append.
45 print {$baz_fh} "second line";
46 close $baz_fh;
47
48 say "Contents of /foo/baz:\n>>" . $foobaz->contents() . '<<';
49
50 # Unmock your file.
51 # (same as the variable going out of scope
52 undef $foobaz;
53
54 # The file check will now happen on file system now the file is no longer mocked.
55 say '/foo/baz is missing again (no longer mocked)' if !-e '/foo/baz';
56
57 my $quux = Test::MockFile->file( '/foo/bar/quux.txt', '' );
58 my @matches = </foo/bar/*.txt>;
59
60 # ( '/foo/bar/quux.txt' )
61 say "Contents of /foo/bar directory: " . join "\n", @matches;
62
63 @matches = glob('/foo/bar/*.txt');
64
65 # same as above
66 say "Contents of /foo/bar directory (using glob()): " . join "\n", @matches;
67
68 IMPORT
69 When the module is loaded with no parameters, strict mode is turned on.
70 Any file checks, "open", "sysopen", "opendir", "stat", or "lstat" will
71 throw a die.
72
73 For example:
74
75 use Test::MockFile;
76
77 # This will not die.
78 my $file = Test::MockFile->file("/bar", "...");
79 my $symlink = Test::MockFile->symlink("/foo", "/bar");
80 -l '/foo' or print "ok\n";
81 open my $fh, '>', '/foo';
82
83 # All of these will die
84 open my $fh, '>', '/unmocked/file'; # Dies
85 sysopen my $fh, '/other/file', O_RDONLY;
86 opendir my $fh, '/dir';
87 -e '/file';
88 -l '/file';
89
90 If we want to load the module without strict mode:
91
92 use Test::MockFile qw< nostrict >;
93
94 Relative paths are not supported:
95
96 use Test::MockFile;
97
98 # Checking relative vs absolute paths
99 $file = Test::MockFile->file( '/foo/../bar', '...' ); # not ok - relative path
100 $file = Test::MockFile->file( '/bar', '...' ); # ok - absolute path
101 $file = Test::MockFile->file( 'bar', '...' ); # ok - current dir
102
103 file_arg_position_for_command
104 Args: ($command)
105
106 Provides a hint with the position of the argument most likely holding
107 the file name for the current $command call.
108
109 This is used internaly to provide better error messages. This can be
110 used when plugging hooks to know what's the filename we currently try to
111 access.
112
113 SUBROUTINES/METHODS
114 file
115 Args: ($file, $contents, $stats)
116
117 This will make cause $file to be mocked in all file checks, opens, etc.
118
119 "undef" contents means that the file should act like it's not there. You
120 can only set the stats if you provide content.
121
122 If you give file content, the directory inside it will be mocked as
123 well.
124
125 my $f = Test::MockFile->file( '/foo/bar' );
126 -d '/foo' # not ok
127
128 my $f = Test::MockFile->file( '/foo/bar', 'some content' );
129 -d '/foo' # ok
130
131 See "Mock Stats" for what goes into the stats hashref.
132
133 file_from_disk
134 Args: "($file_to_mock, $file_on_disk, $stats)"
135
136 This will make cause $file to be mocked in all file checks, opens, etc.
137
138 If "file_on_disk" isn't present, then this will die.
139
140 See "Mock Stats" for what goes into the stats hashref.
141
142 symlink
143 Args: ($readlink, $file )
144
145 This will cause $file to be mocked in all file checks, opens, etc.
146
147 $readlink indicates what "fake" file it points to. If the file $readlink
148 points to is not mocked, it will act like a broken link, regardless of
149 what's on disk.
150
151 If $readlink is undef, then the symlink is mocked but not present.(lstat
152 $file is empty.)
153
154 Stats are not able to be specified on instantiation but can in theory be
155 altered after the object is created. People don't normally mess with the
156 permissions on a symlink.
157
158 dir
159 Args: ($dir)
160
161 This will cause $dir to be mocked in all file checks, and "opendir"
162 interactions.
163
164 The directory name is normalized so any trailing slash is removed.
165
166 $dir = Test::MockFile->dir( 'mydir/', ... ); # ok
167 $dir->path(); # mydir
168
169 If there were previously mocked files (within the same scope), the
170 directory will exist. Otherwise, the directory will be nonexistent.
171
172 my $dir = Test::MockFile->dir('/etc');
173 -d $dir; # not ok since directory wasn't created yet
174 $dir->contents(); # undef
175
176 # Now we can create an empty directory
177 mkdir '/etc';
178 $dir_etc->contents(); # . ..
179
180 # Alternatively, we can already create files with ->file()
181 $dir_log = Test::MockFile->dir('/var');
182 $file_log = Test::MockFile->file( '/var/log/access_log', $some_content );
183 $dir_log->contents(); # . .. access_log
184
185 # If you create a nonexistent file but then give it content, it will create
186 # the directory for you
187 my $file = Test::MockFile->file('/foo/bar');
188 my $dir = Test::MockFile->dir('/foo');
189 -d '/foo' # false
190 -e '/foo/bar'; # false
191 $dir->contents(); # undef
192
193 $file->contents('hello');
194 -e '/foo/bar'; # true
195 -d '/foo'; # true
196 $dir->contents(); # . .. bar
197
198 NOTE: Because "." and ".." will always be the first things "readdir"
199 returns, These files are automatically inserted at the front of the
200 array. The order of files is sorted.
201
202 If you want to affect the stat information of a directory, you need to
203 use the available core Perl keywords. (We might introduce a special
204 helper method for it in the future.)
205
206 $d = Test::MockFile->dir( '/foo', [], { 'mode' => 0755 } ); # dies
207 $d = Test::MockFile->dir( '/foo', undef, { 'mode' => 0755 } ); # dies
208
209 $d = Test::MockFile->dir('/foo');
210 mkdir $d, 0755; # ok
211
212 Mock Stats
213 When creating mocked files or directories, we default their stats to:
214
215 my $attrs = Test::MockFile->file( $file, $contents, {
216 'dev' => 0, # stat[0]
217 'inode' => 0, # stat[1]
218 'mode' => $mode, # stat[2]
219 'nlink' => 0, # stat[3]
220 'uid' => int $>, # stat[4]
221 'gid' => int $), # stat[5]
222 'rdev' => 0, # stat[6]
223 'atime' => $now, # stat[8]
224 'mtime' => $now, # stat[9]
225 'ctime' => $now, # stat[10]
226 'blksize' => 4096, # stat[11]
227 'fileno' => undef, # fileno()
228 } );
229
230 You'll notice that mode, size, and blocks have been left out of this.
231 Mode is set to 666 (for files) or 777 (for directories), xored against
232 the current umask. Size and blocks are calculated based on the size of
233 'contents' a.k.a. the fake file.
234
235 When you want to override one of the defaults, all you need to do is
236 specify that when you declare the file or directory. The rest will
237 continue to default.
238
239 my $mfile = Test::MockFile->file("/root/abc", "...", {inode => 65, uid => 123, mtime => int((2000-1970) * 365.25 * 24 * 60 * 60 }));
240
241 my $mdir = Test::MockFile->dir("/sbin", "...", { mode => 0700 }));
242
243 new
244 This class method is called by file/symlink/dir. There is no good reason
245 to call this directly.
246
247 contents
248 Optional Arg: $contents
249
250 Retrieves or updates the current contents of the file.
251
252 Only retrieves the content of the directory (as an arrayref). You can
253 set directory contents with calling the "file()" method described above.
254
255 Symlinks have no contents.
256
257 filename
258 Deprecated. Same as "path".
259
260 path
261 The path (filename or dirname) of the file or directory this mock object
262 is controlling.
263
264 unlink
265 Makes the virtual file go away. NOTE: This also works for directories.
266
267 touch
268 Optional Args: ($epoch_time)
269
270 This function acts like the UNIX utility touch. It sets atime, mtime,
271 ctime to $epoch_time.
272
273 If no arguments are passed, $epoch_time is set to time(). If the file
274 does not exist, contents are set to an empty string.
275
276 stat
277 Returns the stat of a mocked file (does not follow symlinks.)
278
279 readlink
280 Optional Arg: $readlink
281
282 Returns the stat of a mocked file (does not follow symlinks.) You can
283 also use this to change what your symlink is pointing to.
284
285 is_link
286 returns true/false, depending on whether this object is a symlink.
287
288 is_dir
289 returns true/false, depending on whether this object is a directory.
290
291 is_file
292 returns true/false, depending on whether this object is a regular file.
293
294 size
295 returns the size of the file based on its contents.
296
297 exists
298 returns true or false based on if the file exists right now.
299
300 blocks
301 Calculates the block count of the file based on its size.
302
303 chmod
304 Optional Arg: $perms
305
306 Allows you to alter the permissions of a file. This only allows you to
307 change the 07777 bits of the file permissions. The number passed should
308 be the octal 0755 form, not the alphabetic "755" form
309
310 permissions
311 Returns the permissions of the file.
312
313 mtime
314 Optional Arg: $new_epoch_time
315
316 Returns and optionally sets the mtime of the file if passed as an
317 integer.
318
319 ctime
320 Optional Arg: $new_epoch_time
321
322 Returns and optionally sets the ctime of the file if passed as an
323 integer.
324
325 atime
326 Optional Arg: $new_epoch_time
327
328 Returns and optionally sets the atime of the file if passed as an
329 integer.
330
331 add_file_access_hook
332 Args: ( $code_ref )
333
334 You can use add_file_access_hook to add a code ref that gets called
335 every time a real file (not mocked) operation happens. We use this for
336 strict mode to die if we detect your program is unexpectedly accessing
337 files. You are welcome to use it for whatever you like.
338
339 Whenever the code ref is called, we pass 2 arguments:
340 "$code->($access_type, $at_under_ref)". Be aware that altering the
341 variables in $at_under_ref will affect the variables passed to open /
342 sysopen, etc.
343
344 One use might be:
345
346 Test::MockFile::add_file_access_hook(sub { my $type = shift; print "$type called at: " . Carp::longmess() } );
347
348 clear_file_access_hooks
349 Calling this subroutine will clear everything that was passed to
350 add_file_access_hook
351
352 How this mocking is done:
353 Test::MockFile uses 2 methods to mock file access:
354
355 -X via Overload::FileCheck
356 It is currently not possible in pure perl to override stat
357 <http://perldoc.perl.org/functions/stat.html>, lstat
358 <http://perldoc.perl.org/functions/lstat.html> and -X operators
359 <http://perldoc.perl.org/functions/-X.html>. In conjunction with this
360 module, we've developed Overload::FileCheck.
361
362 This enables us to intercept calls to stat, lstat and -X operators (like
363 -e, -f, -d, -s, etc.) and pass them to our control. If the file is
364 currently being mocked, we return the stat (or lstat) information on the
365 file to be used to determine the answer to whatever check was made. This
366 even works for things like "-e _". If we do not control the file in
367 question, we return "FALLBACK_TO_REAL_OP()" which then makes a normal
368 check.
369
370 CORE::GLOBAL:: overrides
371 Since 5.10, it has been possible to override function calls by defining
372 them. like:
373
374 *CORE::GLOBAL::open = sub(*;$@) {...}
375
376 Any code which is loaded AFTER this happens will use the alternate open.
377 This means you can place your "use Test::MockFile" statement after
378 statements you don't want to be mocked and there is no risk that the
379 code will ever be altered by Test::MockFile.
380
381 We oveload the following statements and then return tied handles to
382 enable the rest of the IO functions to work properly. Only open /
383 sysopen are needed to address file operations. However opendir file
384 handles were never setup for tie so we have to override all of opendir's
385 related functions.
386
387 * open
388
389 * sysopen
390
391 * opendir
392
393 * readdir
394
395 * telldir
396
397 * seekdir
398
399 * rewinddir
400
401 * closedir
402
403 CAEATS AND LIMITATIONS
404 DEBUGGER UNDER STRICT MODE
405 If you want to use the Perl debugger (perldebug) on any code that uses
406 Test::MockFile in strict mode, you will need to load Term::ReadLine
407 beforehand, because it loads a file. Under the debugger, the debugger
408 will load the module after Test::MockFile and get mad.
409
410 # Load it from the command line
411 perl -MTerm::ReadLine -d code.pl
412
413 # Or alternatively, add this to the top of your code:
414 use Term::ReadLine
415
416 FILENO IS UNSUPPORTED
417 Filehandles can provide the file descriptor (in number) using the
418 "fileno" keyword but this is purposefully unsupported in Test::MockFile.
419
420 The reaosn is that by mocking a file, we're creating an alternative file
421 system. Returning a "fileno" (file descriptor number) would require
422 creating file descriptor numbers that would possibly conflict with the
423 file desciptors you receive from the real filesystem.
424
425 In short, this is a recipe for buggy tests or worse - truly destructive
426 behavior. If you have a need for a real file, we suggest File::Temp.
427
428 BAREWORD FILEHANDLE FAILURES
429 There is a particular type of bareword filehandle failures that cannot
430 be fixed.
431
432 These errors occur because there's compile-time code that uses bareword
433 filehandles in a function call that cannot be expressed by this module's
434 prototypes for core functions.
435
436 The only solution to these is loading `Test::MockFile` after the other
437 code:
438
439 This will fail:
440
441 # This will fail because Test2::V0 will eventually load Term::Table::Util
442 # which calls open() with a bareword filehandle that is misparsed by this module's
443 # opendir prototypes
444 use Test::MockFile ();
445 use Test2::V0;
446
447 This will succeed:
448
449 # This will succeed because open() will be parsed by perl
450 # and only then we override those functions
451 use Test2::V0;
452 use Test::MockFile ();
453
454 (Using strict-mode will not fix it, even though you should use it.)
455
456 AUTHOR
457 Todd Rinaldo, "<toddr at cpan.org>"
458
459 BUGS
460 Please report any bugs or feature requests to
461 <https://github.com/cpanel/Test-MockFile>.
462
463 SUPPORT
464 You can find documentation for this module with the perldoc command.
465
466 perldoc Test::MockFile
467
468 You can also look for information at:
469
470 * CPAN Ratings
471
472 <https://cpanratings.perl.org/d/Test-MockFile>
473
474 * Search CPAN
475
476 <https://metacpan.org/release/Test-MockFile>
477
478 ACKNOWLEDGEMENTS
479 Thanks to Nicolas R., "<atoomic at cpan.org>" for help with
480 Overload::FileCheck. This module could not have been completed without
481 it.
482
483 LICENSE AND COPYRIGHT
484 Copyright 2018 cPanel L.L.C.
485
486 All rights reserved.
487
488 <http://cpanel.net>
489
490 This is free software; you can redistribute it and/or modify it under
491 the same terms as Perl itself. See perlartistic.
492