File: extended_schema_test.rb

package info (click to toggle)
ruby-json-schema 6.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 960 kB
  • sloc: ruby: 6,373; makefile: 4
file content (80 lines) | stat: -rw-r--r-- 2,305 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
require File.expand_path('support/test_helper', __dir__)

class ExtendedSchemaTest < Minitest::Test
  class BitwiseAndAttribute < JSON::Schema::Attribute
    def self.validate(current_schema, data, fragments, processor, _validator, options = {})
      return unless data.is_a?(Integer)

      if data & current_schema.schema['bitwise-and'].to_i == 0
        message = "The property '#{build_fragment(fragments)}' did not evaluate to true when bitwise-AND'd with #{current_schema.schema['bitwise-and']}"
        validation_error(processor, message, fragments, current_schema, self, options[:record_errors])
      end
    end
  end

  class ExtendedSchema < JSON::Schema::Draft3
    def initialize
      super
      @attributes['bitwise-and'] = BitwiseAndAttribute
      @names = ['http://test.com/test.json']
      @uri = Addressable::URI.parse('http://test.com/test.json')
      @names = ['http://test.com/test.json']
    end

    JSON::Validator.register_validator(ExtendedSchema.new)
  end

  def test_extended_schema_validation
    schema = {
      '$schema' => 'http://test.com/test.json',
      'properties' => {
        'a' => {
          'bitwise-and' => 1,
        },
        'b' => {
          'type' => 'string',
        },
      },
    }

    assert_valid schema, { 'a' => 1, 'b' => 'taco' }
    refute_valid schema, { 'a' => 0, 'b' => 'taco' }
    refute_valid schema, { 'a' => 1, 'b' => 5 }
  end

  def test_extended_schema_validation_with_fragment
    schema = {
      '$schema' => 'http://test.com/test.json',
      'definitions' => {
        'odd-a' => {
          'properties' => {
            'a' => {
              'bitwise-and' => 1,
            },
          },
        },
      },
    }

    assert_valid schema, { 'a' => 1 }, fragment: '#/definitions/odd-a'
    refute_valid schema, { 'a' => 0 }, fragment: '#/definitions/odd-a'
  end

  def test_unextended_schema
    # Verify that using the original schema disregards the `bitwise-and` property
    schema = {
      'properties' => {
        'a' => {
          'bitwise-and' => 1,
        },
        'b' => {
          'type' => 'string',
        },
      },
    }

    assert_valid schema, { 'a' => 0, 'b' => 'taco' }
    assert_valid schema, { 'a' => 1, 'b' => 'taco' }
    refute_valid schema, { 'a' => 1, 'b' => 5 }
  end
end