当前位置:   article > 正文

pytest框架-详解(学习pytest框架这一篇就够了)

pytest

目录

一、前言

二、pytest安装

2.1、安装

2.2、验证安装

2.3、pytest文档

三、pytest框架的约束

3.1、 python的命名规则

3.2、 pytest的命名规则

四、pytest的运行方式

4.1、主函数运行

4.2、命令行运行

4.3、pytest.ini配置文件方式运行(常用)

五、pytest配置文件pytest.ini文件

六、pytest的常用插件

七、pytest中conftest.py文件

7.1、conftest.py的特点

7.2、conftest.py的示例目录

八、pytest中fixtrue装饰器

8.1、前言

8.2、fixtrue的优势

8.3、Fixture的调用方式:

8.4、Fixture的作用范围

8.5、fixtrue参数详解-scope 

8.5.1、scope = “function”

8.5.2、scope = “class”

8.5.3、scope = “module”:与class相同,只从.py文件开始引用fixture的位置生效​​​​​​​

8.6、fixtrue参数详解-autouse

8.7、fixtrue参数详解params

8.8、fixtrue参数详解-ids

8.9、fixtrue参数详解-name

九、pytest跳过测试用例skip、skipif

9.1、@pytest.mark.skip

9.2、pytest.skip()函数基础使用

9.3、 pytest.skip(msg=“”,allow_module_level=False)

9.4、 pytest.skip(msg=“”,allow_module_level=False)

9.5、跳过标记

9.6、pytest.importorskip( modname: str, minversion: Optional[str] = None, reason: Optional[str] = Nonse )

9.7、使用自定义标记 mark

十、pytest参数化 @pytest.mark.parametrize

10.1、函数数据参数化

十一、pytest标记为失败函数和失败重试

11.1 、标记为预期失败的函数

11.2 失败后重试

十二、pytest调整执行顺序

十三、pytest设置断点

十四、pytest获取用例执行性能数据

十五、pytest生成测试报告

3.1、下载Allure插件

3.2、生成临时的json报告(过度)

3.3、生成html报告

 3.4、allure测试报告优化

十六、pytest中管理日志

16.1、日志级别

16.2、分析解释

16.3、日志输出-控制台

16.4、日志输出-文件

16.5、日志输出-控制台和文件

16.6、format常用格式说明

16.7、捕捉异常traceback记录

16.8、多模块调用logging,日志输出顺序

16.9、日志滚动和过期删除(按时间)

十七、总结


一、前言

pytest是一个非常成熟的全功能的Python测试框架,主要有以下几个特点:

 1、简单灵活,非常方便的组织自动化测试用例;

 2、支持参数化,可以细粒度地控制要测试的测试用例;

 3、能够支持简单的单元测试和复杂的功能测试,比如web端selenium/移动端appnium等自动化测试、request接口自动化测试

 4、pytest具有很多第三方插件,并且可以自定义扩展,比如测试报告生成,失败重运行机制

 5、测试用例的skip和fail处理;

 6、结合业界最美的测试报告allure+Jenkins,持续集成

二、pytest安装

2.1、安装

pip install -U pytest

2.2、验证安装

pytest --version # 会展示当前已安装版本

2.3、pytest文档

官方文档:https://docs.pytest.org/en/latest/contents.html

三、pytest框架的约束

3.1、 python的命名规则


1)py文件全部小写,多个英文用_隔开
2)class名首字母大写,驼峰
3)函数和方法名小写,多个英文用_隔开
4)全局变量,前面要加global
5)常量字母必须全大写,如:AGE_OF_NICK

3.2、 pytest的命名规则


1)模块名(py文件)必须是以test_开头或者_test结尾
2)测试类(class)必须以Test开头,并且不能带init方法,类里的方法必须以test_开头
3)测试用例(函数)必须以test_开头

四、pytest的运行方式

4.1、主函数运行

  1. import pytest
  2. def test_01():
  3. print("啥也没有")
  4. if __name__=='__main__':
  5. pytest.main()
'
运行

main中可使用的参数有:

