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

2022-07-04 21:19:19 浏览数 (1)

这是无量测试之道的第230篇原创

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

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

Part 1:以接口为示例

代码语言:javascript复制
# 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:测试数据示例

代码语言:javascript复制
{
    "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:邮箱发送方法实现

代码语言:javascript复制
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:邮件内容查看

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

end

0 人点赞