summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFlorian Frank <flori@ping.de>2015-06-15 10:06:27 +0200
committerFlorian Frank <flori@ping.de>2015-06-15 10:06:27 +0200
commit6f907a9142e83141a2e01fdddfd18b2013244cd6 (patch)
tree9fa8f8571594f300a2f6038948c4e96842359ff6
parent0ece7a0404cebb8fb2ce4e6110e70fd05fb48d6b (diff)
downloadjson-6f907a9142e83141a2e01fdddfd18b2013244cd6.tar.gz
Refactor tests and make pure parser green
-rw-r--r--VERSION2
-rw-r--r--json.gemspecbin4898 -> 4423 bytes
-rw-r--r--json_pure.gemspec10
-rw-r--r--lib/json/common.rb20
-rw-r--r--lib/json/pure/parser.rb51
-rw-r--r--lib/json/version.rb2
-rw-r--r--tests/fixtures/fail1.json1
-rw-r--r--tests/fixtures/obsolete_fail1.json1
-rw-r--r--[-rwxr-xr-x]tests/json_addition_test.rb (renamed from tests/test_json_addition.rb)41
-rw-r--r--tests/json_common_interface_test.rb101
-rw-r--r--tests/json_encoding_test.rb109
-rw-r--r--tests/json_ext_parser_test.rb17
-rw-r--r--[-rwxr-xr-x]tests/json_fixtures_test.rb (renamed from tests/test_json_fixtures.rb)7
-rw-r--r--[-rwxr-xr-x]tests/json_generator_test.rb (renamed from tests/test_json_generate.rb)59
-rw-r--r--tests/json_generic_object_test.rb (renamed from tests/test_json_generic_object.rb)20
-rw-r--r--tests/json_parser_test.rb433
-rw-r--r--tests/json_string_matching_test.rb37
-rw-r--r--tests/test_helper.rb1
-rwxr-xr-xtests/test_json.rb538
-rw-r--r--tests/test_json_encoding.rb64
-rw-r--r--tests/test_json_string_matching.rb38
-rwxr-xr-xtests/test_json_unicode.rb71
22 files changed, 813 insertions, 810 deletions
diff --git a/VERSION b/VERSION
index a7ee35a..227cea2 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.8.3
+2.0.0
diff --git a/json.gemspec b/json.gemspec
index 47678e7..75f1ae9 100644
--- a/json.gemspec
+++ b/json.gemspec
Binary files differ
diff --git a/json_pure.gemspec b/json_pure.gemspec
index eaa76a7..9b2fe03 100644
--- a/json_pure.gemspec
+++ b/json_pure.gemspec
@@ -1,24 +1,24 @@
# -*- encoding: utf-8 -*-
-# stub: json_pure 1.8.3 ruby lib
+# stub: json_pure 2.0.0 ruby lib
Gem::Specification.new do |s|
s.name = "json_pure"
- s.version = "1.8.3"
+ s.version = "2.0.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.authors = ["Florian Frank"]
- s.date = "2015-06-13"
+ s.date = "2015-06-15"
s.description = "This is a JSON implementation in pure Ruby."
s.email = "flori@ping.de"
s.extra_rdoc_files = ["README.rdoc"]
- s.files = ["./tests/test_helper.rb", "./tests/test_json.rb", "./tests/test_json_addition.rb", "./tests/test_json_encoding.rb", "./tests/test_json_fixtures.rb", "./tests/test_json_generate.rb", "./tests/test_json_generic_object.rb", "./tests/test_json_string_matching.rb", "./tests/test_json_unicode.rb", ".gitignore", ".travis.yml", "CHANGES", "COPYING", "COPYING-json-jruby", "GPL", "Gemfile", "README-json-jruby.markdown", "README.rdoc", "Rakefile", "TODO", "VERSION", "data/example.json", "data/index.html", "data/prototype.js", "diagrams/.keep", "ext/json/ext/fbuffer/fbuffer.h", "ext/json/ext/generator/depend", "ext/json/ext/generator/extconf.rb", "ext/json/ext/generator/generator.c", "ext/json/ext/generator/generator.h", "ext/json/ext/parser/depend", "ext/json/ext/parser/extconf.rb", "ext/json/ext/parser/parser.c", "ext/json/ext/parser/parser.h", "ext/json/ext/parser/parser.rl", "ext/json/extconf.rb", "install.rb", "java/src/json/ext/ByteListTranscoder.java", "java/src/json/ext/Generator.java", "java/src/json/ext/GeneratorMethods.java", "java/src/json/ext/GeneratorService.java", "java/src/json/ext/GeneratorState.java", "java/src/json/ext/OptionsReader.java", "java/src/json/ext/Parser.java", "java/src/json/ext/Parser.rl", "java/src/json/ext/ParserService.java", "java/src/json/ext/RuntimeInfo.java", "java/src/json/ext/StringDecoder.java", "java/src/json/ext/StringEncoder.java", "java/src/json/ext/Utils.java", "json-java.gemspec", "json.gemspec", "json_pure.gemspec", "lib/json.rb", "lib/json/add/bigdecimal.rb", "lib/json/add/complex.rb", "lib/json/add/core.rb", "lib/json/add/date.rb", "lib/json/add/date_time.rb", "lib/json/add/exception.rb", "lib/json/add/ostruct.rb", "lib/json/add/range.rb", "lib/json/add/rational.rb", "lib/json/add/regexp.rb", "lib/json/add/struct.rb", "lib/json/add/symbol.rb", "lib/json/add/time.rb", "lib/json/common.rb", "lib/json/ext.rb", "lib/json/ext/.keep", "lib/json/generic_object.rb", "lib/json/pure.rb", "lib/json/pure/generator.rb", "lib/json/pure/parser.rb", "lib/json/version.rb", "tests/fixtures/fail1.json", "tests/fixtures/fail10.json", "tests/fixtures/fail11.json", "tests/fixtures/fail12.json", "tests/fixtures/fail13.json", "tests/fixtures/fail14.json", "tests/fixtures/fail18.json", "tests/fixtures/fail19.json", "tests/fixtures/fail2.json", "tests/fixtures/fail20.json", "tests/fixtures/fail21.json", "tests/fixtures/fail22.json", "tests/fixtures/fail23.json", "tests/fixtures/fail24.json", "tests/fixtures/fail25.json", "tests/fixtures/fail27.json", "tests/fixtures/fail28.json", "tests/fixtures/fail3.json", "tests/fixtures/fail4.json", "tests/fixtures/fail5.json", "tests/fixtures/fail6.json", "tests/fixtures/fail7.json", "tests/fixtures/fail8.json", "tests/fixtures/fail9.json", "tests/fixtures/pass1.json", "tests/fixtures/pass15.json", "tests/fixtures/pass16.json", "tests/fixtures/pass17.json", "tests/fixtures/pass2.json", "tests/fixtures/pass26.json", "tests/fixtures/pass3.json", "tests/test_helper.rb", "tests/test_json.rb", "tests/test_json_addition.rb", "tests/test_json_encoding.rb", "tests/test_json_fixtures.rb", "tests/test_json_generate.rb", "tests/test_json_generic_object.rb", "tests/test_json_string_matching.rb", "tests/test_json_unicode.rb", "tools/fuzz.rb", "tools/server.rb"]
+ s.files = ["./tests/test_helper.rb", ".gitignore", ".travis.yml", "CHANGES", "COPYING", "COPYING-json-jruby", "GPL", "Gemfile", "README-json-jruby.markdown", "README.rdoc", "Rakefile", "TODO", "VERSION", "data/example.json", "data/index.html", "data/prototype.js", "diagrams/.keep", "ext/json/ext/fbuffer/fbuffer.h", "ext/json/ext/generator/depend", "ext/json/ext/generator/extconf.rb", "ext/json/ext/generator/generator.c", "ext/json/ext/generator/generator.h", "ext/json/ext/parser/depend", "ext/json/ext/parser/extconf.rb", "ext/json/ext/parser/parser.c", "ext/json/ext/parser/parser.h", "ext/json/ext/parser/parser.rl", "ext/json/extconf.rb", "install.rb", "java/src/json/ext/ByteListTranscoder.java", "java/src/json/ext/Generator.java", "java/src/json/ext/GeneratorMethods.java", "java/src/json/ext/GeneratorService.java", "java/src/json/ext/GeneratorState.java", "java/src/json/ext/OptionsReader.java", "java/src/json/ext/Parser.java", "java/src/json/ext/Parser.rl", "java/src/json/ext/ParserService.java", "java/src/json/ext/RuntimeInfo.java", "java/src/json/ext/StringDecoder.java", "java/src/json/ext/StringEncoder.java", "java/src/json/ext/Utils.java", "json-java.gemspec", "json.gemspec", "json_pure.gemspec", "lib/json.rb", "lib/json/add/bigdecimal.rb", "lib/json/add/complex.rb", "lib/json/add/core.rb", "lib/json/add/date.rb", "lib/json/add/date_time.rb", "lib/json/add/exception.rb", "lib/json/add/ostruct.rb", "lib/json/add/range.rb", "lib/json/add/rational.rb", "lib/json/add/regexp.rb", "lib/json/add/struct.rb", "lib/json/add/symbol.rb", "lib/json/add/time.rb", "lib/json/common.rb", "lib/json/ext.rb", "lib/json/ext/.keep", "lib/json/generic_object.rb", "lib/json/pure.rb", "lib/json/pure/generator.rb", "lib/json/pure/parser.rb", "lib/json/version.rb", "tests/fixtures/fail10.json", "tests/fixtures/fail11.json", "tests/fixtures/fail12.json", "tests/fixtures/fail13.json", "tests/fixtures/fail14.json", "tests/fixtures/fail18.json", "tests/fixtures/fail19.json", "tests/fixtures/fail2.json", "tests/fixtures/fail20.json", "tests/fixtures/fail21.json", "tests/fixtures/fail22.json", "tests/fixtures/fail23.json", "tests/fixtures/fail24.json", "tests/fixtures/fail25.json", "tests/fixtures/fail27.json", "tests/fixtures/fail28.json", "tests/fixtures/fail3.json", "tests/fixtures/fail4.json", "tests/fixtures/fail5.json", "tests/fixtures/fail6.json", "tests/fixtures/fail7.json", "tests/fixtures/fail8.json", "tests/fixtures/fail9.json", "tests/fixtures/obsolete_fail1.json", "tests/fixtures/pass1.json", "tests/fixtures/pass15.json", "tests/fixtures/pass16.json", "tests/fixtures/pass17.json", "tests/fixtures/pass2.json", "tests/fixtures/pass26.json", "tests/fixtures/pass3.json", "tests/json_addition_test.rb", "tests/json_common_interface_test.rb", "tests/json_encoding_test.rb", "tests/json_ext_parser_test.rb", "tests/json_fixtures_test.rb", "tests/json_generator_test.rb", "tests/json_generic_object_test.rb", "tests/json_parser_test.rb", "tests/json_string_matching_test.rb", "tests/test_helper.rb", "tools/fuzz.rb", "tools/server.rb"]
s.homepage = "http://flori.github.com/json"
s.licenses = ["Ruby"]
s.rdoc_options = ["--title", "JSON implemention for ruby", "--main", "README.rdoc"]
s.rubygems_version = "2.4.6"
s.summary = "JSON Implementation for Ruby"
- s.test_files = ["./tests/test_helper.rb", "./tests/test_json.rb", "./tests/test_json_addition.rb", "./tests/test_json_encoding.rb", "./tests/test_json_fixtures.rb", "./tests/test_json_generate.rb", "./tests/test_json_generic_object.rb", "./tests/test_json_string_matching.rb", "./tests/test_json_unicode.rb"]
+ s.test_files = ["./tests/test_helper.rb"]
if s.respond_to? :specification_version then
s.specification_version = 4
diff --git a/lib/json/common.rb b/lib/json/common.rb
index f44184e..1215d41 100644
--- a/lib/json/common.rb
+++ b/lib/json/common.rb
@@ -3,12 +3,12 @@ require 'json/generic_object'
module JSON
class << self
- # If _object_ is string-like, parse the string and return the parsed result
- # as a Ruby data structure. Otherwise generate a JSON text from the Ruby
- # data structure object and return it.
+ # If _object_ is string-like, parse the string and return the parsed
+ # result as a Ruby data structure. Otherwise generate a JSON text from the
+ # Ruby data structure object and return it.
#
- # The _opts_ argument is passed through to generate/parse respectively. See
- # generate and parse for their documentation.
+ # The _opts_ argument is passed through to generate/parse respectively.
+ # See generate and parse for their documentation.
def [](object, opts = {})
if object.respond_to? :to_str
JSON.parse(object.to_str, opts)
@@ -138,8 +138,8 @@ module JSON
# _opts_ can have the following
# keys:
# * *max_nesting*: The maximum depth of nesting allowed in the parsed data
- # structures. Disable depth checking with :max_nesting => false. It defaults
- # to 100.
+ # structures. Disable depth checking with :max_nesting => false. It
+ # defaults to 100.
# * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in
# defiance of RFC 4627 to be parsed by the Parser. This option defaults
# to false.
@@ -161,9 +161,9 @@ module JSON
#
# _opts_ can have the following keys:
# * *max_nesting*: The maximum depth of nesting allowed in the parsed data
- # structures. Enable depth checking with :max_nesting => anInteger. The parse!
- # methods defaults to not doing max depth checking: This can be dangerous
- # if someone wants to fill up your stack.
+ # structures. Enable depth checking with :max_nesting => anInteger. The
+ # parse! methods defaults to not doing max depth checking: This can be
+ # dangerous if someone wants to fill up your stack.
# * *allow_nan*: If set to true, allow NaN, Infinity, and -Infinity in
# defiance of RFC 4627 to be parsed by the Parser. This option defaults
# to true.
diff --git a/lib/json/pure/parser.rb b/lib/json/pure/parser.rb
index 9e40eb7..acabe39 100644
--- a/lib/json/pure/parser.rb
+++ b/lib/json/pure/parser.rb
@@ -48,7 +48,7 @@ module JSON
)+
)mx
- UNPARSED = Object.new
+ UNPARSED = Object.new.freeze
# Creates a new JSON::Pure::Parser instance for the string _source_.
#
@@ -107,39 +107,21 @@ module JSON
@current_nesting = 0
end
- # Parses the current JSON string _source_ and returns the complete data
- # structure as a result.
+ # Parses the current JSON string _source_ and returns the
+ # complete data structure as a result.
def parse
reset
obj = nil
- if @quirks_mode
- while !eos? && skip(IGNORE)
- end
- if eos?
- raise ParserError, "source did not contain any JSON!"
- else
- obj = parse_value
- obj == UNPARSED and raise ParserError, "source did not contain any JSON!"
- end
+ while !eos? && skip(IGNORE) do end
+ if eos?
+ raise ParserError, "source is not valid JSON!"
else
- until eos?
- case
- when scan(OBJECT_OPEN)
- obj and raise ParserError, "source '#{peek(20)}' not in JSON!"
- @current_nesting = 1
- obj = parse_object
- when scan(ARRAY_OPEN)
- obj and raise ParserError, "source '#{peek(20)}' not in JSON!"
- @current_nesting = 1
- obj = parse_array
- when skip(IGNORE)
- ;
- else
- raise ParserError, "source '#{peek(20)}' not in JSON!"
- end
- end
- obj or raise ParserError, "source did not contain any JSON!"
+ obj = parse_value
+ UNPARSED.equal?(obj) and raise ParserError,
+ "source is not valid JSON!"
end
+ while !eos? && skip(IGNORE) do end
+ eos? or raise ParserError, "source is not valid JSON!"
obj
end
@@ -149,7 +131,8 @@ module JSON
if source.respond_to?(:to_str)
source = source.to_str
else
- raise TypeError, "#{source.inspect} is not like a string"
+ raise TypeError,
+ "#{source.inspect} is not like a string"
end
if defined?(::Encoding)
source = source.encode(::Encoding::UTF_8)
@@ -222,7 +205,7 @@ module JSON
false
when scan(NULL)
nil
- when (string = parse_string) != UNPARSED
+ when !UNPARSED.equal?(string = parse_string)
string
when scan(ARRAY_OPEN)
@current_nesting += 1
@@ -252,7 +235,7 @@ module JSON
delim = false
until eos?
case
- when (value = parse_value) != UNPARSED
+ when !UNPARSED.equal?(value = parse_value)
delim = false
result << value
skip(IGNORE)
@@ -284,13 +267,13 @@ module JSON
delim = false
until eos?
case
- when (string = parse_string) != UNPARSED
+ when !UNPARSED.equal?(string = parse_string)
skip(IGNORE)
unless scan(PAIR_DELIMITER)
raise ParserError, "expected ':' in object at '#{peek(20)}'!"
end
skip(IGNORE)
- unless (value = parse_value).equal? UNPARSED
+ unless UNPARSED.equal?(value = parse_value)
result[@symbolize_names ? string.to_sym : string] = value
delim = false
skip(IGNORE)
diff --git a/lib/json/version.rb b/lib/json/version.rb
index 5a4013d..b91ccd7 100644
--- a/lib/json/version.rb
+++ b/lib/json/version.rb
@@ -1,6 +1,6 @@
module JSON
# JSON version
- VERSION = '1.8.3'
+ VERSION = '2.0.0'
VERSION_ARRAY = VERSION.split(/\./).map { |x| x.to_i } # :nodoc:
VERSION_MAJOR = VERSION_ARRAY[0] # :nodoc:
VERSION_MINOR = VERSION_ARRAY[1] # :nodoc:
diff --git a/tests/fixtures/fail1.json b/tests/fixtures/fail1.json
deleted file mode 100644
index 6216b86..0000000
--- a/tests/fixtures/fail1.json
+++ /dev/null
@@ -1 +0,0 @@
-"A JSON payload should be an object or array, not a string." \ No newline at end of file
diff --git a/tests/fixtures/obsolete_fail1.json b/tests/fixtures/obsolete_fail1.json
new file mode 100644
index 0000000..98b77de
--- /dev/null
+++ b/tests/fixtures/obsolete_fail1.json
@@ -0,0 +1 @@
+"A JSON payload should be an object or array, not a string."
diff --git a/tests/test_json_addition.rb b/tests/json_addition_test.rb
index 1105705..128f34a 100755..100644
--- a/tests/test_json_addition.rb
+++ b/tests/json_addition_test.rb
@@ -1,6 +1,3 @@
-#!/usr/bin/env ruby
-# -*- coding:utf-8 -*-
-
require 'test_helper'
require 'json/add/core'
require 'json/add/complex'
@@ -9,7 +6,7 @@ require 'json/add/bigdecimal'
require 'json/add/ostruct'
require 'date'
-class TestJSONAddition < Test::Unit::TestCase
+class JSONAdditionTest < Test::Unit::TestCase
include JSON
class A
@@ -63,7 +60,7 @@ class TestJSONAddition < Test::Unit::TestCase
def to_json(*args)
{
- 'json_class' => 'TestJSONAddition::Nix',
+ 'json_class' => 'JSONAdditionTest::Nix',
}.to_json(*args)
end
end
@@ -72,7 +69,7 @@ class TestJSONAddition < Test::Unit::TestCase
a = A.new(666)
assert A.json_creatable?
json = generate(a)
- a_again = JSON.parse(json, :create_additions => true)
+ a_again = parse(json, :create_additions => true)
assert_kind_of a.class, a_again
assert_equal a, a_again
end
@@ -81,7 +78,7 @@ class TestJSONAddition < Test::Unit::TestCase
a = A.new(666)
assert A.json_creatable?
json = generate(a)
- a_hash = JSON.parse(json)
+ a_hash = parse(json)
assert_kind_of Hash, a_hash
end
@@ -89,13 +86,13 @@ class TestJSONAddition < Test::Unit::TestCase
a = A.new(666)
assert A.json_creatable?
json = generate(a)
- a_again = JSON.parse(json, :create_additions => true)
+ a_again = 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)
+ a_hash = parse(json, :create_additions => false)
assert_kind_of Hash, a_hash
assert_equal(
- {"args"=>[666], "json_class"=>"TestJSONAddition::A"}.sort_by { |k,| k },
+ {"args"=>[666], "json_class"=>"JSONAdditionTest::A"}.sort_by { |k,| k },
a_hash.sort_by { |k,| k }
)
end
@@ -104,14 +101,14 @@ class TestJSONAddition < Test::Unit::TestCase
b = B.new
assert !B.json_creatable?
json = generate(b)
- assert_equal({ "json_class"=>"TestJSONAddition::B" }, JSON.parse(json))
+ assert_equal({ "json_class"=>"JSONAdditionTest::B" }, parse(json))
end
def test_extended_json_fail2
c = C.new
assert !C.json_creatable?
json = generate(c)
- assert_raises(ArgumentError, NameError) { JSON.parse(json, :create_additions => true) }
+ assert_raises(ArgumentError, NameError) { parse(json, :create_additions => true) }
end
def test_raw_strings
@@ -129,7 +126,7 @@ class TestJSONAddition < Test::Unit::TestCase
assert_match(/\A\{.*\}\z/, json)
assert_match(/"json_class":"String"/, json)
assert_match(/"raw":\[0,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,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255\]/, json)
- raw_again = JSON.parse(json, :create_additions => true)
+ raw_again = parse(json, :create_additions => true)
assert_equal raw, raw_again
end
@@ -166,19 +163,19 @@ class TestJSONAddition < Test::Unit::TestCase
def test_utc_datetime
now = Time.now
- d = DateTime.parse(now.to_s, :create_additions => true) # usual case
- assert_equal d, JSON.parse(d.to_json, :create_additions => true)
- d = DateTime.parse(now.utc.to_s) # of = 0
- assert_equal d, JSON.parse(d.to_json, :create_additions => true)
+ d = DateTime.parse(now.to_s, :create_additions => true) # usual case
+ assert_equal d, parse(d.to_json, :create_additions => true)
+ d = DateTime.parse(now.utc.to_s) # of = 0
+ assert_equal d, parse(d.to_json, :create_additions => true)
d = DateTime.civil(2008, 6, 17, 11, 48, 32, Rational(1,24))
- assert_equal d, JSON.parse(d.to_json, :create_additions => true)
+ assert_equal d, parse(d.to_json, :create_additions => true)
d = DateTime.civil(2008, 6, 17, 11, 48, 32, Rational(12,24))
- assert_equal d, JSON.parse(d.to_json, :create_additions => true)
+ assert_equal d, parse(d.to_json, :create_additions => true)
end
def test_rational_complex
- assert_equal Rational(2, 9), JSON.parse(JSON(Rational(2, 9)), :create_additions => true)
- assert_equal Complex(2, 9), JSON.parse(JSON(Complex(2, 9)), :create_additions => true)
+ assert_equal Rational(2, 9), parse(JSON(Rational(2, 9)), :create_additions => true)
+ assert_equal Complex(2, 9), parse(JSON(Complex(2, 9)), :create_additions => true)
end
def test_bigdecimal
@@ -190,6 +187,6 @@ class TestJSONAddition < Test::Unit::TestCase
o = OpenStruct.new
# XXX this won't work; o.foo = { :bar => true }
o.foo = { 'bar' => true }
- assert_equal o, JSON.parse(JSON(o), :create_additions => true)
+ assert_equal o, parse(JSON(o), :create_additions => true)
end
end
diff --git a/tests/json_common_interface_test.rb b/tests/json_common_interface_test.rb
new file mode 100644
index 0000000..1fca19d
--- /dev/null
+++ b/tests/json_common_interface_test.rb
@@ -0,0 +1,101 @@
+require 'test_helper'
+require 'stringio'
+require 'tempfile'
+
+class JSONParserTest < Test::Unit::TestCase
+ include JSON
+
+ def setup
+ @hash = {
+ 'a' => 2,
+ 'b' => 3.141,
+ 'c' => 'c',
+ 'd' => [ 1, "b", 3.14 ],
+ 'e' => { 'foo' => 'bar' },
+ 'g' => "\"\0\037",
+ 'h' => 1000.0,
+ 'i' => 0.001
+ }
+ @json = '{"a":2,"b":3.141,"c":"c","d":[1,"b",3.14],"e":{"foo":"bar"},'\
+ '"g":"\\"\\u0000\\u001f","h":1.0E3,"i":1.0E-3}'
+ end
+
+
+ def test_index
+ end
+
+ def test_parser
+ end
+
+ def test_generator
+ end
+
+ def test_state
+ end
+
+ def test_create_id
+ end
+
+ def test_parse
+ end
+
+ def test_parse_bang
+ end
+
+ def test_generate
+ end
+
+ def test_fast_generate
+ end
+
+ def test_pretty_generate
+ end
+
+ def test_load
+ assert_equal @hash, JSON.load(@json)
+ tempfile = Tempfile.open('@json')
+ tempfile.write @json
+ tempfile.rewind
+ assert_equal @hash, JSON.load(tempfile)
+ stringio = StringIO.new(@json)
+ stringio.rewind
+ assert_equal @hash, JSON.load(stringio)
+ assert_equal nil, JSON.load(nil)
+ assert_equal nil, JSON.load('')
+ ensure
+ tempfile.close!
+ end
+
+ def test_load_with_options
+ small_hash = JSON("foo" => 'bar')
+ symbol_hash = { :foo => 'bar' }
+ assert_equal symbol_hash,
+ JSON.load(small_hash, nil, :symbolize_names => true)
+ end
+
+ def test_dump
+ too_deep = '[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]'
+ assert_equal too_deep, dump(eval(too_deep))
+ assert_kind_of String, Marshal.dump(eval(too_deep))
+ assert_raises(ArgumentError) { dump(eval(too_deep), 100) }
+ assert_raises(ArgumentError) { Marshal.dump(eval(too_deep), 100) }
+ assert_equal too_deep, dump(eval(too_deep), 101)
+ assert_kind_of String, Marshal.dump(eval(too_deep), 101)
+ output = StringIO.new
+ dump(eval(too_deep), output)
+ assert_equal too_deep, output.string
+ output = StringIO.new
+ dump(eval(too_deep), output, 101)
+ assert_equal too_deep, output.string
+ end
+
+ def test_dump_should_modify_defaults
+ max_nesting = JSON.dump_default_options[:max_nesting]
+ dump([], StringIO.new, 10)
+ assert_equal max_nesting, JSON.dump_default_options[:max_nesting]
+ end
+
+
+ def test_JSON
+ end
+end
diff --git a/tests/json_encoding_test.rb b/tests/json_encoding_test.rb
new file mode 100644
index 0000000..86335a1
--- /dev/null
+++ b/tests/json_encoding_test.rb
@@ -0,0 +1,109 @@
+require 'test_helper'
+
+class JSONEncodingTest < Test::Unit::TestCase
+ include JSON
+
+ def setup
+ @utf_8 = '"© ≠ €!"'
+ @parsed = "© ≠ €!"
+ @generated = '"\u00a9 \u2260 \u20ac!"'
+ if String.method_defined?(:encode)
+ @utf_16_data = @parsed.encode('utf-16be', 'utf-8')
+ @utf_16be = @utf_8.encode('utf-16be', 'utf-8')
+ @utf_16le = @utf_8.encode('utf-16le', 'utf-8')
+ @utf_32be = @utf_8.encode('utf-32be', 'utf-8')
+ @utf_32le = @utf_8.encode('utf-32le', 'utf-8')
+ else
+ require 'iconv'
+ @utf_16_data, = Iconv.iconv('utf-16be', 'utf-8', @parsed)
+ @utf_16be, = Iconv.iconv('utf-16be', 'utf-8', @utf_8)
+ @utf_16le, = Iconv.iconv('utf-16le', 'utf-8', @utf_8)
+ @utf_32be, = Iconv.iconv('utf-32be', 'utf-8', @utf_8)
+ @utf_32le, = Iconv.iconv('utf-32le', 'utf-8', @utf_8)
+ end
+ end
+
+ def test_parse
+ assert_equal @parsed, JSON.parse(@utf_8)
+ assert_equal @parsed, JSON.parse(@utf_16be)
+ assert_equal @parsed, JSON.parse(@utf_16le)
+ assert_equal @parsed, JSON.parse(@utf_32be)
+ assert_equal @parsed, JSON.parse(@utf_32le)
+ end
+
+ def test_generate
+ assert_equal @generated, JSON.generate(@parsed, :ascii_only => true)
+ if defined?(::Encoding)
+ assert_equal @generated, JSON.generate(@utf_16_data, :ascii_only => true)
+ else
+ # XXX checking of correct utf8 data is not as strict (yet?) without
+ # :ascii_only
+ assert_raises(JSON::GeneratorError) do
+ JSON.generate(@utf_16_data, :ascii_only => true)
+ end
+ end
+ end
+
+ def test_unicode
+ assert_equal '""', ''.to_json
+ assert_equal '"\\b"', "\b".to_json
+ assert_equal '"\u0001"', 0x1.chr.to_json
+ assert_equal '"\u001f"', 0x1f.chr.to_json
+ assert_equal '" "', ' '.to_json
+ assert_equal "\"#{0x7f.chr}\"", 0x7f.chr.to_json
+ utf8 = [ "© ≠ €! \01" ]
+ json = '["© ≠ €! \u0001"]'
+ assert_equal json, utf8.to_json(:ascii_only => false)
+ assert_equal utf8, parse(json)
+ json = '["\u00a9 \u2260 \u20ac! \u0001"]'
+ assert_equal json, utf8.to_json(:ascii_only => true)
+ assert_equal utf8, parse(json)
+ utf8 = ["\343\201\202\343\201\204\343\201\206\343\201\210\343\201\212"]
+ json = "[\"\343\201\202\343\201\204\343\201\206\343\201\210\343\201\212\"]"
+ assert_equal utf8, parse(json)
+ assert_equal json, utf8.to_json(:ascii_only => false)
+ utf8 = ["\343\201\202\343\201\204\343\201\206\343\201\210\343\201\212"]
+ assert_equal utf8, parse(json)
+ json = "[\"\\u3042\\u3044\\u3046\\u3048\\u304a\"]"
+ assert_equal json, utf8.to_json(:ascii_only => true)
+ assert_equal utf8, parse(json)
+ utf8 = ['საქართველო']
+ json = '["საქართველო"]'
+ assert_equal json, utf8.to_json(:ascii_only => false)
+ json = "[\"\\u10e1\\u10d0\\u10e5\\u10d0\\u10e0\\u10d7\\u10d5\\u10d4\\u10da\\u10dd\"]"
+ assert_equal json, utf8.to_json(:ascii_only => true)
+ assert_equal utf8, parse(json)
+ assert_equal '["Ã"]', generate(["Ã"], :ascii_only => false)
+ assert_equal '["\\u00c3"]', generate(["Ã"], :ascii_only => true)
+ assert_equal ["€"], parse('["\u20ac"]')
+ utf8 = ["\xf0\xa0\x80\x81"]
+ json = "[\"\xf0\xa0\x80\x81\"]"
+ assert_equal json, generate(utf8, :ascii_only => false)
+ assert_equal utf8, parse(json)
+ json = '["\ud840\udc01"]'
+ assert_equal json, generate(utf8, :ascii_only => true)
+ assert_equal utf8, parse(json)
+ end
+
+ def test_chars
+ (0..0x7f).each do |i|
+ json = '["\u%04x"]' % i
+ if RUBY_VERSION >= "1.9."
+ i = i.chr
+ end
+ assert_equal i, parse(json).first[0]
+ if i == ?\b
+ generated = generate(["" << i])
+ assert '["\b"]' == generated || '["\10"]' == generated
+ elsif [?\n, ?\r, ?\t, ?\f].include?(i)
+ assert_equal '[' << ('' << i).dump << ']', generate(["" << i])
+ elsif i.chr < 0x20.chr
+ assert_equal json, generate(["" << i])
+ end
+ end
+ assert_raise(JSON::GeneratorError) do
+ generate(["\x80"], :ascii_only => true)
+ end
+ assert_equal "\302\200", parse('["\u0080"]').first
+ end
+end
diff --git a/tests/json_ext_parser_test.rb b/tests/json_ext_parser_test.rb
new file mode 100644
index 0000000..da3bdc1
--- /dev/null
+++ b/tests/json_ext_parser_test.rb
@@ -0,0 +1,17 @@
+require 'test_helper'
+require 'stringio'
+require 'tempfile'
+require 'ostruct'
+
+class JSONExtParserTest < Test::Unit::TestCase
+ if defined?(JSON::Ext::Parser)
+ def test_allocate
+ parser = JSON::Ext::Parser.new("{}")
+ assert_raise(TypeError, '[ruby-core:35079]') do
+ parser.__send__(:initialize, "{}")
+ end
+ parser = JSON::Ext::Parser.allocate
+ assert_raise(TypeError, '[ruby-core:35079]') { parser.source }
+ end
+ end
+end
diff --git a/tests/test_json_fixtures.rb b/tests/json_fixtures_test.rb
index d580522..6681b8d 100755..100644
--- a/tests/test_json_fixtures.rb
+++ b/tests/json_fixtures_test.rb
@@ -1,11 +1,8 @@
-#!/usr/bin/env ruby
-# encoding: utf-8
-
require 'test_helper'
-class TestJSONFixtures < Test::Unit::TestCase
+class JSONFixturesTest < Test::Unit::TestCase
def setup
- fixtures = File.join(File.dirname(__FILE__), 'fixtures/*.json')
+ fixtures = File.join(File.dirname(__FILE__), 'fixtures/{fail,pass}.json')
passed, failed = Dir[fixtures].partition { |f| f['pass'] }
@passed = passed.inject([]) { |a, f| a << [ f, File.read(f) ] }.sort
@failed = failed.inject([]) { |a, f| a << [ f, File.read(f) ] }.sort
diff --git a/tests/test_json_generate.rb b/tests/json_generator_test.rb
index 79c00af..7e487d8 100755..100644
--- a/tests/test_json_generate.rb
+++ b/tests/json_generator_test.rb
@@ -1,9 +1,6 @@
-#!/usr/bin/env ruby
-# encoding: utf-8
-
require 'test_helper'
-class TestJSONGenerate < Test::Unit::TestCase
+class JSONGeneratorTest < Test::Unit::TestCase
include JSON
def setup
@@ -41,9 +38,9 @@ EOT
def test_generate
json = generate(@hash)
- assert_equal(JSON.parse(@json2), JSON.parse(json))
+ assert_equal(parse(@json2), parse(json))
json = JSON[@hash]
- assert_equal(JSON.parse(@json2), JSON.parse(json))
+ assert_equal(parse(@json2), parse(json))
parsed_json = parse(json)
assert_equal(@hash, parsed_json)
json = generate({1=>2})
@@ -55,8 +52,9 @@ EOT
def test_generate_pretty
json = pretty_generate(@hash)
- # hashes aren't (insertion) ordered on every ruby implementation assert_equal(@json3, json)
- assert_equal(JSON.parse(@json3), JSON.parse(json))
+ # hashes aren't (insertion) ordered on every ruby implementation
+ # assert_equal(@json3, json)
+ assert_equal(parse(@json3), parse(json))
parsed_json = parse(json)
assert_equal(@hash, parsed_json)
json = pretty_generate({1=>2})
@@ -85,7 +83,7 @@ EOT
def test_fast_generate
json = fast_generate(@hash)
- assert_equal(JSON.parse(@json2), JSON.parse(json))
+ assert_equal(parse(@json2), parse(json))
parsed_json = parse(json)
assert_equal(@hash, parsed_json)
json = fast_generate({1=>2})
@@ -98,7 +96,7 @@ EOT
def test_own_state
state = State.new
json = generate(@hash, state)
- assert_equal(JSON.parse(@json2), JSON.parse(json))
+ assert_equal(parse(@json2), parse(json))
parsed_json = parse(json)
assert_equal(@hash, parsed_json)
json = generate({1=>2}, state)
@@ -198,7 +196,7 @@ EOT
def test_depth
ary = []; ary << ary
assert_equal 0, JSON::SAFE_STATE_PROTOTYPE.depth
- assert_raises(JSON::NestingError) { JSON.generate(ary) }
+ assert_raises(JSON::NestingError) { generate(ary) }
assert_equal 0, JSON::SAFE_STATE_PROTOTYPE.depth
assert_equal 0, JSON::PRETTY_STATE_PROTOTYPE.depth
assert_raises(JSON::NestingError) { JSON.pretty_generate(ary) }
@@ -324,7 +322,44 @@ EOT
def test_json_generate
assert_raise JSON::GeneratorError do
- assert_equal true, JSON.generate(["\xea"])
+ assert_equal true, generate(["\xea"])
end
end
+
+ def test_nesting
+ too_deep = '[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]'
+ too_deep_ary = eval too_deep
+ assert_raises(JSON::NestingError) { generate too_deep_ary }
+ assert_raises(JSON::NestingError) { generate too_deep_ary, :max_nesting => 100 }
+ ok = generate too_deep_ary, :max_nesting => 101
+ assert_equal too_deep, ok
+ ok = generate too_deep_ary, :max_nesting => nil
+ assert_equal too_deep, ok
+ ok = generate too_deep_ary, :max_nesting => false
+ assert_equal too_deep, ok
+ ok = generate too_deep_ary, :max_nesting => 0
+ assert_equal too_deep, ok
+ end
+
+ def test_backslash
+ data = [ '\\.(?i:gif|jpe?g|png)$' ]
+ json = '["\\\\.(?i:gif|jpe?g|png)$"]'
+ assert_equal json, generate(data)
+ #
+ data = [ '\\"' ]
+ json = '["\\\\\""]'
+ assert_equal json, generate(data)
+ #
+ data = [ '/' ]
+ json = '["/"]'
+ assert_equal json, generate(data)
+ #
+ data = ['"']
+ json = '["\""]'
+ assert_equal json, generate(data)
+ #
+ data = ["'"]
+ json = '["\\\'"]'
+ assert_equal '["\'"]', generate(data)
+ end
end
diff --git a/tests/test_json_generic_object.rb b/tests/json_generic_object_test.rb
index 66fc18d..171fdb8 100644
--- a/tests/test_json_generic_object.rb
+++ b/tests/json_generic_object_test.rb
@@ -1,9 +1,6 @@
-#!/usr/bin/env ruby
-# encoding: utf-8
-
require 'test_helper'
-class TestJSONGenericObject < Test::Unit::TestCase
+class JSONGenericObjectTest < Test::Unit::TestCase
include JSON
def setup
@@ -26,11 +23,20 @@ class TestJSONGenericObject < Test::Unit::TestCase
end
def test_parse_json
- assert_kind_of Hash, JSON('{ "json_class": "JSON::GenericObject", "a": 1, "b": 2 }', :create_additions => true)
+ assert_kind_of Hash,
+ JSON(
+ '{ "json_class": "JSON::GenericObject", "a": 1, "b": 2 }',
+ :create_additions => true
+ )
switch_json_creatable do
- assert_equal @go, l = JSON('{ "json_class": "JSON::GenericObject", "a": 1, "b": 2 }', :create_additions => true)
+ assert_equal @go, l =
+ JSON(
+ '{ "json_class": "JSON::GenericObject", "a": 1, "b": 2 }',
+ :create_additions => true
+ )
assert_equal 1, l.a
- assert_equal @go, l = JSON('{ "a": 1, "b": 2 }', :object_class => GenericObject)
+ assert_equal @go,
+ l = JSON('{ "a": 1, "b": 2 }', :object_class => GenericObject)
assert_equal 1, l.a
assert_equal GenericObject[:a => GenericObject[:b => 2]],
l = JSON('{ "a": { "b": 2 } }', :object_class => GenericObject)
diff --git a/tests/json_parser_test.rb b/tests/json_parser_test.rb
new file mode 100644
index 0000000..6755e6b
--- /dev/null
+++ b/tests/json_parser_test.rb
@@ -0,0 +1,433 @@
+require 'test_helper'
+require 'stringio'
+require 'tempfile'
+require 'ostruct'
+
+class JSONParserTest < Test::Unit::TestCase
+ include JSON
+
+ def test_construction
+ parser = JSON::Parser.new('test')
+ assert_equal 'test', parser.source
+ end
+
+ def test_argument_encoding
+ source = "{}".encode("UTF-16")
+ JSON::Parser.new(source)
+ assert_equal Encoding::UTF_16, source.encoding
+ end if defined?(Encoding::UTF_16)
+
+ def test_parsing
+ parser = JSON::Parser.new('"test"')
+ assert_equal 'test', parser.parse
+ end
+
+ def test_parser_reset
+ parser = Parser.new('{"a":"b"}')
+ assert_equal({ 'a' => 'b' }, parser.parse)
+ assert_equal({ 'a' => 'b' }, parser.parse)
+ end
+
+ def test_parse_simple_arrays
+ assert_equal([], parse('[]'))
+ assert_equal([], parse(' [ ] '))
+ assert_equal([ nil ], parse('[null]'))
+ assert_equal([ false ], parse('[false]'))
+ assert_equal([ true ], parse('[true]'))
+ assert_equal([ -23 ], parse('[-23]'))
+ assert_equal([ 23 ], parse('[23]'))
+ assert_equal_float([ 0.23 ], parse('[0.23]'))
+ assert_equal_float([ 0.0 ], parse('[0e0]'))
+ assert_equal([""], parse('[""]'))
+ assert_equal(["foobar"], parse('["foobar"]'))
+ assert_equal([{}], parse('[{}]'))
+ end
+
+ def test_parse_simple_objects
+ assert_equal({}, parse('{}'))
+ assert_equal({}, parse(' { } '))
+ assert_equal({ "a" => nil }, parse('{ "a" : null}'))
+ assert_equal({ "a" => nil }, parse('{"a":null}'))
+ assert_equal({ "a" => false }, parse('{ "a" : false } '))
+ assert_equal({ "a" => false }, parse('{"a":false}'))
+ assert_raises(JSON::ParserError) { parse('{false}') }
+ assert_equal({ "a" => true }, parse('{"a":true}'))
+ assert_equal({ "a" => true }, parse(' { "a" : true } '))
+ assert_equal({ "a" => -23 }, parse(' { "a" : -23 } '))
+ assert_equal({ "a" => -23 }, parse(' { "a" : -23 } '))
+ assert_equal({ "a" => 23 }, parse('{"a":23 } '))
+ assert_equal({ "a" => 23 }, parse(' { "a" : 23 } '))
+ assert_equal({ "a" => 0.23 }, parse(' { "a" : 0.23 } '))
+ assert_equal({ "a" => 0.23 }, parse(' { "a" : 0.23 } '))
+ end
+
+ def test_parse_numbers
+ assert_raises(JSON::ParserError) { parse('+23.2') }
+ assert_raises(JSON::ParserError) { parse('+23') }
+ assert_raises(JSON::ParserError) { parse('.23') }
+ assert_raises(JSON::ParserError) { parse('023') }
+ assert_equal 23, parse('23')
+ assert_equal -23, parse('-23')
+ assert_equal_float 3.141, parse('3.141')
+ assert_equal_float -3.141, parse('-3.141')
+ assert_equal_float 3.141, parse('3141e-3')
+ assert_equal_float 3.141, parse('3141.1e-3')
+ assert_equal_float 3.141, parse('3141E-3')
+ assert_equal_float 3.141, parse('3141.0E-3')
+ assert_equal_float -3.141, parse('-3141.0e-3')
+ assert_equal_float -3.141, parse('-3141e-3')
+ assert_raises(ParserError) { parse('NaN') }
+ assert parse('NaN', :allow_nan => true).nan?
+ assert_raises(ParserError) { parse('Infinity') }
+ assert_equal 1.0/0, parse('Infinity', :allow_nan => true)
+ assert_raises(ParserError) { parse('-Infinity') }
+ assert_equal -1.0/0, parse('-Infinity', :allow_nan => true)
+ end
+
+ if Array.method_defined?(:permutation)
+ def test_parse_more_complex_arrays
+ a = [ nil, false, true, "foßbar", [ "n€st€d", true ], { "nested" => true, "n€ßt€ð2" => {} }]
+ a.permutation.each do |perm|
+ json = pretty_generate(perm)
+ assert_equal perm, parse(json)
+ end
+ end
+
+ def test_parse_complex_objects
+ a = [ nil, false, true, "foßbar", [ "n€st€d", true ], { "nested" => true, "n€ßt€ð2" => {} }]
+ a.permutation.each do |perm|
+ s = "a"
+ orig_obj = perm.inject({}) { |h, x| h[s.dup] = x; s = s.succ; h }
+ json = pretty_generate(orig_obj)
+ assert_equal orig_obj, parse(json)
+ end
+ end
+ end
+
+ def test_parse_arrays
+ assert_equal([1,2,3], parse('[1,2,3]'))
+ assert_equal([1.2,2,3], parse('[1.2,2,3]'))
+ assert_equal([[],[[],[]]], parse('[[],[[],[]]]'))
+ assert_equal([], parse('[]'))
+ assert_equal([], parse(' [ ] '))
+ assert_equal([1], parse('[1]'))
+ assert_equal([1], parse(' [ 1 ] '))
+ ary = [[1], ["foo"], [3.14], [4711.0], [2.718], [nil],
+ [[1, -2, 3]], [false], [true]]
+ assert_equal(ary,
+ parse('[[1],["foo"],[3.14],[47.11e+2],[2718.0E-3],[null],[[1,-2,3]],[false],[true]]'))
+ assert_equal(ary, parse(%Q{ [ [1] , ["foo"] , [3.14] \t , [47.11e+2]\s
+ , [2718.0E-3 ],\r[ null] , [[1, -2, 3 ]], [false ],[ true]\n ] }))
+ end
+
+ def test_parse_json_primitive_values
+ assert_raise(JSON::ParserError) { parse('') }
+ assert_raise(TypeError) { parse(nil) }
+ assert_raise(JSON::ParserError) { parse(' /* foo */ ') }
+ assert_equal nil, parse('null')
+ assert_equal false, parse('false')
+ assert_equal true, parse('true')
+ assert_equal 23, parse('23')
+ assert_equal 1, parse('1')
+ assert_equal_float 3.141, parse('3.141'), 1E-3
+ assert_equal 2 ** 64, parse('18446744073709551616')
+ assert_equal 'foo', parse('"foo"')
+ assert parse('NaN', :allow_nan => true).nan?
+ assert parse('Infinity', :allow_nan => true).infinite?
+ assert parse('-Infinity', :allow_nan => true).infinite?
+ assert_raise(JSON::ParserError) { parse('[ 1, ]', :quirks_mode => true) }
+ end
+
+ def test_parse_some_strings
+ assert_equal([""], parse('[""]'))
+ assert_equal(["\\"], parse('["\\\\"]'))
+ assert_equal(['"'], parse('["\""]'))
+ assert_equal(['\\"\\'], parse('["\\\\\\"\\\\"]'))
+ assert_equal(
+ ["\"\b\n\r\t\0\037"],
+ parse('["\"\b\n\r\t\u0000\u001f"]')
+ )
+ end
+
+ def test_parse_big_integers
+ json1 = JSON(orig = (1 << 31) - 1)
+ assert_equal orig, parse(json1)
+ json2 = JSON(orig = 1 << 31)
+ assert_equal orig, parse(json2)
+ json3 = JSON(orig = (1 << 62) - 1)
+ assert_equal orig, parse(json3)
+ json4 = JSON(orig = 1 << 62)
+ assert_equal orig, parse(json4)
+ json5 = JSON(orig = 1 << 64)
+ assert_equal orig, parse(json5)
+ end
+
+ def test_some_wrong_inputs
+ assert_raises(ParserError) { parse('[] bla') }
+ assert_raises(ParserError) { parse('[] 1') }
+ assert_raises(ParserError) { parse('[] []') }
+ assert_raises(ParserError) { parse('[] {}') }
+ assert_raises(ParserError) { parse('{} []') }
+ assert_raises(ParserError) { parse('{} {}') }
+ assert_raises(ParserError) { parse('[NULL]') }
+ assert_raises(ParserError) { parse('[FALSE]') }
+ assert_raises(ParserError) { parse('[TRUE]') }
+ assert_raises(ParserError) { parse('[07] ') }
+ assert_raises(ParserError) { parse('[0a]') }
+ assert_raises(ParserError) { parse('[1.]') }
+ assert_raises(ParserError) { parse(' ') }
+ end
+
+ def test_symbolize_names
+ assert_equal({ "foo" => "bar", "baz" => "quux" },
+ parse('{"foo":"bar", "baz":"quux"}'))
+ assert_equal({ :foo => "bar", :baz => "quux" },
+ parse('{"foo":"bar", "baz":"quux"}', :symbolize_names => true))
+ end
+
+ def test_parse_comments
+ json = <<EOT
+{
+ "key1":"value1", // eol comment
+ "key2":"value2" /* multi line
+ * comment */,
+ "key3":"value3" /* multi line
+ // nested eol comment
+ * comment */
+}
+EOT
+ assert_equal(
+ { "key1" => "value1", "key2" => "value2", "key3" => "value3" },
+ parse(json))
+ json = <<EOT
+{
+ "key1":"value1" /* multi line
+ // nested eol comment
+ /* illegal nested multi line comment */
+ * comment */
+}
+EOT
+ assert_raises(ParserError) { parse(json) }
+ json = <<EOT
+{
+ "key1":"value1" /* multi line
+ // nested eol comment
+ closed multi comment */
+ and again, throw an Error */
+}
+EOT
+ assert_raises(ParserError) { parse(json) }
+ json = <<EOT
+{
+ "key1":"value1" /*/*/
+}
+EOT
+ assert_equal({ "key1" => "value1" }, parse(json))
+ end
+
+ def test_nesting
+ too_deep = '[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]'
+ too_deep_ary = eval too_deep
+ assert_raises(JSON::NestingError) { parse too_deep }
+ assert_raises(JSON::NestingError) { parse too_deep, :max_nesting => 100 }
+ ok = parse too_deep, :max_nesting => 101
+ assert_equal too_deep_ary, ok
+ ok = parse too_deep, :max_nesting => nil
+ assert_equal too_deep_ary, ok
+ ok = parse too_deep, :max_nesting => false
+ assert_equal too_deep_ary, ok
+ ok = parse too_deep, :max_nesting => 0
+ assert_equal too_deep_ary, ok
+ end
+
+ def test_backslash
+ data = [ '\\.(?i:gif|jpe?g|png)$' ]
+ json = '["\\\\.(?i:gif|jpe?g|png)$"]'
+ assert_equal data, parse(json)
+ #
+ data = [ '\\"' ]
+ json = '["\\\\\""]'
+ assert_equal data, parse(json)
+ #
+ json = '["/"]'
+ data = [ '/' ]
+ assert_equal data, parse(json)
+ #
+ json = '["\""]'
+ data = ['"']
+ assert_equal data, parse(json)
+ #
+ json = '["\\\'"]'
+ data = ["'"]
+ assert_equal data, parse(json)
+ end
+
+
+ class SubArray < Array
+ def <<(v)
+ @shifted = true
+ super
+ end
+
+ def shifted?
+ @shifted
+ end
+ end
+
+ class SubArray2 < Array
+ def to_json(*a)
+ {
+ JSON.create_id => self.class.name,
+ 'ary' => to_a,
+ }.to_json(*a)
+ end
+
+ def self.json_create(o)
+ o.delete JSON.create_id
+ o['ary']
+ end
+ end
+
+ class SubArrayWrapper
+ def initialize
+ @data = []
+ end
+
+ attr_reader :data
+
+ def [](index)
+ @data[index]
+ end
+
+ def <<(value)
+ @data << value
+ @shifted = true
+ end
+
+ def shifted?
+ @shifted
+ end
+ end
+
+ def test_parse_array_custom_array_derived_class
+ res = parse('[1,2]', :array_class => SubArray)
+ assert_equal([1,2], res)
+ assert_equal(SubArray, res.class)
+ assert res.shifted?
+ end
+
+ def test_parse_array_custom_non_array_derived_class
+ res = parse('[1,2]', :array_class => SubArrayWrapper)
+ assert_equal([1,2], res.data)
+ assert_equal(SubArrayWrapper, res.class)
+ assert res.shifted?
+ end
+
+ def test_parse_object
+ assert_equal({}, parse('{}'))
+ assert_equal({}, parse(' { } '))
+ assert_equal({'foo'=>'bar'}, parse('{"foo":"bar"}'))
+ assert_equal({'foo'=>'bar'}, parse(' { "foo" : "bar" } '))
+ end
+
+ class SubHash < Hash
+ def []=(k, v)
+ @item_set = true
+ super
+ end
+
+ def item_set?
+ @item_set
+ end
+ end
+
+ class SubHash2 < Hash
+ def to_json(*a)
+ {
+ JSON.create_id => self.class.name,
+ }.merge(self).to_json(*a)
+ end
+
+ def self.json_create(o)
+ o.delete JSON.create_id
+ self[o]
+ end
+ end
+
+ class SubOpenStruct < OpenStruct
+ def [](k)
+ __send__(k)
+ end
+
+ def []=(k, v)
+ @item_set = true
+ __send__("#{k}=", v)
+ end
+
+ def item_set?
+ @item_set
+ end
+ end
+
+ def test_parse_object_custom_hash_derived_class
+ res = parse('{"foo":"bar"}', :object_class => SubHash)
+ assert_equal({"foo" => "bar"}, res)
+ assert_equal(SubHash, res.class)
+ assert res.item_set?
+ end
+
+ def test_parse_object_custom_non_hash_derived_class
+ res = parse('{"foo":"bar"}', :object_class => SubOpenStruct)
+ assert_equal "bar", res.foo
+ assert_equal(SubOpenStruct, res.class)
+ assert res.item_set?
+ end
+
+ def test_parse_generic_object
+ res = parse(
+ '{"foo":"bar", "baz":{}}',
+ :object_class => JSON::GenericObject
+ )
+ assert_equal(JSON::GenericObject, res.class)
+ assert_equal "bar", res.foo
+ assert_equal "bar", res["foo"]
+ assert_equal "bar", res[:foo]
+ assert_equal "bar", res.to_hash[:foo]
+ assert_equal(JSON::GenericObject, res.baz.class)
+ end
+
+ def test_generate_core_subclasses_with_new_to_json
+ obj = SubHash2["foo" => SubHash2["bar" => true]]
+ obj_json = JSON(obj)
+ obj_again = parse(obj_json, :create_additions => true)
+ assert_kind_of SubHash2, obj_again
+ assert_kind_of SubHash2, obj_again['foo']
+ assert obj_again['foo']['bar']
+ assert_equal obj, obj_again
+ assert_equal ["foo"],
+ JSON(JSON(SubArray2["foo"]), :create_additions => true)
+ end
+
+ def test_generate_core_subclasses_with_default_to_json
+ assert_equal '{"foo":"bar"}', JSON(SubHash["foo" => "bar"])
+ assert_equal '["foo"]', JSON(SubArray["foo"])
+ end
+
+ def test_generate_of_core_subclasses
+ obj = SubHash["foo" => SubHash["bar" => true]]
+ obj_json = JSON(obj)
+ obj_again = JSON(obj_json)
+ assert_kind_of Hash, obj_again
+ assert_kind_of Hash, obj_again['foo']
+ assert obj_again['foo']['bar']
+ assert_equal obj, obj_again
+ end
+
+ private
+
+ def assert_equal_float(expected, actual, delta = 1e-2)
+ Array === expected and expected = expected.first
+ Array === actual and actual = actual.first
+ assert_in_delta(expected, actual, delta)
+ end
+end
diff --git a/tests/json_string_matching_test.rb b/tests/json_string_matching_test.rb
new file mode 100644
index 0000000..7fec841
--- /dev/null
+++ b/tests/json_string_matching_test.rb
@@ -0,0 +1,37 @@
+require 'test_helper'
+require 'time'
+
+class JSONStringMatchingTest < Test::Unit::TestCase
+ include JSON
+
+ class TestTime < ::Time
+ def self.json_create(string)
+ Time.parse(string)
+ end
+
+ def to_json(*)
+ %{"#{strftime('%FT%T%z')}"}
+ end
+
+ def ==(other)
+ to_i == other.to_i
+ end
+ end
+
+ def test_match_date
+ t = TestTime.new
+ t_json = [ t ].to_json
+ time_regexp = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{4}\z/
+ assert_equal [ t ],
+ parse(
+ t_json,
+ :create_additions => true,
+ :match_string => { time_regexp => TestTime }
+ )
+ assert_equal [ t.strftime('%FT%T%z') ],
+ parse(
+ t_json,
+ :match_string => { time_regexp => TestTime }
+ )
+ end
+end
diff --git a/tests/test_helper.rb b/tests/test_helper.rb
index abc9112..752f5f5 100644
--- a/tests/test_helper.rb
+++ b/tests/test_helper.rb
@@ -1,4 +1,3 @@
-
gem 'json', File.read('VERSION').chomp
case ENV['JSON']
diff --git a/tests/test_json.rb b/tests/test_json.rb
deleted file mode 100755
index 31624a3..0000000
--- a/tests/test_json.rb
+++ /dev/null
@@ -1,538 +0,0 @@
-#!/usr/bin/env ruby
-# encoding: utf-8
-
-require 'test_helper'
-require 'stringio'
-require 'tempfile'
-require 'ostruct'
-
-class TestJSON < Test::Unit::TestCase
- include JSON
-
- def setup
- @ary = [1, "foo", 3.14, 4711.0, 2.718, nil, [1,-2,3], false, true].map do
- |x| [x]
- end
- @ary_to_parse = ["1", '"foo"', "3.14", "4711.0", "2.718", "null",
- "[1,-2,3]", "false", "true"].map do
- |x| "[#{x}]"
- end
- @hash = {
- 'a' => 2,
- 'b' => 3.141,
- 'c' => 'c',
- 'd' => [ 1, "b", 3.14 ],
- 'e' => { 'foo' => 'bar' },
- 'g' => "\"\0\037",
- 'h' => 1000.0,
- 'i' => 0.001
- }
- @json = '{"a":2,"b":3.141,"c":"c","d":[1,"b",3.14],"e":{"foo":"bar"},'\
- '"g":"\\"\\u0000\\u001f","h":1.0E3,"i":1.0E-3}'
- end
-
- def test_construction
- parser = JSON::Parser.new('test')
- assert_equal 'test', parser.source
- end
-
- def assert_equal_float(expected, is)
- assert_in_delta(expected.first, is.first, 1e-2)
- end
-
- def test_parse_simple_arrays
- assert_equal([], parse('[]'))
- assert_equal([], parse(' [ ] '))
- assert_equal([nil], parse('[null]'))
- assert_equal([false], parse('[false]'))
- assert_equal([true], parse('[true]'))
- assert_equal([-23], parse('[-23]'))
- assert_equal([23], parse('[23]'))
- assert_equal([0.23], parse('[0.23]'))
- assert_equal([0.0], parse('[0e0]'))
- assert_raises(JSON::ParserError) { parse('[+23.2]') }
- assert_raises(JSON::ParserError) { parse('[+23]') }
- assert_raises(JSON::ParserError) { parse('[.23]') }
- assert_raises(JSON::ParserError) { parse('[023]') }
- assert_equal_float [3.141], parse('[3.141]')
- assert_equal_float [-3.141], parse('[-3.141]')
- assert_equal_float [3.141], parse('[3141e-3]')
- assert_equal_float [3.141], parse('[3141.1e-3]')
- assert_equal_float [3.141], parse('[3141E-3]')
- assert_equal_float [3.141], parse('[3141.0E-3]')
- assert_equal_float [-3.141], parse('[-3141.0e-3]')
- assert_equal_float [-3.141], parse('[-3141e-3]')
- assert_raises(ParserError) { parse('[NaN]') }
- assert parse('[NaN]', :allow_nan => true).first.nan?
- assert_raises(ParserError) { parse('[Infinity]') }
- assert_equal [1.0/0], parse('[Infinity]', :allow_nan => true)
- assert_raises(ParserError) { parse('[-Infinity]') }
- assert_equal [-1.0/0], parse('[-Infinity]', :allow_nan => true)
- assert_equal([""], parse('[""]'))
- assert_equal(["foobar"], parse('["foobar"]'))
- assert_equal([{}], parse('[{}]'))
- end
-
- def test_parse_simple_objects
- assert_equal({}, parse('{}'))
- assert_equal({}, parse(' { } '))
- assert_equal({ "a" => nil }, parse('{ "a" : null}'))
- assert_equal({ "a" => nil }, parse('{"a":null}'))
- assert_equal({ "a" => false }, parse('{ "a" : false } '))
- assert_equal({ "a" => false }, parse('{"a":false}'))
- assert_raises(JSON::ParserError) { parse('{false}') }
- assert_equal({ "a" => true }, parse('{"a":true}'))
- assert_equal({ "a" => true }, parse(' { "a" : true } '))
- assert_equal({ "a" => -23 }, parse(' { "a" : -23 } '))
- assert_equal({ "a" => -23 }, parse(' { "a" : -23 } '))
- assert_equal({ "a" => 23 }, parse('{"a":23 } '))
- assert_equal({ "a" => 23 }, parse(' { "a" : 23 } '))
- assert_equal({ "a" => 0.23 }, parse(' { "a" : 0.23 } '))
- assert_equal({ "a" => 0.23 }, parse(' { "a" : 0.23 } '))
- end
-
- def test_parse_json_primitive_values
- assert_raise(JSON::ParserError) { JSON.parse('') }
- assert_raise(JSON::ParserError) { JSON.parse('', :quirks_mode => true) }
- assert_raise(TypeError) { JSON::Parser.new(nil).parse }
- assert_raise(TypeError) { JSON::Parser.new(nil, :quirks_mode => true).parse }
- assert_raise(TypeError) { JSON.parse(nil) }
- assert_raise(TypeError) { JSON.parse(nil, :quirks_mode => true) }
- assert_raise(JSON::ParserError) { JSON.parse(' /* foo */ ') }
- assert_raise(JSON::ParserError) { JSON.parse(' /* foo */ ', :quirks_mode => true) }
- parser = JSON::Parser.new('null')
- assert_equal false, parser.quirks_mode?
- assert_raise(JSON::ParserError) { parser.parse }
- assert_raise(JSON::ParserError) { JSON.parse('null') }
- assert_equal nil, JSON.parse('null', :quirks_mode => true)
- parser = JSON::Parser.new('null', :quirks_mode => true)
- assert_equal true, parser.quirks_mode?
- assert_equal nil, parser.parse
- assert_raise(JSON::ParserError) { JSON.parse('false') }
- assert_equal false, JSON.parse('false', :quirks_mode => true)
- assert_raise(JSON::ParserError) { JSON.parse('true') }
- assert_equal true, JSON.parse('true', :quirks_mode => true)
- assert_raise(JSON::ParserError) { JSON.parse('23') }
- assert_equal 23, JSON.parse('23', :quirks_mode => true)
- assert_raise(JSON::ParserError) { JSON.parse('1') }
- assert_equal 1, JSON.parse('1', :quirks_mode => true)
- assert_raise(JSON::ParserError) { JSON.parse('3.141') }
- assert_in_delta 3.141, JSON.parse('3.141', :quirks_mode => true), 1E-3
- assert_raise(JSON::ParserError) { JSON.parse('18446744073709551616') }
- assert_equal 2 ** 64, JSON.parse('18446744073709551616', :quirks_mode => true)
- assert_raise(JSON::ParserError) { JSON.parse('"foo"') }
- assert_equal 'foo', JSON.parse('"foo"', :quirks_mode => true)
- assert_raise(JSON::ParserError) { JSON.parse('NaN', :allow_nan => true) }
- assert JSON.parse('NaN', :quirks_mode => true, :allow_nan => true).nan?
- assert_raise(JSON::ParserError) { JSON.parse('Infinity', :allow_nan => true) }
- assert JSON.parse('Infinity', :quirks_mode => true, :allow_nan => true).infinite?
- assert_raise(JSON::ParserError) { JSON.parse('-Infinity', :allow_nan => true) }
- assert JSON.parse('-Infinity', :quirks_mode => true, :allow_nan => true).infinite?
- assert_raise(JSON::ParserError) { JSON.parse('[ 1, ]', :quirks_mode => true) }
- end
-
- if Array.method_defined?(:permutation)
- def test_parse_more_complex_arrays
- a = [ nil, false, true, "foßbar", [ "n€st€d", true ], { "nested" => true, "n€ßt€ð2" => {} }]
- a.permutation.each do |perm|
- json = pretty_generate(perm)
- assert_equal perm, parse(json)
- end
- end
-
- def test_parse_complex_objects
- a = [ nil, false, true, "foßbar", [ "n€st€d", true ], { "nested" => true, "n€ßt€ð2" => {} }]
- a.permutation.each do |perm|
- s = "a"
- orig_obj = perm.inject({}) { |h, x| h[s.dup] = x; s = s.succ; h }
- json = pretty_generate(orig_obj)
- assert_equal orig_obj, parse(json)
- end
- end
- end
-
- def test_parse_arrays
- assert_equal([1,2,3], parse('[1,2,3]'))
- assert_equal([1.2,2,3], parse('[1.2,2,3]'))
- assert_equal([[],[[],[]]], parse('[[],[[],[]]]'))
- end
-
- def test_parse_values
- assert_equal([""], parse('[""]'))
- assert_equal(["\\"], parse('["\\\\"]'))
- assert_equal(['"'], parse('["\""]'))
- assert_equal(['\\"\\'], parse('["\\\\\\"\\\\"]'))
- assert_equal(["\"\b\n\r\t\0\037"],
- parse('["\"\b\n\r\t\u0000\u001f"]'))
- for i in 0 ... @ary.size
- assert_equal(@ary[i], parse(@ary_to_parse[i]))
- end
- end
-
- def test_parse_array
- assert_equal([], parse('[]'))
- assert_equal([], parse(' [ ] '))
- assert_equal([1], parse('[1]'))
- assert_equal([1], parse(' [ 1 ] '))
- assert_equal(@ary,
- parse('[[1],["foo"],[3.14],[47.11e+2],[2718.0E-3],[null],[[1,-2,3]]'\
- ',[false],[true]]'))
- assert_equal(@ary, parse(%Q{ [ [1] , ["foo"] , [3.14] \t , [47.11e+2]\s
- , [2718.0E-3 ],\r[ null] , [[1, -2, 3 ]], [false ],[ true]\n ] }))
- end
-
- class SubArray < Array
- def <<(v)
- @shifted = true
- super
- end
-
- def shifted?
- @shifted
- end
- end
-
- class SubArray2 < Array
- def to_json(*a)
- {
- JSON.create_id => self.class.name,
- 'ary' => to_a,
- }.to_json(*a)
- end
-
- def self.json_create(o)
- o.delete JSON.create_id
- o['ary']
- end
- end
-
- class SubArrayWrapper
- def initialize
- @data = []
- end
-
- attr_reader :data
-
- def [](index)
- @data[index]
- end
-
- def <<(value)
- @data << value
- @shifted = true
- end
-
- def shifted?
- @shifted
- end
- end
-
- def test_parse_array_custom_array_derived_class
- res = parse('[1,2]', :array_class => SubArray)
- assert_equal([1,2], res)
- assert_equal(SubArray, res.class)
- assert res.shifted?
- end
-
- def test_parse_array_custom_non_array_derived_class
- res = parse('[1,2]', :array_class => SubArrayWrapper)
- assert_equal([1,2], res.data)
- assert_equal(SubArrayWrapper, res.class)
- assert res.shifted?
- end
-
- def test_parse_object
- assert_equal({}, parse('{}'))
- assert_equal({}, parse(' { } '))
- assert_equal({'foo'=>'bar'}, parse('{"foo":"bar"}'))
- assert_equal({'foo'=>'bar'}, parse(' { "foo" : "bar" } '))
- end
-
- class SubHash < Hash
- def []=(k, v)
- @item_set = true
- super
- end
-
- def item_set?
- @item_set
- end
- end
-
- class SubHash2 < Hash
- def to_json(*a)
- {
- JSON.create_id => self.class.name,
- }.merge(self).to_json(*a)
- end
-
- def self.json_create(o)
- o.delete JSON.create_id
- self[o]
- end
- end
-
- class SubOpenStruct < OpenStruct
- def [](k)
- __send__(k)
- end
-
- def []=(k, v)
- @item_set = true
- __send__("#{k}=", v)
- end
-
- def item_set?
- @item_set
- end
- end
-
- def test_parse_object_custom_hash_derived_class
- res = parse('{"foo":"bar"}', :object_class => SubHash)
- assert_equal({"foo" => "bar"}, res)
- assert_equal(SubHash, res.class)
- assert res.item_set?
- end
-
- def test_parse_object_custom_non_hash_derived_class
- res = parse('{"foo":"bar"}', :object_class => SubOpenStruct)
- assert_equal "bar", res.foo
- assert_equal(SubOpenStruct, res.class)
- assert res.item_set?
- end
-
- def test_parse_generic_object
- res = parse('{"foo":"bar", "baz":{}}', :object_class => JSON::GenericObject)
- assert_equal(JSON::GenericObject, res.class)
- assert_equal "bar", res.foo
- assert_equal "bar", res["foo"]
- assert_equal "bar", res[:foo]
- assert_equal "bar", res.to_hash[:foo]
- assert_equal(JSON::GenericObject, res.baz.class)
- end
-
- def test_generate_core_subclasses_with_new_to_json
- obj = SubHash2["foo" => SubHash2["bar" => true]]
- obj_json = JSON(obj)
- obj_again = JSON.parse(obj_json, :create_additions => true)
- assert_kind_of SubHash2, obj_again
- assert_kind_of SubHash2, obj_again['foo']
- assert obj_again['foo']['bar']
- assert_equal obj, obj_again
- assert_equal ["foo"], JSON(JSON(SubArray2["foo"]), :create_additions => true)
- end
-
- def test_generate_core_subclasses_with_default_to_json
- assert_equal '{"foo":"bar"}', JSON(SubHash["foo" => "bar"])
- assert_equal '["foo"]', JSON(SubArray["foo"])
- end
-
- def test_generate_of_core_subclasses
- obj = SubHash["foo" => SubHash["bar" => true]]
- obj_json = JSON(obj)
- obj_again = JSON(obj_json)
- assert_kind_of Hash, obj_again
- assert_kind_of Hash, obj_again['foo']
- assert obj_again['foo']['bar']
- assert_equal obj, obj_again
- end
-
- def test_parser_reset
- parser = Parser.new(@json)
- assert_equal(@hash, parser.parse)
- assert_equal(@hash, parser.parse)
- end
-
- def test_comments
- json = <<EOT
-{
- "key1":"value1", // eol comment
- "key2":"value2" /* multi line
- * comment */,
- "key3":"value3" /* multi line
- // nested eol comment
- * comment */
-}
-EOT
- assert_equal(
- { "key1" => "value1", "key2" => "value2", "key3" => "value3" },
- parse(json))
- json = <<EOT
-{
- "key1":"value1" /* multi line
- // nested eol comment
- /* illegal nested multi line comment */
- * comment */
-}
-EOT
- assert_raises(ParserError) { parse(json) }
- json = <<EOT
-{
- "key1":"value1" /* multi line
- // nested eol comment
- closed multi comment */
- and again, throw an Error */
-}
-EOT
- assert_raises(ParserError) { parse(json) }
- json = <<EOT
-{
- "key1":"value1" /*/*/
-}
-EOT
- assert_equal({ "key1" => "value1" }, parse(json))
- end
-
- def test_backslash
- data = [ '\\.(?i:gif|jpe?g|png)$' ]
- json = '["\\\\.(?i:gif|jpe?g|png)$"]'
- assert_equal json, JSON.generate(data)
- assert_equal data, JSON.parse(json)
- #
- data = [ '\\"' ]
- json = '["\\\\\""]'
- assert_equal json, JSON.generate(data)
- assert_equal data, JSON.parse(json)
- #
- json = '["/"]'
- data = JSON.parse(json)
- assert_equal ['/'], data
- assert_equal json, JSON.generate(data)
- #
- json = '["\""]'
- data = JSON.parse(json)
- assert_equal ['"'], data
- assert_equal json, JSON.generate(data)
- json = '["\\\'"]'
- data = JSON.parse(json)
- assert_equal ["'"], data
- assert_equal '["\'"]', JSON.generate(data)
- end
-
- def test_wrong_inputs
- assert_raises(ParserError) { JSON.parse('"foo"') }
- assert_raises(ParserError) { JSON.parse('123') }
- assert_raises(ParserError) { JSON.parse('[] bla') }
- assert_raises(ParserError) { JSON.parse('[] 1') }
- assert_raises(ParserError) { JSON.parse('[] []') }
- assert_raises(ParserError) { JSON.parse('[] {}') }
- assert_raises(ParserError) { JSON.parse('{} []') }
- assert_raises(ParserError) { JSON.parse('{} {}') }
- assert_raises(ParserError) { JSON.parse('[NULL]') }
- assert_raises(ParserError) { JSON.parse('[FALSE]') }
- assert_raises(ParserError) { JSON.parse('[TRUE]') }
- assert_raises(ParserError) { JSON.parse('[07] ') }
- assert_raises(ParserError) { JSON.parse('[0a]') }
- assert_raises(ParserError) { JSON.parse('[1.]') }
- assert_raises(ParserError) { JSON.parse(' ') }
- end
-
- def test_nesting
- assert_raises(JSON::NestingError) { JSON.parse '[[]]', :max_nesting => 1 }
- assert_raises(JSON::NestingError) { JSON.parser.new('[[]]', :max_nesting => 1).parse }
- assert_equal [[]], JSON.parse('[[]]', :max_nesting => 2)
- too_deep = '[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]'
- too_deep_ary = eval too_deep
- assert_raises(JSON::NestingError) { JSON.parse too_deep }
- assert_raises(JSON::NestingError) { JSON.parser.new(too_deep).parse }
- assert_raises(JSON::NestingError) { JSON.parse too_deep, :max_nesting => 100 }
- ok = JSON.parse too_deep, :max_nesting => 101
- assert_equal too_deep_ary, ok
- ok = JSON.parse too_deep, :max_nesting => nil
- assert_equal too_deep_ary, ok
- ok = JSON.parse too_deep, :max_nesting => false
- assert_equal too_deep_ary, ok
- ok = JSON.parse too_deep, :max_nesting => 0
- assert_equal too_deep_ary, ok
- assert_raises(JSON::NestingError) { JSON.generate [[]], :max_nesting => 1 }
- assert_equal '[[]]', JSON.generate([[]], :max_nesting => 2)
- assert_raises(JSON::NestingError) { JSON.generate too_deep_ary }
- assert_raises(JSON::NestingError) { JSON.generate too_deep_ary, :max_nesting => 100 }
- ok = JSON.generate too_deep_ary, :max_nesting => 101
- assert_equal too_deep, ok
- ok = JSON.generate too_deep_ary, :max_nesting => nil
- assert_equal too_deep, ok
- ok = JSON.generate too_deep_ary, :max_nesting => false
- assert_equal too_deep, ok
- ok = JSON.generate too_deep_ary, :max_nesting => 0
- assert_equal too_deep, ok
- end
-
- def test_symbolize_names
- assert_equal({ "foo" => "bar", "baz" => "quux" },
- JSON.parse('{"foo":"bar", "baz":"quux"}'))
- assert_equal({ :foo => "bar", :baz => "quux" },
- JSON.parse('{"foo":"bar", "baz":"quux"}', :symbolize_names => true))
- end
-
- def test_load
- assert_equal @hash, JSON.load(@json)
- tempfile = Tempfile.open('json')
- tempfile.write @json
- tempfile.rewind
- assert_equal @hash, JSON.load(tempfile)
- stringio = StringIO.new(@json)
- stringio.rewind
- assert_equal @hash, JSON.load(stringio)
- assert_equal nil, JSON.load(nil)
- assert_equal nil, JSON.load('')
- ensure
- tempfile.close!
- end
-
- def test_load_with_options
- small_hash = JSON("foo" => 'bar')
- symbol_hash = { :foo => 'bar' }
- assert_equal symbol_hash, JSON.load(small_hash, nil, :symbolize_names => true)
- end
-
- def test_dump
- too_deep = '[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]'
- assert_equal too_deep, JSON.dump(eval(too_deep))
- assert_kind_of String, Marshal.dump(eval(too_deep))
- assert_raises(ArgumentError) { JSON.dump(eval(too_deep), 100) }
- assert_raises(ArgumentError) { Marshal.dump(eval(too_deep), 100) }
- assert_equal too_deep, JSON.dump(eval(too_deep), 101)
- assert_kind_of String, Marshal.dump(eval(too_deep), 101)
- output = StringIO.new
- JSON.dump(eval(too_deep), output)
- assert_equal too_deep, output.string
- output = StringIO.new
- JSON.dump(eval(too_deep), output, 101)
- assert_equal too_deep, output.string
- end
-
- def test_dump_should_modify_defaults
- max_nesting = JSON.dump_default_options[:max_nesting]
- JSON.dump([], StringIO.new, 10)
- assert_equal max_nesting, JSON.dump_default_options[:max_nesting]
- end
-
- def test_big_integers
- json1 = JSON([orig = (1 << 31) - 1])
- assert_equal orig, JSON[json1][0]
- json2 = JSON([orig = 1 << 31])
- assert_equal orig, JSON[json2][0]
- json3 = JSON([orig = (1 << 62) - 1])
- assert_equal orig, JSON[json3][0]
- json4 = JSON([orig = 1 << 62])
- assert_equal orig, JSON[json4][0]
- json5 = JSON([orig = 1 << 64])
- assert_equal orig, JSON[json5][0]
- end
-
- if defined?(JSON::Ext::Parser)
- def test_allocate
- parser = JSON::Ext::Parser.new("{}")
- assert_raise(TypeError, '[ruby-core:35079]') {parser.__send__(:initialize, "{}")}
- parser = JSON::Ext::Parser.allocate
- assert_raise(TypeError, '[ruby-core:35079]') {parser.source}
- end
- end
-
- def test_argument_encoding
- source = "{}".force_encoding("ascii-8bit")
- JSON::Parser.new(source)
- assert_equal Encoding::ASCII_8BIT, source.encoding
- end if defined?(Encoding::ASCII_8BIT)
-end
diff --git a/tests/test_json_encoding.rb b/tests/test_json_encoding.rb
deleted file mode 100644
index 3536c56..0000000
--- a/tests/test_json_encoding.rb
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/env ruby
-# encoding: utf-8
-
-require 'test_helper'
-
-class TestJSONEncoding < Test::Unit::TestCase
- include JSON
-
- def setup
- @utf_8 = '["© ≠ €!"]'
- @parsed = [ "© ≠ €!" ]
- @generated = '["\u00a9 \u2260 \u20ac!"]'
- if String.method_defined?(:encode)
- @utf_16_data = [@parsed.first.encode('utf-16be', 'utf-8')]
- @utf_8_ascii_8bit = @utf_8.dup.force_encoding(Encoding::ASCII_8BIT)
- @utf_16be = @utf_8.encode('utf-16be', 'utf-8')
- @utf_16be_ascii_8bit = @utf_16be.dup.force_encoding(Encoding::ASCII_8BIT)
- @utf_16le = @utf_8.encode('utf-16le', 'utf-8')
- @utf_16le_ascii_8bit = @utf_16le.dup.force_encoding(Encoding::ASCII_8BIT)
- @utf_32be = @utf_8.encode('utf-32be', 'utf-8')
- @utf_32be_ascii_8bit = @utf_32be.dup.force_encoding(Encoding::ASCII_8BIT)
- @utf_32le = @utf_8.encode('utf-32le', 'utf-8')
- @utf_32le_ascii_8bit = @utf_32le.dup.force_encoding(Encoding::ASCII_8BIT)
- else
- require 'iconv'
- @utf_16_data = Iconv.iconv('utf-16be', 'utf-8', @parsed.first)
- @utf_8_ascii_8bit = @utf_8.dup
- @utf_16be, = Iconv.iconv('utf-16be', 'utf-8', @utf_8)
- @utf_16be_ascii_8bit = @utf_16be.dup
- @utf_16le, = Iconv.iconv('utf-16le', 'utf-8', @utf_8)
- @utf_16le_ascii_8bit = @utf_16le.dup
- @utf_32be, = Iconv.iconv('utf-32be', 'utf-8', @utf_8)
- @utf_32be_ascii_8bit = @utf_32be.dup
- @utf_32le, = Iconv.iconv('utf-32le', 'utf-8', @utf_8)
- @utf_32le_ascii_8bit = @utf_32le.dup
- end
- end
-
- def test_parse
- assert_equal @parsed, JSON.parse(@utf_8)
- assert_equal @parsed, JSON.parse(@utf_16be)
- assert_equal @parsed, JSON.parse(@utf_16le)
- assert_equal @parsed, JSON.parse(@utf_32be)
- assert_equal @parsed, JSON.parse(@utf_32le)
- end
-
- def test_parse_ascii_8bit
- assert_equal @parsed, JSON.parse(@utf_8_ascii_8bit)
- assert_equal @parsed, JSON.parse(@utf_16be_ascii_8bit)
- assert_equal @parsed, JSON.parse(@utf_16le_ascii_8bit)
- assert_equal @parsed, JSON.parse(@utf_32be_ascii_8bit)
- assert_equal @parsed, JSON.parse(@utf_32le_ascii_8bit)
- end
-
- def test_generate
- assert_equal @generated, JSON.generate(@parsed, :ascii_only => true)
- if defined?(::Encoding)
- assert_equal @generated, JSON.generate(@utf_16_data, :ascii_only => true)
- else
- # XXX checking of correct utf8 data is not as strict (yet?) without :ascii_only
- assert_raises(JSON::GeneratorError) { JSON.generate(@utf_16_data, :ascii_only => true) }
- end
- end
-end
diff --git a/tests/test_json_string_matching.rb b/tests/test_json_string_matching.rb
deleted file mode 100644
index 2b89588..0000000
--- a/tests/test_json_string_matching.rb
+++ /dev/null
@@ -1,38 +0,0 @@
-#!/usr/bin/env ruby
-# encoding: utf-8
-
-require 'test_helper'
-require 'stringio'
-require 'time'
-
-class TestJSONStringMatching < Test::Unit::TestCase
- include JSON
-
- class TestTime < ::Time
- def self.json_create(string)
- Time.parse(string)
- end
-
- def to_json(*)
- %{"#{strftime('%FT%T%z')}"}
- end
-
- def ==(other)
- to_i == other.to_i
- end
- end
-
- def test_match_date
- t = TestTime.new
- t_json = [ t ].to_json
- assert_equal [ t ],
- JSON.parse(t_json, :create_additions => true,
- :match_string => { /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{4}\z/ => TestTime })
- assert_equal [ t.strftime('%FT%T%z') ],
- JSON.parse(t_json, :create_additions => true,
- :match_string => { /\A\d{3}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{4}\z/ => TestTime })
- assert_equal [ t.strftime('%FT%T%z') ],
- JSON.parse(t_json,
- :match_string => { /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{4}\z/ => TestTime })
- end
-end
diff --git a/tests/test_json_unicode.rb b/tests/test_json_unicode.rb
deleted file mode 100755
index f59c36a..0000000
--- a/tests/test_json_unicode.rb
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/env ruby
-# encoding: utf-8
-
-require 'test_helper'
-
-class TestJSONUnicode < Test::Unit::TestCase
- include JSON
-
- def test_unicode
- assert_equal '""', ''.to_json
- assert_equal '"\\b"', "\b".to_json
- assert_equal '"\u0001"', 0x1.chr.to_json
- assert_equal '"\u001f"', 0x1f.chr.to_json
- assert_equal '" "', ' '.to_json
- assert_equal "\"#{0x7f.chr}\"", 0x7f.chr.to_json
- utf8 = [ "© ≠ €! \01" ]
- json = '["© ≠ €! \u0001"]'
- assert_equal json, utf8.to_json(:ascii_only => false)
- assert_equal utf8, parse(json)
- json = '["\u00a9 \u2260 \u20ac! \u0001"]'
- assert_equal json, utf8.to_json(:ascii_only => true)
- assert_equal utf8, parse(json)
- utf8 = ["\343\201\202\343\201\204\343\201\206\343\201\210\343\201\212"]
- json = "[\"\343\201\202\343\201\204\343\201\206\343\201\210\343\201\212\"]"
- assert_equal utf8, parse(json)
- assert_equal json, utf8.to_json(:ascii_only => false)
- utf8 = ["\343\201\202\343\201\204\343\201\206\343\201\210\343\201\212"]
- assert_equal utf8, parse(json)
- json = "[\"\\u3042\\u3044\\u3046\\u3048\\u304a\"]"
- assert_equal json, utf8.to_json(:ascii_only => true)
- assert_equal utf8, parse(json)
- utf8 = ['საქართველო']
- json = '["საქართველო"]'
- assert_equal json, utf8.to_json(:ascii_only => false)
- json = "[\"\\u10e1\\u10d0\\u10e5\\u10d0\\u10e0\\u10d7\\u10d5\\u10d4\\u10da\\u10dd\"]"
- assert_equal json, utf8.to_json(:ascii_only => true)
- assert_equal utf8, parse(json)
- assert_equal '["Ã"]', JSON.generate(["Ã"], :ascii_only => false)
- assert_equal '["\\u00c3"]', JSON.generate(["Ã"], :ascii_only => true)
- assert_equal ["€"], JSON.parse('["\u20ac"]')
- utf8 = ["\xf0\xa0\x80\x81"]
- json = "[\"\xf0\xa0\x80\x81\"]"
- assert_equal json, JSON.generate(utf8, :ascii_only => false)
- assert_equal utf8, JSON.parse(json)
- json = '["\ud840\udc01"]'
- assert_equal json, JSON.generate(utf8, :ascii_only => true)
- assert_equal utf8, JSON.parse(json)
- end
-
- def test_chars
- (0..0x7f).each do |i|
- json = '["\u%04x"]' % i
- if RUBY_VERSION >= "1.9."
- i = i.chr
- end
- assert_equal i, JSON.parse(json).first[0]
- if i == ?\b
- generated = JSON.generate(["" << i])
- assert '["\b"]' == generated || '["\10"]' == generated
- elsif [?\n, ?\r, ?\t, ?\f].include?(i)
- assert_equal '[' << ('' << i).dump << ']', JSON.generate(["" << i])
- elsif i.chr < 0x20.chr
- assert_equal json, JSON.generate(["" << i])
- end
- end
- assert_raise(JSON::GeneratorError) do
- JSON.generate(["\x80"], :ascii_only => true)
- end
- assert_equal "\302\200", JSON.parse('["\u0080"]').first
- end
-end