没有数据库连接的django unittest

时间:2013-05-12 13:32:24

标签: python django unit-testing testing

我正在尝试编写一个unittest,它将检查在数据库连接遇到异常的情况下是否返回了正确的错误消息。我试过使用connection.creation.destroy_test_db(':memory:'),但它没有像我预期的那样工作。我想我应该删除表或以某种方式切断数据库连接。这些可能吗?

3 个答案:

答案 0 :(得分:3)

听起来这是mocking的工作。例如,如果您使用的是MySQL,则可以在side_effect方法上添加connect,如下所示:

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

希望有所帮助。

答案 1 :(得分:3)

我在演示文稿Testing and Django by Carl Meyer中找到了答案。我是这样做的:

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')

答案 2 :(得分:2)

在使用pymysql时,如果数据库连接超时,我正在寻找django的实际http响应代码。以下测试在401 Unauthorized提出pymysql时确认为OperationalError

from unittest.mock import patch

import pymysql
from django.test import TestCase, Client


class TestDatabaseOutage(TestCase):
    client = None

    def setUp(self):
        self.client = Client()

    def test_database_connection_timeout_returns_401(self):
        with patch.object(pymysql, 'connect') as connect_method:
            message = "Can't connect to MySQL server on 'some_database.example.com' ([Errno 110] Connection timed out)"
            connect_method.side_effect = pymysql.OperationalError(2003, message)
            response = self.client.get('/')
            self.assertEqual(response.status_code, 401)

401 Unauthorized http cat