且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

TEST Mirror默认数据库,但无数据

更新时间:2023-02-02 21:32:03

这是Django中的一个已知错误: https://code.djangoproject.com/ticket/23718

This is a known bug in Django: https://code.djangoproject.com/ticket/23718

该票中描述的解决方法是***的选择.我遇到了同样的问题,并通过定义自定义TestCase类并在所有测试中从该自定义测试用例继承来实现了变通方法.我还选择使用setUpClass和tearDownClass代替bug票证中所述的setUp和tearDown.无论哪种都可以.

The workaround described in that ticket is your best bet. I ran into this same issue and implemented the workaround by defining a custom TestCase class and inheriting from that custom test case in all my tests. I also chose to use setUpClass and tearDownClass instead of setUp and tearDown as described in the bug ticket. Either should work though.

from django.db import connections

class CustomTestCase(TestCase):

    @classmethod
    def setUpClass(cls):
        super(CustomTestCase, cls).setUpClass()
        connections['replica']._orig_cursor = connections['replica'].cursor
        connections['replica'].cursor = connections['default'].cursor

    @classmethod
    def tearDownClass(cls):
        connections['replica'].cursor = connections['replica']._orig_cursor
        super(CustomTestCase, cls).tearDownClass()