summaryrefslogtreecommitdiff
path: root/t/release-pp-28-readonly-return.t
blob: 1dedca0db71c7b70ad44042ea69f22ad98ed222f (plain)
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106


use Test::More;

BEGIN {
    unless ( $ENV{RELEASE_TESTING} ) {
        plan skip_all => 'these tests are for release testing';
    }

    $ENV{PV_TEST_PERL} = 1;
}

use strict;
use warnings;
use Test::More;

use Devel::Peek qw( SvREFCNT );
use File::Temp qw( tempfile );
use Params::Validate qw( validate SCALAR HANDLE );

{
    my $fh = tempfile();
    my @p  = (
        foo => 1,
        bar => $fh,
    );

    my $ref = val1(@p);

    eval { $ref->{foo} = 2 };
    ok( !$@, 'returned hashref values are not read only' );
    is( $ref->{foo}, 2, 'double check that setting value worked' );
    is( $fh, $ref->{bar}, 'filehandle is not copied during validation' );
}

{

    package ScopeTest;

    my $live = 0;

    sub new { $live++; bless {}, shift }
    sub DESTROY { $live-- }

    sub Live {$live}
}

{
    my @p = ( foo => ScopeTest->new() );

    is(
        ScopeTest->Live(), 1,
        'one live object'
    );

    my $ref = val2(@p);

    isa_ok( $ref->{foo}, 'ScopeTest' );

    @p = ();

    is(
        ScopeTest->Live(), 1,
        'still one live object'
    );

    ok(
        defined $ref->{foo},
        'foo key stays in scope after original version goes out of scope'
    );
    is(
        SvREFCNT( $ref->{foo} ), 1,
        'ref count for reference is 1'
    );

    undef $ref->{foo};

    is(
        ScopeTest->Live(), 0,
        'no live objects'
    );
}

sub val1 {
    my $ref = validate(
        @_, {
            foo => { type => SCALAR },
            bar => { type => HANDLE, optional => 1 },
        },
    );

    return $ref;
}

sub val2 {
    my $ref = validate(
        @_, {
            foo => 1,
        },
    );

    return $ref;
}

done_testing();