#!/usr/bin/env ruby require 'test/unit' require 'json/add/core' require 'date' class TC_JSONAddition < Test::Unit::TestCase include JSON class A def initialize(a) @a = a end attr_reader :a def ==(other) a == other.a end def self.json_create(object) new(*object['args']) end def to_json(*args) { 'json_class' => self.class.name, 'args' => [ @a ], }.to_json(*args) end end class B def self.json_creatable? false end def to_json(*args) { 'json_class' => self.class.name, }.to_json(*args) end end class C def self.json_creatable? false end def to_json(*args) { 'json_class' => 'TC_JSONAddition::Nix', }.to_json(*args) end end def test_extended_json a = A.new(666) assert A.json_creatable? json = generate(a) a_again = JSON.parse(json) assert_kind_of a.class, a_again assert_equal a, a_again end def test_extended_json_disabled a = A.new(666) assert A.json_creatable? json = generate(a) a_again = JSON.parse(json, :create_additions => true) assert_kind_of a.class, a_again assert_equal a, a_again a_hash = JSON.parse(json, :create_additions => false) assert_kind_of Hash, a_hash assert_equal( {"args"=>[666], "json_class"=>"TC_JSONAddition::A"}.sort_by { |k,| k }, a_hash.sort_by { |k,| k } ) end def test_extended_json_fail1 b = B.new assert !B.json_creatable? json = generate(b) assert_equal({ "json_class"=>"TC_JSONAddition::B" }, JSON.parse(json)) end def test_extended_json_fail2 c = C.new assert !C.json_creatable? json = generate(c) assert_raise(ArgumentError) { JSON.parse(json) } end def test_raw_strings raw = '' raw_array = [] for i in 0..255 raw << i raw_array << i end json = raw.to_json_raw json_raw_object = raw.to_json_raw_object hash = { 'json_class' => 'String', 'raw'=> raw_array } assert_equal hash, json_raw_object json_raw = < e e_json = JSON.generate e e_again = JSON e_json assert_kind_of TypeError, e_again assert_equal e.message, e_again.message assert_equal e.backtrace, e_again.backtrace end assert_equal(/foo/, JSON(JSON(/foo/))) assert_equal(/foo/i, JSON(JSON(/foo/i))) end def test_utc_datetime now = Time.now d = DateTime.parse(now.to_s) # usual case assert d, JSON.parse(d.to_json) d = DateTime.parse(now.utc.to_s) # of = 0 assert d, JSON.parse(d.to_json) d = DateTime.civil(2008, 6, 17, 11, 48, 32, 1) # of = 1 / 12 => 1/12 assert d, JSON.parse(d.to_json) d = DateTime.civil(2008, 6, 17, 11, 48, 32, 12) # of = 12 / 12 => 12 assert d, JSON.parse(d.to_json) end end