Ejemplo n.º 1
0
    def getReportAttributes(self, result):
        """
        Return report attributes as a list of (name, value).
        Override this to add custom attributes.
        """
        startTime = str(self.startTime)[:19]
        duration = str(self.stopTime - self.startTime)
        status = []
        count = {
            'restult': '',
            'sum': 0,
            'ok': 0,
            'fail': 0,
            'error': 0,
            'error_1': 0,
            'date': ''
        }
        status.append(
            '共 %s 条接口用例' %
            (result.success_count + result.failure_count + result.error_count))
        count[
            'sum'] = result.success_count + result.failure_count + result.error_count
        if result.success_count:
            status.append('通过 %s 条' % result.success_count)
            count['ok'] = result.success_count
        if result.failure_count:
            status.append('失败 %s 条' % result.failure_count)
            count['fail'] = result.failure_count
        if result.error_count:
            status.append('错误 %s 条' % result.error_count)
            count['error'] = result.error_count
            count['error_1'] = str(
                "%.2f" % (float(result.error_count) /
                          float(result.success_count + result.failure_count +
                                result.error_count) * 100))
        if status:
            status = ','.join(status)
            self.passrate = str(
                "%.2f%%" % (float(result.success_count) /
                            float(result.success_count + result.failure_count +
                                  result.error_count) * 100))
        else:
            status = 'none'
        count["restult"] = str({
            'testname': self.tester,
            'time': startTime,
            'sumtime': duration,
            'testresult': status,
            'tonggl': self.passrate
        })
        count['date'] = now
        gmi.getMysqlInfo(NC.config).Instert_mysql([count])

        return [
            (u'测试人员', self.tester),
            (u'开始时间', startTime),
            (u'合计耗时', duration),
            (u'本次结果', status + ",通过率= " + self.passrate),
        ]
Ejemplo n.º 2
0
 def _generate_chart(self, result):
     redata = gmi.getMysqlInfo(NC.config).get_mysql_info_test(
         "select * from " + gmi.testtable + " ORDER BY date DESC LIMIT 10;",
         1)
     chart = self.ECHARTS_SCRIPT % dict(
         Pass=str(redata['ok']),
         fail=str(redata['fail']),
         error=str(redata['error']),
         error_1=str(redata['error_1']),
     )
     return chart
Ejemplo n.º 3
0
    def mysql_Casedata(self, mode=0):
        data_list = []
        casedata = gmi.getMysqlInfo(NC.config).auto_testcase(self.version)
        if mode == 1:
            loger.info("------------版本指定用例集------------")
            pass
        elif mode == 2:
            loger.info("------------版本区间用例集------------")
            pass
        else:
            loger.info("------------版本全部用例集------------")
            for i in range(len(casedata)):
                id = casedata[i]["id"]
                method = casedata[i]["method"]
                cases_name = casedata[i]["cases_name"]
                url = url_1 + casedata[i]["url"]
                data = eval(casedata[i]["data"])
                sql = eval(casedata[i]["sql"])
                code = casedata[i]["code"]
                dict = {'id': id, 'case_name': cases_name, 'url': url, 'method': method, 'sql': sql, 'data': data,
                        'code': code}
                data_list.append(dict)

        return data_list
