def __repr__(self): args_string = "" if self._args: str_args = [str(arg) for arg in self._args] args_string += ", ".join(str_args) if self._kwargs: args_string += ", " str_kwargs = [ "{}={}".format(key, str(value)) for key, value in self._kwargs.items() ] args_string += ", ".join(str_kwargs) return "LazyFunction({}({}))".format(self.func_name, args_string)
def _eval_content_functions(self, content): functions_list = extract_functions(content) for func_content in functions_list: function_meta = parse_function(func_content) func_name = function_meta['func_name'] args = function_meta.get('args', []) kwargs = function_meta.get('kwargs', {}) args = self.eval_content_with_bindings(args) kwargs = self.eval_content_with_bindings(kwargs) if func_name in ["parameterize", "P"]: eval_value = self.parameterize(*args, **kwargs) else: func = self.get_bind_function(func_name) eval_value = func(*args, **kwargs) func_content = "${" + func_content + "}" if func_content == content: # content is a variable content = eval_value else: # content contains one or many variables content = content.replace(func_content, str(eval_value), 1) return content
def parse_string_functions(content, variables_mapping, functions_mapping): """ parse string content with functions mapping. Args: content (str): string content to be parsed. variables_mapping (dict): variables mapping. functions_mapping (dict): functions mapping. Returns: str: parsed string content. Examples: >>> content = "abc${add_one(3)}def" >>> functions_mapping = {"add_one": lambda x: x + 1} >>> parse_string_functions(content, functions_mapping) "abc4def" """ functions_list = extract_functions(content) for func_content in functions_list: function_meta = parse_function(func_content) func_name = function_meta["func_name"] args = function_meta.get("args", []) kwargs = function_meta.get("kwargs", {}) args = parse_data(args, variables_mapping, functions_mapping) kwargs = parse_data(kwargs, variables_mapping, functions_mapping) if func_name in ["parameterize", "P"]: if len(args) != 1 or kwargs: raise exceptions.ParamsError("P() should only pass in one argument!") from httprunner import loader eval_value = loader.load_csv_file(args[0]) elif func_name in ["environ", "ENV"]: if len(args) != 1 or kwargs: raise exceptions.ParamsError("ENV() should only pass in one argument!") eval_value = utils.get_os_environ(args[0]) else: func = get_mapping_function(func_name, functions_mapping) eval_value = func(*args, **kwargs) func_content = "${" + func_content + "}" if func_content == content: # content is a function, e.g. "${add_one(3)}" content = eval_value else: # content contains one or many functions, e.g. "abc${add_one(3)}def" content = content.replace( func_content, str(eval_value), 1 ) return content
def request(self, method, url, name=None, **kwargs): """ Constructs and sends a :py:class:`requests.Request`. Returns :py:class:`requests.Response` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param name: (optional) Placeholder, make compatible with Locust's HttpSession :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or \ a (`connect timeout, read timeout <user/advanced.html#timeouts>`_) tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. """ # store detail data of request and response self.meta_data = {} # prepend url with hostname unless it's already an absolute URL url = self._build_url(url) logger.log_info("{method} {url}".format(method=method, url=url)) logger.log_debug("request kwargs(raw): {kwargs}".format(kwargs=kwargs)) # set up pre_request hook for attaching meta data to the request object self.meta_data["method"] = method kwargs.setdefault("timeout", 120) self.meta_data["request_time"] = time.time() response = self._send_request_safe_mode(method, url, **kwargs) # record the consumed time self.meta_data["response_time"] = int( (time.time() - self.meta_data["request_time"]) * 1000) self.meta_data["elapsed"] = response.elapsed.total_seconds() self.meta_data["url"] = (response.history and response.history[0] or response)\ .request.path_url self.meta_data["request_headers"] = response.request.headers self.meta_data["request_body"] = response.request.body self.meta_data["status_code"] = response.status_code self.meta_data["response_headers"] = response.headers self.meta_data["response_body"] = response.text if isinstance(self.meta_data["response_body"], str): self.meta_data["response_body"] = self.meta_data[ "response_body"].encode("utf-8") logger.log_debug("response status_code: {}".format( self.meta_data["status_code"])) logger.log_debug("response headers: {}".format( self.meta_data["response_headers"])) logger.log_debug("response body: {}".format( self.meta_data["response_body"])) # get the length of the content, but if the argument stream is set to True, we take # the size from the content-length header, in order to not trigger fetching of the body if kwargs.get("stream", False): self.meta_data["content_size"] = int( self.meta_data["response_headers"].get("content-length") or 0) else: self.meta_data["content_size"] = len(response.content or "") try: response.raise_for_status() except RequestException as e: logger.log_error(u"{exception}".format(exception=str(e))) else: logger.log_info( """status_code: {}, response_time: {} ms, response_length: {} bytes""" .format(self.meta_data["status_code"], self.meta_data["response_time"], self.meta_data["content_size"])) return response
def length_equals(check_value, expect_value): assert isinstance(expect_value, integer_types) if isinstance(check_value, int): assert len(str(check_value)) == expect_value else: assert len(check_value) == expect_value