encoding_test.rb 14.2 KB
Newer Older
1 2 3 4 5 6 7 8
require "securerandom"
require "abstract_unit"
require "active_support/core_ext/string/inflections"
require "active_support/core_ext/regexp"
require "active_support/json"
require "active_support/time"
require "time_zone_test_helpers"
require "json/encoding_test_cases"
9

10
class TestJSONEncoding < ActiveSupport::TestCase
11 12
  include TimeZoneTestHelpers

Y
Yehuda Katz 已提交
13
  def sorted_json(json)
14 15
    if json.start_with?("{") && json.end_with?("}")
      "{" + json[1..-2].split(",").sort.join(",") + "}"
16 17 18
    else
      json
    end
Y
Yehuda Katz 已提交
19 20
  end

21
  JSONTest::EncodingTestCases.constants.each do |class_tests|
22 23
    define_method("test_#{class_tests[0..-6].underscore}") do
      begin
24 25
        prev = ActiveSupport.use_standard_json_time_format

26 27 28 29
        standard_class_tests = /Standard/.match?(class_tests)

        ActiveSupport.escape_html_entities_in_json  = !standard_class_tests
        ActiveSupport.use_standard_json_time_format = standard_class_tests
30
        JSONTest::EncodingTestCases.const_get(class_tests).each do |pair|
Y
Yehuda Katz 已提交
31
          assert_equal pair.last, sorted_json(ActiveSupport::JSON.encode(pair.first))
32 33
        end
      ensure
34
        ActiveSupport.escape_html_entities_in_json  = false
35
        ActiveSupport.use_standard_json_time_format = prev
36 37 38
      end
    end
  end
39

40
  def test_process_status
41 42
    rubinius_skip "https://github.com/rubinius/rubinius/issues/3334"

43 44 45 46 47 48
    # 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 已提交
49
  def test_hash_encoding
