Django LiveServerTestCase:在setUpClass方法中创建的用户在test_方法中不可用?

2024-10-01 07:44:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用django1.4的LiveServerTestCase进行Selenium测试,并且在使用setUpClass类方法时遇到了问题。据我所知,MembershipTests.setUpClass在单元测试运行之前运行一次。在

我在MembershipTests.setUpClass中编写了向数据库添加用户的代码,但是当我运行MembershipTests.test_signup测试时,没有用户添加到测试数据库中。我做错了什么?我希望我在setUpClass中创建的用户可以在所有单元测试中使用。在

如果我把用户创建代码放在MembershipTests.setUp中并运行MembershipTests.test_signup,我可以看到用户,但不希望在每个单元测试之前都像setUp那样运行。如您所见,我使用一个自定义的LiveServerTestCase类来在所有测试中添加基本功能(test_utils.CustomLiveTestCase)。我怀疑这和我的问题有关。在

提前谢谢。在

测试_实用工具.py

from selenium.webdriver.firefox.webdriver import WebDriver
from django.test import LiveServerTestCase

class CustomLiveTestCase(LiveServerTestCase):

    @classmethod
    def setUpClass(cls):
        cls.wd = WebDriver()
        super(CustomLiveTestCase, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        cls.wd.quit()
        super(CustomLiveTestCase, cls).tearDownClass()

测试.py

^{pr2}$

Tags: 代码用户frompytest数据库setup单元测试
3条回答

数据库在每个测试方法上被破坏并重新加载,而不是在测试类上。所以你的用户每次都会丢失。在setUp而不是setUpClass中执行该操作。在

您应该能够按如下方式使用TestCase.setUpTestData(对基类稍作修改):

测试_实用工具.py

from selenium.webdriver.firefox.webdriver import WebDriver
from django.test import LiveServerTestCase, TestCase

class CustomLiveTestCase(LiveServerTestCase, TestCase):

    @classmethod
    def setUpClass(cls):
        cls.wd = WebDriver()
        super(CustomLiveTestCase, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        cls.wd.quit()
        super(CustomLiveTestCase, cls).tearDownClass()

测试.py

^{pr2}$

您可以在MembershipTests中从TestCase继承基类,而不是更改基类,但是每次需要测试数据时都必须这样做。在

请注意,我还删除了def setUp: pass,因为这将中断事务处理。在

查看此线程以获取更多详细信息:https://groups.google.com/forum/#!topic/django-developers/sr3gnsc8gig

如果您在这个解决方案中遇到任何问题,请告诉我!在

由于您使用的是LiveServerTestCase,它几乎与TransactionTestCase相同,TransactionTestCase为每次运行的测试用例创建和销毁数据库(截断表)。在

所以你真的不能用LiveServerTestCase来做全局数据。在

相关问题 更多 >