File Coverage

blib/lib/SimpleMock/ScopeGuard.pm
Criterion Covered Total %
statement 15 15 100.0
branch n/a
condition n/a
subroutine 5 5 100.0
pod 0 1 0.0
total 20 21 95.2


line stmt bran cond sub pod time code
1             package SimpleMock::ScopeGuard;
2 7     7   33 use strict;
  7         9  
  7         181  
3 7     7   35 use warnings;
  7         10  
  7         307  
4 7     7   27 use Scalar::Util qw(refaddr);
  7         9  
  7         1294  
5            
6             our $VERSION = '0.03';
7              
8             sub new {
9 7     7 0 15 my ($class, $layer) = @_;
10 7         34 return bless { layer => $layer }, $class;
11             }
12            
13             sub DESTROY {
14 7     7   4459 my $self = shift;
15 7         25 my $id = refaddr($self->{layer});
16 7         18 @SimpleMock::MOCK_STACK = grep { refaddr($_) != $id } @SimpleMock::MOCK_STACK;
  15         53  
17             }
18              
19             1;
20              
21             =head1 NAME
22              
23             SimpleMock::ScopeGuard - Automatic cleanup of scoped mock layers
24              
25             =head1 SYNOPSIS
26              
27             use SimpleMock qw(register_mocks_scoped);
28              
29             {
30             my $guard = register_mocks_scoped(
31             SUBS => {
32             'My::Module' => {
33             my_sub => [{ returns => 'scoped value' }],
34             },
35             },
36             );
37             # scoped mocks are active here
38             }
39             # $guard goes out of scope, DESTROY fires, scoped layer is removed
40              
41             =head1 DESCRIPTION
42              
43             Helper module to manage scoped mocks via an object that uses DESTROY to remove
44             scoped mocks. The layer is identified by reference address (via
45             C), so nested scopes are safe regardless of exit order.
46              
47             You should not need to use this module directly. Instead, use
48             C from L, which returns a ScopeGuard object.
49              
50             =cut