Ped*_*oja 6 python pytest conftest
我正在 conftest.py 中创建一个对象并在某些装置中使用它。我还需要在我的测试模块中使用这个对象。目前,我正在我的测试模块中导入 conftest.py 并使用该“helper”对象。我很确定这不是推荐的方式。我期待您的建议。
谢谢 :)
以下是我的问题的虚拟编码版本:
测试.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()
Run Code Online (Sandbox Code Playgroud)
测试模块.py
import conftest
helper = conftest.helper
def test_method1(sample):
helper.foo()
...
Run Code Online (Sandbox Code Playgroud)
正如已经评论过的,如果我在测试中有一个辅助类,我之前也通过固定装置处理过此类场景。
测试.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()
Run Code Online (Sandbox Code Playgroud)
测试模块.py
def test_method1(helper, sample):
helper.foo()
Run Code Online (Sandbox Code Playgroud)