* 2022-01-18 [ci skip]
[ruby-80x24.org.git] / test / json / json_generic_object_test.rb
blob82742dcd638967d7ea0d619dea20960fe419eafe
1 #frozen_string_literal: false
2 require 'test_helper'
4 class JSONGenericObjectTest < Test::Unit::TestCase
5   include JSON
7   def setup
8     @go = GenericObject[ :a => 1, :b => 2 ]
9   end
11   def test_attributes
12     assert_equal 1, @go.a
13     assert_equal 1, @go[:a]
14     assert_equal 2, @go.b
15     assert_equal 2, @go[:b]
16     assert_nil @go.c
17     assert_nil @go[:c]
18   end
20   def test_generate_json
21     switch_json_creatable do
22       assert_equal @go, JSON(JSON(@go), :create_additions => true)
23     end
24   end
26   def test_parse_json
27     assert_kind_of Hash,
28       JSON(
29         '{ "json_class": "JSON::GenericObject", "a": 1, "b": 2 }',
30         :create_additions => true
31       )
32     switch_json_creatable do
33       assert_equal @go, l =
34         JSON(
35           '{ "json_class": "JSON::GenericObject", "a": 1, "b": 2 }',
36              :create_additions => true
37         )
38       assert_equal 1, l.a
39       assert_equal @go,
40         l = JSON('{ "a": 1, "b": 2 }', :object_class => GenericObject)
41       assert_equal 1, l.a
42       assert_equal GenericObject[:a => GenericObject[:b => 2]],
43         l = JSON('{ "a": { "b": 2 } }', :object_class => GenericObject)
44       assert_equal 2, l.a.b
45     end
46   end
48   def test_from_hash
49     result  = GenericObject.from_hash(
50       :foo => { :bar => { :baz => true }, :quux => [ { :foobar => true } ] })
51     assert_kind_of GenericObject, result.foo
52     assert_kind_of GenericObject, result.foo.bar
53     assert_equal   true, result.foo.bar.baz
54     assert_kind_of GenericObject, result.foo.quux.first
55     assert_equal   true, result.foo.quux.first.foobar
56     assert_equal   true, GenericObject.from_hash(true)
57   end
59   def test_json_generic_object_load
60     empty = JSON::GenericObject.load(nil)
61     assert_kind_of JSON::GenericObject, empty
62     simple_json = '{"json_class":"JSON::GenericObject","hello":"world"}'
63     simple = JSON::GenericObject.load(simple_json)
64     assert_kind_of JSON::GenericObject, simple
65     assert_equal "world", simple.hello
66     converting = JSON::GenericObject.load('{ "hello": "world" }')
67     assert_kind_of JSON::GenericObject, converting
68     assert_equal "world", converting.hello
70     json = JSON::GenericObject.dump(JSON::GenericObject[:hello => 'world'])
71     assert_equal JSON(json), JSON('{"json_class":"JSON::GenericObject","hello":"world"}')
72   end
74   private
76   def switch_json_creatable
77     JSON::GenericObject.json_creatable = true
78     yield
79   ensure
80     JSON::GenericObject.json_creatable = false
81   end
82 end