Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force an exception in django in order to test it in django

I've really searched for how to patch Whatever.objects.get_or_create, but I can't get any suggestion or idea how to do it.

Well, my problem is that I have something like this:

def create_and_get_object(
    name, request, save_url=True, data=None):

    try:
        (object_type_, created) = Object.objects.get_or_create(
            name=name)
        try:
        ...
    except Exception:
        obj = None
        msg = ("Failed to get or create object `Object` with"
                "name='%s'" % name)
        logger_.exception(msg, extra={'request': request})
    return obj

So, I want to test that Object.objects.get_or_create throws an exception somewhen...

I was trying with Mock(side_effect=Exception()) but I don't really know how to use it to get what I expect.

All this to get 100% coverage for that function (exception lines are not covered), and many others with exceptions like that.

What is the correct way to test this, and code like this?

What am I doing wrong?

like image 751
Tomás Solar Avatar asked Apr 16 '13 16:04

Tomás Solar


People also ask

How do I run a specific test case in Django?

You need to open you init.py and import your tests. Show activity on this post. If you want to run a test case class which has the path <module_name>/tests/test_views.py , you can run the command python manage.py test <module_name>. tests.

How do I create a TestCase in Django?

To write a test you derive from any of the Django (or unittest) test base classes (SimpleTestCase, TransactionTestCase, TestCase, LiveServerTestCase) and then write separate methods to check that specific functionality works as expected (tests use "assert" methods to test that expressions result in True or False values ...

What is automated testing in Django?

Automated Testing is a widely used tool that uses a collection of predefined test cases. Learn how Django and Selenium to ensure a bug free system. Table of contents.


1 Answers

I like to use python's with statement with mock's patch.object. In your case it should be smth like this:

from mock import patch
from django.test import TestCase
from django.db.models.manager import Manager
from anothermodule import create_and_get_object


class TestCreateAndGetObject(TestCase):
    def test_exception_throwing(self):
        with patch.object(Manager, 'get_or_create') as mock_method:
            mock_method.side_effect = Exception("test error")

            result = create_and_get_object('test', 'test')
            self.assertIsNone(result)

Should work in theory, hope that helps.

like image 64
alecxe Avatar answered Sep 27 '22 18:09

alecxe