五、谈谈调用 fixture 的3种方式

1. fixture 的3种调用方式:

  (1)将 fixture 名称直接作为测试函数或者测试类中方法参数传入,前提是需要自定义好对应的 fixture,直接传入fixture名称(即函数名即可)。

  (2)使用 pytest.mark.usefixtures("fixture名称") 装饰测试函数或者测试方法,此种方法的测试固件需要通过全局变量来进行传递。

  (3)直接通过测试固件自带的属性 autouse 完成固件的应用操作,需要将 autouse 的值设置为 True。 

import pytest

@pytest.fixture()
def login():
print("前置操作,输入账号密码登录")

# 1.将 fixture 名称直接作为测试函数传入
def test_1(login):
print("执行测试用例1,继承 login 函数,前置登录后继续下一步操作")


def test_2():
print("用例2,不需要登录")


def test_3(login):
print("执行测试用例3,继承 login 函数,前置登录后继续下一步操作")

# 2.使用 pytest.mark.usefixtures() 引用 fixture
@pytest.mark.usefixtures("login")
def test_4():
  print("执行测试用例4,使用 usefixtures() 调用 fixture")

# 3.使用 @pytest.fixture(autouse=True) 调用 fixture
@pytest.fixture(autouse=True)
def login_2():
  print("前置操作,输入账号密码登录")

def test_5():
  print("执行测试用例5,自动调用 fixture 进行登录")

if __name__ == '__main__':
pytest.main()
posted @ 2024-06-25 21:04  努力的小测试  阅读(118)  评论(0)    收藏  举报