Pytest的测试固件fixture

前言,为什么需要测试固件fixture

  前面学习了setup和teardown,在执行之前执行setup,在执行之后执行teardown

  • 如果是一次执行所有的测试用例,直接用setup和teardown没问题
  • 如果只执行某一个测试用例,这时就需要用到测试固件

实现第一个fixture

  • 所谓的fixture就是python中的一个函数,但是这个函数必须要被pytest中的一个装饰器装饰
    • 例如:
      import pytest
      
      @pytest.fixture()
      def setup():
          print("执行setup.......")
      
      def test_case(setup):
          print("执行第一个测试用例")

      注:函数装饰上@pytest.fixture(),表示这个函数就是一个测试固件了,把这个函数名当作参数传给其它函数,其它函数在执行之前就会先执行它

fixture的自动执行

  问题:如上面实现的第一个fixture示例中,我们必须在测试函数中传入fixture才行,这样的话每次都要在函数中去传入,太麻烦

  • 在fixture中,我们可以传入一个叫autouse的参数,并设置为True,表示每个函数都默认去执行,这时其它函数执行之前之前fixture就不需要传入该函数了
    • 例如:
      import pytest
      
      @pytest.fixture(autouse=True)
      def setup():
          print("执行setup.......")
      
      def test_case1():
          print("执行第一个测试用例")
      
      def test_case2():
          print("执行第二个测试用例")

      注: test_case1执行前会执行setup,test_case2执行之前也会执行test_case1

fixture的作用域

  问题:fixture的自动执行已经在测试每个函数之前都执行一遍fixture装饰的函数,但是如果想实现每个类或者每个模块(py文件)执行前执行一次,怎么办?

  • 在@pytest.fixture中有一个scope参数可以帮助我们修改Fixture的作用域,scope支持以下四种作用域
    • session(会话),所有的测试用例执行前,只会执行一次的操作
    • module (模块,也就是一个py文件),每个py文件之前执行一次
    • class(类),每个类执行前执行一次
    • function(函数),每个函数执行前执行一次
      • 案例
        import pytest
        @pytest.fixture(autouse=True,scope="class")
        def setup():
            print("执行setup.......")
            
        class Test_Case(object):
        
            def test_case1(self):
                print("执行第一个测试用例")
        
            def test_case2(self):
                print("执行第二个测试用例")
        
        class Test_Case2(object):
        
            def test_case3(self):
                print("执行第三个测试用例")
        
            def test_case4(self):
                print("执行第四个测试用例")

        注:在类test_case1和test_case2执行之前会执行setup

fixture全局注册

  • fixture是写在一个py文件中的,只对这一个py文件起作用,如果其它的测试用例中也需要怎么办,这时就需要设置为全局的作用域
  • 全局注册
    • 在项目根目录下,新建一个conftest.py文件
    • 在conftest.py文件中可以把之前的fixture代码放入其中
    • 在conftest.py文件中写入fixture代码,scope写入作用域,就可以对某个作用域有用,例如图中作用域为class,就对用例中的class有用

fixture实现teardown

  • 在上述的作用域中写了setup,只对执行之前有用,但是我们还需要在执行之后也有用,这时需要在conftest.py文件中的fixture固件中加入一行代码,用yield进行分隔
    • 例如:

      conftest.py

      import pytest
      @pytest.fixture(autouse=True,scope="class")
      def setup():
          print("执行setup.......")
          yield
          print("用例执行之后执行")

       

      用例代码,py文件
      class Test_Case(object):
      
          def test_case1(self):
              print("执行第一个测试用例")
      
          def test_case2(self):
              print("执行第二个测试用例")
      
      class Test_Case2(object):
      
          def test_case3(self):
              print("执行第三个测试用例")
      
          def test_case4(self):
              print("执行第四个测试用例")
    • 注:在类执行之前会执行yield上面的代码,在类执行之后就会执行yield之后的代码

posted @ 2023-04-14 00:54  A熙  阅读(53)  评论(0)    收藏  举报