接口自动化测试框架实战:日志和数据库的封装

今天完成两部分的内容,日志和数据库的封装。

log日志的封装

import datetime
import logging
import os

from config import Conf
from config.Conf import ConfigYaml

log_l = {
    "info": logging.INFO,
    "debug": logging.DEBUG,
    "warning": logging.WARNING,
    "error": logging.ERROR

}

class Logger():
    def __init__(self, log_file, log_name, log_level):
        self.log_file = log_file
        self.log_name = log_name
        self.log_level = log_level
        #设置logger名称
        self.logger = logging.getLogger(self.log_name)
        self.logger.setLevel(log_l[self.log_level])
        formatter = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s')
        if not self.logger.handlers:
            # 输出到控制台
            self.fh_stream = logging.StreamHandler()
            self.fh_stream.setLevel(log_l[self.log_level])
            self.fh_stream.setFormatter(formatter)
            self.logger.addHandler(self.fh_stream)
            #写入文件
            self.fh_file = logging.FileHandler(self.log_file)
            self.fh_file.setLevel(log_l[self.log_level])
            self.fh_file.setFormatter(formatter)
            self.logger.addHandler(self.fh_file)

#获取日志文件存储路径
log_path = Conf.get_log_path()

current_time = datetime.datetime.now().strftime("%Y-%m-%d")

log_extension=ConfigYaml().get_conf_log_extension()

#日志文件名称
logfile=os.path.join(log_path,current_time+log_extension)

#获取日志级别(放在配置文件里面,方便根据需求修改)
loglevel = ConfigYaml().get_conf_log()

def my_log(log_name=__file__):

    return Logger(log_file=logfile,log_name=log_name,log_level=loglevel).logger

if __name__ == '__main__':
    my_log().info('123456')

数据库的封装

import pymysql
from utils.LogUtil import my_log
class MySql():
    def __init__(self,host,user,password,database,charset,port):
        self.log = my_log('database')
        self.conn = pymysql.connect(
                    host=host,
                    user=user,
                    password=password,
                    database=database,
                    charset=charset,
                    port=port
                    )
        self.cursor=self.conn.cursor(pymysql.cursors.DictCursor)

    def fetchone(self, sql):
        self.cursor.execute(sql)
        return self.cursor.fetchone()

    def fetchall(self, sql):
        """
        多个查询
        """
        self.cursor.execute(sql)
        return self.cursor.fetchall()

    def exec(self, sql):
        """
        执行
        """
        try:
            if self.conn and self.cursor:
                self.cursor.execute(sql)
                self.conn.commit()
        except Exception as ex:
            self.conn.rollback()
            self.log.error("Mysql 执行失败")
            self.log.error(ex)
            return False
        return True

        # 4、关闭对象

    def __del__(self):
        # 关闭光标对象
        if self.cursor is not None:
            self.cursor.close()
        # 关闭连接对象
        if self.conn is not None:
            self.cursor.close()

if __name__ == "__main__":
    mysql = MySql("xxxxxxx",
                  "test",
                  "test123456","xxxxxx",
                  charset="utf8",
                  port=7090)
    res = mysql.fetchall("select username,password from tb_users")
    # res = mysql.exec("update tb_users set first_name='python' where username = 'python'")
    print('1111',res)

你可能感兴趣的:(接口自动化测试框架实战:日志和数据库的封装)