py.test session level fixtures in setup_method

前端 未结 3 1854
长发绾君心
长发绾君心 2021-02-19 19:05

Is there a way to somehow use pytest fixtures from conftest.py in a test class\'s setup? I need to initialize an object when the session starts and use it in so

3条回答
  •  终归单人心
    2021-02-19 19:23

    I used this kind of a setup for a test class with pytest<=3.7.0 (it stopped working with pytest 3.7.1 release):

    # conftest.py:
    
    import pytest
    
    # autouse=True does not work for fixtures that return value
    # request param for fixture function is only required if the fixture uses it:
    # e.g. for a teardown or parametrization. Otherwise don't use it.
    @pytest.fixture(scope="session")
    def myfixture():
        return "myfixture"
    

    # test_aaa.py
    
    import pytest
    
    class TestAAA(object):
        @classmethod
        @pytest.fixture(scope="class", autouse=True)
        def setup(self, myfixture):
            self.myfixture = myfixture
    
        def test_function1(self):
            # now you can use myfixture without passing it as param to each test function   
            assert self.myfixture == "myfixture"
    

提交回复
热议问题