数据驱动
数据和程序的分离,程序不变,数据变
from selenium import webdriver
import time
driver = webdriver.Firefox(executable_path = "d:\geckodriver")
driver.get("http://www.bing.com")
search_box = driver.find_element_by_xpath("//input[@id='sb_form_q']")
search_box.send_keys("大话西游之月光宝盒")
query_button = driver.find_element_by_xpath("//input[@id='sb_form_go']")
query_button.click()
time.sleep(5)
assert "周星驰" in driver.page_source
driver.quit()
请使用数据驱动的方式,实现访问网址、搜索框定位表达式、搜索词输入、搜索按钮定位表达式和断言值作为数据驱动的数据文件,然后执行测试脚本。
测试脚本:
from selenium import webdriver
import time
import os.path
import sys
def get_data_from_file(data_file_path,coding="utf-8"):
if not os.path.exists(data_file_path):
print("数据文件不存在!")
sys.exit(0)
test_data = []
with open(data_file_path,'r',encoding=coding) as fp:
for line in fp:
if line.strip() == "":
continue
test_data.append(line.split("||"))
return test_data
test_data = get_data_from_file("f:\\urls.txt")
#print(test_data)
def test_step(url,searchbox_xpath,search_button_xpath,search_word,assert_word):
driver = webdriver.Firefox(executable_path = "d:\geckodriver")
driver.get(url)
search_box = driver.find_element_by_xpath(searchbox_xpath)
search_box.send_keys(search_word)
query_button = driver.find_element_by_xpath(search_button_xpath)
query_button.click()
time.sleep(5