typesystem
typesystem copied to clipboard
validate_json example from documentation does not work
I've copy-pasted "Tokenized Errors" example from documentation to example.py:
$ cat example.py
import typesystem
class Config(typesystem.Schema):
num_worker_processes = typesystem.Integer()
enable_auto_reload = typesystem.Boolean()
text = '''{
"num_worker_processes": "x",
"enable_auto_reload": "true"
}'''
value, messages = typesystem.validate_json(text, validator=Config)
assert value is None
for message in messages:
line_no = message.start_position.line_no
column_no = message.start_position.column_no
print(f"Error {message.text!r} at line {line_no}, column {column_no}.")
# Error 'Must be a number.' at line 2, column 29.
However, it fails with ValidationError. I expected it to print 'Must be a number ...' instead:
$ pipenv install typesystem
$ pipenv run python3 -c 'import typesystem; print(typesystem.__version__)'
0.2.2
$ pipenv run python3 example.py
Traceback (most recent call last):
File "/Users/me/.local/share/virtualenvs/example-AxLzGwo/lib/python3.7/site-packages/typesystem/tokenize/positional_validation.py", line 13, in validate_with_positions
return validator.validate(token.value)
File "/Users/me/.local/share/virtualenvs/example-AxLzGwo/lib/python3.7/site-packages/typesystem/schemas.py", line 147, in validate
value = validator.validate(value, strict=strict)
File "/Users/me/.local/share/virtualenvs/example-AxLzGwo/lib/python3.7/site-packages/typesystem/fields.py", line 545, in validate
raise ValidationError(messages=error_messages)
typesystem.base.ValidationError: {'num_worker_processes': 'Must be a number.'}
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "example.py", line 12, in <module>
value, messages = typesystem.validate_json(text, validator=Config)
File "/Users/me/.local/share/virtualenvs/example-AxLzGwo/lib/python3.7/site-packages/typesystem/tokenize/tokenize_json.py", line 197, in validate_json
return validate_with_positions(token=token, validator=validator)
File "/Users/me/.local/share/virtualenvs/example-AxLzGwo/lib/python3.7/site-packages/typesystem/tokenize/positional_validation.py", line 36, in validate_with_positions
raise ValidationError(messages=messages)
typesystem.base.ValidationError: {'num_worker_processes': 'Must be a number.'}
Let's turn this issue into a question :) What is broken - documentation or implementation? I could try to fix it myself, but I don't know the original intent.
Let's turn this issue into a question :) What is broken - documentation or implementation? I could try to fix it myself, but I don't know the original intent.
Good call!
The documentation has the intent correct here.
Taking a look at the function signature is helpful here, since it's clear that it's supposed to return error messages, rather than raise exceptions. https://github.com/encode/typesystem/blob/master/typesystem/tokenize/tokenize_json.py