|
| 1 | +import unittest |
| 2 | + |
| 3 | +from jsonschema import ValidationError, validate |
| 4 | + |
| 5 | +from netjsonconfig import OpenWrt |
| 6 | +from netjsonconfig.exceptions import _list_errors |
| 7 | + |
| 8 | +schema = { |
| 9 | + '$schema': 'http://json-schema.org/draft-04/schema#', |
| 10 | + 'type': 'object', |
| 11 | + 'additionalProperties': True, |
| 12 | + 'definitions': { |
| 13 | + 'spam_object': { |
| 14 | + 'additionalProperties': True, |
| 15 | + 'required': [ |
| 16 | + 'spam', |
| 17 | + ], |
| 18 | + 'properties': { |
| 19 | + 'spam': { |
| 20 | + 'type': 'string', |
| 21 | + }, |
| 22 | + }, |
| 23 | + }, |
| 24 | + 'eggs_object': { |
| 25 | + 'additionalProperties': True, |
| 26 | + 'required': [ |
| 27 | + 'eggs', |
| 28 | + ], |
| 29 | + 'properties': { |
| 30 | + 'eggs': { |
| 31 | + 'type': 'boolean', |
| 32 | + }, |
| 33 | + }, |
| 34 | + }, |
| 35 | + }, |
| 36 | + 'properties': { |
| 37 | + 'test_object': { |
| 38 | + 'type': 'object', |
| 39 | + 'oneOf': [ |
| 40 | + {'$ref': '#/definitions/spam_object'}, |
| 41 | + {'$ref': '#/definitions/eggs_object'}, |
| 42 | + ], |
| 43 | + } |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | + |
| 48 | +class TestJsonSchema(unittest.TestCase): |
| 49 | + """ |
| 50 | + tests ValidationError helpers |
| 51 | + """ |
| 52 | + def test_spam_object(self): |
| 53 | + test_i = {'test_object': {'spam': 'lots of'}} |
| 54 | + validate(test_i, schema) |
| 55 | + |
| 56 | + def test_eggs_object(self): |
| 57 | + test_i = {'test_object': {'eggs': True}} |
| 58 | + validate(test_i, schema) |
| 59 | + |
| 60 | + def test_burrito_object(self): |
| 61 | + test_i = {'test_object': {'burrito': 'yes'}} |
| 62 | + self.assertRaises(ValidationError, validate, test_i, schema) |
| 63 | + |
| 64 | + def test_burrito_error_message(self): |
| 65 | + test_i = {'test_object': {'burrito': 'yes'}} |
| 66 | + with self.assertRaises(ValidationError) as e: |
| 67 | + validate(test_i, schema) |
| 68 | + message_list = [ |
| 69 | + "'spam' is a required property", |
| 70 | + "'eggs' is a required property", |
| 71 | + ] |
| 72 | + self.assertEqual([err.message for err in e.exception.context], message_list) |
| 73 | + |
| 74 | + def test_list_errors(self): |
| 75 | + test_i = {'test_object': {'burrito': 'yes'}} |
| 76 | + with self.assertRaises(ValidationError) as e: |
| 77 | + validate(test_i, schema) |
| 78 | + suberror_list = [ |
| 79 | + ({'$ref': '#/definitions/spam_object'}, "'spam' is a required property"), |
| 80 | + ({'$ref': '#/definitions/eggs_object'}, "'eggs' is a required property"), |
| 81 | + ] |
| 82 | + self.assertEqual(_list_errors(e.exception), suberror_list) |
| 83 | + |
| 84 | + def test_error_str(self): |
| 85 | + o = OpenWrt({'interfaces': [{'wrong': True}]}) |
| 86 | + try: |
| 87 | + o.validate() |
| 88 | + except Exception as e: |
| 89 | + self.assertIn('Against schema', str(e)) |
| 90 | + else: |
| 91 | + self.fail('ValidationError not raised') |
0 commit comments