Best Python code snippet using lisa_python
validate.py
Source:validate.py  
...67        self.schemes = schemes or self.default_schemes68        self.require_tld = require_tld69    def _repr_args(self):70        return 'relative={0!r}'.format(self.relative)71    def _format_error(self, value):72        return self.error.format(input=value)73    def __call__(self, value):74        message = self._format_error(value)75        if not value:76            raise ValidationError(message)77        # Check first if the scheme is valid78        if '://' in value:79            scheme = value.split('://')[0].lower()80            if scheme not in self.schemes:81                raise ValidationError(message)82        regex = self._regex(self.relative, self.require_tld)83        if not regex.search(value):84            raise ValidationError(message)85        return value86class Email(Validator):87    """Validate an email address.88    :param str error: Error message to raise in case of a validation error. Can be89        interpolated with `{input}`.90    """91    USER_REGEX = re.compile(92        r"(^[-!#$%&'*+/=?^`{}|~\w]+(\.[-!#$%&'*+/=?^`{}|~\w]+)*$"  # dot-atom93        # quoted-string94        r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]'95        r'|\\[\001-\011\013\014\016-\177])*"$)', re.IGNORECASE | re.UNICODE)96    DOMAIN_REGEX = re.compile(97        # domain98        r'(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+'99        r'(?:[A-Z]{2,6}|[A-Z0-9-]{2,})$'100        # literal form, ipv4 address (SMTP 4.1.3)101        r'|^\[(25[0-5]|2[0-4]\d|[0-1]?\d?\d)'102        r'(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\]$', re.IGNORECASE | re.UNICODE)103    DOMAIN_WHITELIST = ('localhost',)104    default_message = 'Not a valid email address.'105    def __init__(self, error=None):106        self.error = error or self.default_message107    def _format_error(self, value):108        return self.error.format(input=value)109    def __call__(self, value):110        message = self._format_error(value)111        if not value or '@' not in value:112            raise ValidationError(message)113        user_part, domain_part = value.rsplit('@', 1)114        if not self.USER_REGEX.match(user_part):115            raise ValidationError(message)116        if domain_part not in self.DOMAIN_WHITELIST:117            if not self.DOMAIN_REGEX.match(domain_part):118                try:119                    domain_part = domain_part.encode('idna').decode('ascii')120                except UnicodeError:121                    pass122                else:123                    if self.DOMAIN_REGEX.match(domain_part):124                        return value125                raise ValidationError(message)126        return value127class Range(Validator):128    """Validator which succeeds if the value it is passed is greater129    or equal to ``min`` and less than or equal to ``max``. If ``min``130    is not specified, or is specified as `None`, no lower bound131    exists. If ``max`` is not specified, or is specified as `None`,132    no upper bound exists.133    :param min: The minimum value (lower bound). If not provided, minimum134        value will not be checked.135    :param max: The maximum value (upper bound). If not provided, maximum136        value will not be checked.137    :param str error: Error message to raise in case of a validation error.138        Can be interpolated with `{input}`, `{min}` and `{max}`.139    """140    message_min = 'Must be at least {min}.'141    message_max = 'Must be at most {max}.'142    message_all = 'Must be between {min} and {max}.'143    def __init__(self, min=None, max=None, error=None):144        self.min = min145        self.max = max146        self.error = error147    def _repr_args(self):148        return 'min={0!r}, max={1!r}'.format(self.min, self.max)149    def _format_error(self, value, message):150        return (self.error or message).format(input=value, min=self.min, max=self.max)151    def __call__(self, value):152        if self.min is not None and value < self.min:153            message = self.message_min if self.max is None else self.message_all154            raise ValidationError(self._format_error(value, message))155        if self.max is not None and value > self.max:156            message = self.message_max if self.min is None else self.message_all157            raise ValidationError(self._format_error(value, message))158        return value159class Length(Range):160    """Validator which succeeds if the value passed to it has a161    length between a minimum and maximum. Uses len(), so it162    can work for strings, lists, or anything with length.163    :param int min: The minimum length. If not provided, minimum length164        will not be checked.165    :param int max: The maximum length. If not provided, maximum length166        will not be checked.167    :param int equal: The exact length. If provided, maximum and minimum168        length will not be checked.169    :param str error: Error message to raise in case of a validation error.170        Can be interpolated with `{input}`, `{min}` and `{max}`.171    """172    message_min = 'Shorter than minimum length {min}.'173    message_max = 'Longer than maximum length {max}.'174    message_all = 'Length must be between {min} and {max}.'175    message_equal = 'Length must be {equal}.'176    def __init__(self, min=None, max=None, error=None, equal=None):177        if equal is not None and any([min, max]):178            raise ValueError(179                'The `equal` parameter was provided, maximum or '180                'minimum parameter must not be provided.'181            )182        super(Length, self).__init__(min, max, error)183        self.equal = equal184    def _repr_args(self):185        return 'min={0!r}, max={1!r}, equal={2!r}'.format(self.min, self.max, self.equal)186    def _format_error(self, value, message):187        return (self.error or message).format(input=value, min=self.min, max=self.max,188                                              equal=self.equal)189    def __call__(self, value):190        length = len(value)191        if self.equal is not None:192            if length != self.equal:193                raise ValidationError(self._format_error(value, self.message_equal))194            return value195        if self.min is not None and length < self.min:196            message = self.message_min if self.max is None else self.message_all197            raise ValidationError(self._format_error(value, message))198        if self.max is not None and length > self.max:199            message = self.message_max if self.min is None else self.message_all200            raise ValidationError(self._format_error(value, message))201        return value202class Equal(Validator):203    """Validator which succeeds if the ``value`` passed to it is204    equal to ``comparable``.205    :param comparable: The object to compare to.206    :param str error: Error message to raise in case of a validation error.207        Can be interpolated with `{input}` and `{other}`.208    """209    default_message = 'Must be equal to {other}.'210    def __init__(self, comparable, error=None):211        self.comparable = comparable212        self.error = error or self.default_message213    def _repr_args(self):214        return 'comparable={0!r}'.format(self.comparable)215    def _format_error(self, value):216        return self.error.format(input=value, other=self.comparable)217    def __call__(self, value):218        if value != self.comparable:219            raise ValidationError(self._format_error(value))220        return value221class Regexp(Validator):222    """Validate ``value`` against the provided regex.223    :param regex: The regular expression string to use. Can also be a compiled224        regular expression pattern.225    :param flags: The regexp flags to use, for example re.IGNORECASE. Ignored226        if ``regex`` is not a string.227    :param str error: Error message to raise in case of a validation error.228        Can be interpolated with `{input}` and `{regex}`.229    """230    default_message = 'String does not match expected pattern.'231    def __init__(self, regex, flags=0, error=None):232        self.regex = re.compile(regex, flags) if isinstance(regex, basestring) else regex233        self.error = error or self.default_message234    def _repr_args(self):235        return 'regex={0!r}'.format(self.regex)236    def _format_error(self, value):237        return self.error.format(input=value, regex=self.regex.pattern)238    def __call__(self, value):239        if self.regex.match(value) is None:240            raise ValidationError(self._format_error(value))241        return value242class Predicate(Validator):243    """Call the specified ``method`` of the ``value`` object. The244    validator succeeds if the invoked method returns an object that245    evaluates to True in a Boolean context. Any additional keyword246    argument will be passed to the method.247    :param str method: The name of the method to invoke.248    :param str error: Error message to raise in case of a validation error.249        Can be interpolated with `{input}` and `{method}`.250    :param kwargs: Additional keyword arguments to pass to the method.251    """252    default_message = 'Invalid input.'253    def __init__(self, method, error=None, **kwargs):254        self.method = method255        self.error = error or self.default_message256        self.kwargs = kwargs257    def _repr_args(self):258        return 'method={0!r}, kwargs={1!r}'.format(self.method, self.kwargs)259    def _format_error(self, value):260        return self.error.format(input=value, method=self.method)261    def __call__(self, value):262        method = getattr(value, self.method)263        if not method(**self.kwargs):264            raise ValidationError(self._format_error(value))265        return value266class NoneOf(Validator):267    """Validator which fails if ``value`` is a member of ``iterable``.268    :param iterable iterable: A sequence of invalid values.269    :param str error: Error message to raise in case of a validation error. Can be270        interpolated using `{input}` and `{values}`.271    """272    default_message = 'Invalid input.'273    def __init__(self, iterable, error=None):274        self.iterable = iterable275        self.values_text = ', '.join(text_type(each) for each in self.iterable)276        self.error = error or self.default_message277    def _repr_args(self):278        return 'iterable={0!r}'.format(self.iterable)279    def _format_error(self, value):280        return self.error.format(281            input=value,282            values=self.values_text,283        )284    def __call__(self, value):285        try:286            if value in self.iterable:287                raise ValidationError(self._format_error(value))288        except TypeError:289            pass290        return value291class OneOf(Validator):292    """Validator which succeeds if ``value`` is a member of ``choices``.293    :param iterable choices: A sequence of valid values.294    :param iterable labels: Optional sequence of labels to pair with the choices.295    :param str error: Error message to raise in case of a validation error. Can be296        interpolated with `{input}`, `{choices}` and `{labels}`.297    """298    default_message = 'Not a valid choice.'299    def __init__(self, choices, labels=None, error=None):300        self.choices = choices301        self.choices_text = ', '.join(text_type(choice) for choice in self.choices)302        self.labels = labels if labels is not None else []303        self.labels_text = ', '.join(text_type(label) for label in self.labels)304        self.error = error or self.default_message305    def _repr_args(self):306        return 'choices={0!r}, labels={1!r}'.format(self.choices, self.labels)307    def _format_error(self, value):308        return self.error.format(309            input=value,310            choices=self.choices_text,311            labels=self.labels_text,312        )313    def __call__(self, value):314        try:315            if value not in self.choices:316                raise ValidationError(self._format_error(value))317        except TypeError:318            raise ValidationError(self._format_error(value))319        return value320    def options(self, valuegetter=text_type):321        """Return a generator over the (value, label) pairs, where value322        is a string associated with each choice. This convenience method323        is useful to populate, for instance, a form select field.324        :param valuegetter: Can be a callable or a string. In the former case, it must325            be a one-argument callable which returns the value of a326            choice. In the latter case, the string specifies the name327            of an attribute of the choice objects. Defaults to `str()`328            or `unicode()`.329        """330        valuegetter = valuegetter if callable(valuegetter) else attrgetter(valuegetter)331        pairs = zip_longest(self.choices, self.labels, fillvalue='')332        return ((valuegetter(choice), label) for choice, label in pairs)333class ContainsOnly(OneOf):334    """Validator which succeeds if ``value`` is a sequence and each element335    in the sequence is also in the sequence passed as ``choices``.336    :param iterable choices: Same as :class:`OneOf`.337    :param iterable labels: Same as :class:`OneOf`.338    :param str error: Same as :class:`OneOf`.339    """340    default_message = 'One or more of the choices you made was not acceptable.'341    def _format_error(self, value):342        value_text = ', '.join(text_type(val) for val in value)343        return super(ContainsOnly, self)._format_error(value_text)344    def __call__(self, value):345        choices = list(self.choices)346        if not value and choices:347            raise ValidationError(self._format_error(value))348        # We check list.index instead of using set.issubset so that349        # unhashable types are handled.350        for val in value:351            try:352                index = choices.index(val)353            except ValueError:354                raise ValidationError(self._format_error(value))355            else:356                del choices[index]...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!!
