Python 自動(dòng)化測(cè)試可以通過(guò)多種框架和工具實(shí)現(xiàn),覆蓋單元測(cè)試、接口測(cè)試、UI 測(cè)試等場(chǎng)景。使用Python進(jìn)行自動(dòng)化測(cè)試的方法有很多,unittest是Python的內(nèi)置模塊,不需要額外安裝,提供了一些工具,可以幫助我們編寫和運(yùn)行測(cè)試,確保代碼按預(yù)期工作。以下是具體方法和示例,幫助你快速上手。
一、Python 自動(dòng)化測(cè)試的核心框架
1. 單元測(cè)試:unittest(Python 內(nèi)置)
適用場(chǎng)景:測(cè)試函數(shù)、類等最小單元。
示例:
pythonimport unittestdef add(a, b):return a + bclass TestAdd(unittest.TestCase):def test_add_positive(self):self.assertEqual(add(2, 3), 5)def test_add_negative(self):self.assertEqual(add(-1, 1), 0)if __name__ == '__main__':unittest.main()
運(yùn)行方式:直接執(zhí)行腳本,或通過(guò)命令行 python -m unittest test_module.py。
2. 接口測(cè)試:requests + pytest
適用場(chǎng)景:測(cè)試 RESTful API 的請(qǐng)求與響應(yīng)。
示例:
pythonimport requestsimport [email protected] api_url():return "https://jsonplaceholder.typicode.com/posts/1"def test_get_request(api_url):response = requests.get(api_url)assert response.status_code == 200assert response.json()["id"] == 1def test_post_request(api_url):data = {"title": "foo", "body": "bar", "userId": 1}response = requests.post(api_url, json=data) # 實(shí)際API可能不支持POST到此端點(diǎn)assert response.status_code == 201 # 根據(jù)實(shí)際API調(diào)整
運(yùn)行方式:安裝 pytest 后執(zhí)行 pytest test_api.py -v。
3. UI 測(cè)試:Selenium + pytest
適用場(chǎng)景:自動(dòng)化操作瀏覽器。
示例:
pythonfrom selenium import webdriverfrom selenium.webdriver.common.by import Byimport [email protected] browser():driver = webdriver.Chrome() # 需提前下載ChromeDriveryield driverdriver.quit()def test_search_google(browser):browser.get("https://www.google.com")search_box = browser.find_element(By.NAME, "q")search_box.send_keys("Python自動(dòng)化測(cè)試")search_box.submit()assert "Python自動(dòng)化測(cè)試" in browser.title
運(yùn)行方式:安裝 selenium 和瀏覽器驅(qū)動(dòng)后執(zhí)行 pytest test_ui.py -v。

二、自動(dòng)化測(cè)試進(jìn)階技巧
1. 參數(shù)化測(cè)試
作用:用同一測(cè)試邏輯測(cè)試多組數(shù)據(jù)。
示例:
pythonimport [email protected]("a, b, expected", [(1, 2, 3),(0, 0, 0),(-1, 1, 0),])def test_add_parametrized(a, b, expected):assert a + b == expected
2. 測(cè)試夾具
作用:共享測(cè)試前的初始化代碼。
示例:
pythonimport [email protected] setup_db():# 模擬連接數(shù)據(jù)庫(kù)print("連接數(shù)據(jù)庫(kù)...")yield # 測(cè)試執(zhí)行點(diǎn)print("關(guān)閉數(shù)據(jù)庫(kù)連接...")def test_db_query(setup_db):assert True # 實(shí)際測(cè)試數(shù)據(jù)庫(kù)查詢
3. 生成測(cè)試報(bào)告(pytest-html)
安裝:pip install pytest-html
運(yùn)行:
bashpytest test_module.py --html=report.html
結(jié)果:生成 HTML 格式的測(cè)試報(bào)告,包含通過(guò)/失敗用例詳情。
4. 持續(xù)集成(CI)集成
工具:GitHub Actions、Jenkins。
示例(GitHub Actions 配置):
yamlname: Python CIon: [push]jobs:test:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v2- name: Set up Pythonuses: actions/setup-python@v2with:python-version: '3.9'- name: Install dependenciesrun: pip install pytest selenium- name: Run testsrun: pytest test_ui.py -v
三、自動(dòng)化測(cè)試最佳實(shí)踐
測(cè)試分層:
單元測(cè)試(快速反饋)→ 接口測(cè)試(核心邏輯)→ UI 測(cè)試(全流程)。
測(cè)試數(shù)據(jù)管理:
使用外部文件或數(shù)據(jù)庫(kù)存儲(chǔ)測(cè)試數(shù)據(jù),避免硬編碼。
日志與截圖:
UI 測(cè)試失敗時(shí)自動(dòng)截圖,日志記錄關(guān)鍵步驟。
并行測(cè)試:
使用 pytest-xdist 加速測(cè)試執(zhí)行:
bashpytest -n 4 # 啟用4個(gè)進(jìn)程并行測(cè)試
四、常見(jiàn)問(wèn)題解決
Selenium 報(bào)錯(cuò) WebDriverException:
檢查瀏覽器驅(qū)動(dòng)版本是否與瀏覽器匹配。
接口測(cè)試返回 404:
確認(rèn) API 地址是否正確,或使用 requests.get跳過(guò) SSL 驗(yàn)證。
測(cè)試速度慢:
減少 UI 測(cè)試數(shù)量,優(yōu)先用單元/接口測(cè)試覆蓋核心邏輯。
通過(guò)以上方法,你可以快速搭建 Python 自動(dòng)化測(cè)試體系,覆蓋從簡(jiǎn)單函數(shù)到復(fù)雜 Web 應(yīng)用的測(cè)試需求。根據(jù)項(xiàng)目規(guī)模選擇合適的工具組合,并逐步完善測(cè)試覆蓋率。