python+selenium九:ddt数据驱动

 

第一种,测试数据放在Excel里面

test_Login:

import unittest
import time
import ddt
import os
from selenium import webdriver
from SWYJR.common.readexcel import ExcelUtil
from SWYJR.encapsulation.LoginPage import Login

# # 获取xlsx路径
# curpath = os.path.dirname(os.path.realpath(__file__))
# testxlsx = os.path.join(curpath, "demo_api.xlsx")
#
# # 复制demo_api.xlsx文件到report下
# report_path = os.path.join(os.path.dirname(curpath), "report")
# reportxlsx = os.path.join(report_path, "result.xlsx")
# sheetName = "登录"
# testdata = readexcel.ExcelUtil(testxlsx, sheetName).dict_data()

excel = ExcelUtil("testdata.xlsx", "登录")
print(excel.dict_data())
datas = excel.dict_data()

@ddt.ddt
class LogIn(unittest.TestCase):
''' 登录测试 '''

def setUp(self):
self.driver = webdriver.Firefox()
self.login = Login(self.driver)
self.login.login_before() # 调前置条件

def tearDown(self):
self.driver.quit()

@ddt.data(*datas)
def test_login(self, data):
self.login.login(data['userName'], data['psw'])
self.text = self.login.exit_button()
self.assertIn(data['result'], self.text)

if __name__ == "__main__":
unittest.main()

 

 readExcel:

# coding:utf-8
import xlrd
class ExcelUtil():

def __init__(self, excelPath, sheetName):
#def __init__(self, excelPath, sheetName):
self.data = xlrd.open_workbook(excelPath)
self.table = self.data.sheet_by_name(sheetName)
# 获取第一行作为key值
self.keys = self.table.row_values(0)
# 获取总行数
self.rowNum = self.table.nrows
# 获取总列数
self.colNum = self.table.ncols

def dict_data(self):
if self.rowNum <= 1:
print("总行数小于1")
else:
r = []
j=1
for i in range(self.rowNum-1):
s = {}
# 从第二行取对应values值
values = self.table.row_values(j)
for x in range(self.colNum):
s[self.keys[x]] = values[x]
r.append(s)
j+=1
return r

if __name__ == "__main__":
# filepath = "D:\\test\\web-project\\5ke\\testdata.xlsx"
filepath = "E:\\testdata.xlsx"
sheetName = "登录"
data = ExcelUtil(filepath, sheetName)
print(data.dict_data())

 

 

第二种,搭建个数据库,测试数据放在数据库里面,如:MySQL(个人比较喜欢用数据库的方式做数据分离)

导入第三方库pymysql,进行二次封装

 

import unittest, ddt, urllib3
from interfaces.Process import login
from common.MySQL import MysqlUtil
urllib3.disable_warnings()

# 拿测试数据
datas = MysqlUtil("SELECT explanation, userName, password, expect FROM Login").mysql_getrows()
# print(datas)

@ddt.ddt
class LogIn(unittest.TestCase):
''' 登录测试 '''

@ddt.data(*datas)
def test_login(self, data):
''' 测试用例 '''
self.user = data[1]
print(f'\n用户名:{self.user}')

self.password = data[2]
print(f'\n密码:{self.user}')

loginResult = login(self.user, self.password)[0]
print(f'\n预期结果: {data[3]} \n执行结果: {loginResult}')

self.assertEqual(loginResult, data[3])

if __name__=='__main__':
unittest.main()

 

posted @ 2018-08-30 16:08  向前走。  阅读(2166)  评论(0编辑  收藏  举报