拆分aconftest.py分成几个较小的conftestlike部分

2024-06-23 02:51:21 发布

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

我有一个大的conftest.py我希望将文件拆分为更小的部分,原因有两个:

  1. 文件非常大(大约1000行,包括文档)
  2. 因为其他的fixtures和fixtures的其他部分的fixtures依赖于其他的fixtures来测试,所以我没有把fixtures的其他部分暴露出来

我不知道pytest提供了任何机制来解析同一文件夹中多个位置的conftest文件,因此我设计了一个机制,如下所示:

import sys
import os


sys.path.append(os.path.dirname(__file__))


from _conftest_private_part_1 import *
from _conftest_private_part_2 import *
from _conftest_private_part_3 import *


@pytest.fixture
def a_fixture_that_is_part_of_the_public_conftest_api():
    pass

这符合我的需要,但我不知道有没有更好的方法。在


Tags: 文件pathfrompyimportpytestossys
3条回答

这对我很有效,而且似乎更容易/更清晰:

顶层测试/conftest.py(可重复使用的打印调试示例请求。响应)公司名称:

import pytest
import requests
from requests_toolbelt.utils import dump


@pytest.fixture(scope="session")
def print_response(response: requests.Response):
    data = dump.dump_all(response)
    print("========================")
    print(data.decode('utf-8'))
    print("========================")

    print("response.url = {}".format(response.url))
    print("response.request = {}".format(response.request))
    print("response.status_code = {}".format(response.status_code))
    print("response.headers['content-type'] = {}".format(response.headers['content-type']))
    print("response.encoding = {}".format(response.encoding))
    try:
        print("response.json = {}".format(response.json()))
    except Exception:
        print("response.text = {}".format(response.text))
    print("response.end")

从较低级别的conftest导入较高级别的conftest代码-例如,tests/package1/conftest.py公司名称:

^{pr2}$

然后,在tests/package1/test\*.py中的较低级别测试中,只需通过以下方式导入:

from tests.package1 import conftest

然后您就可以从一个conftest获得合并的conftests。对其他较低级别的详细/模块化重复此模式conftest.py整个测试层次结构中的文件。在

您可以将资料放入其他模块中,并在conftest.py中使用pytest_plugins变量引用它们:

pytest_plugins = ['module1', 'module2']

如果您的conftest.py上有{a1},这也会起作用。在

你不需要任何神奇的魔法。py.测试自动将当前测试文件的路径添加到sys.path,以及指向目标目录的所有父路径。在

因此,您甚至不需要将共享代码放入conftest.py。您可以将其放入普通模块或包中,然后导入它(如果您想共享fixture,那么这些fixture必须位于conftest.py)中。在

另外,还有一个关于从documentation中的conftest.py导入的注释:

If you have conftest.py files which do not reside in a python package directory (i.e. one containing an __init__.py) then “import conftest” can be ambiguous because there might be other conftest.py files as well on your PYTHONPATH or sys.path. It is thus good practise for projects to either put conftest.py under a package scope or to never import anything from a conftest.py file.

相关问题 更多 >