encoding_test.rb 15.0 KB
Newer Older
1
# encoding: utf-8
2
require 'securerandom'
3
require 'abstract_unit'
4
require 'active_support/core_ext/string/inflections'
J
Jeremy Kemper 已提交
5
require 'active_support/json'
6

7
class TestJSONEncoding < ActiveSupport::TestCase
8 9 10 11
  class Foo
    def initialize(a, b)
      @a, @b = a, b
    end
12 13
  end

14 15
  class Hashlike
    def to_hash
16
      { :foo => "hello", :bar => "world" }
17 18 19
    end
  end

20
  class Custom
21 22 23 24
    def initialize(serialized)
      @serialized = serialized
    end

G
Godfrey Chan 已提交
25
    def as_json(options = nil)
26
      @serialized
27 28 29
    end
  end

30 31 32 33 34 35 36 37 38
  class CustomWithOptions
    attr_accessor :foo, :bar

    def as_json(options={})
      options[:only] = %w(foo bar)
      super(options)
    end
  end

39 40 41 42 43 44
  class OptionsTest
    def as_json(options = :default)
      options
    end
  end

45 46 47 48 49 50 51 52 53 54 55 56 57
  class HashWithAsJson < Hash
    attr_accessor :as_json_called

    def initialize(*)
      super
    end

    def as_json(options={})
      @as_json_called = true
      super
    end
  end

58 59 60 61
  TrueTests     = [[ true,  %(true)  ]]
  FalseTests    = [[ false, %(false) ]]
  NilTests      = [[ nil,   %(null)  ]]
  NumericTests  = [[ 1,     %(1)     ],
62
                   [ 2.5,   %(2.5)   ],
63 64 65
                   [ 0.0/0.0,   %(null) ],
                   [ 1.0/0.0,   %(null) ],
                   [ -1.0/0.0,  %(null) ],
66
                   [ BigDecimal('0.0')/BigDecimal('0.0'),  %(null) ],
67
                   [ BigDecimal('2.5'), %("#{BigDecimal('2.5').to_s}") ]]
68

69
  StringTests   = [[ 'this is the <string>',     %("this is the \\u003cstring\\u003e")],
70
                   [ 'a "string" with quotes & an ampersand', %("a \\"string\\" with quotes \\u0026 an ampersand") ],
71
                   [ 'http://test.host/posts/1', %("http://test.host/posts/1")],
72
                   [ "Control characters: \x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\u2028\u2029",
73
                     %("Control characters: \\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f\\u2028\\u2029") ]]
74

