码迷,mamicode.com
首页 > 编程语言 > 详细

python+requests+unittest 搭建接口自动化测试框架(六)

时间:2020-11-04 17:49:23      阅读:20      评论:0      收藏:0      [点我收藏+]

标签:163邮箱   %s   OLE   handler   base   com   logger   div   logs   

封装几个常用的类 

configEmail.py

import os
import smtplib
import base64
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
 
 
class SendEmail(object):
    def __init__(self, username, passwd, recv, title, content,
                 file=None, ssl=False,
                 email_host=smtp.qq.com, port=25, ssl_port=465):
        self.username = username  # 用户名
        self.passwd = passwd  # 密码
        self.recv = recv  # 收件人,多个要传list [a@qq.com,b@qq.com]
        self.title = title  # 邮件标题
        self.content = content  # 邮件正文
        self.file = file  # 附件路径,如果不在当前目录下,要写绝对路径
        self.email_host = email_host  # smtp服务器地址
        self.port = port  # 普通端口
        self.ssl = ssl  # 是否安全链接
        self.ssl_port = ssl_port  # 安全链接端口
 
    def send_email(self):
        msg = MIMEMultipart()

        # 发送内容的对象
        if self.file:  # 处理附件的
            print(self.file)
            try:
                f = open(self.file, rb).read()
            except Exception as e:
                raise Exception(附件打不开!!!!)
        else:
            att = MIMEText(f, "base64", "utf-8")
            att["Content-Type"] = application/octet-stream
            file_name = os.path.split(self.file)[1] # 只取文件名,不取路径

            new_file_name = =?utf-8?b? + base64.b64encode(file_name.encode()).decode() + ?=
            # 这里是处理文件名为中文名的,必须这么写
            att["Content-Disposition"] = attachment; filename="%s" % (new_file_name)
            msg.attach(att)
        msg.attach(MIMEText(self.content))  # 邮件正文的内容
        msg[Subject] = self.title  # 邮件主题
        msg[From] = self.username  # 发送者账号
        msg[To] = ,.join(self.recv)  # 接收者账号列表
        if self.ssl:
            self.smtp = smtplib.SMTP_SSL(self.email_host, port=self.ssl_port)
        else:
            self.smtp = smtplib.SMTP(self.email_host, port=self.port)
        # 发送邮件服务器的对象
        self.smtp.login(self.username, self.passwd)
        self.smtp.sendmail(self.username, self.recv, msg.as_string())

        self.smtp.quit()
 


if __name__ == __main__:
 
    m = SendEmail(
        username=xxxxx@qq.com,
        passwd=gsvrazeeeexbbaldbgbj,  #授权码,还要在163邮箱里添加350375024@qq.com为白名单
        recv=[ssssss@163.com],
        title=2封信,
        content=测试发送邮件,
        file=d:/test_interface/report/report.html,
        ssl=False
    )
    m.send_email()

对requests进行二次封装 configHttp.py

import json
import requests
import os
session = requests.session()
cookie_file = os.path.join(os.getcwd()+/cookies.txt)
cookies_txt = open(cookie_file, r)
cookies_dict = json.loads(cookies_txt.read())

class RunMain(object):

    def send_get(self,url,data=None,header=None,cookie=None):
       
        if header != None:
            res = session.get(url=url,params=data,headers=header,verify=False).json()
            if cookie != None:
                res = session.get(url=url,params=data,headers=header,cookies=cookie,verify=False).json()
        else:
            res = session.get(url=url,params=data,verify=False).json()
            if cookie != None:
                res = session.get(url=url,params=data,cookies=cookie,verify=False).json()

        return res
    
    def send_post(self,url,data,header=None,cookie=None):
        if header != None:
            res = session.post(url=url,data=data,headers=header,verify=False).json()
            if cookie != None:
                res = session.get(url=url,data=data,headers=header,cookies=cookie,verify=False).json()
        else:
            res = session.post(url=url,data=data,verify=False).json()
            if cookie != None:
                res = session.get(url=url,data=data,cookies=cookie,verify=False).json()
        return res

    def run_main(self,method,url,data=None,header=None,cookie=None):
        if method.lower() == post:
            result = self.send_post(url,data,header,cookie)
        elif method.lower() == get:
            result = self.send_get(url,data,header,cookie)
        else:
            result = method error
        return result


# if __name__ == __main__: 
#     result1 = RunMain().run_main(post, http://127.0.0.1:8888/login, {name: xiaoming,pwd:111})
#     result2 = RunMain().run_main(get, http://127.0.0.1:8888/login, {name: xiaoming,pwd:1111})
#     print(result2)

日志类的封装  log.py

import os
import logging
from logging.handlers import TimedRotatingFileHandler

log_path = os.path.join(os.getcwd()+/result)  # 存放log文件的路径
 
 
class Logger(object):
    def __init__(self, logger_name=logs…):
        self.logger = logging.getLogger(logger_name)
        logging.root.setLevel(logging.NOTSET)
        self.log_file_name = logs  # 日志文件的名称
        self.backup_count = 5  # 最多存放日志的数量
        # 日志输出级别
        self.console_output_level = WARNING
        self.file_output_level = DEBUG
        # 日志输出格式
        self.formatter = logging.Formatter(%(asctime)s - %(name)s - %(levelname)s - %(message)s)
 
    def get_logger(self):
        """在logger中添加日志句柄并返回,如果logger已有句柄,则直接返回"""
        if not self.logger.handlers:  # 避免重复日志
            console_handler = logging.StreamHandler()
            console_handler.setFormatter(self.formatter)
            console_handler.setLevel(self.console_output_level)
            self.logger.addHandler(console_handler)
 
            # 每天重新创建一个日志文件,最多保留backup_count份
            file_handler = TimedRotatingFileHandler(filename=os.path.join(log_path, self.log_file_name), when=D,
                                                    interval=1, backupCount=self.backup_count, delay=True,
                                                    encoding=utf-8)
            file_handler.setFormatter(self.formatter)
            file_handler.setLevel(self.file_output_level)
            self.logger.addHandler(file_handler)
        return self.logger
 
 
if __name__ == __main__:
    Logger().get_logger()

 

python+requests+unittest 搭建接口自动化测试框架(六)

标签:163邮箱   %s   OLE   handler   base   com   logger   div   logs   

原文地址:https://www.cnblogs.com/huaniaoyuchong/p/13920367.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!