Example #1
0
def write_case(_path):
    yml_list = write_case_yml(_path)
    project_path = str(os.path.abspath('.').split('/bin')[0])
    test_path = project_path + '/aff/testcase/'
    src = test_path + 'Template.py'

    for case in yml_list:
        yml_path = case.split('/')[0]
        yml_name = case.split('/')[1]
        case_name = 'test_' + yml_name + '.py'
        new_case = test_path + yml_path + '/' + case_name
        mk_dir(test_path + yml_path)
        if case_name in os.listdir(test_path + yml_path):
            pass
        else:
            shutil.copyfile(src, new_case)
            with open(new_case, 'r') as fw:
                source = fw.readlines()
            n = 0
            with open(new_case, 'w') as f:
                for line in source:
                    if 'PATH = setupMain.PATH' in line:
                        line = line.replace("/aff/page/offer",
                                            "/aff/page/%s" % yml_path)
                        f.write(line)
                        n = n + 1
                    elif 'case_dict = ini_case' in line:
                        line = line.replace("Template", yml_name)
                        f.write(line)
                        n = n + 1
                    elif 'class TestTemplate' in line:
                        line = line.replace(
                            "TestTemplate",
                            "Test%s" % yml_name.title().replace("_", ""))
                        f.write(line)
                        n = n + 1
                    elif '@allure.story' in line:
                        line = line.replace("Template", yml_name)
                        f.write(line)
                        n = n + 1
                    elif 'def test_template' in line:
                        line = line.replace("template", yml_name.lower())
                        f.write(line)
                        n = n + 1

                    else:
                        f.write(line)
                        n += 1
                for i in range(n, len(source)):
                    f.write(source[i])
Example #2
0
def write_case(_path):
    yml_list = write_case_yml(_path)
    test_path = project_path + dir_manage('${case_dir}$')
    src = test_path + 'Template.py'

    for case in yml_list:
        yml_path = case.split('/')[0]
        yml_name = case.split('/')[1]
        case_name = 'test_' + yml_name + '.py'
        new_case = test_path + yml_path + '/' + case_name
        mk_dir(test_path + yml_path)
        if case_name in os.listdir(test_path + yml_path):
            pass
        else:
            shutil.copyfile(src, new_case)
            with open(new_case, 'r', encoding='utf-8') as fw:
                source = fw.readlines()
            n = 0
            with open(new_case, 'w', encoding='utf-8') as f:
                for line in source:
                    if 'PATH = project_path' in line:
                        line = line.replace("offer", "%s" % yml_path)
                        f.write(line)
                        n = n + 1
                    elif 'case_dict = ini_case' in line:
                        line = line.replace("Template", yml_name)
                        f.write(line)
                        n = n + 1
                    elif 'class TestTemplate' in line:
                        line = line.replace(
                            "TestTemplate",
                            "Test%s" % yml_name.title().replace("_", ""))
                        f.write(line)
                        n = n + 1
                    elif '@allure.story' in line:
                        line = line.replace("Template", yml_name)
                        f.write(line)
                        n = n + 1
                    elif 'def test_template' in line:
                        line = line.replace("template", yml_name.lower())
                        f.write(line)
                        n = n + 1

                    else:
                        f.write(line)
                        n += 1
                for i in range(n, len(source)):
                    f.write(source[i])
Example #3
0
    def __init__(self, path):
        """
        日志配置
        :param path: 路径
        """

        runtime = time.strftime('%Y-%m-%d', time.localtime(time.time()))

        mk_dir(path + "/log")
        logfile = path + "/log/" + runtime + '.log'
        logfile_err = path + "/log/" + runtime + '_error.log'

        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)
        logger.handlers = []

        # 第二步,创建一个handler,用于写入全部info日志文件

        fh = logging.FileHandler(logfile, mode='a+')
        fh.setLevel(logging.DEBUG)

        # 第三步,创建一个handler,用于写入错误日志文件

        fh_err = logging.FileHandler(logfile_err, mode='a+')
        fh_err.setLevel(logging.ERROR)

        # 第四步,再创建一个handler,用于输出到控制台
        ch = logging.StreamHandler(sys.stdout)
        ch.setLevel(logging.INFO)

        # 第五步,定义handler的输出格式
        formatter = logging.Formatter(
            "%(asctime)s - %(filename)s - %(levelname)s: %(message)s")
        fh.setFormatter(formatter)
        fh_err.setFormatter(formatter)
        ch.setFormatter(formatter)

        # 第六步,将logger添加到handler里面
        logger.addHandler(fh)
        logger.addHandler(fh_err)
        logger.addHandler(ch)
