示例#1
0
 def wrapper(self, *args, **kw):
     who = 'Nobody'
     if hasattr(self, 'username'):
         who = self.username
     logger.info(
         '<==================== {1} Begin call [{0}] ===================='.
         format(__get_full_class(self), who))
     start_time = time.time()
     try:
         c = func(self, *args, **kw)
     except Exception as err:
         text = '\n'.join([
             'an error occured on {}'.format(get_host_port()),
             str(err),
             traceback.format_exc()
         ])
         logger.error('ATP: 接口发现未知错误 \n {traceback}'.format(traceback=text))
         # subject = 'ATP: 系统发现未知错误'
         # try:
         #     from atp.api.send_email import intf_send_mail
         #     from atp.config.default import get_config
         #     config = get_config()
         #     email_to = config.EMAIL_TO
         #     intf_send_mail(email_to, subject, text)
         #     logger.info("send mail {} {} {}".format(email_to, subject, text))
         # except Exception as e:
         #     logger.error("cannot send email: {} {} {}".format(str(e), subject, text))
         c = jsonify({"code": "999", "desc": "system error"})
     end_time = time.time()
     d_time = end_time - start_time
     logger.info(
         "==================== End call [{0}], run {1:.3}s ====================>\n"
         .format(__get_full_class(self), d_time))
     return c
示例#2
0
def make_response(response_dict):
    response_str = json.dumps(response_dict, ensure_ascii=False)
    if len(response_str) <= 5000:
        logger.info("<Response> body= {body}".format(body=response_str))
    else:
        logger.info(
            "<Response> body= {len} characters".format(len=len(response_str)))
    return jsonify(response_dict)
示例#3
0
文件: ssh_client.py 项目: zmhtest/ATP
 def exec_cmd(self, cmd):
     stdin, stdout, stderr = self.client.exec_command(cmd)
     data = stdout.read().decode()
     if len(data) > 0:
         logger.info(data.strip())  # 打印正确结果
         return data
     err = stderr.read().decode()
     if len(err) > 0:
         logger.error(err.strip())  # 输出错误结果
         return err
示例#4
0
文件: ssh_client.py 项目: zmhtest/ATP
 def __enter__(self):
     try:
         logger.info(
             '开始连接服务器,服务器连接信息:hostname-{0},port-{1}, username-{2}, password-{3}'.format(self.hostname, self.port,
                                                                                        self.username,
                                                                                        self.password))
         self.client.connect(hostname=self.hostname, port=self.port, username=self.username, password=self.password,
                             timeout=self.timeout)
         return self
     except Exception as e:
         logger.error(traceback.format_exc())
         raise e
