接口自动化测试---数据库操作封装

与世无争的帅哥 提交于 2020-02-13 20:53:27

本节通过PyMysql驱动编写sql语句来操作数据库。但是通过编写sql语句生成数据库比较麻烦,本节为了简化这一流程,避免直接编写sql语句。

一、目录结构:

  • mysql_db.py文件对数据库进行封装操作,主要包含连接数据库、执行sql语句、数据库的关闭操作,将sql语句单独出来,而不用以后每个接口中调用;
  • db_config.ini文件为数据库的配置内容;

二、数据库操作封装

db_config.ini文件

[mysqlconf]
host=127.0.0.1
port=3306
user=root
password=111111
db_name=guest_test

mysql_db.py文件

# -*-encoding=utf-8-*-
import pymysql.cursors
from os.path import abspath, dirname

#configparser库用来读取ini类型的配置文件
import configparser as cparser

#=======================读取db_config.ini文件设置=======================
# 配置文件的绝对路径
# base_dir = str(os.path.dirname(os.path.dirname(__file__)))
# base_dir = base_dir.replace('\\','/')
# file_path = base_dir + "/db_config.ini"
# print(file_path)
base_dir = dirname(dirname(abspath(__file__)))
base_dir = base_dir.replace('\\', '/')
file_path = base_dir + "/db_config.ini"
print(file_path)

#初始化
cf = cparser.ConfigParser()
#读取配置文件
cf.read(file_path)
host = cf.get("mysqlconf","host")
port = cf.get("mysqlconf","port")
user = cf.get("mysqlconf","user")
password = cf.get("mysqlconf","password")
db = cf.get("mysqlconf","db_name")

# ======== MySql base operating ===================
class DB:

    def __init__(self):
        try:
            # Connect to the database
            self.connection = pymysql.connect(host=host,
                                              port=int(port),
                                              user=user,
                                              password=password,
                                              db=db,
                                              charset='utf8mb4',
                                              cursorclass=pymysql.cursors.DictCursor)
        except pymysql.err.OperationalError as e:
            print("Mysql Error %d: %s" % (e.args[0], e.args[1]))

    # clear table data
    def clear(self, table_name):
        # real_sql = "truncate table " + table_name + ";"
        real_sql = "delete from " + table_name + ";"
        with self.connection.cursor() as cursor:
            cursor.execute("SET FOREIGN_KEY_CHECKS=0;")
            cursor.execute(real_sql)
        self.connection.commit()

    # insert sql statement
    def insert(self, table_name, table_data):
        for key in table_data:
            table_data[key] = "'"+str(table_data[key])+"'"
        key   = ','.join(table_data.keys())
        value = ','.join(table_data.values())
        real_sql = "INSERT INTO " + table_name + " (" + key + ") VALUES (" + value + ")"
        #print(real_sql)

        with self.connection.cursor() as cursor:
            cursor.execute(real_sql)

        self.connection.commit()

    # close database
    def close(self):
        self.connection.close()

    # init data
    def init_data(self, datas):
        for table, data in datas.items():
            self.clear(table)
            for d in data:
                self.insert(table, d)
        self.close()


if __name__ == '__main__':

    db = DB()
    table_name = "sign_event"
    data = {'id':1,'name':'红米','`limit`':2000,'status':1,'address':'北京会展中心','start_time':'2016-08-20 00:25:42','create_time':'2016-08-20 00:25:42'}
    table_name2 = "sign_guest"
    data2 = {'realname':'alen','phone':12312341234,'email':'alen@mail.com','sign':0,'event_id':1}

    db.clear(table_name)
    db.insert(table_name, data)
    db.close()

执行该文件后,数据库中的数据正确 ;

三、番外篇:

1、获取文件路径,文件路径这里后期会单独学习:

base_dir=str(os.path.dirname(os.path.dirname(__file__))) 

print:C:/Users/46297/PycharmProjects/pyrequest/db_config.ini

base_dir=os.path.dirname(os.path.realpath(__file__))+"/db_config.ini"

print:C:\Users\46297\PycharmProjects\pyrequest\db_fixture/db_config.ini

2、问题记录及解决:

问题1:

Db_config.ini数据库配置文件中首行添加注释“#数据库配置”就会报错:UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 15: illegal multibyte sequence,还是和编码有关,去掉注释就好了;

问题2:

D:\Python37\python.exe C:/Users/46297/PycharmProjects/pyrequest/db_fixture/mysql_db.py

C:/Users/46297/PycharmProjects/pyrequest/db_config.ini

Traceback (most recent call last):

  File "C:/Users/46297/PycharmProjects/pyrequest/db_fixture/mysql_db.py", line 85, in <module>

    db = DB()

  File "C:/Users/46297/PycharmProjects/pyrequest/db_fixture/mysql_db.py", line 43, in __init__

    cursorclass=pymysql.cursors.DictCursor)

  File "D:\Python37\lib\site-packages\pymysql\__init__.py", line 94, in Connect

    return Connection(*args, **kwargs)

  File "D:\Python37\lib\site-packages\pymysql\connections.py", line 325, in __init__

    self.connect()

  File "D:\Python37\lib\site-packages\pymysql\connections.py", line 599, in connect

    self._request_authentication()

  File "D:\Python37\lib\site-packages\pymysql\connections.py", line 882, in _request_authentication

    auth_packet = _auth.caching_sha2_password_auth(self, auth_packet)

  File "D:\Python37\lib\site-packages\pymysql\_auth.py", line 264, in caching_sha2_password_auth

    data = sha2_rsa_encrypt(conn.password, conn.salt, conn.server_public_key)

  File "D:\Python37\lib\site-packages\pymysql\_auth.py", line 142, in sha2_rsa_encrypt

    raise RuntimeError("cryptography is required for sha256_password or caching_sha2_password")

RuntimeError: cryptography is required for sha256_password or caching_sha2_password

报错原因:MySQL8.0版本以后采用caching_sha2_password作为默认的身份验证插件。

解决方案:

mysql> use guest_test;

Database changed

mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '111111';

Query OK, 0 rows affected (0.03 sec)

mysql> FLUSH PRIVILEGES;

Query OK, 0 rows affected (0.01 sec)

将db_config.ini文件中密码对应更改后重启pycharm,问题解决,参考博客:https://blog.csdn.net/qq_35762038/article/details/86066107

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!