-
目的
相同的测试脚本使用不同的测试数据来执行,实现测试数据和测试脚本分离。
(如:网站登录功能,使用不同的账号和密码,登陆时对系统影响) -
步骤
(1)编写测试脚本,脚本需要指出从程序对象、文件或数据库读入测试数据;
(2)将测试脚本使用的测试数据存入程序对象、文件或数据库等外部介质中;
(3)运行脚本过程中,循环盗用存储在外部介质中的测试数据;
(4)验证所有的测试结果是否符合预期结果。 -
测试逻辑:
(1)打开百度首页
(2)在搜索框输入一个搜索关键词
(3)点击搜索按钮
(4)验证搜索结果页面是否包含预期关键字,包含则认为测试执行通过,否则认为测试执行失败,并在测试国债中打印日志。 -
百度搜索代码:
4.1. 程序文件结构
DataDrivenProject |---------------python工程
data.txt |---------------数据文件,存储测试数据
DataDrivenTest.py |---------------测试程序文件
4.2. data.txt
搜索词||断言词
4.3. DataDrivenTest.py
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import unittest
import time
class DataDriven(unittest.TestCase):
def setUp(self) -> None:
# 启动浏览器
self.driver = webdriver.Firefox()
# 打开数据库文件
with open('./data1.txt', 'r') as fp:
# 按行读取全部数据
self.datatest = fp.readlines()
def test_dataDrivenByObj(self):
for data in self.datatest:
# 从行数据中区分出用户名和密码
keyword, assertword = data.split('||')
# 打开网址
self.driver.get('https://www.baidu.com/')
# 输入关键词
self.driver.find_element_by_id('kw').send_keys(keyword)
# 点击查询按钮
self.driver.find_element_by_id('su').click()
# 等待2s
time.sleep(2)
# 显示等待查询结果
WebDriverWait(self.driver, 10, 0.5).until(lambda x: x.find_element_by_id('kw'))
# 断言页面关键词
assert assertword in self.driver.page_source
def tearDown(self) -> None:
# 关闭浏览器
self.driver.quit()
if __name__ == '__main__':
unittest.main()
- 126邮箱登陆数据驱动代码:
5.1. 程序文件结构
DataDrivenProject |---------------python工程
data.txt |---------------数据文件,存储测试数据
DataDrivenTest.py |---------------测试程序文件
5.2. data.txt
邮箱名||邮箱密码
5.3. DataDrivenTest.py
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import unittest
class DataDriven(unittest.TestCase):
def setUp(self) -> None:
# 按行读取txt文件中的全部数据
with open('./data.txt', 'r') as fp:
self.data_all = fp.readlines()
# 启动火狐浏览器
self.driver = webdriver.Firefox()
def test_dataDrivenByObj(self):
# 逐行执行测试数据
for data in self.data_all:
# 从行数据中区分出用户名和密码
username, password = data.split('||')
# 打开邮箱网址
self.driver.get("https://mail.126.com/")
# 从二维码登陆方式切换成密码登陆方式
if '密码登录' in self.driver.page_source:
self.driver.find_element_by_id('switchAccountLogin').click()
# 进入到登陆输入frame中
self.driver.switch_to.frame(self.driver.find_element_by_xpath('//iframe[contains(@id,"x-URS-iframe")]'))
# 输入邮箱账号
self.driver.find_element_by_name('email').send_keys(username)
# 输入邮箱密码
self.driver.find_element_by_name('password').send_keys(password)
# 点击登陆按钮
self.driver.find_element_by_id('dologin').click()
# 退出frame
self.driver.switch_to.default_content()
# 显示等待,最长等待时间10秒,调用频率0.5(在超时时间段内,每隔0.5秒执行一次判断)
WebDriverWait(self.driver, 10, 0.5).until(lambda x: x.find_element_by_xpath('//a[contains(text(),"退出")]'))
# 断言页面是否显示登陆名
assert username in self.driver.page_source
# 点击退出按钮
self.driver.find_element_by_xpath('//a[contains(text(),"退出")]').click()
# 断言当前页面是否已退出
assert '重新登录' in self.driver.page_source
def tearDown(self) -> None:
# 退出登陆
self.driver.quit()
if __name__ == '__main__':
unittest.main()