b589ecee4fa6ef5fb0ff7f8d03877772efc1aa68
[gitmo/MooseX-Storage.git] / t / 010_basic_json.t
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 use Test::More;
7
8 BEGIN {        
9     eval "use Test::JSON";
10     plan skip_all => "Test::JSON is required for this test" if $@;            
11     plan tests => 12;
12     use_ok('MooseX::Storage');
13 }
14
15 {
16
17     package Foo;
18     use Moose;
19     use MooseX::Storage;
20
21     with Storage( 'format' => 'JSON' );
22
23     has 'number' => ( is => 'ro', isa => 'Int' );
24     has 'string' => ( is => 'ro', 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
31 {
32     my $foo = Foo->new(
33         number => 10,
34         string => 'foo',
35         float  => 10.5,
36         array  => [ 1 .. 10 ],
37         hash   => { map { $_ => undef } ( 1 .. 10 ) },
38         object => Foo->new( number => 2 ),
39     );
40     isa_ok( $foo, 'Foo' );
41
42     my $json = $foo->freeze;
43
44     is_valid_json($json, '.. this is valid JSON');
45
46
47     is_json(
48         $json,
49 '{"array":[1,2,3,4,5,6,7,8,9,10],"hash":{"6":null,"3":null,"7":null,"9":null,"2":null,"8":null,"1":null,"4":null,"10":null,"5":null},"float":10.5,"object":{"number":2,"__CLASS__":"Foo"},"number":10,"__CLASS__":"Foo","string":"foo"}',
50         '... got the right JSON'
51     );
52
53 }
54
55 {
56     my $foo =
57       Foo->thaw(
58 '{"array":[1,2,3,4,5,6,7,8,9,10],"hash":{"6":null,"3":null,"7":null,"9":null,"2":null,"8":null,"1":null,"4":null,"10":null,"5":null},"float":10.5,"object":{"number":2,"__CLASS__":"Foo"},"number":10,"__CLASS__":"Foo","string":"foo"}'
59       );
60     isa_ok( $foo, 'Foo' );
61
62     is( $foo->number, 10,    '... got the right number' );
63     is( $foo->string, 'foo', '... got the right string' );
64     is( $foo->float,  10.5,  '... got the right float' );
65     is_deeply( $foo->array, [ 1 .. 10 ], '... got the right array' );
66     is_deeply(
67         $foo->hash,
68         { map { $_ => undef } ( 1 .. 10 ) },
69         '... got the right hash'
70     );
71
72     isa_ok( $foo->object, 'Foo' );
73     is( $foo->object->number, 2,
74         '... got the right number (in the embedded object)' );
75 }
76