Esempio n. 1
0
    def _run(self,
             device=None,
             serialno=None,
             stoptime=7200,
             width=1080,
             height=1920,
             isPraise=True):
        if device == None:
            device, serialno = ViewClient.connectToDeviceOrExit()
        elif serialno == None:
            serialno = device.serialno

        device.startActivity("com.jm.video/.ui.main.SplashActivity")
        time.sleep(8)
        device.touch(width / 2, height / 2)
        vc = ViewClient(device, serialno)
        device.touch(width / 2, height / 2)
        while True:
            vc.swipe(width / 2, height / 4 * 1, width / 2, height / 4 * 3)
            t = random.randint(1, 20)
            print t
            if t > stoptime - int(time.time()):
                t = stoptime = int(time.time())
            if t % 2 == 0:
                time.sleep(t / 2)
                vc.findViewByIdOrRaise("com.jm.video:id/praise").touch()
                time.sleep(t / 2)
            else:
                time.sleep(t)
            if int(time.time()) >= stoptime:
                break
        device.shell("am force-stop com.jm.video")
    def __call__(self):
        vc = ViewClient(self.__device, self.__serialno)

        steps = 90
        start_factor = .75
        end_factor = .55

        if self.__serialno == "04a38409344082e7":
            steps = 90
            start_factor = .75
            end_factor = .55
        elif self.__serialno == "010e3939219f5389":
            steps = 155
            start_factor = .70
            end_factor = .45
        elif self.__serialno == "22db15d035057ece":
            steps = 200
            start_factor = .65
            end_factor = .35
        elif self.__serialno == "8aee2aaa":
            steps = 100
            start_factor = .75
            end_factor = .55


        info = self.__device.getDisplayInfo()
        x = int(info['width'] * .5)
        start_y = int(info['height'] * start_factor)
        end_y = int(info['height'] * end_factor)

        vc.swipe(x, start_y, x, end_y, steps)
        vc.sleep(2)
        vc.swipe(x, start_y, x, end_y, steps)
        vc.sleep(2)
        vc.swipe(x, start_y, x, end_y, steps)
Esempio n. 3
0
    def __call__(self):
        vc = ViewClient(self.__device, self.__serialno)

        info = self.__device.getDisplayInfo()
        end_x = int(info['width'] / 4)
        start_y = int(info['height'] / 2)

        if self.__serialno == "04a38409344082e7":
            vc.swipe(0, start_y, end_x, start_y, 100)
        elif self.__serialno == "010e3939219f5389":
            vc.swipe(0, start_y, end_x, start_y, 150)

        vc.swipe(0, start_y, end_x, start_y, 100)

        vc.sleep(2)

        vc.touch(int(end_x * 4 * .9), start_y)
