/
asif-json.t
65 lines (49 loc) · 1.67 KB
/
asif-json.t
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
use v6;
use Test;
plan 3;
# Load the module
use Masquerade;
# Predeclare a reusable variable for the expected jsonification.
my $expected;
# A utility sub to test. Pass in the object, expected result, and test
# description to run the test.
use JSON::Tiny;
sub test_json ($obj, Str $expected, Str $explanation) {
my $obj-asif-json = $obj but AsIf::JSON;
is from-json($obj-asif-json.Str).perl, from-json($expected).perl, $explanation;
}
#####
# Basic perl objects. It's worth noting that the tests for some things
# (e.g. hashes) are a little bit brittle right now: they assume a
# garaunteed order, but order isn't garaunteed. I may have to enforce some
# sort of order in the jsonification.
# Simple hash
test_json {one => 1, two => 'pickle'},
'{ "one" : 1, "two" : "pickle" }',
'simple hash';
# Hash with nested hashes and arrays.
test_json {hash => {a => 1}, array => [<foo bar>]},
'{ "hash" : { "a" : 1 }, "array" : [ "foo", "bar" ] }',
'hash with nested hashes and arrays';
##
# Try a more complex perl object.
class Weather::Phenomenon {
has $!id;
has $.name;
has $.description;
has %.properties;
has @.affects;
};
my $tornado = Weather::Phenomenon.new(
id => 123,
name => 'tornado',
description => 'a twister!',
properties => {
twistiness => 100,
windiness => 88,
size => 40,
},
affects => <Houses Barns Couches Chickens>
);
$expected = '{ "name" : "tornado", "description" : "a twister!", "properties" : { "twistiness" : 100, "windiness" : 88, "size" : 40 }, "affects" : [ "Houses", "Barns", "Couches", "Chickens" ] }';
test_json $tornado, $expected, 'perl object properties render to json objects';