Ejemplo n.º 4
0
def run(version):
    global ver
    ver = version
    print(ver)
    logger = Log('main', NC.log_path)
    # 去随机数赋值图片名称
    name = str(random.randint(0, 18))

    from interface_auto_cases.public import Unit_test
    suite = unittest.TestSuite()  # 实例
    loader = unittest.TestLoader()
    # 测试模块
    suite.addTest(loader.loadTestsFromModule(Unit_test))

    now = time.strftime('%Y-%m-%d_%H_%M_%S')
    file_path = NC.html_path + '/' + now + '.html'

    import interface_auto_cases.HTMLTestRunner_zgh as htr
    with open(file_path, 'wb+') as file:
        # 实例化测试报告运行
        runner = htr.HTMLTestRunner(stream=file, verbosity=2, tester='质量保障部—章广华',
                                    title='AI虚拟机器人接口自动化测试报告【Python】',
                                    description='该测试报告仅体现某接口请求以及参数值验证情况。')
        # 传入测试运行对象
        runner.run(suite)
    import interface_auto_cases.public.get_mysql_info as gmi
    sqlinfo = "select * from " + gmi.testtable + " ORDER BY date DESC LIMIT 10;"
    text = eval(gmi.getMysqlInfo(NC.config).get_mysql_info_test(sqlinfo, 1)['restult'])
    logger.info('获取表单内容成功:%s' % text)
    # 钉钉智能消息机器人AI虚拟机器人
    # url='https://oapi.dingtalk.com/robot/send?access_token=746c8737b87ebb1d394e8790d272846789a73fc263c284d1de43c21162fe642e'
    # url='https://oapi.dingtalk.com/robot/send?access_token=8a41242fd2858c2614077a9f74b503623c0cf87b5db7bdb35f3f983b3de52f1d'
    # 测试地址
    # url='https://oapi.dingtalk.com/robot/send?access_token=9abe37c6a640422cb85c9a877bb026b0b9029378890c5f14fcc106be9ab5725e'
    headers = {"Content-Type": "application/json"}
    data = {
        "msgtype": "markdown",
        "markdown": {
            "title": "AI虚拟机器人接口自动化测试报告",
            "text": "#### AI虚拟机器人接口自动化测试报告【V0.3.5】\n" +
                    "> 【测试人员】:" + str(text['testname']) + "\n" +
                    "\n> 【开始时间】:" + str(text['time']) + "\n" +
                    "\n> 【合计耗时】:" + str(text['sumtime']) + "\n" +
                    "\n> 【本次结果】:" + str(text['testresult']) + "\n" +
                    "\n> 【通过率】:" + str(text['tonggl']) + "\n" +
                    "> ![screenshot](http://47.111.14.23:8500/" + name + ".jpg)\n" +
                    "> ###### " + now[0:10] + " 发布 [在线查看报告详情](http://47.111.14.23:8500/) \n"
        },
        "at": {
            "atMobiles": [
                "18267199586",
                "13111595333"
            ],
            "isAtAll": "false"
        }
    }
    # request = requests.post(url, json=data, headers=headers).json()
    # logger.info("钉钉机器人消息请求内容%s" % data)
    # logger.info('钉钉机器人消息请求成功%s' % request)

    shutil.copyfile(NC.html_path + '/' + now + '.html', NC.html_path + '/report/index.html')
    # 当前时间,邮件对象
    from interface_auto_cases.public.smtp import massageMail
    # name=['*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**']
    # name=['*****@*****.**',]
    # for i in range(len(name)):
    #     try:
    #         massageMail().Message(now,name[i])
    #         logger.info('发送邮箱为:%s' % name[i])
    #     except:
    #         continue
    logger.info('本次Python接口自动化框架执行完毕!%s' % time.strftime('%Y-%m-%d %H:%M:%S'))
    return text
Ejemplo n.º 5
0
# @Author  : zgh
# @Email   : [email protected]
# @File    : smtp.py
# @Software: PyCharm

import smtplib
import configparser
import time
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from interface_auto_cases.public.logger import Log
from interface_auto_cases.public.get_mysql_info import getMysqlInfo
import interface_auto_cases.conf.NacosConfig as NC

gmi = getMysqlInfo(NC.config)
logger = Log('smtp', NC.log_path)


