Selenium + Python 自动化测试14(发送报告)

        我们的目标是:按照这一套资料学习下来,大家可以独立完成自动化测试的任务。

上一篇我们讨论了使用HTMLTestRunner 生成HTML报告的方法。

         本篇文章我们接着讲生成HTML报告是否可以自动邮件发送出去,提高我们测试报告的及时性,方便性,避免自己手动操作发送。

1、SMTP介绍

         SMTP: simple mail transfer protocol  简单邮件传输协议。是一组由源地址到目的地址传送邮件的规则。

         python 的smtplib 模块提供一个很方便的路径用于发送电子邮件。它是对SMTP进行封装而来。我们可以SMTP对象的sendmail 来发送邮件。可以先使用help()查看使用方式:

>>> from smtplib import SMTP

>>> help(SMTP)

connect(self, host='localhost', port=0, source_address=None)

 |      Connect to a host on a given port.

 |     

 |      If the hostname ends with a colon (`:') followed by a number, and

 |      there is no port specified, that suffix will be stripped off and the

 |      number interpreted as the port number to use.

 |     

 |      Note: This method is automatically invoked by __init__, if a host is

 |      specified during instantiation.

login(self, user, password, *, initial_response_ok=True)

 |      Log in on an SMTP server that requires authentication.

 |     

 |      The arguments are:

 |          - user:         The user name to authenticate with.

 |          - password:     The password for the authentication.

 |     

 |      Keyword arguments:

 |          - initial_response_ok: Allow sending the RFC 4954 initial-response

 |            to the AUTH command, if the authentication methods supports it.

 |     

 |      If there has been no previous EHLO or HELO command this session, this

 |      method tries ESMTP EHLO first.

 |     

 |      This method will return normally if the authentication was successful.

 |     

 |      This method may raise the following exceptions:

 |     

 |       SMTPHeloError            The server didn't reply properly to

 |                                the helo greeting.

 |       SMTPAuthenticationError  The server didn't accept the username/

 |                                password combination.

 |       SMTPNotSupportedError    The AUTH command is not supported by the

 |                                server.

 |       SMTPException            No suitable authentication method was

 |                                found.

sendmail(self, from_addr, to_addrs, msg, mail_options=[], rcpt_options=[])

 |      This command performs an entire mail transaction.

 |     

 |      The arguments are:

 |          - from_addr    : The address sending this mail.

 |          - to_addrs     : A list of addresses to send this mail to.  A bare

 |                           string will be treated as a list with 1 address.

 |          - msg          : The message to send.

 |          - mail_options : List of ESMTP options (such as 8bitmime) for the

 |                           mail command.

 |          - rcpt_options : List of ESMTP options (such as DSN commands) for

 |                           all the rcpt commands.

1)connect(host,port)

host:指定连接的邮箱服务器

port: 指定连接的邮箱服务器端口号

2)login(user,password)

登录邮箱的用户和密码

3)sendmail(from_addr,to_addr,msg...)

from_addr:邮件发送者地址

to_addr:邮件接受者邮箱

msg:发送的消息

2、发送报告到指定邮箱

1)编写执行侧用例集的代码

这部分参考之前的,我们上一节已经讨论过的:

#定义测试用例集的目录

test_dir = './'

report_dir = './report'  #测试报告地址

discover = unittest.defaultTestLoader.discover(test_dir,pattern="test_*.py")#所有要执行的文件



if __name__ == '__main__':

    now = time.strftime("%Y-%m-%d %H_%M_%S")   #当前时间,格式是年月日时分秒

    file_name report_dir+ '/' + now + 'result.html'   #报告名称,加上当前时间避免重复

    fp = open(file_name,'wb')      #打开报告文件,读写权限



    runner = HTMLTestRunner(stream=fp,title="Swag Labs 网站测试报告",description="用例测试情况:")#HTML报告设置

    runner.run(discover)  #执行测试案例

    fp.close()   #关闭报告文件

2、编写发送部分

编写对应的发送邮件的函数。

from email.mime.text import MIMEText

from email.header import Header



#定义发送邮件的函数

def send_report_by_mail(file_name):

    f=open(file_name,'rb'#打开文件

    report_body=f.read()

    f.close()



    msg=MIMEText(report_body,'html','utf-8') #内容

    msg['Subject']= Header('Swag Labs 网站测试报','utf-8')



    smtp = smtplib.SMTP()

    smtp.connect('smtp.163.com') #发送邮箱服务器

    smtp.login('用户名@163.com','密码')

    smtp.sendmail('用户名@163.com','接收邮件用户名@163.com',msg.as_string())

    smtp.quit()

    print("报告已通过邮件发送")



#定义测试用例集的目录

test_dir = './'

report_dir = './report'  #测试报告地址

discover = unittest.defaultTestLoader.discover(test_dir,pattern="test_*.py")#所有要执行的文件



if __name__ == '__main__':

    now = time.strftime("%Y-%m-%d %H_%M_%S")   #当前时间,格式是年月日时分秒

    file_name report_dir+ '/' + now + 'result.html'   #报告名称,加上当前时间避免重复

    fp = open(file_name,'wb')      #打开报告文件,读写权限



    runner = HTMLTestRunner(stream=fp,title="Swag Labs 网站测试报告",description="用例测试情况:")#HTML报告设置

    runner.run(discover)  #执行测试案例

    fp.close()   #关闭报告文件



    send_report_by_mail(file_name)   #发送报告

如下图所示发送邮件成功:

Selenium + Python 自动化测试14(发送报告)_第1张图片

收到了邮件如下:

Selenium + Python 自动化测试14(发送报告)_第2张图片

今天就先学习到这里。

每天进步一点点,加油!

你可能感兴趣的:(UI,自动化测试,selenium,python,模块测试,测试工具,功能测试)