【问题标题】:How can I import/reference multiple pytest fixtures without wildcard import?如何在没有通配符导入的情况下导入/引用多个 pytest 固定装置?
【发布时间】:2022-06-27 23:52:56
【问题描述】:

目前,我使用以下设置从名为 fixtures.py 的文件中导入 pytest 设备并使用它们运行测试:

from django.contrib.auth.models import User, Group
from django.core import mail
from main.tests.fixtures import user_a, group_dropoff_for_qc

def test_should_check_password(db, user_a: User) -> None:
    user_a.set_password("secret")
    assert user_a.check_password("secret") is True

# more tests here

随着我编写更多测试并使用更多固定装置,来自main.tests.fixtures 的导入列表变得非常长。是否有一些内置的 pytest 方法?这似乎是一种常见的操作,应该有一种更简化的方法。

【问题讨论】:

    标签: pytest


    【解决方案1】:

    当我在起草这个问题时,我偶然发现了解决方案,所以不是仅仅删除这里的问题而是解决方案,以防万一这对其他人有帮助。

    解决方案来源:https://www.tutorialspoint.com/pytest/pytest_conftest_py.htm

    如果您将包含固定装置的外部文件重命名为 conftest.py,您可以引用该文件中的固定装置,而无需显式导入它们。所以在我上面的例子中,我只需将我的fixtures.py 重命名为conftest.py,这样我就可以按预期运行测试:

    from django.contrib.auth.models import User, Group
    from django.core import mail
    
    def test_should_check_password(db, user_a: User) -> None:
        user_a.set_password("secret")
        assert user_a.check_password("secret") is True
    
    # more code here
    

    【讨论】:

      猜你喜欢
      • 2018-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-24
      • 2012-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多