正式学习pytest之前先回顾下断言:assert
assert的作用是什么呢?先看一段伪代码:
if 条件: { 程序正常运行 } else: { 报错并终止,避免以后引发更大的错误或不可预期错误 }
为了让代码更优雅,就有了断言:assert
>>> age=-1 >>> assert age>1 Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError
这就是断言最基本的用法。更多:https://www.cnblogs.com/thisway/p/5558914.html
pytest是python的一种单元测试框架,使用简洁,效率高。根据pytest的官方网站介绍,它具有如下特点:
pip install pytest # (安装) pytest --version # (查看版本)
在pytest框架中,有如下约束:
新建一个test_simple.py的文件,写下如下代码:
def func(x): return x +1 def test_answer(): assert func(3)==5
打开CMD窗口进入test_simple.py文件所在文件夹,输入:pytest test_simple.py (或者直接输入:pytest)
新建test_class.py文件,输入如下代码:
class TestClass: def test_one(self): x = ‘this‘ assert ‘h‘ in x def test_two(self): x = ‘hello‘ assert hasattr(x, ‘check‘)
打开CMD窗口进入test_class.py文件所在文件夹,输入:pytest test_class.py
第一次测试通过,第二次测试失败
1.执行某个目录下所有的用例
pytest 文件名/
2.执行某一个py文件下用例
pytest 脚本名称.py
3.运行.py模块里面的某个函数
pytest test_mod.py::test_func
4.运行.py模块里面,测试类里面的某个方法
pytest test_mod.py::TestClass::test_method
5.-x 遇到错误时停止测试
pytest -x test_class.py
6.当用例错误个数达到指定2个时,停止测试
pytest --maxfail=2
更多:https://www.cnblogs.com/yoyoketang/p/9374957.html
原文:https://www.cnblogs.com/lymlike/p/11729472.html