50
    assert_equal %({\"a\":\"b\"}), ActiveSupport::JSON.encode(a: :b)
51
    assert_equal %({\"a\":1}), ActiveSupport::JSON.encode("a" => 1)
52
    assert_equal %({\"a\":[1,2]}), ActiveSupport::JSON.encode("a" => [1, 2])
53
    assert_equal %({"1":2}), ActiveSupport::JSON.encode(1 => 2)
54

55
    assert_equal %({\"a\":\"b\",\"c\":\"d\"}), sorted_json(ActiveSupport::JSON.encode(a: :b, c: :d))
T
Thomas Fuchs 已提交
56
  end
57

58 59 60 61 62 63 64
  def test_hash_keys_encoding
    ActiveSupport.escape_html_entities_in_json = true
    assert_equal "{\"\\u003c\\u003e\":\"\\u003c\\u003e\"}", ActiveSupport::JSON.encode("<>" => "<>")
  ensure
    ActiveSupport.escape_html_entities_in_json = false
  end

65
  def test_utf8_string_encoded_properly
66
    result = ActiveSupport::JSON.encode("€2.99")
67
    assert_equal '"€2.99"', result
68
    assert_equal(Encoding::UTF_8, result.encoding)
69

70
    result = ActiveSupport::JSON.encode("✎☺")
71
    assert_equal '"✎☺"', result
72
    assert_equal(Encoding::UTF_8, result.encoding)
73
  end
74

75
  def test_non_utf8_string_transcodes
76
    s = "二".encode("Shift_JIS")
77
    result = ActiveSupport::JSON.encode(s)
78
    assert_equal '"二"', result
79
    assert_equal Encoding::UTF_8, result.encoding
80 81
  end

82
  def test_wide_utf8_chars
83
    w = "𠜎"
84 85 86 87 88 89 90 91
    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)
92
    assert_equal "𐒑", decoded_hash["string"]
93 94
  end

95
  def test_hash_key_identifiers_are_always_quoted
96
    values = { 0 => 0, 1 => 1, :_ => :_, "$" => "$", "a" => "a", :A => :A, :A0 => :A0, "A0B" => "A0B" }
97
    assert_equal %w( "$" "A" "A0" "A0B" "_" "a" "0" "1" ).sort, object_keys(ActiveSupport::JSON.encode(values))
98
  end
99

100
  def test_hash_should_allow_key_filtering_with_only
101
    assert_equal %({"a":1}), ActiveSupport::JSON.encode({ "a" => 1, :b => 2, :c => 3 }, only: "a")
102 103 104
  end

  def test_hash_should_allow_key_filtering_with_except
105
    assert_equal %({"b":2}), ActiveSupport::JSON.encode({ "foo" => "bar", :b => 2, :c => 3 }, except: ["foo", :c])
106
  end
107

108
  def test_time_to_json_includes_local_offset
109
    with_standard_json_time_format(true) do
110
      with_env_tz "US/Eastern" do
111
        assert_equal %("2005-02-01T15:15:10.000-05:00"), ActiveSupport::JSON.encode(Time.local(2005, 2, 1, 15, 15, 10))
112
      end
113 114
    end
  end
115

116
  def test_hash_with_time_to_json
117
    with_standard_json_time_format(false) do
118
      assert_equal '{"time":"2009/01/01 00:00:00 +0000"}', { time: Time.utc(2009) }.to_json
119
    end
120 121
  end

D
Dan Barry 已提交
122 123 124 125
  def test_nested_hash_with_float
    assert_nothing_raised do
      hash = {
        "CHI" => {
126 127
          display_name: "chicago",
          latitude: 123.234
D
Dan Barry 已提交
128 129
        }
      }
S
Santiago Pastorino 已提交
130
      ActiveSupport::JSON.encode(hash)
D
Dan Barry 已提交
131 132 133
    end
  end

134
  def test_hash_like_with_options
135
    h = JSONTest::Hashlike.new
136
    json = h.to_json only: [:foo]
137

138
    assert_equal({ "foo" => "hello" }, JSON.parse(json))
139 140 141 142 143 144
  end

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

147
    assert_equal({ "foo" => "hello" }, JSON.parse(json))
148 149 150 151 152 153
  end

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

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

159 160
  def test_hash_should_pass_encoding_options_to_children_in_as_json
    person = {
161 162 163 164
      name: "John",
      address: {
        city: "London",
        country: "UK"
165 166
      }
    }
167
    json = person.as_json only: [:address, :city]
168

169
    assert_equal({ "address" => { "city" => "London" } }, json)
170 171 172 173
  end

  def test_hash_should_pass_encoding_options_to_children_in_to_json
    person = {
174 175 176 177
      name: "John",
      address: {
        city: "London",
        country: "UK"
178 179
      }
    }
180
    json = person.to_json only: [:address, :city]
181 182 183 184 185 186

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

  def test_array_should_pass_encoding_options_to_children_in_as_json
    people = [
187 188
      { name: "John", address: { city: "London", country: "UK" } },
      { name: "Jean", address: { city: "Paris" , country: "France" } }
189
    ]
190
    json = people.as_json only: [:address, :city]
191
    expected = [
192 193
      { "address" => { "city" => "London" } },
      { "address" => { "city" => "Paris" } }
194 195 196 197 198 199 200
    ]

    assert_equal(expected, json)
  end

  def test_array_should_pass_encoding_options_to_children_in_to_json
    people = [
201 202
      { name: "John", address: { city: "London", country: "UK" } },
      { name: "Jean", address: { city: "Paris" , country: "France" } }
203
    ]
204
    json = people.to_json only: [:address, :city]
205 206 207 208

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

209 210 211 212
  People = Class.new(BasicObject) do
    include Enumerable
    def initialize()
      @people = [
213 214
        { name: "John", address: { city: "London", country: "UK" } },
        { name: "Jean", address: { city: "Paris" , country: "France" } }
215 216 217 218 219 220 221 222 223 224 225
      ]
    end
    def each(*, &blk)
      @people.each do |p|
        yield p if blk
        p
      end.each
    end
  end

  def test_enumerable_should_generate_json_with_as_json
226
    json = People.new.as_json only: [:address, :city]
227
    expected = [
228 229
      { "address" => { "city" => "London" } },
      { "address" => { "city" => "Paris" } }
230
    ]
231 232 233 234 235

    assert_equal(expected, json)
  end

  def test_enumerable_should_generate_json_with_to_json
236
    json = People.new.to_json only: [:address, :city]
237 238 239 240
    assert_equal(%([{"address":{"city":"London"}},{"address":{"city":"Paris"}}]), json)
  end

  def test_enumerable_should_pass_encoding_options_to_children_in_as_json
241
    json = People.new.each.as_json only: [:address, :city]
242
    expected = [
243 244
      { "address" => { "city" => "London" } },
      { "address" => { "city" => "Paris" } }
245 246 247 248 249 250
    ]

    assert_equal(expected, json)
  end

  def test_enumerable_should_pass_encoding_options_to_children_in_to_json
251
    json = People.new.each.to_json only: [:address, :city]
252 253 254 255

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

256 257 258
  class CustomWithOptions
    attr_accessor :foo, :bar

259
    def as_json(options = {})
260 261 262 263 264
      options[:only] = %w(foo bar)
      super(options)
    end
  end

G
Godfrey Chan 已提交
265
  def test_hash_to_json_should_not_keep_options_around
266 267 268 269
    f = CustomWithOptions.new
    f.foo = "hello"
    f.bar = "world"

270
    hash = { "foo" => f, "other_hash" => { "foo" => "other_foo", "test" => "other_test" } }
271 272
    assert_equal({ "foo" => { "foo" => "hello", "bar" => "world" },
                  "other_hash" => { "foo" => "other_foo", "test" => "other_test" } }, ActiveSupport::JSON.decode(hash.to_json))
273 274
  end

G
Godfrey Chan 已提交
275 276 277 278 279
  def test_array_to_json_should_not_keep_options_around
    f = CustomWithOptions.new
    f.foo = "hello"
    f.bar = "world"

280
    array = [f, { "foo" => "other_foo", "test" => "other_test" }]
281 282
    assert_equal([{ "foo" => "hello", "bar" => "world" },
                  { "foo" => "other_foo", "test" => "other_test" }], ActiveSupport::JSON.decode(array.to_json))
G
Godfrey Chan 已提交
283 284
  end

285 286 287 288 289 290
  class OptionsTest
    def as_json(options = :default)
      options
    end
  end

291 292
  def test_hash_as_json_without_options
    json = { foo: OptionsTest.new }.as_json
293
    assert_equal({ "foo" => :default }, json)
294 295 296 297 298 299 300
  end

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

A
Alexey Nayden 已提交
301
  def test_struct_encoding
302 303 304 305 306 307
    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
A
Alexey Nayden 已提交
308 309 310 311 312 313 314 315 316 317 318

    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

319
    assert_equal({ "name" => "David",
320 321
                  "sub" => {
                    "name" => "David",
322
                    "date" => "2010-01-01" } }, ActiveSupport::JSON.decode(json_custom))
323

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

327
    assert_equal({ "name" => "David", "date" => "2010-01-01" },
328
                 ActiveSupport::JSON.decode(json_string_and_date))
A
Alexey Nayden 已提交
329
  end
330

331 332 333 334 335 336
  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

337 338 339 340 341 342 343
  class HashWithAsJson < Hash
    attr_accessor :as_json_called

    def initialize(*)
      super
    end

344
    def as_json(options = {})
345 346 347 348 349
      @as_json_called = true
      super
    end
  end

350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
  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

382 383
  def test_twz_to_json_with_use_standard_json_time_format_config_set_to_false
    with_standard_json_time_format(false) do
384
      zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
385 386 387 388 389 390 391
      time = ActiveSupport::TimeWithZone.new(Time.utc(2000), zone)
      assert_equal "\"1999/12/31 19:00:00 -0500\"", ActiveSupport::JSON.encode(time)
    end
  end

  def test_twz_to_json_with_use_standard_json_time_format_config_set_to_true
    with_standard_json_time_format(true) do
392
      zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
393 394 395 396 397
      time = ActiveSupport::TimeWithZone.new(Time.utc(2000), zone)
      assert_equal "\"1999-12-31T19:00:00.000-05:00\"", ActiveSupport::JSON.encode(time)
    end
  end

398
  def test_twz_to_json_with_custom_time_precision
399
    with_standard_json_time_format(true) do
400
      with_time_precision(0) do
401
        zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
402 403 404
        time = ActiveSupport::TimeWithZone.new(Time.utc(2000), zone)
        assert_equal "\"1999-12-31T19:00:00-05:00\"", ActiveSupport::JSON.encode(time)
      end
405
    end
406 407 408 409
  end

  def test_time_to_json_with_custom_time_precision
    with_standard_json_time_format(true) do
410 411 412
      with_time_precision(0) do
        assert_equal "\"2000-01-01T00:00:00Z\"", ActiveSupport::JSON.encode(Time.utc(2000))
      end
413 414 415 416 417
    end
  end

  def test_datetime_to_json_with_custom_time_precision
    with_standard_json_time_format(true) do
418 419 420
      with_time_precision(0) do
        assert_equal "\"2000-01-01T00:00:00+00:00\"", ActiveSupport::JSON.encode(DateTime.new(2000))
      end
421
    end
422 423 424
  end

  def test_twz_to_json_when_wrapping_a_date_time
425
    zone = ActiveSupport::TimeZone["Eastern Time (US & Canada)"]
426 427 428 429
    time = ActiveSupport::TimeWithZone.new(DateTime.new(2000), zone)
    assert_equal '"1999-12-31T19:00:00.000-05:00"', ActiveSupport::JSON.encode(time)
  end

430 431 432 433 434
  def test_exception_to_json
    exception = Exception.new("foo")
    assert_equal '"foo"', ActiveSupport::JSON.encode(exception)
  end

435 436
  class InfiniteNumber
    def as_json(options = nil)
A
Andrew White 已提交
437
      { "number" => Float::INFINITY }
438 439 440 441
    end
  end

  def test_to_json_works_when_as_json_returns_infinite_number
A
Andrew White 已提交
442
    assert_equal '{"number":null}', InfiniteNumber.new.to_json
443 444 445 446
  end

  class NaNNumber
    def as_json(options = nil)
A
Andrew White 已提交
447
      { "number" => Float::INFINITY }
448 449 450 451
    end
  end

  def test_to_json_works_when_as_json_returns_NaN_number
A
Andrew White 已提交
452
    assert_equal '{"number":null}', NaNNumber.new.to_json
453 454
  end

455
  protected
456

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

461 462 463 464 465 466
    def with_standard_json_time_format(boolean = true)
      old, ActiveSupport.use_standard_json_time_format = ActiveSupport.use_standard_json_time_format, boolean
      yield
    ensure
      ActiveSupport.use_standard_json_time_format = old
    end
467 468 469 470 471 472 473 474

    def with_time_precision(value)
      old_value = ActiveSupport::JSON::Encoding.time_precision
      ActiveSupport::JSON::Encoding.time_precision = value
      yield
    ensure
      ActiveSupport::JSON::Encoding.time_precision = old_value
    end
475
end