参数描述案例
-v输出调试信息。如:打印信息pytest.main([‘-v’,‘testcase/test_one.py’,‘testcase/test_two.py’])
-s输出更详细的信息,如:文件名、用例名pytest.main([‘-vs’,‘testcase/test_one.py’,‘testcase/test_two.py’])
-n多线程或分布式运行测试用例
-x只要有一个用例执行失败,就停止执行测试pytest.main([‘-vsx’,‘testcase/test_one.py’])
– maxfail出现N个测试用例失败,就停止测试pytest.main([‘-vs’,‘-x=2’,‘testcase/test_one.py’]
–html=report.html生成测试报告pytest.main([‘-vs’,‘–html=./report.html’,‘testcase/test_one.py’])
-m通过标记表达式执行
-k根据测试用例的部分字符串指定测试用例,可以使用and,or

4.2、命令行运行


文件路径:testcase/test_one.py

  1. def test_a():
  2. print("啥也不是")
  3. assert 1==1
  4. #终端输入:pytest ./testcase/test_one.py --html=./report/report.html
'
运行
参数描述案例
-v输出调试信息。如:打印信息pytest -x ./testcase/test_one.py
-q输出简单信息。pyets -q ./testcase/test_one.py
-s输出更详细的信息,如:文件名、用例名pytest -s ./testcase/test_one.py
-n多线程或分布式运行测试用例
-x只要有一个用例执行失败,就停止执行测试pytest -x ./testcase/test_one.py
– maxfail出现N个测试用例失败,就停止测试pytest --maxfail=2 ./testcase/test_one.py
–html=report.html生成测试报告pytest ./testcase/test_one.py --html=./report/report.html
–html=report.html生成测试报告pytest ./testcase/test_one.py --html=./report/report.html
-k根据测试用例的部分字符串指定测试用例,可以使用and,orpytest -k “MyClass and not method”,这条命令会匹配文件名、类名、方法名匹配表达式的用例,这里这条命令会运行 TestMyClass.test_something, 不会执行 TestMyClass.test_method_simple

4.3、pytest.ini配置文件方式运行(常用)

不管是mian执行方式还是命令执行,最终都会去读取pytest.ini文件
在项目的根目录下创建pytest.ini文件

  1. [pytest]
  2. addopts=-vs -m slow --html=./report/report.html
  3. testpaths=testcase
  4. test_files=test_*.py
  5. test_classes=Test*
  6. test_functions=test_*
  7. makerers=
  8. smock:冒烟测试用例

pytset.ini文件尽可能不要出现中文。

参数作用
[pytest]用于标志这个文件是pytest的配置文件
addopts命令行参数,多个参数之间用空格分隔
testpaths配置搜索参数用例的范围
python_files改变默认的文件搜索规则
python_classes改变默认的类搜索规则
python_functions改变默认的测试用例的搜索规则
markers用例标记,自定义mark,需要先注册标记,运行时才不会出现warnings

五、pytest配置文件pytest.ini文件

pytest的配置文件通常放在测试目录下,名称为pytest.ini,命令行运行时会使用该配置文件中的配置.

  1. #配置pytest命令行运行参数
  2. [pytest]
  3. addopts = -s ... # 空格分隔,可添加多个命令行参数 -所有参数均为插件包的参数配置测试搜索的路径
  4. testpaths = ./scripts # 当前目录下的scripts文件夹 -可自定义
  5. #配置测试搜索的文件名称
  6. python_files = test*.py
  7. #当前目录下的scripts文件夹下,以test开头,以.py结尾的所有文件 -可自定义
  8. 配置测试搜索的测试类名
  9. python_classes = Test_*
  10. #当前目录下的scripts文件夹下,以test开头,以.py结尾的所有文件中,以Test开头的类 -可自定义
  11. 配置测试搜索的测试函数名
  12. python_functions = test_*
  13. #当前目录下的scripts文件夹下,以test开头,以.py结尾的所有文件中,以Test开头的类内,以test_开头的方法 -可自定义

六、pytest的常用插件

 插件列表网址:https://plugincompat.herokuapp.com
包含很多插件包,大家可依据工作的需求选择使用。

七、pytest中conftest.py文件

7.1、conftest.py的特点

  • pytest 会默认读取 conftest.py里面的所有 fixture
  • conftest.py 文件名称是固定的,不能改动
  • conftest.py 只对同一个 package 下的所有测试用例生效
  • 不同目录可以有自己的 conftest.py,一个项目中可以有多个 conftest.py
  • 测试用例文件中不需要手动 import conftest.py,pytest 会自动查找

7.2、conftest.py的示例目录

最顶层的 conftest,一般写全局的 fixture

八、pytest中fixtrue装饰器

8.1、前言

虽然setup和teardown可以执行一些前置和后置操作,但是这种是针对整个脚本全局生效的
如果有以下场景:1.用例一需要执行登录操作;2.用例二不需要执行登录操作;3.用例三需要执行登录操作,则setup和teardown则不满足要求。fixture可以让我自定义测试用例的前置条件

8.2、fixtrue的优势

  • 命名方式灵活,不限于setup和teardown两种命名
  • conftest.py可以实现数据共享,不需要执行import 就能自动找到fixture
  • scope=module,可以实现多个.py文件共享前置
  • scope=“session” 以实现多个.py 跨文件使用一个 session 来完成多个用例

8.3、Fixture的调用方式:

@pytest.fixture(scope = "function",params=None,autouse=False,ids=None,name=None)

8.4、Fixture的作用范围

取值范围 说明
function函数级 每一个函数或方法都会调用
class函数级 模块级 每一个.py文件调用一次
module模块级 每一个.py文件调用一次
session会话级 每次会话只需要运行一次,会话内所有方法及类,模块都共享这个方法

8.5、fixtrue参数详解-scope 

用于控制Fixture的作用范围
作用类似于Pytest的setup/teardown
默认取值为function(函数级别),控制范围的排序为:session > module > class > function

8.5.1、scope = “function”
  • 场景一:做为参数传入
  1. import pytest
  2. # fixture函数(类中) 作为多个参数传入
  3. @pytest.fixture()
  4. def login():
  5. print("打开浏览器")
  6. a = "account"
  7. return a
  8. @pytest.fixture()
  9. def logout():
  10. print("关闭浏览器")
  11. class TestLogin:
  12. #传入lonin fixture
  13. def test_001(self, login):
  14. print("001传入了loging fixture")
  15. assert login == "account"
  16. #传入logout fixture
  17. def test_002(self, logout):
  18. print("002传入了logout fixture")
  19. def test_003(self, login, logout):
  20. print("003传入了两个fixture")
  21. def test_004(self):
  22. print("004未传入仍何fixture哦")
  23. if __name__ == '__main__':
  24. pytest.main()
'
运行

从运行结果可以看出,fixture做为参数传入时,会在执行函数之前执行该fixture函数。再将值传入测试函数做为参数使用,这个场景多用于登录

  • 场景二:Fixture的相互调用
  1. import pytest
  2. # fixtrue作为参数,互相调用传入
  3. @pytest.fixture()
  4. def account():
  5. a = "account"
  6. print("第一层fixture")
  7. return a
  8. #Fixture的相互调用一定是要在测试类里调用这层fixture才会生次,普通函数单独调用是不生效的
  9. @pytest.fixture()
  10. def login(account):
  11. print("第二层fixture")
  12. class TestLogin:
  13. def test_1(self, login):
  14. print("直接使用第二层fixture,返回值为{}".format(login))
  15. def test_2(self, account):
  16. print("只调用account fixture,返回值为{}".format(account))
  17. if __name__ == '__main__':
  18. pytest.main()
'
运行

1.即使fixture之间支持相互调用,但普通函数直接使用fixture是不支持的,一定是在测试函数内调用才会逐级调用生效
2.有多层fixture调用时,最先执行的是最后一层fixture,而不是先执行传入测试函数的fixture
3.上层fixture的值不会自动return,这里就类似函数相互调用一样的逻辑

8.5.2、scope = “class”

**当测试类内的每一个测试方法都调用了fixture,fixture只在该class下所有测试用例执行前执行一次

**测试类下面只有一些测试方法使用了fixture函数名,这样的话,fixture只在该class下第一个使用fixture函数的测试用例位置开始算,后面所有的测试用例执行前只执行一次。而该位置之前的测试用例就不管。
语法

1@pytest.fixture(scope='class')
  1. import pytest
  2. # fixture作用域 scope = 'class'
  3. @pytest.fixture(scope='class')
  4. def login():
  5. print("scope为class")
  6. class TestLogin:
  7. def test_1(self, login):
  8. print("用例1")
  9. def test_2(self, login):
  10. print("用例2")
  11. def test_3(self, login):
  12. print("用例3")
  13. if __name__ == '__main__':
  14. pytest.main()
'
运行
  1. import pytest
  2. @pytest.fixture(scope='class')
  3. def login():
  4. a = '123'
  5. print("输入账号密码登陆")
  6. class TestLogin:
  7. def test_1(self):
  8. print("用例1")
  9. def test_2(self, login):
  10. print("用例2")
  11. def test_3(self, login):
  12. print("用例3")
  13. def test_4(self):
  14. print("用例4")
  15. if __name__ == '__main__':
  16. pytest.main()
'
运行
8.5.3、scope = “module”:与class相同,只从.py文件开始引用fixture的位置生效
  1. import pytest
  2. # fixture scope = 'module'
  3. @pytest.fixture(scope='module')
  4. def login():
  5. print("fixture范围为module")
  6. def test_01():
  7. print("用例01")
  8. def test_02(login):
  9. print("用例02")
  10. class TestLogin():
  11. def test_1(self):
  12. print("用例1")
  13. def test_2(self):
  14. print("用例2")
  15. def test_3(self):
  16. print("用例3")
  17. if __name__ == '__main__':
  18. pytest.main()
'
运行

8.5.4、scope = “session”:

session的作用范围是针对.py级别的,module是对当前.py生效,seesion是对多个.py文件生效
session只作用于一个.py文件时,作用相当于module
所以session多数与contest.py文件一起使用,做为全局Fixture

8.6、fixtrue参数详解-autouse

默认False
若为True,刚每个测试函数都会自动调用该fixture,无需传入fixture函数名
由此我们可以总结出调用fixture的三种方式:
  1.函数或类里面方法直接传fixture的函数参数名称
  2.使用装饰器@pytest.mark.usefixtures()修饰
  3.autouse=True自动调用,无需传仍何参数,作用范围跟着scope走(谨慎使用)
让我们来看一下,当autouse=ture的效果:

8.7、fixtrue参数详解params

Fixture的可选形参列表,支持列表传入
默认None,每个param的值
fixture都会去调用执行一次,类似for循环
可与参数ids一起使用,作为每个参数的标识,详见ids
被Fixture装饰的函数要调用是采用:Request.param(固定写法,如下图)
举个栗子:

8.8、fixtrue参数详解-ids

用例标识ID与params配合使用,一对一关系
举个栗子:
未配置ids之前,用例:

配置了IDS后:

8.9、fixtrue参数详解-name

fixture的重命名
通常来说使用 fixture 的测试函数会将 fixture 的函数名作为参数传递,但是 pytest 也允许将fixture重命名
如果使用了name,那只能将name传如,函数名不再生效
调用方法:@pytest.mark.usefixtures(‘fixture1’,‘fixture2’)
举栗:

  1. import pytest
  2. @pytest.fixture(name="new_fixture")
  3. def test_name():
  4. pass
  5. #使用name参数后,传入重命名函数,执行成功
  6. def test_1(new_fixture):
  7. print("使用name参数后,传入重命名函数,执行成功")
  8. #使用name参数后,仍传入函数名称,会失败
  9. def test_2(test_name):
  10. print("使用name参数后,仍传入函数名称,会失败")
'
运行

九、pytest跳过测试用例skip、skipif

9.1、@pytest.mark.skip

跳过执行测试用例,有可选参数 reason:跳过的原因,会在执行结果中打印

  • @pytest.mark.skip可以加在函数上,类上,类方法上
  • 如果加在类上面,类里面的所有测试用例都不会执行
  1. import pytest
  2. @pytest.fixture(autouse=True)
  3. def login():
  4. print("====登录====")
  5. def test_case01():
  6. print("我是测试用例11111")
  7. @pytest.mark.skip(reason="不执行该用例!!因为没写好!!")
  8. def test_case02():
  9. print("我是测试用例22222")
  10. class Test1:
  11. def test_1(self):
  12. print("%% 我是类测试用例1111 %%")
  13. @pytest.mark.skip(reason="不想执行")
  14. def test_2(self):
  15. print("%% 我是类测试用例2222 %%")
  16. @pytest.mark.skip(reason="类也可以跳过不执行")
  17. class TestSkip:
  18. def test_1(self):
  19. print("%% 不会执行 %%")
'
运行

9.2、pytest.skip()函数基础使用

作用:在测试用例执行期间强制跳过不再执行剩余内容
类似:在Python的循环里面,满足某些条件则break 跳出循环

  1. def test_function():
  2. n = 1
  3. while True:
  4. print(f"这是我第{n}条用例")
  5. n += 1
  6. if n == 5:
  7. pytest.skip("我跑五次了不跑了")
'
运行

执行结果:

9.3、 pytest.skip(msg=“”,allow_module_level=False)

当 allow_module_level=True 时,可以设置在模块级别跳过整个模块

  1. import sys
  2. import pytest
  3. if sys.platform.startswith("win"):
  4. pytest.skip("skipping windows-only tests", allow_module_level=True)
  5. @pytest.fixture(autouse=True)
  6. def login():
  7. print("====登录====")
  8. def test_case01():
  9. print("我是测试用例11111")
'
运行

9.4、 pytest.skip(msg=“”,allow_module_level=False)

方法:
skipif(condition, reason=None)
参数:
condition:跳过的条件,必传参数
reason:标注原因,必传参数
使用方法:
@pytest.mark.skipif(condition, reason=“xxx”)

  1. import pytest
  2. class Test_ABC:
  3. def setup_class(self):
  4. print("------->setup_class")
  5. def teardown_class(self):
  6. print("------->teardown_class")
  7. def test_a(self):
  8. print("------->test_a")
  9. assert 1
  10. @pytest.mark.skipif(condition=2>1,reason = "跳过该函数") # 跳过测试函数test_b
  11. def test_b(self):
  12. print("------->test_b")
  13. assert 0
  14. 执行结果:
  15. test_abc.py
  16. ------->setup_class
  17. ------->test_a #只执行了函数test_a
  18. .
  19. ------->teardown_class
  20. s # 跳过函数

9.5、跳过标记

  • 可以将 pytest.mark.skip 和 pytest.mark.skipif 赋值给一个标记变量
  • 在不同模块之间共享这个标记变量
  • 若有多个模块的测试用例需要用到相同
  • 的 skip 或 skipif ,可以用一个单独的文件去管理这些通用标记,然后适用于整个测试用例集
  1. # 标记
  2. skipmark = pytest.mark.skip(reason="不能在window上运行=====")
  3. skipifmark = pytest.mark.skipif(sys.platform == 'win32', reason="不能在window上运行啦啦啦=====")
  4. @skipmark
  5. class TestSkip_Mark(object):
  6. @skipifmark
  7. def test_function(self):
  8. print("测试标记")
  9. def test_def(self):
  10. print("测试标记")
  11. @skipmark
  12. def test_skip():
  13. print("测试标记")

9.6、pytest.importorskip( modname: str, minversion: Optional[str] = None, reason: Optional[str] = Nonse )

作用:如果缺少某些导入,则跳过模块中的所有测试
参数列表

  • modname:模块名
  • minversion:版本号
  • reason:跳过原因,默认不给也行
  1. pexpect = pytest.importorskip("pexpect", minversion="0.3")
  2. @pexpect
  3. def test_import():
  4. print("test")

9.7、使用自定义标记 mark

前言

  • pytest可以支持自定义标记,自定义标记可以把一个web项目划分为多个模块,然后指定模块名称执行
  • 譬如我们可以标明哪些用例在window上执行,哪些用例在mac上执行,在运行的时候指定mark就行
  1. import pytest
  2. @pytest.mark.model
  3. def test_model_a():
  4. print("执行test_model_a")
  5. @pytest.mark.regular
  6. def test_regular_a():
  7. print("test_regular_a")
  8. @pytest.mark.model
  9. def test_model_b():
  10. print("test_model_b")
  11. @pytest.mark.regular
  12. class TestClass:
  13. def test_method(self):
  14. print("test_method")
  15. def testnoMark():
  16. print("testnoMark")
'
运行

命令运行:

pytest -s -m model test_one.py

如何避免warnings

创建一个 pytest.ini 文件
加上自定义mark
pytest.ini 需要和运行的测试用例同一个目录,或在根目录下作用于全局

[pytest]
markers =
model: this is model mark

如果不想标记 model 的用例

pytest -s -m " not model" test_one.py

如果想执行多个自定义标记的用例

pytest -s -m “model or regular” 08_mark.py

十、pytest参数化 @pytest.mark.parametrize

pytest允许在多个级别启用测试化参数:
1)pytest.fixture()允许fixture有参数化功能
2)pytest.mark.parametrize 允许在测试函数和类中定义多组参数和fixtures
3)pytest_generate_tests允许定义自定义参数化方案或扩展

