1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
|
#!/usr/bin/env ruby
# frozen_string_literal: true
$LOAD_PATH << __dir__
require 'helper'
# Oj.mimic_JSON
require 'rails/all'
require 'active_model'
require 'active_model_serializers'
require 'active_support/json'
require 'active_support/time'
require 'active_support/all'
require 'oj/active_support_helper'
Oj.mimic_JSON
class Category
include ActiveModel::Model
include ActiveModel::SerializerSupport
attr_accessor :id, :name
def initialize(id, name)
@id = id
@name = name
end
end
class CategorySerializer < ActiveModel::Serializer
attributes :id, :name
end
class MimicRails < Minitest::Test
def test_mimic_exception
ActiveSupport::JSON.decode('{')
puts 'Failed'
rescue ActiveSupport::JSON.parse_error
assert(true)
rescue Exception
assert(false, 'Expected a JSON::ParserError')
end
def test_dump_string
Oj.default_options= {:indent => 2}
json = ActiveSupport::JSON.encode([1, true, nil])
assert_equal(%{[
1,
true,
null
]
}, json)
end
def test_dump_rational
Oj.default_options= {:indent => 2}
json = ActiveSupport::JSON.encode([1, true, Rational(1)])
assert_equal(%{[
1,
true,
"1/1"
]
}, json)
end
def test_dump_range
Oj.default_options= {:indent => 2}
json = ActiveSupport::JSON.encode([1, true, '01'..'12'])
assert_equal(%{[
1,
true,
"01..12"
]
}, json)
end
def test_dump_object
Oj.default_options= {:indent => 2}
category = Category.new(1, 'test')
serializer = CategorySerializer.new(category)
serializer.to_json()
puts "*** serializer.to_json() #{serializer.to_json()}"
serializer.as_json()
puts "*** serializer.as_json() #{serializer.as_json()}"
JSON.dump(serializer)
puts "*** JSON.dump(serializer) #{JSON.dump(serializer)}"
puts "*** category.to_json() #{category.to_json()}"
puts "*** category.as_json() #{category.as_json()}"
puts "*** JSON.dump(serializer) #{JSON.dump(category)}"
puts "*** Oj.dump(serializer) #{Oj.dump(category)}"
end
def test_dump_object_array
Oj.default_options= {:indent => 2}
cat1 = Category.new(1, 'test')
cat2 = Category.new(2, 'test')
a = Array.wrap([cat1, cat2])
# serializer = CategorySerializer.new(a)
puts "*** a.to_json() #{a.to_json()}"
puts "*** a.as_json() #{a.as_json()}"
puts "*** JSON.dump(a) #{JSON.dump(a)}"
puts "*** Oj.dump(a) #{Oj.dump(a)}"
end
def test_dump_time
Oj.default_options= {:indent => 2}
now = ActiveSupport::TimeZone['America/Chicago'].parse('2014-11-01 13:20:47')
json = Oj.dump(now, mode: :object, time_format: :xmlschema)
# puts "*** json: #{json}"
oj_dump = Oj.load(json, mode: :object, time_format: :xmlschema)
# puts "Now: #{now}\n Oj: #{oj_dump}"
assert_equal('2014-11-01T13:20:47-05:00', oj_dump.xmlschema)
end
end # MimicRails
|