Example #4
0
def write_case_yml(har_path):
    """
	循环读取导出文件
	:param har_path: Charles导出文件路径
	:return:
	"""
    # har_list = os.listdir(har_path)
    har_list = [f for f in os.listdir(har_path) if not f.startswith('.')]
    project_path = str(os.path.abspath('.').split('bin')[0])
    case_file_list = {}
    for i in har_list:
        if 'chlsj' in i:
            case_path, title, case_list, expected_request, check, parameter, case_no = write_open_path(
                i, har_path)
            writting_json(title, case_path, expected_request, check, parameter,
                          case_no)
            writting_yml(case_path, title, case_list, case_no)
        else:
            har_fixture_path = har_path + "/" + i
            har_lists = getTestCase(har_fixture_path)
            for case in har_lists:
                case_path = project_path + '/testcase/source/' + case["name"]
                title = list(case["name"].split(" "))
                mk_dir(case_path)
                writting_json(title, case_path, case["expect"], case["check"],
                              case["params"], case["num"])
                writting_yml(case_path, title, case, case["num"])
    srouce_path = project_path + '/testcase/source/'
    srouce_file = [f for f in os.listdir(srouce_path) if not f.startswith('.')]
    for path in srouce_file:
        srouce_file_list = [
            f for f in os.listdir(srouce_path + path) if not f.startswith('.')
        ]
        num = len(srouce_file_list) / 3
        case_file_list[path] = int(num)
    return case_file_list
def write_case_yml(har_path):
    """
    循环读取导出文件
    :param har_path: Charles导出文件路径
    :return:
    """
    har_list = os.listdir(har_path)
    case_file_list = []

    for i in har_list:
        if 'chlsj' in i:
            with open(har_path+'/'+str(i), 'r', encoding='utf-8') as f:
                logging.debug("从%s目录下,读取文件%s" % (har_path, i))

                har_cts = json.loads(f.read())
                har_ct = har_cts[0]
                case_list = dict()
                scheme = har_ct["scheme"]
                method = har_ct["method"]
                path = har_ct["path"]
                title = path.split("/")[-1]
                info_id = "test_" + title + "_01"
                parameter_type = har_ct["request"]["mimeType"]
                parameter = dict()
                try:
                    if method in 'POST':
                        parameter_list = urllib.parse.unquote(har_ct["request"]["body"]["text"])
                    elif method in 'PUT':
                        parameter_list = har_ct["request"]["body"]["text"]
                    elif method in 'DELETE':
                        parameter_list = urllib.parse.unquote(har_ct["request"]["body"]["text"])
                    else:
                        parameter_list = har_ct["query"]

                    if "&" in parameter_list:

                        for key in parameter_list.split("&"):
                            val = key.split("=")
                            parameter[val[0]] = val[1]
                    else:
                        parameter = json.loads(parameter_list)
                except Exception as e:
                    logging.error("未找到parameter: %s" % e)
                    raise e

                case_path = project_path + dir_manage('${page_dir}$') + path.split("/")[-2]
                mk_dir(case_path)

                response_code = har_ct["response"]["status"]
                response_body = har_ct["response"]["body"]["text"]
                test_info = dict()
                test_info["id"] = info_id
                test_info["title"] = path.split("/")[-2]
                test_info["host"] = '${host}$'
                test_info["address"] = path

                # 定义checkout
                check = dict()
                check["check_type"] = 'json'
                check["expected_code"] = response_code
                expected_request = json.loads(response_body)

                result_file = 'result_' + title + '.json'
                # result参数大于4时,写入result.json中
                if len(expected_request) >= 2:
                    if result_file in os.listdir(case_path):
                        pass
                    else:
                        result_list = []
                        result_dicts = dict()
                        with open(case_path + '/' + result_file, "w", encoding='utf-8') as ff:
                            result_dicts["test_name"] = title
                            result_dicts["json"] = expected_request
                            result_list.append(result_dicts)

                            json.dump(result_list, ff, ensure_ascii=False, indent=4)
                    check["expected_request"] = result_file

                else:
                    check["expected_request"] = expected_request

                param_file = case_path + '/' + title + '.json'
                test_case_list = []
                test_case = dict()
                test_case_list.append(test_case)
                # para参数大于等于4时,参数文件单独写入json中
                if len(parameter) >= 4:
                    if title + '.json' in os.listdir(case_path):
                        pass
                    else:
                        new_dicts = dict()
                        new_list = []
                        with open(param_file, "w", encoding='utf-8') as fs:
                            new_dicts["test_name"] = title
                            new_dicts["parameter"] = parameter
                            new_list.append(new_dicts)

                            json.dump(new_list, fs, ensure_ascii=False, indent=4)

                    test_case["test_name"] = title
                    test_case["info"] = title
                    test_case["http_type"] = scheme
                    test_case["request_type"] = method
                    test_case["parameter_type"] = parameter_type
                    test_case["address"] = path
                    test_case["headers"] = {"X-Requested-With": "XMLHttpRequest"}
                    test_case["cookies"] = True
                    test_case["timeout"] = 20
                    test_case["parameter"] = title + '.json'
                    test_case["file"] = False
                    test_case["check"] = check
                    test_case["relevance"] = None

                else:
                    test_case["test_name"] = title
                    test_case["info"] = title
                    test_case["http_type"] = scheme
                    test_case["request_type"] = method
                    test_case["parameter_type"] = parameter_type
                    test_case["address"] = path
                    test_case["headers"] = {"X-Requested-With": "XMLHttpRequest"}
                    test_case["cookies"] = True
                    test_case["timeout"] = 20
                    test_case["parameter"] = parameter
                    test_case["file"] = False
                    test_case["check"] = check
                    test_case["relevance"] = None

                case_list["test_info"] = test_info
                case_list["premise"] = None
                case_list["test_case"] = test_case_list

                case_file = case_path + '/' + title + '.yml'
                if title + '.yml' in os.listdir(case_path):
                    pass
                else:
                    with open(case_path + '/' + title + '.yml', 'w+', encoding='utf-8') as ff:
                        case_file_list.append(path.split("/")[-2]+'/'+title)
                        logging.debug("从%s目录下,写入测试文件%s" % (case_path, case_file))
                        yaml.dump(case_list, ff, Dumper=yaml.RoundTripDumper)
    return case_file_list
