python - Django + Pytest + Selenium

标签 python django selenium pytest pytest-django

我最近从 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)中使用数据库调用,因为它不受支持并且存在其他问题:

django-pytest setup_method database issue

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

相关文章:

python - 并发下载 - Python

python - 一个 Django 实例一个数据库 vs 不同的 Django 实例

java - POM PageFactory 中是否需要 getter?

Java Selenium 和 Appium 不起作用无法启动 REST http 接口(interface)监听器

python - 匹配字符串后还想打印下一行

python - 这些 transient 模型的 ID 发生了什么?

django - Django 中的数组字段

django - 自定义 Django Admin 用户密码修改表单

c# - Web Scrape w/Selenium;性能慢?

python - Django 不会扩展到父文件夹中的 base.html