Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django unittest without database connection

I'm trying to write a unittest that will check if the correct error message is returned in case the database connection hits exception. I've tried to use connection.creation.destroy_test_db(':memory:') but it didn't work as I expected. I suppose I should either remove the tables or somehow cut the db connection. Is any of those possible?

like image 810
tampakrap Avatar asked May 12 '13 13:05

tampakrap


2 Answers

I found my answer in the presentation Testing and Django by Carl Meyer. Here is how I did it:

from django.db import DatabaseError
from django.test import TestCase
from django.test.client import Client
import mock

class NoDBTest(TestCase):
    cursor_wrapper = mock.Mock()
    cursor_wrapper.side_effect = DatabaseError

    @mock.patch("django.db.backends.util.CursorWrapper", cursor_wrapper)
    def test_no_database_connection(self):
        response = self.client.post('/signup/', form_data)
        self.assertEqual(message, 'An error occured with the DB')
like image 68
tampakrap Avatar answered Sep 30 '22 04:09

tampakrap


Sounds like this is a job for mocking. For example, if you are using MySQL, you can put a side_effect on connect method, like this:

from django.test import TestCase
from mock import patch
import MySQLdb


class DBTestCase(TestCase):
    def test_connection_error(self):
        with patch.object(MySQLdb, 'connect') as connect_method:
            connect_method.side_effect = Exception("Database Connection Error")

            # your assertions here

Hope that helps.

like image 44
alecxe Avatar answered Sep 30 '22 04:09

alecxe