数据驱动:程序不变,数据变
首先自定义一个data.txt文件,下面附data.txt文件内容供参考
data.txt
gloryroad test||光荣之路
摔跤爸爸||阿米尔
超人||电影
data_driven_by_txt_file.py
适合做局部自动化:
#encoding=utf-8
from selenium import webdriver
import time
import traceback
with open(u"E:\\PythonDemo\\Glory\\20190224\\data.txt") as fp:
data=fp.readlines()
driver=webdriver.Ie(executable_path="d:\\chromedriver.exe")
test_result=[]
for i in range(len(data)):
try:
driver.get("http://www.baidu.com")
driver.find_element_by_id("kw").send_keys(\
data[i].split("||")[0].strip())
driver.find_element_by_id("su").click()
time.sleep(3)
assert data[i].split('||')[1].strip()\
in driver.page_source
test_result.append(data[i].strip()+u"||成功\n")
print (data[i].split('||')[0].strip()+u"搜索测试执行成功")
except AssertionError as e:
print (data[i].split('||')[1].strip()+u"测试断言失败")
test_result.append(data[i].strip()+u"||断言失败\n")
except Exception as e:
print (data[i].split('||')[1].strip()+u"测试执行失败")
test_result.append(data[i].strip()+u"||异常失败\n")
traceback.print_exc()
with open(u"result.txt","w") as fp:
fp.writelines(test_result)
#driver.quit()
优化第2种方法:
换了路径
#encoding=utf-8
from selenium import webdriver
import time
import traceback
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)),"data.txt")) as fp:
data=fp.readlines()
driver=webdriver.Ie(executable_path="e:\\IEDriverServer")
test_result=[]
for i in range(len(data)):
try:
driver.get("http://www.baidu.com")
driver.find_element_by_id("kw").send_keys(\
data[i].split("||")[0].strip())
driver.find_element_by_id("su").click()
time.sleep(3)
assert data[i].split('||')[1].strip()\
in driver.page_source
test_result.append(data[i].strip()+u"||成功\n")
print (data[i].split('||')[0].strip()+u"搜索测试执行成功")
except AssertionError as e:
print (data[i].split('||')[