pytest特点
pytest 是一个非常成熟的全功能的Python测试框架
可以胜任unittest能做到的各种场景,比如:单元测试、接口测试、web测试等等
pytest更是一个插件化平台,这也是它比unittest更强大的地方。多年来,已经有大量的第三方插件扩展和增强它的功能
你也可以根据自身的需求,定制化开发自己的插件
总而言之,pytest使用更加简单、灵活。
安装
切换到scripts 目录下,运行命令:pip install pytest,查看版本:pytest --version
pycharm中运行 pytest
设置 setting-tools-Python Intergrated Tools --Default test runner 选择 pytest
第一个demo test_demo.py
# _*_ coding:utf-8 _*_
import pytest
def add(x):
return x + 2 ;
class TestClass(object):
#测试是否相等
def test_add(self):
assert add(3) ==5
def test_in(self):
a ='hello word'
b = 'he'
assert b in a
def test_not_in(self):
a = 'hello'
b = 'hi'
assert b not in a
if __name__ == '__main__':
pytest.main(['-s','test_demo.py'])
运行结果:
Pytest用例的设计原则
文件名以 test_.py 文件和test.py
以 test 开头的函数
以 Test 开头的类,不能包含 init 方法
以 test_ 开头的类里面的方法
所有的包 pakege 必项要有init.py 文件
Pytest执行用例规则
下面以windows系统为例,使用命令来来执行pytest
1、指定目录下的所有用例
pytest
2、执行某一个py文件下用例
pytest 文件名.py
3、运行test_demo.py文件中模块里面的某个函数,或者某个类,某个类里面的方法
说明:加v和不加-v都可以,加-v的话,打印的信息更详细
pytest -v test_demo.py::TestClass::test_add
pytest test_demo.py::TestClass::test_not_in
pytest test_demo.py::test_in
4、运行test_demo.py 模块里面,测试类里面的某个方法
pytest test_demo.py::test_in
5、-m 标记表达式(后面有详解)
pytest -m login
将运行用 @pytest.mark.login 装饰器修饰的所有测试,后面有详解!
6、-q 简单打印,只打印测试用例的执行结果
pytest -q test_demo.py
7、-s 详细打印
pytest -s test_demo.py
8、-x 遇到错误时停止测试
pytest test_demo.py -x
9、—maxfail=num,当用例错误个数达到指定数量时,停止测试
pytest test_demo.py --maxfail=1
10、-k 匹配用例名称
pytest -s -k _in test_demo.py
11、-k 根据用例名称排除某些用例
pytest -s -k "not _in" test_demo.py
12、-k 同时匹配不同的用例名称
pytest -s -k "add or _in" test_demo.py