-
Notifications
You must be signed in to change notification settings - Fork 129
/
adapter_shared_example.rb
115 lines (102 loc) · 3.04 KB
/
adapter_shared_example.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
shared_examples_for "an adapter" do |adapter|
before do
begin
MultiJson.use adapter
rescue LoadError
pending "Adapter #{adapter} couldn't be loaded (not installed?)"
end
end
describe '.dump' do
it 'writes decodable JSON' do
[
{'abc' => 'def'},
[1, 2, 3, "4"],
].each do |example|
MultiJson.load(MultiJson.dump(example)).should == example
end
end
it 'dumps symbol keys as strings' do
[
[
{:foo => {:bar => 'baz'}},
{'foo' => {'bar' => 'baz'}},
],
[
[{:foo => {:bar => 'baz'}}],
[{'foo' => {'bar' => 'baz'}}],
],
[
{:foo => [{:bar => 'baz'}]},
{'foo' => [{'bar' => 'baz'}]},
]
].each do |example, expected|
dumped_json = MultiJson.dump(example)
MultiJson.load(dumped_json).should == expected
end
end
it 'dumps rootless JSON' do
MultiJson.dump("random rootless string").should == "\"random rootless string\""
MultiJson.dump(123).should == "123"
end
it 'passes options to the adapter' do
MultiJson.adapter.should_receive(:dump).with('foo', {:bar => :baz})
MultiJson.dump('foo', :bar => :baz)
end
if adapter == 'json_gem' || adapter == 'json_pure'
describe 'with :pretty option set to true' do
it 'passes default pretty options' do
object = 'foo'
object.should_receive(:to_json).with(JSON::PRETTY_STATE_PROTOTYPE.to_h)
MultiJson.dump(object,:pretty => true)
end
end
end
it 'dumps custom objects which implement as_json' do
MultiJson.dump(TimeWithZone.new).should == "\"2005-02-01T15:15:10Z\""
end
end
describe '.load' do
it 'properly loads valid JSON' do
MultiJson.load('{"abc":"def"}').should == {'abc' => 'def'}
end
it 'raises MultiJson::DecodeError on invalid JSON' do
lambda do
MultiJson.load('{"abc"}')
end.should raise_error(MultiJson::DecodeError)
end
it 'raises MultiJson::DecodeError with data on invalid JSON' do
data = '{invalid}'
begin
MultiJson.load(data)
rescue MultiJson::DecodeError => de
de.data.should == data
end
end
it 'stringifys symbol keys when encoding' do
dumped_json = MultiJson.dump(:a => 1, :b => {:c => 2})
MultiJson.load(dumped_json).should == {"a" => 1, "b" => {"c" => 2}}
end
it 'properly loads valid JSON in StringIOs' do
json = StringIO.new('{"abc":"def"}')
MultiJson.load(json).should == {'abc' => 'def'}
end
it 'allows for symbolization of keys' do
[
[
'{"abc":{"def":"hgi"}}',
{:abc => {:def => 'hgi'}},
],
[
'[{"abc":{"def":"hgi"}}]',
[{:abc => {:def => 'hgi'}}],
],
[
'{"abc":[{"def":"hgi"}]}',
{:abc => [{:def => 'hgi'}]},
],
].each do |example, expected|
MultiJson.load(example, :symbolize_keys => true).should == expected
end
end
end
end