yaml-schema 1.0.0

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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 701e8ba71eb1d60990092ad38d7dca6f3954f4bd70ec1a5f292ed9eb244a7aef
4
+ data.tar.gz: a930db9675bdfe08fe078431e3d8ded4104ee427694641e7d88961aed3cd9e16
5
+ SHA512:
6
+ metadata.gz: c943fc76323ec4ad6159939b00773537c76a360ff93bac4dad0e2f1bda94dd814a55437f60e80df6fa37e8d99b4a890a6c150c8d393f10c309d6a4899ee73976
7
+ data.tar.gz: 4bc0b0c28f916e2fb86a43390303714ca19d290d6d5dbf4561a189cfeb6da99b6d01e76d579e3d8b4b6a0aee835173aac31ada6cc0401e6fd41005a80a3168a4
data/Gemfile ADDED
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 Aaron Patterson
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,104 @@
1
+ # yaml-schema
2
+
3
+ A library for validating YAML documents against a schema.
4
+
5
+ ## Overview
6
+
7
+ `yaml-schema` is a schema validation library that allows you to enforce type safety and structural constraints on YAML files. It works directly with an AST (which can be obtained from Psych) representation to provide strict validation without implicit type coercion.
8
+
9
+ ## Usage
10
+
11
+ ### Basic Validation
12
+
13
+ ```ruby
14
+ require 'yaml-schema'
15
+
16
+ schema = {
17
+ type: 'object',
18
+ properties: {
19
+ name: { type: 'string' },
20
+ age: { type: 'integer' },
21
+ active: { type: 'boolean' }
22
+ }
23
+ }
24
+
25
+ yaml_string = <<~YAML
26
+ name: "John Doe"
27
+ age: 30
28
+ active: true
29
+ YAML
30
+
31
+ node = Psych.parse(yaml_string)
32
+ YAMLSchema::Validator.validate(schema, node.children.first)
33
+ ```
34
+
35
+ ### Supported Types
36
+
37
+ - **string** - Scalar string values
38
+ - **integer** - Numeric integers
39
+ - **boolean** - Boolean values (true/false)
40
+ - **null** - Null values
41
+ - **array** - Sequences with optional constraints
42
+ - `items` - Schema for all array elements
43
+ - `prefixItems` - Fixed-position tuple validation
44
+ - `maxItems` - Maximum array length
45
+ - **object** - Mappings with properties
46
+ - `properties` - Named properties with schemas
47
+ - `items` - Schema for arbitrary key-value pairs
48
+ - `tag` - Optional YAML tag requirement
49
+
50
+ ### Type Unions
51
+
52
+ Specify multiple valid types for a field:
53
+
54
+ ```ruby
55
+ schema = {
56
+ type: 'object',
57
+ properties: {
58
+ value: { type: ['null', 'string'] }
59
+ }
60
+ }
61
+ ```
62
+
63
+ ### Nested Objects and Arrays
64
+
65
+ ```ruby
66
+ schema = {
67
+ type: 'object',
68
+ properties: {
69
+ users: {
70
+ type: 'array',
71
+ items: {
72
+ type: 'object',
73
+ properties: {
74
+ name: { type: 'string' },
75
+ tags: {
76
+ type: 'array',
77
+ items: { type: 'string' }
78
+ }
79
+ }
80
+ }
81
+ }
82
+ }
83
+ }
84
+ ```
85
+
86
+ ## Error Handling
87
+
88
+ Validation errors include detailed path information:
89
+
90
+ ```ruby
91
+ begin
92
+ YAMLSchema::Validator.validate(schema, node)
93
+ rescue YAMLSchema::Validator::UnexpectedType => e
94
+ puts e.message # e.g., "Expected integer at root -> age"
95
+ end
96
+ ```
97
+
98
+ ### Error Types
99
+
100
+ - `UnexpectedType` - Node doesn't match expected type
101
+ - `UnexpectedProperty` - Object has unexpected properties
102
+ - `UnexpectedTag` - YAML tag doesn't match schema
103
+ - `UnexpectedValue` - Value doesn't match constraints
104
+ - `InvalidSchema` - Schema definition is invalid
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ require 'rake/testtask'
2
+ require "bundler"
3
+ Bundler::GemHelper.install_tasks
4
+
5
+ Rake::TestTask.new(:test) do |t|
6
+ t.libs << "test"
7
+ t.libs << "lib"
8
+ t.test_files = FileList["test/**/*_test.rb"]
9
+ t.warning = true
10
+ end
11
+
12
+ task :default => :test
@@ -0,0 +1,212 @@
1
+ # frozen_string_literal: true
2
+
3
+ module YAMLSchema
4
+ class Validator
5
+ class Exception < StandardError; end
6
+ class UnexpectedType < Exception; end
7
+ class UnexpectedProperty < Exception; end
8
+ class UnexpectedTag < Exception; end
9
+ class UnexpectedValue < Exception; end
10
+ class InvalidSchema < Exception; end
11
+
12
+ Valid = Struct.new(:exception).new.freeze
13
+
14
+ ##
15
+ # Given a particular schema, validate that the node conforms to the
16
+ # schema. Raises an exception if it is invalid
17
+ def self.validate(schema, node)
18
+ INSTANCE.validate schema, node
19
+ end
20
+
21
+ module NodeInfo # :nodoc:
22
+ def self.read_tag(node)
23
+ node.tag
24
+ end
25
+ end
26
+
27
+ def initialize(node_info = NodeInfo)
28
+ @node_info = node_info
29
+ end
30
+
31
+ INSTANCE = new.freeze
32
+
33
+ ##
34
+ # Given a particular schema, validate that the node conforms to the
35
+ # schema. Raises an exception if it is invalid
36
+ def validate(schema, node)
37
+ val = _validate(schema["type"], schema, node, Valid, {}, ["root"])
38
+ if val.exception
39
+ raise val
40
+ else
41
+ true
42
+ end
43
+ end
44
+
45
+ ##
46
+ # Given a particular schema, validate that the node conforms to the
47
+ # schema. Returns an error object if the node is invalid, otherwise false.
48
+ def invalid?(schema, node)
49
+ res = _validate(schema["type"], schema, node, Valid, {}, ["root"])
50
+ if Valid == res
51
+ false
52
+ else
53
+ res
54
+ end
55
+ end
56
+
57
+ private
58
+
59
+ def make_error(klass, msg, path)
60
+ ex = klass.new msg + " path: #{path.join(" -> ")}"
61
+ ex.set_backtrace caller
62
+ ex
63
+ end
64
+
65
+ def _validate(type, schema, node, valid, aliases, path)
66
+ return valid if valid.exception
67
+
68
+ if node.anchor
69
+ if node.alias?
70
+ node = aliases[node.anchor]
71
+ else
72
+ aliases[node.anchor] = node
73
+ end
74
+ end
75
+
76
+ tag = @node_info.read_tag(node)
77
+
78
+ if Array === type
79
+ v = valid
80
+ type.each do |t|
81
+ v = _validate t, schema, node, valid, aliases, path
82
+ unless v.exception
83
+ break
84
+ end
85
+ end
86
+ valid = v
87
+ return valid
88
+ end
89
+
90
+ if type == "object"
91
+ if tag != schema["tag"]
92
+ if schema["tag"]
93
+ if node.tag
94
+ return make_error UnexpectedTag, "expected tag #{schema["tag"].dump}, but got #{node.tag.dump}", path
95
+ else
96
+ return make_error UnexpectedTag, "expected tag #{schema["tag"].dump}, but none specified", path
97
+ end
98
+ else
99
+ return make_error UnexpectedTag, "expected no tag, but got #{node.tag.dump}", path
100
+ end
101
+ end
102
+ else
103
+ if tag
104
+ return make_error UnexpectedTag, "expected no tag, but got #{node.tag.dump}", path
105
+ end
106
+ end
107
+
108
+ case type
109
+ when "object"
110
+ unless node.mapping?
111
+ return make_error UnexpectedType, "expected Mapping, got #{node.class.name.dump}", path
112
+ end
113
+ if schema["properties"]
114
+ properties = schema["properties"].dup
115
+ node.children.each_slice(2) do |key, val|
116
+ valid = _validate("string", {}, key, valid, aliases, path)
117
+
118
+ return valid if valid.exception
119
+
120
+ sub_schema = properties.delete(key.value) {
121
+ return make_error UnexpectedProperty, "unknown property #{key.value.dump}", path
122
+ }
123
+ valid = _validate(sub_schema["type"], sub_schema, val, valid, aliases, path + [key.value])
124
+
125
+ return valid if valid.exception
126
+ end
127
+ else
128
+ if schema["items"]
129
+ sub_schema = schema["items"]
130
+ node.children.each_slice(2) do |key, val|
131
+ valid = _validate("string", {}, key, valid, aliases, path)
132
+ return valid if valid.exception
133
+ valid = _validate(sub_schema["type"], sub_schema, val, valid, aliases, path + [key.value])
134
+ return valid if valid.exception
135
+ end
136
+ else
137
+ raise InvalidSchema, "objects must specify items or properties"
138
+ end
139
+ end
140
+ when "string"
141
+ unless node.scalar?
142
+ return make_error UnexpectedType, "expected Scalar, got #{node.class.name.dump}", path
143
+ end
144
+
145
+ unless node.quoted || node.tag == "!str"
146
+ if node.value == "false" || node.value == "true"
147
+ return make_error UnexpectedValue, "expected string, got boolean", path
148
+ end
149
+
150
+ if node.value == ""
151
+ return make_error UnexpectedValue, "expected string, got null", path
152
+ end
153
+
154
+ if node.value.match?(/^[-+]?(?:0|[1-9](?:[0-9]|,[0-9]|_[0-9])*)$/)
155
+ return make_error UnexpectedValue, "expected string, got integer", path
156
+ end
157
+ end
158
+ when "array"
159
+ unless node.sequence?
160
+ return make_error UnexpectedType, "expected Sequence, got #{node.class.name.dump}", path
161
+ end
162
+
163
+ if schema["maxItems"] && node.children.length > schema["maxItems"]
164
+ return make_error UnexpectedValue, "expected maximum #{schema["maxItems"]} items, but found #{node.children.length}", path
165
+ end
166
+
167
+ if schema["items"]
168
+ node.children.each_with_index { |item, i|
169
+ sub_schema = schema["items"]
170
+ valid = _validate sub_schema["type"], sub_schema, item, valid, aliases, path + [i]
171
+ }
172
+ elsif schema["prefixItems"]
173
+ node.children.each_with_index { |item, i|
174
+ sub_schema = schema["prefixItems"][i]
175
+ valid = _validate sub_schema["type"], sub_schema, item, valid, aliases, path + [i]
176
+ }
177
+ else
178
+ raise NotImplementedError
179
+ end
180
+ when "null"
181
+ unless node.scalar?
182
+ return make_error UnexpectedType, "expected Scalar, got #{node.class.name.dump}", path
183
+ end
184
+
185
+ unless node.value == ""
186
+ return make_error UnexpectedValue, "expected empty string, got #{node.value.dump}", path
187
+ end
188
+ when "boolean"
189
+ unless node.scalar?
190
+ return make_error UnexpectedType, "expected Scalar, got #{node.class.name.dump}", path
191
+ end
192
+ unless node.value == "false" || node.value == "true"
193
+ return make_error UnexpectedValue, "expected 'true' or 'false' for boolean", path
194
+ end
195
+ when "integer"
196
+ unless node.scalar?
197
+ return make_error UnexpectedType, "expected Scalar, got #{node.class.name.dump}", path
198
+ end
199
+ if node.quoted
200
+ return make_error UnexpectedValue, "expected integer, got string", path
201
+ end
202
+ unless node.value.match?(/^[-+]?(?:0|[1-9](?:[0-9]|,[0-9]|_[0-9])*)$/)
203
+ return make_error UnexpectedValue, "expected integer, got string", path
204
+ end
205
+ else
206
+ raise "unknown type #{schema["type"]}"
207
+ end
208
+
209
+ valid
210
+ end
211
+ end
212
+ end
@@ -0,0 +1,405 @@
1
+ require "minitest/autorun"
2
+ require "yaml-schema"
3
+ require "psych"
4
+
5
+ module YAMLSchema
6
+ class Validator
7
+ class ErrorTest < Minitest::Test
8
+ def test_missing_tag
9
+ ast = Psych.parse("foo: bar")
10
+ assert_raises UnexpectedTag do
11
+ Validator.validate({
12
+ "type" => "object",
13
+ "tag" => "aaron"
14
+ }, ast.children.first)
15
+ end
16
+ end
17
+
18
+ def test_wrong_tag
19
+ ast = Psych.parse("--- !lolol\nfoo: bar")
20
+ ex = assert_raises UnexpectedTag do
21
+ Validator.validate({
22
+ "type" => "object",
23
+ "tag" => "aaron"
24
+ }, ast.children.first)
25
+ end
26
+ assert_match(/lolol/, ex.message)
27
+ end
28
+
29
+ def test_wrong_type
30
+ ast = Psych.parse("foo: bar")
31
+ ex = assert_raises UnexpectedType do
32
+ Validator.validate({
33
+ "type" => "string",
34
+ }, ast.children.first)
35
+ end
36
+ assert_match(/Scalar/, ex.message)
37
+
38
+ ast = Psych.parse("foo")
39
+ ex = assert_raises UnexpectedType do
40
+ Validator.validate({
41
+ "type" => "object",
42
+ }, ast.children.first)
43
+ end
44
+ assert_match(/Mapping/, ex.message)
45
+
46
+ ast = Psych.parse("foo")
47
+ ex = assert_raises UnexpectedType do
48
+ Validator.validate({
49
+ "type" => "array",
50
+ }, ast.children.first)
51
+ end
52
+ assert_match(/Sequence/, ex.message)
53
+ end
54
+
55
+ def test_null_error
56
+ ast = Psych.parse("foo")
57
+ ex = assert_raises UnexpectedValue do
58
+ Validator.validate({
59
+ "type" => "null",
60
+ }, ast.children.first)
61
+ end
62
+ assert_match(/empty string/, ex.message)
63
+
64
+ ast = Psych.parse("foo: bar")
65
+ ex = assert_raises UnexpectedType do
66
+ Validator.validate({
67
+ "type" => "null",
68
+ }, ast.children.first)
69
+ end
70
+ assert_match(/Scalar/, ex.message)
71
+ end
72
+
73
+ def test_boolean_error
74
+ ast = Psych.parse("foo")
75
+ ex = assert_raises UnexpectedValue do
76
+ Validator.validate({
77
+ "type" => "boolean",
78
+ }, ast.children.first)
79
+ end
80
+ assert_match(/true/, ex.message)
81
+
82
+ ast = Psych.parse("foo: bar")
83
+ ex = assert_raises UnexpectedType do
84
+ Validator.validate({
85
+ "type" => "boolean",
86
+ }, ast.children.first)
87
+ end
88
+ assert_match(/Scalar/, ex.message)
89
+ end
90
+
91
+ def test_integer_error
92
+ ast = Psych.parse("foo")
93
+ ex = assert_raises UnexpectedValue do
94
+ Validator.validate({
95
+ "type" => "integer",
96
+ }, ast.children.first)
97
+ end
98
+ assert_match(/expected integer/, ex.message)
99
+
100
+ ast = Psych.parse("'foo'")
101
+ ex = assert_raises UnexpectedValue do
102
+ Validator.validate({
103
+ "type" => "integer",
104
+ }, ast.children.first)
105
+ end
106
+ assert_match(/expected integer/, ex.message)
107
+
108
+ ast = Psych.parse("foo: bar")
109
+ ex = assert_raises UnexpectedType do
110
+ Validator.validate({
111
+ "type" => "integer",
112
+ }, ast.children.first)
113
+ end
114
+ assert_match(/Scalar/, ex.message)
115
+ end
116
+
117
+ def test_error_in_array_sequence
118
+ ast = Psych.parse("- foo\n- 1")
119
+ assert_raises UnexpectedValue do
120
+ Validator.validate({
121
+ "type" => "array",
122
+ "items" => { "type" => "integer" }
123
+ }, ast.children.first)
124
+ end
125
+
126
+ ast = Psych.parse("- 1\n- foo")
127
+ assert_raises UnexpectedValue do
128
+ Validator.validate({
129
+ "type" => "array",
130
+ "items" => { "type" => "integer" }
131
+ }, ast.children.first)
132
+ end
133
+ end
134
+
135
+ def test_error_in_array_sequence_prefixItems
136
+ ast = Psych.parse("- foo\n- 1")
137
+ assert_raises UnexpectedValue do
138
+ Validator.validate({
139
+ "type" => "array",
140
+ "prefixItems" => [
141
+ { "type" => "integer" },
142
+ { "type" => "integer" },
143
+ ]
144
+ }, ast.children.first)
145
+ end
146
+
147
+ ast = Psych.parse("- foo\n- 1")
148
+ assert_raises UnexpectedValue do
149
+ Validator.validate({
150
+ "type" => "array",
151
+ "prefixItems" => [
152
+ { "type" => "string" },
153
+ { "type" => "string" },
154
+ ]
155
+ }, ast.children.first)
156
+ end
157
+ end
158
+
159
+ def test_invalid_string
160
+ ast = Psych.parse("1")
161
+ assert_raises UnexpectedValue do
162
+ Validator.validate({
163
+ "type" => "string",
164
+ }, ast.children.first)
165
+ end
166
+
167
+ ast = Psych.parse("false")
168
+ assert_raises UnexpectedValue do
169
+ Validator.validate({
170
+ "type" => "string",
171
+ }, ast.children.first)
172
+ end
173
+
174
+ ast = Psych.parse("true")
175
+ assert_raises UnexpectedValue do
176
+ Validator.validate({
177
+ "type" => "string",
178
+ }, ast.children.first)
179
+ end
180
+
181
+ ast = Psych.parse("--- ")
182
+ assert_raises UnexpectedValue do
183
+ Validator.validate({
184
+ "type" => "string",
185
+ }, ast.children.first)
186
+ end
187
+ end
188
+
189
+ def test_valid_quoted_string
190
+ ast = Psych.parse("'1'")
191
+ assert Validator.validate({
192
+ "type" => "string",
193
+ }, ast.children.first)
194
+
195
+ ast = Psych.parse("'false'")
196
+ assert Validator.validate({
197
+ "type" => "string",
198
+ }, ast.children.first)
199
+
200
+ ast = Psych.parse("'true'")
201
+ assert Validator.validate({
202
+ "type" => "string",
203
+ }, ast.children.first)
204
+
205
+ ast = Psych.parse("--- ''")
206
+ assert Validator.validate({
207
+ "type" => "string",
208
+ }, ast.children.first)
209
+ end
210
+
211
+ def test_multiple_valid
212
+ ast = Psych.parse("'1'")
213
+ assert Validator.validate({
214
+ "type" => ["string", "integer"],
215
+ }, ast.children.first)
216
+ end
217
+
218
+ def test_multiple_invalid
219
+ ast = Psych.parse("'1'")
220
+ assert_raises UnexpectedValue do
221
+ Validator.validate({
222
+ "type" => ["null", "integer"],
223
+ }, ast.children.first)
224
+ end
225
+ end
226
+
227
+ def test_multiple_valid_array_type
228
+ ast = Psych.parse("- '1'")
229
+ assert Validator.validate({
230
+ "type" => ["null", "array"],
231
+ "items" => { "type" => "string" }
232
+ }, ast.children.first)
233
+ end
234
+
235
+ def test_multiple_invalid_array_type
236
+ ast = Psych.parse("- '1'")
237
+ assert_raises UnexpectedValue do
238
+ Validator.validate({
239
+ "type" => ["null", "array"],
240
+ "items" => { "type" => "integer" }
241
+ }, ast.children.first)
242
+ end
243
+
244
+ ast = Psych.parse("- 1\n- '123'")
245
+ assert_raises UnexpectedValue do
246
+ Validator.validate({
247
+ "type" => ["null", "array"],
248
+ "items" => { "type" => "integer" }
249
+ }, ast.children.first)
250
+ end
251
+ end
252
+
253
+ def test_array_mixed_types
254
+ ast = Psych.parse(<<-eoyml)
255
+ ---
256
+ segments:
257
+ - 3
258
+ - 0
259
+ - 0
260
+ - beta3
261
+ eoyml
262
+ assert Validator.validate({
263
+ "type" => "object",
264
+ "properties" => {
265
+ "segments" => {
266
+ "type" => "array",
267
+ "items" => { "type" => ["integer", "string"] },
268
+ }
269
+ }
270
+ }, ast.children.first)
271
+ end
272
+
273
+ def test_nullable_with_tag
274
+ schema = {
275
+ "type" => ["null", "object"],
276
+ "tag" => "!foo",
277
+ "properties" => {
278
+ "segments" => { "type" => "string" }
279
+ }
280
+ }
281
+
282
+ ast = Psych.parse(<<-eoyml)
283
+ --- !foo
284
+ segments: foo
285
+ eoyml
286
+
287
+ assert Validator.validate(schema, ast.children.first)
288
+
289
+ ast = Psych.parse("---")
290
+
291
+ assert Validator.validate(schema, ast.children.first)
292
+ end
293
+
294
+ def test_array_max_items
295
+ ast = Psych.parse("- 0\n- 1")
296
+ assert Validator.validate({
297
+ "type" => "array",
298
+ "items" => { "type" => "integer" },
299
+ "maxItems" => 2,
300
+ }, ast.children.first)
301
+
302
+ ast = Psych.parse("- 0\n- 1")
303
+ assert_raises UnexpectedValue do
304
+ Validator.validate({
305
+ "type" => "array",
306
+ "items" => { "type" => "integer" },
307
+ "maxItems" => 1,
308
+ }, ast.children.first)
309
+ end
310
+ end
311
+
312
+ def test_unexpected_tag
313
+ ast = Psych.parse("--- !lolol\n foo")
314
+ ex = assert_raises UnexpectedTag do
315
+ Validator.validate({
316
+ "type" => "string",
317
+ }, ast.children.first)
318
+ end
319
+ assert_match(/lolol/, ex.message)
320
+ end
321
+
322
+ def test_object_without_specified_properties
323
+ ast = Psych.parse("---\nfoo: bar")
324
+ assert_raises InvalidSchema do
325
+ Validator.validate({
326
+ "type" => "object",
327
+ }, ast.children.first)
328
+ end
329
+ end
330
+
331
+ def test_invalid_sub_property
332
+ ast = Psych.parse("---\nfoo: \n hello: world")
333
+ assert_raises UnexpectedValue do
334
+ Validator.validate({
335
+ "type" => "object",
336
+ "properties" => {
337
+ "foo" => {
338
+ "type" => "object",
339
+ "properties" => {
340
+ "hello" => {"type" => "integer"}
341
+ }
342
+ }
343
+ }
344
+ }, ast.children.first)
345
+ end
346
+ end
347
+
348
+ def test_invalid_object_key_type # integer keys aren't allowed
349
+ ast = Psych.parse("---\nfoo: \n 1: 2")
350
+ ex = assert_raises UnexpectedValue do
351
+ Validator.validate({
352
+ "type" => "object",
353
+ "properties" => {
354
+ "foo" => {
355
+ "type" => "object",
356
+ "properties" => {
357
+ "hello" => {"type" => "integer"}
358
+ }
359
+ }
360
+ }
361
+ }, ast.children.first)
362
+ end
363
+ assert_match(/expected string, got integer/, ex.message)
364
+ end
365
+
366
+ def test_allow_objects_with_aliases
367
+ ast = Psych.parse(<<-eoyml)
368
+ ---
369
+ foo: &1
370
+ - foo
371
+ bar: *1
372
+ eoyml
373
+ assert Validator.validate({
374
+ "type" => "object",
375
+ "properties" => {
376
+ "foo" => { "type" => "array", "items" => { "type" => "string" } },
377
+ "bar" => { "type" => "array", "items" => { "type" => "string" } },
378
+ },
379
+ }, ast.children.first)
380
+ end
381
+
382
+ class CustomInfo
383
+ def read_tag(node)
384
+ if node.tag == "!aaron"
385
+ "test"
386
+ else
387
+ node.tag
388
+ end
389
+ end
390
+ end
391
+
392
+ def test_custom_node_info
393
+ validator = Validator.new(CustomInfo.new)
394
+ ast = Psych.parse("--- !aaron\nfoo: bar")
395
+ validator.validate({
396
+ "type" => "object",
397
+ "tag" => "test",
398
+ "properties" => {
399
+ "foo" => { "type" => "string" }
400
+ }
401
+ }, ast.children.first)
402
+ end
403
+ end
404
+ end
405
+ end
@@ -0,0 +1,18 @@
1
+ $: << File.expand_path("lib")
2
+
3
+ Gem::Specification.new do |s|
4
+ s.name = "yaml-schema"
5
+ s.version = "1.0.0"
6
+ s.summary = "Validate YAML against a schema"
7
+ s.description = "If you need to validate YAML against a schema, use this"
8
+ s.authors = ["Aaron Patterson"]
9
+ s.email = "tenderlove@ruby-lang.org"
10
+ s.files = `git ls-files -z`.split("\x0")
11
+ s.test_files = s.files.grep(%r{^test/})
12
+ s.homepage = "https://github.com/tenderlove/yaml-schema"
13
+ s.license = "Apache-2.0"
14
+
15
+ s.add_development_dependency 'rake', '~> 13.0'
16
+ s.add_development_dependency 'psych', '~> 5.0'
17
+ s.add_development_dependency 'minitest', '~> 5.15'
18
+ end
metadata ADDED
@@ -0,0 +1,89 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: yaml-schema
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Aaron Patterson
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: rake
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '13.0'
19
+ type: :development
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '13.0'
26
+ - !ruby/object:Gem::Dependency
27
+ name: psych
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - "~>"
31
+ - !ruby/object:Gem::Version
32
+ version: '5.0'
33
+ type: :development
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '5.0'
40
+ - !ruby/object:Gem::Dependency
41
+ name: minitest
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - "~>"
45
+ - !ruby/object:Gem::Version
46
+ version: '5.15'
47
+ type: :development
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - "~>"
52
+ - !ruby/object:Gem::Version
53
+ version: '5.15'
54
+ description: If you need to validate YAML against a schema, use this
55
+ email: tenderlove@ruby-lang.org
56
+ executables: []
57
+ extensions: []
58
+ extra_rdoc_files: []
59
+ files:
60
+ - Gemfile
61
+ - LICENSE
62
+ - README.md
63
+ - Rakefile
64
+ - lib/yaml-schema.rb
65
+ - test/validator_test.rb
66
+ - yaml-schema.gemspec
67
+ homepage: https://github.com/tenderlove/yaml-schema
68
+ licenses:
69
+ - Apache-2.0
70
+ metadata: {}
71
+ rdoc_options: []
72
+ require_paths:
73
+ - lib
74
+ required_ruby_version: !ruby/object:Gem::Requirement
75
+ requirements:
76
+ - - ">="
77
+ - !ruby/object:Gem::Version
78
+ version: '0'
79
+ required_rubygems_version: !ruby/object:Gem::Requirement
80
+ requirements:
81
+ - - ">="
82
+ - !ruby/object:Gem::Version
83
+ version: '0'
84
+ requirements: []
85
+ rubygems_version: 4.0.0.dev
86
+ specification_version: 4
87
+ summary: Validate YAML against a schema
88
+ test_files:
89
+ - test/validator_test.rb