Python封装接口自动化测试套件 !

pip install requests pytest


创建一个项目目录结构,如下所示:



project/│├── common/ # 公共方法模块│ └── utils.py # 存放请求、断言等公共函数│├── conf/ # 配置模块│ └── config.py # 存放测试环境、API基础URL等配置信息│├── data/ # 测试用例参数模块│ └── test_data.json # 存放测试用例的输入数据│├── log/ # 日志模块│ └── log.txt # 存放测试过程中的日志信息│├── report/ # 测试报告模块│ └── report.html # 自动生成的测试报告│├── test_case/ # 测试用例模块│ ├── test_login.py # 登录接口测试用例│ ├── test_signup.py# 注册接口测试用例│ └── … # 其他接口测试用例│└── testsuite.py # 测试套件文件,用于组织和运行测试用例


编写各个模块的代码




![图片](https://img-blog.csdnimg.cn/img_convert/033a8d49dbd006e2819b03d47beb2439.png)


**common/utils.py:封装请求和断言等公共函数。**



import requestsimport jsondef 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() # 如果响应状态不是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]}’"




![图片](https://img-blog.csdnimg.cn/img_convert/a901549f6bca494133274086525f9eaf.png)


**conf/config.py:配置测试环境和基础URL。**



TEST_ENVIRONMENT = “development"BASE_URL = “http://localhost:8000/api/“test_case/test_login.py:编写登录接口测试用例。import jsonfrom project.common.utils import send_request, assert_responsefrom project.conf.config import BASE_URLclass 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.”)




![图片](https://img-blog.csdnimg.cn/img_convert/fa70b94ae4900489a1393aaac584a111.png)




现在我也找了很多测试的朋友,做了一个分享技术的交流群,共享了很多我们收集的技术文档和视频教程。
如果你不想再体验自学时找不到资源,没人解答问题,坚持几天便放弃的感受
可以加入我们一起交流。而且还有很多在自动化,性能,安全,测试开发等等方面有一定建树的技术大牛
分享他们的经验,还会分享很多直播讲座和技术沙龙
可以免费学习!划重点!开源的!!!
qq群号:691998057【暗号:csdn999】


![](https://img-blog.csdnimg.cn/direct/b7f6477ff4994dc78df4f0acc21e5ff6.png)


**testsuite.py:组织和运行测试用例。**



import pytestfrom project.test_case import test_login, test_signup # 导入其他测试用例模块@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.”




![图片](https://img-blog.csdnimg.cn/img_convert/26868fd4342370b013e20e464e312d17.png)


**运行测试套件:**



pytest testsuite.py


这个示例提供了一个基本的接口自动化测试套件的封装结构和代码。你可以根据实际项目的需要对其进行扩展和修改


**添加更复杂的断言、错误处理、测试数据管理、报告生成等功能**


更复杂的断言




![图片](https://img-blog.csdnimg.cn/img_convert/d6bc02f74c81fd97d7952273c340e21a.png)



**在common/utils.py中**,你可以添加更多的断言函数来处理更复杂的情况。例如,检查响应中的某个字段是否在预期的值列表中:



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]}’"



**错误处理**




![图片](https://img-blog.csdnimg.cn/img_convert/9511a9dd95becd8e305a4aa1b4291047.png)


**在common/utils.py的send\_request函数中**,你可以添加更详细的错误处理逻辑,例如捕获和记录不同类型的HTTP错误:



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() # 如果响应状态不是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


测试数据管理




![图片](https://img-blog.csdnimg.cn/img_convert/10d024eabda3b027e705188de4667c0a.png)



你可以创建一个单独的模块或文件来管理测试数据。例如,**在data/test\_data.py**中定义一个字典,包含所有测试用例所需的输入数据:​​​​​​​



LOGIN_TEST_DATA = { “valid_credentials”: { “username”: “test_user”, “password”: “test_password” }, “invalid_credentials”: { “username”: “invalid_user”, “password”: “invalid_password” }}


然后在测试用例中使用这些数据:​​​​​​​



from project.data.test_data import LOGIN_TEST_DATAclass 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.”)


**报告生成**




![图片](https://img-blog.csdnimg.cn/img_convert/6010d132fb08d671aa95d1d26518aae5.png)



你可以使用pytest-html插件来生成HTML格式的测试报告。首先安装插件:



pip install pytest-html


然后在**testsuite.py**中配置报告生成:​​​​​​​



import pytestfrom pytest_html_reporter import attach_extra_css, add_contextfrom project.test_case import test_login, test_signup # 导入其他测试用例模块@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”}) # 添加上下文信息



![图片](https://img-blog.csdnimg.cn/img_convert/243da7c5fb7a6e20099c5c9ad609ceab.png)




![图片](https://img-blog.csdnimg.cn/img_convert/c6ce864da8f2512bf62593da64684a48.png)


**运行测试套件时,将会生成一个名为report.html的测试报告。**
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值