pytest自动化测试简单示例

安装pytest:

pip install -U pytest

root#pytest --version
This is pytest version 4.6.11, imported from /usr/local/lib/python2.7/dist-packages/pytest.pyc
setuptools registered plugins:
  pytest-forked-1.3.0 at /usr/local/lib/python2.7/dist-packages/pytest_forked/__init__.pyc
  pytest-metadata-1.11.0 at /usr/local/lib/python2.7/dist-packages/pytest_metadata/plugin.py
  pytest-html-1.22.1 at /usr/local/lib/python2.7/dist-packages/pytest_html/plugin.py
  pytest-cov-2.12.1 at /usr/local/lib/python2.7/dist-packages/pytest_cov/plugin.py
  pytest-mock-2.0.0 at /usr/local/lib/python2.7/dist-packages/pytest_mock/__init__.pyc
  pytest-xdist-1.34.0 at /usr/local/lib/python2.7/dist-packages/xdist/plugin.py
  pytest-xdist-1.34.0 at /usr/local/lib/python2.7/dist-packages/xdist/looponfail.py
  pytest-randomly-1.2.3 at /usr/local/lib/python2.7/dist-packages/pytest_randomly.py

创建测试文件,文件名以test_开头:

# filename test_abc.py
def func(x):
    return x + 1


def test_answer():
    assert func(3) == 5

执行测试例,直接在当前目录输入pytest运行即可:【自动查找当前目录下,文件名以test_开头或者以_test结尾的py文件】

root#pytest
==================================================== test session starts =====================================================
platform linux2 -- Python 2.7.17, pytest-4.6.11, py-1.11.0, pluggy-0.13.1
Using --randomly-seed=1642812744
rootdir: /home/brian/autotest/aaa
plugins: forked-1.3.0, metadata-1.11.0, html-1.22.1, cov-2.12.1, mock-2.0.0, xdist-1.34.0, randomly-1.2.3
collected 1 item

test_abc.py F                                                                                                          [100%]

========================================================== FAILURES ==========================================================
________________________________________________________ test_answer _________________________________________________________

    def test_answer():
>       assert func(3) == 5
E       assert 4 == 5
E        +  where 4 = func(3)

test_abc.py:7: AssertionError
================================================== 1 failed in 0.04 seconds ==================================================
root#

执行当前目录测试用例并生成html报告:

pytest -s --html=./report.html

pytest常用参数:

-v 用于显示每个测试函数的执行结果
-q quiet
-s 用于显示测试函数中print()函数输出
-h 帮助,查看所有参数

其它执行用例的方式:

pytest ./test_abc.py #执行特定文件里的所有方法
pytest test_abc.py::test_answer  #执行特定方法
pytest test_abc.py::Test_Class::test_c #执行特定类里的特定方法

参考:

官网文档:https://docs.pytest.org/en/latest/getting-started.html#

Python测试框架之pytest(一)https://www.cnblogs.com/wxcx/p/13709570.html

posted @ 2022-01-22 09:29  船长博客  阅读(296)  评论(0编辑  收藏  举报
永远相信美好的事情即将发生!