How to use py2to3 method in Robotframework

Best Python code snippet using robotframework

fields.py

Source:fields.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2import uuid3import decimal4from collections import Iterable5from aserializer.utils import py2to36from aserializer.fields.base import BaseSerializerField, IgnoreField, SerializerFieldValueError7from aserializer.fields import validators as v8class TypeField(BaseSerializerField):9 def __init__(self, name, fixed=False, validate=False, identity=True, *args, **kwargs):10 super(TypeField, self).__init__(*args, **kwargs)11 self.name = name12 self._initial_name = name13 self.identity = identity14 self.error_messages = {}15 self.should_validate = validate16 self.fixed = fixed17 self.has_default = self.has_default or self._initial_name is not None18 def validate(self):19 if self.should_validate:20 if self.name != self._initial_name:21 raise SerializerFieldValueError('Value is not {}.'.format(self._initial_name), field_names=self.names)22 def set_value(self, value):23 if not self.fixed:24 self.name = value25 def to_native(self):26 return py2to3._unicode(self.name)27 def to_python(self):28 return py2to3._unicode(self.name)29 def __set__(self, instance, value):30 pass31class IntegerField(BaseSerializerField):32 validators = [v.validate_integer, ]33 def __init__(self, max_value=None, min_value=None, *args, **kwargs):34 super(IntegerField, self).__init__(*args, **kwargs)35 if max_value is not None:36 self._validators.append(v.MaxValueValidator(max_value))37 if min_value is not None:38 self._validators.append(v.MinValueValidator(min_value))39 @staticmethod40 def to_int(value):41 if value in v.VALIDATORS_EMPTY_VALUES:42 return None43 return int(value)44 def _to_native(self):45 return self.to_int(self.value)46 def _to_python(self):47 return self.to_int(self.value)48class PositiveIntegerField(IntegerField):49 def __init__(self, max_value=None, *args, **kwargs):50 super(PositiveIntegerField, self).__init__(max_value=max_value, min_value=0, *args, **kwargs)51class FloatField(IntegerField):52 validators = [v.validate_float, ]53 @staticmethod54 def to_float(value):55 if value in v.VALIDATORS_EMPTY_VALUES:56 return None57 return float(value)58 def _to_native(self):59 return self.to_float(self.value)60 def _to_python(self):61 return self.to_float(self.value)62class DecimalField(IntegerField):63 OUTPUT_AS_FLOAT = 064 OUTPUT_AS_STRING = 165 validators = [v.validate_decimal, ]66 def __init__(self, decimal_places=3, precision=None, max_value=None, min_value=None, output=None, **kwargs):67 super(DecimalField, self).__init__(max_value=max_value, min_value=min_value, **kwargs)68 self.decimal_places = decimal_places69 self.precision = precision70 if self.value and not isinstance(self.value, decimal.Decimal):71 self.set_value(self.value)72 if output is None or output not in (0, 1):73 self.output = self.OUTPUT_AS_FLOAT74 else:75 self.output = output76 def set_value(self, value):77 context = decimal.getcontext().copy()78 if self.precision is not None:79 context.prec = self.precision80 if isinstance(value, decimal.Decimal):81 self.value = value.quantize(decimal.Decimal(".1") ** self.decimal_places, context=context)82 elif isinstance(value, (py2to3.integer, float,)):83 self.value = decimal.Decimal(value).quantize(decimal.Decimal(".1") ** self.decimal_places, context=context)84 elif isinstance(value, py2to3.string):85 try:86 self.value = decimal.Decimal(value).quantize(decimal.Decimal(".1") ** self.decimal_places,87 context=context)88 except:89 self.value = value90 else:91 self.value = None92 def _to_native(self):93 if self.value in v.VALIDATORS_EMPTY_VALUES:94 return None95 if self.output == self.OUTPUT_AS_STRING:96 result = str(self.value)97 else:98 result = float(u'{}'.format(self.value))99 return result100 def _to_python(self):101 if self.value in v.VALIDATORS_EMPTY_VALUES:102 return None103 return self.value104 @staticmethod105 def __pre_eq__(other):106 if isinstance(other, decimal.Decimal):107 return other108 elif isinstance(other, py2to3.integer):109 return decimal.Decimal(other)110 elif isinstance(other, float):111 return decimal.Decimal(str(other))112 elif isinstance(other, py2to3.string):113 try:114 d = decimal.Decimal(str(other))115 except:116 raise ValueError()117 else:118 return d119 raise ValueError()120 def __eq__(self, other):121 if not isinstance(self.value, decimal.Decimal):122 return False123 try:124 _other = self.__pre_eq__(other=other)125 except ValueError:126 return False127 else:128 return self.value == _other129class BooleanField(BaseSerializerField):130 def __init__(self, required=False, *args, **kwargs):131 super(BooleanField, self).__init__(required=required, *args, **kwargs)132 def set_value(self, value):133 if value in v.VALIDATORS_EMPTY_VALUES:134 self.value = None135 elif isinstance(value, py2to3.string) and value.lower() in ('false', '0'):136 self.value = False137 else:138 self.value = bool(value)139 def _to_native(self):140 return self.value141 def _to_python(self):142 return self.value143 def to_native(self):144 result = super(BooleanField, self).to_native()145 return bool(result)146class StringField(BaseSerializerField):147 validators = [v.validate_string, ]148 def __init__(self, max_length=None, min_length=None, **kwargs):149 super(StringField, self).__init__(**kwargs)150 if max_length is not None:151 self._validators.append(v.MaxStringLengthValidator(max_length))152 if min_length is not None:153 self._validators.append(v.MinStringLengthValidator(min_length))154 @staticmethod155 def to_unicode(value):156 if value in v.VALIDATORS_EMPTY_VALUES:157 return u''158 return py2to3._unicode(value)159 def _to_native(self):160 return self.to_unicode(self.value)161 def _to_python(self):162 return self.to_unicode(self.value)163class EmailField(StringField):164 validators = [v.validate_email, ]165class UUIDField(BaseSerializerField):166 validators = [v.validate_uuid, ]167 def __init__(self, upper=True, binary=True, *args, **kwargs):168 """169 To native always returns a string representation. Upper specifies if it should be upper- or lower-case170 To python returns a UUID object if binary is True (default), otherwise a lowercase string uuid.171 """172 super(UUIDField, self).__init__(*args, **kwargs)173 self.upper = upper174 self.binary = binary175 def _to_native(self):176 if self.value in v.VALIDATORS_EMPTY_VALUES:177 return u''178 if self.upper:179 return py2to3._unicode(self.value).upper()180 else:181 return py2to3._unicode(self.value)182 def _to_python(self):183 if self.value in v.VALIDATORS_EMPTY_VALUES:184 return None185 if self.binary and not isinstance(self.value, uuid.UUID):186 self.value = uuid.UUID(str(self.value))187 if not self.binary:188 return py2to3._unicode(self.value).lower()189 return self.value190class UrlField(BaseSerializerField):191 validators = [v.validate_url, ]192 def __init__(self, base=None, *args, **kwargs):193 super(UrlField, self).__init__(*args, **kwargs)194 self.uri_base = base195 if self.uri_base and not str(self.uri_base).endswith('/'):196 self.uri_base = '{}/'.format(self.uri_base)197 if self.value:198 self.set_value(value=self.value)199 @staticmethod200 def to_unicode(value):201 if value in v.VALIDATORS_EMPTY_VALUES:202 return u''203 return py2to3._unicode(value)204 def set_value(self, value):205 if self.uri_base:206 self.value = '{}{}'.format(self.uri_base, value)207 else:208 self.value = value209 def _to_native(self):210 return self.to_unicode(self.value)211 def _to_python(self):212 return self.to_unicode(self.value)213class ChoiceField(BaseSerializerField):214 error_messages = {215 'required': 'This field is required.',216 'invalid': 'Invalid choice value.',217 }218 def __init__(self, choices=None, upper=False, *args, **kwargs):219 super(ChoiceField, self).__init__(*args, **kwargs)220 self.choices = choices or ()221 self.upper = upper222 self.set_value(self.value)223 def set_value(self, value):224 if self.upper and isinstance(value, py2to3.string):225 value = value.lower()226 self.value = value227 self.python_value = self._get_value(value, to_python=True)228 self.native_value = self._get_value(value, to_python=False)229 def _get_key_value_from_choice_element(self, choice):230 if isinstance(choice, (list, tuple,)):231 try:232 val = choice[0]233 key = choice[1]234 except IndexError:235 return None, None236 return key, val237 return choice, choice238 def _get_value(self, value, to_python=True):239 if value in v.VALIDATORS_EMPTY_VALUES:240 return None241 for choice in self.choices:242 key, val = self._get_key_value_from_choice_element(choice)243 if value == key or value == val:244 if to_python:245 return val246 else:247 return key248 return None249 def validate(self):250 super(ChoiceField, self).validate()251 if self.value in v.VALIDATORS_EMPTY_VALUES:252 return253 _val = self._get_value(self.value)254 if _val is None:255 raise SerializerFieldValueError(self._error_messages['invalid'], field_names=self.names)256 def _to_native(self):257 value = self.native_value258 if self.upper and isinstance(value, py2to3.string):259 value = value.upper()260 return value261 def _to_python(self):262 value = self.python_value263 if self.upper and isinstance(value, py2to3.string):264 value = value.lower()265 return value266class ListField(BaseSerializerField):267 def __init__(self, field, *args, **kwargs):268 super(ListField, self).__init__(*args, **kwargs)269 self._field_cls = field270 self.items = []271 self._python_items = []272 self._native_items = []273 def validate(self):274 if self.items:275 _errors = []276 for field in self.items:277 try:278 field.validate()279 except SerializerFieldValueError as e:280 _errors.append(e.errors)281 if _errors:282 raise SerializerFieldValueError(_errors)283 elif self.required:284 raise SerializerFieldValueError(self._error_messages['required'], field_names=self.names)285 def add_item(self, value):286 field = self._field_cls()287 field.set_value(value=value)288 self.items.append(field)289 def set_value(self, value):290 self.items[:] = []291 self._native_items[:] = []292 self._python_items[:] = []293 if isinstance(value, Iterable):294 for item in value:295 self.add_item(value=item)296 def _to_native(self):297 if not self._native_items:298 for field in self.items:299 self._native_items.append(field.to_native())300 return self._native_items301 def _to_python(self):302 if not self._python_items:303 for field in self.items:304 self._python_items.append(field.to_python())305 return self._python_items306 def append(self, value):307 self.add_item(value=value)308 self.validate()309 def __iter__(self):310 return self.to_python().__iter__()311 def __get__(self, instance, owner):312 if instance is None:313 return self314 field, field_name = self._get_field_from_instance(instance=instance)315 return field316 def __set__(self, instance, value):317 if instance is None:318 return319 field, field_name = self._get_field_from_instance(instance=instance)320 if field is None:321 return322 self.ignore = False323 for name in self.names:324 try:325 value = instance.clean_field_value(name, value)326 except IgnoreField:327 self.ignore = True328 field.set_value(value=value)329 field.validate()330 instance.update_field(field)331 def __setitem__(self, i, value):332 del self.items[i]333 self.add_item(value=value)334 self.validate()335 def __getitem__(self, y):336 return self.to_python()[y]337 def __len__(self):338 return len(self.items)339 def __contains__(self, value):...

