2015-12-29 36 views
0

在pytest的基本目录中的样子,我的测试脚本基线结果计算出的结果,它们通过获取pytest的测试脚本

SCRIPTLOC = os.path.dirname(__file__) 
TESTBASELINE = os.path.join(SCRIPTLOC, 'baseline', 'baseline.csv') 
baseline = pandas.DataFrame.from_csv(TESTBASELINE) 

加载比较是否有一个样板式的方式告诉pytest到从脚本的根目录开始寻找,而不是通过SCRIPTLOC获取绝对位置?

+0

THISIS完全无关pytest,它完全在你自己代码,因此完全是你的责任 – Ronny

+0

也许我错误地问了这个问题。如何在pytest中引用相对(如相对于测试脚本)目录?我放入代码来展示我一直在做什么来解决它。 –

+1

目前没有,这是一个标准的python问题 - 像pkgutil/pkg_ressources这样的东西可以帮助 – Ronny

回答

1

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