示例#1
0
def load_app(app, ob, tlib, envs):
    ob.set_app(app)
    tlib.set_app(app)
    envs['app'] = app

    value.init_params("../etc/", app)
    ob.load("../model/", "../guis/", "../guis-extra/", config.extra_screens,
            config.extra_element_scrs)

    tlib.add_test(microtest.init_test(appdb.get_app(app)))
示例#2
0
    tlib.mark_succ(init, state.init_state, st)
    most_reached = tlib.get_reached(init)
    logger.info("start -> %s", most_reached)
    smgr = StateMgr(tlib, None, dev, ob, wd)
    logger.info("ready")
    ret = smgr.observe_and_clean(prop, st)
    if ret:
        logger.info("prop %s is clean now" % prop)
    else:
        logger.info("observe/clean error")


if __name__ == "__main__":
    import sys
    app = sys.argv[2]

    import logging
    logging.basicConfig(level=logging.INFO)

    import appdb
    appdb.collect_apps("../apks/")

    import value
    value.init_params("../etc/", app)

    import device
    dev = device.Device(serial=sys.argv[1])
    observe_clean_app(dev, app=sys.argv[2], prop=sys.argv[3])

    dev.finish()
示例#3
0
def handle_console_cmd(cons, cmd, envs):
    threading.current_thread().name = 'MainThread'

    dev = envs['dev']
    ob = envs['ob']
    st = envs['state']
    tlib = envs['tlib']
    env = envs['env']

    if 'app' in envs:
        app = envs['app']
    else:
        app = 'cui'

    def save_stat():
        tlib.save_stat(os.path.join("../stat/", "%s.txt" % app))

    if cmd == 'q':
        save_stat()
        dev.finish()
        sys.exit(0)
    elif cmd == 'sense':
        scr = ob.grab_state(dev, no_verify=True, no_print=True)
        if scr.get('guess_descs') is None:
            util.print_tree(scr.get('tree'))
        else:
            util.print_tree(scr.get('tree'), scr.get('guess_descs'),
                            scr.get('guess_score'))
        st.merge(scr)
        return
    elif cmd == 'tags':
        config.show_guess_tags = True
        scr = ob.grab_state(dev, no_verify=True, no_print=True)
        util.print_tree(scr.get('tree'), scr.get('guess_descs'), scr.get('guess_score'))
        st.merge(scr)
        config.show_guess_tags = False
        return
    elif cmd == 'tree':
        scr = ob.grab_state(dev, no_img=True)
        util.print_tree(scr.get('tree'))
        st.merge(scr)
        return
    elif cmd.startswith('app '):
        app = cmd.split(' ')[1]
        load_app(app, ob, tlib, envs)
        return
    elif cmd == 'load':
        tlib = testlib.collect_pieces("../tlib/")
        envs['tlib'] = tlib
        load_app(app, ob, tlib, envs)
        return
    elif cmd == 'reload':
        value.init_params("../etc/", app)
        try:
            if app:
                os.remove("../model/screen_%s" % app)
                os.remove("../model/element_%s" % app)
            else:
                os.remove("../model/screen")
                os.remove("../model/element")
        except:
            pass
        ob.load("../model/", "../guis/", "../guis-extra/", config.extra_screens,
                config.extra_element_scrs)
        return
    elif cmd == 'tlib':
        tlib = testlib.collect_pieces("../tlib/")
        envs['tlib'] = tlib
        return
    elif cmd == 'test':
        tlib = testlib.collect_pieces("../tlib/")
        tlib.set_app(app)
        tlib.add_test(microtest.init_test(appdb.get_app(app)))
        envs['tlib'] = tlib

        config.show_guess_tags = True
        scr = ob.grab_state(dev)
        config.show_guess_tags = False
        st.merge(scr)
        begin_state = st.to_essential(tlib.essential_props())

        tests = tlib.usable_tests(st)
        tests.sort(key=lambda test: test.prio)

        for i in range(len(tests)):
            testinfo = tlib.get_testinfo(tests[i])
            print("%2d. %s: %s [%d %d]" % (i, tests[i].feature_name, tests[i].name,
                                           testinfo.succs, testinfo.fails))
        if len(tests) == 0:
            print("no test available!")
            return
        if len(tests) == 1:
            tid = 0
        else:
            tid = input("which one? ")
            try:
                tid = int(tid)
            except:
                return
        test = tests[tid]
        ret = test.attempt(dev, ob, st, tlib, environ.empty)

        util.print_tree(st.get('tree'), st.get('guess_descs'))
        end_state = st.to_essential(tlib.essential_props())
        if ret:
            print("test SUCC")
            tlib.clear_stat(test)
            tlib.mark_succ(test, begin_state, end_state)
        else:
            print("test FAIL")
            tlib.mark_fail(test, begin_state)
        save_stat()
        return
    elif cmd == 'save':
        save_stat()
        return
    elif cmd == 'stat':
        tlib.print_stat()
        return
    elif cmd == 'items':
        scr = ob.grab_state(dev, no_img=True)
        util.printitems(scr.get('items'))
        return
    elif cmd.startswith('item'):
        itemid = int(cmd.split(' ')[1])
        scr = ob.grab_state(dev, no_img=True)
        items = scr.get('items')
        if itemid in items:
            print(util.describe(items[itemid]))
        else:
            print("no such item: %d" % itemid)
        return
    elif cmd == 'debug':
        logging.basicConfig(level=logging.DEBUG)
        return
    elif cmd == 'idle':
        dev.wait_idle()
        return
    elif cmd == 'dialog':
        scr = ob.grab_state(dev)
        ret = tlib.handle_dialog(scr, dev, ob)
        if ret:
            print("dialog handled")
        else:
            print("dialog not handled")
        return
    elif cmd.startswith('find '):
        tag = cmd.split(' ', 1)[1]
        con = concept.parse(tag)
        if con is None:
            print("invalid locator")
            return
        scr = ob.grab_state(dev)
        widgets = con.locate(scr, ob, environ.Environment())
        if widgets == []:
            print("can't find")
        else:
            for widget in widgets:
                print("FOUND: %s" % widget)
                print("    content:", widget.content())
        return
    elif cmd == 'perf':
        perfmon.print_stat()
        return
    elif cmd == 'clear':
        init = tlib.find_test('meta', 'start app')
        st.reset()
        init.attempt(dev, ob, st, tlib, None)
        ob.update_state(dev, st)
        tlib.mark_succ(init, state.init_state, st)
        return
    elif cmd.startswith('set'):
        parts = cmd.split(' ', 2)
        if len(parts) == 2:
            key = parts[1]
            val = "1"
        else:
            (key, val) = parts[1:]
        st.set(key, val)
        return
    elif cmd.startswith('del'):
        parts = cmd.split(' ', 1)
        key = parts[1]
        st.remove(key)
        return
    elif cmd == 'dump':
        filename = util.choose_filename("../cap/", "page%d")
        logger.info("dumping to page %s", filename)
        dev.dump(filename)
        #sense.dump_page(dev, "../cap/")
        return
    elif cmd == 'list':
        scr = ob.grab_state(dev, no_img=True)
        tree = scr.get('tree')
        treeinfo = analyze.collect_treeinfo(tree)
        for root in sorted(treeinfo['listlike']):
            print("ROOT:", util.describe_node(tree[root]))
            for item in sorted(treeinfo['itemlike']):
                if listinfo.get_lca(tree, [root, item]) == root:
                    print("  NODE:", util.describe_node(tree[item]))
                    for field in sorted(treeinfo['dupid']):
                        if listinfo.get_lca(tree, [item, field]) == item:
                            print("    FIELD:", util.describe_node(tree[field]))
        return
    elif cmd == 'webon':
        config.GRAB_WEBVIEW = True
        return
    elif cmd == 'weboff':
        config.GRAB_WEBVIEW = False
        return
    elif cmd.startswith('ob '):
        prop = cmd.split(' ', 1)[1]
        wd = watchdog.Watchdog(100000)
        smgr = statemgr.StateMgr(tlib, None, dev, ob, wd)
        ret = smgr.observe_prop(prop, st)
        if ret:
            print("prop %s = %s" % (prop, st.get(prop, '')))
        else:
            print("observe error")
        return
    elif cmd.startswith('clean '):
        parts = cmd.split(' ', 2)
        if len(parts) == 2:
            prop = parts[1]
            val = "1"
        else:
            (prop, val) = parts[1:]
        wd = watchdog.Watchdog(100000)
        smgr = statemgr.StateMgr(tlib, None, dev, ob, wd)
        ret = smgr.cleanup_prop(prop, val, st)
        if ret:
            print("prop %s cleaned" % prop)
        else:
            print("clean error")
        return
    elif cmd.startswith('oc '):
        prop = cmd.split(' ', 1)[1]
        wd = watchdog.Watchdog(100000)
        smgr = statemgr.StateMgr(tlib, None, dev, ob, wd)
        ret = smgr.observe_and_clean(prop, st)
        if ret:
            print("prop %s is clean now" % prop)
        else:
            print("observe/clean error")
        return
    elif cmd == 'dbg':
        print(tlib)
        return
    elif cmd.startswith('skip '):
        name = cmd.split(' ', 1)[1]
        add_skip(app, name)
        print("skipping %s" % name)
        return
    elif cmd == 'skip':
        skips = load_skip(app)
        for skip in skips:
            print("now skipping %s" % skip)
        return
    elif cmd.startswith('noskip '):
        name = cmd.split(' ', 1)[1]
        del_skip(app, name)
        print("not skipping %s" % name)
        return
    elif cmd == 'src':
        if st.get('xml') is not None:
            print(st.get('xml'))
        if st.get('src') is not None:
            print(st.get('src'))
        return
    elif cmd == 'install':
        apputils.install(dev, app)
        return
    elif cmd == 'uninstall':
        apputils.uninstall(dev, app)
        return

    op = operation.parse_line(cmd)
    if op is None:
        print("unknown op")
        return

    ret = op.do(dev, ob, st, env, tlib)
    if not ret:
        print("op failed")
