diff options
Diffstat (limited to 'jni/ruby/test/psych')
46 files changed, 5798 insertions, 0 deletions
diff --git a/jni/ruby/test/psych/handlers/test_recorder.rb b/jni/ruby/test/psych/handlers/test_recorder.rb new file mode 100644 index 0000000..96b8eac --- /dev/null +++ b/jni/ruby/test/psych/handlers/test_recorder.rb @@ -0,0 +1,25 @@ +require 'psych/helper' +require 'psych/handlers/recorder' + +module Psych + module Handlers + class TestRecorder < TestCase + def test_replay + yaml = "--- foo\n...\n" + output = StringIO.new + + recorder = Psych::Handlers::Recorder.new + parser = Psych::Parser.new recorder + parser.parse yaml + + assert_equal 5, recorder.events.length + + emitter = Psych::Emitter.new output + recorder.events.each do |m, args| + emitter.send m, *args + end + assert_equal yaml, output.string + end + end + end +end diff --git a/jni/ruby/test/psych/helper.rb b/jni/ruby/test/psych/helper.rb new file mode 100644 index 0000000..11b2216 --- /dev/null +++ b/jni/ruby/test/psych/helper.rb @@ -0,0 +1,114 @@ +require 'minitest/autorun' +require 'stringio' +require 'tempfile' +require 'date' +require 'psych' + +module Psych + class TestCase < MiniTest::Unit::TestCase + def self.suppress_warning + verbose, $VERBOSE = $VERBOSE, nil + yield + ensure + $VERBOSE = verbose + end + + def with_default_external(enc) + verbose, $VERBOSE = $VERBOSE, nil + origenc, Encoding.default_external = Encoding.default_external, enc + $VERBOSE = verbose + yield + ensure + verbose, $VERBOSE = $VERBOSE, nil + Encoding.default_external = origenc + $VERBOSE = verbose + end + + def with_default_internal(enc) + verbose, $VERBOSE = $VERBOSE, nil + origenc, Encoding.default_internal = Encoding.default_internal, enc + $VERBOSE = verbose + yield + ensure + verbose, $VERBOSE = $VERBOSE, nil + Encoding.default_internal = origenc + $VERBOSE = verbose + end + + # + # Convert between Psych and the object to verify correct parsing and + # emitting + # + def assert_to_yaml( obj, yaml ) + assert_equal( obj, Psych::load( yaml ) ) + assert_equal( obj, Psych::parse( yaml ).transform ) + assert_equal( obj, Psych::load( obj.psych_to_yaml ) ) + assert_equal( obj, Psych::parse( obj.psych_to_yaml ).transform ) + assert_equal( obj, Psych::load( + obj.psych_to_yaml( + :UseVersion => true, :UseHeader => true, :SortKeys => true + ) + )) + end + + # + # Test parser only + # + def assert_parse_only( obj, yaml ) + assert_equal( obj, Psych::load( yaml ) ) + assert_equal( obj, Psych::parse( yaml ).transform ) + end + + def assert_cycle( obj ) + v = Visitors::YAMLTree.create + v << obj + assert_equal(obj, Psych.load(v.tree.yaml)) + assert_equal( obj, Psych::load(Psych.dump(obj))) + assert_equal( obj, Psych::load( obj.psych_to_yaml ) ) + end + + # + # Make a time with the time zone + # + def mktime( year, mon, day, hour, min, sec, usec, zone = "Z" ) + usec = Rational(usec.to_s) * 1000000 + val = Time::utc( year.to_i, mon.to_i, day.to_i, hour.to_i, min.to_i, sec.to_i, usec ) + if zone != "Z" + hour = zone[0,3].to_i * 3600 + min = zone[3,2].to_i * 60 + ofs = (hour + min) + val = Time.at( val.tv_sec - ofs, val.tv_nsec / 1000.0 ) + end + return val + end + end +end + +# backport so that tests will run on 1.9 and 2.0.0 +unless Tempfile.respond_to? :create + def Tempfile.create(basename, *rest) + tmpfile = nil + Dir::Tmpname.create(basename, *rest) do |tmpname, n, opts| + mode = File::RDWR|File::CREAT|File::EXCL + perm = 0600 + if opts + mode |= opts.delete(:mode) || 0 + opts[:perm] = perm + perm = nil + else + opts = perm + end + tmpfile = File.open(tmpname, mode, opts) + end + if block_given? + begin + yield tmpfile + ensure + tmpfile.close if !tmpfile.closed? + File.unlink tmpfile + end + else + tmpfile + end + end +end diff --git a/jni/ruby/test/psych/json/test_stream.rb b/jni/ruby/test/psych/json/test_stream.rb new file mode 100644 index 0000000..b0c33e6 --- /dev/null +++ b/jni/ruby/test/psych/json/test_stream.rb @@ -0,0 +1,109 @@ +require 'psych/helper' + +module Psych + module JSON + class TestStream < TestCase + def setup + @io = StringIO.new + @stream = Psych::JSON::Stream.new(@io) + @stream.start + end + + def test_explicit_documents + @io = StringIO.new + @stream = Psych::JSON::Stream.new(@io) + @stream.start + + @stream.push({ 'foo' => 'bar' }) + + assert !@stream.finished?, 'stream not finished' + @stream.finish + assert @stream.finished?, 'stream finished' + + assert_match(/^---/, @io.string) + assert_match(/\.\.\.$/, @io.string) + end + + def test_null + @stream.push(nil) + assert_match(/^--- null/, @io.string) + end + + def test_string + @stream.push "foo" + assert_match(/(["])foo\1/, @io.string) + end + + def test_symbol + @stream.push :foo + assert_match(/(["])foo\1/, @io.string) + end + + def test_int + @stream.push 10 + assert_match(/^--- 10/, @io.string) + end + + def test_float + @stream.push 1.2 + assert_match(/^--- 1.2/, @io.string) + end + + def test_hash + hash = { 'one' => 'two' } + @stream.push hash + + json = @io.string + assert_match(/}$/, json) + assert_match(/^--- \{/, json) + assert_match(/["]one['"]/, json) + assert_match(/["]two['"]/, json) + end + + def test_list_to_json + list = %w{ one two } + @stream.push list + + json = @io.string + assert_match(/\]$/, json) + assert_match(/^--- \[/, json) + assert_match(/["]one["]/, json) + assert_match(/["]two["]/, json) + end + + class Foo; end + + def test_json_dump_exclude_tag + @stream << Foo.new + json = @io.string + refute_match('Foo', json) + end + + class Bar + def encode_with coder + coder.represent_seq 'omg', %w{ a b c } + end + end + + def test_json_list_dump_exclude_tag + @stream << Bar.new + json = @io.string + refute_match('omg', json) + end + + def test_time + time = Time.utc(2010, 10, 10) + @stream.push({'a' => time }) + json = @io.string + assert_match "{\"a\": \"2010-10-10 00:00:00.000000000 Z\"}\n", json + end + + def test_datetime + time = Time.new(2010, 10, 10).to_datetime + @stream.push({'a' => time }) + json = @io.string + assert_match "{\"a\": \"#{time.strftime("%Y-%m-%d %H:%M:%S.%9N %:z")}\"}\n", json + end + end + end +end diff --git a/jni/ruby/test/psych/nodes/test_enumerable.rb b/jni/ruby/test/psych/nodes/test_enumerable.rb new file mode 100644 index 0000000..19cf94b --- /dev/null +++ b/jni/ruby/test/psych/nodes/test_enumerable.rb @@ -0,0 +1,43 @@ +require 'psych/helper' + +module Psych + module Nodes + class TestEnumerable < TestCase + def test_includes_enumerable + yaml = '--- hello' + assert_equal 3, Psych.parse_stream(yaml).to_a.length + end + + def test_returns_enumerator + yaml = '--- hello' + assert_equal 3, Psych.parse_stream(yaml).each.map { |x| x }.length + end + + def test_scalar + assert_equal 3, calls('--- hello').length + end + + def test_sequence + assert_equal 4, calls("---\n- hello").length + end + + def test_mapping + assert_equal 5, calls("---\nhello: world").length + end + + def test_alias + assert_equal 5, calls("--- &yay\n- foo\n- *yay\n").length + end + + private + + def calls yaml + calls = [] + Psych.parse_stream(yaml).each do |node| + calls << node + end + calls + end + end + end +end diff --git a/jni/ruby/test/psych/test_alias_and_anchor.rb b/jni/ruby/test/psych/test_alias_and_anchor.rb new file mode 100644 index 0000000..9e2c240 --- /dev/null +++ b/jni/ruby/test/psych/test_alias_and_anchor.rb @@ -0,0 +1,96 @@ +require_relative 'helper' + +class ObjectWithInstanceVariables + attr_accessor :var1, :var2 +end + +class SubStringWithInstanceVariables < String + attr_accessor :var1 +end + +module Psych + class TestAliasAndAnchor < TestCase + def test_mri_compatibility + yaml = <<EOYAML +--- +- &id001 !ruby/object {} + +- *id001 +- *id001 +EOYAML + result = Psych.load yaml + result.each {|el| assert_same(result[0], el) } + end + + def test_mri_compatibility_object_with_ivars + yaml = <<EOYAML +--- +- &id001 !ruby/object:ObjectWithInstanceVariables + var1: test1 + var2: test2 +- *id001 +- *id001 +EOYAML + + result = Psych.load yaml + result.each do |el| + assert_same(result[0], el) + assert_equal('test1', el.var1) + assert_equal('test2', el.var2) + end + end + + def test_mri_compatibility_substring_with_ivars + yaml = <<EOYAML +--- +- &id001 !str:SubStringWithInstanceVariables + str: test + "@var1": test +- *id001 +- *id001 +EOYAML + result = Psych.load yaml + result.each do |el| + assert_same(result[0], el) + assert_equal('test', el.var1) + end + end + + def test_anchor_alias_round_trip + o = Object.new + original = [o,o,o] + + yaml = Psych.dump original + result = Psych.load yaml + result.each {|el| assert_same(result[0], el) } + end + + def test_anchor_alias_round_trip_object_with_ivars + o = ObjectWithInstanceVariables.new + o.var1 = 'test1' + o.var2 = 'test2' + original = [o,o,o] + + yaml = Psych.dump original + result = Psych.load yaml + result.each do |el| + assert_same(result[0], el) + assert_equal('test1', el.var1) + assert_equal('test2', el.var2) + end + end + + def test_anchor_alias_round_trip_substring_with_ivars + o = SubStringWithInstanceVariables.new + o.var1 = 'test' + original = [o,o,o] + + yaml = Psych.dump original + result = Psych.load yaml + result.each do |el| + assert_same(result[0], el) + assert_equal('test', el.var1) + end + end + end +end diff --git a/jni/ruby/test/psych/test_array.rb b/jni/ruby/test/psych/test_array.rb new file mode 100644 index 0000000..960ffd7 --- /dev/null +++ b/jni/ruby/test/psych/test_array.rb @@ -0,0 +1,57 @@ +require_relative 'helper' + +module Psych + class TestArray < TestCase + class X < Array + end + + class Y < Array + attr_accessor :val + end + + def setup + super + @list = [{ :a => 'b' }, 'foo'] + end + + def test_another_subclass_with_attributes + y = Y.new.tap {|y| y.val = 1} + y << "foo" << "bar" + y = Psych.load Psych.dump y + + assert_equal %w{foo bar}, y + assert_equal Y, y.class + assert_equal 1, y.val + end + + def test_subclass + yaml = Psych.dump X.new + assert_match X.name, yaml + + list = X.new + list << 1 + assert_equal X, list.class + assert_equal 1, list.first + end + + def test_subclass_with_attributes + y = Psych.load Psych.dump Y.new.tap {|y| y.val = 1} + assert_equal Y, y.class + assert_equal 1, y.val + end + + def test_backwards_with_syck + x = Psych.load "--- !seq:#{X.name} []\n\n" + assert_equal X, x.class + end + + def test_self_referential + @list << @list + assert_cycle(@list) + end + + def test_cycle + assert_cycle(@list) + end + end +end diff --git a/jni/ruby/test/psych/test_boolean.rb b/jni/ruby/test/psych/test_boolean.rb new file mode 100644 index 0000000..b656f4f --- /dev/null +++ b/jni/ruby/test/psych/test_boolean.rb @@ -0,0 +1,36 @@ +require_relative 'helper' + +module Psych + ### + # Test booleans from YAML spec: + # http://yaml.org/type/bool.html + class TestBoolean < TestCase + %w{ yes Yes YES true True TRUE on On ON }.each do |truth| + define_method(:"test_#{truth}") do + assert_equal true, Psych.load("--- #{truth}") + end + end + + %w{ no No NO false False FALSE off Off OFF }.each do |truth| + define_method(:"test_#{truth}") do + assert_equal false, Psych.load("--- #{truth}") + end + end + + ### + # YAML spec says "y" and "Y" may be used as true, but Syck treats them + # as literal strings + def test_y + assert_equal "y", Psych.load("--- y") + assert_equal "Y", Psych.load("--- Y") + end + + ### + # YAML spec says "n" and "N" may be used as false, but Syck treats them + # as literal strings + def test_n + assert_equal "n", Psych.load("--- n") + assert_equal "N", Psych.load("--- N") + end + end +end diff --git a/jni/ruby/test/psych/test_class.rb b/jni/ruby/test/psych/test_class.rb new file mode 100644 index 0000000..c7f964c --- /dev/null +++ b/jni/ruby/test/psych/test_class.rb @@ -0,0 +1,36 @@ +require_relative 'helper' + +module Psych + class TestClass < TestCase + module Foo + end + + def test_cycle_anonymous_class + assert_raises(::TypeError) do + assert_cycle(Class.new) + end + end + + def test_cycle_anonymous_module + assert_raises(::TypeError) do + assert_cycle(Module.new) + end + end + + def test_cycle + assert_cycle(TestClass) + end + + def test_dump + Psych.dump TestClass + end + + def test_cycle_module + assert_cycle(Foo) + end + + def test_dump_module + Psych.dump Foo + end + end +end diff --git a/jni/ruby/test/psych/test_coder.rb b/jni/ruby/test/psych/test_coder.rb new file mode 100644 index 0000000..7571e89 --- /dev/null +++ b/jni/ruby/test/psych/test_coder.rb @@ -0,0 +1,184 @@ +require_relative 'helper' + +module Psych + class TestCoder < TestCase + class InitApi + attr_accessor :implicit + attr_accessor :style + attr_accessor :tag + attr_accessor :a, :b, :c + + def initialize + @a = 1 + @b = 2 + @c = 3 + end + + def init_with coder + @a = coder['aa'] + @b = coder['bb'] + @implicit = coder.implicit + @tag = coder.tag + @style = coder.style + end + + def encode_with coder + coder['aa'] = @a + coder['bb'] = @b + end + end + + class TaggingCoder < InitApi + def encode_with coder + super + coder.tag = coder.tag.sub(/!/, '!hello') + coder.implicit = false + coder.style = Psych::Nodes::Mapping::FLOW + end + end + + class ScalarCoder + def encode_with coder + coder.scalar = "foo" + end + end + + class Represent + yaml_tag 'foo' + def encode_with coder + coder.represent_scalar 'foo', 'bar' + end + end + + class RepresentWithInit + yaml_tag name + attr_accessor :str + + def init_with coder + @str = coder.scalar + end + + def encode_with coder + coder.represent_scalar self.class.name, 'bar' + end + end + + class RepresentWithSeq + yaml_tag name + attr_accessor :seq + + def init_with coder + @seq = coder.seq + end + + def encode_with coder + coder.represent_seq self.class.name, %w{ foo bar } + end + end + + class RepresentWithMap + yaml_tag name + attr_accessor :map + + def init_with coder + @map = coder.map + end + + def encode_with coder + coder.represent_map self.class.name, { "string" => 'a', :symbol => 'b' } + end + end + + class RepresentWithObject + def encode_with coder + coder.represent_object self.class.name, 20 + end + end + + def test_represent_with_object + thing = Psych.load(Psych.dump(RepresentWithObject.new)) + assert_equal 20, thing + end + + def test_json_dump_exclude_tag + refute_match('TestCoder::InitApi', Psych.to_json(InitApi.new)) + end + + def test_map_takes_block + coder = Psych::Coder.new 'foo' + tag = coder.tag + style = coder.style + coder.map { |map| map.add 'foo', 'bar' } + assert_equal 'bar', coder['foo'] + assert_equal tag, coder.tag + assert_equal style, coder.style + end + + def test_map_with_tag + coder = Psych::Coder.new 'foo' + coder.map('hello') { |map| map.add 'foo', 'bar' } + assert_equal 'bar', coder['foo'] + assert_equal 'hello', coder.tag + end + + def test_map_with_tag_and_style + coder = Psych::Coder.new 'foo' + coder.map('hello', 'world') { |map| map.add 'foo', 'bar' } + assert_equal 'bar', coder['foo'] + assert_equal 'hello', coder.tag + assert_equal 'world', coder.style + end + + def test_represent_map + thing = Psych.load(Psych.dump(RepresentWithMap.new)) + assert_equal({ "string" => 'a', :symbol => 'b' }, thing.map) + end + + def test_represent_sequence + thing = Psych.load(Psych.dump(RepresentWithSeq.new)) + assert_equal %w{ foo bar }, thing.seq + end + + def test_represent_with_init + thing = Psych.load(Psych.dump(RepresentWithInit.new)) + assert_equal 'bar', thing.str + end + + def test_represent! + assert_match(/foo/, Psych.dump(Represent.new)) + assert_instance_of(Represent, Psych.load(Psych.dump(Represent.new))) + end + + def test_scalar_coder + foo = Psych.load(Psych.dump(ScalarCoder.new)) + assert_equal 'foo', foo + end + + def test_load_dumped_tagging + foo = InitApi.new + bar = Psych.load(Psych.dump(foo)) + assert_equal false, bar.implicit + assert_equal "!ruby/object:Psych::TestCoder::InitApi", bar.tag + assert_equal Psych::Nodes::Mapping::BLOCK, bar.style + end + + def test_dump_with_tag + foo = TaggingCoder.new + assert_match(/hello/, Psych.dump(foo)) + assert_match(/\{aa/, Psych.dump(foo)) + end + + def test_dump_encode_with + foo = InitApi.new + assert_match(/aa/, Psych.dump(foo)) + end + + def test_dump_init_with + foo = InitApi.new + bar = Psych.load(Psych.dump(foo)) + assert_equal foo.a, bar.a + assert_equal foo.b, bar.b + assert_nil bar.c + end + end +end diff --git a/jni/ruby/test/psych/test_date_time.rb b/jni/ruby/test/psych/test_date_time.rb new file mode 100644 index 0000000..72150ad --- /dev/null +++ b/jni/ruby/test/psych/test_date_time.rb @@ -0,0 +1,38 @@ +require_relative 'helper' +require 'date' + +module Psych + class TestDateTime < TestCase + def test_negative_year + time = Time.utc -1, 12, 16 + assert_cycle time + end + + def test_new_datetime + assert_cycle DateTime.new + end + + def test_invalid_date + assert_cycle "2013-10-31T10:40:07-000000000000033" + end + + def test_string_tag + dt = DateTime.now + yaml = Psych.dump dt + assert_match(/DateTime/, yaml) + end + + def test_round_trip + dt = DateTime.now + assert_cycle dt + end + + def test_alias_with_time + t = Time.now + h = {:a => t, :b => t} + yaml = Psych.dump h + assert_match('&', yaml) + assert_match('*', yaml) + end + end +end diff --git a/jni/ruby/test/psych/test_deprecated.rb b/jni/ruby/test/psych/test_deprecated.rb new file mode 100644 index 0000000..fd2d329 --- /dev/null +++ b/jni/ruby/test/psych/test_deprecated.rb @@ -0,0 +1,214 @@ +require_relative 'helper' + +module Psych + class TestDeprecated < TestCase + def teardown + $VERBOSE = @orig_verbose + Psych.domain_types.clear + end + + class QuickEmitter + attr_reader :name + attr_reader :value + + def initialize + @name = 'hello!!' + @value = 'Friday!' + end + + def to_yaml opts = {} + Psych.quick_emit object_id, opts do |out| + out.map taguri, to_yaml_style do |map| + map.add 'name', @name + map.add 'value', nil + end + end + end + end + + def setup + @qe = QuickEmitter.new + @orig_verbose, $VERBOSE = $VERBOSE, false + end + + def test_quick_emit + qe2 = Psych.load @qe.to_yaml + assert_equal @qe.name, qe2.name + assert_instance_of QuickEmitter, qe2 + assert_nil qe2.value + end + + def test_recursive_quick_emit + hash = { :qe => @qe } + hash2 = Psych.load Psych.dump hash + qe = hash2[:qe] + + assert_equal @qe.name, qe.name + assert_instance_of QuickEmitter, qe + assert_nil qe.value + end + + class QuickEmitterEncodeWith + attr_reader :name + attr_reader :value + + def initialize + @name = 'hello!!' + @value = 'Friday!' + end + + def encode_with coder + coder.map do |map| + map.add 'name', @name + map.add 'value', nil + end + end + + def to_yaml opts = {} + raise + end + end + + ### + # An object that defines both to_yaml and encode_with should only call + # encode_with. + def test_recursive_quick_emit_encode_with + qeew = QuickEmitterEncodeWith.new + hash = { :qe => qeew } + hash2 = Psych.load Psych.dump hash + qe = hash2[:qe] + + assert_equal qeew.name, qe.name + assert_instance_of QuickEmitterEncodeWith, qe + assert_nil qe.value + end + + class YamlInit + attr_reader :name + attr_reader :value + + def initialize + @name = 'hello!!' + @value = 'Friday!' + end + + def yaml_initialize tag, vals + vals.each { |ivar, val| instance_variable_set "@#{ivar}", 'TGIF!' } + end + end + + def test_yaml_initialize + hash = { :yi => YamlInit.new } + hash2 = Psych.load Psych.dump hash + yi = hash2[:yi] + + assert_equal 'TGIF!', yi.name + assert_equal 'TGIF!', yi.value + assert_instance_of YamlInit, yi + end + + class YamlInitAndInitWith + attr_reader :name + attr_reader :value + + def initialize + @name = 'shaners' + @value = 'Friday!' + end + + def init_with coder + coder.map.each { |ivar, val| instance_variable_set "@#{ivar}", 'TGIF!' } + end + + def yaml_initialize tag, vals + raise + end + end + + ### + # An object that implements both yaml_initialize and init_with should not + # receive the yaml_initialize call. + def test_yaml_initialize_and_init_with + hash = { :yi => YamlInitAndInitWith.new } + hash2 = Psych.load Psych.dump hash + yi = hash2[:yi] + + assert_equal 'TGIF!', yi.name + assert_equal 'TGIF!', yi.value + assert_instance_of YamlInitAndInitWith, yi + end + + def test_coder_scalar + coder = Psych::Coder.new 'foo' + coder.scalar('tag', 'some string', :plain) + assert_equal 'tag', coder.tag + assert_equal 'some string', coder.scalar + assert_equal :scalar, coder.type + end + + class YamlAs + TestCase.suppress_warning do + psych_yaml_as 'helloworld' # this should be yaml_as but to avoid syck + end + end + + def test_yaml_as + assert_match(/helloworld/, Psych.dump(YamlAs.new)) + end + + def test_ruby_type + types = [] + appender = lambda { |*args| types << args } + + Psych.add_ruby_type('foo', &appender) + Psych.load <<-eoyml +- !ruby.yaml.org,2002/foo bar + eoyml + + assert_equal [["tag:ruby.yaml.org,2002:foo", "bar"]], types + end + + def test_detect_implicit + assert_equal '', Psych.detect_implicit(nil) + assert_equal '', Psych.detect_implicit(Object.new) + assert_equal '', Psych.detect_implicit(1.2) + assert_equal 'null', Psych.detect_implicit('') + assert_equal 'string', Psych.detect_implicit('foo') + end + + def test_private_type + types = [] + Psych.add_private_type('foo') { |*args| types << args } + Psych.load <<-eoyml +- !x-private:foo bar + eoyml + + assert_equal [["x-private:foo", "bar"]], types + end + + def test_tagurize + assert_nil Psych.tagurize nil + assert_equal Psych, Psych.tagurize(Psych) + assert_equal 'tag:yaml.org,2002:foo', Psych.tagurize('foo') + end + + def test_read_type_class + things = Psych.read_type_class 'tag:yaml.org,2002:int:Psych::TestDeprecated::QuickEmitter', Object + assert_equal 'int', things.first + assert_equal Psych::TestDeprecated::QuickEmitter, things.last + end + + def test_read_type_class_no_class + things = Psych.read_type_class 'tag:yaml.org,2002:int', Object + assert_equal 'int', things.first + assert_equal Object, things.last + end + + def test_object_maker + thing = Psych.object_maker(Object, { 'a' => 'b', 'c' => 'd' }) + assert_instance_of(Object, thing) + assert_equal 'b', thing.instance_variable_get(:@a) + assert_equal 'd', thing.instance_variable_get(:@c) + end + end +end diff --git a/jni/ruby/test/psych/test_document.rb b/jni/ruby/test/psych/test_document.rb new file mode 100644 index 0000000..bd77d60 --- /dev/null +++ b/jni/ruby/test/psych/test_document.rb @@ -0,0 +1,46 @@ +require_relative 'helper' + +module Psych + class TestDocument < TestCase + def setup + super + @stream = Psych.parse_stream(<<-eoyml) +%YAML 1.1 +%TAG ! tag:tenderlovemaking.com,2009: +--- !fun + eoyml + @doc = @stream.children.first + end + + def test_parse_tag + assert_equal([['!', 'tag:tenderlovemaking.com,2009:']], + @doc.tag_directives) + end + + def test_emit_tag + assert_match('%TAG ! tag:tenderlovemaking.com,2009:', @stream.yaml) + end + + def test_emit_multitag + @doc.tag_directives << ['!!', 'foo.com,2009:'] + yaml = @stream.yaml + assert_match('%TAG ! tag:tenderlovemaking.com,2009:', yaml) + assert_match('%TAG !! foo.com,2009:', yaml) + end + + def test_emit_bad_tag + assert_raises(RuntimeError) do + @doc.tag_directives = [['!']] + @stream.yaml + end + end + + def test_parse_version + assert_equal([1,1], @doc.version) + end + + def test_emit_version + assert_match('%YAML 1.1', @stream.yaml) + end + end +end diff --git a/jni/ruby/test/psych/test_emitter.rb b/jni/ruby/test/psych/test_emitter.rb new file mode 100644 index 0000000..1c96c12 --- /dev/null +++ b/jni/ruby/test/psych/test_emitter.rb @@ -0,0 +1,93 @@ +# -*- coding: utf-8 -*- + +require_relative 'helper' + +module Psych + class TestEmitter < TestCase + def setup + super + @out = StringIO.new('') + @emitter = Psych::Emitter.new @out + end + + def test_line_width + @emitter.line_width = 10 + assert_equal 10, @emitter.line_width + end + + def test_set_canonical + @emitter.canonical = true + assert_equal true, @emitter.canonical + + @emitter.canonical = false + assert_equal false, @emitter.canonical + end + + def test_indentation_set + assert_equal 2, @emitter.indentation + @emitter.indentation = 5 + assert_equal 5, @emitter.indentation + end + + def test_emit_utf_8 + @emitter.start_stream Psych::Nodes::Stream::UTF8 + @emitter.start_document [], [], false + @emitter.scalar '日本語', nil, nil, false, true, 1 + @emitter.end_document true + @emitter.end_stream + assert_match('日本語', @out.string) + end + + def test_start_stream_arg_error + assert_raises(TypeError) do + @emitter.start_stream 'asdfasdf' + end + end + + def test_start_doc_arg_error + @emitter.start_stream Psych::Nodes::Stream::UTF8 + + [ + [nil, [], false], + [[nil, nil], [], false], + [[], 'foo', false], + [[], ['foo'], false], + [[], [nil,nil], false], + ].each do |args| + assert_raises(TypeError) do + @emitter.start_document(*args) + end + end + end + + def test_scalar_arg_error + @emitter.start_stream Psych::Nodes::Stream::UTF8 + @emitter.start_document [], [], false + + [ + [:foo, nil, nil, false, true, 1], + ['foo', Object.new, nil, false, true, 1], + ['foo', nil, Object.new, false, true, 1], + ['foo', nil, nil, false, true, :foo], + [nil, nil, nil, false, true, 1], + ].each do |args| + assert_raises(TypeError) do + @emitter.scalar(*args) + end + end + end + + def test_start_sequence_arg_error + @emitter.start_stream Psych::Nodes::Stream::UTF8 + @emitter.start_document [], [], false + + assert_raises(TypeError) do + @emitter.start_sequence(nil, Object.new, true, 1) + end + + assert_raises(TypeError) do + @emitter.start_sequence(nil, nil, true, :foo) + end + end + end +end diff --git a/jni/ruby/test/psych/test_encoding.rb b/jni/ruby/test/psych/test_encoding.rb new file mode 100644 index 0000000..517cae2 --- /dev/null +++ b/jni/ruby/test/psych/test_encoding.rb @@ -0,0 +1,259 @@ +# -*- coding: utf-8 -*- + +require_relative 'helper' + +module Psych + class TestEncoding < TestCase + class EncodingCatcher < Handler + attr_reader :strings + def initialize + @strings = [] + end + + (Handler.instance_methods(true) - + Object.instance_methods).each do |m| + class_eval %{ + def #{m} *args + @strings += args.flatten.find_all { |a| + String === a + } + end + } + end + end + + def setup + super + @buffer = StringIO.new + @handler = EncodingCatcher.new + @parser = Psych::Parser.new @handler + @utf8 = Encoding.find('UTF-8') + @emitter = Psych::Emitter.new @buffer + end + + def test_dump_load_encoding_object + assert_cycle Encoding::US_ASCII + assert_cycle Encoding::UTF_8 + end + + def test_transcode_shiftjis + str = "こんにちは!" + loaded = Psych.load("--- こんにちは!".encode('SHIFT_JIS')) + assert_equal str, loaded + end + + def test_transcode_utf16le + str = "こんにちは!" + loaded = Psych.load("--- こんにちは!".encode('UTF-16LE')) + assert_equal str, loaded + end + + def test_transcode_utf16be + str = "こんにちは!" + loaded = Psych.load("--- こんにちは!".encode('UTF-16BE')) + assert_equal str, loaded + end + + def test_io_shiftjis + Tempfile.create(['shiftjis', 'yml'], :encoding => 'SHIFT_JIS') {|t| + t.write '--- こんにちは!' + t.close + + # If the external encoding isn't utf8, utf16le, or utf16be, we cannot + # process the file. + File.open(t.path, 'r', :encoding => 'SHIFT_JIS') do |f| + assert_raises Psych::SyntaxError do + Psych.load(f) + end + end + } + end + + def test_io_utf16le + Tempfile.create(['utf16le', 'yml']) {|t| + t.binmode + t.write '--- こんにちは!'.encode('UTF-16LE') + t.close + + File.open(t.path, 'rb', :encoding => 'UTF-16LE') do |f| + assert_equal "こんにちは!", Psych.load(f) + end + } + end + + def test_io_utf16be + Tempfile.create(['utf16be', 'yml']) {|t| + t.binmode + t.write '--- こんにちは!'.encode('UTF-16BE') + t.close + + File.open(t.path, 'rb', :encoding => 'UTF-16BE') do |f| + assert_equal "こんにちは!", Psych.load(f) + end + } + end + + def test_io_utf8 + Tempfile.create(['utf8', 'yml']) {|t| + t.binmode + t.write '--- こんにちは!'.encode('UTF-8') + t.close + + File.open(t.path, 'rb', :encoding => 'UTF-8') do |f| + assert_equal "こんにちは!", Psych.load(f) + end + } + end + + def test_emit_alias + @emitter.start_stream Psych::Parser::UTF8 + @emitter.start_document [], [], true + e = assert_raises(RuntimeError) do + @emitter.alias 'ドラえもん'.encode('EUC-JP') + end + assert_match(/alias value/, e.message) + end + + def test_to_yaml_is_valid + with_default_external(Encoding::US_ASCII) do + with_default_internal(nil) do + s = "こんにちは!" + # If no encoding is specified, use UTF-8 + assert_equal Encoding::UTF_8, Psych.dump(s).encoding + assert_equal s, Psych.load(Psych.dump(s)) + end + end + end + + def test_start_mapping + foo = 'foo' + bar = 'バー' + + @emitter.start_stream Psych::Parser::UTF8 + @emitter.start_document [], [], true + @emitter.start_mapping( + foo.encode('Shift_JIS'), + bar.encode('UTF-16LE'), + false, Nodes::Sequence::ANY) + @emitter.end_mapping + @emitter.end_document false + @emitter.end_stream + + @parser.parse @buffer.string + assert_encodings @utf8, @handler.strings + assert_equal [foo, bar], @handler.strings + end + + def test_start_sequence + foo = 'foo' + bar = 'バー' + + @emitter.start_stream Psych::Parser::UTF8 + @emitter.start_document [], [], true + @emitter.start_sequence( + foo.encode('Shift_JIS'), + bar.encode('UTF-16LE'), + false, Nodes::Sequence::ANY) + @emitter.end_sequence + @emitter.end_document false + @emitter.end_stream + + @parser.parse @buffer.string + assert_encodings @utf8, @handler.strings + assert_equal [foo, bar], @handler.strings + end + + def test_doc_tag_encoding + key = '鍵' + @emitter.start_stream Psych::Parser::UTF8 + @emitter.start_document( + [1, 1], + [['!'.encode('EUC-JP'), key.encode('EUC-JP')]], + true + ) + @emitter.scalar 'foo', nil, nil, true, false, Nodes::Scalar::ANY + @emitter.end_document false + @emitter.end_stream + + @parser.parse @buffer.string + assert_encodings @utf8, @handler.strings + assert_equal key, @handler.strings[1] + end + + def test_emitter_encoding + str = "壁に耳あり、障子に目あり" + thing = Psych.load Psych.dump str.encode('EUC-JP') + assert_equal str, thing + end + + def test_default_internal + with_default_internal(Encoding::EUC_JP) do + str = "壁に耳あり、障子に目あり" + assert_equal @utf8, str.encoding + + @parser.parse str + assert_encodings Encoding::EUC_JP, @handler.strings + assert_equal str, @handler.strings.first.encode('UTF-8') + end + end + + def test_scalar + @parser.parse("--- a") + assert_encodings @utf8, @handler.strings + end + + def test_alias + @parser.parse(<<-eoyml) +%YAML 1.1 +--- +!!seq [ + !!str "Without properties", + &A !!str "Anchored", + !!str "Tagged", + *A, + !!str "", +] + eoyml + assert_encodings @utf8, @handler.strings + end + + def test_list_anchor + list = %w{ a b } + list << list + @parser.parse(Psych.dump(list)) + assert_encodings @utf8, @handler.strings + end + + def test_map_anchor + h = {} + h['a'] = h + @parser.parse(Psych.dump(h)) + assert_encodings @utf8, @handler.strings + end + + def test_map_tag + @parser.parse(<<-eoyml) +%YAML 1.1 +--- +!!map { a : b } + eoyml + assert_encodings @utf8, @handler.strings + end + + def test_doc_tag + @parser.parse(<<-eoyml) +%YAML 1.1 +%TAG ! tag:tenderlovemaking.com,2009: +--- !fun + eoyml + assert_encodings @utf8, @handler.strings + end + + private + def assert_encodings encoding, strings + strings.each do |str| + assert_equal encoding, str.encoding, str + end + end + end +end diff --git a/jni/ruby/test/psych/test_exception.rb b/jni/ruby/test/psych/test_exception.rb new file mode 100644 index 0000000..30dfb24 --- /dev/null +++ b/jni/ruby/test/psych/test_exception.rb @@ -0,0 +1,157 @@ +require_relative 'helper' + +module Psych + class TestException < TestCase + class Wups < Exception + attr_reader :foo, :bar + def initialize *args + super + @foo = 1 + @bar = 2 + end + end + + def setup + super + @wups = Wups.new + end + + def test_naming_exception + err = String.xxx rescue $! + new_err = Psych.load(Psych.dump(err)) + assert_equal err.message, new_err.message + end + + def test_load_takes_file + ex = assert_raises(Psych::SyntaxError) do + Psych.load '--- `' + end + assert_nil ex.file + + ex = assert_raises(Psych::SyntaxError) do + Psych.load '--- `', 'meow' + end + assert_equal 'meow', ex.file + end + + def test_psych_parse_stream_takes_file + ex = assert_raises(Psych::SyntaxError) do + Psych.parse_stream '--- `' + end + assert_nil ex.file + assert_match '(<unknown>)', ex.message + + ex = assert_raises(Psych::SyntaxError) do + Psych.parse_stream '--- `', 'omg!' + end + assert_equal 'omg!', ex.file + assert_match 'omg!', ex.message + end + + def test_load_stream_takes_file + ex = assert_raises(Psych::SyntaxError) do + Psych.load_stream '--- `' + end + assert_nil ex.file + assert_match '(<unknown>)', ex.message + + ex = assert_raises(Psych::SyntaxError) do + Psych.load_stream '--- `', 'omg!' + end + assert_equal 'omg!', ex.file + end + + def test_parse_file_exception + Tempfile.create(['parsefile', 'yml']) {|t| + t.binmode + t.write '--- `' + t.close + ex = assert_raises(Psych::SyntaxError) do + Psych.parse_file t.path + end + assert_equal t.path, ex.file + } + end + + def test_load_file_exception + Tempfile.create(['loadfile', 'yml']) {|t| + t.binmode + t.write '--- `' + t.close + ex = assert_raises(Psych::SyntaxError) do + Psych.load_file t.path + end + assert_equal t.path, ex.file + } + end + + def test_psych_parse_takes_file + ex = assert_raises(Psych::SyntaxError) do + Psych.parse '--- `' + end + assert_match '(<unknown>)', ex.message + assert_nil ex.file + + ex = assert_raises(Psych::SyntaxError) do + Psych.parse '--- `', 'omg!' + end + assert_match 'omg!', ex.message + end + + def test_attributes + e = assert_raises(Psych::SyntaxError) { + Psych.load '--- `foo' + } + + assert_nil e.file + assert_equal 1, e.line + assert_equal 5, e.column + # FIXME: offset isn't being set correctly by libyaml + # assert_equal 5, e.offset + + assert e.problem + assert e.context + end + + def test_convert + w = Psych.load(Psych.dump(@wups)) + assert_equal @wups, w + assert_equal 1, w.foo + assert_equal 2, w.bar + end + + def test_to_yaml_properties + class << @wups + def to_yaml_properties + [:@foo] + end + end + + w = Psych.load(Psych.dump(@wups)) + assert_equal @wups, w + assert_equal 1, w.foo + assert_nil w.bar + end + + def test_psych_syntax_error + Tempfile.create(['parsefile', 'yml']) do |t| + t.binmode + t.write '--- `' + t.close + + begin + Psych.parse_file t.path + rescue StandardError + assert true # count assertion + ensure + return unless $! + + ancestors = $!.class.ancestors.inspect + + flunk "Psych::SyntaxError not rescued by StandardError: #{ancestors}" + end + end + end + + end +end diff --git a/jni/ruby/test/psych/test_hash.rb b/jni/ruby/test/psych/test_hash.rb new file mode 100644 index 0000000..264a471 --- /dev/null +++ b/jni/ruby/test/psych/test_hash.rb @@ -0,0 +1,49 @@ +require_relative 'helper' + +module Psych + class TestHash < TestCase + class X < Hash + end + + def setup + super + @hash = { :a => 'b' } + end + + def test_load_with_class_syck_compatibility + hash = Psych.load "--- !ruby/object:Hash\n:user_id: 7\n:username: Lucas\n" + assert_equal({ user_id: 7, username: 'Lucas'}, hash) + end + + def test_empty_subclass + assert_match "!ruby/hash:#{X}", Psych.dump(X.new) + x = Psych.load Psych.dump X.new + assert_equal X, x.class + end + + def test_map + x = Psych.load "--- !map:#{X} { }\n" + assert_equal X, x.class + end + + def test_self_referential + @hash['self'] = @hash + assert_cycle(@hash) + end + + def test_cycles + assert_cycle(@hash) + end + + def test_ref_append + hash = Psych.load(<<-eoyml) +--- +foo: &foo + hello: world +bar: + <<: *foo +eoyml + assert_equal({"foo"=>{"hello"=>"world"}, "bar"=>{"hello"=>"world"}}, hash) + end + end +end diff --git a/jni/ruby/test/psych/test_json_tree.rb b/jni/ruby/test/psych/test_json_tree.rb new file mode 100644 index 0000000..a23fc1a --- /dev/null +++ b/jni/ruby/test/psych/test_json_tree.rb @@ -0,0 +1,65 @@ +require_relative 'helper' + +module Psych + class TestJSONTree < TestCase + def test_string + assert_match(/"foo"/, Psych.to_json("foo")) + end + + def test_symbol + assert_match(/"foo"/, Psych.to_json(:foo)) + end + + def test_nil + assert_match(/^null/, Psych.to_json(nil)) + end + + def test_int + assert_match(/^10/, Psych.to_json(10)) + end + + def test_float + assert_match(/^1.2/, Psych.to_json(1.2)) + end + + def test_hash + hash = { 'one' => 'two' } + json = Psych.to_json(hash) + assert_match(/}$/, json) + assert_match(/^\{/, json) + assert_match(/['"]one['"]/, json) + assert_match(/['"]two['"]/, json) + end + + class Bar + def encode_with coder + coder.represent_seq 'omg', %w{ a b c } + end + end + + def test_json_list_dump_exclude_tag + json = Psych.to_json Bar.new + refute_match('omg', json) + end + + def test_list_to_json + list = %w{ one two } + json = Psych.to_json(list) + assert_match(/\]$/, json) + assert_match(/^\[/, json) + assert_match(/"one"/, json) + assert_match(/"two"/, json) + end + + def test_time + time = Time.utc(2010, 10, 10) + assert_equal "{\"a\": \"2010-10-10 00:00:00.000000000 Z\"}\n", +Psych.to_json({'a' => time }) + end + + def test_datetime + time = Time.new(2010, 10, 10).to_datetime + assert_equal "{\"a\": \"#{time.strftime("%Y-%m-%d %H:%M:%S.%9N %:z")}\"}\n", Psych.to_json({'a' => time }) + end + end +end diff --git a/jni/ruby/test/psych/test_marshalable.rb b/jni/ruby/test/psych/test_marshalable.rb new file mode 100644 index 0000000..7df74ee --- /dev/null +++ b/jni/ruby/test/psych/test_marshalable.rb @@ -0,0 +1,54 @@ +require_relative 'helper' +require 'delegate' + +module Psych + class TestMarshalable < TestCase + def test_objects_defining_marshal_dump_and_marshal_load_can_be_dumped + sd = SimpleDelegator.new(1) + loaded = Psych.load(Psych.dump(sd)) + + assert_instance_of(SimpleDelegator, loaded) + assert_equal(sd, loaded) + end + + class PsychCustomMarshalable < BasicObject + attr_reader :foo + + def initialize(foo) + @foo = foo + end + + def marshal_dump + [foo] + end + + def mashal_load(data) + @foo = data[0] + end + + def init_with(coder) + @foo = coder['foo'] + end + + def encode_with(coder) + coder['foo'] = 2 + end + + def respond_to?(method) + [:marshal_dump, :marshal_load, :init_with, :encode_with].include?(method) + end + + def class + PsychCustomMarshalable + end + end + + def test_init_with_takes_priority_over_marshal_methods + obj = PsychCustomMarshalable.new(1) + loaded = Psych.load(Psych.dump(obj)) + + assert(PsychCustomMarshalable === loaded) + assert_equal(2, loaded.foo) + end + end +end diff --git a/jni/ruby/test/psych/test_merge_keys.rb b/jni/ruby/test/psych/test_merge_keys.rb new file mode 100644 index 0000000..1620a6a --- /dev/null +++ b/jni/ruby/test/psych/test_merge_keys.rb @@ -0,0 +1,180 @@ +require_relative 'helper' + +module Psych + class TestMergeKeys < TestCase + class Product + attr_reader :bar + end + + def test_merge_key_with_bare_hash + doc = Psych.load <<-eodoc +map: + <<: + hello: world + eodoc + hash = { "map" => { "hello" => "world" } } + assert_equal hash, doc + end + + def test_roundtrip_with_chevron_key + h = {} + v = { 'a' => h, '<<' => h } + assert_cycle v + end + + def test_explicit_string + doc = Psych.load <<-eoyml +a: &me { hello: world } +b: { !!str '<<': *me } +eoyml + expected = { + "a" => { "hello" => "world" }, + "b" => { + "<<" => { "hello" => "world" } + } + } + assert_equal expected, doc + end + + def test_mergekey_with_object + s = <<-eoyml +foo: &foo + bar: 10 +product: + !ruby/object:#{Product.name} + <<: *foo + eoyml + hash = Psych.load s + assert_equal({"bar" => 10}, hash["foo"]) + product = hash["product"] + assert_equal 10, product.bar + end + + def test_merge_nil + yaml = <<-eoyml +defaults: &defaults +development: + <<: *defaults + eoyml + assert_equal({'<<' => nil }, Psych.load(yaml)['development']) + end + + def test_merge_array + yaml = <<-eoyml +foo: &hello +- 1 +baz: + <<: *hello + eoyml + assert_equal({'<<' => [1]}, Psych.load(yaml)['baz']) + end + + def test_merge_is_not_partial + yaml = <<-eoyml +default: &default + hello: world +foo: &hello +- 1 +baz: + <<: [*hello, *default] + eoyml + doc = Psych.load yaml + refute doc['baz'].key? 'hello' + assert_equal({'<<' => [[1], {"hello"=>"world"}]}, Psych.load(yaml)['baz']) + end + + def test_merge_seq_nil + yaml = <<-eoyml +foo: &hello +baz: + <<: [*hello] + eoyml + assert_equal({'<<' => [nil]}, Psych.load(yaml)['baz']) + end + + def test_bad_seq_merge + yaml = <<-eoyml +defaults: &defaults [1, 2, 3] +development: + <<: *defaults + eoyml + assert_equal({'<<' => [1,2,3]}, Psych.load(yaml)['development']) + end + + def test_missing_merge_key + yaml = <<-eoyml +bar: + << : *foo + eoyml + exp = assert_raises(Psych::BadAlias) { Psych.load yaml } + assert_match 'foo', exp.message + end + + # [ruby-core:34679] + def test_merge_key + yaml = <<-eoyml +foo: &foo + hello: world +bar: + << : *foo + baz: boo + eoyml + + hash = { + "foo" => { "hello" => "world"}, + "bar" => { "hello" => "world", "baz" => "boo" } } + assert_equal hash, Psych.load(yaml) + end + + def test_multiple_maps + yaml = <<-eoyaml +--- +- &CENTER { x: 1, y: 2 } +- &LEFT { x: 0, y: 2 } +- &BIG { r: 10 } +- &SMALL { r: 1 } + +# All the following maps are equal: + +- # Merge multiple maps + << : [ *CENTER, *BIG ] + label: center/big + eoyaml + + hash = { + 'x' => 1, + 'y' => 2, + 'r' => 10, + 'label' => 'center/big' + } + + assert_equal hash, Psych.load(yaml)[4] + end + + def test_override + yaml = <<-eoyaml +--- +- &CENTER { x: 1, y: 2 } +- &LEFT { x: 0, y: 2 } +- &BIG { r: 10 } +- &SMALL { r: 1 } + +# All the following maps are equal: + +- # Override + << : [ *BIG, *LEFT, *SMALL ] + x: 1 + label: center/big + eoyaml + + hash = { + 'x' => 1, + 'y' => 2, + 'r' => 10, + 'label' => 'center/big' + } + + assert_equal hash, Psych.load(yaml)[4] + end + end +end diff --git a/jni/ruby/test/psych/test_nil.rb b/jni/ruby/test/psych/test_nil.rb new file mode 100644 index 0000000..3dbf562 --- /dev/null +++ b/jni/ruby/test/psych/test_nil.rb @@ -0,0 +1,18 @@ +require_relative 'helper' + +module Psych + class TestNil < TestCase + def test_nil + yml = Psych.dump nil + assert_match(/--- \n(?:\.\.\.\n)?/, yml) + assert_nil Psych.load(yml) + end + + def test_array_nil + yml = Psych.dump [nil] + assert_equal "---\n- \n", yml + assert_equal [nil], Psych.load(yml) + end + + end +end diff --git a/jni/ruby/test/psych/test_null.rb b/jni/ruby/test/psych/test_null.rb new file mode 100644 index 0000000..1725550 --- /dev/null +++ b/jni/ruby/test/psych/test_null.rb @@ -0,0 +1,19 @@ +require_relative 'helper' + +module Psych + ### + # Test null from YAML spec: + # http://yaml.org/type/null.html + class TestNull < TestCase + def test_null_list + assert_equal [nil] * 5, Psych.load(<<-eoyml) +--- +- ~ +- null +- +- Null +- NULL + eoyml + end + end +end diff --git a/jni/ruby/test/psych/test_numeric.rb b/jni/ruby/test/psych/test_numeric.rb new file mode 100644 index 0000000..5378b4a --- /dev/null +++ b/jni/ruby/test/psych/test_numeric.rb @@ -0,0 +1,45 @@ +require_relative 'helper' +require 'bigdecimal' + +module Psych + ### + # Test numerics from YAML spec: + # http://yaml.org/type/float.html + # http://yaml.org/type/int.html + class TestNumeric < TestCase + def setup + @old_debug = $DEBUG + $DEBUG = true + end + + def teardown + $DEBUG = @old_debug + end + + def test_load_float_with_dot + assert_equal 1.0, Psych.load('--- 1.') + end + + def test_non_float_with_0 + str = Psych.load('--- 090') + assert_equal '090', str + end + + def test_big_decimal_tag + decimal = BigDecimal("12.34") + assert_match "!ruby/object:BigDecimal", Psych.dump(decimal) + end + + def test_big_decimal_round_trip + decimal = BigDecimal("12.34") + assert_cycle decimal + end + + def test_does_not_attempt_numeric + str = Psych.load('--- 4 roses') + assert_equal '4 roses', str + str = Psych.load('--- 1.1.1') + assert_equal '1.1.1', str + end + end +end diff --git a/jni/ruby/test/psych/test_object.rb b/jni/ruby/test/psych/test_object.rb new file mode 100644 index 0000000..5e3ce82 --- /dev/null +++ b/jni/ruby/test/psych/test_object.rb @@ -0,0 +1,44 @@ +require_relative 'helper' + +module Psych + class Tagged + yaml_tag '!foo' + + attr_accessor :baz + + def initialize + @baz = 'bar' + end + end + + class Foo + attr_accessor :parent + + def initialize parent + @parent = parent + end + end + + class TestObject < TestCase + def test_dump_with_tag + tag = Tagged.new + assert_match('foo', Psych.dump(tag)) + end + + def test_tag_round_trip + tag = Tagged.new + tag2 = Psych.load(Psych.dump(tag)) + assert_equal tag.baz, tag2.baz + assert_instance_of(Tagged, tag2) + end + + def test_cyclic_references + foo = Foo.new(nil) + foo.parent = foo + loaded = Psych.load Psych.dump foo + + assert_instance_of(Foo, loaded) + assert_equal loaded, loaded.parent + end + end +end diff --git a/jni/ruby/test/psych/test_object_references.rb b/jni/ruby/test/psych/test_object_references.rb new file mode 100644 index 0000000..273b466 --- /dev/null +++ b/jni/ruby/test/psych/test_object_references.rb @@ -0,0 +1,71 @@ +require_relative 'helper' + +module Psych + class TestObjectReferences < TestCase + def test_range_has_references + assert_reference_trip 1..2 + end + + def test_module_has_references + assert_reference_trip Psych + end + + def test_class_has_references + assert_reference_trip TestObjectReferences + end + + def test_rational_has_references + assert_reference_trip Rational('1.2') + end + + def test_complex_has_references + assert_reference_trip Complex(1, 2) + end + + def test_datetime_has_references + assert_reference_trip DateTime.now + end + + def test_struct_has_references + assert_reference_trip Struct.new(:foo).new(1) + end + + def assert_reference_trip obj + yml = Psych.dump([obj, obj]) + assert_match(/\*-?\d+/, yml) + data = Psych.load yml + assert_equal data.first.object_id, data.last.object_id + end + + def test_float_references + data = Psych.load <<-eoyml +---\s +- &name 1.2 +- *name + eoyml + assert_equal data.first, data.last + assert_equal data.first.object_id, data.last.object_id + end + + def test_binary_references + data = Psych.load <<-eoyml +--- +- &name !binary |- + aGVsbG8gd29ybGQh +- *name + eoyml + assert_equal data.first, data.last + assert_equal data.first.object_id, data.last.object_id + end + + def test_regexp_references + data = Psych.load <<-eoyml +---\s +- &name !ruby/regexp /pattern/i +- *name + eoyml + assert_equal data.first, data.last + assert_equal data.first.object_id, data.last.object_id + end + end +end diff --git a/jni/ruby/test/psych/test_omap.rb b/jni/ruby/test/psych/test_omap.rb new file mode 100644 index 0000000..36edc26 --- /dev/null +++ b/jni/ruby/test/psych/test_omap.rb @@ -0,0 +1,75 @@ +require_relative 'helper' + +module Psych + class TestOmap < TestCase + def test_parse_as_map + o = Psych.load "--- !!omap\na: 1\nb: 2" + assert_kind_of Psych::Omap, o + assert_equal 1, o['a'] + assert_equal 2, o['b'] + end + + def test_self_referential + map = Psych::Omap.new + map['foo'] = 'bar' + map['self'] = map + assert_equal(map, Psych.load(Psych.dump(map))) + end + + def test_keys + map = Psych::Omap.new + map['foo'] = 'bar' + assert_equal 'bar', map['foo'] + end + + def test_order + map = Psych::Omap.new + map['a'] = 'b' + map['b'] = 'c' + assert_equal [%w{a b}, %w{b c}], map.to_a + end + + def test_square + list = [["a", "b"], ["b", "c"]] + map = Psych::Omap[*list.flatten] + assert_equal list, map.to_a + assert_equal 'b', map['a'] + assert_equal 'c', map['b'] + end + + def test_dump + map = Psych::Omap['a', 'b', 'c', 'd'] + yaml = Psych.dump(map) + assert_match('!omap', yaml) + assert_match('- a: b', yaml) + assert_match('- c: d', yaml) + end + + def test_round_trip + list = [["a", "b"], ["b", "c"]] + map = Psych::Omap[*list.flatten] + assert_cycle(map) + end + + def test_load + list = [["a", "b"], ["c", "d"]] + map = Psych.load(<<-eoyml) +--- !omap +- a: b +- c: d + eoyml + assert_equal list, map.to_a + end + + # NOTE: This test will not work with Syck + def test_load_shorthand + list = [["a", "b"], ["c", "d"]] + map = Psych.load(<<-eoyml) +--- !!omap +- a: b +- c: d + eoyml + assert_equal list, map.to_a + end + end +end diff --git a/jni/ruby/test/psych/test_parser.rb b/jni/ruby/test/psych/test_parser.rb new file mode 100644 index 0000000..0abe0dd --- /dev/null +++ b/jni/ruby/test/psych/test_parser.rb @@ -0,0 +1,339 @@ +# coding: utf-8 + +require_relative 'helper' + +module Psych + class TestParser < TestCase + class EventCatcher < Handler + attr_accessor :parser + attr_reader :calls, :marks + def initialize + @parser = nil + @calls = [] + @marks = [] + end + + (Handler.instance_methods(true) - + Object.instance_methods).each do |m| + class_eval %{ + def #{m} *args + super + @marks << @parser.mark if @parser + @calls << [:#{m}, args] + end + } + end + end + + def setup + super + @handler = EventCatcher.new + @parser = Psych::Parser.new @handler + @handler.parser = @parser + end + + def test_ast_roundtrip + parser = Psych.parser + parser.parse('null') + ast = parser.handler.root + assert_match(/^null/, ast.yaml) + end + + def test_exception_memory_leak + yaml = <<-eoyaml +%YAML 1.1 +%TAG ! tag:tenderlovemaking.com,2009: +--- &ponies +- first element +- *ponies +- foo: bar +... + eoyaml + + [:start_stream, :start_document, :end_document, :alias, :scalar, + :start_sequence, :end_sequence, :start_mapping, :end_mapping, + :end_stream].each do |method| + + klass = Class.new(Psych::Handler) do + define_method(method) do |*args| + raise + end + end + + parser = Psych::Parser.new klass.new + 2.times { + assert_raises(RuntimeError, method.to_s) do + parser.parse yaml + end + } + end + end + + def test_multiparse + 3.times do + @parser.parse '--- foo' + end + end + + def test_filename + ex = assert_raises(Psych::SyntaxError) do + @parser.parse '--- `', 'omg!' + end + assert_match 'omg!', ex.message + end + + def test_line_numbers + assert_equal 0, @parser.mark.line + @parser.parse "---\n- hello\n- world" + line_calls = @handler.marks.map(&:line).zip(@handler.calls.map(&:first)) + assert_equal [[0, :start_stream], + [0, :start_document], + [1, :start_sequence], + [2, :scalar], + [3, :scalar], + [3, :end_sequence], + [3, :end_document], + [3, :end_stream]], line_calls + + assert_equal 3, @parser.mark.line + end + + def test_column_numbers + assert_equal 0, @parser.mark.column + @parser.parse "---\n- hello\n- world" + col_calls = @handler.marks.map(&:column).zip(@handler.calls.map(&:first)) + assert_equal [[0, :start_stream], + [3, :start_document], + [1, :start_sequence], + [0, :scalar], + [0, :scalar], + [0, :end_sequence], + [0, :end_document], + [0, :end_stream]], col_calls + + assert_equal 0, @parser.mark.column + end + + def test_index_numbers + assert_equal 0, @parser.mark.index + @parser.parse "---\n- hello\n- world" + idx_calls = @handler.marks.map(&:index).zip(@handler.calls.map(&:first)) + assert_equal [[0, :start_stream], + [3, :start_document], + [5, :start_sequence], + [12, :scalar], + [19, :scalar], + [19, :end_sequence], + [19, :end_document], + [19, :end_stream]], idx_calls + + assert_equal 19, @parser.mark.index + end + + def test_bom + tadpole = 'おたまじゃくし' + + # BOM + text + yml = "\uFEFF#{tadpole}".encode('UTF-16LE') + @parser.parse yml + assert_equal tadpole, @parser.handler.calls[2][1].first + end + + def test_external_encoding + tadpole = 'おたまじゃくし' + + @parser.external_encoding = Psych::Parser::UTF16LE + @parser.parse tadpole.encode 'UTF-16LE' + assert_equal tadpole, @parser.handler.calls[2][1].first + end + + def test_bogus_io + o = Object.new + def o.external_encoding; nil end + def o.read len; self end + + assert_raises(TypeError) do + @parser.parse o + end + end + + def test_parse_io + @parser.parse StringIO.new("--- a") + assert_called :start_stream + assert_called :scalar + assert_called :end_stream + end + + def test_syntax_error + assert_raises(Psych::SyntaxError) do + @parser.parse("---\n\"foo\"\n\"bar\"\n") + end + end + + def test_syntax_error_twice + assert_raises(Psych::SyntaxError) do + @parser.parse("---\n\"foo\"\n\"bar\"\n") + end + + assert_raises(Psych::SyntaxError) do + @parser.parse("---\n\"foo\"\n\"bar\"\n") + end + end + + def test_syntax_error_has_path_for_string + e = assert_raises(Psych::SyntaxError) do + @parser.parse("---\n\"foo\"\n\"bar\"\n") + end + assert_match '(<unknown>):', e.message + end + + def test_syntax_error_has_path_for_io + io = StringIO.new "---\n\"foo\"\n\"bar\"\n" + def io.path; "hello!"; end + + e = assert_raises(Psych::SyntaxError) do + @parser.parse(io) + end + assert_match "(#{io.path}):", e.message + end + + def test_mapping_end + @parser.parse("---\n!!map { key: value }") + assert_called :end_mapping + end + + def test_mapping_tag + @parser.parse("---\n!!map { key: value }") + assert_called :start_mapping, ["tag:yaml.org,2002:map", false, Nodes::Mapping::FLOW] + end + + def test_mapping_anchor + @parser.parse("---\n&A { key: value }") + assert_called :start_mapping, ['A', true, Nodes::Mapping::FLOW] + end + + def test_mapping_block + @parser.parse("---\n key: value") + assert_called :start_mapping, [true, Nodes::Mapping::BLOCK] + end + + def test_mapping_start + @parser.parse("---\n{ key: value }") + assert_called :start_mapping + assert_called :start_mapping, [true, Nodes::Mapping::FLOW] + end + + def test_sequence_end + @parser.parse("---\n&A [1, 2]") + assert_called :end_sequence + end + + def test_sequence_start_anchor + @parser.parse("---\n&A [1, 2]") + assert_called :start_sequence, ["A", true, Nodes::Sequence::FLOW] + end + + def test_sequence_start_tag + @parser.parse("---\n!!seq [1, 2]") + assert_called :start_sequence, ["tag:yaml.org,2002:seq", false, Nodes::Sequence::FLOW] + end + + def test_sequence_start_flow + @parser.parse("---\n[1, 2]") + assert_called :start_sequence, [true, Nodes::Sequence::FLOW] + end + + def test_sequence_start_block + @parser.parse("---\n - 1\n - 2") + assert_called :start_sequence, [true, Nodes::Sequence::BLOCK] + end + + def test_literal_scalar + @parser.parse(<<-eoyml) +%YAML 1.1 +--- +"literal\n\ + \ttext\n" + eoyml + assert_called :scalar, ['literal text ', false, true, Nodes::Scalar::DOUBLE_QUOTED] + end + + def test_scalar + @parser.parse("--- foo\n") + assert_called :scalar, ['foo', true, false, Nodes::Scalar::PLAIN] + end + + def test_scalar_with_tag + @parser.parse("---\n!!str foo\n") + assert_called :scalar, ['foo', 'tag:yaml.org,2002:str', false, false, Nodes::Scalar::PLAIN] + end + + def test_scalar_with_anchor + @parser.parse("---\n&A foo\n") + assert_called :scalar, ['foo', 'A', true, false, Nodes::Scalar::PLAIN] + end + + def test_scalar_plain_implicit + @parser.parse("---\n&A foo\n") + assert_called :scalar, ['foo', 'A', true, false, Nodes::Scalar::PLAIN] + end + + def test_alias + @parser.parse(<<-eoyml) +%YAML 1.1 +--- +!!seq [ + !!str "Without properties", + &A !!str "Anchored", + !!str "Tagged", + *A, + !!str "", +] + eoyml + assert_called :alias, ['A'] + end + + def test_end_stream + @parser.parse("--- foo\n") + assert_called :end_stream + end + + def test_start_stream + @parser.parse("--- foo\n") + assert_called :start_stream + end + + def test_end_document_implicit + @parser.parse("\"foo\"\n") + assert_called :end_document, [true] + end + + def test_end_document_explicit + @parser.parse("\"foo\"\n...") + assert_called :end_document, [false] + end + + def test_start_document_version + @parser.parse("%YAML 1.1\n---\n\"foo\"\n") + assert_called :start_document, [[1,1], [], false] + end + + def test_start_document_tag + @parser.parse("%TAG !yaml! tag:yaml.org,2002\n---\n!yaml!str \"foo\"\n") + assert_called :start_document, [[], [['!yaml!', 'tag:yaml.org,2002']], false] + end + + def assert_called call, with = nil, parser = @parser + if with + call = parser.handler.calls.find { |x| + x.first == call && x.last.compact == with + } + assert(call, + "#{[call,with].inspect} not in #{parser.handler.calls.inspect}" + ) + else + assert parser.handler.calls.any? { |x| x.first == call } + end + end + end +end diff --git a/jni/ruby/test/psych/test_psych.rb b/jni/ruby/test/psych/test_psych.rb new file mode 100644 index 0000000..8054bd6 --- /dev/null +++ b/jni/ruby/test/psych/test_psych.rb @@ -0,0 +1,168 @@ +require_relative 'helper' + +require 'stringio' +require 'tempfile' + +class TestPsych < Psych::TestCase + def teardown + Psych.domain_types.clear + end + + def test_line_width + yml = Psych.dump('123456 7', { :line_width => 5 }) + assert_match(/^\s*7/, yml) + end + + def test_indent + yml = Psych.dump({:a => {'b' => 'c'}}, {:indentation => 5}) + assert_match(/^[ ]{5}b/, yml) + end + + def test_canonical + yml = Psych.dump({:a => {'b' => 'c'}}, {:canonical => true}) + assert_match(/\? "b/, yml) + end + + def test_header + yml = Psych.dump({:a => {'b' => 'c'}}, {:header => true}) + assert_match(/YAML/, yml) + end + + def test_version_array + yml = Psych.dump({:a => {'b' => 'c'}}, {:version => [1,1]}) + assert_match(/1.1/, yml) + end + + def test_version_string + yml = Psych.dump({:a => {'b' => 'c'}}, {:version => '1.1'}) + assert_match(/1.1/, yml) + end + + def test_version_bool + yml = Psych.dump({:a => {'b' => 'c'}}, {:version => true}) + assert_match(/1.1/, yml) + end + + def test_load_argument_error + assert_raises(TypeError) do + Psych.load nil + end + end + + def test_non_existing_class_on_deserialize + e = assert_raises(ArgumentError) do + Psych.load("--- !ruby/object:NonExistent\nfoo: 1") + end + assert_equal 'undefined class/module NonExistent', e.message + end + + def test_dump_stream + things = [22, "foo \n", {}] + stream = Psych.dump_stream(*things) + assert_equal things, Psych.load_stream(stream) + end + + def test_dump_file + hash = {'hello' => 'TGIF!'} + Tempfile.create('fun.yml') do |io| + assert_equal io, Psych.dump(hash, io) + io.rewind + assert_equal Psych.dump(hash), io.read + end + end + + def test_dump_io + hash = {'hello' => 'TGIF!'} + stringio = StringIO.new '' + assert_equal stringio, Psych.dump(hash, stringio) + assert_equal Psych.dump(hash), stringio.string + end + + def test_simple + assert_equal 'foo', Psych.load("--- foo\n") + end + + def test_libyaml_version + assert Psych.libyaml_version + assert_equal Psych.libyaml_version.join('.'), Psych::LIBYAML_VERSION + end + + def test_load_documents + docs = Psych.load_documents("--- foo\n...\n--- bar\n...") + assert_equal %w{ foo bar }, docs + end + + def test_parse_stream + docs = Psych.parse_stream("--- foo\n...\n--- bar\n...") + assert_equal %w{ foo bar }, docs.children.map { |x| x.transform } + end + + def test_add_builtin_type + got = nil + Psych.add_builtin_type 'omap' do |type, val| + got = val + end + Psych.load('--- !!omap hello') + assert_equal 'hello', got + ensure + Psych.remove_type 'omap' + end + + def test_domain_types + got = nil + Psych.add_domain_type 'foo.bar,2002', 'foo' do |type, val| + got = val + end + + Psych.load('--- !foo.bar,2002/foo hello') + assert_equal 'hello', got + + Psych.load("--- !foo.bar,2002/foo\n- hello\n- world") + assert_equal %w{ hello world }, got + + Psych.load("--- !foo.bar,2002/foo\nhello: world") + assert_equal({ 'hello' => 'world' }, got) + end + + def test_load_file + Tempfile.create(['yikes', 'yml']) {|t| + t.binmode + t.write('--- hello world') + t.close + assert_equal 'hello world', Psych.load_file(t.path) + } + end + + def test_parse_file + Tempfile.create(['yikes', 'yml']) {|t| + t.binmode + t.write('--- hello world') + t.close + assert_equal 'hello world', Psych.parse_file(t.path).transform + } + end + + def test_degenerate_strings + assert_equal false, Psych.load(' ') + assert_equal false, Psych.parse(' ') + assert_equal false, Psych.load('') + assert_equal false, Psych.parse('') + end + + def test_callbacks + types = [] + appender = lambda { |*args| types << args } + + Psych.add_builtin_type('foo', &appender) + Psych.add_domain_type('example.com,2002', 'foo', &appender) + Psych.load <<-eoyml +- !tag:yaml.org,2002:foo bar +- !tag:example.com,2002:foo bar + eoyml + + assert_equal [ + ["tag:yaml.org,2002:foo", "bar"], + ["tag:example.com,2002:foo", "bar"] + ], types + end +end diff --git a/jni/ruby/test/psych/test_safe_load.rb b/jni/ruby/test/psych/test_safe_load.rb new file mode 100644 index 0000000..dd299c0 --- /dev/null +++ b/jni/ruby/test/psych/test_safe_load.rb @@ -0,0 +1,97 @@ +require 'psych/helper' + +module Psych + class TestSafeLoad < TestCase + class Foo; end + + [1, 2.2, {}, [], "foo"].each do |obj| + define_method(:"test_basic_#{obj.class}") do + assert_safe_cycle obj + end + end + + def test_no_recursion + x = [] + x << x + assert_raises(Psych::BadAlias) do + Psych.safe_load Psych.dump(x) + end + end + + def test_explicit_recursion + x = [] + x << x + assert_equal(x, Psych.safe_load(Psych.dump(x), [], [], true)) + end + + def test_symbol_whitelist + yml = Psych.dump :foo + assert_raises(Psych::DisallowedClass) do + Psych.safe_load yml + end + assert_equal(:foo, Psych.safe_load(yml, [Symbol], [:foo])) + end + + def test_symbol + assert_raises(Psych::DisallowedClass) do + assert_safe_cycle :foo + end + assert_raises(Psych::DisallowedClass) do + Psych.safe_load '--- !ruby/symbol foo', [] + end + assert_safe_cycle :foo, [Symbol] + assert_safe_cycle :foo, %w{ Symbol } + assert_equal :foo, Psych.safe_load('--- !ruby/symbol foo', [Symbol]) + end + + def test_foo + assert_raises(Psych::DisallowedClass) do + Psych.safe_load '--- !ruby/object:Foo {}', [Foo] + end + assert_raises(Psych::DisallowedClass) do + assert_safe_cycle Foo.new + end + assert_kind_of(Foo, Psych.safe_load(Psych.dump(Foo.new), [Foo])) + end + + X = Struct.new(:x) + def test_struct_depends_on_sym + assert_safe_cycle(X.new, [X, Symbol]) + assert_raises(Psych::DisallowedClass) do + cycle X.new, [X] + end + end + + def test_anon_struct + assert Psych.safe_load(<<-eoyml, [Struct, Symbol]) +--- !ruby/struct + foo: bar + eoyml + + assert_raises(Psych::DisallowedClass) do + Psych.safe_load(<<-eoyml, [Struct]) +--- !ruby/struct + foo: bar + eoyml + end + + assert_raises(Psych::DisallowedClass) do + Psych.safe_load(<<-eoyml, [Symbol]) +--- !ruby/struct + foo: bar + eoyml + end + end + + private + + def cycle object, whitelist = [] + Psych.safe_load(Psych.dump(object), whitelist) + end + + def assert_safe_cycle object, whitelist = [] + other = cycle object, whitelist + assert_equal object, other + end + end +end diff --git a/jni/ruby/test/psych/test_scalar.rb b/jni/ruby/test/psych/test_scalar.rb new file mode 100644 index 0000000..e6b7697 --- /dev/null +++ b/jni/ruby/test/psych/test_scalar.rb @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- + +require_relative 'helper' + +module Psych + class TestScalar < TestCase + def test_utf_8 + assert_equal "日本語", Psych.load("--- 日本語") + end + end +end diff --git a/jni/ruby/test/psych/test_scalar_scanner.rb b/jni/ruby/test/psych/test_scalar_scanner.rb new file mode 100644 index 0000000..e8e423c --- /dev/null +++ b/jni/ruby/test/psych/test_scalar_scanner.rb @@ -0,0 +1,106 @@ +require_relative 'helper' +require 'date' + +module Psych + class TestScalarScanner < TestCase + attr_reader :ss + + def setup + super + @ss = Psych::ScalarScanner.new ClassLoader.new + end + + def test_scan_time + { '2001-12-15T02:59:43.1Z' => Time.utc(2001, 12, 15, 02, 59, 43, 100000), + '2001-12-14t21:59:43.10-05:00' => Time.utc(2001, 12, 15, 02, 59, 43, 100000), + '2001-12-14 21:59:43.10 -5' => Time.utc(2001, 12, 15, 02, 59, 43, 100000), + '2001-12-15 2:59:43.10' => Time.utc(2001, 12, 15, 02, 59, 43, 100000), + '2011-02-24 11:17:06 -0800' => Time.utc(2011, 02, 24, 19, 17, 06) + }.each do |time_str, time| + assert_equal time, @ss.tokenize(time_str) + end + end + + def test_scan_bad_time + [ '2001-12-15T02:59:73.1Z', + '2001-12-14t90:59:43.10-05:00', + '2001-92-14 21:59:43.10 -5', + '2001-12-15 92:59:43.10', + '2011-02-24 81:17:06 -0800', + ].each do |time_str| + assert_equal time_str, @ss.tokenize(time_str) + end + end + + def test_scan_bad_dates + x = '2000-15-01' + assert_equal x, @ss.tokenize(x) + + x = '2000-10-51' + assert_equal x, @ss.tokenize(x) + + x = '2000-10-32' + assert_equal x, @ss.tokenize(x) + end + + def test_scan_good_edge_date + x = '2000-1-31' + assert_equal Date.strptime(x, '%Y-%m-%d'), @ss.tokenize(x) + end + + def test_scan_bad_edge_date + x = '2000-11-31' + assert_equal x, @ss.tokenize(x) + end + + def test_scan_date + date = '1980-12-16' + token = @ss.tokenize date + assert_equal 1980, token.year + assert_equal 12, token.month + assert_equal 16, token.day + end + + def test_scan_inf + assert_equal(1 / 0.0, ss.tokenize('.inf')) + end + + def test_scan_minus_inf + assert_equal(-1 / 0.0, ss.tokenize('-.inf')) + end + + def test_scan_nan + assert ss.tokenize('.nan').nan? + end + + def test_scan_null + assert_equal nil, ss.tokenize('null') + assert_equal nil, ss.tokenize('~') + assert_equal nil, ss.tokenize('') + end + + def test_scan_symbol + assert_equal :foo, ss.tokenize(':foo') + end + + def test_scan_sexagesimal_float + assert_equal 685230.15, ss.tokenize('190:20:30.15') + end + + def test_scan_sexagesimal_int + assert_equal 685230, ss.tokenize('190:20:30') + end + + def test_scan_float + assert_equal 1.2, ss.tokenize('1.2') + end + + def test_scan_true + assert_equal true, ss.tokenize('true') + end + + def test_scan_strings_starting_with_underscores + assert_equal "_100", ss.tokenize('_100') + end + end +end diff --git a/jni/ruby/test/psych/test_serialize_subclasses.rb b/jni/ruby/test/psych/test_serialize_subclasses.rb new file mode 100644 index 0000000..f597b7a --- /dev/null +++ b/jni/ruby/test/psych/test_serialize_subclasses.rb @@ -0,0 +1,38 @@ +require_relative 'helper' + +module Psych + class TestSerializeSubclasses < TestCase + class SomeObject + def initialize one, two + @one = one + @two = two + end + + def == other + @one == other.instance_eval { @one } && + @two == other.instance_eval { @two } + end + end + + def test_some_object + so = SomeObject.new('foo', [1,2,3]) + assert_equal so, Psych.load(Psych.dump(so)) + end + + class StructSubclass < Struct.new(:foo) + def initialize foo, bar + super(foo) + @bar = bar + end + + def == other + super(other) && @bar == other.instance_eval{ @bar } + end + end + + def test_struct_subclass + so = StructSubclass.new('foo', [1,2,3]) + assert_equal so, Psych.load(Psych.dump(so)) + end + end +end diff --git a/jni/ruby/test/psych/test_set.rb b/jni/ruby/test/psych/test_set.rb new file mode 100644 index 0000000..921fe22 --- /dev/null +++ b/jni/ruby/test/psych/test_set.rb @@ -0,0 +1,49 @@ +require_relative 'helper' + +module Psych + class TestSet < TestCase + def setup + super + @set = Psych::Set.new + @set['foo'] = 'bar' + @set['bar'] = 'baz' + end + + def test_dump + assert_match(/!set/, Psych.dump(@set)) + end + + def test_roundtrip + assert_cycle(@set) + end + + ### + # FIXME: Syck should also support !!set as shorthand + def test_load_from_yaml + loaded = Psych.load(<<-eoyml) +--- !set +foo: bar +bar: baz + eoyml + assert_equal(@set, loaded) + end + + def test_loaded_class + assert_instance_of(Psych::Set, Psych.load(Psych.dump(@set))) + end + + def test_set_shorthand + loaded = Psych.load(<<-eoyml) +--- !!set +foo: bar +bar: baz + eoyml + assert_instance_of(Psych::Set, loaded) + end + + def test_set_self_reference + @set['self'] = @set + assert_cycle(@set) + end + end +end diff --git a/jni/ruby/test/psych/test_stream.rb b/jni/ruby/test/psych/test_stream.rb new file mode 100644 index 0000000..7e41178 --- /dev/null +++ b/jni/ruby/test/psych/test_stream.rb @@ -0,0 +1,93 @@ +require_relative 'helper' + +module Psych + class TestStream < TestCase + def test_parse_partial + rb = Psych.parse("--- foo\n...\n--- `").to_ruby + assert_equal 'foo', rb + end + + def test_load_partial + rb = Psych.load("--- foo\n...\n--- `") + assert_equal 'foo', rb + end + + def test_parse_stream_yields_documents + list = [] + Psych.parse_stream("--- foo\n...\n--- bar") do |doc| + list << doc.to_ruby + end + assert_equal %w{ foo bar }, list + end + + def test_parse_stream_break + list = [] + Psych.parse_stream("--- foo\n...\n--- `") do |doc| + list << doc.to_ruby + break + end + assert_equal %w{ foo }, list + end + + def test_load_stream_yields_documents + list = [] + Psych.load_stream("--- foo\n...\n--- bar") do |ruby| + list << ruby + end + assert_equal %w{ foo bar }, list + end + + def test_load_stream_break + list = [] + Psych.load_stream("--- foo\n...\n--- `") do |ruby| + list << ruby + break + end + assert_equal %w{ foo }, list + end + + def test_explicit_documents + io = StringIO.new + stream = Psych::Stream.new(io) + stream.start + stream.push({ 'foo' => 'bar' }) + + assert !stream.finished?, 'stream not finished' + stream.finish + assert stream.finished?, 'stream finished' + + assert_match(/^---/, io.string) + assert_match(/\.\.\.$/, io.string) + end + + def test_start_takes_block + io = StringIO.new + stream = Psych::Stream.new(io) + stream.start do |emitter| + emitter.push({ 'foo' => 'bar' }) + end + + assert stream.finished?, 'stream finished' + assert_match(/^---/, io.string) + assert_match(/\.\.\.$/, io.string) + end + + def test_no_backreferences + io = StringIO.new + stream = Psych::Stream.new(io) + stream.start do |emitter| + x = { 'foo' => 'bar' } + emitter.push x + emitter.push x + end + + assert stream.finished?, 'stream finished' + assert_match(/^---/, io.string) + assert_match(/\.\.\.$/, io.string) + assert_equal 2, io.string.scan('---').length + assert_equal 2, io.string.scan('...').length + assert_equal 2, io.string.scan('foo').length + assert_equal 2, io.string.scan('bar').length + end + end +end diff --git a/jni/ruby/test/psych/test_string.rb b/jni/ruby/test/psych/test_string.rb new file mode 100644 index 0000000..1ce16fd --- /dev/null +++ b/jni/ruby/test/psych/test_string.rb @@ -0,0 +1,166 @@ +require_relative 'helper' + +module Psych + class TestString < TestCase + class X < String + end + + class Y < String + attr_accessor :val + end + + class Z < String + def initialize + force_encoding Encoding::US_ASCII + end + end + + def test_string_with_newline + assert_equal "1\n2", Psych.load("--- ! '1\n\n 2'\n") + end + + def test_no_doublequotes_with_special_characters + assert_equal 2, Psych.dump(%Q{<%= ENV["PATH"] %>}).count('"') + end + + def test_doublequotes_when_there_is_a_single + yaml = Psych.dump "@123'abc" + assert_match(/---\s*"/, yaml) + end + + def test_cycle_x + str = X.new 'abc' + assert_cycle str + end + + def test_dash_dot + assert_cycle '-.' + assert_cycle '+.' + end + + def test_string_subclass_with_anchor + y = Psych.load <<-eoyml +--- +body: + string: &70121654388580 !ruby/string + str: ! 'foo' + x: + body: *70121654388580 + eoyml + assert_equal({"body"=>{"string"=>"foo", "x"=>{"body"=>"foo"}}}, y) + end + + def test_self_referential_string + y = Psych.load <<-eoyml +--- +string: &70121654388580 !ruby/string + str: ! 'foo' + body: *70121654388580 + eoyml + + assert_equal({"string"=>"foo"}, y) + value = y['string'] + assert_equal value, value.instance_variable_get(:@body) + end + + def test_another_subclass_with_attributes + y = Psych.load Psych.dump Y.new("foo").tap {|y| y.val = 1} + assert_equal "foo", y + assert_equal Y, y.class + assert_equal 1, y.val + end + + def test_backwards_with_syck + x = Psych.load "--- !str:#{X.name} foo\n\n" + assert_equal X, x.class + assert_equal 'foo', x + end + + def test_empty_subclass + assert_match "!ruby/string:#{X}", Psych.dump(X.new) + x = Psych.load Psych.dump X.new + assert_equal X, x.class + end + + def test_empty_character_subclass + assert_match "!ruby/string:#{Z}", Psych.dump(Z.new) + x = Psych.load Psych.dump Z.new + assert_equal Z, x.class + end + + def test_subclass_with_attributes + y = Psych.load Psych.dump Y.new.tap {|y| y.val = 1} + assert_equal Y, y.class + assert_equal 1, y.val + end + + def test_string_with_base_60 + yaml = Psych.dump '01:03:05' + assert_match "'01:03:05'", yaml + assert_equal '01:03:05', Psych.load(yaml) + end + + def test_nonascii_string_as_binary + string = "hello \x80 world!" + string.force_encoding 'ascii-8bit' + yml = Psych.dump string + assert_match(/binary/, yml) + assert_equal string, Psych.load(yml) + end + + def test_binary_string_null + string = "\x00" + yml = Psych.dump string + assert_match(/binary/, yml) + assert_equal string, Psych.load(yml) + end + + def test_binary_string + string = binary_string + yml = Psych.dump string + assert_match(/binary/, yml) + assert_equal string, Psych.load(yml) + end + + def test_non_binary_string + string = binary_string(0.29) + yml = Psych.dump string + refute_match(/binary/, yml) + assert_equal string, Psych.load(yml) + end + + def test_ascii_only_8bit_string + string = "abc".encode(Encoding::ASCII_8BIT) + yml = Psych.dump string + refute_match(/binary/, yml) + assert_equal string, Psych.load(yml) + end + + def test_string_with_ivars + food = "is delicious" + ivar = "on rock and roll" + food.instance_variable_set(:@we_built_this_city, ivar) + + Psych.load Psych.dump food + assert_equal ivar, food.instance_variable_get(:@we_built_this_city) + end + + def test_binary + string = [0, 123,22, 44, 9, 32, 34, 39].pack('C*') + assert_cycle string + end + + def test_float_confusion + assert_cycle '1.' + end + + def binary_string percentage = 0.31, length = 100 + string = '' + (percentage * length).to_i.times do |i| + string << "\b" + end + string << 'a' * (length - string.length) + string + end + end +end diff --git a/jni/ruby/test/psych/test_struct.rb b/jni/ruby/test/psych/test_struct.rb new file mode 100644 index 0000000..8c7f251 --- /dev/null +++ b/jni/ruby/test/psych/test_struct.rb @@ -0,0 +1,49 @@ +require_relative 'helper' + +class PsychStructWithIvar < Struct.new(:foo) + attr_reader :bar + def initialize *args + super + @bar = 'hello' + end +end + +module Psych + class TestStruct < TestCase + class StructSubclass < Struct.new(:foo) + def initialize foo, bar + super(foo) + @bar = bar + end + end + + def test_self_referential_struct + ss = StructSubclass.new(nil, 'foo') + ss.foo = ss + + loaded = Psych.load(Psych.dump(ss)) + assert_instance_of(StructSubclass, loaded.foo) + + assert_equal(ss, loaded) + end + + def test_roundtrip + thing = PsychStructWithIvar.new('bar') + struct = Psych.load(Psych.dump(thing)) + + assert_equal 'hello', struct.bar + assert_equal 'bar', struct.foo + end + + def test_load + obj = Psych.load(<<-eoyml) +--- !ruby/struct:PsychStructWithIvar +:foo: bar +:@bar: hello + eoyml + + assert_equal 'hello', obj.bar + assert_equal 'bar', obj.foo + end + end +end diff --git a/jni/ruby/test/psych/test_symbol.rb b/jni/ruby/test/psych/test_symbol.rb new file mode 100644 index 0000000..558a672 --- /dev/null +++ b/jni/ruby/test/psych/test_symbol.rb @@ -0,0 +1,25 @@ +require_relative 'helper' + +module Psych + class TestSymbol < TestCase + def test_cycle_empty + assert_cycle :'' + end + + def test_cycle_colon + assert_cycle :':' + end + + def test_cycle + assert_cycle :a + end + + def test_stringy + assert_cycle :"1" + end + + def test_load_quoted + assert_equal :"1", Psych.load("--- :'1'\n") + end + end +end diff --git a/jni/ruby/test/psych/test_tainted.rb b/jni/ruby/test/psych/test_tainted.rb new file mode 100644 index 0000000..37fc5b2 --- /dev/null +++ b/jni/ruby/test/psych/test_tainted.rb @@ -0,0 +1,130 @@ +require_relative 'helper' + +module Psych + class TestStringTainted < TestCase + class Tainted < Handler + attr_reader :tc + + def initialize tc + @tc = tc + end + + def start_document version, tags, implicit + tags.flatten.each do |tag| + assert_taintedness tag + end + end + + def alias name + assert_taintedness name + end + + def scalar value, anchor, tag, plain, quoted, style + assert_taintedness value + assert_taintedness tag if tag + assert_taintedness anchor if anchor + end + + def start_sequence anchor, tag, implicit, style + assert_taintedness tag if tag + assert_taintedness anchor if anchor + end + + def start_mapping anchor, tag, implicit, style + assert_taintedness tag if tag + assert_taintedness anchor if anchor + end + + def assert_taintedness thing, message = "'#{thing}' should be tainted" + tc.assert thing.tainted?, message + end + end + + class Untainted < Tainted + def assert_taintedness thing, message = "'#{thing}' should not be tainted" + tc.assert !thing.tainted?, message + end + end + + + def setup + handler = Tainted.new self + @parser = Psych::Parser.new handler + end + + def test_tags_are_tainted + assert_taintedness "%TAG !yaml! tag:yaml.org,2002:\n---\n!yaml!str \"foo\"" + end + + def test_alias + assert_taintedness "--- &ponies\n- foo\n- *ponies" + end + + def test_scalar + assert_taintedness "--- ponies" + end + + def test_anchor + assert_taintedness "--- &hi ponies" + end + + def test_scalar_tag + assert_taintedness "--- !str ponies" + end + + def test_seq_start_tag + assert_taintedness "--- !!seq [ a ]" + end + + def test_seq_start_anchor + assert_taintedness "--- &zomg [ a ]" + end + + def test_seq_mapping_tag + assert_taintedness "--- !!map { a: b }" + end + + def test_seq_mapping_anchor + assert_taintedness "--- &himom { a: b }" + end + + def assert_taintedness string + @parser.parse string.taint + end + end + + class TestStringUntainted < TestStringTainted + def setup + handler = Untainted.new self + @parser = Psych::Parser.new handler + end + + def assert_taintedness string + @parser.parse string + end + end + + class TestStringIOUntainted < TestStringTainted + def setup + handler = Untainted.new self + @parser = Psych::Parser.new handler + end + + def assert_taintedness string + @parser.parse StringIO.new(string) + end + end + + class TestIOTainted < TestStringTainted + def assert_taintedness string + Tempfile.create(['something', 'yml']) {|t| + t.binmode + t.write string + t.close + File.open(t.path, 'r:bom|utf-8') { |f| + @parser.parse f + } + } + end + end +end diff --git a/jni/ruby/test/psych/test_to_yaml_properties.rb b/jni/ruby/test/psych/test_to_yaml_properties.rb new file mode 100644 index 0000000..5b4860c --- /dev/null +++ b/jni/ruby/test/psych/test_to_yaml_properties.rb @@ -0,0 +1,63 @@ +require_relative 'helper' + +module Psych + class TestToYamlProperties < MiniTest::Unit::TestCase + class Foo + attr_accessor :a, :b, :c + def initialize + @a = 1 + @b = 2 + @c = 3 + end + + def to_yaml_properties + [:@a, :@b] + end + end + + def test_object_dump_yaml_properties + foo = Psych.load(Psych.dump(Foo.new)) + assert_equal 1, foo.a + assert_equal 2, foo.b + assert_nil foo.c + end + + class Bar < Struct.new(:foo, :bar) + attr_reader :baz + def initialize *args + super + @baz = 'hello' + end + + def to_yaml_properties + [] + end + end + + def test_struct_dump_yaml_properties + bar = Psych.load(Psych.dump(Bar.new('a', 'b'))) + assert_equal 'a', bar.foo + assert_equal 'b', bar.bar + assert_nil bar.baz + end + + def test_string_dump + string = "okonomiyaki" + class << string + def to_yaml_properties + [:@tastes] + end + end + + string.instance_variable_set(:@tastes, 'delicious') + v = Psych.load Psych.dump string + assert_equal 'delicious', v.instance_variable_get(:@tastes) + end + + def test_string_load_syck + str = Psych.load("--- !str \nstr: okonomiyaki\n:@tastes: delicious\n") + assert_equal 'okonomiyaki', str + assert_equal 'delicious', str.instance_variable_get(:@tastes) + end + end +end diff --git a/jni/ruby/test/psych/test_tree_builder.rb b/jni/ruby/test/psych/test_tree_builder.rb new file mode 100644 index 0000000..7ad3ddd --- /dev/null +++ b/jni/ruby/test/psych/test_tree_builder.rb @@ -0,0 +1,79 @@ +require_relative 'helper' + +module Psych + class TestTreeBuilder < TestCase + def setup + super + @parser = Psych::Parser.new TreeBuilder.new + @parser.parse(<<-eoyml) +%YAML 1.1 +--- +- foo +- { + bar : &A !!str baz, + boo : *A +} +- *A + eoyml + @tree = @parser.handler.root + end + + def test_stream + assert_instance_of Nodes::Stream, @tree + end + + def test_documents + assert_equal 1, @tree.children.length + assert_instance_of Nodes::Document, @tree.children.first + doc = @tree.children.first + + assert_equal [1,1], doc.version + assert_equal [], doc.tag_directives + assert_equal false, doc.implicit + end + + def test_sequence + doc = @tree.children.first + assert_equal 1, doc.children.length + + seq = doc.children.first + assert_instance_of Nodes::Sequence, seq + assert_nil seq.anchor + assert_nil seq.tag + assert_equal true, seq.implicit + assert_equal Nodes::Sequence::BLOCK, seq.style + end + + def test_scalar + doc = @tree.children.first + seq = doc.children.first + + assert_equal 3, seq.children.length + scalar = seq.children.first + assert_instance_of Nodes::Scalar, scalar + assert_equal 'foo', scalar.value + assert_nil scalar.anchor + assert_nil scalar.tag + assert_equal true, scalar.plain + assert_equal false, scalar.quoted + assert_equal Nodes::Scalar::PLAIN, scalar.style + end + + def test_mapping + doc = @tree.children.first + seq = doc.children.first + map = seq.children[1] + + assert_instance_of Nodes::Mapping, map + end + + def test_alias + doc = @tree.children.first + seq = doc.children.first + assert_equal 3, seq.children.length + al = seq.children[2] + assert_instance_of Nodes::Alias, al + assert_equal 'A', al.anchor + end + end +end diff --git a/jni/ruby/test/psych/test_yaml.rb b/jni/ruby/test/psych/test_yaml.rb new file mode 100644 index 0000000..cd3e8ee --- /dev/null +++ b/jni/ruby/test/psych/test_yaml.rb @@ -0,0 +1,1288 @@ +# -*- coding: us-ascii; mode: ruby; ruby-indent-level: 4; tab-width: 4 -*- +# vim:sw=4:ts=4 +# $Id$ +# +require_relative 'helper' +require 'ostruct' + +# [ruby-core:01946] +module Psych_Tests + StructTest = Struct::new( :c ) +end + +class Psych_Unit_Tests < Psych::TestCase + def teardown + Psych.domain_types.clear + end + + def test_y_method + assert_raises(NoMethodError) do + OpenStruct.new.y 1 + end + end + + def test_syck_compat + time = Time.utc(2010, 10, 10) + yaml = Psych.dump time + assert_match "2010-10-10 00:00:00.000000000 Z", yaml + end + + # [ruby-core:34969] + def test_regexp_with_n + assert_cycle(Regexp.new('',0,'n')) + end + # + # Tests modified from 00basic.t in Psych.pm + # + def test_basic_map + # Simple map + assert_parse_only( + { 'one' => 'foo', 'three' => 'baz', 'two' => 'bar' }, <<EOY +one: foo +two: bar +three: baz +EOY + ) + end + + def test_basic_strings + # Common string types + assert_cycle("x") + assert_cycle(":x") + assert_cycle(":") + assert_parse_only( + { 1 => 'simple string', 2 => 42, 3 => '1 Single Quoted String', + 4 => 'Psych\'s Double "Quoted" String', 5 => "A block\n with several\n lines.\n", + 6 => "A \"chomped\" block", 7 => "A folded\n string\n", 8 => ": started string" }, + <<EOY +1: simple string +2: 42 +3: '1 Single Quoted String' +4: "Psych's Double \\\"Quoted\\\" String" +5: | + A block + with several + lines. +6: |- + A "chomped" block +7: > + A + folded + string +8: ": started string" +EOY + ) + end + + # + # Test the specification examples + # - Many examples have been changes because of whitespace problems that + # caused the two to be inequivalent, or keys to be sorted wrong + # + + def test_spec_simple_implicit_sequence + # Simple implicit sequence + assert_to_yaml( + [ 'Mark McGwire', 'Sammy Sosa', 'Ken Griffey' ], <<EOY +- Mark McGwire +- Sammy Sosa +- Ken Griffey +EOY + ) + end + + def test_spec_simple_implicit_map + # Simple implicit map + assert_to_yaml( + { 'hr' => 65, 'avg' => 0.278, 'rbi' => 147 }, <<EOY +avg: 0.278 +hr: 65 +rbi: 147 +EOY + ) + end + + def test_spec_simple_map_with_nested_sequences + # Simple mapping with nested sequences + assert_to_yaml( + { 'american' => + [ 'Boston Red Sox', 'Detroit Tigers', 'New York Yankees' ], + 'national' => + [ 'New York Mets', 'Chicago Cubs', 'Atlanta Braves' ] }, <<EOY +american: + - Boston Red Sox + - Detroit Tigers + - New York Yankees +national: + - New York Mets + - Chicago Cubs + - Atlanta Braves +EOY + ) + end + + def test_spec_simple_sequence_with_nested_map + # Simple sequence with nested map + assert_to_yaml( + [ + {'name' => 'Mark McGwire', 'hr' => 65, 'avg' => 0.278}, + {'name' => 'Sammy Sosa', 'hr' => 63, 'avg' => 0.288} + ], <<EOY +- + avg: 0.278 + hr: 65 + name: Mark McGwire +- + avg: 0.288 + hr: 63 + name: Sammy Sosa +EOY + ) + end + + def test_spec_sequence_of_sequences + # Simple sequence with inline sequences + assert_parse_only( + [ + [ 'name', 'hr', 'avg' ], + [ 'Mark McGwire', 65, 0.278 ], + [ 'Sammy Sosa', 63, 0.288 ] + ], <<EOY +- [ name , hr , avg ] +- [ Mark McGwire , 65 , 0.278 ] +- [ Sammy Sosa , 63 , 0.288 ] +EOY + ) + end + + def test_spec_mapping_of_mappings + # Simple map with inline maps + assert_parse_only( + { 'Mark McGwire' => + { 'hr' => 65, 'avg' => 0.278 }, + 'Sammy Sosa' => + { 'hr' => 63, 'avg' => 0.288 } + }, <<EOY +Mark McGwire: {hr: 65, avg: 0.278} +Sammy Sosa: {hr: 63, + avg: 0.288} +EOY + ) + end + + def test_ambiguous_comments + # [ruby-talk:88012] + assert_to_yaml( "Call the method #dave", <<EOY ) +--- "Call the method #dave" +EOY + end + + def test_spec_nested_comments + # Map and sequences with comments + assert_parse_only( + { 'hr' => [ 'Mark McGwire', 'Sammy Sosa' ], + 'rbi' => [ 'Sammy Sosa', 'Ken Griffey' ] }, <<EOY +hr: # 1998 hr ranking + - Mark McGwire + - Sammy Sosa +rbi: + # 1998 rbi ranking + - Sammy Sosa + - Ken Griffey +EOY + ) + end + + def test_spec_anchors_and_aliases + # Anchors and aliases + assert_parse_only( + { 'hr' => + [ 'Mark McGwire', 'Sammy Sosa' ], + 'rbi' => + [ 'Sammy Sosa', 'Ken Griffey' ] }, <<EOY +hr: + - Mark McGwire + # Name "Sammy Sosa" scalar SS + - &SS Sammy Sosa +rbi: + # So it can be referenced later. + - *SS + - Ken Griffey +EOY + ) + + assert_to_yaml( + [{"arrival"=>"EDI", "departure"=>"LAX", "fareref"=>"DOGMA", "currency"=>"GBP"}, {"arrival"=>"MEL", "departure"=>"SYD", "fareref"=>"MADF", "currency"=>"AUD"}, {"arrival"=>"MCO", "departure"=>"JFK", "fareref"=>"DFSF", "currency"=>"USD"}], <<EOY + - + &F fareref: DOGMA + &C currency: GBP + &D departure: LAX + &A arrival: EDI + - { *F: MADF, *C: AUD, *D: SYD, *A: MEL } + - { *F: DFSF, *C: USD, *D: JFK, *A: MCO } +EOY + ) + + assert_to_yaml( + {"ALIASES"=>["fareref", "currency", "departure", "arrival"], "FARES"=>[{"arrival"=>"EDI", "departure"=>"LAX", "fareref"=>"DOGMA", "currency"=>"GBP"}, {"arrival"=>"MEL", "departure"=>"SYD", "fareref"=>"MADF", "currency"=>"AUD"}, {"arrival"=>"MCO", "departure"=>"JFK", "fareref"=>"DFSF", "currency"=>"USD"}]}, <<EOY +--- +ALIASES: [&f fareref, &c currency, &d departure, &a arrival] +FARES: +- *f: DOGMA + *c: GBP + *d: LAX + *a: EDI + +- *f: MADF + *c: AUD + *d: SYD + *a: MEL + +- *f: DFSF + *c: USD + *d: JFK + *a: MCO + +EOY + ) + + end + + def test_spec_mapping_between_sequences + # Complex key #1 + assert_parse_only( + { [ 'Detroit Tigers', 'Chicago Cubs' ] => [ Date.new( 2001, 7, 23 ) ], + [ 'New York Yankees', 'Atlanta Braves' ] => [ Date.new( 2001, 7, 2 ), Date.new( 2001, 8, 12 ), Date.new( 2001, 8, 14 ) ] }, <<EOY +? # PLAY SCHEDULE + - Detroit Tigers + - Chicago Cubs +: + - 2001-07-23 + +? [ New York Yankees, + Atlanta Braves ] +: [ 2001-07-02, 2001-08-12, + 2001-08-14 ] +EOY + ) + + # Complex key #2 + assert_parse_only( + { [ 'New York Yankees', 'Atlanta Braves' ] => + [ Date.new( 2001, 7, 2 ), Date.new( 2001, 8, 12 ), + Date.new( 2001, 8, 14 ) ], + [ 'Detroit Tigers', 'Chicago Cubs' ] => + [ Date.new( 2001, 7, 23 ) ] + }, <<EOY +? + - New York Yankees + - Atlanta Braves +: + - 2001-07-02 + - 2001-08-12 + - 2001-08-14 +? + - Detroit Tigers + - Chicago Cubs +: + - 2001-07-23 +EOY + ) + end + + def test_spec_sequence_key_shortcut + # Shortcut sequence map + assert_parse_only( + { 'invoice' => 34843, 'date' => Date.new( 2001, 1, 23 ), + 'bill-to' => 'Chris Dumars', 'product' => + [ { 'item' => 'Super Hoop', 'quantity' => 1 }, + { 'item' => 'Basketball', 'quantity' => 4 }, + { 'item' => 'Big Shoes', 'quantity' => 1 } ] }, <<EOY +invoice: 34843 +date : 2001-01-23 +bill-to: Chris Dumars +product: + - item : Super Hoop + quantity: 1 + - item : Basketball + quantity: 4 + - item : Big Shoes + quantity: 1 +EOY + ) + end + + def test_spec_sequence_in_sequence_shortcut + # Seq-in-seq + assert_parse_only( [ [ [ 'one', 'two', 'three' ] ] ], <<EOY ) +- - - one + - two + - three +EOY + end + + def test_spec_sequence_shortcuts + # Sequence shortcuts combined + assert_parse_only( +[ + [ + [ [ 'one' ] ], + [ 'two', 'three' ], + { 'four' => nil }, + [ { 'five' => [ 'six' ] } ], + [ 'seven' ] + ], + [ 'eight', 'nine' ] +], <<EOY ) +- - - - one + - - two + - three + - four: + - - five: + - six + - - seven +- - eight + - nine +EOY + end + + def test_spec_single_literal + # Literal scalar block + assert_parse_only( [ "\\/|\\/|\n/ | |_\n" ], <<EOY ) +- | + \\/|\\/| + / | |_ +EOY + end + + def test_spec_single_folded + # Folded scalar block + assert_parse_only( + [ "Mark McGwire's year was crippled by a knee injury.\n" ], <<EOY +- > + Mark McGwire\'s + year was crippled + by a knee injury. +EOY + ) + end + + def test_spec_preserve_indent + # Preserve indented spaces + assert_parse_only( + "Sammy Sosa completed another fine season with great stats.\n\n 63 Home Runs\n 0.288 Batting Average\n\nWhat a year!\n", <<EOY +--- > + Sammy Sosa completed another + fine season with great stats. + + 63 Home Runs + 0.288 Batting Average + + What a year! +EOY + ) + end + + def test_spec_indentation_determines_scope + assert_parse_only( + { 'name' => 'Mark McGwire', 'accomplishment' => "Mark set a major league home run record in 1998.\n", + 'stats' => "65 Home Runs\n0.278 Batting Average\n" }, <<EOY +name: Mark McGwire +accomplishment: > + Mark set a major league + home run record in 1998. +stats: | + 65 Home Runs + 0.278 Batting Average +EOY + ) + end + + def test_spec_multiline_scalars + # Multiline flow scalars + assert_parse_only( + { 'plain' => 'This unquoted scalar spans many lines.', + 'quoted' => "So does this quoted scalar.\n" }, <<EOY +plain: This unquoted + scalar spans + many lines. +quoted: "\\ + So does this quoted + scalar.\\n" +EOY + ) + end + + def test_spec_type_int + assert_parse_only( + { 'canonical' => 12345, 'decimal' => 12345, 'octal' => '014'.oct, 'hexadecimal' => '0xC'.hex }, <<EOY +canonical: 12345 +decimal: +12,345 +octal: 014 +hexadecimal: 0xC +EOY + ) + assert_parse_only( + { 'canonical' => 685230, 'decimal' => 685230, 'octal' => 02472256, 'hexadecimal' => 0x0A74AE, 'sexagesimal' => 685230 }, <<EOY) +canonical: 685230 +decimal: +685,230 +octal: 02472256 +hexadecimal: 0x0A,74,AE +sexagesimal: 190:20:30 +EOY + end + + def test_spec_type_float + assert_parse_only( + { 'canonical' => 1230.15, 'exponential' => 1230.15, 'fixed' => 1230.15, + 'negative infinity' => -1.0/0.0 }, <<EOY) +canonical: 1.23015e+3 +exponential: 12.3015e+02 +fixed: 1,230.15 +negative infinity: -.inf +EOY + nan = Psych::load( <<EOY ) +not a number: .NaN +EOY + assert( nan['not a number'].nan? ) + end + + def test_spec_type_misc + assert_parse_only( + { nil => nil, true => true, false => false, 'string' => '12345' }, <<EOY +null: ~ +true: yes +false: no +string: '12345' +EOY + ) + end + + def test_spec_complex_invoice + # Complex invoice type + id001 = { 'given' => 'Chris', 'family' => 'Dumars', 'address' => + { 'lines' => "458 Walkman Dr.\nSuite #292\n", 'city' => 'Royal Oak', + 'state' => 'MI', 'postal' => 48046 } } + assert_parse_only( + { 'invoice' => 34843, 'date' => Date.new( 2001, 1, 23 ), + 'bill-to' => id001, 'ship-to' => id001, 'product' => + [ { 'sku' => 'BL394D', 'quantity' => 4, + 'description' => 'Basketball', 'price' => 450.00 }, + { 'sku' => 'BL4438H', 'quantity' => 1, + 'description' => 'Super Hoop', 'price' => 2392.00 } ], + 'tax' => 251.42, 'total' => 4443.52, + 'comments' => "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.\n" }, <<EOY +invoice: 34843 +date : 2001-01-23 +bill-to: &id001 + given : Chris + family : !str Dumars + address: + lines: | + 458 Walkman Dr. + Suite #292 + city : Royal Oak + state : MI + postal : 48046 +ship-to: *id001 +product: + - !map + sku : BL394D + quantity : 4 + description : Basketball + price : 450.00 + - sku : BL4438H + quantity : 1 + description : Super Hoop + price : 2392.00 +tax : 251.42 +total: 4443.52 +comments: > + Late afternoon is best. + Backup contact is Nancy + Billsmer @ 338-4338. +EOY + ) + end + + def test_spec_log_file + doc_ct = 0 + Psych::load_documents( <<EOY +--- +Time: 2001-11-23 15:01:42 -05:00 +User: ed +Warning: > + This is an error message + for the log file +--- +Time: 2001-11-23 15:02:31 -05:00 +User: ed +Warning: > + A slightly different error + message. +--- +Date: 2001-11-23 15:03:17 -05:00 +User: ed +Fatal: > + Unknown variable "bar" +Stack: + - file: TopClass.py + line: 23 + code: | + x = MoreObject("345\\n") + - file: MoreClass.py + line: 58 + code: |- + foo = bar +EOY + ) { |doc| + case doc_ct + when 0 + assert_equal( doc, { 'Time' => mktime( 2001, 11, 23, 15, 01, 42, 00, "-05:00" ), + 'User' => 'ed', 'Warning' => "This is an error message for the log file\n" } ) + when 1 + assert_equal( doc, { 'Time' => mktime( 2001, 11, 23, 15, 02, 31, 00, "-05:00" ), + 'User' => 'ed', 'Warning' => "A slightly different error message.\n" } ) + when 2 + assert_equal( doc, { 'Date' => mktime( 2001, 11, 23, 15, 03, 17, 00, "-05:00" ), + 'User' => 'ed', 'Fatal' => "Unknown variable \"bar\"\n", + 'Stack' => [ + { 'file' => 'TopClass.py', 'line' => 23, 'code' => "x = MoreObject(\"345\\n\")\n" }, + { 'file' => 'MoreClass.py', 'line' => 58, 'code' => "foo = bar" } ] } ) + end + doc_ct += 1 + } + assert_equal( doc_ct, 3 ) + end + + def test_spec_root_fold + y = Psych::load( <<EOY +--- +This Psych stream contains a single text value. +The next stream is a log file - a sequence of +log entries. Adding an entry to the log is a +simple matter of appending it at the end. +EOY + ) + assert_equal( y, "This Psych stream contains a single text value. The next stream is a log file - a sequence of log entries. Adding an entry to the log is a simple matter of appending it at the end." ) + end + + def test_spec_root_mapping + y = Psych::load( <<EOY +# This stream is an example of a top-level mapping. +invoice : 34843 +date : 2001-01-23 +total : 4443.52 +EOY + ) + assert_equal( y, { 'invoice' => 34843, 'date' => Date.new( 2001, 1, 23 ), 'total' => 4443.52 } ) + end + + def test_spec_oneline_docs + doc_ct = 0 + Psych::load_documents( <<EOY +# The following is a sequence of three documents. +# The first contains an empty mapping, the second +# an empty sequence, and the last an empty string. +--- {} +--- [ ] +--- '' +EOY + ) { |doc| + case doc_ct + when 0 + assert_equal( doc, {} ) + when 1 + assert_equal( doc, [] ) + when 2 + assert_equal( doc, '' ) + end + doc_ct += 1 + } + assert_equal( doc_ct, 3 ) + end + + def test_spec_domain_prefix + customer_proc = proc { |type, val| + if Hash === val + _, _, type = type.split( ':', 3 ) + val['type'] = "domain #{type}" + val + else + raise ArgumentError, "Not a Hash in domain.tld,2002/invoice: " + val.inspect + end + } + Psych.add_domain_type( "domain.tld,2002", 'invoice', &customer_proc ) + Psych.add_domain_type( "domain.tld,2002", 'customer', &customer_proc ) + assert_parse_only( { "invoice"=> { "customers"=> [ { "given"=>"Chris", "type"=>"domain customer", "family"=>"Dumars" } ], "type"=>"domain invoice" } }, <<EOY +# 'http://domain.tld,2002/invoice' is some type family. +invoice: !domain.tld,2002/invoice + # 'seq' is shorthand for 'http://yaml.org/seq'. + # This does not effect '^customer' below + # because it is does not specify a prefix. + customers: !seq + # '^customer' is shorthand for the full + # notation 'http://domain.tld,2002/customer'. + - !customer + given : Chris + family : Dumars +EOY + ) + end + + def test_spec_throwaway + assert_parse_only( + {"this"=>"contains three lines of text.\nThe third one starts with a\n# character. This isn't a comment.\n"}, <<EOY +### These are four throwaway comment ### + +### lines (the second line is empty). ### +this: | # Comments may trail lines. + contains three lines of text. + The third one starts with a + # character. This isn't a comment. + +# These are three throwaway comment +# lines (the first line is empty). +EOY + ) + end + + def test_spec_force_implicit + # Force implicit + assert_parse_only( + { 'integer' => 12, 'also int' => 12, 'string' => '12' }, <<EOY +integer: 12 +also int: ! "12" +string: !str 12 +EOY + ) + end + + ### + # Commenting out this test. This line: + # + # - !domain.tld,2002/type\\x30 value + # + # Is invalid according to the YAML spec: + # + # http://yaml.org/spec/1.1/#id896876 + # +# def test_spec_url_escaping +# Psych.add_domain_type( "domain.tld,2002", "type0" ) { |type, val| +# "ONE: #{val}" +# } +# Psych.add_domain_type( "domain.tld,2002", "type%30" ) { |type, val| +# "TWO: #{val}" +# } +# assert_parse_only( +# { 'same' => [ 'ONE: value', 'ONE: value' ], 'different' => [ 'TWO: value' ] }, <<EOY +#same: +# - !domain.tld,2002/type\\x30 value +# - !domain.tld,2002/type0 value +#different: # As far as the Psych parser is concerned +# - !domain.tld,2002/type%30 value +#EOY +# ) +# end + + def test_spec_override_anchor + # Override anchor + a001 = "The alias node below is a repeated use of this value.\n" + assert_parse_only( + { 'anchor' => 'This scalar has an anchor.', 'override' => a001, 'alias' => a001 }, <<EOY +anchor : &A001 This scalar has an anchor. +override : &A001 > + The alias node below is a + repeated use of this value. +alias : *A001 +EOY + ) + end + + def test_spec_explicit_families + Psych.add_domain_type( "somewhere.com,2002", 'type' ) { |type, val| + "SOMEWHERE: #{val}" + } + assert_parse_only( + { 'not-date' => '2002-04-28', 'picture' => "GIF89a\f\000\f\000\204\000\000\377\377\367\365\365\356\351\351\345fff\000\000\000\347\347\347^^^\363\363\355\216\216\216\340\340\340\237\237\237\223\223\223\247\247\247\236\236\236i^\020' \202\n\001\000;", 'hmm' => "SOMEWHERE: family above is short for\nhttp://somewhere.com/type\n" }, <<EOY +not-date: !str 2002-04-28 +picture: !binary | + R0lGODlhDAAMAIQAAP//9/X + 17unp5WZmZgAAAOfn515eXv + Pz7Y6OjuDg4J+fn5OTk6enp + 56enmleECcgggoBADs= + +hmm: !somewhere.com,2002/type | + family above is short for + http://somewhere.com/type +EOY + ) + end + + def test_spec_application_family + # Testing the clarkevans.com graphs + Psych.add_domain_type( "clarkevans.com,2002", 'graph/shape' ) { |type, val| + if Array === val + val << "Shape Container" + val + else + raise ArgumentError, "Invalid graph of type #{val.class}: " + val.inspect + end + } + one_shape_proc = Proc.new { |type, val| + if Hash === val + type = type.split( /:/ ) + val['TYPE'] = "Shape: #{type[2]}" + val + else + raise ArgumentError, "Invalid graph of type #{val.class}: " + val.inspect + end + } + Psych.add_domain_type( "clarkevans.com,2002", 'graph/circle', &one_shape_proc ) + Psych.add_domain_type( "clarkevans.com,2002", 'graph/line', &one_shape_proc ) + Psych.add_domain_type( "clarkevans.com,2002", 'graph/text', &one_shape_proc ) + # MODIFIED to remove invalid Psych + assert_parse_only( + [[{"radius"=>7, "center"=>{"x"=>73, "y"=>129}, "TYPE"=>"Shape: graph/circle"}, {"finish"=>{"x"=>89, "y"=>102}, "TYPE"=>"Shape: graph/line", "start"=>{"x"=>73, "y"=>129}}, {"TYPE"=>"Shape: graph/text", "value"=>"Pretty vector drawing.", "start"=>{"x"=>73, "y"=>129}, "color"=>16772795}, "Shape Container"]], <<EOY +- !clarkevans.com,2002/graph/shape + - !/graph/circle + center: &ORIGIN {x: 73, y: 129} + radius: 7 + - !/graph/line # !clarkevans.com,2002/graph/line + start: *ORIGIN + finish: { x: 89, y: 102 } + - !/graph/text + start: *ORIGIN + color: 0xFFEEBB + value: Pretty vector drawing. +EOY + ) + end + + def test_spec_float_explicit + assert_parse_only( + [ 10.0, 10.0, 10.0, 10.0 ], <<EOY +# All entries in the sequence +# have the same type and value. +- 10.0 +- !float 10 +- !yaml.org,2002/float '10' +- !yaml.org,2002/float "\\ + 1\\ + 0" +EOY + ) + end + + def test_spec_builtin_seq + # Assortment of sequences + assert_parse_only( + { 'empty' => [], 'in-line' => [ 'one', 'two', 'three', 'four', 'five' ], + 'nested' => [ 'First item in top sequence', [ 'Subordinate sequence entry' ], + "A multi-line sequence entry\n", 'Sixth item in top sequence' ] }, <<EOY +empty: [] +in-line: [ one, two, three # May span lines, + , four, # indentation is + five ] # mostly ignored. +nested: + - First item in top sequence + - + - Subordinate sequence entry + - > + A multi-line + sequence entry + - Sixth item in top sequence +EOY + ) + end + + def test_spec_builtin_map + # Assortment of mappings + assert_parse_only( + { 'empty' => {}, 'in-line' => { 'one' => 1, 'two' => 2 }, + 'spanning' => { 'one' => 1, 'two' => 2 }, + 'nested' => { 'first' => 'First entry', 'second' => + { 'key' => 'Subordinate mapping' }, 'third' => + [ 'Subordinate sequence', {}, 'Previous mapping is empty.', + { 'A key' => 'value pair in a sequence.', 'A second' => 'key:value pair.' }, + 'The previous entry is equal to the following one.', + { 'A key' => 'value pair in a sequence.', 'A second' => 'key:value pair.' } ], + 12.0 => 'This key is a float.', "?\n" => 'This key had to be protected.', + "\a" => 'This key had to be escaped.', + "This is a multi-line folded key\n" => "Whose value is also multi-line.\n", + [ 'This key', 'is a sequence' ] => [ 'With a sequence value.' ] } }, <<EOY + +empty: {} +in-line: { one: 1, two: 2 } +spanning: { one: 1, + two: 2 } +nested: + first : First entry + second: + key: Subordinate mapping + third: + - Subordinate sequence + - { } + - Previous mapping is empty. + - A key: value pair in a sequence. + A second: key:value pair. + - The previous entry is equal to the following one. + - + A key: value pair in a sequence. + A second: key:value pair. + !float 12 : This key is a float. + ? > + ? + : This key had to be protected. + "\\a" : This key had to be escaped. + ? > + This is a + multi-line + folded key + : > + Whose value is + also multi-line. + ? + - This key + - is a sequence + : + - With a sequence value. +# The following parses correctly, +# but Ruby 1.6.* fails the comparison! +# ? +# This: key +# is a: mapping +# : +# with a: mapping value. +EOY + ) + end + + def test_spec_builtin_literal_blocks + # Assortment of literal scalar blocks + assert_parse_only( + {"both are equal to"=>" This has no newline.", "is equal to"=>"The \\ ' \" characters may be\nfreely used. Leading white\n space is significant.\n\nLine breaks are significant.\nThus this value contains one\nempty line and ends with a\nsingle line break, but does\nnot start with one.\n", "also written as"=>" This has no newline.", "indented and chomped"=>" This has no newline.", "empty"=>"", "literal"=>"The \\ ' \" characters may be\nfreely used. Leading white\n space is significant.\n\nLine breaks are significant.\nThus this value contains one\nempty line and ends with a\nsingle line break, but does\nnot start with one.\n"}, <<EOY +empty: | + +literal: | + The \\\ ' " characters may be + freely used. Leading white + space is significant. + + Line breaks are significant. + Thus this value contains one + empty line and ends with a + single line break, but does + not start with one. + +is equal to: "The \\\\ ' \\" characters may \\ + be\\nfreely used. Leading white\\n space \\ + is significant.\\n\\nLine breaks are \\ + significant.\\nThus this value contains \\ + one\\nempty line and ends with a\\nsingle \\ + line break, but does\\nnot start with one.\\n" + +# Comments may follow a nested +# scalar value. They must be +# less indented. + +# Modifiers may be combined in any order. +indented and chomped: |2- + This has no newline. + +also written as: |-2 + This has no newline. + +both are equal to: " This has no newline." +EOY + ) + + str1 = "This has one newline.\n" + str2 = "This has no newline." + str3 = "This has two newlines.\n\n" + assert_parse_only( + { 'clipped' => str1, 'same as "clipped" above' => str1, + 'stripped' => str2, 'same as "stripped" above' => str2, + 'kept' => str3, 'same as "kept" above' => str3 }, <<EOY +clipped: | + This has one newline. + +same as "clipped" above: "This has one newline.\\n" + +stripped: |- + This has no newline. + +same as "stripped" above: "This has no newline." + +kept: |+ + This has two newlines. + +same as "kept" above: "This has two newlines.\\n\\n" + +EOY + ) + end + + def test_spec_span_single_quote + assert_parse_only( {"third"=>"a single quote ' must be escaped.", "second"=>"! : \\ etc. can be used freely.", "is same as"=>"this contains six spaces\nand one line break", "empty"=>"", "span"=>"this contains six spaces\nand one line break"}, <<EOY +empty: '' +second: '! : \\ etc. can be used freely.' +third: 'a single quote '' must be escaped.' +span: 'this contains + six spaces + + and one + line break' +is same as: "this contains six spaces\\nand one line break" +EOY + ) + end + + def test_spec_span_double_quote + assert_parse_only( {"is equal to"=>"this contains four spaces", "third"=>"a \" or a \\ must be escaped.", "second"=>"! : etc. can be used freely.", "empty"=>"", "fourth"=>"this value ends with an LF.\n", "span"=>"this contains four spaces"}, <<EOY +empty: "" +second: "! : etc. can be used freely." +third: "a \\\" or a \\\\ must be escaped." +fourth: "this value ends with an LF.\\n" +span: "this contains + four \\ + spaces" +is equal to: "this contains four spaces" +EOY + ) + end + + def test_spec_builtin_time + # Time + assert_parse_only( + { "space separated" => mktime( 2001, 12, 14, 21, 59, 43, ".10", "-05:00" ), + "canonical" => mktime( 2001, 12, 15, 2, 59, 43, ".10" ), + "date (noon UTC)" => Date.new( 2002, 12, 14), + "valid iso8601" => mktime( 2001, 12, 14, 21, 59, 43, ".10", "-05:00" ) }, <<EOY +canonical: 2001-12-15T02:59:43.1Z +valid iso8601: 2001-12-14t21:59:43.10-05:00 +space separated: 2001-12-14 21:59:43.10 -05:00 +date (noon UTC): 2002-12-14 +EOY + ) + end + + def test_spec_builtin_binary + arrow_gif = "GIF89a\f\000\f\000\204\000\000\377\377\367\365\365\356\351\351\345fff\000\000\000\347\347\347^^^\363\363\355\216\216\216\340\340\340\237\237\237\223\223\223\247\247\247\236\236\236iiiccc\243\243\243\204\204\204\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371!\376\016Made with GIMP\000,\000\000\000\000\f\000\f\000\000\005, \216\2010\236\343@\024\350i\020\304\321\212\010\034\317\200M$z\357\3770\205p\270\2601f\r\e\316\001\303\001\036\020' \202\n\001\000;" + assert_parse_only( + { 'canonical' => arrow_gif, 'base64' => arrow_gif, + 'description' => "The binary value above is a tiny arrow encoded as a gif image.\n" }, <<EOY +canonical: !binary "\\ + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOf\\ + n515eXvPz7Y6OjuDg4J+fn5OTk6enp56enmlpaW\\ + NjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++\\ + f/++f/++f/++f/++f/++f/++f/++SH+Dk1hZGUg\\ + d2l0aCBHSU1QACwAAAAADAAMAAAFLCAgjoEwnuN\\ + AFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84Bww\\ + EeECcgggoBADs=" +base64: !binary | + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOf + n515eXvPz7Y6OjuDg4J+fn5OTk6enp56enmlpaW + NjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++ + f/++f/++f/++f/++f/++f/++f/++SH+Dk1hZGUg + d2l0aCBHSU1QACwAAAAADAAMAAAFLCAgjoEwnuN + AFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84Bww + EeECcgggoBADs= +description: > + The binary value above is a tiny arrow + encoded as a gif image. +EOY + ) + end + def test_ruby_regexp + # Test Ruby regular expressions + assert_to_yaml( + { 'simple' => /a.b/, 'complex' => %r'\A"((?:[^"]|\")+)"', + 'case-insensitive' => /George McFly/i }, <<EOY +case-insensitive: !ruby/regexp "/George McFly/i" +complex: !ruby/regexp "/\\\\A\\"((?:[^\\"]|\\\\\\")+)\\"/" +simple: !ruby/regexp "/a.b/" +EOY + ) + end + + # + # Test of Ranges + # + def test_ranges + + # Simple numeric + assert_to_yaml( 1..3, <<EOY ) +--- !ruby/range 1..3 +EOY + + # Simple alphabetic + assert_to_yaml( 'a'..'z', <<EOY ) +--- !ruby/range a..z +EOY + + # Float + assert_to_yaml( 10.5...30.3, <<EOY ) +--- !ruby/range 10.5...30.3 +EOY + + end + + def test_ruby_struct + # Ruby structures + book_struct = Struct::new( "MyBookStruct", :author, :title, :year, :isbn ) + assert_to_yaml( + [ book_struct.new( "Yukihiro Matsumoto", "Ruby in a Nutshell", 2002, "0-596-00214-9" ), + book_struct.new( [ 'Dave Thomas', 'Andy Hunt' ], "The Pickaxe", 2002, + book_struct.new( "This should be the ISBN", "but I have another struct here", 2002, "None" ) + ) ], <<EOY +- !ruby/struct:MyBookStruct + author: Yukihiro Matsumoto + title: Ruby in a Nutshell + year: 2002 + isbn: 0-596-00214-9 +- !ruby/struct:MyBookStruct + author: + - Dave Thomas + - Andy Hunt + title: The Pickaxe + year: 2002 + isbn: !ruby/struct:MyBookStruct + author: This should be the ISBN + title: but I have another struct here + year: 2002 + isbn: None +EOY + ) + + assert_to_yaml( Psych_Tests::StructTest.new( 123 ), <<EOY ) +--- !ruby/struct:Psych_Tests::StructTest +c: 123 +EOY + + end + + def test_ruby_rational + assert_to_yaml( Rational(1, 2), <<EOY ) +--- !ruby/object:Rational +numerator: 1 +denominator: 2 +EOY + + # Read Psych dumped by the ruby 1.8.3. + assert_to_yaml( Rational(1, 2), "!ruby/object:Rational 1/2\n" ) + assert_raises( ArgumentError ) { Psych.load("!ruby/object:Rational INVALID/RATIONAL\n") } + end + + def test_ruby_complex + assert_to_yaml( Complex(3, 4), <<EOY ) +--- !ruby/object:Complex +image: 4 +real: 3 +EOY + + # Read Psych dumped by the ruby 1.8.3. + assert_to_yaml( Complex(3, 4), "!ruby/object:Complex 3+4i\n" ) + assert_raises( ArgumentError ) { Psych.load("!ruby/object:Complex INVALID+COMPLEXi\n") } + end + + def test_emitting_indicators + assert_to_yaml( "Hi, from Object 1. You passed: please, pretty please", <<EOY +--- "Hi, from Object 1. You passed: please, pretty please" +EOY + ) + end + + ## + ## Test the Psych::Stream class -- INACTIVE at the moment + ## + #def test_document + # y = Psych::Stream.new( :Indent => 2, :UseVersion => 0 ) + # y.add( + # { 'hi' => 'hello', 'map' => + # { 'good' => 'two' }, + # 'time' => Time.now, + # 'try' => /^po(.*)$/, + # 'bye' => 'goodbye' + # } + # ) + # y.add( { 'po' => 'nil', 'oper' => 90 } ) + # y.add( { 'hi' => 'wow!', 'bye' => 'wow!' } ) + # y.add( { [ 'Red Socks', 'Boston' ] => [ 'One', 'Two', 'Three' ] } ) + # y.add( [ true, false, false ] ) + #end + + # + # Test YPath choices parsing + # + #def test_ypath_parsing + # assert_path_segments( "/*/((one|three)/name|place)|//place", + # [ ["*", "one", "name"], + # ["*", "three", "name"], + # ["*", "place"], + # ["/", "place"] ] + # ) + #end + + # + # Tests from Tanaka Akira on [ruby-core] + # + def test_akira + + # Commas in plain scalars [ruby-core:1066] + assert_to_yaml( + {"A"=>"A,","B"=>"B"}, <<EOY +A: "A," +B: B +EOY + ) + + # Double-quoted keys [ruby-core:1069] + assert_to_yaml( + {"1"=>2, "2"=>3}, <<EOY +'1': 2 +"2": 3 +EOY + ) + + # Anchored mapping [ruby-core:1071] + assert_to_yaml( + [{"a"=>"b"}] * 2, <<EOY +- &id001 + a: b +- *id001 +EOY + ) + + # Stress test [ruby-core:1071] + # a = []; 1000.times { a << {"a"=>"b", "c"=>"d"} } + # Psych::load( a.to_yaml ) + + end + + # + # Test Time.now cycle + # + def test_time_now_cycle + # + # From Minero Aoki [ruby-core:2305] + # + #require 'yaml' + t = Time.now + t = Time.at(t.tv_sec, t.tv_usec) + 5.times do + assert_cycle(t) + end + end + + # + # Test Range cycle + # + def test_range_cycle + # + # From Minero Aoki [ruby-core:02306] + # + assert_cycle("a".."z") + + # + # From Nobu Nakada [ruby-core:02311] + # + assert_cycle(0..1) + assert_cycle(1.0e20 .. 2.0e20) + assert_cycle("0".."1") + assert_cycle(".."..."...") + assert_cycle(".rb"..".pl") + assert_cycle(".rb"...".pl") + assert_cycle('"'...".") + assert_cycle("'"...".") + end + + # + # Circular references + # + def test_circular_references + a = []; a[0] = a; a[1] = a + inspect_str = "[[...], [...]]" + assert_equal( inspect_str, Psych::load(Psych.dump(a)).inspect ) + end + + # + # Test Symbol cycle + # + def test_symbol_cycle + # + # From Aaron Schrab [ruby-Bugs:2535] + # + assert_cycle(:"^foo") + end + + # + # Test Numeric cycle + # + class NumericTest < Numeric + def initialize(value) + @value = value + end + def ==(other) + @value == other.instance_eval{ @value } + end + end + def test_numeric_cycle + assert_cycle(1) # Fixnum + assert_cycle(111111111111111111111111111111111) # Bignum + assert_cycle(NumericTest.new(3)) # Subclass of Numeric + end + + # + # Test empty map/seq in map cycle + # + def test_empty_map_key + # + # empty seq as key + # + assert_cycle({[]=>""}) + + # + # empty map as key + # + assert_cycle({{}=>""}) + end + + # + # contributed by riley lynch [ruby-Bugs-8548] + # + def test_object_id_collision + omap = Psych::Omap.new + 1000.times { |i| omap["key_#{i}"] = { "value" => i } } + raise "id collision in ordered map" if Psych.dump(omap) =~ /id\d+/ + end + + def test_date_out_of_range + Psych::load('1900-01-01T00:00:00+00:00') + end + + def test_normal_exit + Psych.load("2000-01-01 00:00:00.#{"0"*1000} +00:00\n") + # '[ruby-core:13735]' + end + + def test_multiline_string_uses_literal_style + yaml = Psych.dump("multi\nline\nstring") + assert_match("|", yaml) + end + + def test_string_starting_with_non_word_character_uses_double_quotes_without_exclamation_mark + yaml = Psych.dump("@123'abc") + refute_match("!", yaml) + end + + def test_string_dump_with_colon + yaml = Psych.dump 'x: foo' + refute_match '!', yaml + end + + def test_string_dump_starting_with_star + yaml = Psych.dump '*foo' + refute_match '!', yaml + end +end diff --git a/jni/ruby/test/psych/test_yamldbm.rb b/jni/ruby/test/psych/test_yamldbm.rb new file mode 100644 index 0000000..7853658 --- /dev/null +++ b/jni/ruby/test/psych/test_yamldbm.rb @@ -0,0 +1,193 @@ +require_relative 'helper' +require 'tmpdir' + +begin + require 'yaml/dbm' +rescue LoadError +end + +module Psych + ::Psych::DBM = ::YAML::DBM unless defined?(::Psych::DBM) + + class YAMLDBMTest < TestCase + def setup + @dir = Dir.mktmpdir("rubytest-file") + File.chown(-1, Process.gid, @dir) + @yamldbm_file = make_tmp_filename("yamldbm") + @yamldbm = YAML::DBM.new(@yamldbm_file) + end + + def teardown + @yamldbm.clear + @yamldbm.close + FileUtils.remove_entry_secure @dir + end + + def make_tmp_filename(prefix) + @dir + "/" + prefix + File.basename(__FILE__) + ".#{$$}.test" + end + + def test_store + @yamldbm.store('a','b') + @yamldbm.store('c','d') + assert_equal 'b', @yamldbm['a'] + assert_equal 'd', @yamldbm['c'] + assert_nil @yamldbm['e'] + end + + def test_store_using_carret + @yamldbm['a'] = 'b' + @yamldbm['c'] = 'd' + assert_equal 'b', @yamldbm['a'] + assert_equal 'd', @yamldbm['c'] + assert_nil @yamldbm['e'] + end + + def test_to_a + @yamldbm['a'] = 'b' + @yamldbm['c'] = 'd' + assert_equal([['a','b'],['c','d']], @yamldbm.to_a.sort) + end + + def test_to_hash + @yamldbm['a'] = 'b' + @yamldbm['c'] = 'd' + assert_equal({'a'=>'b','c'=>'d'}, @yamldbm.to_hash) + end + + def test_has_value? + @yamldbm['a'] = 'b' + @yamldbm['c'] = 'd' + assert_equal true, @yamldbm.has_value?('b') + assert_equal true, @yamldbm.has_value?('d') + assert_equal false, @yamldbm.has_value?('f') + end + + # Note: + # YAML::DBM#index makes warning from internal of ::DBM#index. + # It says 'DBM#index is deprecated; use DBM#key', but DBM#key + # behaves not same as DBM#index. + # + # def test_index + # @yamldbm['a'] = 'b' + # @yamldbm['c'] = 'd' + # assert_equal 'a', @yamldbm.index('b') + # assert_equal 'c', @yamldbm.index('d') + # assert_nil @yamldbm.index('f') + # end + + def test_key + skip 'only on ruby 2.0.0' if RUBY_VERSION < '2.0.0' + @yamldbm['a'] = 'b' + @yamldbm['c'] = 'd' + assert_equal 'a', @yamldbm.key('b') + assert_equal 'c', @yamldbm.key('d') + assert_nil @yamldbm.key('f') + end + + def test_fetch + assert_equal('bar', @yamldbm['foo']='bar') + assert_equal('bar', @yamldbm.fetch('foo')) + assert_nil @yamldbm.fetch('bar') + assert_equal('baz', @yamldbm.fetch('bar', 'baz')) + assert_equal('foobar', @yamldbm.fetch('bar') {|key| 'foo' + key }) + end + + def test_shift + @yamldbm['a'] = 'b' + @yamldbm['c'] = 'd' + assert_equal([['a','b'], ['c','d']], + [@yamldbm.shift, @yamldbm.shift].sort) + assert_nil @yamldbm.shift + end + + def test_invert + @yamldbm['a'] = 'b' + @yamldbm['c'] = 'd' + assert_equal({'b'=>'a','d'=>'c'}, @yamldbm.invert) + end + + def test_update + @yamldbm['a'] = 'b' + @yamldbm['c'] = 'd' + @yamldbm.update({'c'=>'d','e'=>'f'}) + assert_equal 'b', @yamldbm['a'] + assert_equal 'd', @yamldbm['c'] + assert_equal 'f', @yamldbm['e'] + end + + def test_replace + @yamldbm['a'] = 'b' + @yamldbm['c'] = 'd' + @yamldbm.replace({'c'=>'d','e'=>'f'}) + assert_nil @yamldbm['a'] + assert_equal 'd', @yamldbm['c'] + assert_equal 'f', @yamldbm['e'] + end + + def test_delete + @yamldbm['a'] = 'b' + @yamldbm['c'] = 'd' + assert_equal 'b', @yamldbm.delete('a') + assert_nil @yamldbm['a'] + assert_equal 'd', @yamldbm['c'] + assert_nil @yamldbm.delete('e') + end + + def test_delete_if + @yamldbm['a'] = 'b' + @yamldbm['c'] = 'd' + @yamldbm['e'] = 'f' + + @yamldbm.delete_if {|k,v| k == 'a'} + assert_nil @yamldbm['a'] + assert_equal 'd', @yamldbm['c'] + assert_equal 'f', @yamldbm['e'] + + @yamldbm.delete_if {|k,v| v == 'd'} + assert_nil @yamldbm['c'] + assert_equal 'f', @yamldbm['e'] + + @yamldbm.delete_if {|k,v| false } + assert_equal 'f', @yamldbm['e'] + end + + def test_reject + @yamldbm['a'] = 'b' + @yamldbm['c'] = 'd' + @yamldbm['e'] = 'f' + assert_equal({'c'=>'d','e'=>'f'}, @yamldbm.reject {|k,v| k == 'a'}) + assert_equal({'a'=>'b','e'=>'f'}, @yamldbm.reject {|k,v| v == 'd'}) + assert_equal({'a'=>'b','c'=>'d','e'=>'f'}, @yamldbm.reject {false}) + end + + def test_values + assert_equal [], @yamldbm.values + @yamldbm['a'] = 'b' + @yamldbm['c'] = 'd' + assert_equal ['b','d'], @yamldbm.values.sort + end + + def test_values_at + @yamldbm['a'] = 'b' + @yamldbm['c'] = 'd' + assert_equal ['b','d'], @yamldbm.values_at('a','c') + end + + def test_selsct + @yamldbm['a'] = 'b' + @yamldbm['c'] = 'd' + @yamldbm['e'] = 'f' + assert_equal(['b','d'], @yamldbm.select('a','c')) + end + + def test_selsct_with_block + @yamldbm['a'] = 'b' + @yamldbm['c'] = 'd' + @yamldbm['e'] = 'f' + assert_equal([['a','b']], @yamldbm.select {|k,v| k == 'a'}) + assert_equal([['c','d']], @yamldbm.select {|k,v| v == 'd'}) + assert_equal([], @yamldbm.select {false}) + end + end +end if defined?(YAML::DBM) && defined?(Psych) diff --git a/jni/ruby/test/psych/test_yamlstore.rb b/jni/ruby/test/psych/test_yamlstore.rb new file mode 100644 index 0000000..94f1330 --- /dev/null +++ b/jni/ruby/test/psych/test_yamlstore.rb @@ -0,0 +1,85 @@ +require_relative 'helper' +require 'yaml/store' +require 'tmpdir' + +module Psych + Psych::Store = YAML::Store unless defined?(Psych::Store) + + class YAMLStoreTest < TestCase + def setup + @dir = Dir.mktmpdir("rubytest-file") + File.chown(-1, Process.gid, @dir) + @yamlstore_file = make_tmp_filename("yamlstore") + @yamlstore = YAML::Store.new(@yamlstore_file) + end + + def teardown + FileUtils.remove_entry_secure @dir + end + + def make_tmp_filename(prefix) + @dir + "/" + prefix + File.basename(__FILE__) + ".#{$$}.test" + end + + def test_opening_new_file_in_readonly_mode_should_result_in_empty_values + @yamlstore.transaction(true) do + assert_nil @yamlstore[:foo] + assert_nil @yamlstore[:bar] + end + end + + def test_opening_new_file_in_readwrite_mode_should_result_in_empty_values + @yamlstore.transaction do + assert_nil @yamlstore[:foo] + assert_nil @yamlstore[:bar] + end + end + + def test_data_should_be_loaded_correctly_when_in_readonly_mode + @yamlstore.transaction do + @yamlstore[:foo] = "bar" + end + @yamlstore.transaction(true) do + assert_equal "bar", @yamlstore[:foo] + end + end + + def test_data_should_be_loaded_correctly_when_in_readwrite_mode + @yamlstore.transaction do + @yamlstore[:foo] = "bar" + end + @yamlstore.transaction do + assert_equal "bar", @yamlstore[:foo] + end + end + + def test_changes_after_commit_are_discarded + @yamlstore.transaction do + @yamlstore[:foo] = "bar" + @yamlstore.commit + @yamlstore[:foo] = "baz" + end + @yamlstore.transaction(true) do + assert_equal "bar", @yamlstore[:foo] + end + end + + def test_changes_are_not_written_on_abort + @yamlstore.transaction do + @yamlstore[:foo] = "bar" + @yamlstore.abort + end + @yamlstore.transaction(true) do + assert_nil @yamlstore[:foo] + end + end + + def test_writing_inside_readonly_transaction_raises_error + assert_raises(PStore::Error) do + @yamlstore.transaction(true) do + @yamlstore[:foo] = "bar" + end + end + end + end +end if defined?(Psych) diff --git a/jni/ruby/test/psych/visitors/test_depth_first.rb b/jni/ruby/test/psych/visitors/test_depth_first.rb new file mode 100644 index 0000000..837c8e8 --- /dev/null +++ b/jni/ruby/test/psych/visitors/test_depth_first.rb @@ -0,0 +1,49 @@ +require 'psych/helper' + +module Psych + module Visitors + class TestDepthFirst < TestCase + class Collector < Struct.new(:calls) + def initialize(calls = []) + super + end + + def call obj + calls << obj + end + end + + def test_scalar + collector = Collector.new + visitor = Visitors::DepthFirst.new collector + visitor.accept Psych.parse_stream '--- hello' + + assert_equal 3, collector.calls.length + end + + def test_sequence + collector = Collector.new + visitor = Visitors::DepthFirst.new collector + visitor.accept Psych.parse_stream "---\n- hello" + + assert_equal 4, collector.calls.length + end + + def test_mapping + collector = Collector.new + visitor = Visitors::DepthFirst.new collector + visitor.accept Psych.parse_stream "---\nhello: world" + + assert_equal 5, collector.calls.length + end + + def test_alias + collector = Collector.new + visitor = Visitors::DepthFirst.new collector + visitor.accept Psych.parse_stream "--- &yay\n- foo\n- *yay\n" + + assert_equal 5, collector.calls.length + end + end + end +end diff --git a/jni/ruby/test/psych/visitors/test_emitter.rb b/jni/ruby/test/psych/visitors/test_emitter.rb new file mode 100644 index 0000000..780c953 --- /dev/null +++ b/jni/ruby/test/psych/visitors/test_emitter.rb @@ -0,0 +1,144 @@ +require 'psych/helper' + +module Psych + module Visitors + class TestEmitter < TestCase + def setup + super + @io = StringIO.new + @visitor = Visitors::Emitter.new @io + end + + def test_options + io = StringIO.new + visitor = Visitors::Emitter.new io, :indentation => 3 + + s = Nodes::Stream.new + doc = Nodes::Document.new + mapping = Nodes::Mapping.new + m2 = Nodes::Mapping.new + m2.children << Nodes::Scalar.new('a') + m2.children << Nodes::Scalar.new('b') + + mapping.children << Nodes::Scalar.new('key') + mapping.children << m2 + doc.children << mapping + s.children << doc + + visitor.accept s + assert_match(/^[ ]{3}a/, io.string) + end + + def test_stream + s = Nodes::Stream.new + @visitor.accept s + assert_equal '', @io.string + end + + def test_document + s = Nodes::Stream.new + doc = Nodes::Document.new [1,1] + scalar = Nodes::Scalar.new 'hello world' + + doc.children << scalar + s.children << doc + + @visitor.accept s + + assert_match(/1.1/, @io.string) + assert_equal @io.string, s.yaml + end + + def test_document_implicit_end + s = Nodes::Stream.new + doc = Nodes::Document.new + mapping = Nodes::Mapping.new + mapping.children << Nodes::Scalar.new('key') + mapping.children << Nodes::Scalar.new('value') + doc.children << mapping + s.children << doc + + @visitor.accept s + + assert_match(/key: value/, @io.string) + assert_equal @io.string, s.yaml + assert(/\.\.\./ !~ s.yaml) + end + + def test_scalar + s = Nodes::Stream.new + doc = Nodes::Document.new + scalar = Nodes::Scalar.new 'hello world' + + doc.children << scalar + s.children << doc + + @visitor.accept s + + assert_match(/hello/, @io.string) + assert_equal @io.string, s.yaml + end + + def test_scalar_with_tag + s = Nodes::Stream.new + doc = Nodes::Document.new + scalar = Nodes::Scalar.new 'hello world', nil, '!str', false, false, 5 + + doc.children << scalar + s.children << doc + + @visitor.accept s + + assert_match(/str/, @io.string) + assert_match(/hello/, @io.string) + assert_equal @io.string, s.yaml + end + + def test_sequence + s = Nodes::Stream.new + doc = Nodes::Document.new + scalar = Nodes::Scalar.new 'hello world' + seq = Nodes::Sequence.new + + seq.children << scalar + doc.children << seq + s.children << doc + + @visitor.accept s + + assert_match(/- hello/, @io.string) + assert_equal @io.string, s.yaml + end + + def test_mapping + s = Nodes::Stream.new + doc = Nodes::Document.new + mapping = Nodes::Mapping.new + mapping.children << Nodes::Scalar.new('key') + mapping.children << Nodes::Scalar.new('value') + doc.children << mapping + s.children << doc + + @visitor.accept s + + assert_match(/key: value/, @io.string) + assert_equal @io.string, s.yaml + end + + def test_alias + s = Nodes::Stream.new + doc = Nodes::Document.new + mapping = Nodes::Mapping.new + mapping.children << Nodes::Scalar.new('key', 'A') + mapping.children << Nodes::Alias.new('A') + doc.children << mapping + s.children << doc + + @visitor.accept s + + assert_match(/&A key: \*A/, @io.string) + assert_equal @io.string, s.yaml + end + end + end +end diff --git a/jni/ruby/test/psych/visitors/test_to_ruby.rb b/jni/ruby/test/psych/visitors/test_to_ruby.rb new file mode 100644 index 0000000..c13d980 --- /dev/null +++ b/jni/ruby/test/psych/visitors/test_to_ruby.rb @@ -0,0 +1,326 @@ +# coding: US-ASCII +require 'psych/helper' + +module Psych + module Visitors + class TestToRuby < TestCase + def setup + super + @visitor = ToRuby.create + end + + def test_object + mapping = Nodes::Mapping.new nil, "!ruby/object" + mapping.children << Nodes::Scalar.new('foo') + mapping.children << Nodes::Scalar.new('bar') + + o = mapping.to_ruby + assert_equal 'bar', o.instance_variable_get(:@foo) + end + + def test_tz_00_00_loads_without_error + assert Psych.load('1900-01-01T00:00:00+00:00') + end + + def test_legacy_struct + foo = Struct.new('AWESOME', :bar) + assert_equal foo.new('baz'), Psych.load(<<-eoyml) +!ruby/struct:AWESOME + bar: baz + eoyml + end + + def test_binary + gif = "GIF89a\f\x00\f\x00\x84\x00\x00\xFF\xFF\xF7\xF5\xF5\xEE\xE9\xE9\xE5fff\x00\x00\x00\xE7\xE7\xE7^^^\xF3\xF3\xED\x8E\x8E\x8E\xE0\xE0\xE0\x9F\x9F\x9F\x93\x93\x93\xA7\xA7\xA7\x9E\x9E\x9Eiiiccc\xA3\xA3\xA3\x84\x84\x84\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9!\xFE\x0EMade with GIMP\x00,\x00\x00\x00\x00\f\x00\f\x00\x00\x05, \x8E\x810\x9E\xE3@\x14\xE8i\x10\xC4\xD1\x8A\b\x1C\xCF\x80M$z\xEF\xFF0\x85p\xB8\xB01f\r\e\xCE\x01\xC3\x01\x1E\x10' \x82\n\x01\x00;" + + hash = Psych.load(<<-'eoyaml') +canonical: !!binary "\ + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5\ + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+\ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC\ + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=" +generic: !binary | + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= +description: + The binary value above is a tiny arrow encoded as a gif image. + eoyaml + assert_equal gif, hash['canonical'] + assert_equal gif, hash['generic'] + end + + A = Struct.new(:foo) + + def test_struct + s = A.new('bar') + + mapping = Nodes::Mapping.new nil, "!ruby/struct:#{s.class}" + mapping.children << Nodes::Scalar.new('foo') + mapping.children << Nodes::Scalar.new('bar') + + ruby = mapping.to_ruby + + assert_equal s.class, ruby.class + assert_equal s.foo, ruby.foo + assert_equal s, ruby + end + + def test_anon_struct_legacy + s = Struct.new(:foo).new('bar') + + mapping = Nodes::Mapping.new nil, '!ruby/struct:' + mapping.children << Nodes::Scalar.new('foo') + mapping.children << Nodes::Scalar.new('bar') + + assert_equal s.foo, mapping.to_ruby.foo + end + + def test_anon_struct + s = Struct.new(:foo).new('bar') + + mapping = Nodes::Mapping.new nil, '!ruby/struct' + mapping.children << Nodes::Scalar.new('foo') + mapping.children << Nodes::Scalar.new('bar') + + assert_equal s.foo, mapping.to_ruby.foo + end + + def test_exception + exc = ::Exception.new 'hello' + + mapping = Nodes::Mapping.new nil, '!ruby/exception' + mapping.children << Nodes::Scalar.new('message') + mapping.children << Nodes::Scalar.new('hello') + + ruby = mapping.to_ruby + + assert_equal exc.class, ruby.class + assert_equal exc.message, ruby.message + end + + def test_regexp + node = Nodes::Scalar.new('/foo/', nil, '!ruby/regexp') + assert_equal(/foo/, node.to_ruby) + + node = Nodes::Scalar.new('/foo/m', nil, '!ruby/regexp') + assert_equal(/foo/m, node.to_ruby) + + node = Nodes::Scalar.new('/foo/ix', nil, '!ruby/regexp') + assert_equal(/foo/ix, node.to_ruby) + end + + def test_time + now = Time.now + zone = now.strftime('%z') + zone = " #{zone[0,3]}:#{zone[3,5]}" + + formatted = now.strftime("%Y-%m-%d %H:%M:%S.%9N") + zone + + assert_equal now, Nodes::Scalar.new(formatted).to_ruby + end + + def test_time_utc + now = Time.now.utc + formatted = now.strftime("%Y-%m-%d %H:%M:%S") + + ".%09dZ" % [now.nsec] + + assert_equal now, Nodes::Scalar.new(formatted).to_ruby + end + + def test_time_utc_no_z + now = Time.now.utc + formatted = now.strftime("%Y-%m-%d %H:%M:%S") + + ".%09d" % [now.nsec] + + assert_equal now, Nodes::Scalar.new(formatted).to_ruby + end + + def test_date + d = '1980-12-16' + actual = Date.strptime(d, '%Y-%m-%d') + + date = Nodes::Scalar.new(d, nil, 'tag:yaml.org,2002:timestamp', false) + + assert_equal actual, date.to_ruby + end + + def test_rational + mapping = Nodes::Mapping.new nil, '!ruby/object:Rational' + mapping.children << Nodes::Scalar.new('denominator') + mapping.children << Nodes::Scalar.new('2') + mapping.children << Nodes::Scalar.new('numerator') + mapping.children << Nodes::Scalar.new('1') + + assert_equal Rational(1,2), mapping.to_ruby + end + + def test_complex + mapping = Nodes::Mapping.new nil, '!ruby/object:Complex' + mapping.children << Nodes::Scalar.new('image') + mapping.children << Nodes::Scalar.new('2') + mapping.children << Nodes::Scalar.new('real') + mapping.children << Nodes::Scalar.new('1') + + assert_equal Complex(1,2), mapping.to_ruby + end + + if RUBY_VERSION >= '1.9' + def test_complex_string + node = Nodes::Scalar.new '3+4i', nil, "!ruby/object:Complex" + assert_equal Complex(3, 4), node.to_ruby + end + + def test_rational_string + node = Nodes::Scalar.new '1/2', nil, "!ruby/object:Rational" + assert_equal Rational(1, 2), node.to_ruby + end + end + + def test_range_string + node = Nodes::Scalar.new '1..2', nil, "!ruby/range" + assert_equal 1..2, node.to_ruby + end + + def test_range_string_triple + node = Nodes::Scalar.new '1...3', nil, "!ruby/range" + assert_equal 1...3, node.to_ruby + end + + def test_integer + i = Nodes::Scalar.new('1', nil, 'tag:yaml.org,2002:int') + assert_equal 1, i.to_ruby + + assert_equal 1, Nodes::Scalar.new('1').to_ruby + + i = Nodes::Scalar.new('-1', nil, 'tag:yaml.org,2002:int') + assert_equal(-1, i.to_ruby) + + assert_equal(-1, Nodes::Scalar.new('-1').to_ruby) + assert_equal 1, Nodes::Scalar.new('+1').to_ruby + end + + def test_int_ignore + ['1,000', '1_000'].each do |num| + i = Nodes::Scalar.new(num, nil, 'tag:yaml.org,2002:int') + assert_equal 1000, i.to_ruby + + assert_equal 1000, Nodes::Scalar.new(num).to_ruby + end + end + + def test_float_ignore + ['1,000.3', '1_000.3'].each do |num| + i = Nodes::Scalar.new(num, nil, 'tag:yaml.org,2002:float') + assert_equal 1000.3, i.to_ruby + + i = Nodes::Scalar.new(num, nil, '!float') + assert_equal 1000.3, i.to_ruby + + assert_equal 1000.3, Nodes::Scalar.new(num).to_ruby + end + end + + # http://yaml.org/type/bool.html + def test_boolean_true + %w{ yes Yes YES true True TRUE on On ON }.each do |t| + i = Nodes::Scalar.new(t, nil, 'tag:yaml.org,2002:bool') + assert_equal true, i.to_ruby + assert_equal true, Nodes::Scalar.new(t).to_ruby + end + end + + # http://yaml.org/type/bool.html + def test_boolean_false + %w{ no No NO false False FALSE off Off OFF }.each do |t| + i = Nodes::Scalar.new(t, nil, 'tag:yaml.org,2002:bool') + assert_equal false, i.to_ruby + assert_equal false, Nodes::Scalar.new(t).to_ruby + end + end + + def test_float + i = Nodes::Scalar.new('12', nil, 'tag:yaml.org,2002:float') + assert_equal 12.0, i.to_ruby + + i = Nodes::Scalar.new('1.2', nil, 'tag:yaml.org,2002:float') + assert_equal 1.2, i.to_ruby + + i = Nodes::Scalar.new('1.2') + assert_equal 1.2, i.to_ruby + + assert_equal 1, Nodes::Scalar.new('.Inf').to_ruby.infinite? + assert_equal 1, Nodes::Scalar.new('.inf').to_ruby.infinite? + assert_equal 1, Nodes::Scalar.new('.Inf', nil, 'tag:yaml.org,2002:float').to_ruby.infinite? + + assert_equal(-1, Nodes::Scalar.new('-.inf').to_ruby.infinite?) + assert_equal(-1, Nodes::Scalar.new('-.Inf').to_ruby.infinite?) + assert_equal(-1, Nodes::Scalar.new('-.Inf', nil, 'tag:yaml.org,2002:float').to_ruby.infinite?) + + assert Nodes::Scalar.new('.NaN').to_ruby.nan? + assert Nodes::Scalar.new('.NaN', nil, 'tag:yaml.org,2002:float').to_ruby.nan? + end + + def test_exp_float + exp = 1.2e+30 + + i = Nodes::Scalar.new(exp.to_s, nil, 'tag:yaml.org,2002:float') + assert_equal exp, i.to_ruby + + assert_equal exp, Nodes::Scalar.new(exp.to_s).to_ruby + end + + def test_scalar + scalar = Nodes::Scalar.new('foo') + assert_equal 'foo', @visitor.accept(scalar) + assert_equal 'foo', scalar.to_ruby + end + + def test_sequence + seq = Nodes::Sequence.new + seq.children << Nodes::Scalar.new('foo') + seq.children << Nodes::Scalar.new('bar') + + assert_equal %w{ foo bar }, seq.to_ruby + end + + def test_mapping + mapping = Nodes::Mapping.new + mapping.children << Nodes::Scalar.new('foo') + mapping.children << Nodes::Scalar.new('bar') + assert_equal({'foo' => 'bar'}, mapping.to_ruby) + end + + def test_document + doc = Nodes::Document.new + doc.children << Nodes::Scalar.new('foo') + assert_equal 'foo', doc.to_ruby + end + + def test_stream + a = Nodes::Document.new + a.children << Nodes::Scalar.new('foo') + + b = Nodes::Document.new + b.children << Nodes::Scalar.new('bar') + + stream = Nodes::Stream.new + stream.children << a + stream.children << b + + assert_equal %w{ foo bar }, stream.to_ruby + end + + def test_alias + seq = Nodes::Sequence.new + seq.children << Nodes::Scalar.new('foo', 'A') + seq.children << Nodes::Alias.new('A') + + list = seq.to_ruby + assert_equal %w{ foo foo }, list + assert_equal list[0].object_id, list[1].object_id + end + end + end +end diff --git a/jni/ruby/test/psych/visitors/test_yaml_tree.rb b/jni/ruby/test/psych/visitors/test_yaml_tree.rb new file mode 100644 index 0000000..40702bc --- /dev/null +++ b/jni/ruby/test/psych/visitors/test_yaml_tree.rb @@ -0,0 +1,173 @@ +require 'psych/helper' + +module Psych + module Visitors + class TestYAMLTree < TestCase + def setup + super + @v = Visitors::YAMLTree.create + end + + def test_tree_can_be_called_twice + @v.start + @v << Object.new + t = @v.tree + assert_equal t, @v.tree + end + + def test_yaml_tree_can_take_an_emitter + io = StringIO.new + e = Psych::Emitter.new io + v = Visitors::YAMLTree.create({}, e) + v.start + v << "hello world" + v.finish + + assert_match "hello world", io.string + end + + def test_binary_formatting + gif = "GIF89a\f\x00\f\x00\x84\x00\x00\xFF\xFF\xF7\xF5\xF5\xEE\xE9\xE9\xE5fff\x00\x00\x00\xE7\xE7\xE7^^^\xF3\xF3\xED\x8E\x8E\x8E\xE0\xE0\xE0\x9F\x9F\x9F\x93\x93\x93\xA7\xA7\xA7\x9E\x9E\x9Eiiiccc\xA3\xA3\xA3\x84\x84\x84\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9\xFF\xFE\xF9!\xFE\x0EMade with GIMP\x00,\x00\x00\x00\x00\f\x00\f\x00\x00\x05, \x8E\x810\x9E\xE3@\x14\xE8i\x10\xC4\xD1\x8A\b\x1C\xCF\x80M$z\xEF\xFF0\x85p\xB8\xB01f\r\e\xCE\x01\xC3\x01\x1E\x10' \x82\n\x01\x00;" + @v << gif + scalar = @v.tree.children.first.children.first + assert_equal Psych::Nodes::Scalar::LITERAL, scalar.style + end + + def test_object_has_no_class + yaml = Psych.dump(Object.new) + assert(Psych.dump(Object.new) !~ /Object/, yaml) + end + + def test_struct_const + foo = Struct.new("Foo", :bar) + assert_cycle foo.new('bar') + Struct.instance_eval { remove_const(:Foo) } + end + + A = Struct.new(:foo) + + def test_struct + assert_cycle A.new('bar') + end + + def test_struct_anon + s = Struct.new(:foo).new('bar') + obj = Psych.load(Psych.dump(s)) + assert_equal s.foo, obj.foo + end + + def test_override_method + s = Struct.new(:method).new('override') + obj = Psych.load(Psych.dump(s)) + assert_equal s.method, obj.method + end + + def test_exception + ex = Exception.new 'foo' + loaded = Psych.load(Psych.dump(ex)) + + assert_equal ex.message, loaded.message + assert_equal ex.class, loaded.class + end + + def test_regexp + assert_cycle(/foo/) + assert_cycle(/foo/i) + assert_cycle(/foo/mx) + end + + def test_time + t = Time.now + assert_equal t, Psych.load(Psych.dump(t)) + end + + def test_date + date = Date.strptime('2002-12-14', '%Y-%m-%d') + assert_cycle date + end + + def test_rational + assert_cycle Rational(1,2) + end + + def test_complex + assert_cycle Complex(1,2) + end + + def test_scalar + assert_cycle 'foo' + assert_cycle ':foo' + assert_cycle '' + assert_cycle ':' + end + + def test_boolean + assert_cycle true + assert_cycle 'true' + assert_cycle false + assert_cycle 'false' + end + + def test_range_inclusive + assert_cycle 1..2 + end + + def test_range_exclusive + assert_cycle 1...2 + end + + def test_anon_class + assert_raises(TypeError) do + @v.accept Class.new + end + + assert_raises(TypeError) do + Psych.dump(Class.new) + end + end + + def test_hash + assert_cycle('a' => 'b') + end + + def test_list + assert_cycle(%w{ a b }) + assert_cycle([1, 2.2]) + end + + def test_symbol + assert_cycle :foo + end + + def test_int + assert_cycle 1 + assert_cycle(-1) + assert_cycle '1' + assert_cycle '-1' + end + + def test_float + assert_cycle 1.2 + assert_cycle '1.2' + + assert Psych.load(Psych.dump(0.0 / 0.0)).nan? + assert_equal 1, Psych.load(Psych.dump(1 / 0.0)).infinite? + assert_equal(-1, Psych.load(Psych.dump(-1 / 0.0)).infinite?) + end + + # http://yaml.org/type/null.html + def test_nil + assert_cycle nil + assert_equal nil, Psych.load('null') + assert_equal nil, Psych.load('Null') + assert_equal nil, Psych.load('NULL') + assert_equal nil, Psych.load('~') + assert_equal({'foo' => nil}, Psych.load('foo: ')) + + assert_cycle 'null' + assert_cycle 'nUll' + assert_cycle '~' + end + end + end +end |