pytest從入門到放棄1--pytest執行規則
阿新 • • 發佈:2020-08-17
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
- 從包裡面執行: 從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)指定檔名,執行pytestdemo_1.py,用例執行成功,只執行 test_開頭的函式,others()方法未執行
5、測試用例設計規則:
- 以test_*.py 或者 *_test.py 的檔案
- 以 test 開頭的函式名
- 以Test 開頭的類(沒有__init__函式),以test_開頭的函式
6、unittest 框架程式碼相容,修改 pycharm 測試指令碼的預設執行器為 pytest,再次執行時,會出現 pytest in xx.py 的執行方式。