test_login.py
3.78 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
"""
登录功能自动化测试
Python 3.7.8 兼容
"""
from base_test import BaseBrowserTest
class LoginTest(BaseBrowserTest):
"""登录测试类"""
def test_successful_login(self):
"""测试成功登录"""
# 测试正常登录
success = self.login('admin', 'password')
assert success, "登录应该成功"
# 截图验证登录状态
self.take_screenshot('login_success')
# 验证登录后的页面元素
# 这里可以根据实际登录后的页面结构添加验证
print("登录成功测试通过")
def test_invalid_username(self):
"""测试无效用户名"""
# 测试错误用户名
success = self.login('invalid_user', 'password')
assert not success, "使用无效用户名登录应该失败"
# 截图验证错误状态
self.take_screenshot('login_invalid_username')
print("无效用户名测试通过")
def test_invalid_password(self):
"""测试无效密码"""
# 测试错误密码
success = self.login('admin', 'wrong_password')
assert not success, "使用无效密码登录应该失败"
# 截图验证错误状态
self.take_screenshot('login_invalid_password')
print("无效密码测试通过")
def test_empty_credentials(self):
"""测试空凭据"""
# 导航到登录页面
self.navigate_to(self.base_url)
# 等待登录表单
self.wait_for_element('input[placeholder="请输入用户名"]')
# 不填写任何信息,直接点击登录
self.click_element('button:has-text("登录")')
# 截图验证错误提示
self.take_screenshot('login_empty_credentials')
print("空凭据测试通过")
def test_remember_me(self):
"""测试记住我功能"""
# 导航到登录页面
self.navigate_to(self.base_url)
# 等待登录表单
self.wait_for_element('input[placeholder="请输入用户名"]')
# 填写用户名和密码
self.fill_input('input[placeholder="请输入用户名"]', 'admin')
self.fill_input('input[placeholder="请输入密码"]', 'password')
# 勾选记住我
self.click_element('input[type="checkbox"]')
# 点击登录
self.click_element('button:has-text("登录")')
# 截图验证
self.take_screenshot('login_remember_me')
print("记住我功能测试通过")
def run_login_tests():
"""运行所有登录测试"""
test = LoginTest(headless=False, slow_mo=500) # 非无头模式,慢速执行便于观察
tests = [
('成功登录测试', test.test_successful_login),
('无效用户名测试', test.test_invalid_username),
('无效密码测试', test.test_invalid_password),
('空凭据测试', test.test_empty_credentials),
('记住我功能测试', test.test_remember_me),
]
results = []
for test_name, test_func in tests:
result = test.run_test(test_name, test_func)
results.append(result)
# 打印测试总结
print(f"\n{'='*60}")
print("登录测试总结")
print(f"{'='*60}")
passed = sum(1 for r in results if r['success'])
total = len(results)
for result in results:
status = "✅ 通过" if result['success'] else "❌ 失败"
print(f"{result['test_name']}: {status} ({result['duration']:.2f}s)")
if result['error']:
print(f" 错误: {result['error']}")
print(f"\n总计: {passed}/{total} 个测试通过")
return results
if __name__ == '__main__':
run_login_tests()