How to use get_dictionary method in autotest

Best Python code snippet using autotest_python

pydevd_resolver.py

Source:pydevd_resolver.py Github

copy

Full Screen

...61 @param var: this is the actual variable to be resolved.62 @param attribute: this is the string representation of a key previously returned in get_dictionary.63 '''64 raise NotImplementedError65 def get_dictionary(self, var):66 '''67 @param var: this is the variable that should have its children gotten.68 @return: a dictionary where each pair key, value should be shown to the user as children items69 in the variables view for the given var.70 '''71 raise NotImplementedError72#=======================================================================================================================73# DefaultResolver74#=======================================================================================================================75class DefaultResolver:76 '''77 DefaultResolver is the class that'll actually resolve how to show some variable.78 '''79 use_value_repr_instead_of_str = False80 def resolve(self, var, attribute):81 return getattr(var, attribute)82 def get_dictionary(self, var, names=None):83 if MethodWrapperType:84 return self._getPyDictionary(var, names)85 else:86 return self._getJyDictionary(var)87 def _getJyDictionary(self, obj):88 ret = {}89 found = java.util.HashMap()90 original = obj91 if hasattr(obj, '__class__') and obj.__class__ == java.lang.Class:92 #get info about superclasses93 classes = []94 classes.append(obj)95 c = obj.getSuperclass()96 while c != None:97 classes.append(c)98 c = c.getSuperclass()99 #get info about interfaces100 interfs = []101 for obj in classes:102 interfs.extend(obj.getInterfaces())103 classes.extend(interfs)104 #now is the time when we actually get info on the declared methods and fields105 for obj in classes:106 declaredMethods = obj.getDeclaredMethods()107 declaredFields = obj.getDeclaredFields()108 for i in xrange(len(declaredMethods)):109 name = declaredMethods[i].getName()110 ret[name] = declaredMethods[i].toString()111 found.put(name, 1)112 for i in xrange(len(declaredFields)):113 name = declaredFields[i].getName()114 found.put(name, 1)115 #if declaredFields[i].isAccessible():116 declaredFields[i].setAccessible(True)117 #ret[name] = declaredFields[i].get( declaredFields[i] )118 try:119 ret[name] = declaredFields[i].get(original)120 except:121 ret[name] = declaredFields[i].toString()122 #this simple dir does not always get all the info, that's why we have the part before123 #(e.g.: if we do a dir on String, some methods that are from other interfaces such as124 #charAt don't appear)125 try:126 d = dir(original)127 for name in d:128 if found.get(name) is not 1:129 ret[name] = getattr(original, name)130 except:131 #sometimes we're unable to do a dir132 pass133 return ret134 def get_names(self, var):135 names = dir(var)136 if not names and hasattr(var, '__members__'):137 names = var.__members__138 return names139 def _getPyDictionary(self, var, names=None):140 filterPrivate = False141 filterSpecial = True142 filterFunction = True143 filterBuiltIn = True144 if not names:145 names = self.get_names(var)146 d = {}147 #Be aware that the order in which the filters are applied attempts to148 #optimize the operation by removing as many items as possible in the149 #first filters, leaving fewer items for later filters150 if filterBuiltIn or filterFunction:151 for n in names:152 if filterSpecial:153 if n.startswith('__') and n.endswith('__'):154 continue155 if filterPrivate:156 if n.startswith('_') or n.endswith('__'):157 continue158 try:159 attr = getattr(var, n)160 #filter builtins?161 if filterBuiltIn:162 if inspect.isbuiltin(attr):163 continue164 #filter functions?165 if filterFunction:166 if inspect.isroutine(attr) or isinstance(attr, MethodWrapperType):167 continue168 except:169 #if some error occurs getting it, let's put it to the user.170 strIO = StringIO.StringIO()171 traceback.print_exc(file=strIO)172 attr = strIO.getvalue()173 d[ n ] = attr174 return d175#=======================================================================================================================176# DictResolver177#=======================================================================================================================178class DictResolver:179 use_value_repr_instead_of_str = False180 def resolve(self, dict, key):181 if key in ('__len__', TOO_LARGE_ATTR):182 return None183 if '(' not in key:184 #we have to treat that because the dict resolver is also used to directly resolve the global and local185 #scopes (which already have the items directly)186 try:187 return dict[key]188 except:189 return getattr(dict, key)190 #ok, we have to iterate over the items to find the one that matches the id, because that's the only way191 #to actually find the reference from the string we have before.192 expected_id = int(key.split('(')[-1][:-1])193 for key, val in dict_iter_items(dict):194 if id(key) == expected_id:195 return val196 raise UnableToResolveVariableException()197 def key_to_str(self, key):198 if isinstance(key, str):199 return '%r' % key200 else:201 if not pydevd_constants.IS_PY3K:202 if isinstance(key, unicode):203 return "u'%s'" % key204 return key205 def get_dictionary(self, dict):206 ret = {}207 i = 0208 for key, val in dict_iter_items(dict):209 i += 1210 #we need to add the id because otherwise we cannot find the real object to get its contents later on.211 key = '%s (%s)' % (self.key_to_str(key), id(key))212 ret[key] = val213 if i > MAX_ITEMS_TO_HANDLE:214 ret[TOO_LARGE_ATTR] = TOO_LARGE_MSG215 break216 ret['__len__'] = len(dict)217 # in case if the class extends built-in type and has some additional fields218 additional_fields = defaultResolver.get_dictionary(dict)219 ret.update(additional_fields)220 return ret221#=======================================================================================================================222# TupleResolver223#=======================================================================================================================224class TupleResolver: #to enumerate tuples and lists225 use_value_repr_instead_of_str = False226 def resolve(self, var, attribute):227 '''228 @param var: that's the original attribute229 @param attribute: that's the key passed in the dict (as a string)230 '''231 if attribute in ('__len__', TOO_LARGE_ATTR):232 return None233 try:234 return var[int(attribute)]235 except:236 return getattr(var, attribute)237 def get_dictionary(self, var):238 l = len(var)239 d = {}240 format_str = '%0' + str(int(len(str(l)))) + 'd'241 i = 0242 for item in var:243 d[format_str % i] = item244 i += 1245 246 if i > MAX_ITEMS_TO_HANDLE:247 d[TOO_LARGE_ATTR] = TOO_LARGE_MSG248 break249 250 d['__len__'] = len(var)251 # in case if the class extends built-in type and has some additional fields252 additional_fields = defaultResolver.get_dictionary(var)253 d.update(additional_fields)254 return d255#=======================================================================================================================256# SetResolver257#=======================================================================================================================258class SetResolver:259 '''260 Resolves a set as dict id(object)->object261 '''262 use_value_repr_instead_of_str = False263 def resolve(self, var, attribute):264 if attribute in ('__len__', TOO_LARGE_ATTR):265 return None266 try:267 attribute = int(attribute)268 except:269 return getattr(var, attribute)270 for v in var:271 if id(v) == attribute:272 return v273 raise UnableToResolveVariableException('Unable to resolve %s in %s' % (attribute, var))274 def get_dictionary(self, var):275 d = {}276 i = 0277 for item in var:278 i+= 1279 d[id(item)] = item280 281 if i > MAX_ITEMS_TO_HANDLE:282 d[TOO_LARGE_ATTR] = TOO_LARGE_MSG283 break284 285 d['__len__'] = len(var)286 # in case if the class extends built-in type and has some additional fields287 additional_fields = defaultResolver.get_dictionary(var)288 d.update(additional_fields)289 return d290#=======================================================================================================================291# InstanceResolver292#=======================================================================================================================293class InstanceResolver:294 use_value_repr_instead_of_str = False295 def resolve(self, var, attribute):296 field = var.__class__.getDeclaredField(attribute)297 field.setAccessible(True)298 return field.get(var)299 def get_dictionary(self, obj):300 ret = {}301 declaredFields = obj.__class__.getDeclaredFields()302 for i in xrange(len(declaredFields)):303 name = declaredFields[i].getName()304 try:305 declaredFields[i].setAccessible(True)306 ret[name] = declaredFields[i].get(obj)307 except:308 traceback.print_exc()309 return ret310#=======================================================================================================================311# JyArrayResolver312#=======================================================================================================================313class JyArrayResolver:314 '''315 This resolves a regular Object[] array from java316 '''317 use_value_repr_instead_of_str = False318 def resolve(self, var, attribute):319 if attribute == '__len__':320 return None321 return var[int(attribute)]322 def get_dictionary(self, obj):323 ret = {}324 for i in xrange(len(obj)):325 ret[ i ] = obj[i]326 ret['__len__'] = len(obj)327 return ret328#=======================================================================================================================329# NdArrayResolver330#=======================================================================================================================331class NdArrayResolver:332 '''333 This resolves a numpy ndarray returning some metadata about the NDArray334 '''335 use_value_repr_instead_of_str = False336 def is_numeric(self, obj):337 if not hasattr(obj, 'dtype'):338 return False339 return obj.dtype.kind in 'biufc'340 def resolve(self, obj, attribute):341 if attribute == '__internals__':342 return defaultResolver.get_dictionary(obj)343 if attribute == 'min':344 if self.is_numeric(obj):345 return obj.min()346 else:347 return None348 if attribute == 'max':349 if self.is_numeric(obj):350 return obj.max()351 else:352 return None353 if attribute == 'shape':354 return obj.shape355 if attribute == 'dtype':356 return obj.dtype357 if attribute == 'size':358 return obj.size359 if attribute.startswith('['):360 container = NdArrayItemsContainer()361 i = 0362 format_str = '%0' + str(int(len(str(len(obj))))) + 'd'363 for item in obj:364 setattr(container, format_str % i, item)365 i += 1366 if i > MAX_ITEMS_TO_HANDLE:367 setattr(container, TOO_LARGE_ATTR, TOO_LARGE_MSG)368 break369 return container370 return None371 def get_dictionary(self, obj):372 ret = dict()373 ret['__internals__'] = defaultResolver.get_dictionary(obj)374 if obj.size > 1024 * 1024:375 ret['min'] = 'ndarray too big, calculating min would slow down debugging'376 ret['max'] = 'ndarray too big, calculating max would slow down debugging'377 else:378 if self.is_numeric(obj):379 ret['min'] = obj.min()380 ret['max'] = obj.max()381 else:382 ret['min'] = 'not a numeric object'383 ret['max'] = 'not a numeric object'384 ret['shape'] = obj.shape385 ret['dtype'] = obj.dtype386 ret['size'] = obj.size387 ret['[0:%s] ' % (len(obj))] = list(obj[0:MAX_ITEMS_TO_HANDLE])388 return ret389class NdArrayItemsContainer: pass390#=======================================================================================================================391# MultiValueDictResolver392#=======================================================================================================================393class MultiValueDictResolver(DictResolver):394 use_value_repr_instead_of_str = False395 def resolve(self, dict, key):396 if key in ('__len__', TOO_LARGE_ATTR):397 return None398 #ok, we have to iterate over the items to find the one that matches the id, because that's the only way399 #to actually find the reference from the string we have before.400 expected_id = int(key.split('(')[-1][:-1])401 for key in dict_keys(dict):402 val = dict.getlist(key)403 if id(key) == expected_id:404 return val405 raise UnableToResolveVariableException()406#=======================================================================================================================407# DjangoFormResolver408#=======================================================================================================================409class DjangoFormResolver(DefaultResolver):410 has_errors_attr = False411 use_value_repr_instead_of_str = True412 def get_names(self, var):413 names = dir(var)414 if not names and hasattr(var, '__members__'):415 names = var.__members__416 if "errors" in names:417 self.has_errors_attr = True418 names.remove("errors")419 return names420 def get_dictionary(self, var, names=None):421 # Do not call self.errors because it is property and has side effects422 d = defaultResolver.get_dictionary(var, self.get_names(var))423 if self.has_errors_attr:424 try:425 errors_attr = getattr(var, "_errors")426 except:427 errors_attr = None428 d["errors"] = errors_attr429 return d430#=======================================================================================================================431# DequeResolver432#=======================================================================================================================433class DequeResolver(TupleResolver):434 use_value_repr_instead_of_str = False435 def get_dictionary(self, var):436 d = TupleResolver.get_dictionary(self, var)437 d['maxlen'] = getattr(var, 'maxlen', None)438 return d439#=======================================================================================================================440# FrameResolver441#=======================================================================================================================442class FrameResolver:443 '''444 This resolves a frame.445 '''446 use_value_repr_instead_of_str = False447 def resolve(self, obj, attribute):448 if attribute == '__internals__':449 return defaultResolver.get_dictionary(obj)450 if attribute == 'stack':451 return self.get_frame_stack(obj)452 if attribute == 'f_locals':453 return obj.f_locals454 return None455 def get_dictionary(self, obj):456 ret = dict()457 ret['__internals__'] = defaultResolver.get_dictionary(obj)458 ret['stack'] = self.get_frame_stack(obj)459 ret['f_locals'] = obj.f_locals460 return ret461 def get_frame_stack(self, frame):462 ret = []463 if frame is not None:464 ret.append(self.get_frame_name(frame))465 while frame.f_back:466 frame = frame.f_back467 ret.append(self.get_frame_name(frame))468 return ret469 def get_frame_name(self, frame):470 if frame is None:471 return 'None'...