Example #6
0
def write_open_path(i, har_path):
    with open(har_path + '/' + str(i), 'r', encoding='utf-8') as f:
        logging.debug("从%s目录下,读取文件%s" % (har_path, i))
        har_cts = json.loads(f.read())
        har_ct = har_cts[0]
        case_list = dict()
        scheme = har_ct["scheme"]
        method = har_ct["method"]
        path = har_ct["path"]
        host = har_ct["host"]
        # title = path.split("/")[-1]
        # if path[-1] == "/":
        # 	title = path.split("/")[-2]
        # else:
        # 	title = path.split("/")[-1]
        title = re.findall('(.*?).chlsj', i)
        # if "_" in title[0]:
        # 	title = title[0].split("_")
        # if len(title) > 1:
        # 	case_no = title[-1]
        # 	info_id = "test_" + title[0] + '_' + title[-1]
        # else:
        title = title[0].split("_")
        case_no = title[-1]
        info_id = "test_" + title[0] + "_" + case_no
        parameter_type = har_ct["request"]["mimeType"]
        parameter = dict()
        try:
            if method == 'POST':
                parameter_list = urllib.parse.unquote(
                    har_ct["request"]["body"]["text"])
            else:
                parameter_list = har_ct["query"]
            # if '&' in parameter_list:
            for key in parameter_list.split("&"):
                val = key.split("=")
                parameter[val[0]] = val[1]
            # else:
            #
            #     pass
        except Exception as e:
            print(e)

        project_path = str(os.path.abspath('.').split('bin')[0])
        if "commonData" in har_path:
            case_path = project_path + '/testcase/source/commonData/' + title[0]
        else:
            case_path = project_path + '/testcase/source/' + title[0]
        mk_dir(case_path)
        request_header = har_ct["request"]["header"]["headers"]
        request_headers = {}
        for i in request_header:
            request_headers[i["name"]] = i["value"]
        response_code = har_ct["response"]["status"]
        response_boby = har_ct["response"]["body"]["text"]
        test_info = dict()
        # test_info = {'id': info_id, 'address': path, 'host': '${host}$', 'title': path.split("/")[-2]}
        test_info["id"] = info_id
        # if case_no != None:
        test_info["title"] = title[0]
        # else:
        # 	test_info["title"] = title[0]
        test_info["host"] = host
        test_info["address"] = path

        # 定义checkout
        check = dict()
        # check = {'check_type': 'json', 'expected_code': response_code}

        #检查类型
        check["check_type"] = 'json'
        check["expected_code"] = response_code
        expected_request = json.loads(response_boby)
        test_case = dict()
        test_case["test_name"] = test_info["title"]
        test_case["info"] = info_id
        test_case["http_type"] = scheme
        test_case["request_type"] = method
        test_case["parameter_type"] = parameter_type
        test_case["address"] = path
        # test_case["headers"] = {"X-Requested-With": "XMLHttpRequest"}
        test_case["headers"] = request_headers
        test_case["cookies"] = True
        test_case["timeout"] = 20
        test_case["parameter"] = title[0] + '.json'
        test_case["file"] = False
        test_case["check"] = check
        test_case["relevance"] = None
        case_list["test_info"] = test_info
        case_list["premise"] = None
        case_list["test_case"] = test_case
    return case_path, title, case_list, expected_request, check, parameter, case_no