[英]Get pytest to look within the base directory of the testing script
In pytest, my testing script compares the calculated results with baseline results which are loaded via 在pytest中,我的测试脚本将计算出的结果与通过基线加载的基线结果进行比较
SCRIPTLOC = os.path.dirname(__file__)
TESTBASELINE = os.path.join(SCRIPTLOC, 'baseline', 'baseline.csv')
baseline = pandas.DataFrame.from_csv(TESTBASELINE)
Is there a non-boilerplate way to tell pytest to start looking from the root directory of the script rather than get the absolute location through SCRIPTLOC? 是否有一种非样板的方法告诉pytest从脚本的根目录开始查找,而不是通过SCRIPTLOC获取绝对位置?
If you are simply looking for the pytest equivalent of using __file__
, you can add the request
fixture to your test and use request.fspath
如果您只是在寻找与使用__file__
等效的pytest,则可以将request
装置添加到测试中并使用request.fspath
class FixtureRequest ... fspath the file system path of the test module which collected this test.
So an example might look like: 因此,一个示例可能看起来像:
def test_script_loc(request):
baseline = os.path.join(request.fspath.dirname, 'baseline', 'baseline.cvs')
print(baseline)
If you're wanting to avoid boilerplate though, you're not going to gain much from doing this (assuming I understand what you mean by 'non-boilerplate') 但是,如果您想避免样板,那么您将不会从中受益(假设我理解您所说的“非样板”的意思)
Personally, I think using the fixture is more explicit (within pytest idioms), but I prefer to wrap the request manipulation in another fixture so I know that I'm specifically grabbing sample test data just by looking at the method signature of a test. 就个人而言,我认为使用夹具更明确(在pytest习惯用法内),但是我更喜欢将请求操作包装在另一个夹具中,因此我知道我只是通过查看测试的方法签名来捕获样本测试数据。
Here's a snippet I use (modified to match your question, I use a subdirectory hierarchy): 这是我使用的代码片段(已修改为匹配您的问题,我使用子目录层次结构):
# 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('..')
And sample usage 和样品用法
def test_script_loc(script_loc):
baseline = script_loc.join('baseline/baseline.cvs')
print(baseline)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.