py.test session level fixtures in setup_method

前端 未结 3 1856
长发绾君心
长发绾君心 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:42

    For the example provided above, the object returned from the fixture can be set as an attribute of the test class. Any methods of this class will have access.

    # test_fixture.py
    
    import pytest
    
    class TestAAA():
    @pytest.fixture(scope="class", autouse=True)
    def setup(self, myfixture):
        TestAAA.myfixture = myfixture
    
    def test_function1(self):
        assert self.myfixture == "myfixture"
    

    or if you inherit from unittest.Testcase you can do the following

    # test_fixture.py
    
    import pytest
    from unittest import TestCase
    
    class TestAAA(TestCase):
        @pytest.fixture(scope="class", autouse=True)
        def setup(self, myfixture):
            self.myfixture = myfixture
    
        def test_function1(self):
            self.assertEqual(self.myfixture, "myfixture")
    

提交回复
热议问题