不鼓励在测试模块中导入conftest.py吗?



我在conftest.py中创建一个对象,并在一些fixture中使用它。我还需要在测试模块中使用这个对象。目前,我正在我的测试模块中导入conftest.py,并使用该"助手"对象。我很确定这不是推荐的方法。我期待你的建议。

谢谢你:)

以下是我的问题的伪编码版本:

conftest.py

import pytest
class Helper():
def __init__(self, img_path:str):
self.img_path = img_path
def grayscale(self):
pass
def foo(self):
pass
helper = Helper("sample.png")
@pytest.fixture()
def sample():
return helper.grayscale()

test_module.py

import conftest
helper = conftest.helper
def test_method1(sample):
helper.foo()
...

如前所述,如果我在测试中有一个helper类,我之前也会通过fixture处理这种情况。

conftest.py

import pytest

class Helper():
def __init__(self, img_path: str):
self.img_path = img_path
def grayscale(self):
pass
def foo(self):
pass

@pytest.fixture(scope="session")
def helper():
return Helper("sample.png")

@pytest.fixture()
def sample(helper):
return helper.grayscale()

test_module.py

def test_method1(helper, sample):
helper.foo()

对于@Niel的回应有一个小小的补充;

如果你想要类型提示,你可以从conftest模块导入。

test_module.py

# If test module is next to conftest
# from .conftest import Helpers 
# If test module is under a subpackage, which is my case
from ..conftest import Helpers
def test_method1(helper: Helpers, sample: str):
helper.foo()

最新更新