目录
前言
目前Python流行的测试框架:pytest和unittest
什么是unittest?
1、python自带的单元测试框架;
2、常用在单元测试、自动化测试中;
3、提供用例组织与执行;
4、提供丰富的断言方法-验证函数等功能是否正确;
5、加上HTMLTestRunner可以生成html报告;
什么是pytest?
pytest是一个非常成熟的全功能的Python测试框架;
1、简单灵活,容易上手;支持参数化;测试用例的跳过(skip)和对用例标记为失败(xfail)处理
2、能够支持简单的单元测试和复杂的功能测试,还可以用来做selenium/appnium等自动化测试、接口自动化测试(pytest+Requests);
3、pytest具有很多第三方插件,并且可以自定义扩展;
4、可生成html报告,可以和pytest-allure结合生成漂亮的测试报告;
5、可以很好的和jenkins集成;
6、pytest兼容unittest脚本,可以以pytest运行unittest脚本
7、目前最优秀的测试框架;
pytest
安装
pip install -U pytest
-U:如果你已经安装pytest,则会升级到最新版本
查看版本
pytest --version
第一个测试
# test_sample.py 的内容
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
进入命令行模式,进入当前目录,直接执行
pytest
将多个测试用例放在一个calss中
# test_class.py的内容
class TestClass(object):
def test_one(self):
x = 'this'
assert 'h' in x
def test_two(self):
x = 'hello'
assert 'w' in x
运行
pytest test_class.py
结果
可以很容易看出来hello不包含w
知识点
1、如果只执行 pytest ,pytest会运行当前目录及子目录下所有以 test_*.py
和 *_test.py
命名的文件,找到文件后,在文件中找到以test开头的函数并执行
2、如果只想执行某个文件,可以: pytest test_class.py
pytest用例的设计原则
用Pytest写用例时候,一定要按照下面的规则去写,否则不符合规则的测试用例是不会执行的
1、文件名以test_*.py
文件和*_test.py
2、以test_
开头的函数
3、以Test
开头的类,不能包含__init__
方法
4、以test_
开头的类里面的方法
5、所有的包pakege
必须要有__init__.py
文件
命令行模式执行pytest命令规则
1、执行某个目录下的所有用例
pytest
2、执行某一个py文件下用例
pytest 脚本名称.py
3、执行.py模块里面的某个函数,或者某个类,或者某个类里面的某个方法
代码
# test_class.py的内容
def test_first():
x = 'word'
assert 'p' in x
class TestClass(object):
def test_one(self):
x = 'this'
assert 'w' in x
def test_two(self):
x = 'hello'
assert 'w' in x
执行test_class.py模块里面的test_first函数
pytest test_class.py::test_first
结果
执行test_class.py模块里面的TestClass类
pytest test_class.py::TestClass
结果
执行test_class.py模块的TestClass类里面的test_two方法
pytest test_class.py::TestClass::test_two
结果
4、-m标记表达式
pytest -m slow
这种方式会运行所有通过装饰器 @pytest.mark.slow进行装饰的测试用例。
5、-q 简单打印,只打印测试用例的执行结果
pytest -q test_class.py::test_first
6、-s 详细打印
pytest -s test_class.py::test_first
7、-x 遇到错误时停止测试
pytest -x test_class.py::TestClass
8、- -maxfail=n,当用例n次故障后停止
第1次故障后停止
pytest --maxfail=1 test_class.py::TestClass
9、-k 运行包含与给定名称匹配的名称的测试
运行测试用例名称包含test的所有用例
pytest -k test test_class.py::TestClass
运行测试用例名称不包含test_two的所有用例
pytest -k “not test_two” test_class.py::TestClass
运行测试用例名称包含test或者test_first的所有用例
pytest -k “test_two or test_first” test_class.py
Pycharm设置以pytest方式运行代码
File—>settings---->Tools---->Python Integrated Tools