Skip to content

Commit

Permalink
Update pre-commit; autoupdate; reformat
Browse files Browse the repository at this point in the history
  • Loading branch information
sloria committed May 5, 2019
1 parent 74e1a72 commit 142e0ae
Show file tree
Hide file tree
Showing 9 changed files with 116 additions and 78 deletions.
6 changes: 3 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
repos:
- repo: https://github.com/asottile/pyupgrade
rev: v1.15.0
rev: v1.16.3
hooks:
- id: pyupgrade
args: ["--py3-plus"]
- repo: https://github.com/asottile/add-trailing-comma
rev: v0.8.0
rev: v1.0.0
hooks:
- id: add-trailing-comma
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.1.0
rev: v2.2.1
hooks:
- id: trailing-whitespace
- id: double-quote-string-fixer
Expand Down
22 changes: 13 additions & 9 deletions performance/benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,12 +92,14 @@ def run_timeit(quotes, iterations, repeat, profile=False):
profile.enable()

gc.collect()
best = min(timeit.repeat(
lambda: quotes_schema.dump(quotes),
'gc.enable()',
number=iterations,
repeat=repeat,
))
best = min(
timeit.repeat(
lambda: quotes_schema.dump(quotes),
'gc.enable()',
number=iterations,
repeat=repeat,
),
)
if profile:
profile.disable()
profile.dump_stats('marshmallow.pprof')
Expand Down Expand Up @@ -137,9 +139,11 @@ def main():
),
)

print('Benchmark Result: {:.2f} usec/dump'.format(
run_timeit(quotes, args.iterations, args.repeat, profile=args.profile),
))
print(
'Benchmark Result: {:.2f} usec/dump'.format(
run_timeit(quotes, args.iterations, args.repeat, profile=args.profile),
),
)


