How to use _adderr method in tavern

Best Python code snippet using tavern

rest.py

Source:rest.py Github

copy

Full Screen

...69 else:70 expected_status_code.append(self.expected["status_code"])71 if response.status_code not in expected_status_code:72 if 400 <= response.status_code < 500:73 self._adderr(74 "Status code was %s, expected %s:\n%s",75 response.status_code, self.expected["status_code"],76 indent_err_text(json.dumps(body)),77 )78 else:79 self._adderr(80 "Status code was %s, expected %s",81 response.status_code, self.expected["status_code"]82 )83 if self.validate_function:84 try:85 self.validate_function(response)86 except Exception as e: # pylint: disable=broad-except87 self._adderr(88 "Error calling validate function '%s':\n%s",89 self.validate_function.func,90 indent_err_text(traceback.format_exc()),91 e=e92 )93 # Get any keys to save94 saved = {}95 try:96 redirect_url = response.headers["location"]97 except KeyError as e:98 if "redirect_query_params" in self.expected.get("save", {}):99 self._adderr(100 "Wanted to save %s, but there was no redirect url in response",101 self.expected["save"]["redirect_query_params"], e=e102 )103 qp_as_dict = {}104 else:105 parsed = urlparse(redirect_url)106 qp = parsed.query107 qp_as_dict = {i: j[0] for i, j in parse_qs(qp).items()}108 saved.update(self._save_value("body", body))109 saved.update(self._save_value("headers", response.headers))110 saved.update(self._save_value("redirect_query_params", qp_as_dict))111 for cookie in self.expected.get("cookies", []):112 if cookie not in response.cookies:113 self._adderr("No cookie named '%s' in response", cookie)114 try:115 wrapped = get_wrapped_response_function(self.expected["save"]["$ext"])116 except KeyError:117 logger.debug("No save function")118 else:119 try:120 to_save = wrapped(response)121 except Exception as e: # pylint: disable=broad-except122 self._adderr(123 "Error calling save function '%s':\n%s",124 wrapped.func,125 indent_err_text(traceback.format_exc()),126 e=e127 )128 else:129 if isinstance(to_save, dict):130 saved.update(to_save)131 elif not isinstance(to_save, None):132 self._adderr("Unexpected return value '%s' from $ext save function")133 self._validate_block("body", body)134 self._validate_block("headers", response.headers)135 self._validate_block("redirect_query_params", qp_as_dict)136 if self.errors:137 raise TestFailError("Test '{:s}' failed:\n{:s}".format(self.name, self._str_errors()))138 return saved139 def _validate_block(self, blockname, block):140 """Validate a block of the response141 Args:142 blockname (str): which part of the response is being checked143 block (dict): The actual part being checked144 """145 try:146 expected_block = self.expected[blockname] or {}147 except KeyError:148 expected_block = {}149 if isinstance(expected_block, dict):150 special = ["$ext"]151 # This has to be a dict at the moment - might be possible at some152 # point in future to allow a list of multiple ext functions as well153 # but would require some changes in init. Probably need to abtract154 # out the 'checking' a bit more.155 for s in special:156 try:157 expected_block.pop(s)158 except KeyError:159 pass160 logger.debug("Validating %s for %s", blockname, expected_block)161 self.recurse_check_key_match(expected_block, block, blockname)162 def _save_value(self, key, to_check):163 """Save a value in the response for use in future tests164 Args:165 to_check (dict): An element of the response from which the given key166 is extracted167 key (str): Key to use168 Returns:169 dict: dictionary of save_name: value, where save_name is the key we170 wanted to save this value as171 """172 espec = self.expected173 saved = {}174 try:175 expected = espec["save"][key]176 except KeyError:177 logger.debug("Nothing expected to save for %s", key)178 return {}179 if not to_check:180 self._adderr("No %s in response (wanted to save %s)", key, expected)181 else:182 for save_as, joined_key in expected.items():183 split_key = joined_key.split(".")184 try:185 saved[save_as] = recurse_access_key(to_check, copy.copy(split_key))186 except (IndexError, KeyError) as e:187 self._adderr(188 "Wanted to save '%s' from '%s', but it did not exist in the response",189 joined_key, key, e=e190 )191 if saved:192 logger.debug("Saved %s for '%s' from response", saved, key)...

Full Screen

Full Screen

base.py

Source:base.py Github

copy

Full Screen

...15 # None by default?16 self.test_block_config = {"variables": {}}17 def _str_errors(self):18 return "- " + "\n- ".join(self.errors)19 def _adderr(self, msg, *args, **kwargs):20 e = kwargs.get('e')21 if e:22 logger.exception(msg, *args)23 else:24 logger.error(msg, *args)25 self.errors += [(msg % args)]26 @abstractmethod27 def verify(self, response):28 """Verify response against expected values and returns any values that29 we wanted to save for use in future requests30 """31 def recurse_check_key_match(self, expected_block, block, blockname):32 """Valid returned data against expected data33 Todo:34 Optionally use a validation library too35 Args:36 expected_block (dict): expected data37 block (dict): actual data38 blockname (str): 'name' of this block (params, mqtt, etc) for error messages39 """40 if not expected_block:41 logger.debug("Nothing to check against")42 return43 expected_block = format_keys(expected_block, self.test_block_config["variables"])44 if block is None:45 self._adderr("expected %s in the %s, but there was no response body",46 expected_block, blockname)47 return48 logger.debug("expected = %s, actual = %s", expected_block, block)49 if blockname == "body" and (not isinstance(expected_block, type(block))):50 if isinstance(block, list):51 block_type = "list"52 else:53 block_type = "dict"54 if isinstance(expected_block, list):55 expected_type = "list"56 else:57 expected_type = "dict"58 self._adderr("Expected %s to be returned, but a %s was returned",59 block_type, expected_type)60 # Fatal61 return62 for split_key, joined_key, expected_val in yield_keyvals(expected_block):63 try:64 actual_val = recurse_access_key(block, list(split_key))65 except KeyError as e:66 self._adderr("Key not present: %s", joined_key, e=e)67 continue68 except IndexError as e:69 self._adderr("Expected returned list to be of at least length %s but length was %s",70 int(joined_key) + 1, len(block), e=e)71 continue72 logger.debug("%s: %s vs %s", joined_key, expected_val, actual_val)73 try:74 check_keys_match_recursive(expected_val, actual_val, [])75 except exceptions.KeyMismatchError as e:76 logger.error("Key mismatch on %s", joined_key)77 self._adderr("Value mismatch: got '%s' (type: %s), expected '%s' (type: %s)",78 actual_val, type(actual_val), expected_val, type(expected_val), e=e)79 else:...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run tavern automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful