python自动化测试(1)——编写python装饰器实现报错函数自动发送邮件

主要实现功能如下:

装饰器,可以自定义邮件标题及计算时间

logging模块封装,记录当前的执行情况

自动发送邮件功能。

import smtplib
from email.mime.text import MIMEText
from email.header import Header
import time, traceback
try:
    from config import mail_user, mail_pass, sender, receivers, mail_host
except:
    raise("please create file and name is 'config.py', then reference comment setting each variable!")
"""
comment:
    mail_user, mail_pass, sender, receivers, mail_host is your personal data. so, I move it to a config.py and the file is ban to push github or gitlab or svn.
    mail_host = "smtp.163.com" set email.server. if your email is qq, replace 163 to qq.   # 设置服务器, 这个如果是qq, 就把163改成qq即可。
    mail_user = "XXXXXX@163.com"  # your email account or login name.
    mail_pass = "password"  # password, sometimes not set password, some email server need your client Authorization code(客户端授权码)
    sender = 'XXXXXX@163.com'   # 发送者 sender Email
    receivers = ['XXXXXX@163.com']  # receivers email,you can set more and use ',' to split.
"""
from functools import wraps
import logging
t = lambda:time.time()
# logging config, the more logging config information, you can learn from "https://www.cnblogs.com/yyds/p/6901864.html"
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"
# this not config filename='my.log'.
logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT, datefmt=DATE_FORMAT)
# used to sendEmail
def sendEmail(message, subject):
    message = MIMEText(message, 'plain', 'utf-8')
    message['Subject'] = Header(subject, 'utf-8')
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)  # 25 为 SMTP 端口号
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())

"""
python decorator, send error email when catched error.
taskname: the email Title.
t() equal to time.time()
@wraps is used to save the function name and docstring. it's not necessary.
traceback.format_exc() is used to collect error message one by one.
the more decorator acknowledge you can search from google or baidu.
"""
def errorSendEmail(taskname):
    def functionwraper(function):
        @wraps(function)
        def wraper(*args, **kwargs):
            try:
                start_time = t()
                function(*args,**kwargs)
                end_time = t()
                logging.info("{} used {}s".format(function.__name__, end_time - start_time))
                sendEmail("succsess", taskname)
            except Exception as e:
                errorMessage = traceback.format_exc()
                logging.error(errorMessage)
                # sendEmail(errorMessage, taskname)
        return wraper
    return functionwraper


if __name__ == "__main__":
    @errorSendEmail("自动化测试信息")
    def testCount(l):
        a = [i for i in range(l)]
        # print(a)
        # print(1/0)
    testCount(1000000)

这里没有用到测试用例, 举得例子也相比以往的装饰器更有难度,这里testCount里面有两个测试,一个是正常创建一个数组。另一个是1/0问题的邮件发送。相信你也能通过阅读code体会到。后面会考虑针对测试用例的使用,接口测试,使用框架测试写一系列文章。后续的文章也会尽可能的用英文做注释,虽然能看懂,但是自己写问题还是挺多。

发布了199 篇原创文章 · 获赞 62 · 访问量 21万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 深蓝海洋 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览