Skip to content

Commit

Permalink
Include module with type name in validation errors (python) (#178)
Browse files Browse the repository at this point in the history
* Include module with type name in validation errors

* Fix linter error

* fix test under py2

* Update stone_validators.py

Co-authored-by: Connor Worley <cworley@dropbox.com>
  • Loading branch information
connorworley and Connor Worley committed Sep 22, 2020
1 parent 4f0c136 commit 7668385
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
20 changes: 17 additions & 3 deletions stone/backends/python_rsrc/stone_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,13 @@ def __repr__(self):
return 'ValidationError(%r)' % six.text_type(self)


def type_name_with_module(t):
# type: (typing.Type[typing.Any]) -> six.text_type
return '%s.%s' % (t.__module__, t.__name__)


def generic_type_name(v):
# type: (typing.Any) -> six.text_type
"""Return a descriptive type name that isn't Python specific. For example,
an int value will return 'integer' rather than 'int'."""
if isinstance(v, bool):
Expand All @@ -87,7 +93,7 @@ def generic_type_name(v):
elif v is None:
return 'null'
else:
return type(v).__name__
return type_name_with_module(type(v))


class Validator(six.with_metaclass(ABCMeta, object)):
Expand Down Expand Up @@ -535,7 +541,11 @@ def validate_type_only(self, val):
# relies on the parent class.
if not isinstance(val, self.definition):
raise ValidationError('expected type %s, got %s' %
(self.definition.__name__, generic_type_name(val)))
(
type_name_with_module(self.definition),
generic_type_name(val),
),
)

def has_default(self):
return not self.definition._has_required_fields
Expand Down Expand Up @@ -600,7 +610,11 @@ def validate_type_only(self, val):
"""
if not issubclass(self.definition, type(val)):
raise ValidationError('expected type %s or subtype, got %s' %
(self.definition.__name__, generic_type_name(val)))
(
type_name_with_module(self.definition),
generic_type_name(val),
),
)


class Void(Primitive):
Expand Down
8 changes: 8 additions & 0 deletions test/test_python_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -652,6 +652,14 @@ def _get_val_data_type(cls, tag, cp):
self.assertEqual(prefix, str(e)[:len(prefix)])
raise

def test_type_name_with_module(self):
class Foo():
def __init__(self):
pass

assert bv.type_name_with_module(Foo) == "test.test_python_gen.Foo"
assert bv.type_name_with_module(int) == "builtins.int" if six.PY3 else "__builtin__.int"


test_spec = """\
namespace ns
Expand Down

0 comments on commit 7668385

Please sign in to comment.