参考:https://cloud.tencent.com/developer/article/1358791
(该网址中使用的示例出现了问题,所以进行了一定的修正)
login.xls文件内容如下所示:(result中0代表登录失败,1代表登录成功)
验证V客网登录界面为实例,来说明ddt模块在自动化中的实战,验证点分别为如下几点:
验证点一:输入有效的用户名和密码,验证是否登录成功
验证点二:输入有效的用户名和无效的密码,验证是否登录成功
验证点三:输入无效的邮箱和无效的密码,验证是否登录成功
location.py 读取数据的方法,登录以及获取登录是否成功的状态,WekeTest.py 用于登录界面的测试。WekeTest.py调用location.py
location.py的代码如下:
# coding:utf-8
import csv
import xlrd
from time import sleep
def getCsv(file_name):
rows = []
with open(file_name, 'rb') as f:
readers = csv.reader(f, delimiter=',', quotechar='|')
next(readers, None)
for row in readers:
rows.append(row)
return rows
def getExcel(rowValue, colValue, file_name='d://login.xls'):
"""
:paramrowValue:表格的行
:paramcolValue: 表格的列
:paramfile_name: excel文件
:return:
"""
book = xlrd.open_workbook(file_name)
sheet = book.sheet_by_index(0)
return sheet.cell_value(rowValue, colValue)
def getDdtExcel(file_name='d://login.xls'):
rows = []
book = xlrd.open_workbook(file_name)
sheet = book.sheet_by_index(0)
for row in range(1, sheet.nrows):
rows.append(list(sheet.row_values(row, 0, sheet.ncols)))
return rows
# V客网登录
def clickLogin(driver, username, password):
sleep(2)
driver.find_element_by_id('login_txtUserName').send_keys(username)
sleep(2)
driver.find_element_by_id('login_txtPassword').send_keys(password)
sleep(2)
driver.find_element_by_id('login_btnLogin').click()
# 获取最终是否登录成功(通过登录成功与否网址不同来判断)
def getText(driver):
url = driver.current_url
if url == "http://www.vke53.com/User/login?ReturnUrl=%2f": # 这是登录失败后跳转的网址的URL
return 0 # 登录失败返回0
else:
return 1 # 登陆成功返回1
WekeTest的代码如下:
# coding:utf-8
from selenium import webdriver
from ddt import ddt, data, unpack
import unittest
import location
@ddt
class WekeTest(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
self.driver.implicitly_wait(30)
self.driver.get('http://www.vke53.com/User/login?ReturnUrl=/')
#通过location模块中的getDdtExcel函数获得Excel文档中的数据进行测试
@data(*location.getDdtExcel())
@unpack
def testCase_01(self, username, password, expect):
location.clickLogin(self.driver, username, password)
self.assertEqual(location.getText(self.driver), expect)
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(WekeTest)
unittest.TextTestRunner(verbosity=2).run(suite)