pytest 官方API說明:https://docs.pytest.org/en/latest/reference.html
1、pytest安裝: pip install -U pytest -i https://pypi.tuna.tsinghua.edu.cn/simple
2、pytest運行方式:
- 不帶參數: pytest
- 指定模塊: pytest .py文件名
- 指定目錄: pytest dir\
-
關鍵字過濾: pytest -k "MyClass and not method"
- 關鍵字包括 文件名、類名、方法名
- 節點id: py模塊名::類名::方法名 或者 py模塊名::函數名 pytest test_xxx.py::TestXxx::func_xxx
- 標簽表達式: 執行被裝飾器 @pytest.mark.smoke 裝飾的所有測試用例 pytest -m smoke
- 從包里面運行: 從pkg.test包所在位置查找和執行用例 pytest --pyargs pkg.test
- 停止測試:
- -x 遇到錯誤時停止測試 pytest -x test_xxx.py
- 當用例錯誤個數達到指定數量時,停止測試 ytest –maxfail=1
3、pytest運行規則:
- pytest 匹配 當前目錄 下以 test_*.py 或者 *_test.py 命名的所有文件
- 如果文件中存在以 test_ 開頭的函數,則運行所有 test_ 開頭的函數
- 如果文件中存在以 Test_ 開頭的類(沒有__init__函數),則匹配 Test_ 類中以 test_ 開頭的方法
4、編寫一個名為 demo_1.py 的文件
def my_func(x):
return x
def test_my_func():
assert my_func('hello world!') == 'hello world'
class TestMethod:
def test_1(self):
a = 'hello world!'
assert 'hello' in a
def test_2(self):
x = 'hello world!'
assert hasattr(x, 'helloWorld')
def others(self):
b = 3
assert b == 4
1)直接執行 pytest,運行結果未找到可執行用例,因為文件名為 demo_1,不符合pytest運行的規則
2)指定文件名,執行 pytest demo_1.py,用例執行成功,只執行 test_開頭的函數,others()方法未執行
5、測試用例設計規則:
- 以test_*.py 或者 *_test.py 的文件
- 以 test 開頭的函數名
- 以Test 開頭的類(沒有__init__函數),以test_開頭的函數
6、unittest 框架代碼兼容,修改 pycharm 測試腳本的默認執行器為 pytest,再次執行時,會出現 pytest in xx.py 的執行方式。