写一段python接口测试框架
时间: 2023-06-06 22:09:09 浏览: 122
好的,以下是一段简单的 Python 接口测试框架示例代码:
```
import requests
class APITestCase():
def __init__(self, url, method='GET', headers=None, data=None):
self.url = url
self.method = method
self.headers = headers
self.data = data
self.response = None
def send_request(self):
if self.method.upper() == 'GET':
self.response = requests.get(self.url, headers=self.headers)
elif self.method.upper() == 'POST':
self.response = requests.post(self.url, headers=self.headers, data=self.data)
def assert_status_code(self, expected_status_code):
assert self.response.status_code == expected_status_code, f'Unexpected status code: {self.response.status_code}'
def assert_response_contains(self, expected_text):
assert expected_text in self.response.text, f'Expected "{expected_text}" not found in response text: {self.response.text}'
# 示例用法:
test = APITestCase('https://jsonplaceholder.typicode.com/posts/1')
test.send_request()
test.assert_status_code(200)
test.assert_response_contains('id')
```
这个框架包含一个 `APITestCase` 类,它有一个构造函数来设置接口地址、方法、请求头和请求数据。`send_request()` 方法发送请求并保存响应。`assert_status_code()` 和 `assert_response_contains()` 方法可以测试响应状态码和包含特定文本。您可以用它来测试您的 API 接口。
阅读全文