2015-12-02 70 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)