Skip to main content
 首页 » 编程设计

python之setupclass 中的 django_db 标记问题

2025年05月04日36lautakyan007

早上好,我正在使用从 django.test.TestCase 继承的测试,我在使用 setupclass 方法时遇到问题,因为访问数据库并引发此错误“失败:不允许访问数据库,使用“django_db”标记来启用”,但是我使用的是 django_db 标记。这是代码:

from django.test import TestCase 
 
@pytest.mark.django_db 
class ViewAllBeneficiariesTest(TestCase): 
''' Tests for Beneficiary ''' 
 
    @classmethod 
    def setUpClass(cls): 
        cls.u = model_mommy_create_user_permission_all() 
 
    def test_clients_view_all_beneficiaries_get_ok(self): 
        #Arrange: 
        self.client.login(username=self.u.username, password="admin") 
        #Act: 
        res = self.client.get('/clients/beneficiaries/all/') 
 
        #Assert: 
        self.assertEqual(res.status_code, 200) 
        self.assertTemplateUsed(res, 'clients/search_beneficiaries.html') 
 
    def test_clients_view_all_beneficiaries_404(self): 
        #Arrange: 
        self.client.login(username=self.u.username, password="admin") 
        #Act: 
        res = self.client.get('/clients/beneficiaries/all/') 
 
        #Assert: 
 
        self.assertEqual(res.status_code, 404) 
 
    def test_clients_view_all_beneficiaries_fail(self): 
        #Arrange: 
        #Act: 
        res = self.client.get('/clients/beneficiaries/all/') 
 
        #Assert: 
 
        self.assertEqual(res.status_code, 302) 
       self.assertRedirects(res, '/accounts/login/') 

请您参考如下方法:

这已在 pytest-django 的 master 分支中修复。

你可以阅读它here

我能够通过发出以下命令使用 pip 安装它 -

pip install https://github.com/pytest-dev/pytest-django/zipball/master