接口自動化測試---數據庫操作封裝

本節通過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':'[email protected]','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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章