def getDevice(self, dmtype="adb", hwid=None, host=None, port=None, packagename=None, verbose=False): ''' Returns a device with the specified parameters ''' logLevel = mozlog.ERROR if verbose: logLevel = mozlog.DEBUG if hwid: return mozdevice.DroidConnectByHWID(hwid, logLevel=logLevel) if dmtype == "adb": if host and not port: port = 5555 return mozdevice.DroidADB(packageName=packagename, host=host, port=port, logLevel=logLevel) elif dmtype == "sut": if not host: self.parser.error("Must specify host with SUT!") if not port: port = 20701 return mozdevice.DroidSUT(host=host, port=port, logLevel=logLevel) else: self.parser.error("Unknown device manager type: %s" % type)
def test_mkdirs(self): subTests = [{'cmds': [('isdir /mnt/sdcard/baz/boop', 'FALSE'), ('isdir /mnt', 'TRUE'), ('isdir /mnt/sdcard', 'TRUE'), ('isdir /mnt/sdcard/baz', 'FALSE'), ('mkdr /mnt/sdcard/baz', '/mnt/sdcard/baz successfully created'), ('isdir /mnt/sdcard/baz/boop', 'FALSE'), ('mkdr /mnt/sdcard/baz/boop', '/mnt/sdcard/baz/boop successfully created')], 'expectException': False}, {'cmds': [('isdir /mnt/sdcard/baz/boop', 'FALSE'), ('isdir /mnt', 'TRUE'), ('isdir /mnt/sdcard', 'TRUE'), ('isdir /mnt/sdcard/baz', 'FALSE'), ('mkdr /mnt/sdcard/baz', '##AGENT-WARNING## Could not create the directory /mnt/sdcard/baz')], 'expectException': True}, ] for subTest in subTests: a = MockAgent(self, commands=subTest['cmds']) exceptionThrown = False try: d = mozdevice.DroidSUT('127.0.0.1', port=a.port, logLevel=mozlog.DEBUG) d.mkDirs('/mnt/sdcard/baz/boop/bip') except mozdevice.DMError: exceptionThrown = True self.assertEqual(exceptionThrown, subTest['expectException']) a.wait()
def test_processExist(self): for i in [('com.android.launcher', 549), ('com.fennec.android', None)]: a = MockAgent(self, commands=self.pscommands) d = mozdevice.DroidSUT("127.0.0.1", port=a.port) self.assertEqual(d.processExist(i[0]), i[1]) a.wait()
def test_init(self): """Tests DeviceManager initialization.""" a = MockAgent(self) d = mozdevice.DroidSUT("127.0.0.1", port=a.port, logLevel=mozlog.DEBUG) # all testing done in device's constructor a.wait()
def test_getLogcat(self): logcat_output = ( "07-17 00:51:10.377 I/SUTAgentAndroid( 2933): onCreate\r\n" "07-17 00:51:10.457 D/dalvikvm( 2933): GC_CONCURRENT freed 351K, 17% free 2523K/3008K, paused 5ms+2ms, total 38ms\r\n" # noqa "07-17 00:51:10.497 I/SUTAgentAndroid( 2933): Caught exception creating file in /data/local/tmp: open failed: EACCES (Permission denied)\r\n" # noqa "07-17 00:51:10.507 E/SUTAgentAndroid( 2933): ERROR: Cannot access world writeable test root\r\n" # noqa "07-17 00:51:10.547 D/GeckoHealthRec( 3253): Initializing profile cache.\r\n" "07-17 00:51:10.607 D/GeckoHealthRec( 3253): Looking for /data/data/org.mozilla.fennec/files/mozilla/c09kfhne.default/times.json\r\n" # noqa "07-17 00:51:10.637 D/GeckoHealthRec( 3253): Using times.json for profile creation time.\r\n" # noqa "07-17 00:51:10.707 D/GeckoHealthRec( 3253): Incorporating environment: times.json profile creation = 1374026758604\r\n" # noqa "07-17 00:51:10.507 D/GeckoHealthRec( 3253): Requested prefs.\r\n" "07-17 06:50:54.907 I/SUTAgentAndroid( 3876): \r\n" "07-17 06:50:54.907 I/SUTAgentAndroid( 3876): Total Private Dirty Memory 3176 kb\r\n" # noqa "07-17 06:50:54.907 I/SUTAgentAndroid( 3876): Total Proportional Set Size Memory 5679 kb\r\n" # noqa "07-17 06:50:54.907 I/SUTAgentAndroid( 3876): Total Shared Dirty Memory 9216 kb\r\n" # noqa "07-17 06:55:21.627 I/SUTAgentAndroid( 3876): 127.0.0.1 : execsu /system/bin/logcat -v time -d dalvikvm:I " # noqa "ConnectivityService:S WifiMonitor:S WifiStateTracker:S wpa_supplicant:S NetworkStateTracker:S\r\n" # noqa "07-17 06:55:21.827 I/dalvikvm-heap( 3876): Grow heap (frag case) to 3.019MB for 102496-byte allocation\r\n" # noqa "return code [0]") inp = ("execsu /system/bin/logcat -v time -d " "dalvikvm:I ConnectivityService:S WifiMonitor:S " "WifiStateTracker:S wpa_supplicant:S NetworkStateTracker:S") commands = [(inp, logcat_output)] m = MockAgent(self, commands=commands) d = mozdevice.DroidSUT("127.0.0.1", port=m.port, logLevel=logging.DEBUG) self.assertEqual( logcat_output[:-17].replace('\r\n', '\n').splitlines(True), d.getLogcat())
def test_push_dir(self): pushfile = "1234ABCD" mdsum = hashlib.md5() mdsum.update(pushfile) expectedFileResponse = mdsum.hexdigest() tempdir = tempfile.mkdtemp() complex_path = os.path.join(tempdir, "baz") os.mkdir(complex_path) f = tempfile.NamedTemporaryFile(dir=complex_path) f.write(pushfile) f.flush() subTests = [ { 'cmds': [("isdir /mnt", "TRUE"), ("isdir /mnt/sdcard", "TRUE"), ("isdir /mnt/sdcard/baz", "TRUE"), ("isdir /mnt", "TRUE"), ("isdir /mnt/sdcard", "TRUE"), ("isdir /mnt/sdcard/baz", "TRUE"), ("push /mnt/sdcard//baz/%s %s" % (os.path.basename(f.name), len(pushfile)), expectedFileResponse)], 'expectException': False }, { 'cmds': [("isdir /mnt", "TRUE"), ("isdir /mnt/sdcard", "TRUE"), ("isdir /mnt/sdcard/baz", "TRUE"), ("isdir /mnt", "TRUE"), ("isdir /mnt/sdcard", "TRUE"), ("isdir /mnt/sdcard/baz", "TRUE"), ("push /mnt/sdcard//baz/%s %s" % (os.path.basename(f.name), len(pushfile)), "BADHASH")], 'expectException': True }, { 'cmds': [("isdir /mnt", "FALSE"), ("mkdr /mnt", "##AGENT-WARNING## Could not create the directory /mnt")], 'expectException': True }, ] for subTest in subTests: a = MockAgent(self, commands=subTest['cmds']) exceptionThrown = False try: mozdevice.DroidSUT.debug = 4 d = mozdevice.DroidSUT("127.0.0.1", port=a.port) d.pushDir(tempdir, "/mnt/sdcard") except mozdevice.DMError, e: exceptionThrown = True self.assertEqual(exceptionThrown, subTest['expectException']) a.wait()
def test_getCurrentTime(self): command = [('clok', '1349980200')] m = MockAgent(self, commands=command) d = mozdevice.DroidSUT("127.0.0.1", port=m.port, logLevel=logging.DEBUG) self.assertEqual(d.getCurrentTime(), int(command[0][1]))
def test_recordLogcat(self): commands = [("execsu /system/bin/logcat -c", "return code [0]")] m = MockAgent(self, commands=commands) d = mozdevice.DroidSUT("127.0.0.1", port=m.port, logLevel=mozlog.DEBUG) # No error raised means success self.assertEqual(None, d.recordLogcat())
def test_getAppRoot(self): command = [("getapproot org.mozilla.firefox", "/data/data/org.mozilla.firefox")] m = MockAgent(self, commands=command) d = mozdevice.DroidSUT("127.0.0.1", port=m.port, logLevel=logging.DEBUG) self.assertEqual(command[0][1], d.getAppRoot('org.mozilla.firefox'))
def test_listFiles(self): m = MockAgent(self, commands=self.commands) d = mozdevice.DroidSUT("127.0.0.1", port=m.port, logLevel=logging.DEBUG) expected = (self.commands[2][1].strip()).split("\n") self.assertEqual(expected, d.listFiles("/mnt/sdcard"))
def test_init(self): """Tests DeviceManager initialization.""" a = MockAgent(self) mozdevice.DroidSUT.debug = 4 d = mozdevice.DroidSUT("127.0.0.1", port=a.port) # all testing done in device's constructor a.wait()
def test_mkdirs_on_root(self): cmds = [('isdir /', 'TRUE')] a = MockAgent(self, commands=cmds) d = mozdevice.DroidSUT('127.0.0.1', port=a.port, logLevel=mozlog.DEBUG) d.mkDirs('/foo') a.wait()
def test_init_err(self): """Tests error handling during initialization.""" a = MockAgent(self, start_commands=[("ver", "##AGENT-WARNING## No version")]) self.assertRaises( mozdevice.DMError, lambda: mozdevice.DroidSUT( "127.0.0.1", port=a.port, logLevel=logging.DEBUG)) a.wait()
def main(): if sys.version_info < (2, 7): print >> sys.stderr, "Error: You must use python version 2.7 or newer but less than 3.0" sys.exit(1) parser = RemoteXPCShellOptions() options, args = parser.parse_args() if not options.localAPK: for file in os.listdir(os.path.join(options.objdir, "dist")): if (file.endswith(".apk") and file.startswith("fennec")): options.localAPK = os.path.join(options.objdir, "dist") options.localAPK = os.path.join(options.localAPK, file) print >> sys.stderr, "using APK: " + options.localAPK break else: print >> sys.stderr, "Error: please specify an APK" sys.exit(1) options = parser.verifyRemoteOptions(options) if len(args) < 1 and options.manifest is None: print >> sys.stderr, """Usage: %s <test dirs> or: %s --manifest=test.manifest """ % (sys.argv[0], sys.argv[0]) sys.exit(1) if options.dm_trans == "adb": if options.deviceIP: dm = mozdevice.DroidADB(options.deviceIP, options.devicePort, packageName=None, deviceRoot=options.remoteTestRoot) else: dm = mozdevice.DroidADB(packageName=None, deviceRoot=options.remoteTestRoot) else: if not options.deviceIP: print "Error: you must provide a device IP to connect to via the --device option" sys.exit(1) dm = mozdevice.DroidSUT(options.deviceIP, options.devicePort, deviceRoot=options.remoteTestRoot) if options.interactive and not options.testPath: print >> sys.stderr, "Error: You must specify a test filename in interactive mode!" sys.exit(1) xpcsh = XPCShellRemote(dm, options, args) # we don't run concurrent tests on mobile options.sequential = True if not xpcsh.runTests(xpcshell='xpcshell', testClass=RemoteXPCShellTestThread, testdirs=args[0:], mobileArgs=xpcsh.mobileArgs, **options.__dict__): sys.exit(1)
def test_processList(self): a = MockAgent(self, commands=self.pscommands) d = mozdevice.DroidSUT("127.0.0.1", port=a.port) pslist = d.getProcessList() self.assertEqual(len(pslist), 2) self.assertEqual(pslist[0], [549, 'com.android.launcher', 10029]) self.assertEqual(pslist[1], [1198, 'com.twitter.android', 10066]) a.wait()
def test_chmod(self): command = [('chmod /mnt/sdcard/test', 'Changing permissions for /storage/emulated/legacy/Test\n' ' <empty>\n' 'chmod /storage/emulated/legacy/Test ok\n')] m = MockAgent(self, commands=command) d = mozdevice.DroidSUT('127.0.0.1', port=m.port, logLevel=mozlog.DEBUG) self.assertEqual(None, d.chmodDir('/mnt/sdcard/test'))
def test_unpackFile(self): commands = [("unzp /data/test/sample.zip /data/test/", "Checksum: 653400271\n" "1 of 1 successfully extracted\n")] m = MockAgent(self, commands=commands) d = mozdevice.DroidSUT("127.0.0.1", port=m.port, logLevel=mozlog.DEBUG) # No error being thrown imples all is well self.assertEqual(None, d.unpackFile("/data/test/sample.zip", "/data/test/"))
def test_validateFile(self): with tempfile.NamedTemporaryFile() as f: f.write(self.content) f.flush() # Test Valid Hashes commands_valid = [("hash /sdcard/test/file", self.temp_hash)] m = MockAgent(self, commands=commands_valid) d = mozdevice.DroidSUT("127.0.0.1", port=m.port, logLevel=mozlog.DEBUG) self.assertTrue(d.validateFile('/sdcard/test/file', f.name)) # Test invalid hashes commands_invalid = [("hash /sdcard/test/file", "0this0hash0is0completely0invalid")] m = MockAgent(self, commands=commands_invalid) d = mozdevice.DroidSUT("127.0.0.1", port=m.port, logLevel=mozlog.DEBUG) self.assertFalse(d.validateFile('/sdcard/test/file', f.name))
def test_init_err(self): """Tests error handling during initialization.""" cmds = [("testroot", "/mnt/sdcard"), ("isdir /mnt/sdcard/tests", "/mnt/sdcard/tests: No such file or directory\n"), ("isdir /mnt/sdcard/tests", "/mnt/sdcard/tests: No such file or directory\n"), ("mkdr /mnt/sdcard/tests", "/mnt/sdcard/tests successfully created"), ("ver", "SUTAgentAndroid Version 1.14")] a = MockAgent(self, start_commands = cmds) dm = mozdevice.DroidSUT("127.0.0.1", port=a.port, logLevel=mozlog.DEBUG) a.wait()
def test_killprocess(self): commands = [("ps", "1000 1486 com.android.settings\n" "10016 420 com.android.location.fused\n" "10023 335 com.android.systemui\n"), ("kill com.android.settings", "Successfully killed com.android.settings\n")] m = MockAgent(self, commands=commands) d = mozdevice.DroidSUT("127.0.0.1", port=m.port, logLevel=logging.DEBUG) # No error raised means success self.assertEqual(None, d.killProcess("com.android.settings"))
def test_moveDir(self): commands = [("mv /mnt/sdcard/tests/foo /mnt/sdcard/tests/bar", ""), ('isdir /mnt/sdcard/tests', 'TRUE'), ('cd /mnt/sdcard/tests', ''), ('ls', 'bar')] m = MockAgent(self, commands=commands) d = mozdevice.DroidSUT("127.0.0.1", port=m.port, logLevel=mozlog.DEBUG) self.assertEqual( None, d.moveTree('/mnt/sdcard/tests/foo', '/mnt/sdcard/tests/bar')) self.assertTrue(d.fileExists('/mnt/sdcard/tests/bar'))
def main(): if sys.version_info < (2, 7): print >> sys.stderr, "Error: You must use python version 2.7 or newer but less than 3.0" sys.exit(1) parser = parser_remote() options = parser.parse_args() if not options.localAPK: for file in os.listdir(os.path.join(options.objdir, "dist")): if (file.endswith(".apk") and file.startswith("fennec")): options.localAPK = os.path.join(options.objdir, "dist") options.localAPK = os.path.join(options.localAPK, file) print >> sys.stderr, "using APK: " + options.localAPK break else: print >> sys.stderr, "Error: please specify an APK" sys.exit(1) options = verifyRemoteOptions(parser, options) log = commandline.setup_logging("Remote XPCShell", options, {"tbpl": sys.stdout}) if options.dm_trans == "adb": if options.deviceIP: dm = mozdevice.DroidADB(options.deviceIP, options.devicePort, packageName=None, deviceRoot=options.remoteTestRoot) else: dm = mozdevice.DroidADB(packageName=None, deviceRoot=options.remoteTestRoot) else: if not options.deviceIP: print "Error: you must provide a device IP to connect to via the --device option" sys.exit(1) dm = mozdevice.DroidSUT(options.deviceIP, options.devicePort, deviceRoot=options.remoteTestRoot) if options.interactive and not options.testPath: print >> sys.stderr, "Error: You must specify a test filename in interactive mode!" sys.exit(1) if options.xpcshell is None: options.xpcshell = "xpcshell" xpcsh = XPCShellRemote(dm, options, log) # we don't run concurrent tests on mobile options.sequential = True if not xpcsh.runTests(testClass=RemoteXPCShellTestThread, mobileArgs=xpcsh.mobileArgs, **vars(options)): sys.exit(1)
def test_timeout_normal(self): """Tests DeviceManager timeout, normal case.""" a = MockAgent(self, commands = [("isdir /mnt/sdcard/tests", "TRUE"), ("cd /mnt/sdcard/tests", ""), ("ls", "test.txt"), ("rm /mnt/sdcard/tests/test.txt", "Removed the file")]) d = mozdevice.DroidSUT("127.0.0.1", port=a.port, logLevel=mozlog.DEBUG) ret = d.removeFile('/mnt/sdcard/tests/test.txt') self.assertEqual(ret, None) # if we didn't throw an exception, we're ok a.wait()
def test_getFile(self): fname = "/mnt/sdcard/file" commands = [("pull %s" % fname, "%s,%s\n%s" % (fname, len(self.content), self.content)), ("hash %s" % fname, self.temp_hash)] with tempfile.NamedTemporaryFile() as f: m = MockAgent(self, commands=commands) d = mozdevice.DroidSUT("127.0.0.1", port=m.port, logLevel=mozlog.DEBUG) # No error means success self.assertEqual(None, d.getFile(fname, f.name))
def test_init(self): self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._sock.bind(("127.0.0.1", 0)) self._sock.listen(1) thread = self._serve([("testroot", "/mnt/sdcard"), ("cd /mnt/sdcard/tests", ""), ("cwd", "/mnt/sdcard/tests")]) port = self._sock.getsockname()[1] d = mozdevice.DroidSUT("127.0.0.1", port=port) thread.join()
def test_getInfo(self): for directive in self.commands.keys(): m = MockAgent(self, commands=[self.commands[directive]]) d = mozdevice.DroidSUT('127.0.0.1', port=m.port, logLevel=logging.DEBUG) expected = re.sub(r'\ +', ' ', self.commands[directive][1]).split('\n') # Account for slightly different return format for 'process' if directive is 'process': expected = [[x] for x in expected] self.assertEqual(d.getInfo(directive=directive)[directive], expected)
def test_copyDir(self): commands = [('dd if=/mnt/sdcard/tests/foo of=/mnt/sdcard/tests/bar', ''), ('isdir /mnt/sdcard/tests', 'TRUE'), ('cd /mnt/sdcard/tests', ''), ('ls', 'foo\nbar')] m = MockAgent(self, commands=commands) d = mozdevice.DroidSUT("127.0.0.1", port=m.port, logLevel=mozlog.DEBUG) self.assertEqual( None, d.copyTree('/mnt/sdcard/tests/foo', '/mnt/sdcard/tests/bar')) expected = (commands[3][1].strip()).split('\n') self.assertEqual(expected, d.listFiles('/mnt/sdcard/tests'))
def test_nouserserial(self): a = MockAgent(self, commands=[("ps", "10029 549 com.android.launcher\n" "10066 1198 com.twitter.android"), ("info sutuserinfo", ""), ("exec am start -W -n " "org.mozilla.fennec/.App -a " "android.intent.action.VIEW", "OK\nreturn code [0]")]) d = mozdevice.DroidSUT("127.0.0.1", port=a.port, logLevel=mozlog.DEBUG) d.launchFennec("org.mozilla.fennec") a.wait()
def test_badProcessList(self): a = MockAgent(self, commands=self.bad_pscommands) d = mozdevice.DroidSUT("127.0.0.1", port=a.port) exceptionTriggered = False try: d.getProcessList() except mozdevice.DMError: exceptionTriggered = True self.assertTrue(exceptionTriggered) a.wait()
def test_removeDir(self): commands = [("isdir /mnt/sdcard/test", "TRUE"), ("rmdr /mnt/sdcard/test", "Deleting file(s) from " "/storage/emulated/legacy/Moztest\n" " <empty>\n" "Deleting directory " "/storage/emulated/legacy/Moztest\n")] m = MockAgent(self, commands=commands) d = mozdevice.DroidSUT("127.0.0.1", port=m.port, logLevel=logging.DEBUG) # No error implies we're all good self.assertEqual(None, d.removeDir("/mnt/sdcard/test"))