Skip to content
This repository has been archived by the owner on Oct 22, 2019. It is now read-only.

Commit

Permalink
Fix detection of iterator attributes
Browse files Browse the repository at this point in the history
Test for the exact methods required by the iterator protocol.
(https://docs.python.org/2/library/stdtypes.html#iterator-types)
  • Loading branch information
sfriesel authored and vandersonmota committed Jun 12, 2015
1 parent aeb987f commit a5aa1a4
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 4 deletions.
10 changes: 6 additions & 4 deletions model_mommy/mommy.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,12 +241,14 @@ def _populate(self):


def is_iterator(value):
try:
iter(value)
return not isinstance(value, string_types)
except TypeError:
if not hasattr(value, '__iter__'):
return False

if PY3:
return hasattr(value, '__next__')
else:
return hasattr(value, 'next')


class Mommy(object):
attr_mapping = {}
Expand Down
7 changes: 7 additions & 0 deletions test/generic/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,10 @@ class CustomFieldWithGenerator(models.TextField):

class CustomFieldWithoutGenerator(models.TextField):
pass

class FakeListField(models.TextField):
def to_python(self, value):
return value.split()

def get_prep_value(self, value):
return super(FakeListField, self).get_prep_value(' '.join(value))
4 changes: 4 additions & 0 deletions test/generic/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,10 @@ class BaseModelForNext(models.Model):
fk = models.ForeignKey(ModelWithNext)


class BaseModelForList(models.Model):
fk = FakeListField()


if VERSION < (1, 4):
class DummyIPAddressFieldModel(models.Model):
ipv4_field = models.IPAddressField() # Deprecated in Django 1.7
Expand Down
11 changes: 11 additions & 0 deletions test/generic/tests/test_mommy.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from test.generic.models import DummyGenericForeignKeyModel, NonAbstractPerson
from test.generic.models import DummyEmptyModel
from test.generic.models import ModelWithNext, BaseModelForNext
from test.generic.models import BaseModelForList


class ModelFinderTest(TestCase):
Expand Down Expand Up @@ -443,6 +444,16 @@ def test_creates_instance_for_model_with_next(self):
self.assertEqual('foo', instance.fk.next())


class MommyHandlesModelWithList(TestCase):
def test_creates_instance_for_model_with_list(self):
instance = mommy.make(
BaseModelForList,
fk=["foo"]
)

self.assertTrue(instance.id)
self.assertEqual(["foo"], instance.fk)

if VERSION < (1, 4):
from test.generic.forms import DummyIPAddressFieldForm

Expand Down

0 comments on commit a5aa1a4

Please sign in to comment.