前言:
1.我們可以通過help幫助查看pytest如何使用
查看pytest命令行參數,可以用pytest -h或pytest --help查看
2. 用例設計原則
(1)文件名以test_*.py 文件和*_test.py
(2)以test_開頭的函數
(3)以Test開頭的類
(4)以test_開頭的方法
(5)所有的包pakege必須有__init__.py文件
3.用例設計
test_sample.py
def func(x): return x + 1 def test_answer(): assert func(3) == 5
test_class.py
class TestClass: def test_one(self): x = "this" assert 'h' in x def test_two(self): x = "hello" assert hasattr(x,'check') def test_three(self): a = "hello" b = "hello world" assert a in b
一、執行方式
cmd執行pytest用例有三種方法,以下三種方法都可以,一般推薦第一個
1.pytest
2.py.test
3.python -m pytest
如果不帶參數,在某個文件夾下執行時,它會查找該文件夾下所有的符合條件的用例(查看用例設計原則)
二、執行規則
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 並使用其文件系統位置來查詢和運行測試。
7.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
三、PyCharm配置pytest

四、PyCharm運行三種方式
def hello(): print("hello world !") if __name__=="__main__": hello()
2.以unittest方式運行
當腳本命名為test_xx.py時,用到unittest框架,此時運行代碼,PyCharm會自動識別到以unittest方式運行
3.pytest方式運行
以pytest方式運行,需要改該工程設置默認的運行器:file->Setting->Tools->Python Integrated Tools->項目名稱->Default test runner->選擇pytest
ps:pytest是可以兼容unittest框架代碼
四、實際應用
在PyCharm里面寫pytest用例,先導入pytest
import pytest class TestClass: def test_one(self): x = "this" assert 'h' in x def test_two(self): x = "hello" assert hasattr(x,'check') def test_three(self): a = "hello" b = "hello world" assert a in b if __name__ == "__main__": pytest.main('[-q test_class.py')
運行結果:
五、PyCharm設置pytest
1.新建一個工程后,左上角file->Setting->Tools->Python Integrated Tools->項目名稱->Default test runner->選擇pytest
2.改完之后,再重新建個腳本(注意是先改項目運行方式,再寫代碼才能出來),接下來右鍵運行就能出來pytest運行了
3.pytest是可以兼容unittest腳本的,之前寫的unittest用例也能用pytest框架去運行
參考鏈接:https://www.jianshu.com/p/8ac2c0f70583