Skip to content

Commit

Permalink
objects() generator implemented
Browse files Browse the repository at this point in the history
  • Loading branch information
Xion committed Oct 1, 2011
1 parent 3e6197e commit 55743b9
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
15 changes: 14 additions & 1 deletion qc/__init__.py
Expand Up @@ -64,9 +64,22 @@ def unicodes(size=(0, 100), minunicode=0, maxunicode=255):
yield unicode('').join(unichr(random.randint(minunicode, maxunicode)) \
for _ in xrange(random.randint(size[0], size[1])))


characters = functools.partial(unicodes, size=(1, 1))

def objects(_object_class, _fields={}, *init_args, **init_kwargs):
''' Endlessly yields objects of given class, with fields specified
by given dictionary. Uses given constructor arguments while creating
each object.
'''
while True:
ctor_args = [arg.next() for arg in init_args]
ctor_kwargs = dict([(k, v.next()) for k, v in init_kwargs.iteritems()])
obj = _object_class(*ctor_args, **ctor_kwargs)
for k, v in _fields.iteritems():
setattr(obj, k, v.next())
yield obj


def forall(tries=100, **kwargs):
def wrap(f):
@functools.wraps(f)
Expand Down
16 changes: 15 additions & 1 deletion tests/test_qc.py
@@ -1,4 +1,4 @@
from qc import integers, floats, unicodes, characters, lists, tuples, dicts, forall
from qc import integers, floats, unicodes, characters, lists, tuples, dicts, objects, forall

@forall(tries=10, i=integers())
def test_integers(i):
Expand Down Expand Up @@ -99,3 +99,17 @@ def each_integer_from_0_to_10(i, target_low, target_high):

def test_qc_partials():
each_integer_from_0_to_10(target_low=0, target_high=10)


class TestClass(object):
def __init__(self, arg):
self.arg_from_init = arg

@forall(tries=10, objs=objects(TestClass, {'an_int': integers(), 'a_float': floats()}, 42))
def test_objects(objs):
for obj in objs:
assert type(obj) == TestClass
assert type(obj.an_int) == int
assert type(obj.a_float) == float
assert obj.arg_from_init == 42

1 comment on commit 55743b9

@dbravender
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Neat idea. I merged this to master.

Please sign in to comment.