Pytest测试框架基础-fixture详解

  fixture修饰的方法可以被其他函数引用,这样就可以实现类似 setup,teardown的效果,但是fixture更加灵活,下面将详细讲解一下其用法。

  

  一、方式1:直接将fixture修饰的方法名称当做参数传入,如下代码:

  

import pytest
from selenium import webdriver

@pytest.fixture()
def open():
    driver = webdriver.Chrome()
    driver.maximize_window()
    print('启动浏览器')
    return driver
    #或者yield driver

def test_case01(open):
    driver = open
    driver.get("https://www.baidu.com")
    print('第一个测试用例')

def test_case02(open):
    driver = open
    driver.get('https://www.cnblogs.com/longlongleg/')
    print('第二个测试用例')


def test_case03(open):
   open.get('https://www.google.com.hk/')
    print('第三个测试用例')

def test_case04():
   
    print('第四个测试用例')
if __name__ == '__main__': pytest.main(['-vs','test_case01.py'])

  open是由fixture修饰的一个方法,在其他的测试用例当中,将open做为参数引入。每一个测试用例都会运行一遍open的方法,没有引用的如case04,则不会运行open函数内容。yield跟return类似,都可以返回参数,但是return后面如果还有内容不会运行,但是yield会运行其后的内容

  二、方式2:添加范围进行引用@pytest.fixture(scope='class'),范围有多种,如下

    function: 默认作用域,每个测试用例都运行一次

    class: 每个测试类只执行一次

    module: 每个模块只执行一次

    package:每个python包只执行一次

    session: 整个会话只执行一次,即整个项目运行时,只执行一次

    

    以class为例

import pytest

@pytest.fixture(scope='class')
def open():
    print('hello,world')


@pytest.mark.usefixtures('open')
class TestDemo:

    def test_case1(self):
        print('case 01')

    def test_case2(self):
        print('case 02')

    def test_case3(self):
        print('case 3')



if __name__ == '__main__':
    pytest.main(['-vs','testcase02.py'])

    运行TestDemo里面的测试用例之前,会执行一次open函数。也可以将open当做参数写在每个testcase里面。

    以module为例,将fixture修饰的函数写在conftest中,被引用的参数会默认先去寻找conftest.py里面的方法,代码如下所示

    conftest.py

from selenium import webdriver
import pytest

@pytest.fixture(scope='module')
def open():
    driver = webdriver.Chrome()
    driver.maximize_window()
   print('open function')
   return driver

    testcase.py

import pytest


class Testcase:

    def testcase01(self,open):
        open.get("https://www.baidu.com")
        print('Testcase03:case1')

    def testcase02(self,open):
        open.get("https://www.google.com.hk/")
        print('Testcase03:case2')

def testcase03(open):
    open.get('https://www.cnblogs.com/longlongleg/')
    print('Testcase03:case3')

if __name__ == '__main__':
    pytest.main(['-vs','testcase.py'])

  

  此时三个testcase都只会运行一次open,如果范围为class,那么会运行两次open。因为最后一个测试用例不属于class Testcase类里面。

  module范围输出内容

  

 

   如果为class范围,输出内容

  

 

posted @ 2021-07-28 16:48  longlongleg  阅读(195)  评论(0编辑  收藏  举报