前言
pytest 是 python 的一個第三方單元測試框架,它繼承自 python 自帶的單元測試框架unittest,兼容 unittest。
相比unittest,pytest的可擴展性更高,也是目前最為流行的 python 單元測試框架。至于它擴展性表現(xiàn)在哪些方面,我們需在后續(xù)的學(xué)習(xí)中一點一點進(jìn)行總結(jié)。
簡單使用
1 安裝
安裝pytest
pip install -U pytest
驗證安裝是否成功
pytest --version
2 用例編寫
為了先讓大家對pytest的使用有個粗淺的認(rèn)識,接下來我們使用pytest對兩個自定義接口進(jìn)行簡單測試,其中查詢所有用戶信息接口為get請求,注冊用戶接口為post請求,編寫腳本test_demo.py,代碼如下:
import pytest
import requests, json
class TestDemo:
def test_get_all_users(self):
'''查詢所有用戶信息'''
url = "http://127.0.0.1:5000/users"
# 請求接口
res = requests.get(url=url).text
res = json.loads(res)
print(res)
# 斷言
assert res['code'] == 0
def test_register(self):
'''注冊用戶'''
headers = {"Content-Type": "application/json;charset=utf8"}
url = "http://127.0.0.1:5000/register"
data = {
"username": "張學(xué)友",
"password": "123456",
"sex": "0",
"telephone": "13823456789",
"address": "北京東城區(qū)"
}
# 請求接口
res = requests.post(url=url, headers=headers, json=data).text
res = json.loads(res)
print(res)
# 斷言
assert res['code'] == 0
if __name__ == '__main__':
pytest.main()
注意,測試類中不能定義init方法。
3 用例執(zhí)行
-
方式一:在python代碼里調(diào)用pytest,使用
pytest.mian()# 執(zhí)行當(dāng)前目錄下的測試用例 pytest.main() # 執(zhí)行指定的測試用例 pytest.main("testcase/test_one.py") # 加參數(shù)如-s,執(zhí)行參數(shù)根據(jù)需要進(jìn)行添加,后面文章會對常用的參數(shù)進(jìn)行說明 pytest.main(["-s", "testcase/test_one.py"])pycharm控制臺輸出如下:
-
方式二:命令行執(zhí)行
pytest命令行執(zhí)行
pytest + 測試文件路徑,示例如下pytest E:/apiAutoTest/test_demo.py # 加參數(shù)如-s pytest -s E:/apiAutoTest/test_demo.py除了上面的直接通過pytest命令調(diào)用外,還可以通過命令在python解釋器里調(diào)用,
python -m 測試文件完整路徑,如下:python -m pytest E:/apiAutoTest/test_demo.py
結(jié)果如下:

總結(jié)
如果使用unittest框架編寫上面的測試用例的話,代碼應(yīng)該如下:
import unittest
import requests, json
class TestDemo(unittest.TestCase):
def test_get_all_users(self):
'''查詢所有用戶信息'''
url = "http://127.0.0.1:5000/users"
res = requests.get(url=url).text
res = json.loads(res)
self.assertEqual(res['code'], 0)
def test_register(self):
'''注冊用戶'''
headers = {"Content-Type": "application/json;charset=utf8"}
url = "http://127.0.0.1:5000/register"
data = {
"username": "張學(xué)友",
"password": "123456",
"sex": "0",
"telephone": "13823456789",
"address": "北京東城區(qū)"
}
res = requests.post(url=url, headers=headers, json=data).text
res = json.loads(res)
self.assertEqual(res['code'], 0)
if __name__ == '__main__':
unittest.main()
由這個簡單的測試用例,我們可以比較出pytest與unittest 在測試用例的編寫及執(zhí)行時不一樣的地方:
pytest框架編寫測試用例時,只需要引入 pytest 模塊,使用python源生態(tài)的 assert 進(jìn)行斷言,且可以使用自帶的命令行執(zhí)行測試用例。而
unittest框架編寫測試用例時,自定義的測試類需要繼承unittest.TestCase,斷言則使用的是unittest提供的斷言方式(如 assertEqual、assertTrue、assertIn等),沒有提供命令行方式執(zhí)行測試用例。
當(dāng)然,pytest與unittest的區(qū)別遠(yuǎn)不止這些,待我們后續(xù)慢慢道來。
