Commit | Line | Data |
124c2ba5 |
1 | #!/usr/bin/perl |
2 | |
3 | use strict; |
4 | use warnings; |
5 | |
6 | use Test::More tests => 11; |
7 | use Storable (); |
5e5d4e28 |
8 | use File::Temp qw(tempdir); |
9 | use File::Spec::Functions; |
10 | my $dir = tempdir( CLEANUP => 1 ); |
124c2ba5 |
11 | |
12 | BEGIN { |
13 | use_ok('MooseX::Storage'); |
14 | } |
15 | |
16 | { |
17 | package Foo; |
18 | use Moose; |
19 | use MooseX::Storage; |
b5f363ac |
20 | |
124c2ba5 |
21 | with Storage(io => 'StorableFile'); |
b5f363ac |
22 | |
124c2ba5 |
23 | has 'number' => (is => 'ro', isa => 'Int'); |
24 | has 'string' => (is => 'rw', isa => 'Str'); |
b5f363ac |
25 | has 'float' => (is => 'ro', isa => 'Num'); |
124c2ba5 |
26 | has 'array' => (is => 'ro', isa => 'ArrayRef'); |
b5f363ac |
27 | has 'hash' => (is => 'ro', isa => 'HashRef'); |
28 | has 'object' => (is => 'ro', isa => 'Object'); |
124c2ba5 |
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 | |
5e5d4e28 |
48 | my $file = catfile($dir,'temp.storable'); |
124c2ba5 |
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); |
b5f363ac |
62 | |
124c2ba5 |
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, |
b5f363ac |
71 | 'string' => 'HELLO WORLD', |
124c2ba5 |
72 | 'array' => [ 1 .. 10], |
b5f363ac |
73 | 'hash' => { map { $_ => undef } 1 .. 10 }, |
124c2ba5 |
74 | 'object' => { |
75 | '__CLASS__' => 'Foo', |
76 | 'number' => 2 |
77 | }, |
78 | }, |
79 | '... got the data struct we expected' |
b5f363ac |
80 | ); |
81 | |
124c2ba5 |
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 | |