import json
import traceback
import yaml

from common.yaml_util import read_data_yaml, get_project_path
from common.log_util import error_log


# 读取测试用列
def read_testcase(yaml_path):
    try:
        # with open(get_project_path() + yaml_path, mode='r', encoding='utf-8') as f:
        with open(yaml_path, mode='r', encoding='utf-8') as f:
            arg_names = yaml.load(stream=f, Loader=yaml.FullLoader)
            if len(arg_names) >= 2:
                return arg_names
            else:
                if "parameterize" in dict(*arg_names).keys():
                    new_arg_names = ddt(*arg_names)
                    return new_arg_names
                else:
                    return arg_names
    except Exception as e:
        error_log("读取测试用例方法read_testcase异常：%s" % str(traceback.format_exc()))


def ddt(arg_names):
    # 新方法
    try:
        arg_names_str = json.dumps(arg_names)
        data_list = arg_names["parameterize"]
        key_length = len(data_list[0])
        # print(key_length)
        length_success = True
        # 循环数据
        for param in arg_names["parameterize"]:
            if len(param) != key_length:
                length_success = False
                error_log("此条数据有误：%s" % param)
        # 替换值
        new_art_names = []
        if length_success:
            for x in range(1, len(data_list)):
                # print(data_list[x])
                temp_arg_names = arg_names_str
                for y in range(0, len(data_list[x])):
                    if isinstance(data_list[x][y], int) or isinstance(data_list[x][y], float):
                        temp_arg_names = temp_arg_names.replace('"$ddt{' + data_list[0][y] + '}"', str(data_list[x][y]))
                    else:
                        temp_arg_names = temp_arg_names.replace("$ddt{" + data_list[0][y] + "}", str(data_list[x][y]))
                new_art_names.append(json.loads(temp_arg_names))
            # print(new_art_names)
        return new_art_names
    except Exception as e:
        error_log("数据驱动ddt异常：%s" % str())