Full Screen

Full Screen

pydevd_extension_api.py

Source:pydevd_extension_api.py Github

copy

Full Screen

...26 @param attribute: this is the string representation of a key previously returned in get_dictionary.27 """28 raise NotImplementedError29 @abc.abstractmethod30 def get_dictionary(self, var):31 """32 @param var: this is the variable that should have its children gotten.33 @return: a dictionary where each pair key, value should be shown to the user as children items34 in the variables view for the given var.35 """36 raise NotImplementedError37class _AbstractProvider(_with_metaclass(abc.ABCMeta)):38 @abc.abstractmethod39 def can_provide(self, type_object, type_name):40 raise NotImplementedError41# =======================================================================================================================42# API CLASSES:43# =======================================================================================================================44class TypeResolveProvider(_AbstractResolver, _AbstractProvider):...

Full Screen

Full Screen

rs.py

Source:rs.py Github

copy

Full Screen

...18 if not hasattr(self, "time"):19 configs = self.problemConfig._space.sample_configuration(self.evals)20 if not isinstance(configs, list):21 configs = [configs]22 param_names = list(configs[0].get_dictionary().keys())23 param_names.append("loss")24 with open(self.prob + '/results/results.csv', 'w') as f:25 writer = csv.writer(f)26 writer.writerow(param_names)27 for i in configs:28 values = []29 loss = self.mod_run.run(i.get_dictionary())30 for j in i.get_dictionary().keys():31 values.append(i.get_dictionary()[j])32 values.append(loss)33 writer.writerow(values)34 else:35 tic = time.perf_counter()36 configs = self.problemConfig._space.sample_configuration()37 if not isinstance(configs, list):38 configs = [configs]39 param_names = list(configs[0].get_dictionary().keys())40 param_names.append("loss")41 with open(self.prob + '/results/results.csv', 'w') as f:42 writer = csv.writer(f)43 writer.writerow(param_names)44 while True:45 values = []46 config = self.problemConfig._space.sample_configuration()47 loss = self.mod_run.run(config.get_dictionary())48 for j in config.get_dictionary().keys():49 values.append(config.get_dictionary()[j])50 values.append(loss)51 writer.writerow(values)52 if time.perf_counter() > tic + self.time:...

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