我最近从 Django 的 TestCase 类切换到第三方 pytest 系统。这使我能够显着加快我的测试套件的速度(提高 5 倍),并且总体上是一次很棒的体验。

我确实有 Selenium 问题。我做了一个简单的装置来在我的测试中包含浏览器

@pytest.yield_fixture
def browser(live_server, transactional_db, admin_user):
    driver_ = webdriver.Firefox()
    driver_.server_url = live_server.url
    driver_.implicitly_wait(3)
    yield driver_
    driver_.quit()

但是由于某种原因,数据库在测试之间没有正确重置。我有一个类似的测试
class TestCase:
    def test_some_unittest(db):
        # Create some items
        #...

    def test_with_selenium(browser):
        # The items from the above testcase exists in this testcase

test_some_unittest 中创建的对象存在于 test_with_selenium 中。我不确定如何解决这个问题。

最佳答案

从 django.test.TestCase 切换到 pytest 意味着使用 pytest-django 插件,你的测试应该是这样的:


class TestSomething(object):
    def setup_method(self, method):
        pass

    @pytest.mark.django_db
    def test_something_with_dg(self):
       assert True

这首先意味着没有 django.test.TestCase (这是从 python std unittest 框架的派生)继承。

@pytest.mark.django_db 意味着您的测试用例将在一个事务中运行,一旦测试用例结束,该事务将回滚。

第一次出现 django_db 标记也会触发 django 迁移。

请注意在特殊的 pytest 方法(例如 setup_method )中使用数据库调用,因为它不受支持并且有其他问题:

django-pytest setup_method database issue

关于python - Django + Pytest + Selenium ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31937472/

10-11 22:24
查看更多