File: 28-readonly-return.t

package info (click to toggle)
libparams-validate-perl 0.91-2
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 524 kB
  • ctags: 729
  • sloc: perl: 2,596; makefile: 52
file content (93 lines) | stat: -rw-r--r-- 1,726 bytes parent folder | download
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
#!/usr/bin/perl -w

use strict;
use Test::More;

BEGIN
{
    eval 'use File::Temp';
    if ($@)
    {
        plan skip_all => 'Need File::Temp for this test';
    }
    else
    {
        plan tests => 9;
    }
}

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;
}