Skip to content

Commit

Permalink
Fix const and add const to error message
Browse files Browse the repository at this point in the history
  • Loading branch information
horejsek committed Feb 1, 2021
1 parent 8d06a05 commit b9141ff
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 11 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
=== 2.15.0 (2021)

* Fix additional property equal to empty object is the same as True
* Fix const with "
* Add const to error message


=== 2.14.5 (2020-08-17)

* Fix missing dependencies
Expand Down
4 changes: 2 additions & 2 deletions fastjsonschema/draft06.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,6 @@ def generate_const(self):
"""
const = self._definition['const']
if isinstance(const, str):
const = '"{}"'.format(const)
const = '"{}"'.format(const.replace('"', '\\"'))
with self.l('if {variable} != {}:', const):
self.exc('{name} must be same as const definition', rule='const')
self.exc('{name} must be same as const definition: {definition_rule}', rule='const')
3 changes: 2 additions & 1 deletion fastjsonschema/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,8 @@ def exc(self, msg, *args, rule=None):
"""
"""
msg = 'raise JsonSchemaException("'+msg+'", value={variable}, name="{name}", definition={definition}, rule={rule})'
self.l(msg, *args, definition=repr(self._definition), rule=repr(rule))
definition_rule = str(self._definition.get(rule) if isinstance(self._definition, dict) else None).replace('"', '\\"')
self.l(msg, *args, definition=repr(self._definition), rule=repr(rule), definition_rule=definition_rule)

def create_variable_with_length(self):
"""
Expand Down
26 changes: 18 additions & 8 deletions tests/test_const.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
import pytest

from fastjsonschema import JsonSchemaException

@pytest.mark.parametrize('value', (
'foo',
42,
False,
[1, 2, 3]

@pytest.mark.parametrize('value, testError', (
('foo', False),
(42, False),
(False, False),
([1, 2, 3], False),
('\'"', False),
('foo', True),
('\'"', False),
))
def test_const(asserter, value):
def test_const(asserter, value, testError):
const = expected = value
if testError:
const = 'x'
expected = JsonSchemaException('data must be same as const definition: x', value='{data}', name='data', definition='{definition}', rule='const')

asserter({
'$schema': 'http://json-schema.org/draft-06/schema',
'const': value,
}, value, value)
'const': const,
}, value, expected)

0 comments on commit b9141ff

Please sign in to comment.