How to use _getPara method in Robotframework-anywherelibrary

Best Python code snippet using robotframework-anywherelibrary

SQLitePersistBasicClasses.py

Source:SQLitePersistBasicClasses.py Github

copy

Full Screen

1import datetime as dt2from email.policy import default3import uuid4import inspect5from enum import Enum, unique6from urllib3 import Retry7class DbType(Enum):8 NULL = 0 9 INTEGER = 110 REAL = 211 TEXT = 312 BLOB = 413 TIMESTAMP = 514class OrderDirection(Enum):15 ASCENDING=016 DESCENDING=117class OperationStackElement(object):18 def __init__(self, left, op, right):19 self._left = left20 self._right = right21 self._op = op22 def __and__(self, other):23 return OperationStackElement(self, "&", other)24 def __or__(self, other):25 return OperationStackElement(self, "|", other)26 def __eq__(self, other):27 return OperationStackElement(self, "==", other)28 def __neq__(self, other):29 return OperationStackElement(self, "!=", other)30 def __str__(self):31 return "op " + str(self._left) + self._op + str(self._right)32 33class BaseComparableType(object):34 def __init__(self):35 pass36 def __eq__(self, other):37 return OperationStackElement(self, "==", other)38 def __neq__(self, other):39 return OperationStackElement(self, "!=", other)40 def __lt__(self, other):41 return OperationStackElement(self, "<", other)42 def __le__(self, other):43 return OperationStackElement(self, "<=", other)44 def __gt__(self, other):45 return OperationStackElement(self, ">", other)46 def __ge__(self, other):47 return OperationStackElement(self, ">=", other)48class Val(BaseComparableType):49 def __init__(self, value):50 self._value = value51class BaseVarType(BaseComparableType):52 _innertype = None #type in instance53 _outertype = None #type in database54 _subclasses = []55 _myfieldname = None #used to cache a field name once it was searched by get_fieldname()56 def __init__(self, **kwarg):57 super().__init__()58 self._subdef = None59 self._varcode = uuid.uuid4()60 self._getpara(kwarg, "default")61 self._getpara(kwarg, "defaultgenerator")62 self._getpara(kwarg, "uniquegrp")63 64 def get_default(self):65 if self._defaultgenerator is None:66 return self._default67 else:68 return self._defaultgenerator()69 def to_innertype(self, dta):70 raise Exception("Override me in <BaseType.to_innertype() in declration-type {}".format(type(self).__name__))71 def get_fieldname(self):72 if self._myfieldname is not None: return self._myfieldname73 vname = getvarname(self)74 self._myfieldname = vname75 return vname76 def is_dbstorable(self):77 return True78 def _getpara(self, kwargs, name, default=None, excstr=None):79 membername = "_" + name80 done = False81 if name in kwargs.keys():82 setattr(self, membername, kwargs[name])83 done = True84 elif default is not None:85 setattr(self, membername, default)86 done = True87 elif excstr is not None:88 done = True89 raise Exception(excstr)90 if not done:91 setattr(self, membername, None)92class Blob(BaseVarType):93 _innertype = bytes94 _outertype = DbType.BLOB95 96 def __init__(self, **kwarg):97 super().__init__(**kwarg)98 def to_innertype(self, dta):99 if dta is None:100 return None101 else:102 return bytes(dta)103class String(BaseVarType):104 _innertype = str105 _outertype = DbType.TEXT106 def __init__(self, **kwarg):107 super().__init__(**kwarg)108 def to_innertype(self, dta):109 if dta is None:110 return None111 else:112 return str(dta)113 114class UUid(BaseVarType):115 _innertype = uuid.uuid4116 _outertype = DbType.TEXT117 def to_innertype(self, dta):118 if dta is None:119 return None120 t = type(dta)121 if t is uuid.uuid4:122 return dta123 elif t is str:124 return uuid.UUID(dta)125 else:126 raise Exception("Type <{0}> cannot be tranformed into a uuid".format(t.__name__))127class Int(BaseVarType):128 _innertype = int129 _outertype = DbType.INTEGER130 def to_innertype(self, dta):131 if dta is None:132 return None133 t = type(dta)134 if t is int:135 return dta136 elif t is str:137 return int(dta)138 else:139 raise Exception("Type <{0}> cannot be tranformed into an int".format(t.__name__))140class Float(BaseVarType):141 _innertype = float142 _outertype = DbType.REAL143 def to_innertype(self, dta):144 if dta is None:145 return None146 t = type(dta)147 if t is float:148 return dta149 elif t is str:150 return float(dta)151 else:152 raise Exception("Type <{0}> cannot be tranformed into a float".format(t.__name__))153class Boolean(BaseVarType):154 _innertype = bool155 _outertype = DbType.TEXT156 def to_innertype(self, dta):157 if dta is None:158 return None159 t = type(dta)160 if t is bool:161 return dta162 elif t is str:163 lowdta = dta.lower()164 if lowdta in ["ja", "yes", "wahr", "true", "y", "1"]:165 return True166 elif lowdta in ["nein", "no", "unwahr", "false", "n", "0"]:167 return False168 else:169 raise Exception("The string <{0}> cannot be transformed to a bool".format(dta))170 elif t is int:171 return dta == 1172 else:173 raise Exception("Type <{0}> cannot be tranformed into a bool".format(t.__name__))174class DateTime(BaseVarType):175 innertype = dt.datetime176 _outertype = DbType.TIMESTAMP177 def to_innertype(self, dta):178 if dta is None:179 return None180 t = type(dta)181 if t is dt.datetime:182 return dta183 elif t is str:184 return dt.strptime(dta, "%m.%d.%Y %H:%M:%S")185 else:186 raise Exception("Type <{0}> cannot be tranformed into a datetime".format(t.__name__))187class Catalog(BaseVarType):188 _innertype = str189 _outertype = DbType.TEXT190 def __init__(self, **kwargs):191 super().__init__(**kwargs)192 self._getpara(kwargs, "catalogtype", excstr="catalogdefinition without catalogtype is not a valid catalog definition")193 def to_innertype(self, dta):194 raise Exception("do not use to_innertype in catalogs!")195 def get_catalogtype(self):196 return self._catalogtype197# classes for queries198class SpecialWhereInfo(object):199 def __init__(self, field, infotype, infodata):200 self._field = field201 self._infotype = infotype202 self._infodata = infodata203 def __and__(self, other):204 return OperationStackElement(self, "&", other)205 def __or__(self, other):206 return OperationStackElement(self, "|", other)207 def __invert__(self):208 return OperationStackElement(None, "~", self)209 def get_left(self):210 return self._field211 def get_right(self):212 return self._infodata213 def get_op(self):214 return self._infotype215class IsIn(SpecialWhereInfo):216 def __init__(self, field, infodata):217 super().__init__(field, infotype="ISIN", infodata=infodata)218class NotIsIn(SpecialWhereInfo):219 def __init__(self, field, infodata):220 super().__init__(field, infotype="NOTISIN", infodata=infodata)221class Regex(SpecialWhereInfo):222 def __init__(self, field, infodata):223 super().__init__(field, infotype="REGEX", infodata=infodata)224# special data declarations225class _EmbeddedObject(BaseVarType):226 _innertype = object227 def __init__(self, **kwargs):228 super().__init__(**kwargs)229 self._getpara(kwargs, "targettype", excstr="EmbeddedObject needs a targettype!!")230 self._getpara(kwargs, "autofill", default=True)231 def is_dbstorable(self):232 #not directly storable in the database233 return False234 def get_targettype(self):235 return self._targettype236 def get_autofill(self) -> bool:237 return self._autofill238 def get_foreign_keyname(self):239 if type(self._foreignid) is str: return self._foreignid240 vname = getvarname(self._foreignid)241 if vname is not None: #if we managed to get the name, store it for future use (caching)242 self._foreignid = vname243 return vname244 def get_local_keyname(self):245 if type(self._localid) is str: return self._localid246 vname = getvarname(self._localid)247 if vname is not None: #if we managed to get the name, store it for future use (caching)248 self._localid = vname249 return vname250class _EmbeddedList(_EmbeddedObject):251 _innertype = list252 def __init__(self, **kwargs):253 super().__init__(**kwargs)254class JoinedEmbeddedList(_EmbeddedList):255 _innertype = list256 def __init__(self, **kwargs):257 super().__init__(**kwargs)258 self._getpara(kwargs, "localid", default="_id")259 self._getpara(kwargs, "foreignid", excstr="A JoinedEmbeddedList needs a foreign id!!!")260 self._getpara(kwargs, "autofill", default=False)261 self._getpara(kwargs, "cascadedelete", default=False)262 def get_cascadedelete(self):263 return self._cascadedelete264class IntersectedList(_EmbeddedList):265 _innertype = list266 def __init__(self, **kwargs):267 super().__init__(**kwargs)268 self._getpara(kwargs, "autofill", default=False)269 self._getpara(kwargs, "cascadedelete", default=False)270 self._getpara(kwargs, "localid", default="_id") 271 self._getpara(kwargs, "foreignid", default="_id")272 self._getpara(kwargs, "interupid", default="upid") 273 self._getpara(kwargs, "interdownid", default="downid")274 def get_down_keyname(self):275 return self._interdownid276 def get_up_keyname(self):277 return self._interupid278class JoinedEmbeddedObject(_EmbeddedObject):279 _innertype = object280 def __init__(self, **kwargs):281 super().__init__(**kwargs)282 self._getpara(kwargs, "localid", excstr="A JoinedEmbeddedObject needs a local id which points to the joined object")283 self._getpara(kwargs, "foreignid", default="_id")284 self._getpara(kwargs, "cascadedelete", default=False)285 def get_cascadedelete(self):286 return self._cascadedelete287class ClassDictEntry(object):288 def __init__(self, membername, dectype, declaration):289 self._membername = membername290 self._dectype = dectype291 self._declaration = declaration292 def get_default(self):293 return self._declaration.get_default()294 def get_dectype(self):295 return self._dectype296 def get_outertype(self):297 return self._declaration._outertype298 def get_declaration(self):299 return self._declaration300 def __repr__(self):301 return "datamember: {} dectype{} declared {}".format(self._membername, self._dectype, self._declaration)302class PBase(object):303 """Base class for any persistant class304 Derive from this and your class will be persistent"""305 _classdict = {}306 Id = UUid()307 Created = DateTime()308 LastUpdate = DateTime()309 @classmethod310 def _setup_class_dict(cls):311 if cls in cls._classdict.keys(): return312 classmemberdict = {}313 allclasses = inspect.getmro(cls) # get classes in method call order aka top derived class first314 for allclass in allclasses:315 if issubclass(allclass, PBase):316 members = vars(allclass)317 for key, value in members.items():318 if key[0].isupper() and issubclass(value.__class__, BaseVarType):319 if key=="Id":320 mykey = "_id"321 else:322 mykey = key.lower()323 if not mykey in classmemberdict.keys(): # do not overwrite overridden member infos324 classmemberdict[mykey] = ClassDictEntry(key, type(value), getattr(allclass, key))325 326 cls._classdict[cls] = classmemberdict327 @classmethod328 def _getclstablename(cls):329 return cls.get_collection_name().lower()330 @classmethod331 def get_collection_name(cls):332 if hasattr(cls, "_collectionname"):333 return getattr(cls, "_collectionname")334 else:335 return cls.__name__336 @classmethod337 def get_memberdeclarationforcls(cls, membercls, membername : str):338 """return then memberdeclaration for a member of the given class"""339 cd = cls._classdict[membercls]340 md = cd[membername]341 return md.get_declaration()342 @classmethod343 def get_clsdict(cls):344 """return the classdict for the class"""345 return cls._classdict[cls]346 @classmethod347 def is_catalogmember(cls, membername):348 cd = cls._classdict[cls]349 md = cd[membername]350 decl = md.get_declaration()351 return issubclass(type(decl), Catalog)352 @classmethod353 def additional_where(cls):354 """ adds an additional whereclause to every where for this class355 override to add your own additional where for your derived class356 mybe like: MyCls.MyProp=="something" """357 return None358 def clone(self):359 """ create an intelligent clone by deep copying all of the members which are declared360 as persistent. _id is not omitted!361 """362 cls = self.__class__363 answ = cls()364 decls = cls.get_clsdict()365 for mname, mdecl in decls.items():366 val = getattr(self, mname, None)367 if val is None:368 setattr(answ, mname, val)369 else:370 if mdecl._dectype is JoinedEmbeddedObject:371 setattr(answ, mname, val.clone())372 elif mdecl._dectype is IntersectedList:373 answval = []374 for valelm in val:375 answval.append(valelm.clone())376 setattr(answ, mname, answval)377 elif mdecl._dectype is JoinedEmbeddedList:378 answval = []379 for valelm in val:380 answval.append(valelm.clone())381 setattr(answ, mname, answval)382 383 else:384 setattr(answ, mname, val)385 return answ386 def __init__(self, **kwargs):387 self._valuesdict = {}388 self.__class__._setup_class_dict()389 for key, value in kwargs.items():390 self._set_my_attribute(key, value)391 self.initialise_attributes()392 self._dbvaluescache = None393 def has_changed(self):394 if self._dbvaluescache is None: #no read from db occured before we ask this395 return True396 vd = self._get_my_memberdict()397 for key, value in vd.items():398 if hasattr(self, key):399 membval = getattr(self, key)400 if not key in self._dbvaluescache:401 continue #we rely on the correct preparation of the cache402 #all joined types are not compared for changes403 if self._dbvaluescache[key] != membval:404 return True405 return False406 407 def initialise_attributes(self):408 vd = self._get_my_memberdict()409 for key, value in vd.items():410 if hasattr(self, key) and getattr(self, key) is not None:411 continue412 413 setattr(self, key, value.get_default())414 def _set_my_attribute(self, key, value):415 """ set my own attributes in a controlled manner416 """417 mycld = self._get_my_memberdict()418 if key not in mycld.keys():419 raise Exception("Cannot initialise undefined member {}".format(key))420 setattr(self, key, value)421 422 def _get_my_memberdict(self):423 mycls = self.__class__424 return mycls._classdict[mycls]425 def get_memberdeclaration(self, membername):426 md = self._get_my_memberdict()[membername]427 return md.get_declaration()428class PCatalog(PBase):429 """Basic class for Attributes defining a catalog"""430 _collectionname = "catalog"431 _cattype = None #overriden in each catalog derived from this class432 _langsensitive = False # by default no language sensititivity, bur may be overriden by derived catalogs433 Type = String(uniquegrp="_CAT_UNI_01")434 Code = String(uniquegrp="_CAT_UNI_01")435 Value = String()436 LangCode = String(uniquegrp="_CAT_UNI_01")437 def __str__(self):438 return "{}.{}.{}.{}".format(self.type, self.langcode, self.code, self.value)439 440 def __eq__(self, other):441 if other is None:442 return False443 444 return self.langcode==other.langcode and self.type==other.type and self.code == other.code445 446 @classmethod447 def is_langsensitive(cls):448 return cls._langsensitive449 @classmethod450 def additional_where(cls):451 if cls._cattype is not None:452 return cls.Type == cls._cattype #this adds where type=<myclastype> to any call 453 else:454 return None455class CommonInter(PBase):456 """derivew from this if you want to have all your intersections reside in just one457 collection identified by a type str"""458 _collectionname = "commoninter"459 _intertype = None #override in your derived class to distinguish your intersection from all of the others460 UpId = UUid(uniquegrp="_COMN_INTER_UNI")461 DownId = UUid(uniquegrp="_COMN_INTER_UNI")462 InterType = String(uniquegrp="_COMN_INTER_UNI")463 @classmethod464 def additional_where(cls):465 if cls._intertype is not None:466 return cls.InterType == cls._intertype #this adds where type=<myintertype> to any call of where467 else:468 return None469 def __init__(self, **kwargs):470 super().__init__(**kwargs)471 self.intertype=self.__class__._intertype472def getvarname(decl: BaseVarType):473 """get the name used for a field of a declaration 474 search is done by _varcode which every intstance of a field declaration gets automatically475 """476 for cls, cldentry in PBase._classdict.items():477 for key, value in cldentry.items():478 if value._declaration._varcode == decl._varcode: 479 return key480 return None481def getsubedvarname(decl: BaseVarType):482 """get the varname with dots when subnames are given or simply like getvarname when there are no subs483 """484 if decl._subdef is None:485 return getvarname(decl)486 else:487 return getvarname(decl) + "." + getsubedvarname(decl._subdef)488def is_none_or_empty(tstr : str) -> bool:489 """checks a string for None or emptyness490 returns True when tstr is None or a string which contains no characters at all"""...

