How to use _monkeyCommand method in fMBT

Best Python code snippet using fMBT_python

fmbtandroid.py

Source:fmbtandroid.py Github

copy

Full Screen

...1100 self._monkeySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)1101 self._monkeySocket.connect((self._m_host, self._m_port))1102 self._monkeySocket.setblocking(0)1103 self._monkeySocket.settimeout(1.0)1104 self._platformVersion = self._monkeyCommand("getvar build.version.release", retry=0)[1]1105 if len(self._platformVersion) > 0:1106 self._monkeySocket.settimeout(5.0)1107 return True1108 except Exception, e:1109 failureCountSinceKill += 11110 time.sleep(pollDelay)1111 if failureCountSinceKill > 2 and tryKillingMonkeyOnFailure > 0:1112 if self._shellSupportsSu:1113 self._runSetupCmd(["shell", "su", "root", "pkill", "monkey"])1114 else:1115 self._runSetupCmd(["shell", "pkill", "monkey"])1116 tryKillingMonkeyOnFailure -= 11117 failureCountSinceKill = 01118 time.sleep(pollDelay)1119 if self._stopOnError:1120 msg = 'Android monkey error: cannot connect to "adb shell monkey --port 1080" to device %s' % (self._serialNumber)1121 _adapterLog(msg)1122 raise AndroidConnectionError(msg)1123 else:1124 return False1125 def _monkeyCommand(self, command, retry=3):1126 try:1127 self._monkeySocket.sendall(command + "\n")1128 data = self._monkeySocket.recv(4096).strip()1129 if len(data) == 0 and retry > 0:1130 return self._monkeyCommand(command, retry-1)1131 if data == "OK":1132 return True, None1133 elif data.startswith("OK:"):1134 return True, data.split("OK:")[1]1135 _adapterLog("monkeyCommand failing... command: '%s' response: '%s'" % (command, data))1136 return False, None1137 except socket.error:1138 try: self._monkeySocket.close()1139 except: pass1140 if retry > 0:1141 self._resetMonkey()1142 return self._monkeyCommand(command, retry=retry-1)1143 else:1144 raise AndroidConnectionError('Android monkey socket connection lost while sending command "%s"' % (command,))1145 def reboot(self, reconnect, firstBootAfterFlashing, timeout):1146 if firstBootAfterFlashing:1147 self._runAdb("root")1148 time.sleep(2)1149 self._runAdb(["shell", "rm", "/data/data/com.android.launcher/shared_prefs/com.android.launcher2.prefs.xml"])1150 self._runAdb("reboot")1151 _adapterLog("rebooting " + self._serialNumber)1152 if reconnect:1153 time.sleep(2)1154 endTime = time.time() + timeout1155 status, _, _ = self._runAdb("wait-for-device", expectedExitStatus=None, timeout=timeout)1156 if status != 0:1157 raise AndroidDeviceNotFound('"timeout %s adb wait-for-device" status %s' % (timeout, status))1158 self._detectFeatures()1159 while time.time() < endTime:1160 try:1161 if self._resetMonkey(timeout=1, pollDelay=1):1162 break1163 except AndroidConnectionError:1164 pass1165 time.sleep(1)1166 else:1167 msg = "reboot: reconnecting to " + self._serialNumber + " failed"1168 _adapterLog(msg)1169 raise AndroidConnectionError(msg)1170 self._resetWindow()1171 return True1172 def recvVariable(self, variableName):1173 ok, value = self._monkeyCommand("getvar " + variableName)1174 if ok: return value1175 else:1176 # LOG: getvar variableName failed1177 return None1178 def recvScreenSize(self):1179 try:1180 height = int(self.recvVariable("display.height"))1181 width = int(self.recvVariable("display.width"))1182 except TypeError:1183 return None, None1184 return width, height1185 def recvTopAppWindow(self):1186 _, output, _ = self._runAdb(["shell", "dumpsys", "window"], 0)1187 if self._platformVersion >= "4.2":1188 s = re.findall("mCurrentFocus=Window\{(#?[0-9A-Fa-f]{8})( [^ ]*)? (?P<winName>[^}]*)\}", output)1189 else:1190 s = re.findall("mCurrentFocus=Window\{(#?[0-9A-Fa-f]{8}) (?P<winName>[^ ]*) [^ ]*\}", output)1191 if s and len(s[-1][-1].strip()) > 1:1192 topWindowName = s[-1][-1]1193 if len(s) > 0:1194 _adapterLog('recvTopAppWindow warning: several mCurrentFocus windows: "%s"'1195 % ('", "'.join([w[-1] for w in s]),))1196 else: topWindowName = None1197 s = re.findall("mFocusedApp=AppWindowToken.*ActivityRecord\{#?[0-9A-Fa-f]{8}( [^ ]*)? (?P<appName>[^}]*)\}", output)1198 if s and len(s[0][-1].strip()) > 1:1199 topAppName = s[0][-1].strip()1200 else:1201 topAppName = None1202 return topAppName, topWindowName1203 def sendTap(self, xCoord, yCoord):1204 xCoord, yCoord = self._screenToDisplay(xCoord, yCoord)1205 return self._monkeyCommand("tap " + str(xCoord) + " " + str(yCoord))[0]1206 def sendKeyUp(self, key):1207 return self._monkeyCommand("key up " + key)[0]1208 def sendKeyDown(self, key):1209 return self._monkeyCommand("key down " + key)[0]1210 def sendTouchUp(self, xCoord, yCoord):1211 xCoord, yCoord = self._screenToDisplay(xCoord, yCoord)1212 return self._monkeyCommand("touch up " + str(xCoord) + " " + str(yCoord))[0]1213 def sendTouchDown(self, xCoord, yCoord):1214 xCoord, yCoord = self._screenToDisplay(xCoord, yCoord)1215 return self._monkeyCommand("touch down " + str(xCoord) + " " + str(yCoord))[0]1216 def sendTouchMove(self, xCoord, yCoord):1217 xCoord, yCoord = self._screenToDisplay(xCoord, yCoord)1218 return self._monkeyCommand("touch move " + str(xCoord) + " " + str(yCoord))[0]1219 def sendTrackBallMove(self, dx, dy):1220 dx, dy = self._screenToDisplay(dx, dy)1221 return self._monkeyCommand("trackball " + str(dx) + " " + str(dy))[0]1222 def sendPress(self, key):1223 return self._monkeyCommand("press " + key)[0]1224 def sendType(self, text):1225 for lineIndex, line in enumerate(text.split('\n')):1226 if lineIndex > 0: self.sendPress("KEYCODE_ENTER")1227 for wordIndex, word in enumerate(line.split(' ')):1228 if wordIndex > 0: self.sendPress("KEYCODE_SPACE")1229 if len(word) > 0 and not self._monkeyCommand("type " + word)[0]:1230 _adapterLog('sendType("%s") failed when sending word "%s"' %1231 (text, word))1232 return False1233 return True1234 def sendWake(self):1235 return self._monkeyCommand("wake")[0]1236 def recvScreenshot(self, filename, retry=2, retryDelay=1.0):1237 """1238 Capture a screenshot and copy the image file to given path or1239 system temp folder.1240 Returns True on success, otherwise False.1241 """1242 remotefile = '/sdcard/' + os.path.basename(filename)1243 self._runAdb(['shell', 'screencap', '-p', remotefile], 0)1244 status, out, err = self._runAdb(['pull', remotefile, filename], [0, 1])1245 if status != 0:1246 raise FMBTAndroidError("Failed to fetch screenshot from the device: %s. SD card required." % ((out + err).strip(),))1247 status, _, _ = self._runAdb(['shell', 'rm', remotefile], 0)1248 if os.path.getsize(filename) == 0:1249 _adapterLog("received screenshot of size 0")...

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