Skip to content

Commit 7e01c7b

Browse files
committed
Add custom_formats parameter when validating $ref
1 parent 1a54972 commit 7e01c7b

File tree

2 files changed

+33
-8
lines changed

2 files changed

+33
-8
lines changed

Diff for: fastjsonschema/generator.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -137,8 +137,7 @@ def generate_validation_function(self, uri, name):
137137
self._validation_functions_done.add(uri)
138138
self.l('')
139139
with self._resolver.resolving(uri) as definition:
140-
args = "data, custom_formats={}" if self._custom_formats else "data"
141-
with self.l('def {}({}):', name, args):
140+
with self.l('def {}(data, custom_formats={{}}):', name):
142141
self.generate_func_code_block(definition, 'data', 'data', clear_variables=True)
143142
self.l('return data')
144143

@@ -192,7 +191,7 @@ def generate_ref(self):
192191
if uri not in self._validation_functions_done:
193192
self._needed_validation_functions[uri] = name
194193
# call validation function
195-
self.l('{}({variable})', name)
194+
self.l('{}({variable}, custom_formats)', name)
196195

197196

198197
# pylint: disable=invalid-name

Diff for: tests/test_compile_to_code.py

+31-5
Original file line numberDiff line numberDiff line change
@@ -88,11 +88,37 @@ def test_compile_complex_one_of_all_of():
8888

8989

9090
def test_compile_to_code_custom_format():
91-
formats = {'identifier': str.isidentifier}
92-
code = compile_to_code({'type': 'string', 'format': 'identifier'}, formats=formats)
91+
formats = {'my-format': str.isidentifier}
92+
code = compile_to_code({'type': 'string', 'format': 'my-format'}, formats=formats)
9393
with open('temp/schema_3.py', 'w') as f:
9494
f.write(code)
9595
from temp.schema_3 import validate
96-
assert validate("identifier", formats) == "identifier"
97-
with pytest.raises(JsonSchemaValueException):
98-
validate("not-identifier", formats)
96+
assert validate("valid", formats) == "valid"
97+
with pytest.raises(JsonSchemaValueException) as exc:
98+
validate("not-valid", formats)
99+
assert exc.value.message == "data must be my-format"
100+
101+
102+
def test_compile_to_code_custom_format_with_refs():
103+
schema = {
104+
'type': 'object',
105+
'properties': {
106+
'a': {'$ref': '#/definitions/a'}
107+
},
108+
'definitions': {
109+
'a': {
110+
'$id': '#/definitions/a',
111+
'type': 'array',
112+
'items': {'type': 'string', 'format': 'my-format'}
113+
}
114+
}
115+
}
116+
formats = {'my-format': str.isidentifier}
117+
code = compile_to_code(schema, formats=formats)
118+
with open('temp/schema_4.py', 'w') as f:
119+
f.write(code)
120+
from temp.schema_4 import validate
121+
assert validate({"a": ["identifier"]}, formats) is not None
122+
with pytest.raises(JsonSchemaValueException) as exc:
123+
validate({"a": ["identifier", "not-valid"]}, formats)
124+
assert exc.value.message == "data[1] must be my-format"

0 commit comments

Comments
 (0)