Full Screen

Full Screen

toxcmd3.py

Source:toxcmd3.py Github

copy

Full Screen

...122# -----------------------------------------------------------------------------123# SUBCOMMAND: py2to3124# -----------------------------------------------------------------------------125command_py2to4_work_around3k = True126def command_py2to3(args):127 """128 Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.129 """130 from lib2to3.main import main131 args2 = []132 if command_py2to4_work_around3k:133 if args.no_diffs:134 args2.append("--no-diffs")135 if args.write:136 args2.append("-w")137 if args.nobackups:138 args2.append("-n")139 args2.extend(args.sources)140 sys.exit(main("lib2to3.fixes", args=args2))141def setup_parser4py2to3(parser):142 if command_py2to4_work_around3k:143 parser.add_argument("--no-diffs", action="store_true",144 help="Don't show diffs of the refactoring")145 parser.add_argument("-w", "--write", action="store_true",146 help="Write back modified files")147 parser.add_argument("-n", "--nobackups", action="store_true", default=False,148 help="Don't write backups for modified files.")149 parser.add_argument("sources", nargs="+", help="Source files.")150command_py2to3.name = "2to3"151command_py2to3.usage = "%(prog)s sources..."152command_py2to3.short = "Apply python's 2to3 tool to Python sources."153command_py2to3.setup_parser = setup_parser4py2to3154# -----------------------------------------------------------------------------155# COMMAND HELPERS/UTILS:...

