Best Python code snippet using fMBT_python
fmbtgti.py
Source:fmbtgti.py
...113 if isinstance(screenshotOrOcrEngine, Screenshot):114 ocrEngine = screenshotOrOcrEngine.ocrEngine()115 else:116 ocrEngine = screenshotOrOcrEngine117 return _takeArgs(ocrEngine._findTextArgNames(), d, thatsAll)118def _takeArgs(argNames, d, thatsAll=False):119 """120 Returns pair:121 (dict of items where key in argNames,122 dict of items that were left in d)123 If thatsAll is True, require that all arguments have been124 consumed.125 """126 retval = {}127 for a in argNames:128 if a in d:129 retval[a] = d.pop(a, None)130 if thatsAll and len(d) > 0:131 raise TypeError('Unknown argument(s): "%s"' %132 ('", "'.join(sorted(d.keys()))))133 return retval, d134def _intCoords((x, y), (width, height)):135 if 0 <= x <= 1 and type(x) == float: x = x * width136 if 0 <= y <= 1 and type(y) == float: y = y * height137 return (int(round(x)), int(round(y)))138def _edgeDistanceInDirection((x, y), (width, height), direction):139 x, y = _intCoords((x, y), (width, height))140 direction = direction % 360 # -90 => 270, 765 => 45141 dirRad = math.radians(direction)142 if 0 < direction < 180:143 distTopBottom = y / math.sin(dirRad)144 elif 180 < direction < 360:145 distTopBottom = -(height - y) / math.sin(dirRad)146 else:147 distTopBottom = float('inf')148 if 90 < direction < 270:149 distLeftRight = -x / math.cos(dirRad)150 elif 270 < direction <= 360 or 0 <= direction < 90:151 distLeftRight = (width - x) / math.cos(dirRad)152 else:153 distLeftRight = float('inf')154 return min(distTopBottom, distLeftRight)155### Binding to eye4graphics.so156_libpath = ["", ".", distutils.sysconfig.get_python_lib(plat_specific=1)]157_suffix = ".so"158if sys.platform == "win32":159 _suffix = ".dll"160for _dirname in _libpath:161 try:162 eye4graphics = ctypes.CDLL(os.path.join(_dirname , "eye4graphics"+_suffix))163 break164 except: pass165else:166 raise ImportError("%s cannot load eye4graphics.so" % (__file__,))167class _Bbox(ctypes.Structure):168 _fields_ = [("left", ctypes.c_int32),169 ("top", ctypes.c_int32),170 ("right", ctypes.c_int32),171 ("bottom", ctypes.c_int32),172 ("error", ctypes.c_int32)]173### end of binding to eye4graphics.so174def _e4gImageDimensions(e4gImage):175 struct_bbox = _Bbox(0, 0, 0, 0, 0)176 eye4graphics.openedImageDimensions(ctypes.byref(struct_bbox), e4gImage)177 return (struct_bbox.right, struct_bbox.bottom)178def _e4gImageIsBlank(filename):179 e4gImage = eye4graphics.openImage(filename)180 rv = (eye4graphics.openedImageIsBlank(e4gImage) == 1)181 eye4graphics.closeImage(e4gImage)182 return rv183class GUITestConnection(object):184 """185 Implements GUI testing primitives needed by GUITestInterface.186 All send* and recv* methods return187 - True on success188 - False on user error (unknown keyName, coordinates out of range)189 - raise Exception on framework error (connection lost, missing190 dependencies).191 """192 def sendPress(self, keyName):193 raise NotImplementedError('sendPress("%s") needed but not implemented.' % (keyName,))194 def sendKeyDown(self, keyName):195 raise NotImplementedError('sendKeyDown("%s") needed but not implemented.' % (keyName,))196 def sendKeyUp(self, keyName):197 raise NotImplementedError('sendKeyUp("%s") needed but not implemented.' % (keyName,))198 def sendTap(self, x, y):199 raise NotImplementedError('sendTap(%d, %d) needed but not implemented.' % (x, y))200 def sendTouchDown(self, x, y):201 raise NotImplementedError('sendTouchDown(%d, %d) needed but not implemented.' % (x, y))202 def sendTouchMove(self, x, y):203 raise NotImplementedError('sendTouchMove(%d, %d) needed but not implemented.' % (x, y))204 def sendTouchUp(self, x, y):205 raise NotImplementedError('sendTouchUp(%d, %d) needed but not implemented.' % (x, y))206 def sendType(self, text):207 raise NotImplementedError('sendType("%s") needed but not implemented.' % (text,))208 def recvScreenshot(self, filename):209 """210 Saves screenshot from the GUI under test to given filename.211 """212 raise NotImplementedError('recvScreenshot("%s") needed but not implemented.' % (filename,))213 def target(self):214 """215 Returns a string that is unique to each test target. For216 instance, Android device serial number.217 """218 return "GUITestConnectionTarget"219class OrEngine(object):220 """221 Optical recognition engine. Base class for OCR and OIR engines,222 enables registering engine instances.223 """224 def __init__(self, *args, **kwargs):225 pass226 def register(self, defaultOcr=False, defaultOir=False):227 """228 Register this engine instance to the list of OCR and/or OIR229 engines.230 Parameters:231 defaultOcr (optional, boolean):232 if True, use this OCR engine by default in all new233 GUITestInterface instances. The default is False.234 defaultOir (optional, boolean):235 if True, use this OIR engine by default in all new236 GUITestInterface instances. The default is False.237 Returns the index with which the engine was registered to the238 list of OCR or OIR engines. If this instance implements both239 OCR and OIR engines, returns pair (OCR index, OIR index).240 """241 # Allow a single engine implement both OCR and OIR engine242 # interfaces. Therefore, it must be possible to call243 # e.register(defaultOcr=True, defaultOir=True).244 #245 global _g_defaultOcrEngine, _g_defaultOirEngine246 global _g_ocrEngines, _g_oirEngines247 engineIndexes = []248 if isinstance(self, OcrEngine):249 if not self in _g_ocrEngines:250 _g_ocrEngines.append(self)251 engineIndexes.append(_g_ocrEngines.index(self))252 if defaultOcr:253 _g_defaultOcrEngine = self254 if isinstance(self, OirEngine):255 if not self in _g_oirEngines:256 _g_oirEngines.append(self)257 engineIndexes.append(_g_oirEngines.index(self))258 if defaultOir:259 _g_defaultOirEngine = self260 if len(engineIndexes) == 1:261 return engineIndexes[0]262 else:263 return engineIndexes264class OcrEngine(OrEngine):265 """266 This is an abstract interface for OCR engines that can be plugged267 into fmbtgti.GUITestInterface instances and Screenshots.268 To implement an OCR engine, you need to override _findText() at269 minimum. See _findText documentation in this class for270 requirements.271 If possible in your OCR engine, you can provide _dumpOcr() to272 reveal what is recognized in screenshots.273 For efficient caching of results and freeing cached results, you274 can override _addScreenshot() and _removeScreenshot(). Every275 screenshot is added before findText() or dumpOcr().276 A typical usage of OcrEngine instance:277 - oe.addScreenshot(ss)278 - oe.findText(ss, text1, <engine/screenshot/find-specific-args>)279 - oe.findText(ss, text2, <engine/screenshot/find-specific-args>)280 - oe.removeScreenshot(ss)281 Note that there may be several screenshots added before they are282 removed.283 """284 def __init__(self, *args, **kwargs):285 super(OcrEngine, self).__init__(*args, **kwargs)286 self._ssFindTextDefaults = {}287 self._findTextDefaults = {}288 ocrFindArgs, _ = _takeOcrArgs(self, kwargs)289 self._setFindTextDefaults(ocrFindArgs)290 def dumpOcr(self, screenshot, **kwargs):291 """292 Returns what is recognized in the screenshot. For debugging293 purposes.294 """295 ocrArgs = self.__ocrArgs(screenshot, **kwargs)296 return self._dumpOcr(screenshot, **ocrArgs)297 def _dumpOcr(self, screenshot, **kwargs):298 return None299 def addScreenshot(self, screenshot, **findTextDefaults):300 """301 Prepare for finding text from the screenshot.302 Parameters:303 screenshot (fmbtgti.Screenshot)304 screenshot object to be searched from.305 other parameters (optional)306 findText defaults for this screenshot.307 Notice that there may be many screenshots simultaneously.308 Do not keep reference to the screenshot object.309 """310 self.setScreenshotFindTextDefaults(screenshot, **findTextDefaults)311 return self._addScreenshot(screenshot, **findTextDefaults)312 def _addScreenshot(self, screenshot, **findTextDefaults):313 pass314 def removeScreenshot(self, screenshot):315 """316 OCR queries on the screenshot will not be made anymore.317 """318 self._removeScreenshot(screenshot)319 try:320 del self._ssFindTextDefaults[id(screenshot)]321 except KeyError:322 raise KeyError('screenshot "%s" does not have findTextDefaults. '323 'If OcrEngine.addScreenshot() is overridden, it '324 '*must* call parent\'s addScreenshot.' % (screenshot.filename(),))325 def _removeScreenshot(self, screenshot):326 pass327 def setFindTextDefaults(self, **findTextDefaults):328 return self._setFindTextDefaults(findTextDefaults, screenshot=None)329 def setScreenshotFindTextDefaults(self, screenshot, **findTextDefaults):330 return self._setFindTextDefaults(findTextDefaults, screenshot=screenshot)331 def _setFindTextDefaults(self, defaults, screenshot=None):332 """333 Set default values for optional arguments for findText().334 Parameters:335 defaults (dictionary)336 Default keyword arguments and their values.337 screenshot (optional, fmbtgti.Screenshot instance)338 Use the defaults for findText on this screenshot. If339 the defaults are None, make them default for all340 screenshots. Screenshot-specific defaults override341 engine default.342 """343 if screenshot == None:344 self._findTextDefaults.update(defaults)345 else:346 ssid = id(screenshot)347 if not ssid in self._ssFindTextDefaults:348 self._ssFindTextDefaults[ssid] = self._findTextDefaults.copy()349 self._ssFindTextDefaults[ssid].update(defaults)350 def findTextDefaults(self, screenshot=None):351 if screenshot == None:352 return self._findTextDefaults353 elif id(screenshot) in self._ssFindTextDefaults:354 return self._ssFindTextDefaults[id(screenshot)]355 else:356 return None357 def _findTextArgNames(self):358 """359 Returns names of optional findText arguments.360 """361 return inspect.getargspec(self._findText).args[3:]362 def __ocrArgs(self, screenshot, **priorityArgs):363 ocrArgs = {}364 ocrArgs.update(self._findTextDefaults)365 ssId = id(screenshot)366 if ssId in self._ssFindTextDefaults:367 ocrArgs.update(self._ssFindTextDefaults[ssId])368 ocrArgs.update(priorityArgs)369 return ocrArgs370 def findText(self, screenshot, text, **kwargs):371 """...
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!!