I'm writing some simple test for a django-model and I'm just using assertEqual and assertNotEqual for it.
Now I'm not fully grasping how to test BooleanField in this case. I have a model field like this:
duplicate = models.BooleanField(default=False)
and I'm writing this test for it, just to check if it is equal:
def test_feed_duplicate_create(self):
stefan_feed_duplicate = Feed.objects.get(duplicate='False')
milan_feed_duplicate = Feed.objects.get(duplicate='False')
self.assertEqual(
stefan_feed_duplicate.duplicate, 'False'
)
self.assertEqual(
milan_feed_duplicate.duplicate, 'False'
)
But the error that I'm facing is:
(venv) vagrant@jessie:/var/www/vhosts/bspotted.net/app$ ./manage.py test --keepdb socialmedia
nosetests socialmedia --verbosity=1
Using existing test database for alias 'default'...
............E....................
======================================================================
ERROR: test_feed_duplicate_create (app.socialmedia.tests.test_feed_model.CommentsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/var/www/vhosts/bspotted.net/app/socialmedia/tests/test_feed_model.py", line 225, in test_feed_duplicate_create
stefan_feed_duplicate = Feed.objects.get(duplicate='False')
File "/var/www/vhosts/bspotted.net/venv/lib/python3.4/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/var/www/vhosts/bspotted.net/venv/lib/python3.4/site-packages/django/db/models/query.py", line 338, in get
(self.model._meta.object_name, num)
socialmedia.models.feed.MultipleObjectsReturned: get() returned more than one Feed -- it returned 2!
----------------------------------------------------------------------
Ran 33 tests in 0.159s
Can someone explain me what is the proper way of testing BooleanField in this case? Thanks.
The get method of QuerySet returns exactly 1 (one) entry. It will throw error if it can't retrieve an entry and it will throw an error if it retrieves more than one entry.
If you expect more than one entry, or eventually no entries at all, you should use the filter method, which returns itself a QuerySet.
In your particular case you can't just retrieve one entry based on the field duplicate. It is a BooleanField and there will be entries with value True and entries with value False.
You have to retrieve those particular entries for stefan and milan based on another field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With