一、摘要

本博文将介绍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】的更多相关文章

  1. python selenium 使用unittest 示例

    python selenium 使用unittest 示例 并等待某个元素示例 from selenium.webdriver.support.ui import WebDriverWait from ...

  2. python+requests+excel+unittest+ddt接口自动化数据驱动并生成html报告

    1.环境准备: python3.6 requests xlrd openpyxl HTMLTestRunner_api 2.目前实现的功能: 封装requests请求方法 在excel填写接口请求参数 ...

  3. python+requests+excel+unittest+ddt接口自动化数据驱动并生成html报告(二)

    可以参考 python+requests接口自动化完整项目设计源码(一)https://www.cnblogs.com/111testing/p/9612671.html 原文地址https://ww ...

  4. python+selenium九:ddt数据驱动

    第一种,测试数据放在Excel里面 test_Login: import unittestimport timeimport ddtimport osfrom selenium import webd ...

  5. Python 数据驱动 unittest + ddt

    一数据驱动测试的含义: 在百度百科上的解释是: 数据驱动测试,即黑盒测试(Black-box Testing),又称为功能测试,是把测试对象看作一个黑盒子.利用黑盒测试法进行动态测试时,需要测试软件产 ...

  6. python+requests+excel+unittest+ddt接口自动化数据驱动并生成html报告(已弃用)

    前言 1.环境准备: python3.6 requests xlrd openpyxl HTMLTestRunner_api 2.目前实现的功能: 封装requests请求方法 在excel填写接口请 ...

  7. Python&Selenium 数据驱动【unittest+ddt】

    一.摘要 本博文将介绍Python和Selenium做自动化测试的时候,基于unittest框架,借助ddt实现数据驱动 二.测试代码 # encoding = utf-8 ""& ...

  8. Python&Selenium 数据驱动【unittest+ddt+json】

    一.摘要 本博文将介绍Python和Selenium做自动化测试的时候,基于unittest框架,借助ddt模块使用json文件作为数据文件作为测试输入,最后生成html测试报告 二.json文件 [ ...

  9. Python&Selenium 数据驱动测试【unittest+ddt+xml】

    一.摘要 本博文将介绍Python和Selenium做自动化测试时,基于unittest框架,借助ddt模块,使用xml文件作为测试输入. 二.xml文件 保存路径:D:\\Programs\\Pyt ...

随机推荐

  1. Github搭建个人博客的总结

    1.  参考 这个 博客 : https://blog.csdn.net/xudailong_blog/article/details/78762262 2. 把上面按照的就安装,并把git 仓库克隆 ...

  2. Burp_Suite_Pro_v1.7.*激活

    先下载工具: 链接:https://pan.baidu.com/s/1ZLvg8eqkgWI94FtrhkcTxg 提取码:9z1j 工具运行需要Java环境.解压完后双击keygen   填一下Li ...

  3. 【OpenCV开发】使用OpenCV的OpenCL(ocl)模块

    参加OpenCV的OpenCL模块(以下称OCL)移植工作已经有2个月了.这里我说移植而不是开发,是因为大部分OCL模块的函数都是从已经很成熟的GPU模块移植过来的.于是目前阶段OCL模块所支持的函数 ...

  4. 【并行计算与CUDA开发】基于NVIDIA显卡的硬编解码的一点心得 (完结)

    原文:基于NVIDIA显卡的硬编解码的一点心得 (完结) 1.硬解码软编码方法:大体流程,先用ffmpeg来读取视频文件的包,接着开启两个线程,一个用于硬解码,一个用于软编码,然后将读取的包传给解码器 ...

  5. 什么是 redis 的雪崩、穿透和击穿?

    缓存雪崩 对于系统 A,假设每天高峰期每秒 5000 个请求,本来缓存在高峰期可以扛住每秒 4000 个请求,但是缓存机器意外发生了全盘宕机.缓存挂了,此时 1 秒 5000 个请求全部落数据库,数据 ...

  6. Scala当中parallelize并行化的用法

    [学习笔记] parallelize并行化集合是根据一个已经存在的Scala集合创建的RDD对象.集合的里面的元素将会被拷贝进入新创建出的一个可被并行操作的分布式数据集.例如:val rdd03 = ...

  7. TCP连接可能出现的异常总结

    1.java.net.BindException:Address already in use:bind 服务端出错,两次对同一个端口进行启动(会在服务端发生报错,抛出异常,不考虑) 2.java.n ...

  8. 图数据库-Neo4j-常用算法

    本次主要学习图数据库中常用到的一些算法,以及如何在Neo4j中调用,所以这一篇偏实战,每个算法的原理就简单的提一下. 1. 图数据库中常用的算法 PathFinding & Search 一般 ...

  9. 利用Mathpix Snipping Tool轻松在markdown/LaTeX中输入电子书和论文的数学公式

    最近写图形学博客写累了,公式太多了,一个个输入实在太累,所以从数学建模队友那里吃了一个安利. 官网下载 下载安装后,直接新建一个截图,就可以转成LaTeX数学公式了.效果如下: 爽的一批啊!!! 另外 ...

  10. 进程程序替换(自主实现shell)

    进程替换 替换进程所运行的程序 流程:将另一段代码加载到内存中,通过页表将原来进程的映射关系重新建立到新的程序在内存中的地址,相当于替换了进程所运行程序以及所要处理的数据 (替换了代码段,重新初始化数 ...