【pytest单元测试框架】(1)pytest 简单例子
pytest 简单例子
pytest 官方网站:https://docs.pytest.org/en/latest/ pytest 支持 pip 安装pip install pytest通过 pytest 编写一个简单的测试用例,创建 test_sample.py 文件
# -*- coding:utf-8 -*- # filename: /pyTest/test_sample # author: hello.yin # date: 2021/11/18 import pytest def inc(x): return x + 1 def test_answer(): assert inc(3) == 5 if __name__ == "__main__": pytest.main()
执行结果:
C:\Users\yzp\AppData\Local\Programs\Python\Python37\python.exe D:/00test/base_practice/pyTest/test_sample.py ============================= test session starts ============================= platform win32 -- Python 3.7.4, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 rootdir: D:\00test\base_practice\pyTest collected 1 item test_sample.py F [100%] ================================== FAILURES =================================== _________________________________ test_answer _________________________________ def test_answer(): > assert inc(3) == 5 E assert 4 == 5 E + where 4 = inc(3) test_sample.py:13: AssertionError =========================== short test summary info =========================== FAILED test_sample.py::test_answer - assert 4 == 5 ============================== 1 failed in 0.04s ============================== Process finished with exit code 0
“pytest”命令在安装 pytest 测试框架时默认生成于...\Python37\Scripts\目录。通过上面的例子,相信你已经感受到了 pytest 的优点,它更加简单。首先,不必像 unittest一样必须创建测试类。其次,使用 assert 断言也比使用 unittest 提供的断言方法更加简单。不过,它也有自己的规则,即测试文件和测试函数必须以“test”开头。这也是在执行“pytest”命令时并没有指定测试文件也可以执行 test_sample.py 文件的原因,因为该文件名以“test”开头。
能否像 unittest 一样,通过 main()方法执行测试用例呢?当然可以,pytest 同样提供了main()方法。 main()方法默认执行当前文件中所有以“test”开头的函数。现在可以直接在 IDE 中运行测试了。