• python webdriver测试框架--数据驱动DB驱动


    简介:

    数据驱动数据库驱动方式,就是数据配置在数据库里面,主程序调用的时候每次用从数据库里取出的数据作为参数,进行操作,
    需要掌握的地方是对数据库的操作,要灵活的找到目标数据

     

    测试数据:

    创建数据库、表

    Sql.py

    #encoding=utf-8

    # 创建gloryroad数据库sql语句
    create_database = 'CREATE DATABASE IF NOT EXISTS gloryroad DEFAULT CHARSET utf8 COLLATE utf8_general_ci;'

    # 创建testdata表
    drop_table_if_exist_sql="drop table if exists testdata;"
    create_table = """

    create table testdata(
    id int not null auto_increment comment '主键',
    bookname varchar(40) unique not null comment '书名',
    author varchar(30) not null comment '作者',
    test_result varchar(30) default null,
    primary key(id)
    )engine=innodb character set utf8 comment '测试数据表';
    """

    数据库初始化,创建测试数据

    DatabaseInit.py

    #encoding=utf-8
    import pymysql
    from Sql import *

    class DataBaseInit(object):
    # 本类用于完成初始化数据操作
    # 创建数据库,创建数据表,向表中插入测试数据
    def __init__(self, host, port, dbName, username, password, charset):
    self.host = host
    self.port = port
    self.db = dbName
    self.user = username
    self.passwd = password
    self.charset = charset

    def create(self):
    try:
    # 连接mysql数据库
    conn = pymysql.connect(
    host = self.host,
    port = self.port,
    user = self.user,
    passwd = self.passwd,
    charset = self.charset
    )
    # 获取数据库游标
    cur = conn.cursor()
    # 创建数据库
    cur.execute(create_database)
    # 选择创建好的gloryroad数据库
    conn.select_db("gloryroad")
    # 创建测试表
    cur.execute(drop_table_if_exist_sql)
    cur.execute(create_table)
    except pymysql.Error as e:
    raise e
    else:
    # 关闭游标
    cur.close()
    # 提交操作
    conn.commit()
    # 关闭连接
    conn.close()
    print (u"创建数据库及表成功")

    def insertDatas(self):
    try:
    # 连接mysql数据库中具体某个库
    conn = pymysql.connect(
    host = self.host,
    port = self.port,
    db = self.db,
    user = self.user,
    passwd = self.passwd,
    charset = self.charset
    )
    cur = conn.cursor()
    # 向测试表中插入测试数据
    sql = "insert into testdata(bookname, author) values(%s, %s);"
    res = cur.executemany(sql, [('Selenium WebDriver实战宝典', '吴晓华'),
    ('HTTP权威指南', '古尔利'),
    ('探索式软件测试', '惠特克'),
    ('暗时间', '刘未鹏')])
    except pymysql.Error as e:
    raise e
    else:
    conn.commit()
    print("初始数据插入成功")
    # 确认插入数据成功
    cur.execute("select * from testdata;")
    for i in cur.fetchall():
    print (i[1], i[2])
    cur.close()
    conn.close()


    if __name__ == '__main__':
    db = DataBaseInit(
    host="localhost",
    port=3306,
    dbName="gloryroad",
    username="root",
    password="test",
    charset="utf8"
    )
    db.create()
    db.insertDatas()
    print("数据库初始化结束")

    单独执行结果:

    创建数据库及表成功
    初始数据插入成功
    Selenium WebDriver实战宝典 吴晓华
    HTTP权威指南 古尔利
    探索式软件测试 惠特克
    暗时间 刘未鹏
    数据库初始化结束

    MysqlUtil.py

    #encoding=utf-8
    import pymysql
    from DatabaseInit import DataBaseInit

    class MyMySQL(object):
    def __init__(self, host, port, dbName, username, password, charset):
    # 进行数据库初始化
    dbInit = DataBaseInit(host, port, dbName, username, password, charset)
    dbInit.create()
    dbInit.insertDatas()
    self.conn = pymysql.connect(
    host = host,
    port = port,
    db = dbName,
    user = username,
    passwd = password,
    charset = charset
    )
    self.cur = self.conn.cursor()

    def getDataFromDataBases(self):
    # 从testdata表中获取需要的测试数据
    # bookname作为搜索关键词,author作为预期关键词
    self.cur.execute("select bookname, author from testdata;")
    # 从查询区域取回所有查询结果
    datasTuple = self.cur.fetchall()
    return datasTuple

    def closeDatabase(self):
    # 数据库后期清理工作
    self.cur.close()
    self.conn.commit()
    self.conn.close()

    if __name__ == '__main__':
    db = MyMySQL(
    host="localhost",
    port=3306,
    dbName="gloryroad",
    username="root",
    password="test",
    charset="utf8"
    )
    print (db.getDataFromDataBases())

    单独执行的结果:

    创建数据库及表成功
    初始数据插入成功
    Selenium WebDriver实战宝典 吴晓华
    HTTP权威指南 古尔利
    探索式软件测试 惠特克
    暗时间 刘未鹏
    (('Selenium WebDriver实战宝典', '吴晓华'), ('HTTP权威指南', '古尔利'), ('探索式软件测试', '惠特克'), ('暗时间', '刘未鹏'))

    最后执行的脚本

    data_driven_by_mysql_1.py

    #encoding=utf-8
    from selenium import webdriver
    import time
    import datetime
    from openpyxl import *
    import pymysql

    def get_test_data():
    conn = pymysql.connect(
    host = "localhost",
    port = 3306,
    user = "root",
    passwd = "test" ,
    db = "gloryroad",
    charset = "utf8"
    )
    # 使用cursor()方法获取数据库的操作游标
    cursor = conn.cursor()
    cursor.execute("select * from testdata;")
    resSet = cursor.fetchall()
    print("共%s条数据。" %len(resSet))
    print( resSet)
    # 关闭游标
    cursor.close()
    # 提交事务
    conn.commit()
    # 关闭数据库连接
    conn.close()
    return resSet

    def update_test_result(data,result):
    conn = pymysql.connect(
    host = "localhost",
    port = 3306,
    user = "root",
    passwd = "test" ,
    db = "gloryroad",
    charset = "utf8"
    )
    # 使用cursor()方法获取数据库的操作游标
    cursor = conn.cursor()
    print( 'update testdata set test_result="'+result+'" where bookname="'+data+'";')
    update=cursor.execute('update testdata set test_result="'+result+'" where bookname="'+data+'";')

    print( u"修改语句受影响的行数:", update)
    # 关闭游标
    cursor.close()
    # 提交事务
    conn.commit()
    # 关闭数据库连接
    conn.close()

    driver = webdriver.Firefox(executable_path="D:\python\geckodriver")
    test_result=[]
    for data in get_test_data():
    try:
    driver.get("http://www.baidu.com")
    driver.find_element_by_id("kw").send_keys(data[1])
    driver.find_element_by_id("su").click()
    time.sleep(3)
    assert data[2] in driver.page_source
    update_test_result(data[1], "成功")
    except AssertionError as e:
    print( data[2] + "断言失败")
    update_test_result(data[1], "断言失败")
    except Exception as e:
    print(e)
    print(data[1] + "测试执行出现异常")
    update_test_result(data[1], "执行出现异常")

    driver.quit()


    执行结果:

    D:pythonpython.exe D:/db_data/data_driven_by_mysql_1.py
    共4条数据。
    ((1, 'Selenium WebDriver实战宝典', '吴晓华', None), (2, 'HTTP权威指南', '古尔利', None), (3, '探索式软件测试', '惠特克', None), (4, '暗时间', '刘未鹏', None))
    update testdata set test_result="成功" where bookname="Selenium WebDriver实战宝典";
    修改语句受影响的行数: 1
    update testdata set test_result="成功" where bookname="HTTP权威指南";
    修改语句受影响的行数: 1
    update testdata set test_result="成功" where bookname="探索式软件测试";
    修改语句受影响的行数: 1
    update testdata set test_result="成功" where bookname="暗时间";
    修改语句受影响的行数: 1

    Process finished with exit code 0

    总结:
    数据驱动DB驱动、Excel驱动方式和txt驱动方式原理大同小异,都是把数据从文件中取出来,传进主程序,脚本运行完毕后再把结果写入文件中;
    难点在于对不同的文件类型进行读取可能需要专门的程序包来处理;都是对基础的运用进行整合,真正项目上用到肯定比这复杂的多。。。


  • 相关阅读:
    MySQL锁的调试
    MySQL的分支与变种
    leetcode Merge Two Sorted Lists
    leetcode Next Permutation
    leetcode n后问题
    leetcode Remove Duplicates from Sorted List I && II
    leetcode minimum path sum
    leetcode simplify path
    leetcode ip地址组合
    leetcode path sum II
  • 原文地址:https://www.cnblogs.com/ff-gaofeng/p/12670181.html
Copyright © 2020-2023  润新知