[TOC]python
pytest
安裝與入門
1.pip install -U pytest
2.建立一個test01.py的文件
def func(x): return x + 1 def test_answer(): assert func(3) == 5
3.在該目錄下執行pytest(venv)
D:\4_code\study>pytest ============================= test session starts ============================= platform win32 -- Python 3.6.2, pytest-3.7.1, py-1.5.4, pluggy-0.7.1 rootdir: D:\4_code\study, inifile: collected 1 itemjson
test01.py . [100%]session
========================== 1 passed in 0.19 seconds ===========================ide
(venv) D:\4_code\study>pytest測試
4.執行多個,新建一個py文件 test02.py
def add(x, y): return x + y def test_add(): assert add(1, 0) == 1 assert add(1, 1) == 2 assert add(1, 99) == 100
執行pytestui
(venv) D:\4_code\study>pytest ============================= test session starts ============================= platform win32 -- Python 3.6.2, pytest-3.7.1, py-1.5.4, pluggy-0.7.1 rootdir: D:\4_code\study, inifile: collected 2 itemsthis
test01.py . [ 50%] test02.py . [100%]url
========================== 2 passed in 0.30 seconds ===========================spa
pytest
將在當前目錄及其子目錄中運行test _ * .py或* _test.py形式的全部文件。.net
5.在一個類中組合多個測試
一旦開發了多個測試,您可能但願將它們分組到一個類中。pytest能夠很容易地建立一個包含多個測試的類:
class TestClass(object): def test_one(self): x = "this" assert 'h' in x def test_two(self): x = "hello" assert hasattr(x, 'check')
(venv) D:\4_code\study>pytest ============================= test session starts ============================= platform win32 -- Python 3.6.2, pytest-3.7.1, py-1.5.4, pluggy-0.7.1 rootdir: D:\4_code\study, inifile: collected 4 items
test_calc.py . [ 25%] test_class.py .F [ 75%] test_quick_start.py . [100%]
================================== FAILURES =================================== _____________________________ TestClass.test_two ______________________________
self = <test_class.TestClass object at 0x058A59F0>
def test_two(self): x = "hello"
assert hasattr(x, 'check') E AssertionError: assert False E + where False = hasattr('hello', 'check')
test_class.py:16: AssertionError ===================== 1 failed, 3 passed in 0.37 seconds ======================
6.指定測試 用例
(venv) D:\4_code\study>pytest -q test_calc.py . [100%] 1 passed in 0.02 seconds
7.Assert
pytest使用的是python自帶的assert關鍵字來進行斷言 assert關鍵字後面能夠接一個表達式,只要表達式的最終結果爲True,那麼斷言經過,用例執行成功,不然用例執行失敗
斷言異常拋出 如
import pytest def test_zero_division(): with pytest.raises(ZeroDivisionError): 1 / 0
1/0的時候應該拋出ZeroDivisionError,不然用例失敗,斷言不經過。
8.Fixture
如測試數據爲
[ {"name":"jack","password":"Iloverose"}, {"name":"rose","password":"Ilovejack"}, {"name":"tom","password":"password123"} ]
import pytest import json class TestUserPassword(object): @pytest.fixture def users(self): return json.loads(open('./users.dev.json', 'r').read()) # 讀取當前路徑下的users.dev.json文件,返回的結果是dict def test_user_password(self, users): # 遍歷每條user數據 for user in users: passwd = user['password'] assert len(passwd) >= 6 msg = "user %s has a weak password" %(user['name']) assert passwd != 'password', msg assert passwd != 'password123', msg
(venv) D:\4_code\study>pytest test_user_password.py ============================= test session starts ============================= platform win32 -- Python 3.6.2, pytest-3.7.1, py-1.5.4, pluggy-0.7.1 rootdir: D:\4_code\study, inifile: collected 1 item test_user_password.py F [100%] ================================== FAILURES =================================== _____________________ TestUserPassword.test_user_password _____________________ self = <test_user_password.TestUserPassword object at 0x044783B0> users = [{'name': 'jack', 'password': 'Iloverose'}, {'name': 'rose', 'password': 'Ilovejack'}, {'name': 'tom', 'password': 'password123'}] def test_user_password(self, users): # 遍歷每條user數據 for user in users: passwd = user['password'] assert len(passwd) >= 6 msg = "user %s has a weak password" %(user['name']) assert passwd != 'password', msg > assert passwd != 'password123', msg E AssertionError: user tom has a weak password E assert 'password123' != 'password123' test_user_password.py:16: AssertionError ========================== 1 failed in 0.26 seconds ===========================
使用@pytest.fixture裝飾器能夠定義feature 在用例的參數中傳遞fixture的名稱以便直接調用fixture,拿到fixture的返回值 3個assert是遞進關係,前1個assert斷言失敗後,後面的assert是不會運行的,所以重要的assert放到前面 E AssertionError: user tom has a weak password能夠很容易的判斷出是哪條數據出了問題,因此定製可讀性好的錯誤信息是很必要的 任何1個斷言失敗之後,for循環就會退出,因此上面的用例1次只能發現1條錯誤數據,換句話說任何1個assert失敗後,用例就終止運行了
執行順序
pytest找到以test_開頭的方法,也就是test_user_password方法,執行該方法時發現傳入的參數裏有跟fixture users名稱相同的參數 pytest認定users是fixture,執行該fixture,讀取json文件解析成dict實例 test_user_password方法真正被執行,users fixture被傳入到該方法
使用下面的命令來查看用例中可用的fixtures
pytest --fixtures test_user_password.py
------------------ fixtures defined from test_user_password ------------------- users test_user_password.py:6: no docstring available ======================== no tests ran in 0.07 seconds =========================
數據清理
有時候咱們須要在用例結束的時候去清理一些測試數據,或清除測試過程當中建立的對象,咱們能夠使用下面的方式
import smtplib import pytest @pytest.fixture(scope="module") def smtp(): smtp = smtplib.SMTP("smtp.gmail.com", 587, timeout=5) yield smtp # provide the fixture value print("teardown smtp") smtp.close() yield 關鍵字返回了fixture中實例化的對象smtp module中的用例執行完成後smtp.close()方法會執行,不管用例的運行狀態是怎麼樣的,都會執行