Best Python code snippet using Testify_python
objects.py
Source:objects.py
1import json2import warnings3from datetime import datetime, date4import autoviv5from autoviv import NoneProp6import simplejson7from dateutil import parser as dateutil_parser8from sqlalchemy.ext.mutable import Mutable9from RestResponse import utils10def _encode_hook(opts):11 def _default(o):12 if isinstance(o, RestObject):13 return {k: _default(v) for k, v in o.items()}14 elif isinstance(o, RestList) or isinstance(o, ApiCollection):15 return [_default(x) for x in o]16 if isinstance(o, ApiModel):17 return _default(o._data)18 return utils.encode_item(o, **opts)19 return _default20def _decode_hook(obj):21 for k, v in obj.items():22 obj[k] = utils.decode_item(v)23 return obj24def none_prop_getattr(self, key):25 if key == '__clause_element__':26 raise AttributeError(key)27 return NoneProp(self, key)28NoneProp.__getattr__ = none_prop_getattr29class RestEncoder(json.JSONEncoder):30 def __init__(self, *args, **kwargs):31 super(RestEncoder, self).__init__(*args, **kwargs)32 setattr(self, 'default', _encode_hook({}))33class RestEncoderSimple(simplejson.JSONEncoder):34 def __init__(self, *args, **kwargs):35 super(RestEncoderSimple, self).__init__(*args, **kwargs)36 setattr(self, 'default', _encode_hook({}))37 def iterencode(self, o, *args, **kwargs):38 try:39 return super(RestEncoderSimple, self).iterencode(o, *args, **kwargs)40 except Exception:41 # this could use a better solution42 return super(RestEncoderSimple, self).iterencode(json.loads(str(o)), *args, **kwargs)43json._default_encoder = RestEncoder()44simplejson._default_encoder = RestEncoderSimple()45class RestResponseObj(Mutable, object):46 __opts__ = {47 'encode_binary': True,48 'encode_callable': True,49 'decode_binary': True,50 'decode_callable': True51 }52 @classmethod53 def coerce(cls, key, value):54 if isinstance(value, dict) and not isinstance(value, RestObject):55 return RestObject(value)56 elif isinstance(value, list) and not isinstance(value, RestList):57 return RestList(value)58 else:59 return value60 def changed(self):61 super(RestResponseObj, self).changed()62 def __call__(self):63 return self64 def __json__(self, options=None):65 return _encode_hook(options or self.__opts__)(self)66class RestList(RestResponseObj, autoviv.List):67 def __init__(self, iterable=()):68 for x in iter(iterable):69 self.append(x)70 def __repr__(self):71 return autoviv.pprint(self, indent=None, cls=RestEncoder)72 def pretty_print(self, indent=4):73 return autoviv.pprint(self, indent=indent, cls=RestEncoder)74 def __setitem__(self, index, item):75 if isinstance(item, NoneProp):76 return77 item = RestResponse.parse(item)78 super(RestList, self).__setitem__(index, item)79 self.changed()80 def append(self, item):81 self.insert(len(self), item)82 self.changed()83 def extend(self, items):84 for item in items:85 self.append(item)86 def insert(self, index, item):87 if isinstance(item, NoneProp):88 return89 item = RestResponse.parse(item)90 super(RestList, self).insert(index, item)91 self.changed()92 def pop(self, index=None):93 if index:94 item = super(RestList, self).pop(index)95 else:96 item = super(RestList, self).pop()97 self.changed()98 return item99 def remove(self, item):100 super(RestList, self).remove(item)101 self.changed()102class RestObject(RestResponseObj, autoviv.Dict):103 def __init__(self, *args, **kwargs):104 super(RestObject, self).__init__()105 self.update(*args, **kwargs)106 def __repr__(self):107 return self.pretty_print(indent=None)108 def __str__(self):109 return self.pretty_print(indent=None)110 def pretty_print(self, indent=4):111 return autoviv.pprint(self, indent=indent, cls=RestEncoder)112 def __delattr__(self, name):113 if name in self:114 del self[name]115 self.changed()116 def clear(self):117 super(RestObject, self).clear()118 self.changed()119 def pop(self, name, default=None):120 if name in self:121 value = super(RestObject, self).pop(name, default)122 self.changed()123 else:124 value = default125 return value126 def popitem(self):127 value = super(RestObject, self).popitem()128 self.changed()129 return value130 def __missing__(self, key):131 return self.__getattr__(key)132 def __getattr__(self, key):133 if key in self:134 value = self[key]135 return value136 elif key == '__clause_element__':137 # SQLAlchemy will try to call this prop, raise AttributeError to avoid138 raise AttributeError(key)139 else:140 return super(RestObject, self).__getattr__(key)141 def __setattr__(self, key, value):142 if isinstance(value, NoneProp):143 return144 if key != '__none_props__':145 value = RestResponse.parse(value)146 super(RestObject, self).__setattr__(key, value)147 self.changed()148 def update(self, *args, **kwargs):149 result = {}150 for k, v in dict(*args, **kwargs).items():151 result[k] = RestResponse.parse(v)152 super(RestObject, self).update(result)153 self.changed()154class RestResponse(object):155 def __new__(self, data, **kwargs):156 if isinstance(data, str):157 return RestResponse.loads(data)158 else:159 return RestResponse.parse(data)160 @staticmethod161 def parse(data):162 if isinstance(data, RestResponseObj) or isinstance(data, NoneProp):163 return data164 elif isinstance(data, dict):165 return RestObject(data)166 elif isinstance(data, list):167 return RestList(data)168 else:169 # decode properties encoded by RestResponse170 if isinstance(data, str) and (data.startswith(('__callable__: ', '__binary__'))):171 data = utils.decode_item(data)172 elif isinstance(data, bytes) and (data.startswith((b'__callable__: ', b'__binary__'))):173 data = utils.decode_item(data)174 return data175 @staticmethod176 def loads(data, **kwargs):177 try:178 data = json.loads(data, object_hook=_decode_hook, **kwargs)179 except Exception:180 raise ValueError('RestResponse.loads data must be JSON deserializable')181 return RestResponse.parse(data)182 @staticmethod183 def dumps(data, **kwargs):184 try:185 return json.dumps(data, cls=RestEncoder, **kwargs)186 except Exception:187 raise ValueError('RestResponse.dumps data must be JSON serializable')188class ApiModel(object):189 __opts__ = {190 'encode_binary': False,191 'encode_callable': False,192 'decode_binary': False,193 'decode_callable': False,194 'encode_datetime': lambda x: datetime.strftime(x, '%Y-%m-%dT%H:%M:%SZ'),195 'encode_date': lambda x: datetime.strftime(x, '%Y-%m-%d'),196 '_overrides': [],197 }198 def __bool__(self):199 return bool(self._data)200 def __nonzero__(self):201 return bool(self._data)202 def __eq__(self, other):203 if not isinstance(other, ApiModel):204 return False205 return self._data == other._data206 @property207 def _data(self):208 return self.__data209 @_data.setter210 def _data(self, data):211 data = data or RestResponse.parse({})212 if isinstance(data, dict) or isinstance(data, list):213 data = RestResponse.parse(data)214 elif isinstance(data, str):215 try:216 data = RestResponse.loads(data or "{}")217 except ValueError as e:218 raise ValueError('{0} data must be JSON serializable'.format(self.__class__)) from e219 elif isinstance(data, ApiModel):220 data = data._data221 self.__data = RestResponse.parse({})222 for prop in dir(self):223 if (not prop.startswith('_') or prop in self.__opts__.get('_overrides', [])) and prop in data:224 setattr(self, prop, data[prop])225 @property226 def _as_json(self):227 return json.loads(json.dumps(self._data, default=_encode_hook(self.__opts__)))228 def _set_datetime(self, d, format='%Y-%m-%dT%H:%M:%SZ'):229 return self._format_datetime(d, format=format, raises_value_error=True)230 def _get_datetime(self, d, format='%Y-%m-%dT%H:%M:%SZ'):231 return self._format_datetime(d, format=format, raises_value_error=False)232 def _format_datetime(self, d, format='%Y-%m-%dT%H:%M:%SZ', raises_value_error=False):233 if not isinstance(d, datetime) or not isinstance(d, date):234 try:235 d = dateutil_parser.parse(d)236 return datetime.strptime(d.strftime(format), format)237 except ValueError:238 if raises_value_error:239 raise240 else:241 warnings.warn('Value must be date or datetime')242 return None243 else:244 return d245 def _set_date(self, d, format='%Y-%m-%d'):246 return self._format_date(d, format=format, raises_value_error=True)247 def _get_date(self, d, format='%Y-%m-%d'):248 return self._format_date(d, format=format, raises_value_error=False)249 def _format_date(self, d, format='%Y-%m-%d', raises_value_error=False):250 if not isinstance(d, date):251 try:252 d = dateutil_parser.parse(d)253 return datetime.strptime(d.strftime(format), format).date()254 except ValueError:255 if raises_value_error:256 raise257 else:258 warnings.warn('Value must be date')259 return None260 else:261 return d262 def _set_string(self, s):263 return self._format_string(s, raises_value_error=True)264 def _get_string(self, s):265 return self._format_string(s, raises_value_error=False)266 def _format_string(self, s, raises_value_error=False):267 if raises_value_error and not isinstance(s, str):268 raise ValueError('Value must be str')269 return '%s' % (s or '')270 def _set_float(self, f):271 return self._format_float(f, raises_value_error=True)272 def _get_float(self, f):273 return self._format_float(f, raises_value_error=False)274 def _format_float(self, f, raises_value_error=False):275 try:276 return float(f)277 except (ValueError, TypeError):278 if raises_value_error:279 raise280 else:281 warnings.warn('Value must be float')282 return None283 def _set_int(self, i):284 return self._format_int(i, raises_value_error=True)285 def _get_int(self, i):286 return self._format_int(i, raises_value_error=False)287 def _format_int(self, i, raises_value_error=False):288 try:289 return int(i)290 except (ValueError, TypeError):291 if raises_value_error:292 raise293 else:294 warnings.warn('Value must be integer')295 return None296 def _set_bool(self, b):297 return self._format_bool(b, raises_value_error=True)298 def _get_bool(self, b):299 return self._format_bool(b, raises_value_error=False)300 def _format_bool(self, b, raises_value_error=False):301 if (302 raises_value_error303 and not isinstance(b, bool)304 ):305 raise ValueError('Value must be bool')306 return b in [True, 'True', 'true', '1', 1]307class ApiCollection(RestList):308 def __init__(self, setter, iterable=(), **setter_kwargs):309 self.setter = setter310 self.setter_kwargs = setter_kwargs311 self.extend(iterable)312 @property313 def _data(self):314 return RestResponse.parse([x for x in self])315 @property316 def _as_json(self):317 return json.loads(json.dumps(self, default=_encode_hook(self.__opts__)))318 def append(self, item):319 self.insert(len(self), item)320 def insert(self, index, item):321 value = self.setter(item, **self.setter_kwargs)322 if value is not None:323 super(ApiCollection, self).insert(index, value)324 def extend(self, items):325 for item in items:326 self.append(item)327 def __setitem__(self, index, value):328 if index >= 0 and index < len(self):329 self.pop(index)330 self.insert(index, value)331 else:...
test_utils.py
Source:test_utils.py
...3from django import test4from django_psdash.utils import import_function5from django_psdash.utils import check_settings6class ImportFunctionTestCase(test.TestCase):7 def raises_value_error(self, func_addr):8 with self.assertRaises(ValueError):9 import_function(func_addr)10 def test_wrong_addr(self):11 self.raises_value_error('')12 self.raises_value_error('.')13 self.raises_value_error('..')14 self.raises_value_error('.relative_path')15 self.raises_value_error('wrong_import.')16 self.raises_value_error('fake.module')17 self.raises_value_error('os')18 self.raises_value_error('os.wrong_function')19 self.raises_value_error('sys.args')20 def test_all_ok(self):21 func = import_function('os.path.join')22 self.assertTrue(inspect.isfunction(func))23class CheckCategoriesSettingsTestCase(test.TestCase):24 def test_wrong_type(self):25 with self.assertRaises(ValueError):26 check_settings([1, 2, 3])27 def test_wrong_item_of_categories(self):28 with self.assertRaises(ValueError):29 check_settings({'test': []})30 def test_required_name_for_item(self):31 with self.assertRaises(ValueError):32 check_settings(33 {...
control_flow_try_except.py
Source:control_flow_try_except.py
1# Try and Except Statements2# The function in the editor is very simple and serves one purpose: it raises a ValueError.3# Try running it by entering raises_value_error() into the code editor and hitting run.4# Remember, unindent this function call so it isnât included in the function itself.5def raises_value_error():6 raise ValueError7# Great! Nice error raising! Now letâs make that error message a little more palatable.8# Write a try statement and an except statement around the line of code that executes the function to catch a ValueError and make the error message print You raised a ValueError!9try:10 raises_value_error()11except ValueError:...
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!!