yaml-schema 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: df10b8348eda9fb9eb5d36af1119234e00b48a4d1e5ef7f104d9fade49f02493
4
- data.tar.gz: 0d208c8b1883843586bd30c9de3cb5cafb6a65e8978eb495902d34e5c660462f
3
+ metadata.gz: df12251a77e6bf331750d95947b30e485e490987aeb677a69da3be5e6f95a285
4
+ data.tar.gz: e0d1173acce4cb5f416ce191eb8f65c47c6ba49c1733a54701543e721c73d3f1
5
5
  SHA512:
6
- metadata.gz: f345acb0e18034d923671d42507b3851a9735a41254e9bbd34caf2b6c9f89007e161fdf6b65844bd69528c40488db44ff341894aba73522622beae059d7c56c2
7
- data.tar.gz: 847b358731e0a6acaa24964bed4d58849ccc3da6e6440b95ff143396e16f79adeadd58b0a1a00f1cbf7d61ce6ec7eaff231a18653a0693170f671d07d3abaf78
6
+ metadata.gz: 0c0b69d6a20bff8eae82ad7ecbd36d03e20b658f992e0d38869e7f7cb755f391b32cd5939aa930613c1ffaad1fa6cd935767a708d26f3aefcc3e9f3a03fd4e7a
7
+ data.tar.gz: 0e9a49530ca5412592c45e0e834a561a9fde474003edd101bb074843f2bd53d57ab3555ca3e380b3c36c6b53d2d57ba8474ca36397783f969fb9bb7f439655cf
data/README.md CHANGED
@@ -60,6 +60,38 @@ schema = {
60
60
  }
61
61
  ```
62
62
 
63
+ ### Symbol Keys
64
+
65
+ Psych writes Symbol hash keys as plain scalars like `:name`. To describe one,
66
+ use a Symbol as the property name. A Symbol property only matches a Symbol key,
67
+ and a String property only matches a String key:
68
+
69
+ ```ruby
70
+ schema = {
71
+ "type" => "object",
72
+ "properties" => {
73
+ name: { "type" => "string" }, # matches `:name: bob`
74
+ "label" => { "type" => "string" } # matches `label: x`
75
+ },
76
+ "required" => [:name]
77
+ }
78
+ ```
79
+
80
+ Keys that aren't listed in `properties` (with `additionalProperties`), and the
81
+ keys of an `items` object, must be Strings unless `propertyNames` allows
82
+ Symbols:
83
+
84
+ ```ruby
85
+ schema = {
86
+ "type" => "object",
87
+ "items" => { "type" => "integer" },
88
+ "propertyNames" => { "type" => ["string", "symbol"] }
89
+ }
90
+ ```
91
+
92
+ A `propertyNames` `pattern` is matched against the key as written, so a Symbol
93
+ key `:name` is matched as `":name"`.
94
+
63
95
  ### Nested Objects and Arrays
64
96
 
65
97
  ```ruby
@@ -167,7 +167,7 @@ module YAMLSchema
167
167
  @methods = []
168
168
  @constants = []
169
169
  @names = {}.compare_by_identity
170
- @key_names = {}.compare_by_identity # schemas forced to "string" (property names)
170
+ @key_names = Hash.new { |h, type| h[type] = {}.compare_by_identity } # property name schemas, by forced type
171
171
  @counter = 0
172
172
  end
173
173
 
@@ -193,6 +193,11 @@ module YAMLSchema
193
193
  str.dump
194
194
  end
195
195
 
196
+ # A Ruby literal for a property name, which is a String or a Symbol.
197
+ def name_lit name
198
+ Symbol === name ? name.inspect : lit(name)
199
+ end
200
+
196
201
  def next_name prefix
197
202
  @counter += 1
198
203
  "#{prefix}#{@counter}"
@@ -207,7 +212,7 @@ module YAMLSchema
207
212
  # +schema+ (alias resolution, tag lookup, and type checks). Schemas are
208
213
  # memoized by identity so shared sub-schemas share a method.
209
214
  def schema_method schema, path, forced_type = nil
210
- memo = forced_type ? @key_names : @names
215
+ memo = forced_type ? @key_names[forced_type] : @names
211
216
  return memo[schema] if memo.key?(schema)
212
217
 
213
218
  name = memo[schema] = next_name("_v")
@@ -314,11 +319,21 @@ module YAMLSchema
314
319
 
315
320
  if schema["properties"]
316
321
  properties = schema["properties"]
