Skip to content

Commit

Permalink
Tuple type (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
vartec authored Oct 25, 2016
1 parent 81704f4 commit 4c8065d
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
2 changes: 1 addition & 1 deletion conformity/fields/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .basic import Base, Constant, Anything, Hashable, Boolean, Integer, Float, ByteString, UnicodeString
from .structures import List, Dictionary, SchemalessDictionary
from .structures import List, Dictionary, SchemalessDictionary, Tuple
from .meta import Polymorph, ObjectInstance
from .temporal import DateTime, Date, TimeDelta, Time, TZInfo
22 changes: 22 additions & 0 deletions conformity/fields/structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,25 @@ def errors(self, value):
for error in (self.value_type.errors(field) or [])
)
return result


class Tuple(Base):
"""
A tuple with types per element.
"""

def __init__(self, *contents):
self.contents = contents

def errors(self, value):
if not isinstance(value, tuple):
return ["Not a tuple"]

result = []
if len(value) != len(self.contents):
result.append("number of elements %d doesn't match expected %d" % (len(value), len(self.contents)))

for i, (c_elem, v_elem) in enumerate(zip(self.contents, value)):
result.extend("Element %d: %s" % (i, error) for error in (c_elem.errors(v_elem) or []))

return result
28 changes: 28 additions & 0 deletions conformity/tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
TimeDelta,
SchemalessDictionary,
ObjectInstance,
Tuple,
)


Expand Down Expand Up @@ -220,3 +221,30 @@ class SomethingElse(object):
schema.errors(SomethingElse()),
["not an instance of Thing"]
)

def test_tuple(self):
schema = Tuple(Integer(gt=0), UnicodeString(), Constant("I love tuples"))

self.assertEqual(
schema.errors((1, "test", "I love tuples")),
[]
)

# too short
self.assertEqual(
schema.errors((1, "test")),
["number of elements 2 doesn't match expected 3"]
)

# too long
self.assertEqual(
schema.errors((1, "test", "I love tuples", "... and coffee")),
["number of elements 4 doesn't match expected 3"]
)

self.assertEqual(
schema.errors((-1, None, "I hate tuples",)),
['Element 0: Value not > 0',
'Element 1: Not a unicode string',
"Element 2: Value is not u'I love tuples'"]
)

0 comments on commit 4c8065d

Please sign in to comment.