1 背景
- 每种语言都有一种自动的测试框架。例如java的junitest,Python的unitest/pytest
- 对于python而言,unitest是一种自带的无需用户安装的一种框架,这种框架应该广为人知,满足大部分的需求,可以用来做接口,ui
- pytest是一种基于unitest的一种更高级的测试框架,引用官网介绍来说
The pytest framework makes it easy to write small, readable tests, and can scale to support complex functional testing for applications and libraries
2 为什么使用pytest
既然已经有了unitest为什么要使用pytest呢?官网:helps you write better programs;根据官网的介绍,它具有如下特点:
- Pytest 可以并行运行多个测试,从而减少了测试套件的执行时间
- 如果没有明确提及,Pytest 有自己的方式来自动检测测试文件和测试函数
- Pytest 允许我们在执行期间跳过测试的子集
- Pytest 允许我们运行整个测试套件的一个子集
- 由于语法简单,pytest 很容易上手
总结起来就是,pytest能够支持简单的单元测试和复杂的功能测试;并且支持参数化,可以生成漂亮的测试报告,拥有较多的第三方插件
3 pytest的使用
3.1 安装pytest
pytest是python的三方包,需要使用pip进行安装
pip install -U pytest
pip3 install pytest -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
这里临时使用豆瓣的镜像源,如果想修改pip的镜像源参考修改pip镜像源进行修改
3.2 查看版本
pytest --version
3.3 简单例子
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@Project : demo
@File : test_demo.py
@Author : coder
@Time : 8/10/2022 2:31 PM
"""
# content of test_sample.py
def inc(x):
return x + 1
def test_answer():
assert inc(3) == 5
if __name__ == "__main__":
run_code = 0
打开pycharm的终端,cd到当前目录执行pytest
注意
- 如果只执行 pytest ,会查找当前目录及其子目录下以 test_*.py 或 *_test.py 文件,找到文件后,在文件中找到以 test 开头函数并执行
- 如果只想执行某个文件,可以 pytest xxxx.py
- 加上-q,就是显示简单的结果: pytest -q xxxx.py
3.4 用例的设计规范
用Pytest写用例时候,一定要按照下面的规则去写,否则不符合规则的测试用例是不会执行的
- 文件名以 test_.py 文件和_test.py
- 以 test_ 开头的函数
- 以 Test 开头的类,不能包含 init 方法
- 以 test_ 开头的类里面的方法
- 所有的包 package 必须要有__init__.py 文件
4 pytest执行方法
4.1 执行路径下的所有用例
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@Project : demo
@File : demo_test.py
@Author : coder
@Time : 8/10/2022 2:31 PM
"""
# content of test_sample.py
def inc(x):
return x + 1
def test_answer():
assert inc(3) == 5
if __name__ == "__main__":
run_code = 0
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@Project : demo
@File : test_success.py
@Author : coder
@Time : 8/10/2022 2:31 PM
"""
# content of test_sample.py
def inc(x):
return x + 1
def test_success():
assert inc(3) == 4
if __name__ == "__main__":
run_code = 0
pytest
4.2 执行某一个 py 文件下用例
pytest .\test_success.py
4.3运行模块里面的某个函数,或者某个类,某个类里面的方法标题
pytest -v XXX.py::TestClass::test_method
pytest XXX.py::TestClass::test_method
pytest XXX.py::test_answer
4.4根据标记执行
pytest -m login(标记)
4.5简单打印,只打印测试用例的执行结果
pytest -q .\test_success.py
4.6 -s 详细打印
默认就是详细打印 -s加与不加都是详细打印
4.7 -x 遇到错误时停止测试
4.8 —maxfail=num,当用例错误个数达到指定数量时,停止测试
4.9 -k 匹配用例名称
test_demo中用例名称包含hello的所有用例
pytest -k hello test_demo.py
4.10 -k 根据用例名称排除某些用例
pytest -k ‘not hello ’ test_demo.py
4.11 -k 同时匹配不同的用例名称
pytest -k ‘hello or kitty ’ test_demo.py