python+requests+unittest+HTMLTestRunner构建接口自动化测试框架(三)数据库、日志、http请求、邮件方法封装

  • python+requests+unittest+HTMLTestRunner构建接口自动化测试框架(一)了解基础框架,读取配置文件
  • python+requests+unittest+HTMLTestRunner构建接口自动化测试框架(二)commonMoudle模板详解
  • python+requests+unittest+HTMLTestRunner构建接口自动化测试框架(三)数据库、日志、http请求、邮件方法封装
  • python+requests+unittest+HTMLTestRunner构建接口自动化测试框架(四)测试用例执行

本篇主要针对数据库、日志、http请求、邮件方法封装的方法进行讲解

一、日志打印

封装日志打印的方法,可以使用不同等级的log打印想要的内容,Log.py文件完整代码如下:

# -*- coding:utf-8 -*-
#@Time  : 2019/8/13 11:32
#@Author: csu
#@File  : Log.py
import  logging, threading, os
from datetime import datetime
import readConfig

localConfig = readConfig.ReadConfig()

class Log:
    def __init__(self):
        global logPath, resultPath, basePath
        basePath = readConfig.basePath

        resultPath = os.path.join(basePath, 'result')
        if not os.path.exists(resultPath):
            os.mkdir(resultPath)

        logPath = os.path.join(resultPath, str(datetime.now().strftime("%Y%m%d%H%M%S")))
        if not os.path.exists(logPath):
            os.mkdir(logPath)

        self.logger = logging.getLogger()
        self.logger.setLevel(logging.INFO)

        handler = logging.FileHandler(os.path.join(logPath, "output.log"))      # logging.FileHandler  -> 文件输出
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')    #设置日志格式
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)

    def get_logger(self):
        """
        get logger
        :return:
        """
        return self.logger

    def build_start_line(self, case_no):
        """
        write start line
        :return:
        """
        self.logger.info("--------" + case_no + " START--------")

    def build_end_line(self, case_no):
        """
        write end line
        :return:
        """
        self.logger.info("--------" + case_no + " END--------")

    def build_case_line(self, case_name, code, msg):
        """
        write test case line
        :param case_name:
        :param code:
        :param msg:
        :return:
        """
        self.logger.info(case_name+" - Code:"+code+" - msg:"+msg)

    def get_report_path(self):
        """
        get report file path
        :return:
        """
        report_path = os.path.join(logPath, "report.html")
        return report_path

    def get_result_path(self):
        """
        get test result path
        :return:
        """
        return logPath

    def write_result(self, result):
        """

        :param result:
        :return:
        """
        result_path = os.path.join(logPath, "report.txt")
        fb = open(result_path, "wb")
        try:
            fb.write(result)
        except FileNotFoundError as ex:
            self.logger.error(str(ex))

class MyLog:
    log = None
    mutex = threading.Lock()       #创建锁

    def __init__(self):
        pass

    @staticmethod
    def get_log():
        if MyLog.log is None:
            MyLog.mutex.acquire()   #锁定
            MyLog.log = Log()
            MyLog.mutex.release()   #释放

        return MyLog.log

二、邮件发送

因为公司邮箱是Outlook,所以选用邮件是Outlook发送,可能不适用于其他类型的邮箱发送,如果采用其他邮件方式发送的话,需要小伙伴自己研究啦

# -*- coding:utf-8 -*-
#@Time  : 2019/4/11 17:18
#@Author: junni
#@File  : configEmail.py
import os
import readConfig
import datetime
import win32com.client as win32
from common.Log import MyLog

localReadConfig = readConfig.ReadConfig()
proDir = readConfig.basePath

class send_email:
    def __init__(self):
        global subject, app, addressee, cc, mail_path
        self.subject = localReadConfig.get_email("subject")
        self.app = localReadConfig.get_email("app")
        self.addressee = localReadConfig.get_email("addressee")
        self.cc = localReadConfig.get_email("cc")

        self.log = MyLog.get_log()
        self.logger = self.log.get_logger()
        #self.mail_path = os.path.join(proDir, 'result', 'report.html')
        self.mail_path = MyLog.get_log().get_report_path()

    def outlook(self):
        olook = win32.Dispatch("%s.application" % self.app)  #固定写法
        mail = olook.CreateItem(0)                           #固定写法
        mail.To = self.addressee      #收件人
        mail.CC = self.cc             #抄送人
        mail.Subject = str(datetime.datetime.now())[0:19] + '测试报告'  # 邮件主题
        mail.Attachments.Add(self.mail_path, 1, 1, "myFile")
        read = open(self.mail_path, encoding='utf-8')  # 打开需要发送的测试报告附件文件
        content = read.read()  # 读取测试报告文件中的内容
        read.close()
        #mail.Body = content  # 将从报告中读取的内容,作为邮件正文中的内容
        mail.Body = '接口测试结果'
        mail.Send()  # 发送

三、http请求

这里只是简单的封装post和get请求,需要结合具体请求进行设置

# -*- coding:utf-8 -*-
#@Time  : 2019/8/12 19:57
#@Author: csu
#@File  : configHttp.py
import requests
from common.Log import MyLog as Log
import readConfig

localReadConfig = readConfig.ReadConfig()

class ConfigHttp:
    def __init__(self):
        global protocol, ip, port
        protocol = localReadConfig.get_http('protocol')
        ip = localReadConfig.get_http('ip')
        port = localReadConfig.get_http('port')

        self.log = Log.get_log()
        self.logger = self.log.get_logger()
        self.data = None
        self.url = None

    def set_url(self, url):
        self.url = protocol + '://' + ip + ':' + port + url
        return self.url

    def set_data(self, data):
        self.data = data
        return self.data

    def get(self):
        response = requests.get(self.url)
        return response

    def post(self):
        response = requests.post(self.url, data = self.data)
        return response

四、数据库

# -*- coding:utf-8 -*-
#@Time  : 2019/8/12 17:02
#@Author: csu
#@File  : configDB.py
import pymysql
import readConfig
from common.Log import MyLog as Log

localReadConfig = readConfig.ReadConfig()

class ConfigDB:
    global host, username, password, port, database, config
    host = localReadConfig.get_db('host')
    username = localReadConfig.get_db('username')
    password = localReadConfig.get_db('password')
    port = localReadConfig.get_db('port')
    database = localReadConfig.get_db('database')
    config = {
        'host':str(host),
        'user':username,
        'passwd':password,
        'port':int(port),
        'db':database

    }

    def __init__(self):
        self.log = Log.get_log()
        self.logger = self.log.get_logger()
        self.db = None
        self.cursor = None

    def connectDB(self):
        try:
            self.db = pymysql.connect(**config)
            self.cursor = self.db.cursor()
            print("数据库连接成功")
        except ConnectionError as ex:
            self.logger.error(str(ex))

    def executeSQL(self, sql, params):
        self.connectDB()
        self.cursor.execute(sql, params)
        self.db.commit()
        return self.cursor

    def get_all(self, cursor):
        value = cursor.fetchall()
        return value

    def get_one(self, cursor):
        value = cursor.fetchone()
        return value

    def close_db(self):
        self.db.close()
        print("关闭数据库")

你可能感兴趣的:(#,Python)