用unittest写一组登录网页的用例,需要用到三个测试用例
时间: 2024-03-25 11:35:53 浏览: 28
好的,以下是使用 unittest 编写的三个登录网页的测试用例示例:
```python
import unittest
from selenium import webdriver
class TestLogin(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
self.driver.implicitly_wait(10)
def tearDown(self):
self.driver.quit()
def test_login_success(self):
"""测试登录成功"""
self.driver.get('http://localhost:8080/login')
self.driver.find_element_by_name('username').send_keys('admin')
self.driver.find_element_by_name('password').send_keys('123456')
self.driver.find_element_by_css_selector('button[type="submit"]').click()
self.assertEqual(self.driver.title, '欢迎页面')
def test_login_failed(self):
"""测试登录失败"""
self.driver.get('http://localhost:8080/login')
self.driver.find_element_by_name('username').send_keys('admin')
self.driver.find_element_by_name('password').send_keys('wrong_password')
self.driver.find_element_by_css_selector('button[type="submit"]').click()
error_msg = self.driver.find_element_by_css_selector('.error-message').text
self.assertIn('用户名或密码错误', error_msg)
def test_empty_username_password(self):
"""测试用户名和密码为空"""
self.driver.get('http://localhost:8080/login')
self.driver.find_element_by_css_selector('button[type="submit"]').click()
error_msg = self.driver.find_element_by_css_selector('.error-message').text
self.assertIn('用户名不能为空', error_msg)
self.assertIn('密码不能为空', error_msg)
if __name__ == '__main__':
unittest.main()
```
这个测试用例会使用 Chrome 浏览器打开一个登录页面,并且执行三个测试用例:
1. `test_login_success`: 测试输入正确的用户名和密码,是否能够成功登录,并且跳转到欢迎页面。
2. `test_login_failed`: 测试输入错误的密码,是否会提示用户名或密码错误。
3. `test_empty_username_password`: 测试提交空的用户名和密码,是否会提示用户名和密码不能为空。
每个测试用例都会在执行前打开浏览器窗口,并在执行后关闭浏览器窗口。执行测试用例时,可以使用 `python test_login.py` 命令来运行测试用例。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)