用gpt定制一个pytest接口测试框(附源码)

目的:

描述我的需求和目标让gpt给我写一个测试接口框架 并且让他自己完善。

我说:帮我写一个基于python语言的 pytest的接口测试框架 支持post get put delete请求 添加详细的断言,处理身份验证和授权,处理HTTP错误 加上allure2报告和有请求失败发邮件功能

gpt回答:

好的,下面是一个更完整的代码示例,这个示例结合了你的所有需求:


import requests
import pytest
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import allure

class APIClient(object):
    def __init__(self, base_url, token):
        self.base_url = base_url
        self.headers = {'Authorization': 'Bearer ' + token}

    def get(self, path, params=None):
        return requests.get(self.base_url + path, params=params, headers=self.headers)

    def post(self, path, data=None, json=None):
        return requests.post(self.base_url + path, data=data, json=json, headers=self.headers)

    def put(self, path, data=None):
        return requests.put(self.base_url + path, data=data, headers=self.headers)

    def delete(self, path):
        return requests.delete(self.base_url + path, headers=self.headers)

@pytest.fixture(scope="module")
def api_client():
    token = 'your_token' # 替换成你的Token
    return APIClient("http://your-base-url.com", token) # 你的API的基础URL

def send_email(subject, content, to):
    # Replace the following lines with your email settings
    smtp_server = 'your_smtp_server'
    username = 'your_username'
    password = 'your_password'
    from_email = 'your_email'

    msg = MIMEText(content, 'plain', 'utf-8')
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = from_email
    msg['To'] = to

    try:
        server = smtplib.SMTP(smtp_server)
        server.login(username, password)
        server.sendmail(from_email, [to], msg.as_string())
        server.quit()
    except smtplib.SMTPException as e:
        print(f"Error: unable to send email: {e}")

@pytest.allure.feature('HTTP methods')
def test_get(api_client):
    try:
        response = api_client.get("/path-for-get") # 这里需要替换成你的GET接口的路径
        assert response.status_code == 200
        assert 'expected_field' in response.json() # 检查预期的字段是否存在
        assert response.json()['expected_field'] == 'expected_value' # 检查预期的字段是否等于预期的值
    except Exception as e:
        send_email('Test failed', str(e), '[email protected]')
        raise

@pytest.allure.feature('HTTP methods')
def test_post(api_client):
    data = {} # 这里添加POST请求需要的数据
    try:
        response = api_client.post("/path-for-post", data=data) # 这里需要替换成你的POST接口的路径
        assert response.status_code == 200
        assert 'expected_field' in response.json() # 检查预期的字段是否存在
        assert response.json()['expected_field'] == 'expected_value' # 检查预期的字段是否等于预期的值
    except Exception as e:
        send_email('Test failed', str(e), '[email protected]')
        raise

@pytest.allure.feature('HTTP methods')
def test_put(api_client):
    data = {} # 这里添加PUT请求需要的数据
    try:
        response = api_client.put("/path-for-put", data=data) # 这里需要替换成你的PUT接口的路径
        assert response.status_code== 200
    assert 'expected_field' in response.json() # 检查预期的字段是否存在
    assert response.json()['expected_field'] == 'expected_value' # 检查预期的字段是否等于预期的值
    except Exception as e:
    send_email('Test failed', str(e), '[email protected]')
    raise
    
    @pytest.allure.feature('HTTP methods')
    def test_delete(api_client):
    try:
    response = api_client.delete("/path-for-delete") # 这里需要替换成你的DELETE接口的路径
    assert response.status_code == 200
    assert 'expected_field' in response.json() # 检查预期的字段是否存在
    assert response.json()['expected_field'] == 'expected_value' # 检查预期的字段是否等于预期的值
    except Exception as e:
    send_email('Test failed', str(e), '[email protected]')
    raise

请注意你需要替换一些地方的内容,包括`your_token`, `http://your-base-url.com`, `your_smtp_server`, `your_username`, `your_password`, `[email protected]`等等。这些应该替换为你自己的实际值。

此外,你也需要根据实际的接口情况,修改`"/path-for-get"`, `"/path-for-post"`, `"/path-for-put"`, `"/path-for-delete"`以及你的断言内容。

在你的测试过程中,如果测试失败,将会发送一封邮件到指定的邮箱。生成Allure报告的命令如下:

