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

后端 未结 5 858
醉酒成梦
醉酒成梦 2020-12-01 17:41

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

5条回答
  •  误落风尘
    2020-12-01 18:25

    Having a big dictionary of globals that every test uses is probably a bad idea. If possible, I suggest refactoring your tests to avoid this sort of thing.

    That said, here is how I would do it: define an autouse fixture that adds a reference to the dictionary in the global namespace of every function.

    Here is some code. It's all in the same file, but you can move the fixture out to conftest.py at the top level of your tests.

    import pytest
    
    my_big_global = {'key': 'value'}
    
    @pytest.fixture(autouse=True)
    def myglobal(request):
        request.function.func_globals['foo'] = my_big_global
    
    def test_foo():
        assert foo['key'] == 'value'
    
    def test_bar():
        assert foo['key'] == 'bar'
    

    Here is the output from when I run this code:

    $ py.test test_global.py -vv
    ======================================= test session starts =======================================
    platform darwin -- Python 2.7.5 -- py-1.4.20 -- pytest-2.5.2 -- env/bin/python
    collected 2 items
    
    test_global.py:9: test_foo PASSED
    test_global.py:12: test_bar FAILED
    
    ============================================ FAILURES =============================================
    ____________________________________________ test_bar _____________________________________________
    
        def test_bar():
    >       assert foo['key'] == 'bar'
    E       assert 'value' == 'bar'
    E         - value
    E         + bar
    
    test_global.py:13: AssertionError
    =============================== 1 failed, 1 passed in 0.01 seconds ===============================
    

    Note that you can't use a session-scoped fixture because then you don't have access to each function object. Because of this, I'm making sure to define my big global dictionary once and use references to it -- if I defined the dictionary in that assignment statement, a new copy would be made each time.

    In closing, doing anything like this is probably a bad idea. Good luck though :)

提交回复
热议问题