如何理解Python自动化测试pytest中fixtureAPI

发布时间:2021-10-09 13:47:06 作者:iii
来源:亿速云 阅读:176

这篇文章主要讲解了“如何理解Python自动化测试pytest中fixtureAPI”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“如何理解Python自动化测试pytest中fixtureAPI”吧!

什么是fixture

根据pytest官方文档的说明,fixture可以简单的归纳为具有以下功能的函数:

与xUnit风格的setup和teardown的对比

fixture的功能与setup和teardown类似,可以实现setup和teardown的功能,但是对这些功能进行了明显的改进,主要有以下方面:

 fixture运行报错后,pytest的处理方式

通过上面的说明,我们可以知道fixture函数本身是允许调用其他fixture函数的。在这种情况下,测试运行的时候,其中一个fixture函数报错了,pytest的会如何处理呢?
通过pytest官方文档的说明,我们可以知道:

示例1:

1.在以下demo代码中,order()返回类型存在问题,正确的应该返回一个list,我们给其返回一个None:

import pytest
@pytest.fixture
def order():
    return None  #正确应该返回[],我们给返回一个None
@pytest.fixture
def append_first(order):
    order.append(1)
@pytest.fixture
def append_second(order, append_first):
    order.extend([2])
@pytest.fixture(autouse=True)
def append_third(order, append_second):
    order += [3]
def test_order(order):
    assert order == [1, 2,3]

运行后结果如下:

test_order被标记Error,并且信息提示:test setup failed,说明是调用的fixture函数存在问题,且说明了错误原因。

如何理解Python自动化测试pytest中fixtureAPI

2.如果是test_order运行未通,运行信息会怎么样提醒呢?我们按照以下demo修改测试代码,修改test_order的断言语句:

import pytest
@pytest.fixture
def order():
    return []   #返回一个list
@pytest.fixture
def append_first(order):
    order.append(1)
@pytest.fixture
def append_second(order, append_first):
    order.extend([2])
@pytest.fixture(autouse=True)
def append_third(order, append_second):
    order += [3]
def test_order(order):
    assert order == [1, 2]  #断言失败,正确应该是 order==[1,2,3]

运行结果如下:

test_order被标记failed,且提醒是AssertionError,断言出错。这说明是test_order 本身运行未通过。

如何理解Python自动化测试pytest中fixtureAPI

2.fixture API @pytest.fixture()说明

pytest使用@pytest.fixture()来声明fixture方法。具体如何使用,我会在文章后面进行详细说明。在此,主要来简单说明一下fixture()

def fixture(
    fixture_function: Optional[_FixtureFunction] = None,
    *,
    scope: "Union[_Scope, Callable[[str, Config], _Scope]]" = "function",
    params: Optional[Iterable[object]] = None,
    autouse: bool = False,
    ids: Optional[
        Union[
            Iterable[Union[None, str, float, int, bool]],
            Callable[[Any], Optional[object]],
        ]
    ] = None,
    name: Optional[str] = None,
) -> Union[FixtureFunctionMarker, _FixtureFunction]:

参数说明:

2.1 scope

fixture函数的作用域。作用域从小到大依次为:function(默认)classmodulepackagesession

还可传入一个可调用对象,以实现动态修改fixture的作用域。

后面会单独写一篇文章,为大家详细介绍fixture的scope。

2.2 params

传入测试数据集,动态生成测试用例,每一条数据都单独生成一条测试用例。通过request.param,可以获取传入的这些数据。

后面会单独写一篇文章,为大家详细介绍fixture的参数化。

2.3 autouse

fixture自动应用标识。

如果是True,则在同作用域下的测试函数,会自动调用该fixture;如果是False,则测试函数需要主动去调用该fixture。

后面会在介绍fixture调用方法的文章给大家详细说明。

2.4 ids

测试用例ID标识,与parmas传入的参数一一对应。当未定义时,会自动生成id。

示例2:

1.传入ids参数,运行以下demo:

import pytest
@pytest.fixture(params=[1,2,3],ids=['A','B','C'])
def ids(request):
    data=request.param
    print(f'获取测试数据{data}')
    return data
def test_ids(ids):
    print(ids)

运行结果:

在执行信息中,我们可以发现ids的三个参数和params的三个参数一一对应显示,并且ids的参数作为测试用例id的一部分呈现出来。

如何理解Python自动化测试pytest中fixtureAPI

2. 修改上面demo中的代码,不传入ids参数,运行一下:

import pytest
@pytest.fixture(params=[1,2,3]) #未传入ids
def ids(request):
    data=request.param
    print(f'获取测试数据{data}')
    return data
def test_ids(ids):
    print(ids)

运行结果:

查看运行结果我们可以发现,虽然没有传入ids,但是却自动生成了ids

如何理解Python自动化测试pytest中fixtureAPI

测试结束后,我们常常以测试报告的形式来汇报测试结果,如结合allure呈现测试结果。通过ids传入的参数可以对测试用例进行说明,这样更方便我们查看测试结果。

2.5 name

fixture的别名。fixture的name默认是@pytest.fixture所装饰的函数的函数名。使用fixture的别名可以提高代码的阅读性。

示例3:
以下面的demo为例:

import pytest
@pytest.fixture()
def login():
    print('login')
class SubClass:
    def sub_login(self):
        print('subcalss_login')
class TestCase:
    def test_case1(self,login):  #调用fixture——login
        login=SubClass()  #定义一个login并实例化SubClass
        login.sub_login() #调用SubClass中的sub_login()
        print('这是testcase1')

我们定义了一个fixture函数——login(),同时在test_case1中实例化了一个Subclass类,并起名为login,然后调用了SubClass类中的sub_login()。如果代码复杂的情况,很容易将fixture函数的login与SubClass实例的login弄混淆,增加代码的阅读的复杂度。

当我们使用fixture别名的话,在阅读代码的时候就很容易进行区分。

@pytest.fixture(name='module_login') 
def login():
    print('login')
class TestCase:
    def test_case1(self,module_login):  #使用fixture别名:module_login
        login=SubClass()  #定义一个login并实例化SubClass
        login.sub_login() #调用SubClass中的sub_login()
        print('这是testcase1')

注意:

当使用name参数后,则无法再通过@pytest.fixture所装饰的函数的函数名来进行调用,必须使用name所指定fixture别名来调用。

感谢各位的阅读,以上就是“如何理解Python自动化测试pytest中fixtureAPI”的内容了,经过本文的学习后,相信大家对如何理解Python自动化测试pytest中fixtureAPI这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. Python+Requests接口自动化测试之 引入Pytest框架
  2. Python基础学习之 pytest

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

pytest

上一篇:C和C++的区别有哪些

下一篇:在android中怎么用Java加载解析so

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》