Merge branch 'master' of gitmo@git.moose.perl.org:MooseX-Storage
[gitmo/MooseX-Storage.git] / t / 103_io_storable_file_custom.t
CommitLineData
124c2ba5 1#!/usr/bin/perl
2
3use strict;
4use warnings;
5
6use Test::More tests => 11;
7use Storable ();
5e5d4e28 8use File::Temp qw(tempdir);
9use File::Spec::Functions;
10my $dir = tempdir( CLEANUP => 1 );
124c2ba5 11
12BEGIN {
13 use_ok('MooseX::Storage');
14}
15
16{
17 package Foo;
18 use Moose;
19 use MooseX::Storage;
766ab81f 20
124c2ba5 21 with Storage(io => 'StorableFile');
766ab81f 22
124c2ba5 23 has 'number' => (is => 'ro', isa => 'Int');
24 has 'string' => (is => 'rw', isa => 'Str');
766ab81f 25 has 'float' => (is => 'ro', isa => 'Num');
124c2ba5 26 has 'array' => (is => 'ro', isa => 'ArrayRef');
766ab81f 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 48my $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);
766ab81f 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,
766ab81f 71 'string' => 'HELLO WORLD',
124c2ba5 72 'array' => [ 1 .. 10],
766ab81f 73 'hash' => { map { $_ => undef } 1 .. 10 },
124c2ba5 74 'object' => {
75 '__CLASS__' => 'Foo',
76 'number' => 2
77 },
78 },
79 '... got the data struct we expected'
766ab81f 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