Full Screen

Full Screen

BasicClasses.py

Source:BasicClasses.py Github

copy

Full Screen

1import datetime as dt2import uuid3import inspect4from pymongo.common import RETRY_READS5class ClassDictEntry(object):6 def __init__(self, membername, dectype, declaration):7 self._membername = membername8 self._dectype = dectype9 self._declaration = declaration10 def get_default(self):11 return self._declaration.get_default()12 def get_dectype(self):13 return self._dectype14 def get_declaration(self):15 return self._declaration16 def __repr__(self):17 return "datamember: {} dectype{} declared {}".format(self._membername, self._dectype, self._declaration)18class OperationStackElement(object):19 def __init__(self, left, op, right):20 self._left = left21 self._right = right22 self._op = op23 def __and__(self, other):24 return OperationStackElement(self, "&", other)25 def __or__(self, other):26 return OperationStackElement(self, "|", other)27 def __eq__(self, other):28 return OperationStackElement(self, "==", other)29 def __neq__(self, other):30 return OperationStackElement(self, "!=", other)31 def __str__(self):32 return "op " + str(self._left) + self._op + str(self._right)33class BaseComparableType(object):34 def __init__(self):35 pass36 def __eq__(self, other):37 return OperationStackElement(self, "==", other)38 def __neq__(self, other):39 return OperationStackElement(self, "!=", other)40 def __lt__(self, other):41 return OperationStackElement(self, "<", other)42 def __le__(self, other):43 return OperationStackElement(self, "<=", other)44 def __gt__(self, other):45 return OperationStackElement(self, ">", other)46 def __ge__(self, other):47 return OperationStackElement(self, ">=", other)48class Val(BaseComparableType):49 def __init__(self, value):50 self._value = value51class OrderInfo(object):52 def __init__(self, field, direction : str):53 self.field = field54 self.orderdir = direction55class SpecialWhereInfo(object):56 def __init__(self, field, infotype, infodata):57 self._field = field58 self._infotype = infotype59 self._infodata = infodata60 def __and__(self, other):61 return OperationStackElement(self, "&", other)62 def __or__(self, other):63 return OperationStackElement(self, "|", other)64 def __invert__(self):65 return OperationStackElement(None, "~", self)66 def get_left(self):67 return self._field68 def get_right(self):69 return self._infodata70 def get_op(self):71 return self._infotype72class IsIn(SpecialWhereInfo):73 def __init__(self, field, infodata):74 super().__init__(field, infotype="ISIN", infodata=infodata)75class NotIsIn(SpecialWhereInfo):76 def __init__(self, field, infodata):77 super().__init__(field, infotype="NOTISIN", infodata=infodata)78class Regex(SpecialWhereInfo):79 def __init__(self, field, infodata):80 super().__init__(field, infotype="REGEX", infodata=infodata)81class BaseType(BaseComparableType):82 _innertype = None83 _subclasses = []84 _myfieldname = None #used to cache a field name once it was searched by get_fieldname()85 def __init__(self, **kwarg):86 super().__init__()87 self._subdef = None88 self._varcode = uuid.uuid4()89 self._getpara(kwarg, "default")90 self._getpara(kwarg, "defaultgenerator")91 92 def get_default(self):93 if self._defaultgenerator is None:94 return self._default95 else:96 return self._defaultgenerator()97 def to_innertype(self, dta):98 raise Exception("Override me in <BaseType.to_innertype() in declration-type {}".format(type(self).__name__))99 def get_fieldname(self):100 if self._myfieldname is not None: return self._myfieldname101 vname = getvarname(self)102 self._myfieldname = vname103 return vname104 def _getpara(self, kwargs, name, default=None, excstr=None):105 membername = "_" + name106 done = False107 if name in kwargs.keys():108 setattr(self, membername, kwargs[name])109 done = True110 elif default is not None:111 setattr(self, membername, default)112 done = True113 elif excstr is not None:114 done = True115 raise Exception(excstr)116 if not done:117 setattr(self, membername, None)118 def desc(self):119 return OrderInfo(self, "desc")120 def asc(self):121 return OrderInfo(self, "asc")122 def sub(self, subdef):123 self._subdef = subdef124 return self125 def isin(self, subdata):126 return IsIn(self, subdata)127 def notisin(self, subdata):128 return NotIsIn(self, subdata)129 def regex(self, subdata):130 return Regex(self, subdata)131class String(BaseType):132 _innertype = str133 def __init__(self, **kwarg):134 super().__init__(**kwarg)135 def to_innertype(self, dta):136 if dta is None:137 return None138 else:139 return str(dta)140 141class UUid(BaseType):142 _innertype = uuid.uuid4143 def to_innertype(self, dta):144 if dta is None:145 return None146 t = type(dta)147 if t is uuid.uuid4:148 return dta149 elif t is str:150 return uuid.UUID(dta)151 else:152 raise Exception("Type <{0}> cannot be tranformed into a uuid".format(t.__name__))153class Int(BaseType):154 _innertype = int155 def to_innertype(self, dta):156 if dta is None:157 return None158 t = type(dta)159 if t is int:160 return dta161 elif t is str:162 return int(dta)163 else:164 raise Exception("Type <{0}> cannot be tranformed into an int".format(t.__name__))165class Float(BaseType):166 _innertype = float167 def to_innertype(self, dta):168 if dta is None:169 return None170 t = type(dta)171 if t is float:172 return dta173 elif t is str:174 return float(dta)175 else:176 raise Exception("Type <{0}> cannot be tranformed into a float".format(t.__name__))177class Boolean(BaseType):178 _innertype = bool179 def to_innertype(self, dta):180 if dta is None:181 return None182 t = type(dta)183 if t is bool:184 return dta185 elif t is str:186 lowdta = dta.lower()187 if lowdta in ["ja", "yes", "wahr", "true", "y", "1"]:188 return True189 elif lowdta in ["nein", "no", "unwahr", "false", "n", "0"]:190 return False191 else:192 raise Exception("The string <{}> cannot be transformed to a bool".format(dta))193 elif t is int:194 return dta == 1195 else:196 raise Exception("Type <{0}> cannot be tranformed into a bool".format(t.__name__))197class DateTime(BaseType):198 innertype = dt.datetime199 def to_innertype(self, dta):200 if dta is None:201 return None202 t = type(dta)203 if t is dt.datetime:204 return dta205 elif t is str:206 return dt.strptime(dta, "%m.%d.%Y %H:%M:%S")207 else:208 raise Exception("Type <{0}> cannot be tranformed into a uuid".format(t.__name__))209class Catalog(BaseType):210 _innertype = str211 def __init__(self, **kwargs):212 super().__init__(**kwargs)213 self._getpara(kwargs, "catalogtype", excstr="catalogdefinition without catalogtype is not a valid catalog definition")214 def to_innertype(self, dta):215 raise Exception("do not use to_innertype in catalogs!")216 def get_catalogtype(self):217 return self._catalogtype218class EmbeddedObject(BaseType):219 _innertype = object220 def __init__(self, **kwargs):221 super().__init__(**kwargs)222 self._getpara(kwargs, "targettype", excstr="EmbeddedObject needs a targettype!!")223 self._getpara(kwargs, "autofill", default=True)224 def get_targettype(self):225 return self._targettype226 def get_autofill(self) -> bool:227 return self._autofill228 def get_foreign_keyname(self):229 if type(self._foreignid) is str: return self._foreignid230 vname = getvarname(self._foreignid)231 if vname is not None: #if we managed to get the name, store it for future use (caching)232 self._foreignid = vname233 return vname234 def get_local_keyname(self):235 if type(self._localid) is str: return self._localid236 vname = getvarname(self._localid)237 if vname is not None: #if we managed to get the name, store it for future use (caching)238 self._localid = vname239 return vname240class EmbeddedList(EmbeddedObject):241 _innertype = list242 def __init__(self, **kwargs):243 super().__init__(**kwargs)244class JoinedEmbeddedList(EmbeddedList):245 _innertype = list246 def __init__(self, **kwargs):247 super().__init__(**kwargs)248 self._getpara(kwargs, "localid", default="_id")249 self._getpara(kwargs, "foreignid", excstr="A JoinedEmbeddedList needs a foreign id!!!")250 self._getpara(kwargs, "autofill", default=False)251 self._getpara(kwargs, "cascadedelete", default=False)252 def get_cascadedelete(self):253 return self._cascadedelete254class IntersectedList(EmbeddedList):255 _innertype = list256 def __init__(self, **kwargs):257 super().__init__(**kwargs)258 self._getpara(kwargs, "autofill", default=False)259class JoinedEmbeddedObject(EmbeddedObject):260 _innertype = object261 def __init__(self, **kwargs):262 super().__init__(**kwargs)263 self._getpara(kwargs, "localid", excstr="A JoinedEmbeddedObject needs a local id which points to the joined object")264 self._getpara(kwargs, "foreignid", default="_id")265 self._getpara(kwargs, "cascadedelete", default=False)266 def get_cascadedelete(self):267 return self._cascadedelete268class MpBase(object):269 _classdict = {}270 Id = String() #convention use uppercase first letter to create a correct data definition!!!!!! 271 Created = DateTime() # see - upercase name!!!!272 Lastupdate = DateTime() # same here273 @classmethod274 def _setup_class_dict(cls):275 if cls in cls._classdict.keys(): return276 classmemberdict = {}277 allclasses = inspect.getmro(cls)278 for allclass in allclasses:279 if issubclass(allclass, MpBase):280 members = vars(allclass)281 for key, value in members.items():282 if key[0].isupper() and issubclass(value.__class__, BaseType):283 if key=="Id":284 mykey = "_id"285 else:286 mykey = key.lower()287 classmemberdict[mykey] = ClassDictEntry(key, type(value), getattr(allclass, key))288 289 cls._classdict[cls] = classmemberdict290 @classmethod291 def get_collection_name(cls):292 if hasattr(cls, "_collectionname"):293 return getattr(cls, "_collectionname")294 else:295 return cls.__name__296 def __init__(self, **kwargs):297 self._valuesdict = {}298 self.__class__._setup_class_dict()299 for key, value in kwargs.items():300 self._set_my_attribute(key, value)301 self.initialise_attributes()302 def initialise_attributes(self):303 vd = self._get_my_memberdict()304 for key, value in vd.items():305 if hasattr(self, key) and getattr(self, key) is not None:306 continue307 308 setattr(self, key, value.get_default())309 def _set_my_attribute(self, key, value):310 """ set my own attributes in a controlled manner311 """312 mycld = self._get_my_memberdict()313 if key not in mycld.keys():314 raise Exception("Cannot initialise undefined member {}".format(key))315 setattr(self, key, value)316 317 def _get_my_memberdict(self):318 mycls = self.__class__319 return mycls._classdict[mycls]320 def get_memberdeclaration(self, membername):321 md = self._get_my_memberdict()[membername]322 return md.get_declaration()323class MpCatalog(MpBase):324 _collectionname = "catalog"325 Type = String()326 Code = String()327 Value = String()328 LangCode = String()329def getvarname(decl: BaseType):330 """get the name used for a field of a declaration 331 search is done by _varcode which every intstance of a field declaration gets automatically332 """333 for cls, cldentry in MpBase._classdict.items():334 for key, value in cldentry.items():335 if value._declaration._varcode == decl._varcode: 336 return key337 return None338def getsubedvarname(decl: BaseType):339 """get the varname with dots when subnames are given or simply like getvarname when there are no subs340 """341 if decl._subdef is None:342 return getvarname(decl)343 else:344 return getvarname(decl) + "." + getsubedvarname(decl._subdef)345def v(val):...

