51Testing软件测试论坛

标题: Pytest - 使用介绍 [打印本页]

作者: 恭喜发财dife    时间: 2018-4-18 13:54
标题: Pytest - 使用介绍
1. 概述

pytest是一个非常成熟的全功能的Python测试框架,主要特点有以下几点:

1、简单灵活,容易上手,文档丰富;
2、支持参数化,可以细粒度地控制要测试的测试用例;
3、能够支持简单的单元测试和复杂的功能测试,还可以用来做selenium/appnium等自动化测试、接口自动
化测试(pytest+requests);
4、pytest具有很多第三方插件,并且可以自定义扩展,比较好用的如pytest-selenium(集成selenium)、
pytest-html(完美html测试报告生成)、pytest-rerunfailures(失败case重复执行)、pytest-xdist(多CP
U分发)等;
5、测试用例的skip和xfail处理;
6、可以很好的和CI工具结合,例如jenkins
2. 使用介绍

2.1. 安装

pip install pytest

2.2. 示例代码

编写规则

编写pytest测试样例非常简单,只需要按照下面的规则:

  1. 测试文件以test_开头(以_test结尾也可以)
  2. 测试类以Test开头,并且不能带有 init 方法
  3. 测试函数以test_开头
  4. 断言使用基本的assert即可
  5. pytest1.py

  6. # -*- coding:utf-8 -*-
  7. import pytest

  8. @pytest.fixture(scope='function')
  9. def setup_function(request):
  10.     def teardown_function():
  11.         print("teardown_function called.")
  12.     request.addfinalizer(teardown_function)  # 此内嵌函数做teardown工作
  13.     print('setup_function called.')

  14. @pytest.fixture(scope='module')
  15. def setup_module(request):
  16.     def teardown_module():
  17.         print("teardown_module called.")
  18.     request.addfinalizer(teardown_module)
  19.     print('setup_module called.')

  20. @pytest.mark.website
  21. def test_1(setup_function):
  22.     print('Test_1 called.')

  23. def test_2(setup_module):
  24.     print('Test_2 called.')

  25. def test_3(setup_module):
  26.     print('Test_3 called.')
  27.     assert 2==1+1              # 通过assert断言确认测试结果是否符合预期
  28. fixture的scope参数

  29. scope参数有四种,分别是'function','module','class','session',默认为function。

  30. function:每个test都运行,默认是function的scope
  31. class:每个class的所有test只运行一次
  32. module:每个module的所有test只运行一次
  33. session:每个session只运行一次
  34. setup和teardown操作
复制代码


setup,在测试函数或类之前执行,完成准备工作,例如数据库链接、测试数据、打开文件等
teardown,在测试函数或类之后执行,完成收尾工作,例如断开数据库链接、回收内存资源等
备注:也可以通过在fixture函数中通过yield实现setup和teardown功能
2.3. 测试结果

