Pytest测试实战|执行常用命令

Pytest测试实战

本文章主要详细地阐述下Pytest测试框架执行TestCase常用命令。

按分类执行

在Pytest测试框架中按照分类执行的命令为“-k”,它的主要特点是按照TestCase名字的模式来执行,在编写具体的TestCase的时候,都会编写每个TestCase的名称,一般而言TestCase名称都是需要被测对象模块的名称,这样执行的时候可以按照实际需求选择性的执行需要执行的模块,案例代码如下:


import pytest


def test_login_001():

pass


def test_login_002():

pass


def test_product():

pass


def test_platform():

pass

如上的测试模块中编写的被测对象分别是login、product、platform,如果只是想执行login模块的代码,那么执行的命令为:

pytest -s -v -k "login" test_command.py

执行后的结果信息如下所示。

图片

如果想同时执行login与platform模块的TestCase,执行的命令为:

pytest -s -v -k "login or platform" test_command.py

如上可以看到使用or的关系来解决多个模块需要同时执行的问题,执行后的结果信息如下所示。

图片

按分组执行

按照分组执行使用的命令是“-m”。在编写TestCase的时候会针对TestCase按照业务属性打标签,那么使用“-m”可以按照标签的模式来进行执行,比如编写的TestCase中有部分是SmokeTest,打的标签一般是“smoke”,应用的场景如环境部署后,需要验证环境的可用性,只需要执行打的标签为“smoke”的TestCase,案例代码如下。

 

import pytest


@pytest.mark.smoke

def test_login_001():

pass


def test_login_002():

pass


@pytest.mark.smoke

def test_product():

pass


@pytest.mark.smoke

def test_platform():

pass


@pytest.mark.book

def test_book_001():

pass

如上代码中TestCase打的标签分别是“smoke与book”,如果只执行标签为“smoke”,那么执行的命令如下。

pytest -s -v -m "smoke" test_command.py

执行结果信息如下。

图片

根据如上的结果信息可以看到,只执行了标签为“smoke”的TestCase,其他的并没有执行,如果一个TestCase同时打了多个标签但是又需要执行它,那么使用“and”就可以了,案例代码如下。

 

import pytest


@pytest.mark.smoke

@pytest.mark.login

def test_login_001():

pass


@pytest.mark.login

def test_login_002():

pass


@pytest.mark.smoke

def test_product():

pass


@pytest.mark.smoke

def test_platform():

pass


@pytest.mark.book

def test_book_001():

pass

执行命令如下所示。

 pytest -s -v -m "smoke and login" test_command.py

执行结果如下所示。

图片

执行失败立刻停止

Fixtue执行失败立刻停止使用到的命令为“-x”,一般不建议使用该命令,理由是在TestCase执行的时候,不能因为失败就停止执行,而大多数的时候需要把被执行的TestCase全部执行完成,再分析执行失败的具体原因到底是什么?一般这种情况需要加入重试的机制,如在API测试中,第一次请求可能HTTP协议状态码不是200,而是非200,那么此时再等待几秒再次发送请求,可能HTTP返回的协议状态码是200,因为这个过程有可能网关层异常,如API GateWay TimeOut时会返回504。

忽略执行

忽略执行使用到的命令为“-rs”,这样的场景在实际工作中应用还是很广泛的,具体如编写的TestCase,但是由于业务调整,这部分TestCase不需要执行了,那么这些TestCase可以打上“skip”的标签并且说明理由,见案例代码。

 

import pytest


@pytest.mark.smoke

@pytest.mark.login

def test_login_001():

pass


@pytest.mark.login

def test_login_002():

pass


@pytest.mark.smoke

def test_product():

pass


@pytest.mark.skip("屏蔽平台入口")

def test_platform():

pass

如执行的时候忽略执行加了标签“skip”的TestCase,执行命令如下。

pytest -s -v -rs test_command.py

执行后的结果信息如下。

图片

如上所示可以看到打了“skip”标签的TestCase执行的时候会忽略并且显示忽略执行的信息。

在Pytest测试框架中执行TestCase使用到的命令会非常丰富,本文章主要总结了执行TestCase常用的命令,关于使用命令分布式执行后续文章介绍,感谢您的阅读。

最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:【文末自行领取】

这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值