pytest-learn
通過文章 Python 單元測試框架之 Pytest 剖解入門(第一篇) 學習 Pytest。
有很多的第三方插件可以自定義擴展,並且支持 Allure,生成可視化的測試報告和測試結果,並能輸出 log 信息
說明
本文實驗環境為:
- windows 7
- python 3.7.0
- pytest version 4.0.1
安裝
pip install -U pytest
pytest --version # This is pytest version 4.0.1
# 安裝插件
pip install pytest-html # 自動生成 HTML 格式測試報告
pip install pytest-autochecklog # 不只是自動生成測試日志
pip install pytest-describe # 給測試用例一個美麗的名字
Pycahrm 配置 Pytest
File -> Settings -> Tools -> Python Integrated Tools
,在 Default test runner 中選擇 Pytest 。我們可以回到寫有測試函數的文件中直接右鍵,會出現一個Run 'py.test' for project_name
,直接點擊即可運行自動化測試。
Pytest 測試樣例規范
- 測試文件以 test_ 開頭(以 _test 結尾也可以)
- 測試類以 Test 開頭,並且不能帶有 init 方法
- 測試函數以 test_ 開頭
- 斷言使用基本的 assert 即可
創建第一個測試用例
# content of test_sample.py
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
直接在該文件夾下打開命令行,輸入pytest
即可運行。
斷言某個異常會引發
# content of test_sysexit.py
import pytest
def f():
raise SystemExit(1)
def test_mytest():
with pytest.raises(SystemExit):
f()
運行如下命令:
pytest -q test_sysexit.py # 用例通過 -q 表示 quite
在一個 class 中組合多個測試
一旦開發了多個測試,您可能希望將它們分組到一個類中。 pytest 可以輕松創建包含多個測試的類:
# content of test_class.py
class TestClass(object):
def test_one(self):
x = "this"
assert 'h' in x
def test_two(self):
x = "hello"
assert hasattr(x, 'check')
運行如下命令:
pytest -q test_class.py
為功能測試請求一個唯一的臨時目錄
pytest 提供 Built fixtures/function arguments 來請求任意資源,比如一個獨一無二的臨時目錄:
# content of test_tmpdir.py
def test_needsfiles(tmpdir):
print(tmpdir)
assert 0
pytest -q test_tmpdir.py
pytest 會在測試函數調用之前,查找並調用一個fixture factory
來創建這個資源。 在這個測試用例運行之前,pytest 為每個測試調用創建獨一無二的目錄。
關於提供的tmpdir
更多的信息,可以查詢Temporary diretories and files
可以通過如下命令查看自帶的 pytest fixtures:
pytest --fixtures # shows builtin and custom fixtures
Note: 命令行除非加上 -v
,否則如上命令將會自動省略_
開頭的fixtures
。
生成測試報告
pytest-html
# 安裝插件
pip install -U pytest-html
運行:
pytest --html=report.html