示例#5
0
def disconf_get_config(disconf_host, cookie, config_id):
    url = disconf_host + '/api/web/config/' + str(config_id)
    heard_info = {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Cookie': cookie}
    value = None
    try:
        response = requests.get(url=url, headers=heard_info)
        logger.debug("response.text: {0}".format(response.text))
        response_dict = json.loads(response.text)
        logger.info('response_dict: {}'.format(response_dict))
        value = response_dict['result']['value']
    except Exception as err:
        raise err
    return value
示例#6
0
文件: api_runner.py 项目: zmhtest/ATP
    def _assign_celery_tasks(self, header):
        """分配异步测试任务, 增加回调任务收集测试结果"""
        worker_num = len(header)
        logger.info('本次运行总共需要的worker数量: {}'.format(worker_num))

        callback = celery_collect_results.s()
        chord_result = chord(header)(callback)
        callback_celery_no = chord_result.id

        # 更新api_run_task_result表,本次运行总共需要的worker数量
        ApiRunTaskResultManager.update_result(id_=self.run_task_result_id, worker_num=worker_num)
        # 写入celery任务表
        CeleryTaskRecordManager.insert_celery(celery_task_no=callback_celery_no, celery_task_status='WAITING',
                                              api_run_task_result_id=self.run_task_result_id)
        return callback_celery_no
示例#7
0
def query_disconf_value(disconf_host, disconf_id, disconf_name):
    """
    根据传入的配置文件唯一标识id查询某个配置的值(Disconf)
    :param disconf_id:配置文件唯一标识
    :param disconf_name:配置文件的变量名
    :return:
    """
    cookie = disconf_session(disconf_host)
    cookie = disconf_signin(disconf_host, cookie)
    value = disconf_get_config(disconf_host, cookie, disconf_id)
    if value:
        disconf_List = query_configId_value(disconf_name, value)
        logger.info("查询disconf结果为: {0}".format(disconf_List[0]))
        return str(disconf_List[0]).split('=', 1)[1]
    else:
        return -1
示例#8
0
 def get(self, action):
     if action.endswith("xmind") or action.endswith("xlsx"):
         return send_from_directory(CONFIG.DOWNLOADS_DIR,
                                    action,
                                    mimetype='application/octet-stream')
     elif action.endswith("zip"):
         filename = 'run.zip'
         logger.info('zip_path', CONFIG.DOWNLOADS_DIR)
         return send_from_directory(CONFIG.DOWNLOADS_DIR,
                                    filename,
                                    mimetype='application/octet-stream')
     elif action == 'recentTestcasesToExcel':
         # print(action)
         from_ = request.args.get('from', type=str)
         # print(from_)
         excel_name = export_by_time(from_)
         return send_from_directory(CONFIG.DOWNLOADS_DIR,
                                    excel_name,
                                    mimetype='application/octet-stream')
示例#9
0
    def wrapper(*args, **kw):
        start_time = time.time()
        try:
            c = func(*args, **kw)
        except Exception as err:
            text = '\n'.join([
                'an error occured on {}'.format(get_host_port()),
                str(err),
                traceback.format_exc()
            ])
            logger.error(
                'ATP: 自定义方法发现未知错误 \n {traceback}'.format(traceback=text))
            c = "自定义方法调用失败"
            raise err
        end_time = time.time()
        d_time = end_time - start_time

        logger.info(
            "==================== custom_func[{0}], run {1:.3}s ====================>\n"
            .format(func.__name__, d_time))
        return c
示例#10
0
    def writeExcel(self, values):
        # 写excel文件
        wb = Workbook()
        #ws = wb.active
        #ws.title = self.ws_title
        if not os.path.exists(CONFIG.DOWNLOADS_DIR):
            os.makedirs(CONFIG.DOWNLOADS_DIR)
        file_name = "{0}_业务用例_{1}.xlsx".format(self.ws_title, int(time.time()))
        # file_name = "{0}_业务用例.xlsx".format(self.ws_title)
        file_dir = CONFIG.DOWNLOADS_DIR + file_name

        # 创建sheet
        sheet_idx = 0
        for module_name, value in values.items():
            ws = wb.create_sheet(module_name, sheet_idx)
            if value:
                row_idx = 0
                for i in range(0, len(value)):
                    if i > 1:
                        '''row_idx表示前面用例所占操作步骤总行数'''
                        if len(value[i - 1][4]) <= 1:
                            row_idx = row_idx
                        else:
                            row_idx = row_idx + len(value[i - 1][4]) - 1  #2
                    for j in range(0, len(value[i])):
                        if i == 0:
                            ws.cell(row=i + 1,
                                    column=j + 1,
                                    value=str(value[i][j]))
                        elif i == 1:
                            if isinstance(value[i][j], list):
                                if len(value[i][j]) >= 1:
                                    for x in range(0, len(value[i][j])):
                                        ws.cell(row=i + 1 + x,
                                                column=j + 1,
                                                value=str(value[i][j][x]))
                                elif len(value[i][j]) == 0:
                                    ws.cell(row=i + 1,
                                            column=j + 1,
                                            value=str(''))
                            else:
                                ws.cell(row=i + 1,
                                        column=j + 1,
                                        value=str(value[i][j]))
                        else:
                            if isinstance(value[i][j], list):
                                if len(value[i][j]) >= 1:
                                    for x in range(0, len(value[i][j])):
                                        ws.cell(row=i + 1 + row_idx + x,
                                                column=j + 1,
                                                value=str(value[i][j][x]))
                                elif len(value[i][j]) == 0:
                                    ws.cell(row=i + 1 + row_idx,
                                            column=j + 1,
                                            value=str(''))
                            else:
                                ws.cell(row=i + 1 + row_idx,
                                        column=j + 1,
                                        value=str(value[i][j]))
                for cols in ws.iter_cols():
                    for cell in cols:
                        cell.font = Font(size=9)
                        cell.border = self.border
                        cell.alignment = self.alignment
                    cell_title = cols[0]
                    cell_title.font = self.font
                    cell_title.fill = self.fill
                ws.row_dimensions[1].height = 20
                ws.column_dimensions['A'].width = 10
                ws.column_dimensions['B'].width = 20
                ws.column_dimensions['C'].width = 20
                ws.column_dimensions['D'].width = 20
                ws.column_dimensions['E'].width = 40
                ws.column_dimensions['F'].width = 40
                ws.column_dimensions['G'].width = 20
                ws.column_dimensions['H'].width = 20
                ws.freeze_panes = 'A2'
            else:
                raise Exception("存储Excel失败")
            sheet_idx += 1
        wb.save(file_dir)
        logger.info("写入数据成功!")
        return file_name
示例#11
0
文件: ssh_client.py 项目: zmhtest/ATP
 def __exit__(self, exc_type, exc_val, exc_tb):
     logger.info('开始清理操作,关闭SSH连接')
     if self.shell:
         self.shell.close()
     if self.client:
         self.client.close()
示例#12
0
def get_request_json():
    data = request.get_json()
    logger.info('<Request> url= {url}, body= {body}'.format(
        url=request.url, body=json.dumps(data, ensure_ascii=False)))
    return data