5

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

4

3 回答 3

4

我在Carl Meyer 的演讲 Testing and Django中找到了答案。这是我的做法:

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')
于 2013-06-08T19:27:11.010 回答
3

听起来这是一项嘲笑的工作。例如,如果您使用的是 MySQL,则可以放置一个side_effectonconnect方法,如下所示:

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

希望有帮助。

于 2013-05-12T20:21:59.157 回答
2

我正在寻找 django 的实际 http 响应代码,以防使用pymysql. 下面的测试证实了它是一个401 Unauthorizedwhen pymysqlraises an 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未经授权的http猫

于 2017-12-04T16:05:28.153 回答