如何执行

  1. pytest # run all tests below current dir
  2. pytest test_mod.py # run tests in module file test_mod.py
  3. pytest somepath # run all tests below somepath like ./tests/
  4. pytest -k stringexpr # only run tests with names that match the
  5. # the "string expression", e.g. "MyClass and not method"
  6. # will select TestMyClass.test_something
  7. # but not TestMyClass.test_method_simple
  8. pytest test_mod.py::test_func # only run tests that match the "node ID",
  9. # e.g "test_mod.py::test_func" will be selected
  10. # only run test_func in test_mod.py
  11. 通过pytest.mark对test方法分类执行

  12. 通过@pytest.mark控制需要执行哪些feature的test,例如在执行test前增加修饰@pytest.mark.website

  13. 通过 -m "website" 执行有website标记的test方法
  14. $ pytest  -v -m "website" pytest1.py
  15. ============================================================================== test session starts ===============================================================================
  16. platform linux2 -- Python 2.7.14, pytest-3.0.0, py-1.5.2, pluggy-0.3.1 -- /home/kevin/soft/anaconda2/bin/python
  17. cachedir: .cache
  18. Using --randomly-seed=1522925202
  19. rootdir: /home/kevin/learn/python-web/tox/case2, inifile:
  20. plugins: randomly-1.0.0, mock-1.2, cov-2.0.0
  21. collected 3 items

  22. pytest1.py::test_1 PASSED

  23. ============================================================================= pytest-warning summary =============================================================================
  24. WC1 None pytest_funcarg__cov: declaring fixtures using "pytest_funcarg__" prefix is deprecated and scheduled to be removed in pytest 4.0.  Please remove the prefix and use the @pytest.fixture decorator instead.
  25. =============================================================================== 2 tests deselected ===============================================================================
  26. =========================================================== 1 passed, 2 deselected, 1 pytest-warnings in 0.00 seconds ============================================================
  27. 通过 -m "not website" 执行没有website标记的test方法
  28. $ pytest  -v -m "not website" pytest1.py
  29. ============================================================================== test session starts ===============================================================================
  30. platform linux2 -- Python 2.7.14, pytest-3.0.0, py-1.5.2, pluggy-0.3.1 -- /home/kevin/soft/anaconda2/bin/python
  31. cachedir: .cache
  32. Using --randomly-seed=1522925192
  33. rootdir: /home/kevin/learn/python-web/tox/case2, inifile:
  34. plugins: randomly-1.0.0, mock-1.2, cov-2.0.0
  35. collected 3 items

  36. pytest1.py::test_3 PASSED
  37. pytest1.py::test_2 PASSED

  38. ============================================================================= pytest-warning summary =============================================================================
  39. WC1 None pytest_funcarg__cov: declaring fixtures using "pytest_funcarg__" prefix is deprecated and scheduled to be removed in pytest 4.0.  Please remove the prefix and use the @pytest.fixture decorator instead.
  40. =============================================================================== 1 tests deselected ===============================================================================
  41. =========================================================== 2 passed, 1 deselected, 1 pytest-warnings in 0.00 seconds ============================================================
  42. Console参数介绍

  43. -v 用于显示每个测试函数的执行结果
  44. -q 只显示整体测试结果
  45. -s 用于显示测试函数中print()函数输出
  46. -x, --exitfirst, exit instantly on first error or failed test
  47. -h 帮助
  48. Case 1

  49. $ pytest -v pytest1.py
  50. ============================================================================== test session starts ===============================================================================
  51. platform linux2 -- Python 2.7.14, pytest-3.0.0, py-1.5.2, pluggy-0.3.1 -- /home/kevin/soft/anaconda2/bin/python
  52. cachedir: .cache
  53. Using --randomly-seed=1522920341
  54. rootdir: /home/kevin/learn/python-web/tox/case2, inifile:
  55. plugins: randomly-1.0.0, mock-1.2, cov-2.0.0
  56. collected 3 items

  57. pytest1.py::test_1 PASSED
  58. pytest1.py::test_3 PASSED
  59. pytest1.py::test_2 PASSED

  60. ============================================================================= pytest-warning summary =============================================================================
  61. WC1 None pytest_funcarg__cov: declaring fixtures using "pytest_funcarg__" prefix is deprecated and scheduled to be removed in pytest 4.0.  Please remove the prefix and use the @pytest.fixture decorator instead.
  62. ================================================================== 3 passed, 1 pytest-warnings in 0.01 seconds ===================================================================
  63. Case 2

  64. $ pytest -s pytest1.py
  65. ============================================================================== test session starts ===============================================================================
  66. platform linux2 -- Python 2.7.14, pytest-3.0.0, py-1.5.2, pluggy-0.3.1
  67. Using --randomly-seed=1522920508
  68. rootdir: /home/kevin/learn/python-web/tox/case2, inifile:
  69. plugins: randomly-1.0.0, mock-1.2, cov-2.0.0
  70. collected 3 items

  71. pytest1.py setup_function called.
  72. Test_1 called.
  73. .teardown_function called.
  74. setup_module called.
  75. Test_2 called.
  76. .Test_3 called.
  77. .teardown_module called.


  78. ====================================================================
  79. ========= pytest-warning summary ===========================================
  80. ==================================
  81. WC1 None pytest_funcarg__cov: declaring fixtures using "pytest_funcarg__" prefix is deprecated and schedu
  82. led to be removed in pytest 4.0.  Please remove the prefix and use the @pytest.fixture decorator instead.
  83. ==================================================================
  84. 3 passed, 1 pytest-warnings in 0.01 seconds ======================================
  85. =============================
  86. 3. 扩展插件

  87. 3.1. 测试报告

  88. 安装与样例

  89. pip install pytest-cov # 计算pytest覆盖率,支持输出多种格式的测试报告
  90. pytest --cov-report=html --cov=./ test_code_target_dir

  91. Console参数介绍

  92. --cov=[path], measure coverage for filesystem path (multi-allowed), 指定被测试对象,用于计算测试覆盖率
  93. --cov-report=type, type of report to generate: term, term-missing, annotate, html, xml (multi-allowed), 测试报告的类型
  94. --cov-config=path, config file for coverage, default: .coveragerc, coverage配置文件
  95. --no-cov-on-fail, do not report coverage if test run fails, default: False,如果测试失败,不生成测试报告
  96. --cov-fail-under=MIN, Fail if the total coverage is less than MIN. 如果测试覆盖率低于MIN,则认为失败
  97. Console Result
复制代码


---------------------------------------------------------------- coverage: platform linux2, python 2.7.14-final-0 ----------------------------------------------------------------
Name         Stmts   Miss  Cover
--------------------------------
pytest1.py      18      0   100%
Html Result

[attach]113881[/attach]
3.2. 测试顺序随机

pip install pytest-randomly

3.3. 分布式测试

pip install pytest-xdist

3.4. 出错立即返回

pip install pytest-instafail




作者: libingyu135    时间: 2018-4-19 17:41
腻害了,多谢分享
作者: libingyu135    时间: 2018-4-19 17:41
腻害了,多谢分享
作者: 赵佳乐SMILE    时间: 2019-4-16 08:33
强大 学习了




欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) Powered by Discuz! X3.2