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

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

    You can add your global variable as an option inside the pytest_addoption hook. It is possible to do it explicitly with addoption or use set_defaults method if you want your attribute be determined without any inspection of the command line, docs


    When option was defined, you can paste it inside any fixture with request.config.getoption and then pass it to the test explicitly or with autouse. Alternatively, you can pass your option into almost any hook inside the config object.

    #conftest.py
    def pytest_addoption(parser):    
        parser.addoption("--my_global_var", default="foo")
        parser.set_defaults(my_hidden_var="bar")
    
    @pytest.fixture()
    def my_hidden_var(request):
        return request.config.getoption("my_hidden_var")
    
    #test.py
    def test_my_hidden_var(my_hidden_var):
        assert my_hidden_var == "bar"
    

提交回复
热议问题