文章目录
- 一、pytest简介和安装
- 二、定义测试类、测试方法
- 三、执行测试方法(重点)
- 四、Fixture风格
- 五、断言
- 5.1 断言-案例
- 六、测试报告
一、pytest简介和安装
1、pytest 是开发人员用来实现 “单元测试” 的框架。测试工程师,可以在自动化 “测试执行” 时使用。
2、使用 pytest 的好处:
- 方便管理、维护测试用例。
- 简单的断言方法。
- 生成测试报告。
3、安装 pytest
pip install pytest pip install requests-i https://pypi.douban.com/simple/# 指定镜像源安装二、定义测试类、测试方法
- 定义测试类管理测试用例
- 测试类中的测试方法和excel写的测试用例一一对应。(excel表格写一条测试用例,在测试类中添加一条测试方法)
如:登录接口,共 15 条测试用例。但,需要15个测试方法。
# 测试类名,建议以Test开头。(类名首字母大写)classTestXxx(object):# 测试方法名,必须以小写test开头。deftest_xxx(self):pass三、执行测试方法(重点)
单文件执行(了解) 方法1:终端命令 pytest -s xxx.py。 方法2:①方法定义后,右键->运行 此方法。在方法后面去运行,只运行这一个方法。 ②类定义后,右键->运行 所有方法。在类后面去运行,则运行类里面的所有方法。 注:方法2需要pycharm2020以上版本,才可以。 方法3:导包 import pytest if __name__ == '__main__': pytest.main(['-s', 'xxx.py']) 多文件执行【重点】 1. 直接在项目目录下,创建文件 pytest.ini 2. 编写 pytest.ini 文件 [pytest] 固定内容 addopts = -s 添加命令行参数 add options testpaths = ./xxx .py 测试用例文件,相对于 pytest.ini 位置 python_files = xxx*.py .py 文件名。 可用 通配符 python_classes = Test* 测试类名。 可用 通配符 python_functions = test* 测试方法名。 可用 通配符 3. 终端执行命令 pytest四、Fixture风格
# 1.方法级别方法defsetup(self):在 每个 普通测试方法执行之前,自动被调用一次。defteardown(self):在 每个 普通测试方法执行之后,自动被调用一次。# 2.类级别方法defsetup_class(self):在 类中 所有测试方法 执行之前,自动被调用一次。defteardown_class(self):在 类中 所有测试方法 执行结束之后,自动被调用一次。五、断言
断言错误,会在控制台显示断言错误(AssertionError)。
# 方法1:assert预期结果==实际结果 ———— 断言相等# 方法2:assert预期结果in实际结果 ———— 断言包含5.1 断言-案例
# 定义测试类classTestAdd(object):# 定义测试方法deftest01_add(self):print("第 1 个 测试方法!!!")assert10==2+8deftest02_add(self):print("第 2 个 测试方法!!!")assert"hello"in"helloword"# hello是包含在hellohelloword里面结果:
# 前面已经配置了 pytest.ini 文件,才能直接在终端中使用pytest。PS C:\XM1\requestsTestSh27>pytest=================================================================================testsession starts=================================================================================platform win32 -- Python3.7.4, pytest-7.4.4, pluggy-0.13.0 rootdir: C:\XM1\requestsTestSh27 configfile: pytest.ini testpaths: ./ plugins: arraydiff-0.3, doctestplus-0.4.0, html-3.2.0, metadata-3.0.0, openfiles-0.4.0, remotedata-0.3.2 collected2items pytest01_review.py 第1个 测试方法!!! .第2个 测试方法!!!.---------------------------------------- generated html file: file:///C:/XM1/requestsTestSh27/report/%E6%88%91%E7%9A%84%E6%8A%A5%E5%91%8A.html ----------------------------------------==================================================================================2passedin0.05s==================================================================================PS C:\XM1\requestsTestSh27>六、测试报告
必须在项目所在的目录下,执行pytest命令,生成测试报告。
# 1. 安装插件pip install pytest-html# 2. 修改 pytest.ini 文件的 addopts 的值。""" report:表示目录,当前项目下得有这个report目录。 - ①测试报告名.html:自己起测试报告名。 - ②--self-contained-html:这个参数如果不加,每次生成测试报告会有一个中间文件,这个中间文件没用。 这个参数就是不加这个缓存文件。 """addopts=-s--html=report/测试报告名.html--self-contained-html# 3. 使用命令 pytest 生成测试报告