class massageMail:
    def read_config(self, conf_path, section, option):
        tt = configparser.ConfigParser()
        tt.read(conf_path, encoding='utf-8')
        result = eval(tt.get(
            section,
            option,
        ))
        return result

    def Message(
        self,
Ejemplo n.º 6
0
def run(version):
    global ver
    ver = version
    print(ver)
    logger = Log('main', NC.log_path)
    # 去随机数赋值图片名称
    name = str(random.randint(0, 30))

    from interface_auto_cases.public import Unit_test
    suite = unittest.TestSuite()  # 实例
    loader = unittest.TestLoader()
    # 测试模块
    suite.addTest(loader.loadTestsFromModule(Unit_test))

    now = time.strftime('%Y-%m-%d_%H_%M_%S')
    file_path = NC.html_path + '/' + now + '.html'

    import interface_auto_cases.HTMLTestRunner_zgh as htr
    with open(file_path, 'wb+') as file:
        # 实例化测试报告运行
        runner = htr.HTMLTestRunner(stream=file,
                                    verbosity=2,
                                    tester='质量保障部—章广华',
                                    title='项目质量控制数据统计【Python】',
                                    description='该测试报告仅体现某接口请求以及参数值验证情况。')
        # 传入测试运行对象
        runner.run(suite)
    import interface_auto_cases.public.get_mysql_info as gmi
    sqlinfo = "select * from " + gmi.testtable + " ORDER BY date DESC LIMIT 10;"
    text = eval(
        gmi.getMysqlInfo(NC.config).get_mysql_info_test(sqlinfo, 1)['restult'])
    logger.info('获取表单内容成功:%s' % text)
    # 钉钉智能消息机器人项目质量报告机器人
    # url='https://oapi.dingtalk.com/robot/send?access_token=6128ef1568799123702f701123c30b2c19f953c1f0a028b0c1a0598ccbf94481'
    # 测试地址
    # url='https://oapi.dingtalk.com/robot/send?access_token=9abe37c6a640422cb85c9a877bb026b0b9029378890c5f14fcc106be9ab5725e'
    headers = {"Content-Type": "application/json"}

    data = {
        "msgtype": "markdown",
        "markdown": {
            "title":
            "项目质量数据统计报告",
            "text":
            "#### 项目质量数据统计报告【test】\n" + "> 【项目个数】:{}".format(6) + "\n" +
            "\n> 【共计用例】:{}".format(3403) + "\n" +
            "\n> 【成功率】:{}".format('87%') + "\n" +
            "\n> 【失败率】:{}".format('10%') + "\n" + "\n> 【错误率】:{}".format('3%') +
            "\n" +
            "> ![screenshot](http://autotest-report.oss-cn-hangzhou.aliyuncs.com/report/"
            + name + ".jpg)\n" + "> ###### " + now[0:10] +
            " 发布 [在线查看报告详情](http://172.16.25.46:82/admin/home/) \n"
        },
        "at": {
            "atMobiles": [
                "17681829051",
            ],
            "isAtAll": "false"
        }
    }
    # request = requests.post(url, json=data, headers=headers).json()
    # logger.info("钉钉机器人消息请求内容%s" % data)
    # logger.info('钉钉机器人消息请求成功%s' % request)

    shutil.copyfile(NC.html_path + '/' + now + '.html',
                    NC.html_path + '/report/index.html')
    # 当前时间,邮件对象
    from interface_auto_cases.public.smtp import massageMail
    # name=['*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**']
    # name=['*****@*****.**',]
    # for i in range(len(name)):
    #     try:
    #         massageMail().Message(now,name[i])
    #         logger.info('发送邮箱为:%s' % name[i])
    #     except:
    #         continue
    logger.info('本次Python接口自动化框架执行完毕!%s' % time.strftime('%Y-%m-%d %H:%M:%S'))
    return text
Ejemplo n.º 7
0
 def write_Mysql(self, i, dict):
     casedata = gmi.getMysqlInfo(NC.config).auto_testcase(self.version)
Ejemplo n.º 8
0
    def httpGet(self, url, method, data, sql):
        from interface_auto_cases.public.get_mysql_info import getMysqlInfo
        global request
        headers = {
            "Host":
            "47.110.131.231",
            "Connection":
            "keep-alive",
            "Origin":
            "http://47.110.131.231",
            "X-TraceId":
            "c502d7c0-5c48-11ea-98c2-1b2105b568ad",
            "Referer":
            "http://47.110.131.231/customerService/SystemManagement/Online",
        }
        header = {
            "Host":
            "47.110.131.231",
            "Connection":
            "keep-alive",
            "Origin":
            "http://47.110.131.231",
            "X-TraceId":
            "b2486a20-a9d1-11e9-a2b4-5fa2b013c14c",
            "Referer":
            "http://47.110.131.231/customerService/SystemManagement/Online",
        }
        oo = get_login_cookie()
        pp = get_login_khcookie()
        headers["Cookie"] = 's_authorization=' + oo["s_authorization"]
        header["Cookie"] = 'v_authorization=' + pp["v_authorization"]
        # headers["Content-Type"] = "application/json"
        logger.info("当前客服headers配置:%s" % headers)
        logger.info("当前客客户header配置:%s" % header)

        if method == 'GET':
            logger.info('现在开始进行get请求')
            request = requests.get(url, data, headers=headers).json()
        elif method == 'GET_kh':
            logger.info('现在开始进行GET_kh请求')
            if data['1'] == 1:
                sql_result = getMysqlInfo(NC.config).get_mysql_info(
                    sql['my_sql'], sql['condition'], sql['code'])
                url1 = url % str(sql_result[sql['1']])
                logger.info('现在开始进行数据库请求获取:{},当前请求地址:{}'.format(
                    sql_result, url1))
                request = requests.get(url1, data, headers=header).json()
            elif data['1'] == 2:
                sql_result = getMysqlInfo(NC.config).get_mysql_info(
                    sql['my_sql'], sql['condition'], sql['code'])
                url1 = url % str(sql_result[sql['1']])
                logger.info('现在开始进行数据库请求获取:{},当前请求地址:{}'.format(
                    sql_result, url1))
                request = requests.get(url1, data, headers=headers).json()
            elif data['1'] == 0:
                # print(header)
                request = requests.get(url, headers=header).json()
            else:
                request = requests.get(url, data, headers=headers).json()

        elif method == 'POST_kh':
            logger.info('现在开始进行POST_kh请求')
            data['from'] = pp["visitor_id"]
            print(data)
            # body格式
            request = requests.post(url, json=data, headers=header).json()
            request['code'] = request['data']['message']

        elif method == 'POST':
            logger.info('现在开始进行post请求')
            # body格式
            request = requests.post(url, json=data, headers=headers).json()

        elif method == 'POST_file':
            logger.info('现在开始进行post_file请求')
            path = Allpath.project_path + "/request_file/" + sql['filename']
            print(sql['name'], headers, path)
            files = {sql['name']: (sql['filename'], open(path, 'rb'))}
            # body格式
            request = requests.post(url,
                                    data=data,
                                    files=files,
                                    headers=headers).json()

        elif method == 'POST1':
            logger.info('现在开始进行post1请求')
            # 参数格式
            request = requests.post(url, data, headers=headers).json()
            print(headers)

        elif method == 'POST2':
            logger.info('现在开始进行post2请求')
            # 参数格式
            request = requests.post(url, headers).json()

        elif method == 'POST_word':
            logger.info('现在开始进行post_word请求')
            request = {}
            # 参数格式,返回的是字符串格式
            text = requests.post(url, data, headers).text
            request['code'] = text

        elif method == 'POST_del':
            logger.info('现在开始进行post_del请求')
            sql_result = getMysqlInfo(NC.config).get_mysql_info(
                sql['my_sql'], sql['condition'], sql['code'])
            logger.info('post删除数据库返回:' + str(sql_result))
            data['id'] = sql_result[0]
            # body格式
            request = requests.post(url, json=data, headers=headers).json()

        elif method == 'PUT':
            # 0:上下线单独处理;1:正常put;2:质检规则关闭处理;3、获取多个字段值json格式;4、获取多个字段值参数格式
            logger.info('现在开始进行put请求')
            headers["Content-Type"] = "application/json"
            # 2019年7月23日 16:17:38新增cookie不变循环处理方法
            if sql['1'] == 0:
                request1 = requests.put(
                    'http://47.110.131.231/v1/tenants/_1NTMWLA/staffs/s_819aee8ed8554b9f82e8d6302c8d2411/online',
                    data='{"status":"online"}',
                    headers=headers).json()
                # print(request1)
                if 'test' in request1['data']:
                    oo["o_authorization"] = request1['data']['test']
                    # print(oo)
                # 新增cookie中o_authorization状态保存
                headers["Cookie"] = 's_authorization=' + oo[
                    "s_authorization"] + ';o_authorization=' + oo[
                        "o_authorization"]
                request = requests.put(url,
                                       data=json.dumps(data),
                                       headers=headers).json()
                time.sleep(0.3)
                # 退出
                get_logout('http://47.110.131.231/v1/tenants/_1NTMWLA/logout',
                           '', headers)
            elif sql['1'] == 2:
                sql_result = getMysqlInfo(NC.config).get_mysql_info(
                    sql['my_sql'], sql['condition'], sql['code'])
                for i in range(len(sql_result)):
                    url_d = url + str(sql_result[i]["rule_id"])
                    request = requests.put(url_d, headers=headers).json()
                    logger.info("规则ID:%s关闭处理成功!" % sql_result[i]["rule_id"])
                logger.info(sql['condition'] + "关闭处理成功!")
            elif sql['1'] == 3:
                sql_result = getMysqlInfo(NC.config).get_mysql_info(
                    sql['my_sql'], sql['condition'], sql['code'])
                logger.info("再分配结果ID获取成功!{}".format(sql_result))
                url_d = url.format(sql_result[0], sql_result[3])
                print(url_d)
                request = requests.put(url_d, json=data,
                                       headers=headers).json()
            elif sql['1'] == 4:
                headers.pop('Content-Type')
                sql_result = getMysqlInfo(NC.config).get_mysql_info(
                    sql['my_sql'], sql['condition'], sql['code'])
                logger.info("再分配结果ID获取成功!{}".format(sql_result))
                url_d = url.format(sql_result[0], sql_result[3])
                print(url_d)
                request = requests.put(url_d, data, headers=headers).json()
            else:
                # print(data)
                # .encode("UTF-8")对字符串进行`UTF-8`编码格式编码
                # 用dumps转义成json格式
                # json.dump()函数的使用,将json信息写进文件
                # json.dumps()   编码:把一个Python对象编码转换成Json字符串
                # json.load()函数的使用,将读取json信息
                # json.loads()  解码:把Json格式字符串解码转换成Python对象
                # body格式
                request = requests.put(url,
                                       data=json.dumps(data),
                                       headers=headers).json()

        elif method == 'DELETE':
            logger.info('现在开始进行delete请求')
            # excel的data中指定:0表示正常请求,1取数据库返回第一个值,2指定数据库返回第二个值,3指定删除规则
            if '1' in data.keys() and data['1'] == 1:
                sql_result = getMysqlInfo(NC.config).get_mysql_info(
                    sql['my_sql'], sql['condition'], sql['code'])
                logger.info('数据库返回:' + str(sql_result))
                logger.info("excel取值获取数据库返回第%s位:" % data['1'])
                url_del = url + str(sql_result[0])
                logger.info("请求URL:%s" % url_del)
                request = requests.delete(url_del, headers=headers).json()
            elif '1' in data.keys() and data['1'] == 2:
                sql_result = getMysqlInfo(NC.config).get_mysql_info(
                    sql['my_sql'], sql['condition'], sql['code'])
                logger.info('数据库返回:' + str(sql_result))
                logger.info("excel取值获取数据库返回第%s位:" % data['1'])
                url_del = url + str(sql_result[1])
                logger.info("请求URL:%s" % url_del)
                request = requests.delete(url_del, headers=headers).json()
            elif '1' in data.keys() and data['1'] == 3:
                sql_result = getMysqlInfo(NC.config).get_mysql_info(
                    sql['my_sql'], sql['condition'], sql['code'])
                for i in range(len(sql_result)):
                    if 'rule_id' in sql_result[i].keys():
                        url_d = url + str(sql_result[i]["rule_id"])
                        request = requests.delete(url_d,
                                                  headers=headers).json()
                        logger.info("rule_id:%s删除处理成功!" %
                                    sql_result[i]["rule_id"])
                    elif 'id' in sql_result[i].keys():
                        url_d = url + str(sql_result[i]["id"])
                        request = requests.delete(url_d,
                                                  headers=headers).json()
                        logger.info("规则ID:%s删除处理成功!" % sql_result[i]["id"])
                logger.info(sql['condition'] + "删除处理成功!")
            elif '1' in data.keys() and data['1'] == 0:
                logger.info("客户进行关闭会话请求!")
                sql_result = getMysqlInfo(NC.config).get_mysql_info(
                    sql['my_sql'], sql['condition'], sql['code'])
                logger.info('数据库返回:' + str(sql_result))
                url1 = url.format(sql_result[4], pp["visitor_id"])
                request = requests.delete(url1, headers=header).json()
            elif sql['1'] == 1:
                logger.info("批量删除自定义问答请求!")
                sql_result = getMysqlInfo(NC.config).get_mysql_info(
                    sql['my_sql'], sql['condition'], sql['code'])
                a = ''
                for i in range(len(sql_result)):
                    a = a + str(sql_result[i]["id"]) + ','
                data['ids'] = a
                request = requests.delete(url, data=data,
                                          headers=headers).json()

            elif sql['1'] == 0:
                request = requests.delete(url, data=data,
                                          headers=headers).json()
            else:
                request = requests.delete(url, headers=headers).json()

        else:
            logger.info('请求方法未知!请核对后在尝试!')
        return request