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

后端 未结 5 870
醉酒成梦
醉酒成梦 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:22

    There are tons of things I love about py.test, but one thing I absolutely HATE is how poorly it plays with code intelligence tools. I disagree that an autouse fixture to declare a variable is the "most clear" method in this case because not only does it completely baffle my linter, but also anyone else who is not familiar with how py.test works. There is a lot of magic there, imo.

    So, one thing you can do that doesn't make your linter explode and doesn't require TestCase boilerplate is to create a module called globals. Inside this module, stub the names of the things you want global to {} or None and import the global module into your tests. Then in your conftest.py file, use the py.test hooks to set (or reset) your global variable(s) as appropriate. This has the advantage of giving you the stub to work with when building tests and the full data for the tests at runtime.

    For example, you can use the pytest_configure() hook to set your dict right when py.test starts up. Or, if you wanted to make sure the data was pristine between each test, you could autouse a fixture to assign your global variable to your known state before each test.

    # globals.py
    my_data = {}  # Create a stub for your variable
    
    
    # test_module.py
    import globals as gbl
    
    def test_foo():
        assert gbl.my_data['foo'] == 'bar'  # The global is in the namespace when creating tests
    
    
    # conftest.py
    import globals as gbl
    my_data = {'foo': 'bar'}  # Create the master copy in conftest
    
    @pytest.fixture(autouse=True)
    def populate_globals():
        gbl.my_data = my_data  # Assign the master value to the global before each test
    

    One other advantage to this approach is you can use type hinting in your globals module to give you code completion on the global objects in your test, which probably isn't necessary for a dict but I find it handy when I am using an object (such as webdriver). :)

提交回复
热议问题