Full Screen

Full Screen

util.py

Source:util.py Github

copy

Full Screen

...54 configuration_file_path=os.path.abspath(file_path)55 self._loadConfigFile(configuration_file_path)56 if Util.platform=='iphone':57 Util.driver = appiumdriver.Remote(58 command_executor=self._getPara('remote_server'),59 desired_capabilities={60 'deviceName':self._getPara('deviceName'),61 'platformName':self._getPara('platformName'),62 'platformVersion':self._getPara('platformVersion'),63 'app': self._getPara('app')64 }) 65 elif Util.platform=='ipad':66 Util.driver = appiumdriver.Remote(67 command_executor=self._getPara('remote_server'),68 desired_capabilities={69 'deviceName': self._getPara('deviceName'),70 'platformName':self._getPara('platformName'),71 'platformVersion':self._getPara('platformVersion'),72 'app': self._getPara('app')73 })74 elif Util.platform=='android':75 Util.driver = appiumdriver.Remote(command_executor=self._getPara('remote_server'),76 desired_capabilities={77 'deviceName': self._getPara('deviceName'),78 'platformName':self._getPara('platformName'),79 'app': os.path.abspath(self._getPara('app')),80 'appPackage': self._getPara('appPackage'),81 'appActivity': self._getPara('appActivity')82 })83 elif Util.platform =='selendroid':84 Util.driver = appiumdriver.Remote(command_executor=self._getPara('remote_server'),85 desired_capabilities={86 'deviceName': self._getPara('deviceName'),87 'platformName':self._getPara('platformName'),88 'automationName': os.path.abspath(self._getPara('automationName')),89 'app': os.path.abspath(self._getPara('app')),90 'appPackage': self._getPara('appPackage'),91 'appActivity': self._getPara('appActivity')92 })9394 elif Util.platform=='chrome':95 Util.driver=webdriver.Chrome()96 Util.driver.maximize_window()97 self.navigate_to_url(self._getPara('url'))98 elif Util.platform=='firefox':99 Util.driver=webdriver.Firefox()100 Util.driver.maximize_window()101 self.navigate_to_url(self._getPara('url'))102 elif Util.platform=='ie':103 caps = DesiredCapabilities.INTERNETEXPLORER104 caps['ignoreProtectedModeSettings'] = True105 Util.driver=webdriver.Ie(capabilities=caps)106 Util.driver.maximize_window()107 self.navigate_to_url(self._getPara('url'))108 109 def switch_to_webview(self,index=1):110 """ Using this method before you do action of any web element in mobile. 111112 *index* argument specifies which webview you want to switch.113 114 Example:115 | switch to webview |116 """117 self._info('Current app contains below contexts(%s)'%Util.driver.contexts)118 if Util.platform=='iphone' or Util.platform=='ipad':119 Util.driver.switch_to.context('WEBVIEW_%s'%index)120 elif Util.platform=='selendroid':121 index=int(index)-1122 Util.driver.switch_to.context('WEBVIEW_%s'%index)123 124 def switch_to_native(self):125 """ Using this method before you do action of any native element in mobile. 126 127 Example:128 | switch to native |129 """130 self._info('Current app contains below contexts(%s)'%Util.driver.contexts)131 if Util.platform=='iphone' or Util.platform=='ipad':132 Util.driver.switch_to.context('NATIVE_APP')133 elif Util.platform=='selendroid':134 Util.driver.switch_to.context('NATIVE_APP') 135 136 def navigate_to_url(self,url):137 """ Using this method if you want to navigate to specified url. 138139 In device, the keyword is available for navigate to url in webview.140141 *captureScreenShot* argument : the specified url you want to navigated to.142143 Example:144 | switch to native |145 """146 self._info('Navigate to url %s'%url)147 if Util.platform in ['chrome','firefox','ie']:148 self.driver.get(url)149 elif Util.platform in ['iphone','ipad','android','selendroid']:150 self.switch_to_webview()151 self.driver.execute_script('document.location.href=arguments[0]',url) 152153 def _loadConfigFile(self,filepath):154 try:155 filepath = os.path.abspath(filepath)156 Util.configtree = ET.fromstring(open(filepath).read())157 except:158 raise EnvironmentError('Loading configuration file failed ') 159 160 def _getPara(self,paraname):161 lst_node = Util.configtree.iterfind('.//platform[@name="%s"]/para'%Util.platform)162 for child in lst_node:163 if child.attrib['name']==paraname:164 return child.attrib['value']165 break166 else:167 raise EnvironmentError('Can not find related para "%s" in "%s" node of configration file '%(paraname,Util.platform))168169 def tear_downDriver(self):170 """ Tear down Driver is just quit current driver after finishing test cases execution.171 172 It's a pair with initialdriver method, recommend putting these two functions before/after to each test cases.173 174 Example: ...

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