没有数据库连接的django unittest

tam*_*rap 5 python testing django unit-testing

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

tam*_*rap 5

我在Carl Meyer 的演示文稿“测试和 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')
Run Code Online (Sandbox Code Playgroud)


Edu*_*uim 2

自 2021 年 12 月起,出现了Django Mockingbird库。

有了这个,您可以模拟将从数据库检索的对象。

from djangomockingbird import mock_model

@mock_model('myapp.myfile.MyModel')
def test_my_test():
    some_test_query = MyModel.objects.filter(bar='bar').filter.(foo='foo').first()
    #some more code
    #assertions here
Run Code Online (Sandbox Code Playgroud)