Pytest系列(8)- fixture的用法

fixture的应用场景

  • 比如在自动化的过程中,有的用例需要登录才能执行,有的用例不需要登录,这种场景setup和teardown比较难满足,fixture可以满足这种场景

fixture优点

  • 命令灵活:对于setupteardown,可以不起这两个名字

  • 数据共享:在conftest.py配置李写方法可以实现数据共享,不需要import导入

  • scope的层次及与yield组合相当于各种setupteardown

fixture参数

@pytest.fixture(scope="function", params=None, autouse=False, ids=None, name=None)
def test():
    print("fixture初始化的参数列表")

参数列表

  • scope:即作用域,默认function,常用class、module、package、session(整个项目)
  • autouse:默认false,若设置为true,则所有的测试用例执行前会自动调用该fixture

使用方法

定义

  • 使用装饰器来定义fixture@pytest.fixture()

调用

  • 若需使用fixture的返回数据,需使用fixture的名字来引用
  • 若不需要使用fixture的返回数据,则可以使用装饰器@pytest.mark.usefixtures('fixture_name')来使用fixture

即👇👇👇

@pytest.fixture(scope='module')
def login():
    print("实现登录")
    return "token"
def test_case1(login):
    print("cese1")

🍄 ATTENTION:

  • 不设置autouse为true时,需要手动调用fixture
  • 若在测试用例中需要用到fixture的返回数据,那么一定要在用例的参数中加上fixture的名字

yield实现teardown

yield在python里可以实现生成器??(这里我还需要再了解一下)

import pytest

@pytest.fixture(scope='module', autouse=True)
def login():
    print("实现登录")
    yield "token"
    print("退出登录")

def test_case1():
    print("cese1")

def test_case2():
    print("case2")

def test_case3():
    print("case3")

运行结果👇👇👇

说明

  • yield相当于return(可以记录上一次的执行位置,下一次继续执行后面的内容)

  • yield之前的操作相当于setup

  • yield之后的操作相当于teardown

🍄 ATTENTION:

  • 如果yield前面的代码,即setup部分已经抛出异常了,则不会执行yield后面的teardown内容
  • 如果测试用例抛出异常,yield后面的teardown内容还是会正常执行

TIPS:可以通过命令行参数pytest xx.py --setup-show查看fixture的执行过程

posted @ 2021-11-22 22:13  莫伊101  阅读(63)  评论(0编辑  收藏  举报