unittest: 模板化
pytest: 灵活 - 测试框架
安装pytest:
pip install pytest
1、编写用例:
1、unittest: 继承unittest.TestCase类。
2、pytest: 函数的形式、类的形式。用例名要以test_开头。测试类要以Test开头。
用例涵盖:前置后置(fixture)、步骤、断言。
2、断言:
1、unittest: self.assertXXXX()
2、pytest: assert 表达式(True表示断言为真,False表示断言失败)
3、生成测试结果文件:
1、unittest: text,html(HtmlTestRunner,beautifulReport)
2、pytest:
1. 生成JunitXML 格式的测试报告:命令:--junitxml=path
2. 生成result log格式的测试报告:命令:--resultlog=report\log.txt价值不大
3. 生成Html格式的测试报告:命令:--html=report\test_one_func.html(相对于rootdir路径 )
第一步:安装pytest html插件
pip install pytest-html
第二步:在pytest的命令行参数中:--html=....
4. 生成allure的测试文件(unittest不支持)。命令:--alluredir=xx/xxx (相对于rootdir路径)
1、allure是什么? 依据测试结果文件,呈现更好看的更多维度的测试报告。
注意:它不执行用例也不生成测试结果文件。所以,要使用allure的时候,一定要先生成测试结果文件。
要结合其它的测试框架一起使用的。
allure的官方地址:http://allure.qatools.ru/
如何使用allure?
1、要安装allure命令行工具。
下载地址:https://repo.maven.apache.org/maven2/io/qameta/allure/allure-commandline/
下载完成之后,解压到任意目录
配置环境变量:allure的bin目录。比如D:\allure-2.12.1\bin
在cmd当中,执行allure命令
2、pytest在执行用例之后,要生成allure可以识别的测试结果文件。
安装插件:pip install allure-pytest
在pytest.main()的参数当中添加:--alluredir=xx/xxx (相对于rootdir路径)
3、使用allure去解析2中的测试结果文件,再呈现最终的测试报告
在cmd当中首先跳转到rootdir下面
在cmd当中执行命令:allure serve 2中的测试结果文件路径
4、收集和执行用例:
1、unittest: 用例收集(TestSuite/TestLoader)到TestSuite, TestRunner去执行用例。
2、pytest: 自动收集用例,再去执行。
pytest自动收集用例的规则:
1)确定搜索目录:从哪个目录开始搜索用例?
-- pytest命令在哪个目录下执行,就以哪个目录为rootdir
-- 新建main.py,在文件当中使用pytest.main() - 与在命令行当中执行pytest是一样的。
2)过滤测试文件:目录下有很多文件,如何过滤有测试用例的文件?
-- 测试文件名:test_*.py 或者 *_test.py
3)过滤测试用例:文件当中,如何过滤测试用例?
-- 测试用例名:test_开头 测试类名:Test开头。
pytest收集到的用例执行顺序??
先找到测试文件,再找测试文件当中的用例。
测试文件顺序:ASCII码
测试文件内部顺序:代码先后顺序
5、插件(第三方库):
1、unittest没有。
2、pytest有非常多的插件。
html报告插件:
7、数据驱动:
unittest: ddt模块
pytest:
@pytest.mark.parametrize("参数名",列表数据)
@pytest.mark.parametrize("case",datas)
def test_read_datas(case):
pass