Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 没有数据库连接的django单元测试_Python_Django_Unit Testing_Testing - Fatal编程技术网

Python 没有数据库连接的django单元测试

Python 没有数据库连接的django单元测试,python,django,unit-testing,testing,Python,Django,Unit Testing,Testing,我正在尝试编写一个unittest,它将检查在数据库连接遇到异常时是否返回了正确的错误消息。我尝试使用connection.creation.destroy\u test\u db(':memory:')但它没有像我预期的那样工作。我想我要么删除表,要么以某种方式切断数据库连接。这些都有可能吗?听起来这是一份适合你的工作。例如,如果您使用的是MySQL,您可以在connect方法上设置副作用,如下所示: from django.test import TestCase from mock imp

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

听起来这是一份适合你的工作。例如,如果您使用的是MySQL,您可以在
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

希望能有所帮助。

我在演示文稿中找到了答案。我是这样做的:

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

在使用
pymysql
时,我正在寻找django在数据库连接超时情况下的实际http响应代码。当
pymysql
引发
操作错误时,以下测试确认这是
401未经授权的

来自unittest.mock导入修补程序的

导入pymysql
从django.test导入TestCase,客户端
类TestDatabaseOutput(TestCase):
客户端=无
def设置(自):
self.client=client()
def测试\数据库\连接\超时\返回\ 401(自身):
使用patch.object(pymysql,'connect')作为connect\u方法:
message=“无法连接到'some_database.example.com'上的MySQL服务器([Errno 110]连接超时)”
connect_method.side_effect=pymysql.OperationalError(2003,消息)
response=self.client.get(“/”)
self.assertEqual(response.status\u代码,401)

也许您可以提出一个数据库错误并捕获它。从django.db导入DatabaseError在这里引发DatabaseError默认django异常列表我感到困惑。这个问题的标题是“无连接”,但在正文中,您说您试图断言消息在出现异常时返回。像什么?重复的钥匙?标题和身体不太匹配,我只是感到困惑。澄清?没有与数据库的连接会引发DatabaseError异常,这正是我试图引起并断言我的webapp在这种情况下打印的错误消息的原因。谢谢您的回复!我做的有点不同,看看我的答案。