if __name__ == '__main__':
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
],
'lint': [
'flake8==3.7.7',
'pre-commit==1.15.2',
'pre-commit==1.16.0',
],
}
EXTRAS_REQUIRE['dev'] = (
Expand Down
12 changes: 8 additions & 4 deletions src/marshmallow/class_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,17 @@ def get_class(classname, all=False):
try:
classes = _registry[classname]
except KeyError:
raise RegistryError('Class with name {!r} was not found. You may need '
'to import the class.'.format(classname))
raise RegistryError(
'Class with name {!r} was not found. You may need '
'to import the class.'.format(classname),
)
if len(classes) > 1:
if all:
return _registry[classname]
raise RegistryError('Multiple classes with name {!r} '
raise RegistryError(
'Multiple classes with name {!r} '
'were found. Please use the full, '
'module-qualified path.'.format(classname))
'module-qualified path.'.format(classname),
)
else:
return _registry[classname][0]
22 changes: 14 additions & 8 deletions src/marshmallow/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -642,8 +642,10 @@ def _deserialize(
if partial_is_collection:
prefix = field_name + '.'
len_prefix = len(prefix)
sub_partial = [f[len_prefix:]
for f in partial if f.startswith(prefix)]
sub_partial = [
f[len_prefix:]
for f in partial if f.startswith(prefix)
]
else:
sub_partial = partial
d_kwargs['partial'] = sub_partial
Expand Down Expand Up @@ -997,12 +999,16 @@ def _bind_field(self, field_name, field_obj):
self.on_bind_field(field_name, field_obj)
except TypeError:
# field declared as a class, not an instance
if (isinstance(field_obj, type) and
issubclass(field_obj, base.FieldABC)):
msg = ('Field for "{}" must be declared as a '
'Field instance, not a class. '
'Did you mean "fields.{}()"?'
.format(field_name, field_obj.__name__))
if (
isinstance(field_obj, type) and
issubclass(field_obj, base.FieldABC)
):
msg = (
'Field for "{}" must be declared as a '
'Field instance, not a class. '
'Did you mean "fields.{}()"?'
.format(field_name, field_obj.__name__)
)
raise TypeError(msg)

def _has_processors(self, tag):
Expand Down
78 changes: 48 additions & 30 deletions tests/test_deserialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -654,10 +654,12 @@ def test_structured_dict_key_value_deserialization(self):
assert field.deserialize({'foo@test.com': 1}) == {'foo@test.com': decimal.Decimal(1)}
with pytest.raises(ValidationError) as excinfo:
field.deserialize({1: 'bar'})
assert excinfo.value.args[0] == {1: {
'key': ['Not a valid string.'],
'value': ['Not a valid number.'],
}}
assert excinfo.value.args[0] == {
1: {
'key': ['Not a valid string.'],
'value': ['Not a valid number.'],
},
}
with pytest.raises(ValidationError) as excinfo:
field.deserialize({'foo@test.com': 'bar'})
assert excinfo.value.args[0] == {'foo@test.com': {'value': ['Not a valid number.']}}
Expand All @@ -668,10 +670,12 @@ def test_structured_dict_key_value_deserialization(self):
assert excinfo.value.valid_data == {}
with pytest.raises(ValidationError) as excinfo:
field.deserialize({'foo': 'bar'})
assert excinfo.value.args[0] == {'foo': {
'key': ['Not a valid email address.', 'String does not match expected pattern.'],
'value': ['Not a valid number.'],
}}
assert excinfo.value.args[0] == {
'foo': {
'key': ['Not a valid email address.', 'String does not match expected pattern.'],
'value': ['Not a valid number.'],
},
}
assert excinfo.value.valid_data == {}

def test_url_field_deserialization(self):
Expand Down Expand Up @@ -981,20 +985,26 @@ def test_field_deserialization_with_validator_with_nonascii_input(self):
assert type(excinfo.value) == ValidationError

def test_field_deserialization_with_user_validators(self):
validators_gen = (func for func in (
lambda s: s.lower() == 'valid',
lambda s: s.lower()[::-1] == 'dilav',
))

m_colletion_type = [
fields.String(validate=[
lambda s: s.lower() == 'valid',
lambda s: s.lower()[::-1] == 'dilav',
]),
fields.String(validate=(
validators_gen = (
func for func in (
lambda s: s.lower() == 'valid',
lambda s: s.lower()[::-1] == 'dilav',
)),
)
)

m_colletion_type = [
fields.String(
validate=[
lambda s: s.lower() == 'valid',
lambda s: s.lower()[::-1] == 'dilav',
],
),
fields.String(
validate=(
lambda s: s.lower() == 'valid',
lambda s: s.lower()[::-1] == 'dilav',
),
),
fields.String(validate=validators_gen),
]

Expand Down Expand Up @@ -1374,9 +1384,11 @@ def validate_with_bool(val):
return False

class MySchema(Schema):
email = fields.Email(validate=[
validate_with_bool,
])
email = fields.Email(
validate=[
validate_with_bool,
],
)
with pytest.raises(ValidationError) as excinfo:
MySchema().load({'email': 'foo'})
errors = excinfo.value.messages
Expand All @@ -1388,9 +1400,11 @@ def validate_with_bool(val):
return False

class MySchema(Schema):
url = fields.Url(validate=[
validate_with_bool,
])
url = fields.Url(
validate=[
validate_with_bool,
],
)
with pytest.raises(ValidationError) as excinfo:
MySchema().load({'url': 'foo'})
errors = excinfo.value.messages
Expand Down Expand Up @@ -1595,11 +1609,15 @@ class MySchema(Schema):

validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x])

validators_gen_float = (func for func in
[lambda f: f <= 4.1, lambda f: f >= 1.0])
validators_gen_float = (
func for func in
[lambda f: f <= 4.1, lambda f: f >= 1.0]
)

validators_gen_str = (func for func in
[lambda n: len(n) == 3, lambda n: n[1].lower() == 'o'])
validators_gen_str = (
func for func in
[lambda n: len(n) == 3, lambda n: n[1].lower() == 'o']
)

class TestValidation:

Expand Down
20 changes: 11 additions & 9 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,17 @@ class TestField:
def test_repr(self):
default = 'œ∑´'
field = fields.Field(default=default, attribute=None)
assert repr(field) == ('<fields.Field(default={0!r}, attribute=None, '
'validate=None, required=False, '
'load_only=False, dump_only=False, '
'missing={missing}, allow_none=False, '
'error_messages={error_messages})>'
.format(
default, missing=missing,
error_messages=field.error_messages,
))
assert repr(field) == (
'<fields.Field(default={0!r}, attribute=None, '
'validate=None, required=False, '
'load_only=False, dump_only=False, '
'missing={missing}, allow_none=False, '
'error_messages={error_messages})>'
.format(
default, missing=missing,
error_messages=field.error_messages,
)
)
int_field = fields.Integer(validate=lambda x: True)
assert '<fields.Integer' in repr(int_field)

Expand Down
20 changes: 11 additions & 9 deletions tests/test_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,15 +121,17 @@ def test_nested_field_order_with_only_arg_is_maintained_on_dump(self, user):

def test_nested_field_order_with_only_arg_is_maintained_on_load(self):
schema = OrderedNestedOnly()
data = schema.load({'user': {
'name': 'Foo',
'email': 'Foo@bar.com',
'age': 42,
'created': dt.datetime.now().isoformat(),
'id': 123,
'homepage': 'http://foo.com',
'birthdate': dt.datetime.now().date().isoformat(),
}})
data = schema.load({
'user': {
'name': 'Foo',
'email': 'Foo@bar.com',
'age': 42,
'created': dt.datetime.now().isoformat(),
'id': 123,
'homepage': 'http://foo.com',
'birthdate': dt.datetime.now().date().isoformat(),
},
})
user_data = data['user']
keys = list(user_data)
assert keys == ['name', 'email', 'age', 'created', 'id', 'homepage', 'birthdate']
Expand Down
12 changes: 7 additions & 5 deletions tests/test_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -1348,11 +1348,13 @@ def data(self):
str_dump_only='Dump Only',
str_load_only='Load Only',
str_regular='Regular String',
child=[dict(
str_dump_only='Dump Only',
str_load_only='Load Only',
str_regular='Regular String',
)],
child=[
dict(
str_dump_only='Dump Only',
str_load_only='Load Only',
str_regular='Regular String',
),
],
)

def test_load_only(self, schema, data):
Expand Down

0 comments on commit 142e0ae

Please sign in to comment.