Best Python code snippet using gabbi_python
case.py
Source:case.py  
...183        value = '%s' % value184        value = value.encode('UTF-8')185        return value186    @staticmethod187    def _regex_replacer(replacer, escape_regex):188        """Wrap a replacer function to escape return values in a regex."""189        if escape_regex:190            @functools.wraps(replacer)191            def replace(match):192                return re.escape(replacer(match))193            return replace194        else:195            return replacer196    def _cast_value(self, value, message):197        """Cast a replacement value the cast is in APPROVED_CASTS."""198        # Turn off the casting flag, to reset state199        cast = self.cast200        self.cast = None201        if cast in APPROVED_CASTS:202            return APPROVED_CASTS[cast](value)203        else:204            raise RuntimeError('Invalid cast <%s> used in: %s' % (205                cast, message))206    def _environ_replace(self, message, escape_regex=False):207        """Replace an indicator in a message with the environment value.208        If value can be a number, cast it as such. If value is a form of209        "null", "true", or "false" cast it to None, True, False.210        """211        value = re.sub(self._replacer_regex('ENVIRON'),212                       self._regex_replacer(self._environ_replacer,213                                            escape_regex),214                       message)215        if self.cast:216            return self._cast_value(value, message)217        else:218            try:219                if '.' in value:220                    value = float(value)221                else:222                    value = int(value)223                return value224            except ValueError:225                pass226            if value.lower() == "false":227                return False228            if value.lower() == "true":229                return True230            if value.lower() == "null":231                return None232            return value233    def _environ_replacer(self, match):234        """Replace a regex match with an environment value.235        Let KeyError raise if variable not present. Capture236        the 'cast' if any.237        """238        environ_name = match.group('arg')239        self.cast = match.group('cast')240        return os.environ[environ_name]241    def _cookie_replace(self, message, escape_regex=False):242        """Replace $COOKIE in a message.243        With cookie data from set-cookie in the prior request.244        """245        return re.sub(self._simple_replacer_regex('COOKIE'),246                      self._regex_replacer(self._cookie_replacer,247                                           escape_regex),248                      message)249    def _cookie_replacer(self, match):250        """Replace a regex match with the cookie of a previous response."""251        case = match.group('case')252        if case:253            referred_case = self.history[case]254        else:255            referred_case = self.prior256        response_cookies = referred_case.response['set-cookie']257        cookies = http_cookies.SimpleCookie()258        cookies.load(response_cookies)259        cookie_string = cookies.output(attrs=[], header='', sep=',').strip()260        return cookie_string261    def _headers_replace(self, message, escape_regex=False):262        """Replace a header indicator in a message.263        Replace it with the header's value from the prior request.264        """265        return re.sub(self._replacer_regex('HEADERS'),266                      self._regex_replacer(self._header_replacer,267                                           escape_regex),268                      message)269    def _header_replacer(self, match):270        """Replace a regex match with the value of a prior header."""271        header_key = match.group('arg')272        case = match.group('case')273        if case:274            referred_case = self.history[case]275        else:276            referred_case = self.prior277        return referred_case.response[header_key.lower()]278    def _last_url_replace(self, message, escape_regex=False):279        """Replace $LAST_URL in a message.280        With the URL used in the prior request.281        """282        last_url = self.prior.url283        if escape_regex:284            last_url = re.escape(last_url)285        return message.replace('$LAST_URL', last_url)286    def _url_replace(self, message, escape_regex=False):287        """Replace $URL in a message.288        With the URL used in a previous request.289        """290        return re.sub(self._simple_replacer_regex('URL'),291                      self._regex_replacer(self._url_replacer,292                                           escape_regex),293                      message)294    def _url_replacer(self, match):295        """Replace a regex match with the value of a previous url."""296        case = match.group('case')297        if case:298            referred_case = self.history[case]299        else:300            referred_case = self.prior301        return referred_case.url302    def _location_replace(self, message, escape_regex=False):303        """Replace $LOCATION in a message.304        With the location header from a previous request.305        """306        return re.sub(self._simple_replacer_regex('LOCATION'),307                      self._regex_replacer(self._location_replacer,308                                           escape_regex),309                      message)310    def _location_replacer(self, match):311        """Replace a regex match with the value of a previous location."""312        case = match.group('case')313        if case:314            referred_case = self.history[case]315        else:316            referred_case = self.prior317        return referred_case.location318    def _load_data_file(self, filename):319        """Read a file from the current test directory."""320        path = os.path.join(self.test_directory, filename)321        has_dir_traversal = os.path.relpath(322            path, start=self.test_directory).startswith(os.pardir)323        if has_dir_traversal:324            raise ValueError(325                'Attempted loading of data file outside test directory: %s'326                % filename)327        with open(path, mode='rb') as data_file:328            return data_file.read()329    def _netloc_replace(self, message, escape_regex=False):330        """Replace $NETLOC with the current host and port."""331        netloc = self.netloc332        if self.prefix:333            netloc = '%s%s' % (netloc, self.prefix)334        if escape_regex:335            netloc = re.escape(netloc)336        return message.replace('$NETLOC', netloc)337    def _parse_url(self, url):338        """Create a url from test data.339        If provided with a full URL, just return that. If SSL is requested340        set the scheme appropriately.341        Scheme and netloc are saved for later use in comparisons.342        """343        query_params = self.test_data['query_parameters']344        ssl = self.test_data['ssl']345        parsed_url = urlparse.urlsplit(url)346        if not parsed_url.scheme:347            full_url = utils.create_url(url, self.host, port=self.port,348                                        prefix=self.prefix, ssl=ssl)349            # parse again to set updated netloc and scheme350            parsed_url = urlparse.urlsplit(full_url)351        self.scheme = parsed_url.scheme352        self.netloc = parsed_url.netloc353        if query_params:354            query_string = self._update_query_params(parsed_url.query,355                                                     query_params)356        else:357            query_string = parsed_url.query358        return urlparse.urlunsplit((parsed_url.scheme, parsed_url.netloc,359                                    parsed_url.path, query_string, ''))360    _history_regex = (361        r"(?:\$HISTORY\[(?P<quote1>['\"])(?P<case>.+?)(?P=quote1)\]\.)??"362    )363    @staticmethod364    def _replacer_regex(key):365        """Compose a regular expression for test template variables."""366        case = HTTPTestCase._history_regex367        return (368            r"%s\$%s(:(?P<cast>\w+))?"369            r"\[(?P<quote>['\"])(?P<arg>.+?)(?P=quote)\]"370            % (case, key))371    @staticmethod372    def _simple_replacer_regex(key):373        """Compose a regular expression for simple variable replacement."""374        case = HTTPTestCase._history_regex375        return r"%s\$%s" % (case, key)376    def _response_replace(self, message, escape_regex=False):377        """Replace a content path with the value from a previous response.378        If the match would replace the entire message, then don't cast it379        to a string.380        """381        regex = self._replacer_regex('RESPONSE')382        match = re.match('^%s$' % regex, message)383        if match:384            return self._response_replacer(match, preserve=True)385        return re.sub(regex,386                      self._regex_replacer(self._response_replacer,387                                           escape_regex),388                      message)389    def _response_replacer(self, match, preserve=False):390        """Replace a regex match with the value from a previous response."""391        response_path = match.group('arg')392        case = match.group('case')393        self.cast = match.group('cast')394        if not preserve and self.cast:395            raise RuntimeError(396                'Unable to process cast <%s> within message: %s'397                % (self.cast, match.string))398        if case:399            referred_case = self.history[case]400        else:...controller.py
Source:controller.py  
...14class NewTestEmailNotification(Notification):15    def __init__(self, classname, source_address, params, module=None):16        Notification.__init__(self, classname, source_address, params, module)17        18    def _regex_replacer(self, matchobj):19        command = matchobj.group(1)20        if command == 'readable':21            parameter = 'type, format, timezone, mapped_aliases'22        else:23            parameter = 'format, timezone'24        25        return '| %s(%s)}}' % (command, parameter)26    def pre_extract(self):27        #Collection is 'Alert' by default. Make it dynamic later28        id = is_mongokit_objectid(self.params.get("alert_id", None))29        if id:30            return {"_id":id}31        32        return {}...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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
