b66563ac86d720a1e45ffc041068867b9770439e
[gitmo/MooseX-Storage.git] / t / 103_io_storable_file_custom.t
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use Test::More tests => 11;
7 use Storable ();
8 use File::Temp qw(tempdir);
9 use File::Spec::Functions;
10 my $dir = tempdir( CLEANUP => 1 );
11
12 BEGIN {
13     use_ok('MooseX::Storage');
14 }
15
16 {
17     package Foo;
18     use Moose;
19     use MooseX::Storage;
20
21     with Storage(io => 'StorableFile');
22
23     has 'number' => (is => 'ro', isa => 'Int');
24     has 'string' => (is => 'rw', isa => 'Str');
25     has 'float'  => (is => 'ro', isa => 'Num'); 
26     has 'array'  => (is => 'ro', isa => 'ArrayRef');
27     has 'hash'   => (is => 'ro', isa => 'HashRef');
28         has 'object' => (is => 'ro', isa => 'Object');
29         
30         ## add some custom freeze/thaw hooks here ...
31         
32     sub thaw {
33         my ( $class, $data ) = @_;
34         my $self = $class->unpack( $data );
35         $self->string("Hello World");
36         $self;
37     }
38
39     sub freeze {
40         my ( $self, @args ) = @_;
41         my $data = $self->pack(@args);
42         $data->{string} = "HELLO WORLD";
43         $data;
44     }
45
46 }
47
48 my $file = catfile($dir,'temp.storable');
49
50 {
51     my $foo = Foo->new(
52         number => 10,
53         string => 'foo',
54         float  => 10.5,
55         array  => [ 1 .. 10 ],
56         hash   => { map { $_ => undef } (1 .. 10) },
57         object => Foo->new( number => 2 ),
58     );
59     isa_ok($foo, 'Foo');
60
61     $foo->store($file);
62
63     # check our custom freeze hook fired ...
64     my $data = Storable::retrieve($file);
65     is_deeply(
66         $data,
67         {
68             '__CLASS__' => 'Foo',
69             'float'     => 10.5,
70             'number'    => 10,
71             'string'    => 'HELLO WORLD', 
72             'array'     => [ 1 .. 10],
73             'hash'      => { map { $_ => undef } 1 .. 10 },
74             'object'    => {
75                 '__CLASS__' => 'Foo',
76                 'number' => 2
77             },
78         },
79         '... got the data struct we expected'
80     );
81
82 }
83
84 {
85     my $foo = Foo->load($file);
86     isa_ok($foo, 'Foo');
87
88     ## check our custom thaw hook fired
89     is($foo->string, 'Hello World', '... got the right string');
90
91     is($foo->number, 10, '... got the right number');
92     is($foo->float, 10.5, '... got the right float');
93     is_deeply($foo->array, [ 1 .. 10], '... got the right array');
94     is_deeply($foo->hash, { map { $_ => undef } (1 .. 10) }, '... got the right hash');
95
96     isa_ok($foo->object, 'Foo');
97     is($foo->object->number, 2, '... got the right number (in the embedded object)');
98 }
99