Example #1
0
 def __init__(self):
     self.curDateTime = str(
         time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))  # 当前日期时间
     self.config = conf.get_yaml_field(gl.configFile)  # 配置文件路径
     self.sender = self.config['EMAIL']['Smtp_Sender']  # 从配置文件获取,发件人
     self.receivers = self.config['EMAIL']['Receivers']  # 从配置文件获取,接收人
     self.msg_title = self.config['EMAIL']['Msg_Title']  # 从配置文件获取,邮件标题
     self.sender_server = self.config['EMAIL'][
         'Smtp_Server']  # 从配置文件获取,发送服务器
     self.From = self.config['EMAIL']['From']
     self.To = self.config['EMAIL']['To']
     self.Port = self.config['EMAIL']['Port']
Example #2
0
def get_run_flag(skey):
    """
    Get the flag in the configuration file.
    param:
        skey: flag
    usage:
        ret = get_run_flag('Flag')
    return:
        ret: 'Y' or 'N'
    """
    yaml_dict = conf.get_yaml_field(gl.exeConfigFile)
    ret_flag = yaml_dict['RUNING'][skey]['Flag']
    return ret_flag
Example #3
0
    def tmpl_msg(low_path):
        # 发送钉钉模版测试结果
        config = conf.get_yaml_field(gl.configFile)
        # report外网发布地址ip+port
        report_url = config['REPORT_URL']
        # 钉钉标题
        content = config['DING_TITLE']
        # 从报告中取得测试结果数据 e.g. 3 tests; 2.23 seconds; 3 passed; 0 failed; 0 errors
        file_result = os.path.join(gl.loadcasePath, 'result.cache')
        #
        result_content = read_file(file_result, 'r')
        # Remove file
        remove_file(file_result)

        res_list = result_content.split(";")

        # 发送钉钉消息
        msg = """{}执行【已完成】:\n共{}个用例, 执行耗时{}秒, 通过{}, 失败{}, 错误{}, 通过率{}\n测试报告: {}/{}"""
        msg = msg.format(content, res_list[0], res_list[1], res_list[2],
                         res_list[3], res_list[4], res_list[5], report_url,
                         low_path)
        return msg
Example #4
0
    def invoke():
        """
        Start executing tests generate test reports.
        :return: There is no.
        """
        # CONFIG: Read configuration information
        config = conf.get_yaml_field(gl.configFile)
        dd_enable = config['ENABLE_DDING']
        dd_token = config['DD_TOKEN']
        dd_url = config['DING_URL']
        email_enable = config['EMAIL_ENABLE']
        # END CONFIG.

        # Test report file name.
        time_str = time.strftime('%Y%m%d_%H%M%S', time.localtime())
        path = RunTestCase.create_report_file()

        # Start test the send pin message.
        if dd_enable:
            scripts.send_msg_dding('{}:★开始API接口自动化测试★'.format(time_str),
                                   dd_token, dd_url)

        # Execute the test and send the test report.
        RunTestCase.run(path)
        if dd_enable:
            # Template message.
            dir_list = path.split('\\')
            low_path = dir_list[len(dir_list) - 2]
            msg = RunTestCase.tmpl_msg(low_path)
            print(msg)
            scripts.send_msg_dding(msg, dd_token, dd_url)

        if email_enable:
            # Send test report to EMAIL.
            email = EmailClass()
            email.send(path)
Example #5
0
def _parse_config(config):
    """
    Parse config parameters.
    """
    if config:
        # Setting global var.
        if config[0] == 'set' and config.__len__() == 1:
            try:
                os.system(gl.configFile)
            except (KeyboardInterrupt, SystemExit):
                print("已终止执行.")
        elif config[0] == 'set' and len(config) == 2 and '=' in config[1]:
            cf = config[1].split("=")
            update_yam_content(gl.configFile, cf[0], parse_string_value(cf[1]))

        elif config[0] == 'get' and len(config) == 2 and '=' not in config[1]:
            content = conf.get_yaml_field(gl.configFile)

            try:
                print(content[config[1]])
            except KeyError as ex:
                print('[KeyError]: {}'.format(ex))
        else:
            print('Unknown command: {}'.format(config[0]))
