Best Python code snippet using lemoncheesecake
validators.py
Source:validators.py
...32 duration_str = str(int(hours) + duration_timedelta.days*24) + ':' + minutes_seconds33 return duration_str34 def __call__(self, value):35 if not isinstance(value, dict):36 self._raise_error('invalid')37 #check for valid keys:38 if len(set(value.keys()) - {'vendor', 'id', 'startTime', 'endTime', 'meta',}):39 self._raise_error('invalid')40 #check vendor is allowed:41 video_vendor = value.get('vendor', '')42 if self.allowed_vendors is not None:43 if video_vendor not in self.allowed_vendors:44 self._raise_error('vendor_not_allowed', (video_vendor,))45 #check vendor id:46 vendor_id_validator = self.vendor_id_validators.get(video_vendor)47 video_id = value.get('id', '')48 if vendor_id_validator:49 if not vendor_id_validator(video_id):50 self._raise_error('invalid_vendor_id')51 #check startTime:52 video_start_time = value.get('startTime')53 video_start_timedelta = None54 if video_start_time:55 #validate and clean time string:56 video_start_timedelta = dateparse.parse_duration(video_start_time)57 if video_start_timedelta is None:58 self._raise_error('invalid_time', ('startTime',))59 video_start_time = self._duration_to_str(video_start_timedelta)60 value['startTime'] = video_start_time61 #check endTime:62 video_end_time = value.get('endTime')63 if video_end_time:64 #validate and clean time string:65 video_end_timedelta = dateparse.parse_duration(video_end_time)66 if video_end_timedelta is None:67 self._raise_error('invalid_time', ('endTime',))68 video_end_time = self._duration_to_str(video_end_timedelta)69 value['endTime'] = video_end_time70 #validate timedelta between end and start times:71 if video_start_timedelta and video_end_timedelta:72 if video_end_timedelta <= video_start_timedelta:73 self._raise_error('invalid_time_delta')74 #check meta, in case exists:75 if 'meta' in value:76 if len(set(value['meta'].keys()) - {'published', 'author', 'title', 'duration',}):77 self._raise_error('invalid')78 if 'published' in value['meta'] and not dateparse.parse_datetime(value['meta']['published']):79 self._raise_error('invalid_meta_field', ('published',))80 for f in ['author', 'title']:81 if f in value['meta'] and (not isinstance(value['meta'][f], basestring) or len(value['meta'][f]) > 255):82 self._raise_error('invalid_meta_field', (f,))83 if 'duration' in value['meta']:84 video_duration_timedelta = dateparse.parse_duration(value['meta']['duration'])85 if video_duration_timedelta is None:86 self._raise_error('invalid_meta_field', ('duration',))87 value['meta']['duration'] = self._duration_to_str(video_duration_timedelta)88 def _raise_error(self, error_code, msg_args=tuple()):89 raise ValidationError(self.error_messages[error_code] % msg_args, code=error_code)90@deconstructible91class InlineTeacherFileJSONValidator(object):92 '''93 Validates inline JSON for teacher file field.94 '''95 error_messages = {96 'invalid': 'Enter a valid value: { url, size, name, time }',97 'invalid_field': 'Field \'%s\' is invalid.',98 }99 def __call__(self, value):100 if not isinstance(value, dict):101 self._raise_error('invalid')102 #check all keys exist:103 if set(value.keys()) != {'url', 'size', 'name', 'time',}:104 self._raise_error('invalid')105 #check url:106 try:107 validators.URLValidator()(value['url'])108 except Exception:109 self._raise_error('invalid_field', ('url',))110 if len(value['url']) > 500:111 self._raise_error('invalid_field', ('url',))112 #check size:113 if type(value['size']) is not int or value['size'] < 0:114 self._raise_error('invalid_field', ('size',))115 #check name:116 if not isinstance(value['name'], basestring) or not value['name'] or len(value['name']) > 255:117 self._raise_error('invalid_field', ('name',))118 #check time:119 if not dateparse.parse_datetime(value['time']):120 self._raise_error('invalid_field', ('time',))121 def _raise_error(self, error_code, msg_args=tuple()):122 raise ValidationError(self.error_messages[error_code] % msg_args, code=error_code)123@deconstructible124class InstructablesJSONValidator(object):125 '''126 Validates JSON for instructables field.127 '''128 error_messages = {129 'invalid': 'Enter a valid value: { urlId }',130 'invalid_field': 'Field \'%s\' is invalid.',131 }132 def __call__(self, value):133 if not isinstance(value, dict):134 self._raise_error('invalid')135 #check all keys exist:136 if set(value.keys()) != {'urlId',}:137 self._raise_error('invalid')138 #check urlId (validate as url slug):139 try:140 validators.validate_slug(value['urlId'])141 except ValidationError:142 self._raise_error('invalid_field', ('urlId',))143 def _raise_error(self, error_code, msg_args=tuple()):144 raise ValidationError(self.error_messages[error_code] % msg_args, code=error_code)145@deconstructible146class InstructionJSONValidator(object):147 '''148 Validates inline JSON for video field.149 '''150 error_messages = {151 'invalid': 'Enter a valid values: { description, image, hint, id, order }',152 'invalid_field': 'Field \'%s\' is invalid.',153 }154 def __call__(self, value):155 if not isinstance(value, dict):156 self._raise_error('invalid')157 #check description keys exist:158 if not 'description' in set(value.keys()) or not value.get('description'):159 self._raise_error('invalid')160 #check all keys exist:161 if len(set(value.keys()) - { 'description', 'image', 'hint', 'id', 'order' }) > 0:162 self._raise_error('invalid')163 #check image:164 if value.get('image'):165 try:166 validators.URLValidator()(value['image'])167 except ValidationError:168 self._raise_error('invalid_field', ('image',))169 if len(value['image']) > 500:170 self._raise_error('invalid_field', ('image',))171 def _raise_error(self, error_code, msg_args=tuple()):172 raise ValidationError(self.error_messages[error_code] % msg_args, code=error_code)173@deconstructible174class SeparatorJSONValidator(object):175 '''176 Validates JSON for separator field.177 '''178 error_messages = {179 'invalid': 'Enter a valid value: { before, label }',180 'invalid_field': 'Field \'%s\' is invalid.',181 }182 def __call__(self, value):183 if not isinstance(value, dict):184 self._raise_error('invalid')185 #check all keys exist:186 if set(value.keys()) != {'before', 'label',}:187 self._raise_error('invalid')188 #check before:189 if type(value['before']) is not int or value['before'] < 0:190 self._raise_error('invalid_field', ('before',))191 #check label:192 if not isinstance(value['label'], basestring) or not value['label'] or len(value['label']) > 140:193 self._raise_error('invalid_field', ('label',))194 def _raise_error(self, error_code, msg_args=tuple()):...
test_errors.py
Source:test_errors.py
...10 """Go through all possible error messages and see that they are parsed11 correctly.12 """13 with self.assertRaises(ex.AuthenticationError):14 self.api._raise_error(15 {'response': 'Authentication failed. Unique API key is not valid for this user.'})16 with self.assertRaises(ex.AuthenticationError):17 self.api._raise_error(18 {'response': 'Authentication failed. No user with this email address found.'})19 with self.assertRaises(ex.AuthenticationError):20 self.api._raise_error(21 {'response': 'This user does not have a valid Spin Rewriter subscription.'})22 with self.assertRaises(ex.QuotaLimitError):23 self.api._raise_error(24 {'response': 'API quota exceeded. You can make 50 requests per day.'})25 with self.assertRaises(ex.UsageFrequencyError):26 self.api._raise_error(27 {'response': 'You can only submit entirely new text for analysis once every 5 seconds.'})28 with self.assertRaises(ex.UnknownActionError):29 self.api._raise_error(30 {'response': 'Requested action does not exist. Please refer to the Spin Rewriter API documentation.'})31 with self.assertRaises(ex.MissingParameterError):32 self.api._raise_error(33 {'response': 'Email address and unique API key are both required. At least one is missing.'})34 with self.assertRaises(ex.ParamValueError):35 self.api._raise_error(36 {'response': 'Original text too short.'})37 with self.assertRaises(ex.ParamValueError):38 self.api._raise_error(39 {'response': 'Original text too long. Text can have up to 4,000 words.'})40 with self.assertRaises(ex.ParamValueError):41 self.api._raise_error(42 {'response': 'Original text after analysis too long. Text can have up to 4,000 words.'})43 with self.assertRaises(ex.ParamValueError):44 self.api._raise_error(45 {'response': 'Spinning syntax invalid. With this action you should provide text with existing valid {first option|second option} spintax.'})46 with self.assertRaises(ex.ParamValueError):47 self.api._raise_error(48 {'response': 'The {first|second} spinning syntax invalid. Re-check the syntax, i.e. curly brackets and pipes.'})49 with self.assertRaises(ex.ParamValueError):50 self.api._raise_error(51 {'response': 'Spinning syntax invalid.'})52 with self.assertRaises(ex.InternalApiError):53 self.api._raise_error(54 {'response': 'Analysis of your text failed. Please inform us about this.'})55 with self.assertRaises(ex.InternalApiError):56 self.api._raise_error(57 {'response': 'Synonyms for your text could not be loaded. Please inform us about this.'})58 with self.assertRaises(ex.InternalApiError):59 self.api._raise_error(60 {'response': 'Unable to load your new analyzed project.'})61 with self.assertRaises(ex.InternalApiError):62 self.api._raise_error(63 {'response': 'Unable to load your existing analyzed project.'})64 with self.assertRaises(ex.InternalApiError):65 self.api._raise_error(66 {'response': 'Unable to find your project in the database.'})67 with self.assertRaises(ex.InternalApiError):68 self.api._raise_error(69 {'response': 'Unable to load your analyzed project.'})70 with self.assertRaises(ex.InternalApiError):71 self.api._raise_error(72 {'response': 'One-Click Rewrite failed.'})73 with self.assertRaises(ex.UnknownApiError):74 self.api._raise_error(...
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!!