Skip to content

测试登录功能

测试最基本的两个要素是测试输入和预期输出结果。对于给定程序,相同的测试输入必然对应相同的输出结果。一个完整的测试必须能够预测输出结果是什么,并将其与实际输出结果进行比对。如果实际输出结果和预期输出结果相同,才能认为测试通过;否则,认为测试失败。

初始版本

python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome()
driver.get("https://www.epubit.com/")
#等待页面关键区域渲染完毕再操作
WebDriverWait(driver, 5).until(lambda p: p.find_element(By.CLASS_NAME, "el-carousel__item"))
driver.find_element(By.XPATH, "//i[text()='登录']").click()
driver.find_element(By.ID, "username").send_keys("yibushequUser1")
driver.find_element(By.ID, "password").send_keys("yibushquPwd1")
driver.find_element(By.ID, "passwordLoginBtn").click()

driver.quit()

优化结果

python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome()
driver.implicitly_wait(5)
driver.get("https://www.epubit.com/")

# 等待页面关键区域渲染完毕再操作
WebDriverWait(driver, 5).until(lambda p: p.find_element(By.CLASS_NAME, "el-carousel_
_item"))
driver.find_element(By.XPATH, "//i[text()='登录']").click()
driver.find_element(By.ID, "username").send_keys("yibushequUser1")
driver.find_element(By.ID, "password").send_keys("yibushequPwd1")
driver.find_element(By.ID, "passwordLoginBtn").click()
# 比较预期结果与实际结果
isJumpToHomePage = driver.current_url == "https://www.epubit.com/"
isShowUserImg = len(driver.find_elements(By.CLASS_NAME,"userLogo")) > 0
isShowLogout = len(driver.find_elements(By.XPATH,"//div[contains(@class,'logout')]/
div[contains(text(),'退出')]")) > 0
if not isJumpToHomePage or not isShowUserImg or not isShowLogout:
    raise Exception("Login failed!")

driver.quit()