引言
代码测试一直以来是一个非常耗费时间的事情,且需要涵盖每一个样例,本文我们将介绍如何使用 pytest 库进行代码的自动化测试。
正文
首先在 bash 下输入如下代码安装 pytest 库。
pip install pytest
然后针对特定函数或类书写 assert 断言来对函数和类进行测试。
示例 1
import pytest
def inc(x):
return x + 1
def test_answer():
assert inc(2) == 3
assert inc(3) == 4
assert inc(3) == 5
def test_answer1():
assert inc(2) == 3
assert inc(3) == 4
if __name__ == '__main__':
pytest.main([__file__])
我们的被测试函数是 inc(),这里我们书写了两个用于自动化 pytest 库进行测试的样例,test_answer() 与 test_answer1()。注意,这里的 pytest.main([file]) 等效于在终端 cmd 中输入 pytest 命令,pytest 会自动查找符合测试书写规范的测试样例进行执行。即,这里运行后,Python 会自动执行 test_answer() 与 test_answer1() 两个测试样例。有些时候,我们可能会遇到 pytest.main([file], “-v”) 的写法,这里的 -v 指的是 verbose,即将测试结构详细输出出来。
运行后的结果如下图所示:

结果显示,运行了两个测试样例,test_answer1() 完全通过测试,test_answer() 只通过了一半。且未通过的测试样例被标记了出来。

此时,如果我们点击图上的 click to see difference,我们会得到以下图像。Pycharm 会打开一个 comparison failure 窗口,同时将实际值与期望值给出。

转载自 CSDN-专业IT技术社区
原文链接:https://blog.csdn.net/u011699626/article/details/170348747