Example #6
0
def load_case_data(flag='TEST_CASE'):
    """
    :Desc:
        load DDT data form YAML.
    :param flag:
        The starting node of the interface case in YAML.
        default:
            TEST_CASE
    :import
        from httptesting.library.scripts import load_case_data
        or
        form httptesting.library import scripts
    :invoke
        load_case_data()
        or
        scripts.load_case_data()

    :return: [] DDT data list
    """
    data_list = []
    temp_list = []
    case_path = None
    for _ in range(0, case_exec_queue.qsize()):
        if not case_exec_queue.empty():
            case_name = case_exec_queue.get()

            # OFF/ON Specify the execution case.
            parse_bool = False
            # Specify the execution CASE.
            if '&#' in case_name:
                parse_bool = True
                path_parse = case_name.split('&#')
                case_name = path_parse[0]
                path_parse.pop(0)

            # case path
            case_path = os.path.dirname(case_name)

            # Read the case
            read_yaml = conf.get_yaml_field(case_name)
            # yaml start the node,The default is TEST_CASE.
            case_dict = read_yaml[flag]

            # OFF/ON Specify the execution case.
            if parse_bool:
                for case_name in path_parse:
                    try:
                        data_list.append(case_dict[case_name])
                    except KeyError as ex:
                        print('{}测试用例名称错误,请检查拼写、大小写.'.format(case_name))
                        raise ex
            else:
                # Loop through the configuration data under the node,
                # so case begins the use case
                for key in case_dict:
                    # What begins with a case in configuration data is considered a use case.
                    if str(key).lower().startswith('case'):

                        # Organize DDT [] data, and each case is a dict object
                        data_list.append(case_dict[key])
        else:
            raise Exception("The CASE execution queue is empty.")

        # csv or parameter var.
        temp_list, csv_exec_flag = _csv_parameter_func(case_path, data_list)
        if not csv_exec_flag:
            temp_list = _parameter_variable(data_list)

        # Scenario case Skip.
        temp_list = _skip_scenario_interface(temp_list)

    # case order by desc
    data_list = sorted_data_fuction(temp_list, orderby='desc')
    return data_list
Example #7
0
 def __init__(self):
     self.config = conf.get_yaml_field(gl.configFile)
     self.base_url = self.config['BASE_URL']
     self.OUT_TMPL = """{0} {1}请求:{2}\n请求:\n{3}\n响应:"""
Example #8
0
    def run(path):
        """
        Execute the test and generate the test report file.
        Args:
            path: Report file absolute path.
        Return:
            There is no return.
        """
        config = conf.get_yaml_field(gl.configFile)
        exe_con = config['ENABLE_EXECUTION']
        exe_num = config['EXECUTION_NUM']
        rerun = config['ENABLE_RERUN']
        reruns_nums = config['RERUN_NUM']
        repeat = config['ENABLE_REPEAT']
        repeat_num = config['REPEAT_NUM']
        exec_mode = config['ENABLE_EXEC_MODE']
        debug_mode = config['ENABLE_DEBUG_MODE']
        last_failed = config['ENABLE_LAST_FAILED']
        failed_first = config['ENABLE_FAILED_FIRST']

        # custom function
        RunTestCase.copy_custom_function()

        # failed first
        failed_first_args = (
            ' --ff ' if failed_first else '') if not last_failed else ''

        # last failed
        last_failed_args = (
            ' --lf ' if last_failed else '') if not failed_first else ''

        # Enable repeat case.
        repeat_args = ' --count={} '.format(repeat_num) if repeat else ''

        # Enable CPU concurrency
        py_args = ' -n {} '.format(exe_num) if exe_con else ''

        # Enable failed retry
        reruns_args = ' --reruns {} '.format(reruns_nums) if rerun else ''

        # debug mode print debug info.
        debug = '' if debug_mode else '--tb=no'
        """
        Load the pytest framework,
        which must be written here or DDT will be loaded first.
        from httptesting.case import test_load_case
        """
        case_path = gl.loadcasePath
        # Output mode console or report.
        if exec_mode:
            cmd = 'cd {} && py.test -q -s {} {} {} {}'.format(
                case_path, reruns_args, 'test_load_case.py', repeat_args,
                debug)
        else:
            cmd = 'cd {} && py.test {} {} {} {} {} {} --html={} {} --self-contained-html'.format(
                case_path, py_args, reruns_args, last_failed_args,
                failed_first_args, 'test_load_case.py', repeat_args, path,
                debug)
        try:
            os.system(cmd)
        except (KeyboardInterrupt, SystemExit):
            print('已终止执行.')