如果你只是尋找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