@@ -92,6 +92,46 @@ def test_dump_strict
9292 assert_equal '"World"' , "World" . to_json ( strict : true )
9393 end
9494
95+ def test_state_depth_to_json
96+ depth = Object . new
97+ def depth . to_json ( state )
98+ JSON ::State . from_state ( state ) . depth . to_s
99+ end
100+
101+ assert_equal "0" , JSON . generate ( depth )
102+ assert_equal "[1]" , JSON . generate ( [ depth ] )
103+ assert_equal %({"depth":1}) , JSON . generate ( depth : depth )
104+ assert_equal "[[2]]" , JSON . generate ( [ [ depth ] ] )
105+ assert_equal %([{"depth":2}]) , JSON . generate ( [ { depth : depth } ] )
106+
107+ state = JSON ::State . new
108+ assert_equal "0" , state . generate ( depth )
109+ assert_equal "[1]" , state . generate ( [ depth ] )
110+ assert_equal %({"depth":1}) , state . generate ( depth : depth )
111+ assert_equal "[[2]]" , state . generate ( [ [ depth ] ] )
112+ assert_equal %([{"depth":2}]) , state . generate ( [ { depth : depth } ] )
113+ end
114+
115+ def test_state_depth_to_json_recursive
116+ recur = Object . new
117+ def recur . to_json ( state = nil , *)
118+ state = JSON ::State . from_state ( state )
119+ if state . depth < 3
120+ state . generate ( [ state . depth , self ] )
121+ else
122+ state . generate ( [ state . depth ] )
123+ end
124+ end
125+
126+ assert_raise ( NestingError ) { JSON . generate ( recur , max_nesting : 3 ) }
127+ assert_equal "[0,[1,[2,[3]]]]" , JSON . generate ( recur , max_nesting : 4 )
128+
129+ state = JSON ::State . new ( max_nesting : 3 )
130+ assert_raise ( NestingError ) { state . generate ( recur ) }
131+ state . max_nesting = 4
132+ assert_equal "[0,[1,[2,[3]]]]" , JSON . generate ( recur , max_nesting : 4 )
133+ end
134+
95135 def test_generate_pretty
96136 json = pretty_generate ( { } )
97137 assert_equal ( '{}' , json )
0 commit comments