From af0044ae16b6731780a211ec1433ff326e6fc074 Mon Sep 17 00:00:00 2001 From: ono-max Date: Sat, 26 Mar 2022 16:56:08 +0900 Subject: [PATCH] Refactor some logic in "CDP_Validator" class Improve error messages in ValidationError Use the hash map to get ruby classes from JSON type instead of the method --- test/support/protocol_utils.rb | 34 +++++++++++++--------------------- 1 file changed, 13 insertions(+), 21 deletions(-) diff --git a/test/support/protocol_utils.rb b/test/support/protocol_utils.rb index 7648504e8..b6b6bae9a 100644 --- a/test/support/protocol_utils.rb +++ b/test/support/protocol_utils.rb @@ -553,6 +553,15 @@ class CDP_Validator class ValidationError < Exception end + JSON_TYPE_TO_CLASS_MAPS = { + 'string' => String, + 'integer' => Integer, + 'boolean' => [TrueClass, FalseClass], + 'object' => Hash, + 'array' => Array, + 'any' => Object + } + def validate res, domain, command @seen = [] pattern = get_cmd_pattern(domain, command) @@ -567,10 +576,10 @@ def validate_ res, props props.each{|prop| name = prop[:name].to_sym if property = res[name] - types = get_ruby_type prop[:type] - types.each{|type| - raise ValidationError, "Expected #{property} to be kind of #{types.join}" unless property.is_a? type - } + cs = Array JSON_TYPE_TO_CLASS_MAPS[prop[:type]] + unless cs.any?{|c| property.is_a? c} + raise ValidationError, "Expected property `#{name}` to be kind of #{cs.join}, but it was #{property.class}" + end validate_ property, prop[:properties] else raise ValidationError, "Expected to include `#{name}` in responses" unless prop.fetch(:optional, false) @@ -578,23 +587,6 @@ def validate_ res, props } end - def get_ruby_type type - case type - when 'string' - [String] - when 'integer' - [Integer] - when 'boolean' - [TrueClass, FalseClass] - when 'object' - [Hash] - when 'array' - [Array] - when 'any' - [Object] - end - end - def get_cmd_pattern domain, command cmd = nil # FIXME: Commonalize this part.