-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_api.py
More file actions
85 lines (66 loc) · 2.49 KB
/
test_api.py
File metadata and controls
85 lines (66 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import requests
import os
import random
"""该路径为后端的地址,按照你的需要去更改"""
BASE_URL = "http://127.0.0.1:5000/api/v1"
def test_root():
"""测试根路径"""
response = requests.get("http://127.0.0.1:5000")
print("根路径测试:", response.status_code, response.json())
def safe_json(resp):
try:
return resp.json()
except Exception:
return resp.text
def property_login():
"""使用物业/管理员账号登录以获取 token,凭证从环境变量读取"""
phone = os.getenv('PROPERTY_PHONE')
password = os.getenv('PROPERTY_PASSWORD')
if not phone or not password:
print('跳过物业登录:请通过环境变量 PROPERTY_PHONE / PROPERTY_PASSWORD 提供物业账号凭证')
return None
data = {"phone": phone, "password": password}
resp = requests.post(f"{BASE_URL}/auth/login", json=data)
print('物业登录:', resp.status_code, safe_json(resp))
if resp.status_code == 200:
return resp.json().get('data', {}).get('token')
return None
def create_owner(token):
"""通过物业端接口创建业主账号并返回账号信息"""
# 随机生成手机号避免冲突(中国手机号规则简单生成示例)
phone = '139' + ''.join([str(random.randint(0, 9)) for _ in range(8)])
password = 'Password123!'
payload = {
'phone': phone,
'password': password,
'real_name': '自动化测试用户',
'id_card': '11010119900101' + str(random.randint(1000, 9999)),
'building': '1',
'unit': '1',
'room': '101'
}
headers = {'Authorization': f'Bearer {token}'} if token else {}
resp = requests.post(f"{BASE_URL}/owners", json=payload, headers=headers)
print('创建业主:', resp.status_code, safe_json(resp))
if resp.status_code == 200:
return {'phone': phone, 'password': password}
return None
def test_user_login(phone, password):
data = {"phone": phone, "password": password}
resp = requests.post(f"{BASE_URL}/auth/login", json=data)
print('新业主登录测试:', resp.status_code, safe_json(resp))
return resp
if __name__ == '__main__':
print('开始API测试...')
print('=' * 50)
test_root()
print('-' * 50)
token = property_login()
print('-' * 50)
if token:
creds = create_owner(token)
print('-' * 50)
if creds:
test_user_login(creds['phone'], creds['password'])
print('=' * 50)
print('API测试完成')