Skip to content

Commit

Permalink
Merge pull request #489 from toumorokoshi/allow_dict-names
Browse files Browse the repository at this point in the history
Allow fields names to override the mapping-interface methods.
  • Loading branch information
lkraider committed May 24, 2017
2 parents a0beffc + cd94171 commit e8352d8
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 4 deletions.
5 changes: 1 addition & 4 deletions schematics/iteration.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

from .compat import iteritems
from .undefined import Undefined
from collections import namedtuple
Expand Down Expand Up @@ -44,9 +43,7 @@ def atoms(schema, mapping, keys=Atom._fields, filter=None):

if has_value:
try:
value = getattr(mapping, field_name)
except AttributeError:
value = mapping.get(field_name, Undefined)
value = mapping[field_name]
except Exception:
value = Undefined

Expand Down
44 changes: 44 additions & 0 deletions tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,50 @@
from schematics.exceptions import *


def test_dict_methods_in_model():
"""
a regression test to ensure that an issue where attributes on
dictionaries are not being misintrepreted as actual schematics
fields.
"""

class M(Model):
items, values, get = IntType(), IntType(), IntType()

m = M({"items": 1, "values": 1, "get": 1})
m.validate()


def test_dict_methods_in_model_atoms():
"""
atoms should return the raw values, and not call any overriden methods.
"""
class M(Model):
get = IntType()
m = M({"get": 1})
atom = list(m.atoms())[0]
assert atom.name == "get"
assert atom.value == 1


def test_nested_model_override_mapping_methods():
"""
overriding mapping methods on child models should not cause issues
with validation on the parent.
"""

class Nested(Model):
items, values, get, keys = IntType(), IntType(), IntType(), IntType()

class Root(Model):
keys = ModelType(Nested)

root = Root({"keys": {"items": 1, "values": 1, "get": 1, "keys": 1}})
root.validate()
for key in ["items", "values", "get", "keys"]:
assert getattr(root.keys, key) == 1


def test_init_with_dict():

class M(Model):
Expand Down

0 comments on commit e8352d8

Please sign in to comment.