317
- key_meth = schema_method(schema["propertyNames"] || EMPTY_SCHEMA, "#{path}/propertyNames", "string")
322
+ key_schema = schema["propertyNames"] || EMPTY_SCHEMA
323
+ key_meth = schema_method(key_schema, "#{path}/propertyNames", "string")
324
+ sym_key_meth = schema_method(key_schema, "#{path}/propertyNames", "symbol")
318
325
 
319
326
  unknown = if schema["additionalProperties"]
320
327
  meth = schema_method(schema["additionalProperties"], "#{path}/additionalProperties")
321
- child_call(meth, "val", "key.value")
328
+ src_unknown = +""
329
+ unless Validator.symbol_keys?(schema["propertyNames"])
330
+ src_unknown << <<~RUBY
331
+ if sym
332
+ return make_error(UnexpectedValue, "expected string, got symbol", path)
333
+ end
334
+ RUBY
335
+ end
336
+ src_unknown << child_call(meth, "val", "key.value")
322
337
  else
323
338
  <<~RUBY
324
339
  path.push(key.value)
@@ -337,7 +352,8 @@ module YAMLSchema
337
352
  val = children[i + 1]
338
353
  i += 2
339
354
 
340
- err = #{key_meth}(key, aliases, path, allow_aliases)
355
+ sym = symbol_key(key)
356
+ err = sym ? #{sym_key_meth}(key, aliases, path, allow_aliases) : #{key_meth}(key, aliases, path, allow_aliases)
341
357
  return err if err
342
358
 
343
359
  RUBY
@@ -345,15 +361,15 @@ module YAMLSchema
345
361
  if properties.empty?
346
362
  src << indent(unknown, 2)
347
363
  else
348
- src << " case key.value\n"
364
+ src << " case sym || key.value\n"
349
365
  properties.each_with_index do |(name, sub), idx|
350
366
  meth = schema_method(sub, "#{path}/properties/#{name}")
351
- src << " when #{lit name}\n"
367
+ src << " when #{name_lit name}\n"
352
368
  src << " if #{seen[idx]}\n"
353
369
  src << indent(unknown, 6)
354
370
  src << " else\n"
355
371
  src << " #{seen[idx]} = true\n"
356
- src << indent(child_call(meth, "val", lit(name)), 6)
372
+ src << indent(child_call(meth, "val", Symbol === name ? "key.value" : lit(name)), 6)
357
373
  src << " end\n"
358
374
  end
359
375
  src << " else\n"
@@ -367,7 +383,7 @@ module YAMLSchema
367
383
  unless checks.empty?
368
384
  src << "\nmissing = nil\n"
369
385
  checks.each do |name, idx|
370
- src << "(missing ||= []) << #{lit name.dump} unless #{seen[idx]}\n"
386
+ src << "(missing ||= []) << #{lit Validator.name_dump(name)} unless #{seen[idx]}\n"
371
387
  end
372
388
  src << <<~RUBY
373
389
  if missing
@@ -377,6 +393,12 @@ module YAMLSchema
377
393
  end
378
394
  else
379
395
  key_meth = schema_method(EMPTY_SCHEMA, "#{path}/propertyNames", "string")
396
+ key_call = if Validator.symbol_keys?(schema["propertyNames"])
397
+ sym_key_meth = schema_method(EMPTY_SCHEMA, "#{path}/propertyNames", "symbol")
398
+ "(symbol_key(key) ? #{sym_key_meth}(key, aliases, path, allow_aliases) : #{key_meth}(key, aliases, path, allow_aliases))"
399
+ else
400
+ "#{key_meth}(key, aliases, path, allow_aliases)"
401
+ end
380
402
  meth = schema_method(schema["items"], "#{path}/items")
381
403
  src << <<~RUBY
382
404
  while i < len
@@ -384,7 +406,7 @@ module YAMLSchema
384
406
  val = children[i + 1]
385
407
  i += 2
386
408
 
387
- err = #{key_meth}(key, aliases, path, allow_aliases)
409
+ err = #{key_call}
388
410
  return err if err
389
411
 
390
412
  #{indent(child_call(meth, "val", "key.value"), 2)}end
@@ -72,6 +72,22 @@ module YAMLSchema
72
72
  end
73
73
  end
74
74
 
