2015-12-29 37 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)