我最近从 Django 的 TestCase 类切换到第三方 pytest 系统。这使我能够显着加快我的测试套件(5 倍),并且总体上是一次很棒的体验。
不过我确实对 selenium 有疑问。我制作了一个简单的 fixture 以将浏览器包含在我的测试中
@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)中使用数据库调用,因为它不受支持并且存在其他问题:
关于python - Django + Pytest + Selenium ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31937472/