Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 927
Trevor Avatar asked Mar 31 '14 18:03

Trevor


People also ask

How do you share a variable across a module in Python?

The best way to share global variables across modules across a single program is to create a config module. Just import the config module in all modules of your application; the module then becomes available as a global name. Hope it works!!

What are global variables in Python?

Variables that are created outside of a function (as in all of the examples above) are known as global variables. Global variables can be used by everyone, both inside of functions and outside.

What is Conftest py in pytest?

conftest.py is where you setup test configurations and store the testcases that are used by test functions. The configurations and the testcases are called fixture in pytest. The test_*. py files are where the actual test functions reside.


1 Answers

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.

like image 159
flub Avatar answered Sep 18 '22 12:09

flub