Best Python code snippet using pyatom_python
_a11y.py
Source:_a11y.py
...50 raise ErrorUnsupported('Return value not supported yet: {}'.format(ax_attr_type))51def _sigHandler(sig):52 AppHelper.stopEventLoop()53 raise KeyboardInterrupt('Keyboard interrupted Run Loop')54def _setError(error_code, error_message):55 error_mapping = {56 kAXErrorAttributeUnsupported: ErrorUnsupported, # -2520557 kAXErrorActionUnsupported: ErrorUnsupported, # -2520658 kAXErrorNotificationUnsupported: ErrorUnsupported, # -2520759 kAXErrorAPIDisabled: ErrorAPIDisabled, # -2521160 kAXErrorInvalidUIElement: ErrorInvalidUIElement, # -2520261 kAXErrorCannotComplete: ErrorCannotComplete, # -2520462 kAXErrorNotImplemented: ErrorNotImplemented, # -2520863 }64 msg = '{} (AX Error {})'.format(error_message, error_code)65 raise error_mapping[error_code](msg)66class Error(Exception):67 pass68class ErrorAPIDisabled(Error):69 pass70class ErrorInvalidUIElement(Error):71 pass72class ErrorCannotComplete(Error):73 pass74class ErrorUnsupported(Error):75 pass76class ErrorNotImplemented(Error):77 pass78class AXUIElement(object):79 """80 Apple AXUIElement object81 """82 """83 1. Factory class methods for getAppRefByPid and getSystemObject which84 properly instantiate the class.85 2. Generators and methods for finding objects for use in child classes.86 3. __getattribute__ call for invoking actions.87 4. waitFor utility based upon AX notifications.88 """89 def __init__(self, ref=None, callback_fn=None, callback_args=None, callback_kwargs=None, observer_res=None):90 super(AXUIElement, self).__init__()91 self.ref = ref92 self.callbackFn = callback_fn93 self.callbackArgs = callback_args94 self.callbackKwargs = callback_kwargs95 self.observerRes = observer_res96 def _setNotification(self, timeout=0, notificationStr=None, callbackFn=None, callbackArgs=None, callbackKwargs=None):97 if callable(callbackFn):98 self.callbackFn = callbackFn99 if isinstance(callbackArgs, tuple):100 self.callbackArgs = callbackArgs101 else:102 self.callbackArgs = tuple()103 if isinstance(callbackKwargs, dict):104 self.callbackKwargs = callbackKwargs105 self.observerRes = None106 pid = self._getPid()107 err, observer = AXObserverCreate(pid, observerCallback, None)108 if err != kAXErrorSuccess:109 _setError(err, 'Could not create observer for notification')110 err = AXObserverAddNotification(111 observer, self.ref,112 notificationStr,113 self114 )115 if err != kAXErrorSuccess:116 _setError(err, 'Could not add notification to observer')117 #Add observer source to run loop118 CFRunLoopAddSource(119 CFRunLoopGetCurrent(),120 AXObserverGetRunLoopSource(observer),121 kCFRunLoopDefaultMode122 )123 # Set the signal handlers prior to running the run loop124 oldSigIntHandler = MachSignals.signal(signal.SIGINT, _sigHandler)125 # If an error occurs (return value is SIG_ERR), continue as it's not fatal126 AppHelper.runConsoleEventLoop(127 mode=kCFRunLoopDefaultMode,128 installInterrupt=False,129 maxTimeout=timeout,130 )131 MachSignals.signal(signal.SIGINT, oldSigIntHandler)132 err = AXObserverRemoveNotification(observer, self.ref, notificationStr)133 if err != kAXErrorSuccess:134 _setError(err, 'Could not remove notification from observer')135 return self.observerRes136 # if timeout137 # return False138 def _getAttributes(self):139 """140 Get a list of the actions available on the AXUIElement141 :return:142 """143 err, attr = AXUIElementCopyAttributeNames(self.ref, None)144 if err != kAXErrorSuccess:145 _setError(err, 'Error retrieving attribute list')146 else:147 return list(attr)148 def _getActions(self):149 """150 Get a list of the actions available on the AXUIElement151 :return:152 """153 if self.ref is None:154 raise Error('Not a valid accessibility object')155 err, actions = AXUIElementCopyActionNames(self.ref, None)156 if err != kAXErrorSuccess:157 _setError(err, 'Error retrieving action names')158 else:159 return list(actions)160 def _performAction(self, action):161 """162 Perform the specified action on the AXUIElement object163 :param action:164 :return:165 """166 err = AXUIElementPerformAction(self.ref, action)167 if err != kAXErrorSuccess:168 _setError(err, 'Error performing requested action')169 def _getAttribute(self, attr):170 """171 Get the value of the the specified attribute172 :param args:173 :return:174 """175 err, attrValue = AXUIElementCopyAttributeValue(self.ref, attr, None)176 if err == kAXErrorNoValue:177 return178 if err != kAXErrorSuccess:179 if err == kAXErrorNotImplemented:180 _setError(err, 'Attribute not implemented')181 else:182 _setError(err, 'Error retrieving attribute')183 return _CFAttributeToPyObject(self, attrValue)184 def _setAttribute(self, attr, val):185 """186 Set the specified attribute to the specified value187 :param args:188 :return:189 """190 self._getAttribute(attr)191 err, to_set = AXUIElementCopyAttributeValue(self.ref, attr, None)192 if err != kAXErrorSuccess:193 _setError(err, 'Error retrieving attribute to set')194 err, settable = AXUIElementIsAttributeSettable(self.ref, attr, None)195 if err != kAXErrorSuccess:196 _setError(err, 'Error querying attribute')197 if not settable:198 raise ErrorUnsupported('Attribute is not settable')199 err = AXUIElementSetAttributeValue(self.ref, attr, val)200 if err != kAXErrorSuccess:201 if err == kAXErrorIllegalArgument:202 _setError(err, 'Invalid value for element attribute')203 _setError(err, 'Error setting attribute value')204 # def __setattr__(self, name, value):205 # pass206 def _setString(self, attribute, value):207 err = AXUIElementSetAttributeValue(self.ref, attribute, str(value))208 if err != kAXErrorSuccess:209 _setError(err, 'Error setting attribute to string')210 def _getPid(self):211 """212 Get the PID of the AXUIElement213 """214 error_code, pid = AXUIElementGetPid(self.ref, None)215 if error_code != kAXErrorSuccess:216 _setError(error_code, 'Error retrieving PID')217 return pid218 def _setTimeout(self, newTimeout):219 if self.ref is None:220 raise ErrorUnsupported('Operation not supported on null element references')221 err = AXUIElementSetMessagingTimeout(self.ref, newTimeout)222 if err == kAXErrorIllegalArgument:223 raise ValueError('Accessibility timeout values must be non-negative')224 if err == kAXErrorInvalidUIElement:225 _setError(err, 'The element reference is invalid')226 def _getElementAtPosition(self, x, y):227 if self.ref is None:228 raise ErrorUnsupported('Operation not supported on null element references')229 err, res = AXUIElementCopyElementAtPosition(self.ref, x, y, None)230 if err == kAXErrorIllegalArgument:231 raise ValueError('Arguments must be two floats.')232 return self.with_ref(res)233 @classmethod234 def with_ref(cls, ref):235 """236 Create a new Python AXUIElement object from a given Apple AXUIElementRef237 :param ref:238 :return:239 """...
prefMng.py
Source:prefMng.py
...13 ErrorMsg=""14 def __init__(self,filename):15 self.filename=filename16 self.UpgradeSettings()17 def _setError(self,code,msg):18 self.ErrorNum=code19 self.ErrorMsg=msg20 def _MergeSettings(self,new,curr):21 data={}22 for nk in new:23 if nk in curr:24 if type(new[nk])==type(curr[nk]):25 if type(new[nk])==dict:26 data[nk]=self._MergeSettings(new[nk],curr[nk])27 else:28 data[nk]=curr[nk]29 else:30 data[nk]=new[nk]31 return data32 33 34 def UpgradeSettings(self):35 defdata=self.default_data36 data=self.ReadJSON(self.filename,False)37 if data==None:38 self.settings=self.default_data 39 self._setError(2,"No setting file found. No settings re-use needed.")40 return41 if "version" in data and defdata["version"]==data["version"]:42 self.settings=data 43 self._setError(0,"No Setting upgrade needed.")44 return45 newdata=self._MergeSettings(defdata,data)46 newdata["version"]=defdata["version"]47 self.WriteJSON(self.filename,newdata)48 self.settings=newdata49 return newdata50 def ReadJSON(self,filename=None,useDefault=True):51 if filename==None: filename=self.filename52 try:53 with open(self.filename) as outfile:54 try:55 self.settings=json.load(outfile)56 self._setError(0,"Load OK")57 except Exception as ex:58 self._setError(1,f"Unable to load json. {ex}")59 print(ex)60 if useDefault: self.settings=self.default_data61 else: self.settings=None62 outfile.close()63 except Exception as ex:64 if useDefault: self.settings=self.default_data65 else: self.settings=None66 self._setError(1,f"Fail to load setting! Default data ({ex})")67 return self.settings68 def WriteJSON(self,filename,data):69 try:70 with open(filename, "w") as outfile:71 json.dump(data,outfile,indent=4,default=str)72 outfile.close()73 self.isPendingChanges=False74 except Exception as ex:75 pass76 def SetSetting(self,settingList:list,value,data={}):77 resp=False78 if len(data)==0: data=self.settings79 for setting in settingList:80 if setting in data:...
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!!