151π
You donβt need to import it β as youβve already correctly written, DoesNotExist
is a property of the model itself, in this case Answer
.
Your problem is that you are calling the get
method β which raises the exception β before it is passed to assertRaises
. You need to separate the arguments from the callable, as described in the unittest documentation:
self.assertRaises(Answer.DoesNotExist, Answer.objects.get, body__exact='<p>User can reply to discussion.</p>')
or better:
with self.assertRaises(Answer.DoesNotExist):
Answer.objects.get(body__exact='<p>User can reply to discussion.</p>')
210π
You can also import ObjectDoesNotExist
from django.core.exceptions
, if you want a generic, model-independent way to catch the exception:
from django.core.exceptions import ObjectDoesNotExist
try:
SomeModel.objects.get(pk=1)
except ObjectDoesNotExist:
print 'Does Not Exist!'
- [Django]-How to query as GROUP BY in Django?
- [Django]-In Django 1.4, do Form.has_changed() and Form.changed_data, which are undocumented, work as expected?
- [Django]-Django related_name for field clashes
13π
DoesNotExist
is always a property of the model that does not exist. In this case it would be Answer.DoesNotExist
.
- [Django]-How do you perform Django database migrations when using Docker-Compose?
- [Django]-Django: Get list of model fields?
- [Django]-How to upload a file in Django?
3π
One thing to watch out for is that the second parameter to assertRaises
needs to be a callable β not just a property. For instance, I had difficulties with this statement:
self.assertRaises(AP.DoesNotExist, self.fma.ap)
but this worked fine:
self.assertRaises(AP.DoesNotExist, lambda: self.fma.ap)
- [Django]-Django.db.migrations.exceptions.InconsistentMigrationHistory
- [Django]-Get list item dynamically in django templates
- [Django]-Django β what is the difference between render(), render_to_response() and direct_to_template()?
3π
self.assertFalse(Answer.objects.filter(body__exact='<p>User...discussion.</p>').exists())
- [Django]-Django Reverse with arguments '()' and keyword arguments '{}' not found
- [Django]-How do you serialize a model instance in Django?
- [Django]-Strings won't be translated in Django using format function available in Python 2.7
0π
This is how I do such a test.
from foo.models import Answer
def test_z_Kallie_can_delete_discussion_response(self):
...snip...
self._driver.get("http://localhost:8000/questions/3/want-a-discussion")
try:
answer = Answer.objects.get(body__exact = '<p>User can reply to discussion.</p>'))
self.fail("Should not have reached here! Expected no Answer object. Found %s" % answer
except Answer.DoesNotExist:
pass #Β all is as expected
- [Django]-How to get username from Django Rest Framework JWT token
- [Django]-South migration: "database backend does not accept 0 as a value for AutoField" (mysql)
- [Django]-Django return file over HttpResponse β file is not served correctly