用python写一个基于unitest的接口自动化测试框架
时间: 2024-05-01 20:16:34 浏览: 105
python unittest自动化接口测试框架
以下是一个基于unittest的接口自动化测试框架:
```python
import unittest
import requests
class TestAPI(unittest.TestCase):
def setUp(self):
self.base_url = "https://api.example.com"
self.headers = {'Content-Type': 'application/json'}
def test_get_user(self):
url = self.base_url + "/users/1"
response = requests.get(url, headers=self.headers)
self.assertEqual(response.status_code, 200)
self.assertIn("John", response.json()['name'])
def test_create_user(self):
url = self.base_url + "/users"
data = {"name": "Bob", "email": "bob@example.com"}
response = requests.post(url, headers=self.headers, json=data)
self.assertEqual(response.status_code, 201)
self.assertEqual(response.json()['name'], "Bob")
def test_update_user(self):
url = self.base_url + "/users/1"
data = {"name": "John Doe"}
response = requests.put(url, headers=self.headers, json=data)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()['name'], "John Doe")
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
```
该框架包含三个测试用例,分别测试获取用户信息、创建用户和更新用户信息的接口。setUp()方法在每个测试用例执行前都会运行,用于初始化测试环境。tearDown()方法在每个测试用例执行后都会运行,用于清理测试环境。运行测试用例时,可以使用unittest.main()方法来执行测试。
阅读全文