Elliott Miller
Elliott Miller

Reputation: 363

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

Lets say my code looks like this

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

And I would like to run this test via Py.Test

If I run Py.test from the directory that it is in, it is fine. BUT if I run it from an above directory, it fails due to not being able to find 'sample_item_for_test.json'. Is there a way to make this test run correctly no matter where I execute Py.test?

Upvotes: 2

Views: 411

Answers (2)

dbn
dbn

Reputation: 13940

When I migrated to py.test, I had a large set of legacy tests that were accustomed to being executed in the directory where the test file lives. Instead of tracking down every test failure, I added a pytest hook to my conftest.py to chdir to the test directory before each test starts:

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)

Upvotes: 1

mgilson
mgilson

Reputation: 310117

The magic attribute __file__ is the path to the python file on the filesystem. So, you can use that with some magic from os to get the current directory...

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)

Upvotes: 2

Related Questions