Python&Selenium 数据驱动【unittest+ddt+mysql】
一、摘要
本博文将介绍Python和Selenium做自动化测试的时候,基于unittest框架,借助ddt模块使用mysql数据库为数据源作为测试输入
二、SQL脚本
# encoding = utf-8 create_database = 'CREATE DATABASE IF NOT EXISTS davieyang DEFAULT CHARSET utf8 COLLATE utf8_general_ci;'
drop_table = 'DROP TABLE testdata;'
create_table = """
CREATE TABLE testdata(
ID int primary key not null auto_increment comment '主键',
BOOKNAME varchar(40) unique not null comment '书名',
AUTHOR varchar(30) not null comment '作者'
)engine = innodb character set utf8 comment '测试数据表';
"""
三、解析Mysql
# encoding = utf-8
"""
__title__ = ''
__author__ = 'davieyang'
__mtime__ = '2018/4/21'
"""
import pymysql
from TestData.SqlScripts import create_table
from TestData.SqlScripts import create_database
from TestData.SqlScripts import drop_table class MySQL(object):
def __init__(self, host, port, dbName, username, password, charset):
self.conn = pymysql.connect(
host=host,
port=port,
db=dbName,
user=username,
password=password,
charset=charset
)
self.cur = self.conn.cursor() def create(self):
try:
self.cur.execute(create_database)
self.conn.select_db("davieyang")
self.cur.execute(drop_table)
self.cur.execute(create_table)
'''
cur.execute("drop database if exists davieyang") #如果davieyang数据库存在则删除
cur.execute("create database davieyang") #新创建一个数据库davieyang
cur.execute("use davieyang") #选择davieyang这个数据库
# sql 中的内容为创建一个名为testdata的表
sql = """create table testdata(id BIGINT,name VARCHAR(20),age INT DEFAULT 1)""" #()中的参数可以自行设置
conn.execute("drop table if exists testdata") # 如果表存在则删除
conn.execute(sql)# 创建表
# 删除
# conn.execute("drop table testdata")
conn.close()# 关闭游标连接
connect.close()# 关闭数据库服务器连接 释放内存
'''
except pymysql.Error as e:
raise e
else:
self.cur.close()
self.conn.commit()
self.conn.close()
print(u"创建数据库和表成功") def insertDatas(self):
try:
sql = "insert into testdata(bookname, author) values(%s, %s);"
self.cur.executemany(sql, [('selenium xml DataDriven', 'davieyang'),
('selenium excel DataDriven', 'davieyang'),
('selenium ddt data list', 'davieyang')])
except pymysql.Error as e:
raise e
else:
self.conn.commit()
print(u"初始数据插入成功")
self.cur.execute("select * from testData;")
for i in self.cur.fetchall():
print(i[1], i[2])
self.cur.close()
self.conn.close() def getDataFromDataBase(self):
# 从数据库中获取数据
# bookname作为搜索关键词,author作为期望结果
self.cur.execute("select bookname, author from testdata;")
# 从查询区域取回所有查询结果
dataTuple = self.cur.fetchall()
return dataTuple def closeDataBase(self):
# 数据库清理
self.cur.close()
self.conn.commit()
self.conn.close() if __name__ == "__main__":
db = MySQL(
host="localhost",
port=3306,
dbName="davieyang",
username="root",
password="root",
charset="utf8"
)
print(db.getDataFromDataBase())
db.closeDataBase()
四、测试脚本
# encoding = utf-8
"""
__title__ = ''
__author__ = 'davieyang'
__mtime__ = '2018/4/21'
"""
from selenium import webdriver
import unittest
import time
import logging
import traceback
import ddt
from Util.MysqlDBUtil import MySQL
from selenium.common.exceptions import NoSuchElementException # 初始化日志对象
logging.basicConfig(
# 日志级别
level=logging.INFO,
# 时间、代码所在文件名、代码行号、日志级别名字、日志信息
format='%(asctime)s %(filename)s[line: %(lineno)d] %(levelname)s %(message)s',
# 打印日志的时间
datefmt='%a, %d %b %Y %H:%M:%S',
# 日志文件存放的目录及日志文件名
filename='F:\\DataDriven\\TestResults\TestResults.TestResults',
# 打开日志的方式
filemode='w'
) def getTestDatas():
db = MySQL(
host="localhost",
port=3306,
dbName="davieyang",
username="root",
password="root",
charset="utf8"
)
# 从数据库中获取测试数据
testData = db.getDataFromDataBase()
db.closeDataBase()
return testData @ddt.ddt
class DataDrivenByMySQL(unittest.TestCase): def setUp(self):
self.driver = webdriver.Chrome(executable_path=r"F:\automation\webdriver\chromedriver.exe") @ddt.data(* getTestDatas())
def test_dataDrivenByMySQL(self, data):
# 对获得的数据进行解包
testData, expectData =data
url = "http://www.baidu.com"
self.driver.get(url)
self.driver.maximize_window()
print(testData, expectData)
self.driver.implicitly_wait(10)
try:
self.driver.find_element_by_id("kw").send_keys(testData)
self.driver.find_element_by_id("su").click()
time.sleep(3)
self.assertTrue(expectData in self.driver.page_source)
except NoSuchElementException as e:
logging.error(u"查找的页面元素不存在,异常堆栈信息为:" + str(traceback.format_exc()))
except AssertionError as e:
logging.info(u"搜索 ‘%s’,期望 ‘%s’ ,失败" % (testData, expectData))
except Exception as e:
logging.error(u"未知错误,错误信息:" + str(traceback.format_exc()))
else:
logging.info(u"搜索 ‘%s’,期望 ‘%s’ ,通过" % (testData, expectData)) def tearDown(self):
self.driver.quit() if __name__ == "__main__":
unittest.main()
Python&Selenium 数据驱动【unittest+ddt+mysql】的更多相关文章
- python selenium 使用unittest 示例
python selenium 使用unittest 示例 并等待某个元素示例 from selenium.webdriver.support.ui import WebDriverWait from ...
- python+requests+excel+unittest+ddt接口自动化数据驱动并生成html报告
1.环境准备: python3.6 requests xlrd openpyxl HTMLTestRunner_api 2.目前实现的功能: 封装requests请求方法 在excel填写接口请求参数 ...
- python+requests+excel+unittest+ddt接口自动化数据驱动并生成html报告(二)
可以参考 python+requests接口自动化完整项目设计源码(一)https://www.cnblogs.com/111testing/p/9612671.html 原文地址https://ww ...
- python+selenium九:ddt数据驱动
第一种,测试数据放在Excel里面 test_Login: import unittestimport timeimport ddtimport osfrom selenium import webd ...
- Python 数据驱动 unittest + ddt
一数据驱动测试的含义: 在百度百科上的解释是: 数据驱动测试,即黑盒测试(Black-box Testing),又称为功能测试,是把测试对象看作一个黑盒子.利用黑盒测试法进行动态测试时,需要测试软件产 ...
- python+requests+excel+unittest+ddt接口自动化数据驱动并生成html报告(已弃用)
前言 1.环境准备: python3.6 requests xlrd openpyxl HTMLTestRunner_api 2.目前实现的功能: 封装requests请求方法 在excel填写接口请 ...
- Python&Selenium 数据驱动【unittest+ddt】
一.摘要 本博文将介绍Python和Selenium做自动化测试的时候,基于unittest框架,借助ddt实现数据驱动 二.测试代码 # encoding = utf-8 ""& ...
- Python&Selenium 数据驱动【unittest+ddt+json】
一.摘要 本博文将介绍Python和Selenium做自动化测试的时候,基于unittest框架,借助ddt模块使用json文件作为数据文件作为测试输入,最后生成html测试报告 二.json文件 [ ...
- Python&Selenium 数据驱动测试【unittest+ddt+xml】
一.摘要 本博文将介绍Python和Selenium做自动化测试时,基于unittest框架,借助ddt模块,使用xml文件作为测试输入. 二.xml文件 保存路径:D:\\Programs\\Pyt ...
随机推荐
- Apache Jmeter教程(一) - 入门
一.下载Jmeter 登录官网Jmeter下载,得到压缩包jmeter-5.0.tgz,下载地址:http://jmeter.apache.org/download_jmeter.cgi. 二.安装 ...
- harbor清理存储
harbor仓库中镜像按tag清理,删除tag后需要清理gc才能释放空间 #!/bin/bash set -e HARBOR_URL=127.0.0.1 HARBOR_PASSWD=harbor123 ...
- 【Qt开发】关于QWSServer
QWS Server QT Embeded应用没有来严格的区分server和client进程,如果一个QT进程的启动参数中有-qws,那么这个进程就具有server管理功能,被称为QWS server ...
- MIT 6.828 课程介绍
MIT 6.828 课程介绍 本文是对MIT 6.828操作系统课程介绍的简单摘录,详细介绍见6.828: Learning by doing以及朱佳顺的推荐一门课:6.828.学习资源均可以在课程主 ...
- Django使用DataTables插件总结
Django使用Datatables插件总结 文章中的例子已上传至github 基本使用 Datatables插件是一款方便简单的展示数据的列表插件.关于基本使用,官方网站上的已介绍的很详细,这里我再 ...
- 解决python无法安装mysql数据库问题
解决python无法安装mysql数据库问题: pip install pymysql[使用这个命令来安装]
- global和nonlocal的区别
global可以在任何地方修饰变量,而且被global修饰的变量直接被标识为全局变量,对该变量修改会影响全局变量的值,但不影响函数中未被global修饰的同名变量(依然是局部变量),nonlocal只 ...
- linux下mysql启动 Starting MySQL. ERROR! The server quit without updating PID file(xxx/x.pid)
service mysql start 报错: Starting MySQL. ERROR! The server quit without updating PID file(xxx/x.pid) ...
- Excel2016 保存\复制 卡死问题解决
遇到的问题: 工作中经常碰到一些Excel表, 复制一行, 再粘贴要等5s以上才能显示成功. 保存一下文档, 也会出现页面白屏卡死的情况, 经过网上多个帖子进行操作依旧无解, 最后找到了自己的方法得以 ...
- k8s之helm入门
1.概述 helm是k8s的另外一个项目,相当于linux的yum,在yum仓库中,yum不光要解决包之间的依赖关系,还要提供具体的程序包,helm仓库里面只有配置清单文件,而没有镜像,镜像还是由镜像 ...