python封装接口自动化测试套件

TEST_ENVIRONMENT = "development"
BASE_URL = "http://localhost:8000/api/"
test_case/test_login.py:编写登录接口测试用例。
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:组织和运行测试用例。

import pytest
from 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."

运行测试套件:

pytest testsuite.py

  • 1

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

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

更复杂的断言

在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]}'"

错误处理

在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

测试数据管理

你可以创建一个单独的模块或文件来管理测试数据。例如,在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_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.")

报告生成

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

pip install pytest-html

  • 1

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

import pytest
from pytest_html_reporter import attach_extra_css, add_context
from 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"})  # 添加上下文信息

运行测试套件时,将会生成一个名为report.html的测试报告。

以上就是本次分享,有学习接口自动化测试的伙伴有什么不清楚的,可以留言,看到了会及时回复

总结:

感谢每一个认真阅读我文章的人!!!

作为一位过来人也是希望大家少走一些弯路,如果你不想再体验一次学习时找不到资料,没人解答问题,坚持几天便放弃的感受的话,在这里我给大家分享一些自动化测试的学习资源,希望能给你前进的路上带来帮助。

软件测试面试文档

我们学习必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有字节大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

如果你也是看准了Python,想自学Python,在这里为大家准备了丰厚的免费学习大礼包,带大家一起学习,给大家剖析Python兼职、就业行情前景的这些事儿。

一、Python所有方向的学习路线

Python所有方向路线就是把Python常用的技术点做整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

二、学习软件

工欲善其必先利其器。学习Python常用的开发软件都在这里了,给大家节省了很多时间。

三、全套PDF电子书

书籍的好处就在于权威和体系健全,刚开始学习的时候你可以只看视频或者听某个人讲课,但等你学完之后,你觉得你掌握了,这时候建议还是得去看一下书籍,看权威技术书籍也是每个程序员必经之路。

四、入门学习视频

我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了。

四、实战案例

光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。

五、面试资料

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

成为一个Python程序员专家或许需要花费数年时间,但是打下坚实的基础只要几周就可以,如果你按照我提供的学习路线以及资料有意识地去实践,你就有很大可能成功!
最后祝你好运!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值