def parametrize(self,argnames, argvalues, indirect=False, ids=None, scope=None):
argnames:
含义:参数值列表
格式:字符串"arg1,arg2,arg3"
例如:
@pytest.mark.parametrize(“name,pwd”, [(“yy1”, “123”), (“yy2”, “123”)])
argvalues:
含义:参数值列表
格式:必须是列表,如:[ val1,val2,val3 ]
如果只有一个参数,里面则是值的列表如:@pytest.mark.parametrize(“username”, [“yy”, “yy2”, “yy3”])
如果有多个参数例,则需要用元组来存放值,一个元组对应一组参数的值,如:@pytest.mark.parametrize(“name,pwd”, [(“yy1”, “123”), (“yy2”, “123”), (“yy3”, “123”)])
ids:
含义:用例的id
格式:传一个字符串列表
作用:可以标识每一个测试用例,自定义测试数据结果的显示,为了增加可读性
indirect:
作用:如果设置成 True,则把传进来的参数当函数执行,而不是一个参数(下一篇文章即讲解

  1. @pytest.mark.parametrize("test_input,expected", [("3+5", 8), ("2+4", 6), ("6*9", 42)])
  2. def test_eval(test_input, expected):
  3. print(f"测试数据{test_input},期望结果{expected}")
  4. assert eval(test_input) == expected

10.1、函数数据参数化

方便测试函数对测试属于的获取。
方法:
parametrize(argnames, argvalues, indirect=False, ids=None, scope=None)
常用参数:
argnames:参数名
argvalues:参数对应值,类型必须为list
当参数为一个时格式:[value]
当参数个数大于一个时,格式为:[(param_value1,param_value2…),(param_value1,param_value2…)]
使用方法:
@pytest.mark.parametrize(argnames,argvalues)
️ 参数值为N个,测试方法就会运行N次

  1. import pytest
  2. class Test_ABC:
  3. def setup_class(self):
  4. print("------->setup_class")
  5. def teardown_class(self):
  6. print("------->teardown_class")
  7. @pytest.mark.parametrize("a",[3,6]) # a参数被赋予两个值,函数会运行两遍
  8. def test_a(self,a): # 参数必须和parametrize里面的参数一致
  9. print("test data:a=%d"%a)
  10. assert a%3 == 0
  11. 执行结果:
  12. test_abc.py
  13. ------->setup_class
  14. test data:a=3 # 运行第一次取值a=3
  15. .
  16. test data:a=6 # 运行第二次取值a=6
  17. .
  18. ------->teardown_class

多个参数:

  1. import pytest
  2. class Test_ABC:
  3. def setup_class(self):
  4. print("------->setup_class")
  5. def teardown_class(self):
  6. print("------->teardown_class")
  7. @pytest.mark.parametrize("a,b",[(1,2),(0,3)]) # 参数a,b均被赋予两个值,函数会运行两遍
  8. def test_a(self,a,b): # 参数必须和parametrize里面的参数一致
  9. print("test data:a=%d,b=%d"%(a,b))
  10. assert a+b == 3
  11. 执行结果:
  12. test_abc.py
  13. ------->setup_class
  14. test data:a=1,b=2 # 运行第一次取值 a=1,b=2
  15. .
  16. test data:a=0,b=3 # 运行第二次取值 a=0,b=3
  17. .
  18. ------->teardown_class

函数返回值作为参数

  1. import pytest
  2. def return_test_data():
  3. return [(1,2),(0,3)]
  4. class Test_ABC:
  5. def setup_class(self):
  6. print("------->setup_class")
  7. def teardown_class(self):
  8. print("------->teardown_class")
  9. @pytest.mark.parametrize("a,b",return_test_data()) # 使用函数返回值的形式传入参数值
  10. def test_a(self,a,b):
  11. print("test data:a=%d,b=%d"%(a,b))
  12. assert a+b == 3
  13. 执行结果:
  14. test_abc.py
  15. ------->setup_class
  16. test data:a=1,b=2 # 运行第一次取值 a=1,b=2
  17. .
  18. test data:a=0,b=3 # 运行第二次取值 a=0,b=3
  19. .
  20. ------->teardown_class

“笛卡尔积”,多个参数化装饰器

一个函数或一个类可以装饰多个 @pytest.mark.parametrize
这种方式,最终生成的用例数是 nm,比如上面的代码就是:参数a的数据有 3 个,参数b的数据有 2 个,所以最终的用例数有 32=6 条
当参数化装饰器有很多个的时候,用例数都等于 nnnn…

  1. # 笛卡尔积,组合数据
  2. data_1 = [1, 2, 3]
  3. data_2 = ['a', 'b']
  4. @pytest.mark.parametrize('a', data_1)
  5. @pytest.mark.parametrize('b', data_2)
  6. def test_parametrize_1(a, b):
  7. print(f'笛卡尔积 测试数据为 : {a}{b}')

参数化,标记数据

  1. # 标记参数化
  2. @pytest.mark.parametrize("test_input,expected", [
  3. ("3+5", 8),
  4. ("2+4", 6),
  5. pytest.param("6 * 9", 42, marks=pytest.mark.xfail),
  6. pytest.param("6*6", 42, marks=pytest.mark.skip)
  7. ])
  8. def test_mark(test_input, expected):
  9. assert eval(test_input) == expected

十一、pytest标记为失败函数和失败重试

11.1 、标记为预期失败的函数

标记测试函数为失败函数

  1. 方法:
  2. xfail(condition=None, reason=None, raises=None, run=True, strict=False)
  3. 常用参数:
  4. condition:预期失败的条件,必传参数
  5. reason:失败的原因,必传参数
  6. 使用方法:
  7. @pytest.mark.xfail(condition, reason="xx")
  1. import pytest
  2. class Test_ABC:
  3. def setup_class(self):
  4. print("------->setup_class")
  5. def teardown_class(self):
  6. print("------->teardown_class")
  7. def test_a(self):
  8. print("------->test_a")
  9. assert 1
  10. @pytest.mark.xfail(2 > 1, reason="标注为预期失败") # 标记为预期失败函数test_b
  11. def test_b(self):
  12. print("------->test_b")
  13. assert 0
  14. 执行结果:
  15. test_abc.py
  16. ------->setup_class
  17. ------->test_a
  18. .
  19. ------->test_b
  20. ------->teardown_class
  21. x # 失败标记

11.2 失败后重试

需安装第三方插件:pytest-rerun、pytest-rerunfailures

失败重试:【–reruns=1】,用例执行失败后,会立即开始重试一次此用例,再执行下一条用例
失败重运行:【–if】 ,用例集或用例执行完成之后,再次pytest.main(),会收集失败的用例,再次运行;如果没有失败的用例,会执行全部
一个run文件,可以同时写多条pytest.main(),执行pytest的命令

  1. if __name__=="__main__":
  2. pytest.main(['-s','test_firstFile.py']) # 第一次运行,如果有失败的用例/第一次没有失败的用例
  3. pytest.main(['-s','--lf','test_firstFile.py']) # 收集到第一次失败的用例,进行执行/则运行全部

注意:如果用例数较多,第一次运行全部成功的情况,第二个pytest.main(),是会收集所有的用例再执行一遍;建议使用失败重试次数(–reruns=1),失败一次后,立刻执行一次,也可减少用例的失败率

失败重试方式:
1、可在命令行 –reruns=1 reruns_delay=2 失败后重运行1次,延时2s
2、使用装饰器进行失败重运行
@pytest.mark.flaky(reruns=1, reruns_delay=2)
使用方式:
命令行参数:–reruns n(重新运行次数),–reruns-delay m(等待运行秒数)
装饰器参数:reruns=n(重新运行次数),reruns_delay=m(等待运行秒数)

重新运行所有失败的用例:

#运行失败的 fixture 或 setup_class 也将重新执行
pytest --reruns=5

添加重新运行的延时:

#要在两次重试之间增加延迟时间,使用 --reruns-delay 命令行选项,指定下次测试重新开始之前等待的秒数
pytest.main( [‘-vs’,‘–reruns=5’,‘–reruns_delay=10’,‘./testcase/test_debug.py’,‘–report=_report.html’])

重新运行指定的测试用例:

  1. #要指定某些测试用例时,需要添加 flaky 装饰器@pytest.mark.flaky(reruns=5) ,它会在测试失败时自动重新运行,且需要指定最大重新运行的次数
  2. import pytest
  3. @pytest.mark.flaky(reruns=5)
  4. def test_example():
  5. import random
  6. assert random.choice([True, False, False])
  7. #同样的,这个也可以指定重新运行的等待时间
  8. @pytest.mark.flaky(reruns=5, reruns_delay=2)
  9. def test_example():
  10. import random
  11. assert random.choice([True, False, False])
'
运行

注意:

1.如果指定了用例的重新运行次数,在命令行添加的 --reruns 对这些用例是不会生效的
2.不可以和 fixture 装饰器@pytest.fixture()一起使用
3.该插件与 pytest-xdist 的 --looponfail 标志不兼容
4.该插件与核心 --pdb 标志不兼容

十二、pytest调整执行顺序

十三、pytest设置断点

在用例脚本中加入如下python代码,pytest会自动关闭执行输出的抓取,这里,其他test脚本不会受到影响,带断点的test上一个test正常输出

 import pdb; pdb.set_trace()

十四、pytest获取用例执行性能数据

获取最慢的10个用例的执行耗时

pytest --durations=10

十五、pytest生成测试报告

3.1、下载Allure插件

官方地址:allure官方下载地址,bin目录放到path变量当中
​​​​​​​验证是否安装成功:allure -- version

3.2、生成临时的json报告(过度)

pytest.ini文件中,addopts中加上一个--alluredir=./temps
​​​​​​​--clean-alluredir        清除上次的数据

3.3、生成html报告

pytest框架自带一个测试报告,内容也相对全面,但是可读性差点,allure生成的测试报告,可改造性强,看起来也美观。使用过程在此总结一下。

 3.4、allure测试报告优化

在allure测试报告页面可以选择中英文切换,我个人比较倾向使用【功能/Behaviors】这个菜单里面的信息,因为这里可以看到更多详细的内容,也比较容易对我们的测试用例进行规范化,allure测试报告的改造也大部分都在这个环节上。

1、增加功能模块描述、测试点描述及测试步骤

方法:先import allure,然后在类上添加装饰器@allure.feature("生成账单"),在方法上添加装饰器@allure.story("批量生成账单"),在方法里面添加步骤with allure.step("1.进入[社区管理]菜单"):

使用及效果图:

(feature相当于一个功能,一个大的模块,将case分类到某个feature中,报告中在behaviore中显示,相当于testsuite)

(story相当于对应这个功能或者模块下的不同场景,分支功能,属于feature之下的结构,报告在features中显示,相当于testcase)

 2、执行断言,失败截图、成功截图

一条case可以在中间步骤进行断言,可以在最后进行断言,看测试需要。我们想要的一个结果是断言失败的截图并放到allure测试报告中。

  1.         with allure.step("5.执行断言"):
  2.             #如果断言失败就截图并保存
  3.             try:
  4.                 assert "添加成功" in self.driver.page_source
  5.             except:
  6.                 self.driver.save_screenshot("./screenshot/houseInfoFail.png")
  7.                 allure.attach.file("./screenshot/houseInfoFail.png", attachment_type=allure.attachment_type.PNG)
  8.                 #如果断言失败就截图,这里加一个断言失败,方便报告里记录失败用例,
  9.                 # 不加的话无论失败与否pytest框架都会判断你的用例执行成功了
  10.                 assert "添加成功" in self.driver.page_source


现在项目下面建一个screenshot文件夹,用来放截取的图片,然后allure再获取该图片。houseInfoFail.png这个是自己定义的图片的文件名。

如果断言成功了,也截取一张图片,并放到allure报告中。完整代码如下:

  1.         with allure.step("5.执行断言"):
  2.             
  3.             #如果断言失败就截图并保存
  4.             try:
  5.                 assert "添加成功" in self.driver.page_source
  6.             except:
  7.                 
  8.                 self.driver.save_screenshot("./screenshot/houseInfoFail.png")
  9.                 allure.attach.file("./screenshot/houseInfoFail.png", attachment_type=allure.attachment_type.PNG)
  10.                 #如果断言失败就截图,这里加一个断言失败,方便报告里记录失败用例,
  11.                 # 不加的话无论失败与否pytest框架都会判断你的用例执行成功了
  12.                 assert "添加成功" in self.driver.page_source
  13.         #截图
  14.         with allure.step("6.保存图片"):
  15.             
  16.             self.driver.save_screenshot("./screenshot/houseInfo.png")
  17.             allure.attach.file("./screenshot/houseInfo.png", attachment_type=allure.attachment_type.PNG)

 houseInfo.png这个是执行成功截取的图片,注意和上面执行失败截取的图片文件名区分一下。

效果:

 还有很多功能,想要的效果达到了就可以了。

十六、pytest中管理日志

16.1、日志级别

  1. import logging  # 引入logging模块
  2. # 将信息打印到控制台上
  3. logging.debug(u"勇士")
  4. logging.info(u"湖人")
  5. logging.warning(u"太阳")
  6. logging.error(u"雄鹿")
  7. logging.critical(u"热火")


默认生成的root logger的level是logging.WARNING,低于该级别的就不输出了

级别排序:CRITICAL > ERROR > WARNING > INFO > DEBUG

debug : 打印全部的日志,详细的信息,通常只出现在诊断问题上
info : 打印info,warning,error,critical级别的日志,确认一切按预期运行
warning : 打印warning,error,critical级别的日志,一个迹象表明,一些意想不到的事情发生了,或表明一些问题在不久的将来(例如。磁盘空间低”),这个软件还能按预期工作
error : 打印error,critical级别的日志,更严重的问题,软件没能执行一些功能
critical : 打印critical级别,一个严重的错误,这表明程序本身可能无法继续运行

这时候,如果需要显示低于WARNING级别的内容,可以引入NOTSET级别来显示:

  1. import logging  # 引入logging模块
  2. logging.basicConfig(level=logging.NOTSET)  # 设置日志级别
  3. logging.debug(u"如果设置了日志级别为NOTSET,那么这里可以采取debug、info的级别的内容也可以显示在控制台上了")


16.2、分析解释

Logging.Formatter:这个类配置了日志的格式,在里面自定义设置日期和时间,输出日志的时候将会按照设置的格式显示内容。

Logging.Logger:Logger是Logging模块的主体。
进行以下三项工作:
为程序提供记录日志的接口;
判断日志所处级别,并判断是否要过滤;
根据其日志级别将该条日志分发给不同handler;

常用函数有:
Logger.setLevel() 设置日志级别;
Logger.addHandler() 和 Logger.removeHandler() 添加和删除一个Handler;
Logger.addFilter() 添加一个Filter,过滤作用;
Logging.Handler:Handler基于日志级别对日志进行分发,如设置为WARNING
级别的Handler只会处理WARNING及以上级别的日志。

常用函数有:
setLevel() 设置级别;
setFormatter() 设置Formatter;

16.3、日志输出-控制台

  1. import logging  # 引入logging模块
  2. logging.basicConfig(level=logging.DEBUG,
  3.                     format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')  # logging.basicConfig函数对日志的输出格式及方式做相关配置
  4. # 由于日志基本配置中级别设置为DEBUG,所以一下打印信息将会全部显示在控制台上
  5. logging.info('this is a loggging info message')
  6. logging.debug('this is a loggging debug message')
  7. logging.warning('this is loggging a warning message')
  8. logging.error('this is an loggging error message')
  9. logging.critical('this is a loggging critical message')


上面代码通过logging.basicConfig函数进行配置了日志级别和日志内容输出格式;
因为级别为DEBUG,所以会将DEBUG级别以上的信息都输出显示再控制台上。

16.4、日志输出-文件

  1. import logging  # 引入logging模块
  2. import os.path
  3. import time
  4. # 第一步,创建一个logger
  5. logger = logging.getLogger()
  6. logger.setLevel(logging.INFO)  # Log等级总开关
  7. # 第二步,创建一个handler,用于写入日志文件
  8. rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
  9. log_path = os.path.dirname(os.getcwd()) + '/Logs/'
  10. log_name = log_path + rq + '.log'
  11. logfile = log_name
  12. fh = logging.FileHandler(logfile, mode='w')
  13. fh.setLevel(logging.DEBUG)  # 输出到file的log等级的开关
  14. # 第三步,定义handler的输出格式
  15. formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
  16. fh.setFormatter(formatter)
  17. # 第四步,将logger添加到handler里面
  18. logger.addHandler(fh)
  19. # 日志
  20. logger.debug('this is a logger debug message')
  21. logger.info('this is a logger info message')
  22. logger.warning('this is a logger warning message')
  23. logger.error('this is a logger error message')
  24. logger.critical('this is a logger critical message')

16.5、日志输出-控制台和文件

只要在输入到日志中的第二步和第三步插入一个handler输出到控制台:
创建一个handler,用于输出到控制台

  1. ch = logging.StreamHandler()
  2. ch.setLevel(logging.WARNING)  # 输出到console的log等级的开关


第四步和第五步分别加入以下代码即可

  1. ch.setFormatter(formatter)
  2. logger.addHandler(ch)



16.6、format常用格式说明

%(levelno)s: 打印日志级别的数值
%(levelname)s: 打印日志级别名称
%(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
%(filename)s: 打印当前执行程序名
%(funcName)s: 打印日志的当前函数
%(lineno)d: 打印日志的当前行号
%(asctime)s: 打印日志的时间
%(thread)d: 打印线程ID
%(threadName)s: 打印线程名称
%(process)d: 打印进程ID
%(message)s: 打印日志信息

16.7、捕捉异常traceback记录

  1. import os.path
  2. import time
  3. import logging
  4. # 创建一个logger
  5. logger = logging.getLogger()
  6. logger.setLevel(logging.INFO)  # Log等级总开关
  7. # 创建一个handler,用于写入日志文件
  8. rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
  9. log_path = os.path.dirname(os.getcwd()) + '/Logs/'
  10. log_name = log_path + rq + '.log'
  11. logfile = log_name
  12. fh = logging.FileHandler(logfile, mode='w')
  13. fh.setLevel(logging.DEBUG)  # 输出到file的log等级的开关
  14. # 定义handler的输出格式
  15. formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
  16. fh.setFormatter(formatter)
  17. logger.addHandler(fh)
  18. # 使用logger.XX来记录错误,这里的"error"可以根据所需要的级别进行修改
  19. try:
  20.     open('/path/to/does/not/exist', 'rb')
  21. except (SystemExit, KeyboardInterrupt):
  22.     raise
  23. except Exception, e:
  24.     logger.error('Failed to open file', exc_info=True)


如果需要将日志不上报错误,仅记录,可以写成exc_info=False

16.8、多模块调用logging,日志输出顺序

warning_output.py

  1. import logging
  2. def write_warning():
  3.     logging.warning(u"记录文件warning_output.py的日志")


error_output.py

  1. import logging
  2. def write_error():
  3.     logging.error(u"记录文件error_output.py的日志")


main.py

  1. import logging
  2. import warning_output
  3. import error_output
  4. def write_critical():
  5.     logging.critical(u"记录文件main.py的日志")
  6. warning_output.write_warning()  # 调用warning_output文件中write_warning方法
  7. write_critical()
  8. error_output.write_error()  # 调用error_output文件中write_error方法


16.9、日志滚动和过期删除(按时间)

  1. # coding:utf-8
  2. import logging
  3. import time
  4. import re
  5. from logging.handlers import TimedRotatingFileHandler
  6. from logging.handlers import RotatingFileHandler
  7. def backroll():
  8.     #日志打印格式
  9.     log_fmt = '%(asctime)s\tFile \"%(filename)s\",line %(lineno)s\t%(levelname)s: %(message)s'
  10.     formatter = logging.Formatter(log_fmt)
  11.     #创建TimedRotatingFileHandler对象
  12.     log_file_handler = TimedRotatingFileHandler(filename="ds_update", when="M", interval=2, backupCount=2)
  13.     #log_file_handler.suffix = "%Y-%m-%d_%H-%M.log"
  14.     #log_file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}.log$")
  15.     log_file_handler.setFormatter(formatter)
  16.     logging.basicConfig(level=logging.INFO)
  17.     log = logging.getLogger()
  18.     log.addHandler(log_file_handler)
  19.     #循环打印日志
  20.     log_content = "test log"
  21.     count = 0
  22.     while count < 30:
  23.         log.error(log_content)
  24.         time.sleep(20)
  25.         count = count + 1
  26.     log.removeHandler(log_file_handler)
  27. if __name__ == "__main__":
  28.     backroll()

说明:
filename:日志文件名的prefix;
when:是一个字符串,用于描述滚动周期的基本单位,字符串的值及意义如下:
“S”:Seconds
“M”:Minutes
“H”:Hours
“D”:Days
“W”:Week day (0=Monday)
“midnight”:Roll over at midnight
interva:滚动周期,单位有when指定,比如:when=’D’,interval=1,表示每天产生一个日志文件
backupCount:表示日志文件的保留个数

十七、总结

如果你看到了总结,那么恭喜你看到了总结,总结是全文的精华,而精华是全文的内容,总而言之,言而总之,你浪费了5秒钟~

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/882952
推荐阅读
相关标签
  

闽ICP备14008679号