對多表進行查詢並知道這個資料是哪張表得出的,同時需要對結果集進行排序等操作
阿新 • • 發佈:2020-12-21
是什麼
python的一種單元測試框架,與python自帶的unittest測試框架類似,但是比unittest框架使用起來更簡潔,效率更高
安裝
pip install -U pytest
舉例
測試檔案
# content of test_sample.py
def func(x):
return x+1
def test_func():
assert func(3) == 3
執行測試
$ py.test =========================== test session starts ============================ platform linux -- Python 3.4.1 -- py-1.4.27 -- pytest-2.7.1 rootdir: /tmp/doc-exec-101, inifile: collected 1 items test_sample.py F ================================= FAILURES ================================= _______________________________ test_answer ________________________________ def test_answer(): > assert func(3) == 5 E assert 4 == 5 E + where 4 = func(3) test_sample.py:5: AssertionError ========================= 1 failed in 0.01 seconds =========================
使用
編寫規則
編寫pytest測試樣例非常簡單,只需要按照下面的規則:
- 測試檔案以test_開頭(以_test結尾也可以)
- 測試類以Test開頭,並且不能帶有 init 方法
- 測試函式以test_開頭
- 斷言使用基本的assert即可
執行測試
py.test # run all tests below current dir py.test test_mod.py # run tests in module py.test somepath # run all tests below somepath py.test -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 py.test test_mod.py::test_func # only run tests that match the "node ID", # e.g "test_mod.py::test_func" will select # only test_func in test_mod.py
測試報告
安裝pytest-html外掛
pip install pytest-html
執行生成
py.test --html=path
生成xml報告(無需外掛)
py.test --junitxml=path
覆蓋率
安裝外掛pytest-cov
pip install pytest-cov
執行
pytest --cov-report=html --cov=./ test_code_target_dir
注:這裡的覆蓋率值被測試函式的覆蓋率,未被顯式測試函式不參與覆蓋率計算
引數說明
—cov=[path], measure coverage for filesystem path (multi-allowed), 指定被測試物件,用於計算測試覆蓋率 —cov-report=type, type of report to generate: term, term-missing, annotate, html, xml (multi-allowed), 測試報告的型別 —cov-config=path, config file for coverage, default: .coveragerc, coverage配置檔案 —no-cov-on-fail, do not report coverage if test run fails, default: False,如果測試失敗,不生成測試報告 —cov-fail-under=MIN, Fail if the total coverage is less than MIN. 如果測試覆蓋率低於MIN,則認為失敗
獲取幫助
py.test --version # shows where pytest was imported from
py.test --fixtures # show available builtin function arguments
py.test -h | --help # show help on command line and config file options
- -v 用於顯示每個測試函式的執行結果
- -q 只顯示整體測試結果
- -s 用於顯示測試函式中print()函式輸出
- -x, —exitfirst, exit instantly on first error or failed test
- -h 幫助
其他功能
- 測試順序隨機
pip install pytest-randomly - 分散式測試
pip install pytest-xdist - 出錯立即返回
pip install pytest-instafail