```bash
pytest --alluredir=/tmp/my_allure_results

然后使用allure命令生成报告:
allure serve /tmp/my_allure_results

我说:帮我总结下这个框架和如何优化

gpt回答:这个测试框架主要包括以下几个部分:

1、APIClient:一个用于发送HTTP请求的客户端,支持GET、POST、PUT和DELETE方法。它使用了requests库来发送HTTP请求,同时使用Bearer Token进行身份验证和授权。

2、Pytest:使用Pytest作为测试框架。每个HTTP方法(GET、POST、PUT、DELETE)都有对应的测试函数。测试函数中使用了断言来验证HTTP响应的状态码和内容。

3、Allure:使用Allure生成测试报告。通过在测试函数上添加allure.feature装饰器,我们可以在Allure报告中看到每个测试的详细信息。

4、邮件通知:如果测试失败,会发送一封包含错误详情的邮件。

扫描二维码关注公众号,回复: 15230278 查看本文章

这个框架可以在多个方面进行优化:

1、参数化:可以使用Pytest的参数化功能来运行多个测试案例。例如,你可以创建一个列表或字典来存储多个不同的请求数据和预期结果,然后在测试函数中使用pytest.mark.parametrize装饰器来为每个数据和结果创建一个测试。

2、使用环境变量:出于安全考虑,你可以将一些敏感数据(例如Token和电子邮件设置)存储在环境变量中,而不是直接在代码中写出这些数据。Python的os.environ可以用来访问环境变量。

3、异常处理:可以增加更多的异常处理代码,以便更好地处理可能发生的错误。例如,你可以检查HTTP响应的状态码是否在200-299的范围内,如果不在这个范围内,就认为请求失败。

4、使用配置文件:可以使用配置文件(例如JSON或YAML文件)来存储测试设置。这样,如果你想修改测试设置,就不需要修改代码,只需要修改配置文件就可以了。

5、日志:可以添加日志代码,将测试过程中的重要信息记录下来,这样在出现问题时可以更方便地进行调试。Python的logging库可以用来添加日志。

6、并行测试:如果你有很多测试需要运行,可以使用Pytest的-xdist插件来并行运行测试,从而减少测试时间。但请注意,如果你的测试会影响到共享的资源或状态(例如数据库),那么并行运行可能会导致问题。

我说:能不能基于这些优化 在帮我扩展下这个测试框架

gpt回答:当然可以,我将在原有的测试框架上添加以下功能:

1、参数化测试案例

2、使用环境变量

3、异常处理增强

4、使用配置文件

代码如下:

首先,我们需要一个配置文件,比如一个名为config.json的JSON文件,内容如下:


{
    "base_url": "http://your-base-url.com",
    "smtp_server": "your_smtp_server",
    "smtp_username": "your_username",
    "smtp_password": "your_password",
    "from_email": "your_email",
    "to_email": "[email protected]"
}

测试代码如下:


import requests
import pytest
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import allure
import os
import json

class APIClient(object):
    def __init__(self, base_url):
        self.base_url = base_url
        self.headers = {'Authorization': 'Bearer ' + os.getenv('TOKEN')}

    def get(self, path, params=None):
        try:
            response = requests.get(self.base_url + path, params=params, headers=self.headers)
            response.raise_for_status()
            return response
        except requests.exceptions.RequestException as e:
            pytest.fail(f"GET request failed: {e}")

    # Similar changes can be made for the post, put and delete methods

@pytest.fixture(scope="module")
def api_client():
    with open('config.json') as f:
        config = json.load(f)
    return APIClient(config["base_url"])

def send_email(subject, content, to, config):
    msg = MIMEText(content, 'plain', 'utf-8')
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = config["from_email"]
    msg['To'] = to

    try:
        server = smtplib.SMTP(config["smtp_server"])
        server.login(config["smtp_username"], config["smtp_password"])
        server.sendmail(config["from_email"], [to], msg.as_string())
        server.quit()
    except smtplib.SMTPException as e:
        print(f"Error: unable to send email: {e}")

@pytest.fixture(scope="module")
def test_data():
    # Replace this with your actual test data
    return [
        {
            "path": "/path-for-get",
            "expected_field": "field",
            "expected_value": "value"
        },
        # Add more dictionaries for more test cases
    ]

@pytest.mark.parametrize('data', test_data, indirect=True)
@pytest.allure.feature('HTTP methods')
def test_get(api_client, data):
    try:
        response = api_client.get(data["path"])
        assert data["expected_field"] in response.json()
        assert response.json()[data["expected_field"]] == data["expected_value"]
    except Exception as e:
        with open('config.json') as f:
            config = json.load(f)
        send_email('Test failed', str(e), config["to_email"], config)
        raise

以上代码中,我增加了一个config.json的配置文件,其中存储了一些基础配置信息,比如SMTP服务器的信息,API的基础URL等。并且,我使用了os.getenv(‘TOKEN’)来获取环境变量中的Token。

对于异常处理,我添加了response.raise_for_status()来抛出HTTP错误。如果HTTP请求的状态码不在200-299之间,raise_for_status会抛出一个异常。

我还添加了一个test_data fixture用于参数化测试。在test_data中,你可以添加你的实际测试数据。在这个示例中,每个测试数据都是一个包含"path"、"expected_field"和"expected_value"的字典。

在test_get测试函数中,我使用了pytest.mark.parametrize装饰器来参数化测试。这样,对于test_data中的每一个测试数据,都会运行一次test_get测试。并且,如果测试失败,会发送一封包含错误详情的邮件。

对于post,put和delete的方法,也可以进行类似的修改。

这个新的测试框架增加了配置文件的使用,环境变量的使用,异常处理的增强,以及测试参数化,使得测试更加灵活和强大。如果你需要对其他特定的部分进行扩展或者需要帮助,请告诉我,我会很高兴为你提供更多的帮助。

结果:后面还可以用gpt不断这个框架,有需要可以找我

最后为了方便软件测试人员,我研究了一个专为软件测试人使用的GPT人工智能:

http://ai.hctestedu.com/#/chat/1002

免费分享给大家使用!!

需要激活码的朋友可以关注我下方的公众号,免费获取!

猜你喜欢

转载自blog.csdn.net/weixin_56331124/article/details/131021039
今日推荐