如果你只是寻找pytest相当于使用__file__
的,你可以在request
夹具添加到您的测试和使用request.fspath
从docs:
class FixtureRequest
...
fspath
the file system path of the test module which collected this test.
因此,一个示例可能如下所示:
def test_script_loc(request):
baseline = os.path.join(request.fspath.dirname, 'baseline', 'baseline.cvs')
print(baseline)
如果你想避免样板,但你不会从这么做(假设我明白你的意思是'非样板')
个人而言,我认为使用夹具是更明确(在pytest成语中),但我更愿意将请求操作包装在另一个夹具中,所以我知道我只是通过查看测试的方法签名来抓取样本测试数据。
这里有一个片段我使用(修改,以符合你的问题,我用一个子目录层次):
# in conftest.py
import pytest
@pytest.fixture(scope="module")
def script_loc(request):
'''Return the directory of the currently running test script'''
# uses .join instead of .dirname so we get a LocalPath object instead of
# a string. LocalPath.join calls normpath for us when joining the path
return request.fspath.join('..')
而且样品使用
def test_script_loc(script_loc):
baseline = script_loc.join('baseline/baseline.cvs')
print(baseline)
THISIS完全无关pytest,它完全在你自己代码,因此完全是你的责任 – Ronny
也许我错误地问了这个问题。如何在pytest中引用相对(如相对于测试脚本)目录?我放入代码来展示我一直在做什么来解决它。 –
目前没有,这是一个标准的python问题 - 像pkgutil/pkg_ressources这样的东西可以帮助 – Ronny