Full Screen

Full Screen

toxcmd.py

Source:toxcmd.py Github

copy

Full Screen

...122# -----------------------------------------------------------------------------123# SUBCOMMAND: py2to3124# -----------------------------------------------------------------------------125command_py2to3_work_around3k = six.PY3126def command_py2to3(args):127 """128 Apply '2to3' tool (Python2 to Python3 conversion tool) to Python sources.129 """130 from lib2to3.main import main131 args2 = []132 if command_py2to3_work_around3k:133 if args.no_diffs:134 args2.append("--no-diffs")135 if args.write:136 args2.append("-w")137 if args.nobackups:138 args2.append("-n")139 args2.extend(args.sources)140 sys.exit(main("lib2to3.fixes", args=args2))141def setup_parser4py2to3(parser):142 if command_py2to3_work_around3k:143 parser.add_argument("--no-diffs", action="store_true",144 help="Don't show diffs of the refactoring")145 parser.add_argument("-w", "--write", action="store_true",146 help="Write back modified files")147 parser.add_argument("-n", "--nobackups", action="store_true", default=False,148 help="Don't write backups for modified files.")149 parser.add_argument("sources", nargs="+", help="Source files.")150command_py2to3.name = "2to3"151command_py2to3.usage = "%(prog)s sources..."152command_py2to3.short = "Apply python's 2to3 tool to Python sources."153command_py2to3.setup_parser = setup_parser4py2to3154# -----------------------------------------------------------------------------155# COMMAND HELPERS/UTILS:...

