/
json_spec.rb
128 lines (116 loc) · 2.88 KB
/
json_spec.rb
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
require File.expand_path('../spec_helper', __FILE__)
require 'asir/coder/json'
describe "ASIR::Coder::JSON" do
unless RUBY_PLATFORM =~ /java/
before(:each) do
@enc = ASIR::Coder::JSON.new
@dec = @enc.dup
end
basic_objs = [ ]
[
[ nil, 'null' ],
true,
false,
].each do | x |
x, str = *x
str ||= x.inspect
str = "[#{str}]"
basic_objs << [ x, str ]
it "should handle #{x.inspect}" do
out = @enc.encode(x)
out.should == str
@dec.decode(out).should == x
end
end
[
1234,
1.234,
[ :symbol, '"symbol"' ],
].each do | x |
x, str = *x
str ||= x.inspect
str = "[#{str}]"
basic_objs << [ x, str ]
it "should handle #{x.inspect}" do
out = @enc.encode(x)
out.should == str
y = @dec.decode(out)
y = y.to_sym if Symbol === x
y.should == x
end
end
[
'String',
].each do | x |
x, str = *x
str ||= x.inspect
str = "[#{str}]"
basic_objs << [ x, str ]
it "should handle #{x.inspect}" do
out = @enc.encode(x)
out.should == str
y = @dec.decode(out)
y.should == x
end
end
it "should handle empty Array" do
x = [ ]
out = @enc.encode(x)
out.should == "[[]]"
@dec.decode(out).should == x
end
it "should handle Array" do
x = basic_objs.map{|e| e[0]}
out = @enc.encode(x)
out.should == "[[null,true,false,1234,1.234,\"symbol\",\"String\"]]"
y = @dec.decode(out)
y.should == x.map{|e| Symbol === e ? e.to_s : e }
end
it "should handle empty Hash" do
x = { }
out = @enc.encode(x)
out.should == "[{}]"
@dec.decode(out).should == x
end
it "should handle Hash" do
x = Hash[ *basic_objs.flatten.reverse ]
out = @enc.encode(x)
out.should =~ %r{\A\[\{}
out.should =~ %r{\}\]\Z}
basic_objs.each do | v, str |
# out.should =~ %r{#{k.inspect}:}
out.should =~ %r{#{str}}
end
y = @dec.decode(out)
y.should == x.inject({}){|h, (k, v)| h[k] = Symbol === v ? v.to_s : v; h }
end
module ASIR::Coder::Test
class Object
attr_accessor :a, :h, :o
end
end
it "should handle deep objects" do
x = ASIR::Coder::Test::Object.new
x.a = [ *basic_objs.map{|a| a[0]} ]
x.h = Hash[ *basic_objs.flatten.reverse ]
x.o = ASIR::Coder::Test::Object.new
x.o.a = 123
out = @enc.encode(x)
# FIXME:
out.should =~ %r{\A\[\"#<ASIR::Coder::Test::Object:[^>]+>\"\]\Z}
#out.should =~ %r{<#{x.class.name.gsub('::', '.')} id=\"#{x.object_id}\" >}
#out.should =~ %r{</#{x.class.name.gsub('::', '.')}>}
y = @dec.decode(out)
(String === y).should == true
=begin
FIXME:
y.a.should == x.a
y.h.should == x.h
y.o.class.should == ASIR::Coder::Test::Object
y.o.a.should == x.o.a
x.instance_variables.sort { | a, b | a.to_s <=> b.to_s }.should ==
y.instance_variables.sort { | a, b | a.to_s <=> b.to_s }
=end
end
end
end