File: examples.pl

package info (click to toggle)
libtest-mockfile-perl 0.037-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 436 kB
  • sloc: perl: 4,110; makefile: 7
file content (55 lines) | stat: -rw-r--r-- 1,629 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!perl

use strict;
use warnings;
use feature qw< say >;

use lib 'lib';

# This is straight from the SYNOPSIS

# strict mode by default
use Test::MockFile ();

# non-strict mode
# use Test::MockFile qw< nostrict >;

# Be sure to assign the output of mocks, they disappear when they go out of scope
my $foobar = Test::MockFile->file( "/foo/bar", "contents\ngo\nhere" );
open my $fh, '<', '/foo/bar' or die;    # Does not actually open the file on disk
say '/foo/bar exists' if -e $fh;
close $fh;

say '/foo/bar is a file' if -f '/foo/bar';
say '/foo/bar is THIS BIG: ' . -s '/foo/bar';

my $foobaz = Test::MockFile->file('/foo/baz');    # File starts out missing
my $opened = open my $baz_fh, '<', '/foo/baz';    # File reports as missing so fails
say '/foo/baz does not exist yet' if !-e '/foo/baz';

open $baz_fh, '>', '/foo/baz' or die;             # open for writing
print {$baz_fh} "first line\n";

open $baz_fh, '>>', '/foo/baz' or die;            # open for append.
print {$baz_fh} "second line";
close $baz_fh;

say "Contents of /foo/baz:\n>>" . $foobaz->contents() . '<<';

# Unmock your file.
# (same as the variable going out of scope
undef $foobaz;

# The file check will now happen on file system now the file is no longer mocked.
say '/foo/baz is missing again (no longer mocked)' if !-e '/foo/baz';

my $quux    = Test::MockFile->file( '/foo/bar/quux.txt', '' );
my @matches = </foo/bar/*.txt>;

# ( '/foo/bar/quux.txt' )
say "Contents of /foo/bar directory: " . join "\n", @matches;

@matches = glob('/foo/bar/*.txt');

# same as above
say "Contents of /foo/bar directory (using glob()): " . join "\n", @matches;