1. 概述
pytest是一個非常成熟的全功能的Python測試框架,主要特點有以下幾點:
- 1、簡單靈活,容易上手,文檔豐富;
- 2、支持參數化,可以細粒度地控制要測試的測試用例;
- 3、能夠支持簡單的單元測試和複雜的功能測試,還可以用來做selenium/appnium等自動化測試、接口自動化測試(pytest+requests);
- 4、pytest具有很多第三方插件,並且可以自定義擴展,比較好用的如pytest-selenium(集成selenium)、pytest-html(完美html測試報告生成)、pytest-rerunfailures(失敗case重複執行)、pytest-xdist(多CPU分發)等;
- 5、測試用例的skip和xfail處理;
- 6、可以很好的和CI工具結合,例如jenkins
編寫規則
編寫pytest測試樣例非常簡單,只需要按照下面的規則:
- 測試文件以test_開頭(以_test結尾也可以)
- 測試類以Test開頭,並且不能帶有 init 方法
- 測試函數以test_開頭
- 斷言使用基本的assert即可
pytest1.py
# -*- coding:utf-8 -*-
import pytest
@pytest.fixture(scope='function')
def setup_function(request):
def teardown_function():
print("teardown_function called.")
request.addfinalizer(teardown_function) # 此內嵌函數做teardown工作
print('setup_function called.')
@pytest.fixture(scope='module')
def setup_module(request):
def teardown_module():
print("teardown_module called.")
request.addfinalizer(teardown_module)
print('setup_module called.')
@pytest.mark.website
def test_1(setup_function):
print('Test_1 called.')
def test_2(setup_module):
print('Test_2 called.')
def test_3(setup_module):
print('Test_3 called.')
assert 2==1+1 # 通過assert斷言確認測試結果是否符合預期
fixture的scope參數
scope參數有四種,分別是'function','module','class','session',默認爲function。
- function:每個test都運行,默認是function的scope
- class:每個class的所有test只運行一次
- module:每個module的所有test只運行一次
- session:每個session只運行一次
setup和teardown操作
- setup,在測試函數或類之前執行,完成準備工作,例如數據庫鏈接、測試數據、打開文件等
- teardown,在測試函數或類之後執行,完成收尾工作,例如斷開數據庫鏈接、回收內存資源等
- 備註:也可以通過在fixture函數中通過yield實現setup和teardown功能
2.3. 測試結果
如何執行
- pytest # run all tests below current dir
- pytest test_mod.py # run tests in module file test_mod.py
- pytest somepath # run all tests below somepath like ./tests/
- pytest -k stringexpr # only run tests with names that match the
# the "string expression", e.g. "MyClass and not method"
# will select TestMyClass.test_something
# but not TestMyClass.test_method_simple - pytest test_mod.py::test_func # only run tests that match the "node ID",
# e.g "test_mod.py::test_func" will be selected
# only run test_func in test_mod.py
通過pytest.mark對test方法分類執行
Console參數介紹
- -v 用於顯示每個測試函數的執行結果
- -q 只顯示整體測試結果
- -s 用於顯示測試函數中print()函數輸出
- -x, --exitfirst, exit instantly on first error or failed test
- -h 幫助
Case 1
$ pytest -v pytest1.py
============================================================================== test session starts ===============================================================================
platform linux2 -- Python 2.7.14, pytest-3.0.0, py-1.5.2, pluggy-0.3.1 -- /home/kevin/soft/anaconda2/bin/python
cachedir: .cache
Using --randomly-seed=1522920341
rootdir: /home/kevin/learn/python-web/tox/case2, inifile:
plugins: randomly-1.0.0, mock-1.2, cov-2.0.0
collected 3 items
pytest1.py::test_1 PASSED
pytest1.py::test_3 PASSED
pytest1.py::test_2 PASSED
============================================================================= pytest-warning summary =============================================================================
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.
================================================================== 3 passed, 1 pytest-warnings in 0.01 seconds ===================================================================
Case 2
$ pytest -s pytest1.py
============================================================================== test session starts ===============================================================================
platform linux2 -- Python 2.7.14, pytest-3.0.0, py-1.5.2, pluggy-0.3.1
Using --randomly-seed=1522920508
rootdir: /home/kevin/learn/python-web/tox/case2, inifile:
plugins: randomly-1.0.0, mock-1.2, cov-2.0.0
collected 3 items
pytest1.py setup_function called.
Test_1 called.
.teardown_function called.
setup_module called.
Test_2 called.
.Test_3 called.
.teardown_module called.
============================================================================= pytest-warning summary =============================================================================
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.
================================================================== 3 passed, 1 pytest-warnings in 0.01 seconds ===================================================================
參考
-
python的測試工具大全
https://wiki.python.org/moin/PythonTestingToolsTaxonomy -
python主流的測試工具橫向比較
http://docs.python-guide.org/en/latest/writing/tests/
http://pythontesting.net/test-podcast/ -
python單元測試框架pytest簡介
https://blog.csdn.net/liuchunming033/article/details/46501653
===============================================================================
1. pytest簡介
pytest是一款以python爲開發語言的測試框架,具有以下優點:
- 文檔豐富,簡單,易上手;
- 支持參數化,可以細粒度地控制要測試的測試用例;
- pytest具有很多第三方插件,並且可以自定義擴展,比較好用的如pytest-selenium(集成selenium)、pytest-html(完美html測試報告生成)等;
- 很好的和CI工具結合;
2. pytest安裝
2.1Python3安裝
2.2 pytest安裝
1. python3安裝好後,使用pip命令安裝pytest:pip install pytest
2. 輸入如下命令,查看pytest是否安裝成功:pytest --version
3. pytest測試case編寫規則
- 測試類以Test開頭;
- 測試文件以test_開頭或_test結尾;
- 測試函數以test_開頭;
4. 一個例子
4.1 實現
# -*- coding:utf-8 -*-
import pytest
@pytest.mark.pytestto
class TestPytestDemo(object):
def setup_class(self):
pass
@pytest.mark.asserttest
def test_assert(self):
assert 3 < 4, "3期望是小於4"
@pytest.mark.strtest
def test_str(self):
b = "hello"
assert "h" in b, "字符h期望在單詞hello中出現"
4.2 pytest用例運行
4.2.1 運行整個testcase文件,比如測試文件名爲:test_pytest_demo_ok.py。
pytest test_pytest_demo_ok.py
pytest-case-run.jpg
4.2.2 通過mark運行case
# 通過mark後的關鍵字制定用例運行,上個圖中看到運行log中有很多警告,
# 如果不要看警告可通過參數 ----disable-pytest-warnings
pytest -m asserttest --disable-pytest-warnings
mark-run.jpg
4.3 運行結果以html格式報告輸出
** 4.3.1 Pytest有個用於生成html測試結果報告的插件:pytest-html,可直接使用pip命令安裝。**
pip install pytest-html
4.3.2 在執行用例時,需要加上參數:--html,如:
pytest -m pytestto --disable-pytest-warnings --html=report.html
html-report.jpg
4.3.3 指定報告的存放路徑,需使用如下格式,比如,指定到一個log的文件夾裏:
pytest --html=./log/report.html