zl程序教程

您现在的位置是:首页 >  工具

当前栏目

接口自动化测试框架实战:邮件、断言、Excel类的封装

2023-09-14 09:11:13 时间

邮件发送类封装

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib

# smtp地址,用户名,密码,接收邮件者,邮件标题,邮件内容,邮件附件
class SendEmail:
    def __init__(self, smtp_addr, username, password, recv,
                 title, content=None, file=None):
        self.smtp_addr = smtp_addr
        self.username = username
        self.password = password
        self.recv = recv
        self.title = title
        self.content = content
        self.file = file

    # 发送邮件方法
    def send_mail(self):
        # MIME
        msg = MIMEMultipart()
        # 初始化邮件信息
        msg.attach(MIMEText(self.content, _charset="utf-8"))
        msg["Subject"] = self.title
        msg["From"] = self.username
        msg["To"] = self.recv
        # 邮件附件
        # 判断是否附件
        if self.file:
            # MIMEText读取文件
            att = MIMEText(open(self.file).read())
            # 设置内容类型
            att["Content-Type"] = 'application/octet-stream'
            # 设置附件头
            att["Content-Disposition"] = 'attachment;filename="%s"' % self.file
            # 将内容附加到邮件主体中
            msg.attach(att)
        # 登录邮件服务器
        self.smtp = smtplib.SMTP(self.smtp_addr, port=25)
        self.smtp.login(self.username, self.password)
        # 发送邮件
        self.smtp.sendmail(self.username, self.recv, msg.as_string())


if __name__ == "__main__":
#password:GEBOVPBETWLBTLDK 这个是授权码,请使用自己的邮箱的。
    email = SendEmail("smtp.126.com", "xxxxx0115@126.com", "GEBOVPBETWLBTLDK",
                      'xxxx0115@126.com', "这是一个测试",content='测试报告的路径为xxx/yyy/zzz')
    email.send_mail()

授权码获取

效果如下

断言方法的封装

import json
class AssertUtil():

    def __init__(self):
        pass

    def assert_code(self, code, expected_code):
        """
        验证返回状态码
        """
        try:
            assert int(code) == int(expected_code)
            return True
        except:
            raise

    def assert_body(self, body, expected_body):
        """
        验证返回结果内容相等
        """
        try:
            assert body == expected_body
            return True
        except:
            self.log.error("body error,body is %s,expected_body is %s" % (body, expected_body))
            raise

    def assert_in_body(self, body, expected_body):
        """
        验证返回结果是否包含期望的结果
        """
        try:
            body = json.dumps(body)
            print(body)
            assert expected_body in body
            return True
        except:
            raise

Excel类的封装

import os
import xlrd

class SheetTypeError:
    pass

class ExcelReader:
    def __init__(self,excel_file,sheet_by):
        if os.path.exists(excel_file):
            self.excel_file = excel_file
            self.sheet_by = sheet_by
            self._data=list()
        else:
            raise  FileNotFoundError("文件不存在")

    def data(self):

        if not self._data:
            workbook = xlrd.open_workbook(self.excel_file)
            if type(self.sheet_by) not in [str,int]:
                raise SheetTypeError("请输入Int or Str")
            elif type(self.sheet_by) == int:
                sheet = workbook.sheet_by_index(self.sheet_by)
            elif type(self.sheet_by) == str:
                sheet = workbook.sheet_by_name(self.sheet_by)

            title = sheet.row_values(0)

            for col in range(1,sheet.nrows):
                col_value = sheet.row_values(col)

                self._data.append(dict(zip(title, col_value)))


        return self._data


if __name__ == "__main__":
    reader = ExcelReader("testdata.xlsx","xxxx测试")
    print(reader.data())
    

今天我们所有的类已经封装完了,是不是看着觉得太简单了。

中间有些东西我省略掉了,比如一下配置,我们可以写在yaml文件里面,这样我们在执行测试用例的时候,只需要修改一个位置就够了。

这些东西本来应该是昨天就应该弄出来的,无奈意志力不够,拖来拖去,拖到今天,有点遗憾。

好吧,今天就是这些。


学习资源分享

最后感谢每一个认真阅读我文章的人,看着粉丝一路的上涨和关注,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走

这些资料,对于目前想进阶【自动化测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴我走过了最艰难的路程,希望也能帮助到你!凡事要趁早,特别是技术行业,一定要提升技术功底。希望对大家有所帮助……【下方获取】