Full Screen

Full Screen

validators.py

Source:validators.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2import uuid3import re4import decimal5from aserializer.utils import py2to36VALIDATORS_EMPTY_VALUES = (None, 'null', '', u'', [], (), {})7class SerializerValidatorError(Exception):8 error_code = None9 message = ''10 def __init__(self, message=None, error_code=None, params=None):11 self.message = message or self.message12 self.error_code = error_code or self.error_code13 if params:14 self.message %= params15 def __str__(self):16 return repr(self.message)17 def __repr__(self):18 return u'{}'.format(self.message)19class SerializerInvalidError(SerializerValidatorError):20 error_code = 'invalid'21class SerializerRequiredError(SerializerValidatorError):22 error_code = 'required'23class CompareValidator(object):24 compare = lambda self, a, b: a is not b25 message = 'Value should be %(compare_value)s (it is %(value)s).'26 error_code = 'compare'27 def __init__(self, compare_value):28 self.compare_value = compare_value29 def __call__(self, value):30 if self.compare(value, self.compare_value):31 self.raise_validation_error(value)32 def raise_validation_error(self, value):33 params = {'compare_value': self.compare_value, 'value': value}34 raise SerializerValidatorError(message=self.message, error_code=self.error_code, params=params)35class ConvertAndCompareValidator(CompareValidator):36 """37 Some fields might require casting of string values to the type of the compare_value.38 """39 def __call__(self, value):40 if isinstance(value, py2to3.string) and not isinstance(self.compare_value, py2to3.string):41 try:42 value = type(self.compare_value)(value)43 except ValueError:44 return45 super(ConvertAndCompareValidator, self).__call__(value)46class MaxValueValidator(ConvertAndCompareValidator):47 compare = lambda self, a, b: a > b48 message = 'Value is greater than %(compare_value)s.'49 error_code = 'max_value'50class MinValueValidator(ConvertAndCompareValidator):51 compare = lambda self, a, b: a < b52 message = 'Value is less than %(compare_value)s.'53 error_code = 'min_value'54def validate_integer(value):55 try:56 int(value)57 except (ValueError, TypeError):58 raise SerializerValidatorError('Enter a valid integer.', error_code='invalid')59def validate_float(value):60 try:61 float(value)62 except (ValueError, TypeError):63 raise SerializerValidatorError('Enter a valid float.', error_code='invalid')64def validate_decimal(value):65 if isinstance(value, decimal.Decimal):66 return67 try:68 decimal.Decimal(value)69 except (ValueError, TypeError, decimal.InvalidOperation,):70 raise SerializerValidatorError('Enter a valid decimal.', error_code='invalid')71def validate_string(value):72 if not isinstance(value, py2to3.string):73 raise SerializerValidatorError('Enter a valid string.', error_code='invalid')74class MinStringLengthValidator(CompareValidator):75 compare = lambda self, a, b: len(py2to3._unicode(a)) < b76 message = 'Value is too short. Minimum value length is %(compare_value)s.'77 code = 'min_length'78class MaxStringLengthValidator(CompareValidator):79 compare = lambda self, a, b: len(py2to3._unicode(a)) > b80 message = 'Value is too long. Maximum value length is %(compare_value)s.'81 code = 'max_length'82RE_UUID = re.compile(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', re.I)83def validate_uuid(value):84 if not isinstance(value, uuid.UUID):85 if not RE_UUID.search(py2to3._unicode(value)):86 raise SerializerValidatorError('Enter a valid uuid.', error_code='invalid')87RE_URL = re.compile(88 r'^(?:http|ftp)s?://'89 r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'90 r'localhost|'91 r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|'92 r'\[?[A-F0-9]*:[A-F0-9:]+\]?)'93 r'(?::\d+)?'94 r'(?:/?|[/?]\S+)$', re.IGNORECASE)95def validate_url(value):96 if not RE_URL.search(py2to3._unicode(value)):97 raise SerializerValidatorError('Enter a valid url.', error_code='invalid')98RE_EMAIL = re.compile(99 r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom100 r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string101 r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', re.IGNORECASE)102def validate_email(value):103 if not RE_EMAIL.search(py2to3._unicode(value)):...

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 Robotframework 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