how to share a variable across modules for all tests in py.test

Trevor picture Trevor · Mar 31, 2014 · Viewed 34.7k times · Source

I have multiple tests run by py.test that are located in multiple classes in multiple files.

What is the simplest way to share a large dictionary - which I do not want to duplicate - with every method of every class in every file to be used by py.test?

In short, I need to make a "global variable" for every test. Outside of py.test, I have no use for this variable, so I don't want to store it in the files being tested. I made frequent use of py.test's fixtures, but this seems overkill for this need. Maybe it's the only way?

Answer

flub picture flub · Apr 1, 2014

Update: pytest-namespace hook is deprecated/removed. Do not use. See #3735 for details.

You mention the obvious and least magical option: using a fixture. You can apply it to entire modules using pytestmark = pytest.mark.usefixtures('big_dict') in your module, but then it won't be in your namespace so explicitly requesting it might be best.

Alternatively you can assign things into the pytest namespace using the hook:

# conftest.py

def pytest_namespace():
    return {'my_big_dict': {'foo': 'bar'}}

And now you have pytest.my_big_dict. The fixture is probably still nicer though.