示例#4
0
    logformat = "%(levelname).4s %(asctime)-15s %(module)10s: %(message)s"
    if args.log:
        logging.basicConfig(level=loglevel,
                            format=logformat,
                            filename=args.log)
    else:
        logging.basicConfig(level=loglevel, format=logformat)

    if args.tag:
        tagged = set(args.tag.split(','))
        tagged.add(args.app)
    else:
        tagged = None

    if args.state:
        progress.init(args.state)
    tags.load(os.path.join(args.parampath, "tags.txt"))
    value.init_params(args.parampath, args.app)
    dev = device.create_device(serial=args.serial)
    if dev.kind == 'adb':
        appdb.collect_apps(args.apkspath)
    elif dev.kind == 'web':
        appdb.load_urls(os.path.join(args.parampath, "urls.txt"))
    miner = Miner(dev, args.guispath, args.modelpath, args.tlibpath,
                  args.batch, args.app, args.statpath, args.errpath,
                  args.skippath, args.extrapath, args.mempath, True)
    if args.explore:
        miner.explore_mode()
    else:
        miner.mine(tagged, args.rounds)
示例#5
0
    for filename in glob.glob(os.path.join(tlibpath, "*.feature")):
        try:
            tests = tlibparser.parse_feature_file(filename)
        except:
            logger.error("fail to parse %s", filename)
            raise
        for test in tests:
            tlib.add_test(test)

    return tlib


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    import value
    value.init_params("../etc/", "cui")
    import sys
    if len(sys.argv) > 1:
        tlibpath = sys.argv[1]
    else:
        tlibpath = "../tlib/"
    tlib = collect_pieces(tlibpath)
    print(tlib)
    tlib.print_stat()
    tlib.add_test(microtest.init_test("testapp"))
    tlib.assume_reached('meta', 'start app', 'main')
    tlib.assume_reached('signin', 'login', 'main')
