1. 執行方式
cmd執行pytest用例有三種方法,以下三種方法都可以,一般推薦第一個
- pytest
- py.test
- python -m pytest
如果不帶參數,在某個文件夾下執行時,它會查找該文件夾下所有的符合條件的用例(查看用例設計原則)
2. 執行規則
1.執行某個目錄下所有的用例
pytest
文件名/
2.執行某一個py文件下用例
pytest
腳本名稱.py
3.-k 按關鍵字匹配
pytest -k
“MyClass and not method”
4.按節點運行
運行.py模塊里面的某個函數
pytest test_mod.py::test_func
運行.py模塊里面,測試類里面的某個方法
pytest test_mod.py::TestClass::test_method
5.標記表達式
pytest -m slow
將運行用@ pytest.mark.slow
裝飾器修飾的所有測試。
6.從包里面運行
pytest —pyargs pkg.testing
這將導入pkg.testing
并使用其文件系統位置來查找和運行測試。
- pytest -x( 遇到錯誤時停止測試)
pytest -x test_class.py
從運行結果可以看出,本來有3個用例,第二個用例失敗后就沒繼續往下執行了
D:\YOYO>pytest -x test_class.py
============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-3.6.3, py-1.5.4, pluggy-0.6.0
rootdir: D:\YOYO, inifile:
collected 3 items
test_class.py .F
================================== FAILURES ===================================
_____________________________ TestClass.test_two ______________________________
self = <YOYO.test_class.TestClass object at 0x0000000003A29780>
def test_two(self):
x = "hello"
> assert hasattr(x, 'check')
E AssertionError: assert False
E + where False = hasattr('hello', 'check')
test_class.py:11: AssertionError
===================== 1 failed, 1 passed in 0.05 seconds ======================
8.pytest -maxfail=num(當用例錯誤個數達到指定數量時,停止測試)
pytest —maxfail=1
3. pycharm配置pytest
以pytest方式運行,需要改該工程設置默認的運行器:file->Setting->Tools->Python Integrated Tools->項目名稱->Default test runner->選擇pytes
image.png