2015-12-02 73 views
2

比方說我的代碼看起來像這樣使python py.test單元測試獨立運行py.test在執行位置?

import pytest 
import json 

@pytest.fixture 
def test_item(): 
    test_item = json.load(open('./directory/sample_item_for_test.json','rb')) 
    return test_item 

def test_fun(test_document): 
    assert type(test_item.description[0]) == unicode 

而且我想通過Py.Test

運行該測試。如果我從它在目錄中運行Py.test,它是好的。但是如果我從上面的目錄運行它,由於無法找到'sample_item_for_test.json'而失敗。有沒有辦法讓這個測試正確運行,無論我在哪裏執行Py.test?

+1

還要注意的是'型(一)== B'通常不是你想。 'isinstance(a,b)'更具慣用性,並且還會傳遞子類的實例。 – mgilson

回答

2

魔術屬性__file__是文件系統上python文件的路徑。所以,你可以使用一些魔法的os得到當前目錄...

import pytest 
import json 
import os 

_HERE = os.path.dirname(__file__) 
_TEST_JSON_FILENAME = os.path.join(_HERE, 'directory', 'sample_item_for_test.json') 

@pytest.fixture 
def test_item(): 
    with open(_TEST_JSON_FILENAME, 'rb') as file_input: 
     return json.load(file_input) 
1

當我遷移到py.test,我有一大套的傳統測試,習慣於在被執行測試文件所在的目錄。相反,跟蹤每一個測試失敗,我添加了一個pytest鉤到我的conftest.py到CHDIR到test目錄每次測試開始之前:

import os 
import functools 

def pytest_runtest_setup(item): 
    """ 
    Execute each test in the directory where the test file lives. 
    """ 
    starting_directory = os.getcwd() 
    test_directory = os.path.dirname(str(item.fspath)) 
    os.chdir(test_directory) 

    teardown = functools.partial(os.chdir, starting_directory) 
    # There's probably a cleaner way than accessing a private member. 
    item.session._setupstate.addfinalizer(teardown, item)