#    for testid in tlib.tests:
#        test = tlib.tests[testid]
#        methods = tlib.synthesis_test(test, try_count=5)
#        logger.info("TEST %s:", test.name)
示例#6
0
def main():
    parser = argparse.ArgumentParser(description="Miner")
    parser.add_argument('--tlibpath',
                        help="Test library path",
                        default="../tlib/")
    parser.add_argument('--apkspath', help="Apps path", default="../apks/")
    parser.add_argument('--parampath',
                        help="Param file path",
                        default="../etc/")
    parser.add_argument('app', help="App name")
    parser.add_argument('--mempath', help="memory path", default="../memory/")
    parser.add_argument('--erase', help="erase memory of tests")
    parser.add_argument('--query', help="query screen")
    parser.add_argument('--reset', help="reset route")
    args = parser.parse_args()

    logging.basicConfig(level=logging.INFO)

    tags.load(os.path.join(args.parampath, "tags.txt"))
    value.init_params(args.parampath, args.app)
    appdb.collect_apps(args.apkspath)
    #appdb.load_urls(os.path.join(args.parampath, "urls.txt"))
    mine = miner.Miner(None, None, None, args.tlibpath, True, args.app, None,
                       None, None, None, args.mempath, False)

    if args.erase is not None:
        if os.path.exists(args.erase):
            keys = list(
                filter(lambda x: x,
                       open(args.erase).read().strip().split('\n')))
        else:
            keys = args.erase.split('#')

        if len(keys) == 0:
            print("no case to erase!")
            return

        print("%d cases to erase" % len(keys))
        for key in keys:
            feature_name, test_name = key.split(':')
            mine.erase_memory(feature_name, test_name)

        #mine.print_stat(simple=True)
        mine.save_memory()

        print("%d cases erased" % len(keys))
        return

    if args.reset is not None:
        route_no = int(args.reset)
        mine.slib.reset_route(route_no)
        mine.save_memory()
        return

    if args.query is not None:
        attrs = {}
        if ',' in args.query:
            screen = args.query.split(',')[0]
            for entry in args.query.split(',')[1:]:
                if '=' in entry:
                    key, val = entry.split('=', 1)
                    attrs[key] = val
                else:
                    if entry[0] == '-':
                        attrs[entry[1:]] = 'false'
                    else:
                        attrs[entry] = 'true'
        else:
            screen = args.query
        if screen != '.':
            attrs['screen'] = screen
        mine.slib.query_screen(attrs)
        return

    mine.print_stat(simple=True)