75
+ # If +key+ is a mapping key that Psych loads as a Symbol (a plain, untagged
76
+ # scalar like <tt>:name</tt> or <tt>:"two words"</tt>), return that Symbol.
77
+ # Otherwise return nil.
78
+ def symbol_key key
79
+ return unless key.scalar? && !key.quoted && key.tag.nil?
80
+
81
+ value = key.value
82
+ return unless extract_type(value) == :symbol
83
+
84
+ if (m = value.match(/\A:(["'])(.*)\1\z/m))
85
+ m[2].to_sym
86
+ else
87
+ value[1..].to_sym
88
+ end
89
+ end
90
+
75
91
  def make_error klass, msg, path
76
92
  ex = klass.new msg + " path: /#{path.join("/")}"
77
93
  ex.set_backtrace caller
data/lib/yaml-schema.rb CHANGED
@@ -3,7 +3,7 @@
3
3
  require "yaml-schema/runtime"
4
4
 
5
5
  module YAMLSchema
6
- VERSION = "1.3.0"
6
+ VERSION = "1.3.1"
7
7
 
8
8
  class Pointer
9
9
  include Enumerable
@@ -100,6 +100,20 @@ module YAMLSchema
100
100
  INSTANCE = new.freeze
101
101
 
102
102
  VALID_TYPES = %w[object array string integer float boolean null date time symbol].freeze
103
+ KEY_TYPES = %w[string symbol].freeze
104
+
105
+ ##
106
+ # Whether a +propertyNames+ schema lets keys that aren't listed in
107
+ # +properties+ be Symbols.
108
+ def self.symbol_keys? key_schema
109
+ !!key_schema && Array(key_schema["type"]).include?("symbol")
110
+ end
111
+
112
+ ##
113
+ # How a property name is written in error messages.
114
+ def self.name_dump name
115
+ Symbol === name ? name.inspect : name.dump
116
+ end
103
117
 
104
118
  ##
105
119
  # Given a particular schema, validate that the node conforms to the
@@ -171,7 +185,7 @@ module YAMLSchema
171
185
  if schema["properties"]
172
186
  raise InvalidSchema, "\"properties\" must be a Hash#{_sp path}" unless Hash === schema["properties"]
173
187
  schema["properties"].each do |key, sub|
174
- raise InvalidSchema, "property name must be a String#{_sp path}" unless String === key
188
+ raise InvalidSchema, "property name must be a String or Symbol#{_sp path}" unless String === key || Symbol === key
175
189
  validate_schema!(sub, "#{path}/#{key}")
176
190
  end
177
191
  elsif schema["items"]
@@ -192,13 +206,18 @@ module YAMLSchema
192
206
 
193
207
  if schema["propertyNames"]
194
208
  raise InvalidSchema, "\"propertyNames\" must be a Hash#{_sp path}" unless Hash === schema["propertyNames"]
195
- validate_schema!(schema["propertyNames"], "#{path}/propertyNames") if schema["propertyNames"]["type"]
209
+ if (key_types = schema["propertyNames"]["type"])
210
+ validate_schema!(schema["propertyNames"], "#{path}/propertyNames")
211
+ unless (Array(key_types) - KEY_TYPES).empty?
212
+ raise InvalidSchema, "propertyNames type must be \"string\" or \"symbol\"#{_sp path}"
213
+ end
214
+ end
196
215
  end
197
216
 
198
217
  if schema["required"]
199
218
  raise InvalidSchema, "\"required\" must be an Array#{_sp path}" unless Array === schema["required"]
200
219
  schema["required"].each do |r|
201
- raise InvalidSchema, "\"required\" entries must be Strings#{_sp path}" unless String === r
220
+ raise InvalidSchema, "\"required\" entries must be Strings or Symbols#{_sp path}" unless String === r || Symbol === r
202
221
  end
203
222
  end
204
223
  end
@@ -288,15 +307,18 @@ module YAMLSchema
288
307
  properties = schema["properties"].dup
289
308
  key_restriction = schema["propertyNames"] || {}
290
309
  node.children.each_slice(2) do |key, val|
291
- valid = _validate("string", key_restriction, key, valid, aliases, path, allow_aliases)
310
+ sym = symbol_key(key)
311
+ valid = _validate(sym ? "symbol" : "string", key_restriction, key, valid, aliases, path, allow_aliases)
292
312
 
293
313
  return valid if valid.exception
294
314
 
295
- sub_schema = properties.delete(key.value) {
296
- if schema["additionalProperties"]
297
- schema["additionalProperties"]
298
- else
315
+ sub_schema = properties.delete(sym || key.value) {
316
+ if !schema["additionalProperties"]
299
317
  return make_error UnexpectedProperty, "unknown property #{key.value.dump}", path + [key.value]
318
+ elsif sym && !Validator.symbol_keys?(schema["propertyNames"])
319
+ return make_error UnexpectedValue, "expected string, got symbol", path
320
+ else
321
+ schema["additionalProperties"]
300
322
  end
301
323
  }
302
324
 
@@ -308,14 +330,16 @@ module YAMLSchema
308
330
  if schema["required"]
309
331
  missing_fields = properties.keys & schema["required"]
310
332
  unless missing_fields.empty?
311
- return make_error MissingRequiredField, "missing fields #{missing_fields.map(&:dump).join(" ")}", path
333
+ return make_error MissingRequiredField, "missing fields #{missing_fields.map { |f| Validator.name_dump(f) }.join(" ")}", path
312
334
  end
313
335
  end
314
336
  else
315
337
  if schema["items"]
316
338
  sub_schema = schema["items"]
339
+ symbol_keys = Validator.symbol_keys?(schema["propertyNames"])
317
340
  node.children.each_slice(2) do |key, val|
318
- valid = _validate("string", {}, key, valid, aliases, path, allow_aliases)
341
+ key_type = symbol_keys && symbol_key(key) ? "symbol" : "string"
342
+ valid = _validate(key_type, {}, key, valid, aliases, path, allow_aliases)
319
343
  return valid if valid.exception
320
344
  valid = _validate(sub_schema["type"], sub_schema, val, valid, aliases, path + [key.value], allow_aliases)
321
345
  return valid if valid.exception
@@ -57,6 +57,27 @@ module YAMLSchema
57
57
  },
58
58
  },
59
59
  },
60
+ {
61
+ "type" => "object",
62
+ "properties" => {
63
+ name: { "type" => "string" },
64
+ "label" => { "type" => "string" },
65
+ :"two words" => { "type" => "integer" },
66
+ },
67
+ "required" => [:name],
68
+ },
69
+ {
70
+ "type" => "object",
71
+ "properties" => { id: { "type" => "integer" } },
72
+ "additionalProperties" => { "type" => "string" },
73
+ "propertyNames" => { "type" => ["string", "symbol"], "pattern" => /\A:?[a-z]+\z/ },
74
+ },
75
+ {
76
+ "type" => "object",
77
+ "properties" => { id: { "type" => "integer" } },
78
+ "additionalProperties" => { "type" => "string" },
79
+ },
80
+ { "type" => "object", "items" => { "type" => "integer" }, "propertyNames" => { "type" => "symbol" } },
60
81
  ]
61
82
 
62
83
  DOCUMENTS = [
@@ -71,6 +92,9 @@ module YAMLSchema
71
92
  "users:\n- name: a\n meta:\n x: 1\n y: z\n- name: b", "users:\n- meta: {}",
72
93
  "users:\n- name: a\n meta:\n x: [1]",
73
94
  "a: &x 1\nb: *x", "x: &x\n- 1\ny: *x",
95
+ ":name: bob", ":name: bob\nlabel: x", "label: x", "name: bob\n:label: x", "':name': bob",
96
+ ":name: bob\n:\"two words\": 1", ":name: bob\n:name: again", ":name: 1", ":id: 1\n:other: x",
97
+ ":id: 1\nother: x", ":id: 1\n:Other: x", ":a: 1\n:b: 2", "!ruby/symbol a: 1",
74
98
  ]
75
99
 
76
100
  def outcome
@@ -881,5 +881,106 @@ bar: *1
881
881
  end
882
882
  end
883
883
  end
884
+
885
+ class SymbolKeyTest < Minitest::Test
886
+ PERSON = {
887
+ "type" => "object",
888
+ "properties" => {
889
+ name: { "type" => "string" },
890
+ "label" => { "type" => "string" },
891
+ :"two words" => { "type" => "integer" },
892
+ },
893
+ "required" => [:name],
894
+ }.freeze
895
+
896
+ def node yaml
897
+ Psych.parse(yaml).children.first
898
+ end
899
+
900
+ def test_symbol_properties_match_symbol_keys
901
+ yaml = Psych.dump({ name: "bob", "label" => "x", :"two words" => 1 })
902
+ assert Validator.validate(PERSON, node(yaml))
903
+ end
904
+
905
+ def test_symbol_property_validates_its_value
906
+ err = assert_raises(UnexpectedValue) { Validator.validate(PERSON, node(":name: 1")) }
907
+ assert_equal "expected string, got integer path: /:name", err.message
908
+ end
909
+
910
+ def test_symbol_property_does_not_match_string_key
911
+ err = assert_raises(UnexpectedProperty) { Validator.validate(PERSON, node("name: bob")) }
912
+ assert_equal "unknown property \"name\" path: /name", err.message
913
+ end
914
+
915
+ def test_string_property_does_not_match_symbol_key
916
+ err = assert_raises(UnexpectedProperty) { Validator.validate(PERSON, node(":name: bob\n:label: x")) }
917
+ assert_equal "unknown property \":label\" path: /:label", err.message
918
+ end
919
+
920
+ def test_quoted_symbol_looking_key_is_a_string
921
+ err = assert_raises(UnexpectedProperty) { Validator.validate(PERSON, node("':name': bob")) }
922
+ assert_equal "unknown property \":name\" path: /:name", err.message
923
+ end
924
+
925
+ def test_quoted_symbol_key
926
+ assert Validator.validate(PERSON, node(":name: bob\n:\"two words\": 1"))
927
+ end
928
+
929
+ def test_missing_required_symbol_property
930
+ err = assert_raises(MissingRequiredField) { Validator.validate(PERSON, node("label: x")) }
931
+ assert_equal "missing fields :name path: /", err.message
932
+ end
933
+
934
+ def test_additional_symbol_keys_need_property_names_type
935
+ schema = {
936
+ "type" => "object",
937
+ "properties" => { id: { "type" => "integer" } },
938
+ "additionalProperties" => { "type" => "string" },
939
+ }
940
+ err = assert_raises(UnexpectedValue) { Validator.validate(schema, node(":id: 1\n:other: x")) }
941
+ assert_equal "expected string, got symbol path: /", err.message
942
+
943
+ schema = schema.merge("propertyNames" => { "type" => ["string", "symbol"] })
944
+ assert Validator.validate(schema, node(":id: 1\n:other: x\nplain: y"))
945
+ end
946
+
947
+ def test_property_names_pattern_applies_to_symbol_keys
948
+ schema = {
949
+ "type" => "object",
950
+ "properties" => { id: { "type" => "integer" } },
951
+ "additionalProperties" => { "type" => "string" },
952
+ "propertyNames" => { "type" => "symbol", "pattern" => /\A:[a-z]+\z/ },
953
+ }
954
+ assert Validator.validate(schema, node(":id: 1\n:other: x"))
955
+ assert_raises(InvalidPattern) { Validator.validate(schema, node(":id: 1\n:Other: x")) }
956
+ end
957
+
958
+ def test_items_object_with_symbol_keys
959
+ schema = { "type" => "object", "items" => { "type" => "integer" } }
960
+ err = assert_raises(UnexpectedValue) { Validator.validate(schema, node(Psych.dump({ a: 1 }))) }
961
+ assert_equal "expected string, got symbol path: /", err.message
962
+
963
+ schema = schema.merge("propertyNames" => { "type" => "symbol" })
964
+ assert Validator.validate(schema, node(Psych.dump({ a: 1, b: 2 })))
965
+ end
966
+
967
+ def test_property_names_type_must_be_string_or_symbol
968
+ schema = { "type" => "object", "items" => { "type" => "integer" }, "propertyNames" => { "type" => "integer" } }
969
+ err = assert_raises(InvalidSchema) { Validator.validate(schema, node("a: 1")) }
970
+ assert_equal "propertyNames type must be \"string\" or \"symbol\"", err.message
971
+ end
972
+
973
+ def test_property_names_must_be_strings_or_symbols
974
+ schema = { "type" => "object", "properties" => { 1 => { "type" => "integer" } } }
975
+ err = assert_raises(InvalidSchema) { Validator::INSTANCE.validate_schema!(schema) }
976
+ assert_equal "property name must be a String or Symbol", err.message
977
+ end
978
+
979
+ def test_required_entries_must_be_strings_or_symbols
980
+ schema = { "type" => "object", "properties" => { name: { "type" => "string" } }, "required" => [1] }
981
+ err = assert_raises(InvalidSchema) { Validator::INSTANCE.validate_schema!(schema) }
982
+ assert_equal "\"required\" entries must be Strings or Symbols", err.message
983
+ end
984
+ end
884
985
  end
885
986
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: yaml-schema
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.3.0
4
+ version: 1.3.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Aaron Patterson