75 76
  ArrayTests    = [[ ['a', 'b', 'c'],          %([\"a\",\"b\",\"c\"])          ],
                   [ [1, 'a', :b, nil, false], %([1,\"a\",\"b\",null,false]) ]]
77

78 79 80 81
  RangeTests    = [[ 1..2,     %("1..2")],
                   [ 1...2,    %("1...2")],
                   [ 1.5..2.5, %("1.5..2.5")]]

82 83 84 85
  SymbolTests   = [[ :a,     %("a")    ],
                   [ :this,  %("this") ],
                   [ :"a b", %("a b")  ]]

86
  ObjectTests   = [[ Foo.new(1, 2), %({\"a\":1,\"b\":2}) ]]
87
  HashlikeTests = [[ Hashlike.new, %({\"bar\":\"world\",\"foo\":\"hello\"}) ]]
88 89 90 91 92 93 94
  CustomTests   = [[ Custom.new("custom"), '"custom"' ],
                   [ Custom.new(nil), 'null' ],
                   [ Custom.new(:a), '"a"' ],
                   [ Custom.new([ :foo, "bar" ]), '["foo","bar"]' ],
                   [ Custom.new({ :foo => "hello", :bar => "world" }), '{"bar":"world","foo":"hello"}' ],
                   [ Custom.new(Hashlike.new), '{"bar":"world","foo":"hello"}' ],
                   [ Custom.new(Custom.new(Custom.new(:a))), '"a"' ]]
95

96
  RegexpTests   = [[ /^a/, '"(?-mix:^a)"' ], [/^\w{1,2}[a-z]+/ix, '"(?ix-m:^\\\\w{1,2}[a-z]+)"']]
97

98 99 100
  DateTests     = [[ Date.new(2005,2,1), %("2005/02/01") ]]
  TimeTests     = [[ Time.utc(2005,2,1,15,15,10), %("2005/02/01 15:15:10 +0000") ]]
  DateTimeTests = [[ DateTime.civil(2005,2,1,15,15,10), %("2005/02/01 15:15:10 +0000") ]]
101

102
  StandardDateTests     = [[ Date.new(2005,2,1), %("2005-02-01") ]]
103 104
  StandardTimeTests     = [[ Time.utc(2005,2,1,15,15,10), %("2005-02-01T15:15:10.000Z") ]]
  StandardDateTimeTests = [[ DateTime.civil(2005,2,1,15,15,10), %("2005-02-01T15:15:10.000+00:00") ]]
105
  StandardStringTests   = [[ 'this is the <string>', %("this is the <string>")]]
106

Y
Yehuda Katz 已提交
107 108 109 110 111
  def sorted_json(json)
    return json unless json =~ /^\{.*\}$/
    '{' + json[1..-2].split(',').sort.join(',') + '}'
  end

112
  constants.grep(/Tests$/).each do |class_tests|
113 114
    define_method("test_#{class_tests[0..-6].underscore}") do
      begin
115 116
        prev = ActiveSupport.use_standard_json_time_format

117
        ActiveSupport.escape_html_entities_in_json  = class_tests !~ /^Standard/
118 119
        ActiveSupport.use_standard_json_time_format = class_tests =~ /^Standard/
        self.class.const_get(class_tests).each do |pair|
Y
Yehuda Katz 已提交
120
          assert_equal pair.last, sorted_json(ActiveSupport::JSON.encode(pair.first))
121 122
        end
      ensure
123
        ActiveSupport.escape_html_entities_in_json  = false
124
        ActiveSupport.use_standard_json_time_format = prev
125 126 127
      end
    end
  end
128

129 130 131 132 133 134 135
  def test_process_status
    # There doesn't seem to be a good way to get a handle on a Process::Status object without actually
    # creating a child process, hence this to populate $?
    system("not_a_real_program_#{SecureRandom.hex}")
    assert_equal %({"exitstatus":#{$?.exitstatus},"pid":#{$?.pid}}), ActiveSupport::JSON.encode($?)
  end

T
Thomas Fuchs 已提交
136
  def test_hash_encoding
137 138 139 140
    assert_equal %({\"a\":\"b\"}), ActiveSupport::JSON.encode(:a => :b)
    assert_equal %({\"a\":1}), ActiveSupport::JSON.encode('a' => 1)
    assert_equal %({\"a\":[1,2]}), ActiveSupport::JSON.encode('a' => [1,2])
    assert_equal %({"1":2}), ActiveSupport::JSON.encode(1 => 2)
141

Y
Yehuda Katz 已提交
142
    assert_equal %({\"a\":\"b\",\"c\":\"d\"}), sorted_json(ActiveSupport::JSON.encode(:a => :b, :c => :d))
T
Thomas Fuchs 已提交
143
  end
144

145 146
  def test_utf8_string_encoded_properly
    result = ActiveSupport::JSON.encode('€2.99')
147
    assert_equal '"€2.99"', result
148
    assert_equal(Encoding::UTF_8, result.encoding)
149 150

    result = ActiveSupport::JSON.encode('✎☺')
151
    assert_equal '"✎☺"', result
152
    assert_equal(Encoding::UTF_8, result.encoding)
153
  end
154

155 156 157
  def test_non_utf8_string_transcodes
    s = '二'.encode('Shift_JIS')
    result = ActiveSupport::JSON.encode(s)
158
    assert_equal '"二"', result
159
    assert_equal Encoding::UTF_8, result.encoding
160 161
  end

162 163 164 165 166 167 168 169 170 171 172 173 174
  def test_wide_utf8_chars
    w = '𠜎'
    result = ActiveSupport::JSON.encode(w)
    assert_equal '"𠜎"', result
  end

  def test_wide_utf8_roundtrip
    hash = { string: "𐒑" }
    json = ActiveSupport::JSON.encode(hash)
    decoded_hash = ActiveSupport::JSON.decode(json)
    assert_equal "𐒑", decoded_hash['string']
  end

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
  def test_reading_encode_big_decimal_as_string_option
    assert_deprecated do
      assert ActiveSupport.encode_big_decimal_as_string
    end
  end

  def test_setting_deprecated_encode_big_decimal_as_string_option
    assert_raise(NotImplementedError) do
      ActiveSupport.encode_big_decimal_as_string = true
    end

    assert_raise(NotImplementedError) do
      ActiveSupport.encode_big_decimal_as_string = false
    end
  end

191
  def test_exception_raised_when_encoding_circular_reference_in_array
192 193
    a = [1]
    a << a
194 195 196
    assert_deprecated do
      assert_raise(ActiveSupport::JSON::Encoding::CircularReferenceError) { ActiveSupport::JSON.encode(a) }
    end
197
  end
198

199 200 201
  def test_exception_raised_when_encoding_circular_reference_in_hash
    a = { :name => 'foo' }
    a[:next] = a
202 203 204
    assert_deprecated do
      assert_raise(ActiveSupport::JSON::Encoding::CircularReferenceError) { ActiveSupport::JSON.encode(a) }
    end
205 206 207 208 209
  end

  def test_exception_raised_when_encoding_circular_reference_in_hash_inside_array
    a = { :name => 'foo', :sub => [] }
    a[:sub] << a
210 211 212
    assert_deprecated do
      assert_raise(ActiveSupport::JSON::Encoding::CircularReferenceError) { ActiveSupport::JSON.encode(a) }
    end
213 214
  end

215
  def test_hash_key_identifiers_are_always_quoted
216
    values = {0 => 0, 1 => 1, :_ => :_, "$" => "$", "a" => "a", :A => :A, :A0 => :A0, "A0B" => "A0B"}
217
    assert_equal %w( "$" "A" "A0" "A0B" "_" "a" "0" "1" ).sort, object_keys(ActiveSupport::JSON.encode(values))
218
  end
219

220
  def test_hash_should_allow_key_filtering_with_only
221
    assert_equal %({"a":1}), ActiveSupport::JSON.encode({'a' => 1, :b => 2, :c => 3}, :only => 'a')
222 223 224
  end

  def test_hash_should_allow_key_filtering_with_except
225
    assert_equal %({"b":2}), ActiveSupport::JSON.encode({'foo' => 'bar', :b => 2, :c => 3}, :except => ['foo', :c])
226
  end
227

228
  def test_time_to_json_includes_local_offset
229
    prev = ActiveSupport.use_standard_json_time_format
230 231
    ActiveSupport.use_standard_json_time_format = true
    with_env_tz 'US/Eastern' do
232
      assert_equal %("2005-02-01T15:15:10.000-05:00"), ActiveSupport::JSON.encode(Time.local(2005,2,1,15,15,10))
233 234
    end
  ensure
235
    ActiveSupport.use_standard_json_time_format = prev
236
  end
237

238
  def test_hash_with_time_to_json
239 240
    prev = ActiveSupport.use_standard_json_time_format
    ActiveSupport.use_standard_json_time_format = false
241
    assert_equal '{"time":"2009/01/01 00:00:00 +0000"}', { :time => Time.utc(2009) }.to_json
242 243
  ensure
    ActiveSupport.use_standard_json_time_format = prev
244 245
  end

D
Dan Barry 已提交
246 247 248 249
  def test_nested_hash_with_float
    assert_nothing_raised do
      hash = {
        "CHI" => {
250
          :display_name => "chicago",
D
Dan Barry 已提交
251 252 253
          :latitude => 123.234
        }
      }
S
Santiago Pastorino 已提交
254
      ActiveSupport::JSON.encode(hash)
D
Dan Barry 已提交
255 256 257
    end
  end

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
  def test_hash_like_with_options
    h = Hashlike.new
    json = h.to_json :only => [:foo]

    assert_equal({"foo"=>"hello"}, JSON.parse(json))
  end

  def test_object_to_json_with_options
    obj = Object.new
    obj.instance_variable_set :@foo, "hello"
    obj.instance_variable_set :@bar, "world"
    json = obj.to_json :only => ["foo"]

    assert_equal({"foo"=>"hello"}, JSON.parse(json))
  end

  def test_struct_to_json_with_options
    struct = Struct.new(:foo, :bar).new
    struct.foo = "hello"
    struct.bar = "world"
    json = struct.to_json :only => [:foo]

    assert_equal({"foo"=>"hello"}, JSON.parse(json))
  end

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
  def test_hash_should_pass_encoding_options_to_children_in_as_json
    person = {
      :name => 'John',
      :address => {
        :city => 'London',
        :country => 'UK'
      }
    }
    json = person.as_json :only => [:address, :city]

    assert_equal({ 'address' => { 'city' => 'London' }}, json)
  end

  def test_hash_should_pass_encoding_options_to_children_in_to_json
    person = {
      :name => 'John',
      :address => {
        :city => 'London',
        :country => 'UK'
      }
    }
    json = person.to_json :only => [:address, :city]

    assert_equal(%({"address":{"city":"London"}}), json)
  end

  def test_array_should_pass_encoding_options_to_children_in_as_json
    people = [
      { :name => 'John', :address => { :city => 'London', :country => 'UK' }},
      { :name => 'Jean', :address => { :city => 'Paris' , :country => 'France' }}
    ]
    json = people.as_json :only => [:address, :city]
    expected = [
      { 'address' => { 'city' => 'London' }},
      { 'address' => { 'city' => 'Paris' }}
    ]

    assert_equal(expected, json)
  end

  def test_array_should_pass_encoding_options_to_children_in_to_json
    people = [
      { :name => 'John', :address => { :city => 'London', :country => 'UK' }},
      { :name => 'Jean', :address => { :city => 'Paris' , :country => 'France' }}
    ]
    json = people.to_json :only => [:address, :city]

    assert_equal(%([{"address":{"city":"London"}},{"address":{"city":"Paris"}}]), json)
  end

333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
  def test_enumerable_should_pass_encoding_options_to_children_in_as_json
    people = [
      { :name => 'John', :address => { :city => 'London', :country => 'UK' }},
      { :name => 'Jean', :address => { :city => 'Paris' , :country => 'France' }}
    ]
    json = people.each.as_json :only => [:address, :city]
    expected = [
      { 'address' => { 'city' => 'London' }},
      { 'address' => { 'city' => 'Paris' }}
    ]

    assert_equal(expected, json)
  end

  def test_enumerable_should_pass_encoding_options_to_children_in_to_json
    people = [
      { :name => 'John', :address => { :city => 'London', :country => 'UK' }},
      { :name => 'Jean', :address => { :city => 'Paris' , :country => 'France' }}
    ]
    json = people.each.to_json :only => [:address, :city]

    assert_equal(%([{"address":{"city":"London"}},{"address":{"city":"Paris"}}]), json)
  end

G
Godfrey Chan 已提交
357
  def test_hash_to_json_should_not_keep_options_around
358 359 360 361 362
    f = CustomWithOptions.new
    f.foo = "hello"
    f.bar = "world"

    hash = {"foo" => f, "other_hash" => {"foo" => "other_foo", "test" => "other_test"}}
363
    assert_equal({"foo"=>{"foo"=>"hello","bar"=>"world"},
364
                  "other_hash" => {"foo"=>"other_foo","test"=>"other_test"}}, ActiveSupport::JSON.decode(hash.to_json))
365 366
  end

G
Godfrey Chan 已提交
367 368 369 370 371 372 373 374 375 376
  def test_array_to_json_should_not_keep_options_around
    f = CustomWithOptions.new
    f.foo = "hello"
    f.bar = "world"

    array = [f, {"foo" => "other_foo", "test" => "other_test"}]
    assert_equal([{"foo"=>"hello","bar"=>"world"},
                  {"foo"=>"other_foo","test"=>"other_test"}], ActiveSupport::JSON.decode(array.to_json))
  end

377 378 379 380 381 382 383 384 385 386
  def test_hash_as_json_without_options
    json = { foo: OptionsTest.new }.as_json
    assert_equal({"foo" => :default}, json)
  end

  def test_array_as_json_without_options
    json = [ OptionsTest.new ].as_json
    assert_equal([:default], json)
  end

A
Alexey Nayden 已提交
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
  def test_struct_encoding
    Struct.new('UserNameAndEmail', :name, :email)
    Struct.new('UserNameAndDate', :name, :date)
    Struct.new('Custom', :name, :sub)
    user_email = Struct::UserNameAndEmail.new 'David', 'sample@example.com'
    user_birthday = Struct::UserNameAndDate.new 'David', Date.new(2010, 01, 01)
    custom = Struct::Custom.new 'David', user_birthday


    json_strings = ""
    json_string_and_date = ""
    json_custom = ""

    assert_nothing_raised do
      json_strings = user_email.to_json
      json_string_and_date = user_birthday.to_json
      json_custom = custom.to_json
    end

406 407 408
    assert_equal({"name" => "David",
                  "sub" => {
                    "name" => "David",
409
                    "date" => "2010-01-01" }}, ActiveSupport::JSON.decode(json_custom))
410 411

    assert_equal({"name" => "David", "email" => "sample@example.com"},
412
                 ActiveSupport::JSON.decode(json_strings))
413

414
    assert_equal({"name" => "David", "date" => "2010-01-01"},
415
                 ActiveSupport::JSON.decode(json_string_and_date))
A
Alexey Nayden 已提交
416
  end
417

418 419 420 421 422 423
  def test_nil_true_and_false_represented_as_themselves
    assert_equal nil,   nil.as_json
    assert_equal true,  true.as_json
    assert_equal false, false.as_json
  end

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
  def test_json_gem_dump_by_passing_active_support_encoder
    h = HashWithAsJson.new
    h[:foo] = "hello"
    h[:bar] = "world"

    assert_equal %({"foo":"hello","bar":"world"}), JSON.dump(h)
    assert_nil h.as_json_called
  end

  def test_json_gem_generate_by_passing_active_support_encoder
    h = HashWithAsJson.new
    h[:foo] = "hello"
    h[:bar] = "world"

    assert_equal %({"foo":"hello","bar":"world"}), JSON.generate(h)
    assert_nil h.as_json_called
  end

  def test_json_gem_pretty_generate_by_passing_active_support_encoder
    h = HashWithAsJson.new
    h[:foo] = "hello"
    h[:bar] = "world"

    assert_equal <<EXPECTED.chomp, JSON.pretty_generate(h)
{
  "foo": "hello",
  "bar": "world"
}
EXPECTED
    assert_nil h.as_json_called
  end

456
  protected
457

458 459 460
    def object_keys(json_object)
      json_object[1..-2].scan(/([^{}:,\s]+):/).flatten.sort
    end
461

462 463 464 465 466 467
    def with_env_tz(new_tz = 'US/Eastern')
      old_tz, ENV['TZ'] = ENV['TZ'], new_tz
      yield
    ensure
      old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
    end
468
end