better import errors, fix #309 (#336)

This commit is contained in:
Samuel Colvin
2018-12-27 19:37:53 +00:00
committed by GitHub
parent 8301f9e4b2
commit 0d5cd3bce5
4 changed files with 24 additions and 4 deletions
+1
View File
@@ -14,6 +14,7 @@ v0.17.0 (unreleased)
* support for passing Config class in dataclasses decorator, #276 by @jarekkar
(**breaking change**: this supersedes the ``validate_assignment`` argument with ``config``)
* support for nested dataclasses, #334 by @samuelcolvin
* better errors when getting an ``ImportError`` with ``PyObject``, #309 by @samuelcolvin
v0.16.1 (2018-12-10)
....................
+1 -1
View File
@@ -109,7 +109,7 @@ class PathNotADirectoryError(_PathValueError):
class PyObjectError(PydanticTypeError):
msg_template = 'ensure this value contains valid import path'
msg_template = 'ensure this value contains valid import path: {error_message}'
class ListError(PydanticTypeError):
+4 -2
View File
@@ -6,7 +6,7 @@ from typing import Optional, Pattern, Set, Type, Union
from uuid import UUID
from . import errors
from .utils import change_exception, import_string, make_dsn, url_regex_generator, validate_email
from .utils import import_string, make_dsn, url_regex_generator, validate_email
from .validators import (
anystr_length_validator,
anystr_strip_whitespace,
@@ -221,8 +221,10 @@ class PyObject:
@classmethod
def validate(cls, value):
if value is not None:
with change_exception(errors.PyObjectError, ImportError):
try:
return import_string(value)
except ImportError as e:
raise errors.PyObjectError(error_message=str(e))
class DSN(str):
+18 -1
View File
@@ -111,10 +111,27 @@ def test_module_import():
m = PyObjectModel()
assert m.module == os.path
with pytest.raises(ValidationError) as exc_info:
PyObjectModel(module='foobar')
assert exc_info.value.errors() == [
{'loc': ('module',), 'msg': 'ensure this value contains valid import path', 'type': 'type_error.pyobject'}
{
'loc': ('module',),
'msg': 'ensure this value contains valid import path: ' '"foobar" doesn\'t look like a module path',
'type': 'type_error.pyobject',
'ctx': {'error_message': '"foobar" doesn\'t look like a module path'},
}
]
with pytest.raises(ValidationError) as exc_info:
PyObjectModel(module='os.missing')
assert exc_info.value.errors() == [
{
'loc': ('module',),
'msg': 'ensure this value contains valid import path: ' 'Module "os" does not define a "missing" attribute',
'type': 'type_error.pyobject',
'ctx': {'error_message': 'Module "os" does not define a "missing" attribute'},
}
]