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