python pytest使用_pytest使用详解

pytest:帮助你写出更好的程序:

开源,免费。

升级pytest,严格的向后兼容性。

丰富的第三方插件。

内置assert断言

基础用法

deftest_due():

x=”why”

assert ‘w’ in x

常用断言:pytest里面的断言实际上就是python里面assert的断言方法,常用以下几种:

·assert xx 判断xx为真

·assert not xx 判断xx不为真

·assert a in b 判断b包含a

·assert a == b 判断a等于b

·assert a != b 判断a不等于b

异常信息提示:如果想在异常的时候输出一些提示信息,这样报错后就方便查看是什么原因了

defadd(a,b):return a+bdeftest_assert():assert 6 == add(3,4),”方法返回的值不等于6,而是等于{0}”.format(add(3,4))

python pytest使用_pytest使用详解

异常信息的断言

我们要断言它抛的异常是不是预期的,比如执行:1/0,预期结果是抛异常:ZeroDivisionError: division by zero,那我们要断言这个异常。通常是断言异常的type和value的值。这里1/0的异常类型是ZeroDivisionError,异常的value值是”integer division or modulo by zero”,于是以下是代码的设计用例

importpytestdeftest_zero_division():

with pytest.raises(ZeroDivisionError,message=”Exceptions ZeroDivisionError”) as exinfo:1/0assert exinfo.type ==ZeroDivisionErrorassert str(exinfo.value) == “integer division or modulo by zero”,”{0}”.format(exinfo.value)

message:如果失败,显示失败的原因

deftest_zero_division():

with pytest.raises(ZeroDivisionError,message=’0不能被除’)as exec:pass

fixture可以声明function,module,fixture。也可以使用xunit的fixture的格式,setup和teardown。使用fixtures作为function的参数使用。

小编最常用识货大概就是关联测试接口时候,比如保单的查询,前提条件必须要生成一个新的保单再去查询

@pytest.fixture()defbefore():print ‘\nbefore each test’

deftest_1(before):print ‘test_1()’

deftest_2(before):print ‘test_2()’

assert 0

执行结果:test_1、test_2执行前都要执行before,可以做关联接口测试使用

test_fixture_basic.py::test_1

before each test

test_1()

PASSED

test_fixture_basic.py::test_2

before each test

test_2()

FAILED

scope控制fixtrue调用的频率,默认是function。可选的有:

function:每个测试函数之前执行一次

class:每个测试类之前执行一次

module:每个module之前执行一次

session:每次session之前执行一次,即每次测试执行一次

Original: https://blog.csdn.net/weixin_42144554/article/details/113963392
Author: 雯儿ccu
Title: python pytest使用_pytest使用详解

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/773862/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球