简体   繁体   中英

How to handle view throwing manual exception in django in unit-testing?

I have made a django application and am writing tests for it. In one of my views I'm manually throwing an exception:

raise Http404('Not authorised')

While writing test for that using django's built-in test framework(based on unittest).

TL;DR: Is there way to write test such that it makes sure that the view is indeed returning Http404 . ( assertEqual(response.status_code, 404 doesn't work)

This should work:

resp = self.client.get(url)
self.assertEqual(resp.status_code, 404)

Run your tests via:

python manage.py test

If it does not, recheck your code and supply an error message.

If self.assertEqual doesn't work you could try it with a with tag as shown here assertRaises(exception, callable, *args, **kwds)

with self.assertRaises(Http404):
    // your logic here

For example. I have a function that will return an order or raise a HTTP 404 response

from django.http import Http404

def test_get_order_with_method_404(self):
    client = MyPaymentClient("super_secret_key")
    with self.assertRaises(Http404):
        client.get_order_with_method("payment_id", "payment_method")

You could also do it with get_object_or_404

Example:

from django.http import Http404
from django.shortcuts import get_object_or_404

with self.assertRaises(Http404):
    get_object_or_404(MyModel, some_argument="MyCriteria")

Well i guess you get the point. Hope this helps you out!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM