Esempio n. 1
0
def start_plan_task(function_name,task_name,run_info,run_list):
    try:
        sched_my=PLAN_TASKS.get(task_name)
        run_type = run_info.get('run_type')
        run_time = run_info.get('run_time')
        if run_type == '每周执行一次':
        # schedmy = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults)
            sched_my.add_job(function_name,
                            trigger='cron',
                            day_of_week=run_time,
                            hour=8, minute=00,
                            id=task_name,
                            replace_existing=True,
                            args=[run_list])
        elif run_type == '间隔固定小时':
            sched_my.add_job(function_name,
                            trigger='interval',
                            hours=int(run_time),
                            id=task_name,
                            replace_existing=True,
                            args=[run_list])
        elif run_type == '间隔固定分钟':
            sched_my.add_job(function_name,
                            trigger='interval',
                            minutes=int(run_time),
                            id=task_name,
                            replace_existing=True,
                            args=[run_list])
        else:LogController.write_log('没有配置执行方式,或者执行方式配置的不对')
        sched_my.start()
        # print schedmy.state
    except(KeyboardInterrupt, SystemExit):
        sched_my.remove_job(task_name)
        sched_my.remove_job(task_name)
        LogController.write_log('start_plan_task失败,原因是:%s' % traceback.format_exc())
Esempio n. 2
0
def update_db_data(sql):
    try:
        db = DBController()
        db.connect_sqlite(join_path(BASE_DIR, 'db.sqlite3'))
        db.exe_update(sql)
        db.connect_close()
    except Exception,e:
        db.connect_close()
        LogController.write_log('update_db_data失败,原因是:%s' % traceback.format_exc())
Esempio n. 3
0
def get_sqlite_info(sql):
    try:
        db = DBController()
        db.connect_sqlite(join_path(BASE_DIR, 'db.sqlite3'))
        result = db.exe_query(sql)
        db.connect_close()
        return result
    except Exception,e:
        db.connect_close()
        LogController.write_log(exe_result=traceback.format_exc(),sql=sql)
Esempio n. 4
0
def del_db_info(db_info,table,where):
    try:
        db = DBController()
        sql = "delete from %s %s" % (table,where)
        if DB_TYPE == 'sqlite' or DB_TYPE == 'sqlite3':
            db.connect_sqlite(join_path(BASE_DIR, 'db.sqlite3'))
        db.exe_update(sql)
        db.connect_close()
    except Exception,e:
        db.connect_close()
        LogController.write_log('del_db_info失败,原因是%s' % traceback.format_exc(),table=table,where=where)
Esempio n. 5
0
 def exe_update(self, sql):
     """
     已知sql,执行更新语句
     :param sql:
     :return:
     """
     try:
         rows = self.cursor.execute(sql)
         self.connect.commit()
         return rows
     except Exception,e:
         self.connect.rollback()  # 发生错误时回滚
         self.cursor.close()
         self.connect.close()
         LogController.write_log("update_result处理失败。原因为:%s" % traceback.format_exc(),sql=sql)
         raise e
Esempio n. 6
0
def get_excel_datas(file_path, sheet=None, **kwargs):
    """
    获取excel文件中的数据流
    :param file_path:
    :param sheet:
    :param kwargs:
    :return:
    """
    try:
        datas = xlrd.open_workbook(file_path)
        if sheet is not None:
            return datas.sheet_by_name(sheet)
        else:
            return datas
    except Exception, e:
        LogController.write_log("get_excel_datas处理失败,原因为:%s" %
                                traceback.format_exc())
Esempio n. 7
0
def start_interface_test(run_list):
    if 'service' in run_list and 'api' in run_list:
        LogController.write_log("111111" + '\n')
        os.popen(
            "python -m unittest AutoTestService.TestManage.WebTest.PlanServiceTask"
        )
        LogController.write_log("2222" + '\n')
        os.popen(
            "python -m unittest AutoTestService.TestManage.WebTest.PlanApiTask"
        )
    elif 'service' in run_list:
        os.popen(
            "python -m unittest AutoTestService.TestManage.WebTest.PlanServiceTask"
        )
    elif 'api' in run_list:
        os.popen(
            "python -m unittest AutoTestService.TestManage.WebTest.PlanApiTask"
        )
Esempio n. 8
0
def write_config(config_info, group, app_info):
    """
    根据执行的内容将需要执行的接口写入配置
    :param config_info:
    :return:
    """
    try:
        writ_file = RUN_TEST_CONFIG.get(group.lower())
        config = get_config(writ_file)
        sections = config.sections()
        for sect in sections:
            config.remove_section(sect)
        for key in range(len(config_info.keys())):
            if config_info.keys()[key] == 'run_id':
                if not config.has_section('run_id'):
                    config.add_section('run_id')
                config.set('run_id', 'run_id',
                           json.dumps(config_info.get('run_id').get('run_id')))
            else:
                project_name = config_info.keys()[key]
                class_info = config_info.get(project_name)
                for class_key in range(len(class_info.keys())):
                    class_name = class_info.keys()[class_key]
                    function_datas = class_info.get(class_name)
                    if not config.has_section(project_name):
                        config.add_section(project_name)
                    config.set(project_name, class_name,
                               json.dumps(function_datas))
        for key in app_info.keys():
            if not config.has_section('app_info'):
                config.add_section('app_info')
            config.set('app_info', key, app_info.get(key))
        with open(Common.get_path_by_relative_path(writ_file), "w+") as f:
            config.write(f)
    except Exception, e:
        LogController.write_log("write_config处理失败,原因为:%s" %
                                traceback.format_exc())
Esempio n. 9
0
def start_task(task_name, run_info, is_run=True, project_name=""):
    if run_info.get('run_time') == '星期一':
        run_info['run_time'] = 0
    elif run_info.get('run_time') == '星期二':
        run_info['run_time'] = 1
    elif run_info.get('run_time') == '星期三':
        run_info['run_time'] = 2
    elif run_info.get('run_time') == '星期四':
        run_info['run_time'] = 3
    elif run_info.get('run_time') == '星期五':
        run_info['run_time'] = 4
    elif run_info.get('run_time') == '星期六':
        run_info['run_time'] = 5
    elif run_info.get('run_time') == '星期日':
        run_info['run_time'] = 6
    write_status = Data.write_run_task_v2(task_name, is_run=is_run)
    # write_status = {'code':1,'data':['UserInfo','PromoCard']}
    if write_status.get('code'):
        Data.PlanTask(task_name)
        project_list = write_status.get('data')
        temp = ''
        for i in range(len(project_list)):
            if i == 0:
                temp += '('
            if i == len(project_list) - 1:
                temp += '\'%s\'' % project_list[i] + ')'
            else:
                temp += '\'%s\'' % project_list[i] + ','
        sql = 'select DISTINCT(project_type) from timetask_totalprojects where project_name in %s' % temp
        LogController.write_log(sql)
        result = Data.get_sqlite_info(sql)
        run_list = []
        for item in result:
            run_list.append(item[0])
        Data.start_plan_task(start_interface_test, task_name, run_info,
                             run_list)
Esempio n. 10
0
    def test_Run(self, datas):
        """
        服务端接口测试统一调度方法
        :param datas:
        :return:
        """
        chart_type = 'service'
        # print datas
        if datas.has_key('run_id') and datas.get('run_id') is not None:
            for item in datas.get('run_id'):
                self.test_run_id.append(item)
        if not datas.has_key('request_title'):
            if datas.has_key('log_str'):
                log_str = datas.get('log_str')
            else:
                log_str = u'脚本里没有该接口的测试数据'
            self.test_result.append({
                'project': datas.get('project'),
                'class_name': datas.get('class_name'),
                'function': datas.get('function'),
                'parameter': u'未获取到',
                'result': {
                    'code': False,
                    'response': log_str
                },
                'remark': "",
                'assert_data': "",
                'pre_data': "",
                'after_data': ""
            })
            write_chart_db(datas.get('project'), datas.get('class_name'),
                           datas.get('function'), chart_type, False)
        else:
            # 1、处理传入的数据,得到接口参数,与前置条件数据,后置处理数据,检查数据
            request_infos = datas.get(
                'request_info')  # 接口主要处理数据:包含接口入参,检查数据,前置操作,后置操作
            request_title = datas.get('request_title')  # 请求头包含:项目名称,类,接口名称
            parameters = request_infos.get("parameters")  # 接口入参
            assert_data = request_infos.get("assert_datas")  # 检查数据
            pre_data = request_infos.get("pre_datas") if request_infos.has_key(
                "pre_datas") else ""  # 前置条件数据
            # pre_data = ""
            after_data = request_infos.get(
                "after_datas") if request_infos.has_key(
                    "after_datas") else ""  # 后置处理数据
            remark = request_infos.get("remark") if request_infos.has_key(
                "remark") else ""
            # 2、进行前置条件操作
            if pre_data:
                pre_options(pre_data)
            if after_data:
                after_options(after_data)
            # 3、组装接口入参
            params = []
            for item in parameters:
                params.append(item)
            # 4、调用接口得到返回值

            # 5、进行检查check
            response = {}
            assert_key = ""
            try:
                response = get_response(request_title.get('project'),
                                        request_title.get('class'),
                                        request_title.get('function'), params)
                for key in assert_data.keys():
                    # print "开始检查"
                    assert_key = key
                    if assert_key == "other":
                        other_assert_data = assert_data.get(key)
                        other_assert_key = other_assert_data.get("other_key")
                        value_list = other_assert_data.get("other_value")
                        for i in range(len(other_assert_key)):
                            other_key = other_assert_key[i]
                            if other_key in configSetting.ASSERT_OTHER_KEY:
                                if other_key in configSetting.ASSERT_LENTH:
                                    other_value_key = value_list[i].keys()
                                    assert_value = value_list[i].get(
                                        other_value_key[0])
                                    while isinstance(assert_value, dict):
                                        print "ssss"
                                    actual_value = len(
                                        response.get(other_value_key[i]))
                                    # print assert_value,actual_value
                                    self.assertTrue(
                                        assert_value == actual_value)
                                elif other_key in configSetting.ASSERT_DIC_VALUE:
                                    list_key = []
                                    other_value_key = value_list[i].keys()
                                    assert_value = value_list[i].get(
                                        other_value_key[0])
                                    list_key.append(other_value_key[0])
                                    while isinstance(assert_value, dict):
                                        key_tmp = assert_value.keys()[0]
                                        list_key.append(key_tmp)
                                        assert_value = assert_value.get(
                                            key_tmp)
                                    # print assert_value,list_key
                                    response_value = response
                                    actual_value = ""
                                    for i_key in list_key:
                                        response_value_tmp = response_value.get(
                                            i_key)
                                        if isinstance(response_value_tmp,
                                                      dict):
                                            response_value = response_value_tmp
                                        else:
                                            actual_value = response_value_tmp
                                    self.assertTrue(
                                        actual_value == assert_value)
                    else:
                        self.assertTrue(
                            assert_data.get(key) == response.get(key))
                log_str = u'成功'
                self.test_result.append({
                    'project':
                    request_title.get('project'),
                    'class_name':
                    request_title.get('class'),
                    'function':
                    request_title.get('function'),
                    'parameter':
                    json.dumps(parameters).decode("utf-8"),
                    'result': {
                        'code': True,
                        'response': log_str
                    },
                    'remark':
                    remark,
                    'assert_data':
                    assert_data,
                    'pre_data':
                    pre_data,
                    'after_data':
                    after_data
                })
                write_chart_db(request_title.get('project'),
                               request_title.get('class'),
                               request_title.get('function'), chart_type, True)
            except Exception, e:
                if assert_data and assert_data is not None:
                    actual_response = response.get(
                        assert_key) if response.has_key(assert_key) else (
                            response if len(response) > 0 else e)
                    log_str = u"%s期望是%s,实际得到的是%s:" % (
                        str(assert_key), str(
                            assert_data.get(assert_key)), str(actual_response))
                else:
                    log_str = u"检查结果数据有误或者缺失"
                self.test_result.append({
                    'project':
                    request_title.get('project'),
                    'class_name':
                    request_title.get('class'),
                    'function':
                    request_title.get('function'),
                    'parameter':
                    json.dumps(parameters).decode("utf-8"),
                    'result': {
                        'code': False,
                        'response': log_str
                    },
                    'remark':
                    remark,
                    'assert_data':
                    assert_data,
                    'pre_data':
                    pre_data,
                    'after_data':
                    after_data
                })
                if not AssertionError:
                    LogController.write_log(traceback.format_exc())
                write_chart_db(request_title.get('project'),
                               request_title.get('class'),
                               request_title.get('function'), chart_type,
                               False)