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