python接口自动化第三章

python接口自动化第三章,第1张

AutomatedTesting

第三节 common目录(邮件开关,封装邮件信息,封装日志)


文章目录
  • AutomatedTesting
  • 前言
  • 一、邮件开关
  • 二、封装邮件信息
  • 三、封装日志
  • 总结


前言

接口自动化 项目结构图

目录结构大部分都是常用目录
common - 公共方法
config - 配置文件信息
report - 日志/报告存放
runtest - 运行入口
testfile - 用例文件
tools - 工具箱
DDT - 数据驱动参数化
jenkins - 定时运行
实现:读取表格用例文件,jenkins定时运行,实现接口自动化,并做到数据与代码分离。


一、邮件开关

代码如下:

"""
@File    :  email_switch.py
@Time    :  2022/4/21
@Author  :  Mr_桐
"""

# -*- coding:utf-8 -*-
import sys
import os
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
from configobj import ConfigObj
from common import setting_path

# 邮件开关
def SwitchTrue():
    config = ConfigObj(setting_path.global_ini, encoding='UTF8')
    config['switch']['button'] = "True"
    config.write()


def SwitchFlase():
    config = ConfigObj(setting_path.global_ini, encoding='UTF8')
    config['switch']['button'] = "Flase"
    config.write()




二、封装邮件信息

代码如下:

"""
@File    :  send_email.py
@Time    :  2022/4/21
@Author  :  Mr_桐
"""

# -*- coding:utf-8 -*-
import smtplib
import sys
import os
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
from common import setting_path
from common.read_config import ReadConfig
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


current_time = setting_path.current_time
result_dir = setting_path.result_dir


def send_email():
    readconfig = ReadConfig()
    # 判断邮件开关是否为True
    if readconfig.get_config_str('switch', 'button') == 'True':
        email_conf = setting_path.email_ini  # email.ini路径
        readconfig.conf.read(email_conf, encoding='utf-8')
        # 发送邮箱服务器
        smtpserver = readconfig.get_config_str('email_msg', 'smtpserver')
        # 发送邮箱用户名密码
        user = readconfig.get_config_str('email_msg', 'user')
        password = readconfig.get_config_str('email_msg', 'password')
        # 发送和接收邮箱
        sender = readconfig.get_config_str('email_msg', 'sender')
        receives = readconfig.get_config_str('email_msg', 'receives')
        # 发送邮件主题和内容
        subject = current_time + readconfig.get_config_str('email_msg', 'subject')
        content = readconfig.get_config_str('email_msg', 'content')
        # 构造附件内容:定义附件,构造附件内容
        send_file = open(result_dir, 'rb').read()
        att = MIMEText(send_file, 'base64', 'utf-8')
        # 附件描述外层要用单引号
        	# 附件名称为中文时的写法
        att.add_header(
            "Content-Disposition",
            "attachment",
            filename=(
                "gbk",
                "",
                "接口自动化测试报告.html"))
        # 附件名称非中文时的写法
        # att["Content-Disposition"] = 'attachment; filename="test.html")'

        '''
        --------------------------------------------------------------------------------------------------
        '''

        # 构建发送与接收信息
        msgRoot = MIMEMultipart()  # 发送附件的方法定义为一个变量
        msgRoot.attach(MIMEText(content, 'html', 'utf-8'))  # 发送附件的方法中嵌套发送正文的方法
        msgRoot['subject'] = subject
        msgRoot['From'] = sender
        msgRoot['To'] = receives
        msgRoot.attach(att)  # 添加附件到正文中

        '''
        --------------------------------------------------------------------------------------------------
    
        '''
        # win环境
        # smtp = smtplib.SMTP(smtpserver)
        # linux环境中使用_SSl
        smtp = smtplib.SMTP_SSL(smtpserver, 465)
        # HELO 向服务器标识用户身份
        smtp.helo(smtpserver)
        # 服务器返回结果确认
        smtp.ehlo(smtpserver)
        # 登录邮箱服务器用户名和密码
        smtp.login(user, password)
        print("Start send email...")
        # receives 收件人需要用split(',')切割
        smtp.sendmail(sender, receives.split(','), msgRoot.as_string())
        smtp.quit()
        print("Send End!")
    else:
        print('No exception found, no mail sent')


三、封装日志

代码如下:

"""
@File    :  logger.py
@Time    :  2022/4/21
@Author  :  Mr_桐
"""

# -*- coding:utf-8 -*-
import sys
import os
import common.setting_path
import logging
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)


log_path = common.setting_path.log_dir


class LogInformation(object):

    def __init__(self):
        self.logname = log_path

    def get_log(self, level, msg):

        # 创建日志收集器
        logger = logging.getLogger()
        logger.setLevel('DEBUG')

        # 创建handler
        fh = logging.FileHandler(self.logname, 'a', encoding='utf-8')
        fh.setLevel('INFO')
        ch = logging.StreamHandler()
        ch.setLevel('INFO')

        # 定义handler的输出格式
        formatter = logging.Formatter(
            '%(asctime)s - %(filename)s - %(name)s - %(levelname)s - 日志信息: %(message)s')
        ch.setFormatter(formatter)
        fh.setFormatter(formatter)

        # 给logger添加handler
        logger.addHandler(fh)
        logger.addHandler(ch)

        if level == 'DEBUG':
            logger.debug(msg)
        elif level == 'INFO':
            logger.info(msg)
        elif level == 'WARNING':
            logger.warning(msg)
        elif level == 'ERROR':
            logger.error(msg)
        elif level == 'CRITICAL':
            logger.critical(msg)

        logger.removeHandler(fh)
        logger.removeHandler(ch)
        fh.close()

    def log_debug(self, msg):
        self.get_log('DEBUG', msg)

    def log_info(self, msg):
        self.get_log('INFO', msg)

    def log_warning(self, msg):
        self.get_log('WARNING', msg)

    def log_error(self, msg):
        self.get_log('ERROR', msg)

    def log_critical(self, msg):
        self.get_log('CRITICAL', msg)


总结

欢迎大家多交流,vx:-20206688

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/730808.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-27
下一篇 2022-04-27

发表评论

登录后才能评论

评论列表(0条)

保存