簡體   English   中英

使python py.test單元測試獨立於執行py.test的位置運行嗎?

[英]Make a python py.test unit test run independantly of the location where py.test in executed?

可以說我的代碼看起來像這樣

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,有沒有辦法使此測試正確運行?

魔術屬性__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)

當我遷移到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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM