python接口自动化框架源码
时间: 2023-10-10 10:15:01 浏览: 192
python接口自动化框架源码
5星 · 资源好评率100%
以下是一个简单的Python接口自动化测试框架的示例代码:
```python
import requests
import json
class APITestCase:
def __init__(self, url, method, headers=None, params=None, data=None, json=None):
self.url = url
self.method = method
self.headers = headers
self.params = params
self.data = data
self.json = json
def execute(self):
response = requests.request(
method=self.method,
url=self.url,
headers=self.headers,
params=self.params,
data=self.data,
json=self.json
)
return response
class APITestRunner:
def __init__(self):
self.test_cases = []
def add_test_case(self, test_case):
self.test_cases.append(test_case)
def run(self):
results = []
for test_case in self.test_cases:
response = test_case.execute()
result = {
"url": test_case.url,
"method": test_case.method,
"status_code": response.status_code,
"response_time": response.elapsed.total_seconds(),
"response_content": None
}
try:
result["response_content"] = json.loads(response.content)
except:
pass
results.append(result)
return results
```
使用此框架,您可以创建一个或多个测试用例,并将它们添加到测试运行程序中。然后,使用`run()`方法执行测试,并返回每个测试用例的结果。
以下是一个使用此框架的示例测试脚本:
```python
# 创建测试用例
test_case1 = APITestCase(
url="https://jsonplaceholder.typicode.com/posts",
method="GET"
)
test_case2 = APITestCase(
url="https://jsonplaceholder.typicode.com/posts",
method="POST",
json={
"title": "foo",
"body": "bar",
"userId": 1
}
)
# 创建测试运行程序
test_runner = APITestRunner()
# 将测试用例添加到测试运行程序中
test_runner.add_test_case(test_case1)
test_runner.add_test_case(test_case2)
# 运行测试
results = test_runner.run()
# 打印测试结果
for result in results:
print("URL:", result["url"])
print("Method:", result["method"])
print("Status Code:", result["status_code"])
print("Response Time:", result["response_time"])
print("Response Content:", result["response_content"])
print()
```
阅读全文