pytest快速入门

简介

The pytest framework makes it easy to write small, readable tests, and can scale to support complex functional testing for applications and libraries.

官网地址
中文翻译地址

1、安装

pip install pytest

2、快速上手

新建test.py文件:

  1. #test.py
  2. import pytest
  3. def inc(x):
  4. return x+1
  5. def testAnswerWrong():
  6. assert inc(3) == 5
  7. def testAnswerRight():
  8. assert inc(3) == 4
  9. if __name__ =="__main__":
  10. pytest.main(['test.py'])

运行结果:

  1. ============================= test session starts =============================
  2. platform win32 -- Python 3.8.5, pytest-6.2.5, py-1.10.0, pluggy-0.13.1
  3. plugins: allure-pytest-2.9.42, Faker-8.4.0, forked-1.3.0, html-2.0.1, metadata-1.11.0, ordering-0.6, rerunfailures-10.0, xdist-2.3.0, seleniumbase-1.63.11
  4. collected 2 items
  5. test.py F. [100%]
  6. ================================== FAILURES ===================================
  7. _______________________________ testAnswerWrong _______________________________
  8. def testAnswerWrong():
  9. > assert inc(3) == 5
  10. E assert 4 == 5
  11. E + where 4 = inc(3)
  12. test.py:11: AssertionError
  13. =========================== short test summary info ===========================
  14. FAILED test.py::testAnswerWrong - assert 4 == 5
  15. ========================= 1 failed, 1 passed in 0.21s =========================
  16. ***Repl Closed***

注解

  • pytest 使用 . 标识测试成功(PASSED)
  • pytest 使用 F 标识测试失败(FAILED)

3、编写原则

用Pytest写用例时候,一定要按照下面的规则去写,否则不符合规则的测试用例是不会执行的

  • 文件名以 test_.py 文件和 _test.py
  • 以test_开头的函数
  • 以Test开头的类,不能包含init方法
  • 以test_开头的类里面的方法
  • 所有的包 package 必须要有init.py文件

    4、运行方式

    以前文test.py测试文件举例

(1) 主函数方式运行:

指定运行文件:pytest.main(['-s','test.py'])

注意:如果py文件是以test开头或者以_test结尾则可以使用pytest.main()运行。因为pytest.main()会运行当前目录下所有以test开头或者以_test结尾的文件。

(2) 命令行方式运行

点开Pycharm左下角,在Terminal打开当面目录下的命令行窗口,或者windows用户也可直接打开CMD命令行窗口,输入命令执行:pytest test.py

注意:如果py文件是以test开头或者以_test结尾则可以使用pytest命令运行,因为pytest会运行当前目录下所有以test开头或者以_test结尾的文件。

5、运行参数说明

  • -s显示打印内容

如:pytest test.py -s

等价于:pytest.main([‘-s’,’test.py’])

  • ::指定测试用例运行

运行函数,如:pytest pytest-demo.py::test_01

等价于:pytest.main([‘-s’,’test.py::test01’])

运行类中方法:如:pytest test.py::TestCase::test_03

等价于:pytest.main([‘-s’, ‘test.py::TestCase::test_03’])

  • –html=路径/report.html生成xml/html格式测试报告(需要先安装pytest-html)

如:pytest pytest-demp.py —html-./report.html

等价于:pytest.main([‘-s’,’test.py’,’–html=./report.html’])

  • –maxfail=1出现1个失败就终止测试

如:pytest pytest-demo.py —maxfail=1

等价于:pytest.main([’-s’,’pytest-demo.py’,’ —maxfail=1’])

  • -npytest-xdist多线程运行(需要先安装pytest-xdist)

如:pytest test.py -n 2

等价于:pytest.main([‘-s’,’pytest-demo.py’,’-n=2’])

  • -x 遇到错误时停止测试

如:pytest test.py -x

  • --maxfail=num,当用例错误个数达到指定数量时,停止测试

如:pytest test.py —maxfail=3

  • -k 匹配用例名称 ,执行测试用例名称包含关键字的所有用例

如:pytest test.py -k 关键字
排除某些用例
如:pytest test.py -k ‘not 关键字’
或者关系的某些用例
如:pytest test.py -k ‘关键字A or 关键字B’