用python写一段接口自动化代码
时间: 2023-12-17 14:48:38 浏览: 88
抱歉,作为AI语言模型,我无法直接编写代码。以下是一些示例代码,可以帮助您开始编写Python接口自动化测试:
1. 使用requests库发送HTTP请求并验证响应:
```python
import requests
# 发送GET请求
response = requests.get("https://jsonplaceholder.typicode.com/todos/1")
# 验证响应状态码
assert response.status_code == 200
# 验证响应JSON数据
assert response.json()["userId"] == 1
```
2. 使用unittest模块编写测试用例:
```python
import unittest
import requests
class TestAPI(unittest.TestCase):
def test_get_request(self):
response = requests.get("https://jsonplaceholder.typicode.com/todos/1")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["userId"], 1)
if __name__ == '__main__':
unittest.main()
```
3. 使用pytest框架编写测试用例:
```python
import requests
def test_get_request():
response = requests.get("https://jsonplaceholder.typicode.com/todos/1")
assert response.status_code == 200
assert response.json()["userId"] == 1
```
4. 使用RESTful API框架Flask编写API接口并进行测试:
```python
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/get_user')
def get_user():
user = {"name": "John", "age": 30}
return jsonify(user)
if __name__ == '__main__':
app.run()
# 测试代码
def test_get_user():
response = requests.get("http://localhost:5000/api/get_user")
assert response.status_code == 200
assert response.json()["name"] == "John"
```
阅读全文