一、自动化测试用例用excel表格管理,表名为login.xlsx.,主要实现通过不同的用户名和密码判断登录成功与否,如图:
二、那么如何实现代码与数据进行分离,方便测试用例维护呢?详细代码如下
#coding=utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import requests
import xlrd
import os
import time
from seleniumimport webdriver
from selenium.common.exceptionsimport *
class Runmain:
def run_main(self,url,data,params,headers):
data = xlrd.open_workbook(os.getcwd() +"\\login.xlsx")#打开步骤一中的表格
table = data.sheet_by_name("Sheet1")#选取表格中的某一页,如图所示
rows=table.nrows#计算出该表中有多少行数据
print ('行数:'+str(rows))
for i in range(1,rows):#遍历每一行数据,除去第一行
tabledata = table.row_values(i)#计算出第i行数据
username,password,method,loginurl= tabledata[0],tabledata[1],tabledata[2],tabledata[3]#找出第i行索引值
print username,',',int(password),',',method,',',loginurl
response =None
if method =='GET':
# response=self.send_get(url,params,headers)
print ("method:GET")
else:
print ("method:POST")
# response=self.send_post(url,data,headers)
driver=webdriver.Firefox()
driver.get(loginurl)
urllogonbefore=driver.current_url
print ("urllogonbefore:",urllogonbefore)
driver.find_element_by_xpath(".//*[@id='username']").send_keys(username)
driver.find_element_by_xpath(".//*[@id='password']").send_keys(int(password))
driver.find_element_by_xpath(".//*[@id='content']/div/section/div/div/div[2]/div/form/div[3]/div/button").click()
time.sleep(2)
try:
if driver.switch_to_alert():
#driver.switch_to_alert().accept()#接受警告框,点击警告框中的确定按钮
ErrorMsg=driver.switch_to_alert().text#获取警告框弹出内容
print ('ErrorMsg:',ErrorMsg)
print (ErrorMsg[0:5])#打印警告框弹出内容,用分片进行操作
print ("登录账号或密码错误!")
driver.quit()
except NoAlertPresentExceptionas e:#如果没有抛出"NoAlertPresentException"异常,则表示没有弹出警告框,登录成功
print ('login success,because no ',e,"see!!!")
urlloginend = driver.current_url
print ("urlloginend:", urlloginend)
driver.quit()
Rmain=Runmain()
Rmain.run_main(1,2,3,4)