Best Python code snippet using pyatom_python
_a11y.py
Source:_a11y.py
...7from PyObjCTools import AppHelper, MachSignals8"""9Library of Apple A11y functions10"""11def _CFAttributeToPyObject(self, attrValue):12 def list_helper(list_value):13 list_builder = []14 for item in list_value:15 list_builder.append(_CFAttributeToPyObject(self, item))16 return list_builder17 def number_helper(number_value):18 success, int_value = CFNumberGetValue(number_value, kCFNumberIntType, None)19 if success:20 return int(int_value)21 success, float_value = CFNumberGetValue(number_value, kCFNumberDoubleType, None)22 if success:23 return float(float_value)24 raise ErrorUnsupported('Error converting numeric attribute: {}'.format(number_value))25 def axuielement_helper(element_value):26 return self.with_ref(element_value)27 cf_attr_type = CFGetTypeID(attrValue)28 cf_type_mapping = {29 CFStringGetTypeID(): str,30 CFBooleanGetTypeID(): bool,31 CFArrayGetTypeID(): list_helper,32 CFNumberGetTypeID(): number_helper,33 AXUIElementGetTypeID(): axuielement_helper,34 }35 try:36 return cf_type_mapping[cf_attr_type](attrValue)37 except KeyError:38 # did not get a supported CF type. Move on to AX type39 pass40 ax_attr_type = AXValueGetType(attrValue)41 ax_type_map = {42 kAXValueCGSizeType: NSSizeFromString,43 kAXValueCGPointType: NSPointFromString,44 kAXValueCFRangeType: NSRangeFromString,45 }46 try:47 extracted_str = re.search('{.*}', attrValue.description()).group()48 return tuple(ax_type_map[ax_attr_type](extracted_str))49 except KeyError: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:...
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!!