Beispiel #1
0
def uniform_validator(validator):
    """ unify validator

    Args:
        validator (dict): validator maybe in two formats:

            format1: this is kept for compatibility with the previous versions.
                {"check": "status_code", "comparator": "eq", "expect": 201}
                {"check": "$resp_body_success", "comparator": "eq", "expect": True}
            format2: recommended new version, {assert: [check_item, expected_value]}
                {'eq': ['status_code', 201]}
                {'eq': ['$resp_body_success', True]}

    Returns
        dict: validator info

            {
                "check": "status_code",
                "expect": 201,
                "assert": "equals"
            }

    """
    if not isinstance(validator, dict):
        raise ParamsError(f"invalid validator: {validator}")

    if "check" in validator and "expect" in validator:
        # format1
        check_item = validator["check"]
        expect_value = validator["expect"]
        comparator = validator.get("comparator", "eq")

    elif len(validator) == 1:
        # format2
        comparator = list(validator.keys())[0]
        compare_values = validator[comparator]

        if not isinstance(compare_values, list) or len(compare_values) != 2:
            raise ParamsError(f"invalid validator: {validator}")

        check_item, expect_value = compare_values

    else:
        raise ParamsError(f"invalid validator: {validator}")

    # uniform comparator, e.g. lt => less_than, eq => equals
    assert_method = get_uniform_comparator(comparator)

    return {
        "check": check_item,
        "expect": expect_value,
        "assert": assert_method
    }
Beispiel #2
0
def get_timestamp(str_len=13):
    """ get timestamp string, length can only between 0 and 16
    """
    if isinstance(str_len, integer_types) and 0 < str_len < 17:
        return builtin_str(time.time()).replace(".", "")[:str_len]

    raise ParamsError("timestamp length can only between 0 and 16.")
Beispiel #3
0
 def _build_url(self, path):
     """ prepend url with hostname unless it's already an absolute URL """
     # if absolute_http_url_regexp.match(path):
     # return path
     # elif self.base_url:
     # return "{}/{}".format(self.base_url.rstrip("/"), path.lstrip("/"))
     # else:
     # raise ParamsError("base url missed!")
     if path == "https://account.ihr360.com/ac/login" and self.base_url == "https://www.ihr360.com":
         return path
     if path == "https://account.ihr360.com/ac/login" and self.base_url == "https://uat.ihr360.com":
         return "https://passport-uat.ihr360.com/ac/login"
     if path == "https://account.ihr360.com/ac/login" and self.base_url == "https://beta.ihr360.com":
         return "https://passport.ihr360.com/ac/login"
     if path == "https://account.ihr360.com/ac/login" and self.base_url == "https://qa.ihr360.com":
         return "https://passport-qa.ihr360.com/ac/login"
     if absolute_http_url_regexp.match(path):
         return path
     # 为空,检验
     if path == "":
         return False
     elif self.base_url:
         return "{}/{}".format(self.base_url.rstrip("/"), path.lstrip("/"))
     else:
         raise ParamsError("base url missed!")
Beispiel #4
0
def build_url(base_url, path):
    """ prepend url with base_url unless it's already an absolute URL """
    if absolute_http_url_regexp.match(path):
        return path
    elif base_url:
        return "{}/{}".format(base_url.rstrip("/"), path.lstrip("/"))
    else:
        raise ParamsError("base url missed!")
Beispiel #5
0
def get_timestamp(str_len=13):
    """
    获取时间戳字符串,长度只能在0到16之间
    :param str_len:
    :return:
    """
    if isinstance(str_len, integer_types) and 0 < str_len < 17:
        return builtin_str(time.time()).replace(".", "")[:str_len]

    raise ParamsError("时间戳长度只能在0到16之间.")
Beispiel #6
0
    def get_export_variables(self) -> Dict:
        export_vars_mapping = {}
        for var_name in self.config.export:
            if var_name not in self.__session_variables:
                raise ParamsError(
                    f"failed to export variable {var_name} from session variables {self.__session_variables}"
                )

            export_vars_mapping[var_name] = self.__session_variables[var_name]

        return export_vars_mapping
Beispiel #7
0
    def get_export_variables(self) -> Dict:
        # override testcase export vars with step export
        export_var_names = self.__export or self.__config.export
        export_vars_mapping = {}
        for var_name in export_var_names:
            if var_name not in self.__session_variables:
                raise ParamsError(
                    f"failed to export variable {var_name} from session variables {self.__session_variables}"
                )

            export_vars_mapping[var_name] = self.__session_variables[var_name]

        return export_vars_mapping
Beispiel #8
0
    def __run_step(self, step: TStep):
        """run teststep, teststep maybe a request or referenced testcase"""
        logger.info(f"run step: {step.name}")

        if step.request:
            step_data = self.__run_step_request(step)
        elif step.testcase:
            step_data = self.__run_step_testcase(step)
        else:
            raise ParamsError(
                f"teststep is neither a request nor a referenced testcase: {step.dict()}"
            )

        self.__step_datas.append(step_data)
        return step_data.export
Beispiel #9
0
def prepare_upload_test(test_dict):
    """ preprocess for upload test
        replace `upload` info with MultipartEncoder

    Args:
        test_dict (dict):

            {
                "variables": {},
                "request": {
                    "url": "http://httpbin.org/upload",
                    "method": "POST",
                    "headers": {
                        "Cookie": "session=AAA-BBB-CCC"
                    },
                    "upload": {
                        "file": "data/file_to_upload"
                        "md5": "123"
                    }
                }
            }

    """
    upload_json = test_dict["request"].pop("upload", {})
    if not upload_json:
        raise ParamsError("invalid upload info: {}".format(upload_json))

    params_list = []
    for key, value in upload_json.items():
        test_dict["variables"][key] = value
        params_list.append("{}=${}".format(key, key))

    params_str = ", ".join(params_list)
    test_dict["variables"][
        "m_encoder"] = "${multipart_encoder(" + params_str + ")}"

    test_dict["request"].setdefault("headers", {})
    test_dict["request"]["headers"][
        "Content-Type"] = "${multipart_content_type($m_encoder)}"

    test_dict["request"]["data"] = "$m_encoder"