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