?在Python中,我們可以使用requests庫(kù)來實(shí)現(xiàn)接口自動(dòng)化測(cè)試,并使用unittest或pytest等測(cè)試框架來組織和運(yùn)行測(cè)試套件。以下是一個(gè)基本的接口自動(dòng)化測(cè)試套件封裝示例:
首先,我們需要安裝所需的庫(kù):
pip install requests pytest
創(chuàng)建一個(gè)項(xiàng)目目錄結(jié)構(gòu),如下所示:
project/
│
├── common/ # 公共方法模塊
│ └── utils.py # 存放請(qǐng)求、斷言等公共函數(shù)
│
├── conf/ # 配置模塊
│ └── config.py # 存放測(cè)試環(huán)境、API基礎(chǔ)URL等配置信息
│
├── data/ # 測(cè)試用例參數(shù)模塊
│ └── test_data.json # 存放測(cè)試用例的輸入數(shù)據(jù)
│
├── log/ # 日志模塊
│ └── log.txt # 存放測(cè)試過程中的日志信息
│
├── report/ # 測(cè)試報(bào)告模塊
│ └── report.html # 自動(dòng)生成的測(cè)試報(bào)告
│
├── test_case/ # 測(cè)試用例模塊
│ ├── test_login.py # 登錄接口測(cè)試用例
│ ├── test_signup.py# 注冊(cè)接口測(cè)試用例
│ └── ... # 其他接口測(cè)試用例
│
└── testsuite.py # 測(cè)試套件文件,用于組織和運(yùn)行測(cè)試用例
同時(shí),在這我也準(zhǔn)備了一份軟件測(cè)試視頻教程(含接口、自動(dòng)化、性能等),需要的可以直接在下方觀看就行,希望對(duì)你有所幫助!【公眾號(hào):互聯(lián)網(wǎng)雜貨鋪】免費(fèi)領(lǐng)取軟件測(cè)試資料!
2024年P(guān)ython自動(dòng)化測(cè)試全套保姆級(jí)教程,70個(gè)項(xiàng)目實(shí)戰(zhàn),3天練完,永久白嫖...
編寫各個(gè)模塊的代碼
common/utils.py:封裝請(qǐng)求和斷言等公共函數(shù)。
import requests
import json
def send_request(method, url, headers=None, params=None, data=None):
response = requests.request(method, url, headers=headers, params=params, data=data)
response.raise_for_status() # 如果響應(yīng)狀態(tài)不是200,拋出異常
return response.json()
def assert_response(response_data, expected_key, expected_value):
assert expected_key in response_data, f"Expected key '{expected_key}' not found in response."
assert response_data[expected_key] == expected_value, f"Expected value for '{expected_key}' is '{expected_value}', but got '{response_data[expected_key]}'"
conf/config.py:配置測(cè)試環(huán)境和基礎(chǔ)URL。
TEST_ENVIRONMENT = "development"
BASE_URL = "http://localhost:8000/api/"
test_case/test_login.py:編寫登錄接口測(cè)試用例。
import json
from project.common.utils import send_request, assert_response
from project.conf.config import BASE_URL
class TestLogin:
def test_successful_login(self):
url = f"{BASE_URL}login"
data = {
"username": "test_user",
"password": "test_password"
}
response_data = send_request("POST", url, data=json.dumps(data))
assert_response(response_data, "status", "success")
assert_response(response_data, "message", "Logged in successfully.")
def test_invalid_credentials(self):
url = f"{BASE_URL}login"
data = {
"username": "invalid_user",
"password": "invalid_password"
}
response_data = send_request("POST", url, data=json.dumps(data))
assert_response(response_data, "status", "error")
assert_response(response_data, "message", "Invalid credentials.")
testsuite.py:組織和運(yùn)行測(cè)試用例。
import pytest
from project.test_case import test_login, test_signup # 導(dǎo)入其他測(cè)試用例模塊
@pytest.mark.parametrize("test_case_module", [test_login, test_signup])
def test_suite(test_case_module):
suite = unittest.TestLoader().loadTestsFromModule(test_case_module)
runner = unittest.TextTestRunner()
results = runner.run(suite)
assert results.wasSuccessful(), "Test suite failed."
??????運(yùn)行測(cè)試套件:
pytest testsuite.py
這個(gè)示例提供了一個(gè)基本的接口自動(dòng)化測(cè)試套件的封裝結(jié)構(gòu)和代碼。你可以根據(jù)實(shí)際項(xiàng)目的需要對(duì)其進(jìn)行擴(kuò)展和修改
添加更復(fù)雜的斷言、錯(cuò)誤處理、測(cè)試數(shù)據(jù)管理、報(bào)告生成等功能
更復(fù)雜的斷言
在common/utils.py中,你可以添加更多的斷言函數(shù)來處理更復(fù)雜的情況。例如,檢查響應(yīng)中的某個(gè)字段是否在預(yù)期的值列表中:
def assert_in_response(response_data, key, expected_values):
assert key in response_data, f"Expected key '{key}' not found in response."
assert response_data[key] in expected_values, f"Expected value for '{key}' to be one of {expected_values}, but got '{response_data[key]}'"
錯(cuò)誤處理
在common/utils.py的send_request函數(shù)中,你可以添加更詳細(xì)的錯(cuò)誤處理邏輯,例如捕獲和記錄不同類型的HTTP錯(cuò)誤:
def send_request(method, url, headers=None, params=None, data=None):
try:
response = requests.request(method, url, headers=headers, params=params, data=data)
response.raise_for_status() # 如果響應(yīng)狀態(tài)不是200,拋出異常
return response.json()
except requests.exceptions.HTTPError as http_error:
logging.error(f"HTTP error occurred: {http_error}")
raise http_error
except Exception as e:
logging.error(f"Unexpected error occurred: {e}")
raise e
測(cè)試數(shù)據(jù)管理
你可以創(chuàng)建一個(gè)單獨(dú)的模塊或文件來管理測(cè)試數(shù)據(jù)。例如,在data/test_data.py中定義一個(gè)字典,包含所有測(cè)試用例所需的輸入數(shù)據(jù):
LOGIN_TEST_DATA = {
"valid_credentials": {
"username": "test_user",
"password": "test_password"
},
"invalid_credentials": {
"username": "invalid_user",
"password": "invalid_password"
}
}
然后在測(cè)試用例中使用這些數(shù)據(jù):
from project.data.test_data import LOGIN_TEST_DATA
class TestLogin:
def test_successful_login(self):
url = f"{BASE_URL}login"
data = LOGIN_TEST_DATA["valid_credentials"]
response_data = send_request("POST", url, data=json.dumps(data))
assert_response(response_data, "status", "success")
assert_response(response_data, "message", "Logged in successfully.")
def test_invalid_credentials(self):
url = f"{BASE_URL}login"
data = LOGIN_TEST_DATA["invalid_credentials"]
response_data = send_request("POST", url, data=json.dumps(data))
assert_response(response_data, "status", "error")
assert_response(response_data, "message", "Invalid credentials.")
報(bào)告生成
你可以使用pytest-html插件來生成HTML格式的測(cè)試報(bào)告。首先安裝插件:
pip install pytest-html
然后在testsuite.py中配置報(bào)告生成:文章來源:http://www.zghlxwxcb.cn/news/detail-774910.html
import pytest
from pytest_html_reporter import attach_extra_css, add_context
from project.test_case import test_login, test_signup # 導(dǎo)入其他測(cè)試用例模塊
@pytest.mark.parametrize("test_case_module", [test_login, test_signup])
def test_suite(test_case_module):
suite = unittest.TestLoader().loadTestsFromModule(test_case_module)
runner = unittest.TextTestRunner()
results = runner.run(suite)
assert results.wasSuccessful(), "Test suite failed."
if __name__ == "__main__":
pytest.main(["--html=report/report.html", "--self-contained-html"])
attach_extra_css("custom.css") # 添加自定義CSS樣式
add_context({"project_name": "My API Test Project"}) # 添加上下文信息
運(yùn)行測(cè)試套件時(shí),將會(huì)生成一個(gè)名為report.html的測(cè)試報(bào)告。文章來源地址http://www.zghlxwxcb.cn/news/detail-774910.html
到了這里,關(guān)于接口自動(dòng)化測(cè)試套件封裝示例的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!