• Python+Pytest+Allure+Json 最全Api自动化框架之邮件发送功能


    Python+Pytest+Allure+Json 最全Api自动化框架 分享后,受到许多小伙伴的关注,最近一直在完善这个 API 自动化框架的功能,准备在框架成熟后分享给更多需要的小伙伴们。

    今日分享的主题是:Python+Pytest+Allure+Json 的 API 自动化框架的邮件发送功能的完善。该邮件发送功能的实现分为以下四个部分。

    Part 1:以接口为示例

    # coding:utf-8
    import pytest
    import allure
    import os
    import subprocess
    
    from commons.HandleJson import handle_json
    import commons.configs as config
    from commons.DBConn import DBConn
    from commons.log import logger
    from commons.HandleCompare import compareTest
    from commons.ApiRequest import apiRequest
    from SendEmail import send_mail
    
    baseFileName = '../testdata/post_user_login_data.json'
    testCaseData = handle_json.load_json(baseFileName)
    
    
    @pytest.fixture()
    def executeSql():
        logger.info("execute the sql")
    
    # @pytest.mark.run(order=1)
    @pytest.mark.usefixtures('executeSql')
    @allure.feature('用户登录')
    class TestUserLogin():
        @allure.title('用户登录接口')
        @allure.testcase('测试地址:http://127.0.0.1:5055')
        @allure.description('通过接口进行用户登录')
        @allure.step("第一步:用户登录")
        @allure.severity(allure.severity_level.BLOCKER)
        @pytest.mark.parametrize('case_data', testCaseData['testcase'])
        def testUserLogin(self, case_data):
            api_response = apiRequest.api_request(config.apiurl, testCaseData, case_data)
            for case_validate in case_data['validate']:
                logger.info('断言期望相关参数:check:{},comparator:{},expect:{}'.format(case_validate['check'],case_validate['comparator'],case_validate['expect']))
                compareTest.compare_Assert(api_response, case_validate['check'], case_validate['comparator'],case_validate['expect'])
    
    if __name__ == "__main__":
        # 生成配置信息 "-s 代表可以将执行成功的案例日志打印出来 ; -q+文件执行路径 代表只需要执行的文件"
        # pytest.main(['-s', '-v', 'TestGetPropertyType.py','-q'])
        pytest.main(['-s', '-v', 'TestUserLogin.py', '-q', '--alluredir', 'report'])
        os.system('if exist "report/htmls" (rd /s/q report/htmls)')
        os.system('allure generate report -o report/htmls --clean')
        send_mail("Liang.Wu@test.com", "api测试报告", "测试报告的访问地址为:http://desktop-fe56ou7:8881/index.html<br> 请在收到邮件后三十分钟内查看!")
        os.system('allure open -h 10.8.31.61 -p 8881 report/htmls')

    Part 2:测试数据示例

    {
        "config":{
            "apiname":"user login",
            "url":"/login",
            "method":"POST",
            "headers":{
                "Content-Type":"application/json"
            },
            "cookies":{}
        },
        "testcase":[
            {
                "name":"case1",
                "params":{
                    "username":"root",
                    "password":"root"
                },
                "validate":[
                    {
                        "check":"message",
                        "comparator":"eq",
                        "expect":"success"
                    },
                    {
                        "check":"code",
                        "comparator":"eq",
                        "expect": 200
                    }
                ]
            },
            {
                "name":"case2",
                "params":{
                    "username":"admin",
                    "password":"1234567"
                },
                "validate":[
                    {
                        "check":"message",
                        "comparator":"eq",
                        "expect":"fail"
                    },
                     {
                        "check":"code",
                        "comparator":"eq",
                        "expect": 401
                    }
                ]
            },
             {
                "name":"case3",
                "params":{
                    "username":"root",
                    "password":"1234567"
                },
                "validate":[
                    {
                        "check":"message",
                        "comparator":"eq",
                        "expect":"fail"
                    },
                     {
                        "check":"code",
                        "comparator":"eq",
                        "expect": 401
                    }
                ]
            },
            {
                "name":"case3",
                "params":{
                    "username":"roots",
                    "password":"root"
                },
                "validate":[
                    {
                        "check":"message",
                        "comparator":"eq",
                        "expect":"fail"
                    },
                     {
                        "check":"code",
                        "comparator":"eq",
                        "expect": 401
                    }
                ]
            }
        ]
    }

    Part 3:邮箱发送方法实现

    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    import smtplib
    
    def send_mail(receivers, title, content):
        sender = 'qa.notice@test.com'
        print(receivers)
        mailto = receivers.split(",")
        print(mailto)
        try:
            msg = MIMEMultipart()
            msg['Subject'] = title
            to_user = ",".join(mailto)
            print("receivers...", to_user)
            msg['to'] = to_user
            msg['From'] = sender
            body = MIMEText(content, 'html', 'utf-8')
            msg.attach(body)
            smtp = smtplib.SMTP('smtp.office360.com', 587)
            smtp.starttls()
            smtp.login("qa.notice@test.com", "rdvkmzbckyj")
            smtp.sendmail(sender, mailto, msg.as_string())
            print("send success")
            smtp.quit()
        except Exception as e:
            print("send failed is %s",e)

    Part 4:邮件内容查看

    如下图所示,点击邮件中的测试报告链接即可查看。

    欢迎关注【无量测试之道】公众号,回复【领取资源】
    Python编程学习资源干货、
    Python+Appium框架APP的UI自动化、
    Python+Selenium框架Web的UI自动化、
    Python+Unittest框架API自动化、
    资源和代码 免费送啦~
    文章下方有公众号二维码,可直接微信扫一扫关注即可。

    备注:我的个人公众号已正式开通,致力于测试技术的分享,包含:大数据测试、功能测试,测试开发,API接口自动化、测试运维、UI自动化测试等,微信搜索公众号:“无量测试之道”,或扫描下方二维码:

    添加关注,让我们一起共同成长!

  • 相关阅读:
    169_Majority Element
    171_Excel Sheet Column Number
    217_Contains Duplicate
    242_Valid Anagram
    【findIndex】根据数组对象某一元素的id,找到此元素在数组所在的位置
    【鼠标右击组件】v-contextmenu
    【 拖拽组件】基于 Sortable.js 的 Vue 拖拽组件。 访问地址:Vue.Draggable
    【vue-markdown编辑器】vue-markdown 组件github地址
    mac下如何制作windows启动盘
    【vue webstorm】WebStorm Vue代码格式错误
  • 原文地址:https://www.cnblogs.com/Wu13241454771/p/15157710.html
Copyright © 2020-2023  润新知