pytest单元测试框架实战(一)

一、pytest简介

1.基于python的单元测试框架,它可以和selenium,requests,appium结合实现自动化
测试。
2.实现用例跳过skip和reruns失败用例重跑。
3.它可以结合allure-pytest插件生成allure报告。
4.很方便和jenkins实现持续集成。
5.有很多强大的插件:
    pytest-html 生成html测试报告。
    pytest-xdist 多线程执行测试用例。
    pytest-ordering 改变测试用例的执行顺序。
    pytest-rerunfailures 失败用例重跑
    allure-pytest 生成allure报告。

二、pytest的最基本的测试用例的规则

1.模块名必须以test_开头或者_test结尾。
2.测试类必须以Test开头,并且不能带有init方法。
3.测试用例必须以test_开头。
命令规范:
模块名:一般全小写:多个英文之间用_隔开。
类名:类名一般是首字母大写
方法名:一般全小写:多个英文之间用_隔开。

三、运行方式

1.主函数模式

pytest单元测试框架实战(一)_第1张图片

常见参数:
-v:输出更加详细的信息。比如文件和用例名称等。
-s:输出调试信息。打印信息等。
可以合并成:-vs
–reruns=数字:失败重跑
-x 出现1个失败就停止测试。
–maxfail=2 出现N个失败就终止测试。
–html=report.html 生成html的测试报告
-n=2:多线程。
-k:运行测试用例名称中包含指定字符串的用例。
pytest.main([’-vs’,’-k’,‘weiwei or baili’])
pytest.main([’-vs’,’-k’,‘weiwei and baili’])
在这里插入图片描述
忽略这个告警:PytestAssertRewriteWarning: Module already imported so cannot be rewritten: pytest_rerunfailures
self._mark_plugins_for_rewrite(hook)

2.指定模块运行。
pytest单元测试框架实战(一)_第2张图片
3.指定文件夹

if __name__ == '__main__':
	pytest.main(['‐vs','pytest_demo/'])

4.通过node id的方式运行测试用例

if __name__ == '__main__':
	 pytest.main(['-vs','pytest_demo/test_project1.py::Test_demo::test_NO1'])

2.命令行模式

pytest -vs pytest_demo/test_project1.py

3.通过pytest.ini的配置文件运行

不管是命令行还是主函数都会读取这个配置文件

[pytest] 用于标记这个文件是pytest的配置文件
addopts = -vs 命令行参数,多个参数之间用空格分隔。 addoptions
testpaths = testcases/ 配置搜索测试用例的范围
python_files = test_*.py 改变默认的文件搜索规则
python_classes = Test* 改变默认的类搜索规则
python_functions = test_* 改变默认的测试用例的搜索规则。
#用例分组
markers =
smoke:冒烟用例
productmanage:商品管理模块

特别提示:
此文件中最好不要出现中文, 如果有中文的情况下,比如使用notpad++改成GBK的编
码。
pytest单元测试框架实战(一)_第3张图片
执行的时候通过-m参数指定标记

 addopts = ‐vs ‐m smoke

四、跳过测试用例

1.无条件跳过

@pytest.mark.skip(reason="不需要")
    def test_NO1(self):
        print("这是第一个例子")

2.有条件跳过

pid=2
@pytest.mark.skipif(pid>1,reason="大于1的版本不执行")
def test_NO1(self):
    print("这是第一个例子")

五、用例的前后置,固件,夹具,钩子函数

def setup_module():
	print("在每个模块之前执行")5
def teardown_module():
 	print("在每个模块之后执行")
def setup_class(self):
	print("在每个类之前执行,创建日志对象(创建多个日志对象,那么日志会出现重复,创建数据库连接")

def teardown_class(self):
	print("在每个类之后执行,销毁日志对象,关闭数据库连接")
def setup(self):
	print("在每个用例之前执行,web自动化:打开浏览器,加载网页,接口自动化:日志开始")

def teardown(self):
	print("在每个用例之后执行,日志结束,关闭浏览器")

你可能感兴趣的:(pytest,单元测试,python)