From 4de50eb1e7ab3201bb9966be6633c0bb3ed24cf5 Mon Sep 17 00:00:00 2001 From: kwatch Date: Sat, 19 Nov 2016 12:14:58 +0900 Subject: [PATCH 9/9] feat(psych): add test script --- test/psych/visitors/test_custom_class.rb | 66 ++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 test/psych/visitors/test_custom_class.rb diff --git a/test/psych/visitors/test_custom_class.rb b/test/psych/visitors/test_custom_class.rb new file mode 100644 index 0000000..cf623ab --- /dev/null +++ b/test/psych/visitors/test_custom_class.rb @@ -0,0 +1,66 @@ +# coding: US-ASCII +# frozen_string_literal: false +require 'psych/helper' +require 'psych/visitors/custom_class' + +module Psych + module Visitors + class TestCustomClass < TestCase + + INPUT_STRING = <<-'END' + teams: + - name: SOS Brigade + members: + - {name: Haruhi, gender: F} + - {name: Kyon, gender: M} + - {name: Mikuru, gender: F} + - {name: Itsuki, gender: M} + - {name: Yuki, gender: F} + END + + def test_custom_classes + classmap = { + "teams" => Struct.new('Team', 'name', 'members'), + "members" => Struct.new('Member', 'name', 'gender'), + } + # + visitor = Psych::Visitors::CustomClassVisitor.create(classmap) + tree = Psych.parse(INPUT_STRING) + ydoc = visitor.accept(tree) + # + assert_kind_of Hash, ydoc + assert_kind_of classmap["teams"], ydoc['teams'][0] + assert_kind_of classmap["members"], ydoc['teams'][0]['members'][0] + # + team = ydoc['teams'][0] + assert_equal 'SOS Brigade', team.name + assert_equal 'Haruhi', team.members[0].name + assert_equal 'F', team.members[0].gender + end + + def test_default_class + magic_hash_cls = Class.new(Hash) do + def method_missing(method, *args) + return super unless args.empty? + return self[method.to_s] + end + end + classmap = {'*' => magic_hash_cls} + # + visitor = Psych::Visitors::CustomClassVisitor.create(classmap) + tree = Psych.parse(INPUT_STRING) + ydoc = visitor.accept(tree) + # + assert_kind_of magic_hash_cls, ydoc + assert_kind_of magic_hash_cls, ydoc['teams'][0] + assert_kind_of magic_hash_cls, ydoc['teams'][0]['members'][0] + # + team = ydoc['teams'][0] + assert_equal "SOS Brigade", team.name + assert_equal "Haruhi", team.members[0].name + assert_equal "F", team.members[0].gender + end + + end + end +end -- 2.9.3 (Apple Git-75)