Python测试框架pytest(04)
fixture
测试用例调用fixture、fixture传递测试数据
setup、teardown 可以实现在执行用例前或结束后加入一些操作,但这种都是针对整个脚本全局的。
假设有以下场景:用例A需要先登录,用例B不需要登录,用例C需要先登录;很显然无法用 setup 和 teardown 来实现。
fixture 的作用是可以让我们自定义测试用例的前置条件。
fixture的优势:
fixture的参数列表:
@pytest.fixture(scope="function", params=None, autouse=False, ids=None, name=None)
def test():
print("fixture初始化的参数列表")
1、创建test_fixture_0.py文件
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公众号:AllTests软件测试
"""
import pytest
@pytest.fixture()
def fixturefun():
return 123
def test_case(fixturefun):
assert fixturefun == 123
@pytest.fixture() 装饰器用于声明函数是一个 fixture,如果测试用例的参数中包含此 fixture 函数,则在测试用例运行前会先运行此 fixture 函数。如果 fixture 函数有返回值,则将返回值传递给测试用例函数。
2、运行结果:
fixturefun 函数返回123给 test_case 函数,则断言成功。
1、测试用例调用fixture
1、创建test_fixture.py文件
调用的三种方式:
(1)将 fixture 名称作为测试用例函数的输入参数,例如 login 是 test_s1 函数的输入参数。
(2)测试用例加上装饰器:@pytest.mark.usefixtures(fixture_name)
(3)fixture 设置 autouse=True
脚本代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公众号:AllTests软件测试
"""
import pytest
# 调用方式一
@pytest.fixture
def login():
print("输入账号 login,密码登录")
def test_s1(login):
print("用例 1:登录之后其它动作 test_s1")
def test_s2():
print("用例 2:不需要登录,操作 test_s2")
# 调用方式二
@pytest.fixture
def login2():
print("输入账号 login2,密码登录")
@pytest.mark.usefixtures("login2", "login")
def test_s3():
print("用例 3:登录之后其它动作 test_s3")
# 调用方式三
@pytest.fixture(autouse=True)
def login3():
print("====login3====")
# 不是test开头,加了装饰器也不会执行fixture
@pytest.mark.usefixtures("login2")
def login4():
print("====login4====")
2、运行结果:
(1)login3 设置为 autouse=True,则每次执行用例前都会先执行 login3
(2)test_s1 引用了入参 login,则先执行 login,之后再执行 test_s1
(3)test_s2 没有引用入参,直接执行 test_s2
(4)test_s3 使用了装饰器,则先执行 login2,之后 login,最后 test_s3
(5)login4 加了装饰器,但不是 test 开头,所以不会执行
关键点:
2、fixture传递测试数据
1、创建test_fixture_1.py文件
脚本代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
微信公众号:AllTests软件测试
"""
import pytest
@pytest.fixture()
def fixturefun():
return (1,2,3,4)
def test_one(fixturefun):
assert fixturefun[0] == 2
def test_two(fixturefun):
assert fixturefun[1] == 2
2、运行结果:
函数 test_one 断言失败,fixturefun[0] 值是1,fixturefun[1] 的值才是2。
函数 test_two 断言成功。
本文分享自 AllTests软件测试 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!