使用Python实现Postman功能,你可以使用`requests`库来发送HTTP请求。以下是一个简单的示例,展示了如何使用Python发送GET和POST请求,并包含了一些基本的测试和断言。
```python
import os
import requests
import json
from unittest import TestCase
class PostMan:
__instance = None
def __new__(cls, *args, kwargs):
if not cls.__instance:
cls.__instance = object.__new__(cls)
return cls.__instance
def postMan(self, data):
return json.dumps(data, indent=4, ensure_ascii=False)
class GetInfo:
def __init__(self):
self.url = 'https://api.example.com/data' 替换为你的URL
def get_test_info(self, params):
headers = {'content-type': 'application/json'}
payload = json.dumps(params)
res = requests.post(self.url, data=payload, headers=headers).json()
post = PostMan()
print(post.postMan(res))
class OperationTest(TestCase):
def test_get_info(self):
get_info = GetInfo()
params = {'username': 'zxj', 'password': 'zxj01'}
get_info.get_test_info(params)
if __name__ == '__main__':
unittest.main()
发送GET请求
```python
发送GET请求
response = requests.get('https://api.example.com/data', params={'username': 'zxj', 'password': 'zxj01'})
print(response.json())
发送POST请求
```python
发送POST请求
data = {'username': 'zxj', 'password': 'zxj01'}
response = requests.post('https://api.example.com/data', data=data)
print(response.json())
使用断言进行测试
```python
使用断言进行测试
class OperationTest(TestCase):
def test_get_info(self):
get_info = GetInfo()
params = {'username': 'zxj', 'password': 'zxj01'}
response = get_info.get_test_info(params)
self.assertEqual(response['username'], 'zxj')
self.assertEqual(response['password'], 'zxj01')
```python
设置环境变量
os.environ['API_KEY'] = 'your_api_key'
预请求脚本示例
pre_request_script = """
pm.environment.set("API_KEY", pm.variables.get("API_KEY"))
"""
运行测试
```python
运行测试
if __name__ == '__main__':
unittest.main()
请确保你已经安装了`requests`库,可以通过以下命令安装:
```
pip install requests
以上代码示例展示了如何使用Python发送HTTP请求,并包含了一些基本的测试和断言。你可以根据自己的需求修改URL、参数和测试逻辑。