Esempio n. 4
0
def testAppFromTestcase(apkPath,
                        testCaseFile,
                        avdSerialno="",
                        waitInterval=1,
                        takeSnapshots=False,
                        allowCrashes=False,
                        uninstallApp=True):
    """
    Tests an app according to a specific test case loaded from a JSON file generated by a previous test
    :param apkPath: The path to the APK to test
    :type apkPath: str
    :param testCaseFile: The path to the test case file from whence the actions are loaded
    :type testCaseFile: str
    :param avdSerialno: The serial number of the Android virtual device (in case multiple devices are running simultaneously)
    :type avdSerialno: str
    :param waitInterval: The time (in seconds) to wait between actions
    :type waitInterval: int 
    :param takeSnapshots: Whether to take snapshots of the device screen after every performed action (default: False)
    :type takeSnapshots: bool
    :param allowCrashes: Whether to allow the app under test to crash. If (by default) False, the app will be re-started and re-tested.
    :type allowCrashes: bool
    :param uninstallApp: Whether to uninstall the app under test before returning
    :type uninstallApp: bool
    :return: A bool indicating the success/failure of the test
    """
    try:
        # 1. Connect to the virtual device
        prettyPrint("Connecting to device", "debug")
        if avdSerialno != "":
            vc = ViewClient(*ViewClient.connectToDeviceOrExit(
                ignoreversioncheck=True, verbose=True, serialno=avdSerialno))
        else:
            vc = ViewClient(*ViewClient.connectToDeviceOrExit(
                ignoreversioncheck=True, verbose=True))

        # 1.a. Analyzing app
        prettyPrint("Analyzing app using \"androguard\"", "debug")
        apk, dx, vm = analyzeAPK(apkPath)
        appComponents = extractAppComponents(apk)

        # 2. Install package and configure Introspy (if requested)
        prettyPrint("Installing package \"%s\"" % apkPath, "debug")
        subprocess.call([vc.adb, "-s", avdSerialno, "install", "-r", apkPath])

        # 3. Load and parse test case file
        prettyPrint("Loading the test case file \"%s\"" % testCaseFile,
                    "debug")
        if not os.path.exists(testCaseFile):
            prettyPrint("Could not find the test case file", "error")
            return False
        content = json.loads(open(testCaseFile).read())
        if len(content["events"]) < 1:
            prettyPrint("Could not retrieve events to run", "error")

        # 4. Iterate over events and execute them
        tapEvents = [
            "Button", "CheckBox", "RadioButton", "Switch", "ToggleButton"
        ]
        touchEvents = ["longtouch", "touch"]
        textEvents = ["EditText"]
        swipeEvents = ["swipeleft", "swiperight"]
        pressEvents = ["press"]
        for e in content["events"]:
            # 4.1. Parse and execute event
            if e["type"] == "activity":
                try:
                    prettyPrint("Starting activity \"%s\"" % e["id"], "debug")
                    vc.device.startActivity(e["id"])
                except exceptions.RuntimeError as rte:
                    prettyPrint("Unable to start activity \"%s\"" % e["id"],
                                "warning")
            elif e["type"] == "broadcast":
                prettyPrint("Broadcasting intent action: %s" % e["intent"],
                            "debug")
                vc.device.shell("am broadcast -a %s" % e["intent"])
            elif e["type"] in tapEvents:
                prettyPrint(
                    "Tapping %s at (%s, %s)" % (e["type"], e["x"], e["y"]),
                    "debug")
                vc.touch(int(e["x"]), int(e["y"]))
            elif e["type"] in textEvents:
                prettyPrint(
                    "Writing \"%s\" to EditText field \"%s\"" %
                    (e["text"], e["id"]), "debug")
                allviews = vc.getViewsById()
                if len(allviews) < 1 or e["id"] not in allviews.keys():
                    prettyPrint(
                        "Could not find EditText with id \"%s\". Skipping" %
                        e["id"], "warning")
                else:
                    allviews[e["id"]].setText(e["text"])
            elif e["type"] in swipeEvents:
                prettyPrint(
                    "Swiping screen from (%s, %s) to (%s, %s)" %
                    (e["x"], e["y"], e["xd"], e["yd"]), "debug")
                vc.swipe(int(e["x"]), int(e["y"]), int(e["xd"]), int(e["yd"]))
            elif e["type"] in pressEvents:
                prettyPrint("Pressing \"%s\"" % e["key"], "debug")
                vc.device.press(e["key"])
            elif e["type"].lower().find("touch") != -1:
                if e["type"] == "longtouch":
                    prettyPrint("Long touching at (%s,%s)" % (e["x"], e["y"]),
                                "debug")
                    vc.longTouch(int(e["x"]), int(e["y"]))
                else:
                    prettyPrint("Touching at (%s,%s)" % (e["x"], e["y"]),
                                "debug")
                    vc.touch(int(e["x"]), int(e["y"]))

            # 4.2. Wait for [waitInterval] seconds and take a snapshot if instructed to
            if waitInterval > 0:
                prettyPrint("Waiting for %s seconds" % waitInterval, "debug")
                time.sleep(waitInterval)
                if takeSnapshots:
                    prettyPrint("Taking snapshot", "debug")
                    snapshot = vc.device.takeSnapshot()
                    snapshot.save(
                        "%s_%s.png" %
                        (appComponents["package_name"], str(int(time.time()))))

            # 4.3. Check whether the performed action crashed or stopped (sent to background) the app
            if _appCrashed(vc, avdSerialno):
                if not allowCrashes:
                    prettyPrint(
                        "The previous action(s) caused the app to crash. Exiting",
                        "warning")
                    if uninstallApp:
                        prettyPrint("Uninstalling app \"%s\"" %
                                    appComponents["package_name"])
                        subprocess.call([
                            vc.adb, "-s", avdSerialno, "uninstall",
                            appComponents["package_name"]
                        ])
                    return False
                prettyPrint(
                    "The previous action(s) caused the app to crash. Restarting",
                    "warning")
                vc.device.startActivity("%s/%s" %
                                        (appComponents["package_name"],
                                         appComponents["main_activity"]))
                time.sleep(
                    waitInterval)  # Give time for the main activity to start
            elif _appStopped(vc, appComponents, avdSerialno):
                prettyPrint(
                    "The previous action(s) stopped the app. Restarting",
                    "warning")
                vc.device.startActivity("%s/%s" %
                                        (appComponents["package_name"],
                                         appComponents["main_activity"]))
                time.sleep(
                    waitInterval)  # Give time for the main activity to start

        # 6. Uninstalling app under test
        if uninstallApp:
            prettyPrint("Uninstalling app \"%s\"" %
                        appComponents["package_name"])
            subprocess.call([
                vc.adb, "-s", avdSerialno, "uninstall",
                appComponents["package_name"]
            ])

    except Exception as e:
        prettyPrintError(e)
        return False

    return True