def __init__(self, project_rootpath):
     self.log = platform_logger("BuildTestcases")
     self.project_rootpath = project_rootpath
     self.is_doublefwk = UserConfigManager().get_user_config_flag(
         "common", "doublefwk")
     self.is_build_example = UserConfigManager().get_user_config_flag(
         "build", "example")
Ejemplo n.º 2
0
def main_process():
    main_log = platform_logger("main")
    main_log.info(
        "************* Developer Test Framework Starting **************")
    console = Console()
    console.console(sys.argv)
    main_log.info(
        "************* Developer Test Framework Finished **************")
Ejemplo n.º 3
0
 def __init__(self, filepath=""):
     if filepath == "":
         self.filepath = os.path.abspath(
             os.path.join(CONFIG_PATH,
                          ConfigFileConst.FRAMECONFIG_FILEPATH))
     else:
         self.filepath = filepath
     self.framework_log = platform_logger("FrameworkConfigManager")
Ejemplo n.º 4
0
 def __init__(self, filepath=""):
     if filepath == "":
         self.filepath = os.path.abspath(
             os.path.join(CONFIG_PATH,
                          ConfigFileConst.FILTERCONFIG_FILEPATH))
     else:
         self.filepath = filepath
     self.filter_log = platform_logger("FilterConfigManager")
Ejemplo n.º 5
0
 def __init__(self, filepath=""):
     if filepath == "":
         self.filepath = os.path.abspath(
             os.path.join(CONFIG_PATH,
                          ConfigFileConst.RESOURCECONFIG_FILEPATH))
     else:
         self.filepath = filepath
     self.resource_log = platform_logger("ResourceConfigManager")
Ejemplo n.º 6
0
 def __init__(self, filepath=""):
     if filepath == "":
         self.filepath = os.path.abspath(
             os.path.join(CONFIG_PATH,
                          ConfigFileConst.BUILDCONFIG_FILEPATH))
     else:
         self.filepath = filepath
     self.build_config_log = platform_logger("BuildConfigManager")
Ejemplo n.º 7
0
 def __init__(self, config_file=""):
     if config_file == "":
         self.filepath = os.path.abspath(
             os.path.join(CONFIG_PATH, ConfigFileConst.USERCONFIG_FILEPATH))
     else:
         if os.path.isabs(config_file):
             self.filepath = config_file
         else:
             self.filepath = os.path.abspath(
                 os.path.join(CONFIG_PATH, config_file))
     self.user_config_log = platform_logger("UserConfigManager")
class BuildLiteManager(object):
    """
    build lite system version or test cases
    build param:
    device type:for examples, watch or camera
    board platform:for examples, HI3518ev300 or HI3516DV300
    kernel type:for examples, liteos_m, liteos_a, linux
    """
    log = platform_logger("BuildLiteManager")

    def __init__(self):
        self.product_type = ""
        self.platform = ""
        self.kernel_type = ""

    def _parse_build_param(self, param_option):
        if param_option is None or "|" not in param_option.productform:
            return False
        if "|" in param_option.productform:
            self.product_type, self.platform, self.kernel_type = \
                param_option.productform.split("|")
        return True

    def build_version_and_cases(self):
        build_command = "python build/lite/ compile %s --platform " \
                        "%s_%s --test c  -b release" % (self.product_type,
                                                        self.platform,
                                                        self.kernel_type)
        self.log.info("build param:%s" % build_command)
        return subprocess.call(build_command) == 0

    def exec_build_test(self, param_option):
        """
        build os lite version and test cases
        :param param_option: build param
        :return:build success or failed
        """
        self._parse_build_param(param_option)
        if platform.system() == "Linux":
            return self.build_version_and_cases()
        self.log.info("windows environment, only use .bin test cases")
        return True
Ejemplo n.º 9
0
class ResourceManager(object):
    resource_log = platform_logger("ResourceManager")

    def __init__(self):
        self.resource_path = ""

    def _find_node_by_target(self, file_path, targe_tname):
        node = None
        try:
            if os.path.exists(file_path):
                tree = ElementTree.parse(file_path)
                root = tree.getroot()
                targets = root.getiterator("target")
                for target in targets:
                    curr_dic = target.attrib
                    if curr_dic.get("name") == targe_tname:
                        node = target
                        break
        except ElementTree.ParseError as node_exception:
            self.resource_log.error("resource_test.xml parsing failed." +
                                    node_exception.args)
        return node

    ##########################################################################
    ##########################################################################

    @classmethod
    def _get_file_name_extension(cls, filepath):
        _, fullname = os.path.split(filepath)
        filename, ext = os.path.splitext(fullname)
        cls.resource_log.debug("file path:{}".format(filepath))
        return filename, ext

    def process_resource_file(self, resource_dir, preparer_list, device):
        for item in preparer_list:
            if "name" not in item.keys():
                continue

            if item["name"] == "push":
                push_value = item["value"]

                find_key = "->"
                pos = push_value.find(find_key)
                src = os.path.join(resource_dir, push_value[0:pos].strip())
                dst = push_value[pos + len(find_key):len(push_value)].strip()

                self.resource_log.info("create_dir: dst = %s" % (dst))
                device.create_dir(dst)
                self.resource_log.info("push_file: src = %s, dst = %s" %
                                       (src, dst))
                device.push_file(src, dst)
            elif item["name"] == "pull":
                push_value = item["value"]
                find_key = "->"
                pos = push_value.find(find_key)
                src = os.path.join(resource_dir, push_value[0:pos].strip())
                dst = push_value[pos + len(find_key):len(push_value)].strip()
                self.resource_log.info("pull_file: src = %s, dst = %s" %
                                       (src, dst))
                device.pull_file(src, dst)
            elif item["name"] == "shell":
                command = item["value"].strip()
                print("shell = " + command)
                device.execute_shell_command(command)
            else:
                command = item["name"] + " " + item["value"]
                command = command.strip()
                self.resource_log.info("others = " + command)
                device.execute_command(command)

    @classmethod
    def _get_environment_data(cls, environment_list):
        env_data_dic = {}
        device_name = ""
        option_dic = {}

        for item in environment_list:
            if "type" in item.keys():
                if device_name != "":
                    temp_dic = option_dic.copy()
                    env_data_dic[device_name] = temp_dic
                    device_name = ""
                    option_dic.clear()
                device_name = item["type"]

            if "name" in item.keys():
                name = item["name"]
                value = item["value"]
                option_dic[name] = value

        if device_name != "":
            temp_dic = option_dic.copy()
            env_data_dic[device_name] = temp_dic
            device_name = ""
            option_dic.clear()
        cls.resource_log.debug("get environment data finish")
        return env_data_dic

    def _get_resource_xml_file_path(self, test_suit_file_path):
        current_dir = os.path.dirname(test_suit_file_path)
        while True:
            if current_dir.endswith(os.sep + "tests"):
                current_dir = ""
                break
            if current_dir == "/" or current_dir.endswith(":\\"):
                current_dir = ""
                break
            if os.path.exists(os.path.join(current_dir, "resource")):
                break
            current_dir = os.path.dirname(current_dir)

        if current_dir != "":
            xml_filepath = os.path.join(current_dir, "resource",
                                        "resource_test.xml")
        else:
            xml_filepath = ""
        self.resource_log.info("xml_filepath = %s" % xml_filepath)
        return xml_filepath

    @classmethod
    def get_nodeattrib_data(cls, data_dic):
        curr_timeout = DEFAULT_TIMEOUT
        if "nodeattrib" in data_dic.keys():
            print("++++++++++++++nodeattrib+++++++++++++++")
            nodeattrib_list = data_dic["nodeattrib"]
            if len(nodeattrib_list) != 0:
                node_item_dic = nodeattrib_list[0]
                if "timeout" in node_item_dic:
                    curr_timeout = node_item_dic["timeout"]
        return curr_timeout

    def get_environment_data(self, data_dic):
        env_data_dic = {}
        if "environment" in data_dic.keys():
            print("++++++++++++++environment+++++++++++++++")
            environment_list = data_dic["environment"]
            env_data_dic = self._get_environment_data(environment_list)
        return env_data_dic

    def process_preparer_data(self, data_dic, resource_dir, device):
        if "preparer" in data_dic.keys():
            print("++++++++++++++preparer+++++++++++++++")
            preparer_list = data_dic["preparer"]
            self.process_resource_file(resource_dir, preparer_list, device)
        return

    def process_cleaner_data(self, data_dic, resource_dir, device):
        if "cleaner" in data_dic.keys():
            print("++++++++++++++cleaner+++++++++++++++")
            cleaner_list = data_dic["cleaner"]
            self.process_resource_file(resource_dir, cleaner_list, device)
        return

    def get_resource_xml_file_version(self, xml_filepath):
        xml_file_version = ""
        try:
            if os.path.exists(xml_filepath):
                tree = ElementTree.parse(xml_filepath)
                root = tree.getroot()
                curr_dic = root.attrib
                xml_file_version = curr_dic.get("ver", "")
        except ElementTree.ParseError as xml_exception:
            self.resource_log.error("Error: resource_test.xml parse fail." +
                                    xml_exception.args)
        return xml_file_version
Ejemplo n.º 10
0
class Run(object):
    run_log = platform_logger("Run")

    def process_command_run(self, command, options):
        para = Parameter()
        test_type_list = para.get_testtype_list(options.testtype)
        if len(test_type_list) == 0:
            self.run_log.error("The testtype parameter is incorrect.")
            return
        options.testtype = test_type_list

        self.run_log.info("")
        self.run_log.info("------------------------------------")
        self.run_log.info("Input parameter:")
        self.run_log.info("productform   = %s" % options.productform)
        self.run_log.info("testtype      = %s" % options.testtype)
        self.run_log.info("subsystem     = %s" % options.subsystem)
        self.run_log.info("testmodule    = %s" % options.testmodule)
        self.run_log.info("testsuit      = %s" % options.testsuit)
        self.run_log.info("testcase      = %s" % options.testcase)
        self.run_log.info("testlevel     = %s" % options.testlevel)
        self.run_log.info("------------------------------------")
        self.run_log.info("")

        if not para.check_run_parameter(options):
            self.run_log.error("Input parameter is incorrect.")
            return

        if not self._build_test_cases(options):
            self.run_log.error("Build test cases failed.")
            return

        test_case_path = self._get_tests_out_path(
            options.productform, options.build_variant)
        if not os.path.exists(test_case_path):
            self.run_log.error("%s is not exist." % test_case_path)
            return

        test_dictionary = TestCaseManager().get_test_files(test_case_path,
                                                           options)
        if not self._check_test_dictionary(test_dictionary):
            self.run_log.error("The test file list is empty.")
            return

        setattr(options, "testdriver", "LiteUnitTest")
        options.testdict = test_dictionary
        options.target_outpath = self.get_target_out_path(
            options.productform, options.build_variant)

        scheduler = get_plugin(plugin_type=Plugin.SCHEDULER,
                               plugin_id=SchedulerType.SCHEDULER)[0]
        if scheduler is None:
            self.run_log.error("Can not find the scheduler plugin.")
        else:
            scheduler.exec_command(command, options)

        return

    ##############################################################
    ##############################################################

    @classmethod
    def get_target_out_path(cls, product_form, build_variant):
        target_out_path = UserConfigManager().get_user_config(
            "test_cases").get("dir", "")
        if target_out_path == "":
            target_out_path = os.path.join(
                sys.source_code_root_path,
                "out",
                build_variant,
                "packages",
                product_form)
        target_out_path = os.path.abspath(target_out_path)
        return target_out_path

    def _build_test_cases(self, options):
        if options.coverage == "coverage":
            self.run_log.info("Coverage testing, no need to compile testcases")
            return True

        project_root_path = sys.source_code_root_path
        if "testcase" in options.build and project_root_path != "":
            from core.build.build_manager import BuildManager
            build_manager = BuildManager()
            return build_manager.build_testcases(project_root_path, options)
        else:
            return True

    @classmethod
    def _check_test_dictionary(cls, test_dictionary):
        is_valid_status = False
        key_list = sorted(test_dictionary.keys())
        for key in key_list:
            file_list = test_dictionary[key]
            if len(file_list) > 0:
                is_valid_status = True
                break
        return is_valid_status

    @classmethod
    def _get_tests_out_path(cls, product_form, build_variant):
        tests_out_path = UserConfigManager().get_user_config(
            "test_cases").get("dir")
        if tests_out_path == "":
            tests_out_path = os.path.abspath(os.path.join(
                sys.source_code_root_path,
                "out",
                build_variant,
                "packages",
                product_form,
                "tests"))
        return tests_out_path
Ejemplo n.º 11
0
class Console(object):
    """
    Class representing an console for executing test.
    Main xDevice console providing user with the interface to interact
    """
    __instance = None
    wizard_dic = {}
    log = platform_logger("Console")

    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = super(Console, cls).__new__(cls, *args, **kwargs)
        return cls.__instance

    def __init__(self):
        pass

    def handler_ctrl_c(self, signalnum, frame):
        pass

    def handler_ctrl_z(self, signalnum, frame):
        pass

    def console(self, args):
        """
        Main xDevice console providing user with the interface to interact
        """
        if args is None or len(args) < 2:
            self.wizard_dic = show_wizard_mode()
            print(self.wizard_dic)
            EnvironmentManager()
            if self._build_version(self.wizard_dic["productform"]):
                self._console()
            else:
                self.log.error("Build version failed, exit test framework.")
        else:
            EnvironmentManager()
            self.command_parser(" ".join(args[1:]))

    def _console(self):
        if platform.system() != 'Windows':
            signal.signal(signal.SIGTSTP, self.handler_ctrl_z)  # ctrl+x linux
        signal.signal(signal.SIGINT, self.handler_ctrl_c)  # ctrl+c

        while True:
            try:
                usr_input = input(">>> ")
                if usr_input == "":
                    continue
                self.command_parser(usr_input)
            except SystemExit:
                self.log.info("Program exit normally!")
                return
            except (IOError, EOFError, KeyboardInterrupt) as error:
                self.log.exception("Input Error: %s" % error)

    @classmethod
    def argument_parser(cls, para_list):
        """
        argument parser
        """
        options = None
        unparsed = []
        valid_param = True
        parser = None

        try:
            parser = argparse.ArgumentParser(description="Specify test para.")
            parser.add_argument("action",
                                type=str.lower,
                                help="Specify action")

            # Developer test general test parameters
            parser.add_argument("-p",
                                "--productform",
                                action="store",
                                type=str,
                                dest="productform",
                                default="phone",
                                help="Specified product form")
            parser.add_argument("-t",
                                "--testtype",
                                nargs='*',
                                dest="testtype",
                                default=["ut"],
                                help="Specify test type(ut,mst,st,perf,all)")
            parser.add_argument("-ss",
                                "--subsystem",
                                action="store",
                                type=str,
                                dest="subsystem",
                                default="",
                                help="Specify test subsystem")
            parser.add_argument("-tm",
                                "--testmodule",
                                action="store",
                                type=str,
                                dest="testmodule",
                                default="",
                                help="Specified test module")
            parser.add_argument("-ts",
                                "--testsuit",
                                action="store",
                                type=str,
                                dest="testsuit",
                                default="",
                                help="Specify test suit")
            parser.add_argument("-tc",
                                "--testcase",
                                action="store",
                                type=str,
                                dest="testcase",
                                default="",
                                help="Specify test case")
            parser.add_argument("-tl",
                                "--testlevel",
                                action="store",
                                type=str,
                                dest="testlevel",
                                default="",
                                help="Specify test level")

            # Developer test extended test parameters
            parser.add_argument("-os",
                                "--target_os_name",
                                action="store",
                                type=str,
                                dest="target_os_name",
                                default="OHOS",
                                help="Specify target os name")
            parser.add_argument("-bv",
                                "--build_variant",
                                action="store",
                                type=str,
                                dest="build_variant",
                                default="release",
                                help="Specify build variant(release,debug)")
            parser.add_argument("-b",
                                "--build",
                                nargs='*',
                                dest="build",
                                default=["testcase"],
                                help="Specify build values(version,testcase)")
            parser.add_argument("-cov",
                                "--coverage",
                                action="store",
                                type=str,
                                dest="coverage",
                                default="",
                                help="Specify coverage")
            parser.add_argument("-tf",
                                "--testfile",
                                action="store",
                                type=str,
                                dest="testfile",
                                default="",
                                help="Specify test suites list file")
            parser.add_argument("-res",
                                "--resource",
                                action="store",
                                type=str,
                                dest="resource",
                                default="",
                                help="Specify test resource")

            # Developer test other test parameters
            parser.add_argument("-sn",
                                "--device_sn",
                                action="store",
                                type=str,
                                dest="device_sn",
                                default="",
                                help="Specify device serial number")
            parser.add_argument("-c",
                                "--config",
                                action="store",
                                type=str,
                                dest="config",
                                default="",
                                help="Specify test config file")
            parser.add_argument("-rp",
                                "--reportpath",
                                action="store",
                                type=str,
                                dest="reportpath",
                                default="",
                                help="Specify test report path")
            parser.add_argument("-e",
                                "--exectype",
                                action="store",
                                type=str,
                                dest="exectype",
                                default="device",
                                help="Specify test execute type")
            parser.add_argument("-td",
                                "--testdriver",
                                action="store",
                                type=str,
                                dest="test_driver",
                                default="",
                                help="Specify test driver id")
            (options, unparsed) = parser.parse_known_args(para_list)
        except SystemExit:
            valid_param = False
            parser.print_help()
            cls.log.warning("Parameter parsing systemexit exception.")

        return options, unparsed, valid_param, parser

    def command_parser(self, args):
        try:
            self.log.info("Input command: " + args)
            para_list = args.split()
            (options, _, valid_param, parser) = \
                self.argument_parser(para_list)
            if options is None or not valid_param:
                self.log.warning("options is None.")
                return

            command = options.action
            if command == "":
                self.log.warning("action is empty.")
                return

            if command.startswith(ToolCommandType.TOOLCMD_KEY_HELP):
                self._process_command_help(parser, para_list)
            elif command.startswith(ToolCommandType.TOOLCMD_KEY_SHOW):
                self._process_command_show(para_list)
            elif command.startswith(ToolCommandType.TOOLCMD_KEY_RUN):
                if "productform" in self.wizard_dic:
                    options.productform = self.wizard_dic["productform"]
                self._process_command_run(command, options)
            elif command.startswith(ToolCommandType.TOOLCMD_KEY_QUIT):
                self._process_command_quit(command)
            elif command.startswith(ToolCommandType.TOOLCMD_KEY_LIST):
                self._process_command_device(command)
            else:
                self.log.error("command error: %s" % command)
        except (AttributeError, IOError, IndexError, ImportError, NameError,
                RuntimeError, SystemError, TypeError, ValueError,
                UnicodeError) as exception:
            self.log.exception(exception, exc_info=False)

    @classmethod
    def _process_command_help(cls, parser, para_list):
        if para_list[0] == ToolCommandType.TOOLCMD_KEY_HELP:
            parser.print_help()
        else:
            cls.log.error("Wrong help command.")
        return

    @classmethod
    def _process_command_show(cls, para_list):
        if para_list[0] == ToolCommandType.TOOLCMD_KEY_SHOW:
            display_show_info(para_list)
        else:
            cls.log.error("Wrong show command.")
        return

    @classmethod
    def _process_command_run(cls, command, options):
        if command == ToolCommandType.TOOLCMD_KEY_RUN:
            Run().process_command_run(command, options)
        else:
            cls.log.error("Wrong run command.")
        return

    @classmethod
    def _process_command_device(cls, command):
        if command == ToolCommandType.TOOLCMD_KEY_LIST:
            env_manager = EnvironmentManager()
            env_manager.list_devices()
        else:
            cls.log.error("Wrong list command.")
        return

    @classmethod
    def _process_command_quit(cls, command):
        if command == ToolCommandType.TOOLCMD_KEY_QUIT:
            env_manager = EnvironmentManager()
            env_manager.env_stop()
            sys.exit(0)
        else:
            cls.log.error("Wrong exit command.")
        return

    @classmethod
    def _build_version(cls, product_form):
        build_result = True
        project_root_path = sys.source_code_root_path
        if project_root_path != "":
            from _core.build.build_manager import BuildManager
            build_manager = BuildManager()
            is_build_version = UserConfigManager().get_user_config_flag(
                "build", "version")
            if is_build_version:
                build_result = build_manager.build_version(
                    project_root_path, product_form)
            else:
                build_result = build_manager.build_gn_file(
                    project_root_path, product_form)
        return build_result
Ejemplo n.º 12
0
class LiteUnitTest(IDriver):
    """
    lite gtest test driver for L1
    """
    config = None
    log = platform_logger("LiteUnitTest")
    nfs_dir = ""
    lite_device = None
    result = None

    @classmethod
    def __check_failed__(cls, msg):
        cls.log.error("check failed {}".format(msg))
        return None

    @classmethod
    def __check_environment__(cls, device_options):
        pass

    @classmethod
    def __check_config__(cls, config):
        """
        1. check serial protocol
        2. login device
        3. NFS is available
        :param config:包含serial_protocol,serial_device,nfs_operation
        :return:
        """
        cls.log.error("Lite driver check config:{}".format(config))

    @classmethod
    def __execute__(cls, request):
        """

        1. select test case by subsystem, module, suite
        2. open test dir
        3、execute single test case, eg. ./test_demo
        :param request: contains test condition, sub_system
            module_name,test_suit,
        test_case,test_level,test_case_dir
        :return:
        """
        cls.log.debug("Test suite FilePath: %s" %
                      request.root.source.source_file)
        cls.lite_device = request.config.environment.devices[0]
        cls.lite_device.connect()
        if not cls._before_execute_test():
            cls.log.error("open test dir failed")
            return
        cls.log.debug("open test dir success")
        if cls._execute_test(request) == "":
            cls.log.error("execute test command failed")
            return
        cls.log.info("execute test command success")
        if not cls._after_execute_test(request):
            cls.log.error("after execute test failed")
            return
        cls.log.info("lite device execute request success")

    @classmethod
    def _before_execute_test(cls):
        """
        need copy test case to nfs dir
        :param request: nfs dir, test case path
        :return:
        """
        cls.nfs_dir = \
            UserConfigManager().get_user_config("NFS").get("host_dir")
        if cls.nfs_dir == "":
            cls.log.error("no configure for nfs directory")
            return False
        pre_result, status, _ = \
            cls.lite_device.execute_command_with_timeout("cd /{}".format(
                UserConfigManager().get_user_config("NFS").get("board_dir")),
            case_type=DeviceTestType.lite_cpp_test)
        if not status:
            cls.log.error("pre execute command failed")
            return False
        cls.log.info("pre execute command success")
        return True

    @classmethod
    def _execute_test(cls, request):
        test_cases = request.config.testdict['BIN']
        cxx_test_cases = request.config.testdict['CXX']
        test_cases += cxx_test_cases
        for test_case in test_cases:
            case_name = os.path.basename(test_case)
            shutil.copyfile(test_case, os.path.join(cls.nfs_dir, case_name))
            case_result, status, _ = \
                cls.lite_device.execute_command_with_timeout(
                "./" + case_name, case_type=DeviceTestType.lite_cpp_test)
            if status:
                cls.log.info("test case result:\n %s" % case_result)
                continue
            cls.log.error("failed case: %s" % test_case)

    @classmethod
    def _after_execute_test(cls, request):
        """
        copy test result to result dir
        :param request:
        :return:
        """
        if request.config is None:
            cls.log.error("test config is null")
            return False
        report_path = request.config.report_path
        test_result = os.path.join(report_path, "result")
        test_cases = request.config.testdict['BIN']
        for test_case in test_cases:
            case_name = os.path.basename(test_case)
            result_name = case_name + ".xml"
            result_file = os.path.join(cls.nfs_dir, result_name)
            if not os.path.exists(result_file):
                cls.log.error("file %s not exist." % result_file)
                continue
            file_name = os.path.basename(result_file)
            if not os.path.exists(test_result):
                os.mkdir(test_result)
            final_result = os.path.join(test_result, file_name)
            shutil.copyfile(result_file, final_result)
        cls.log.info("after execute test")
        cls.lite_device.close()
        return True

    @classmethod
    def show_help_info(cls):
        """
        show help info.
        """
        cls.log.info("this is test driver for cpp test")
        return None

    @classmethod
    def show_driver_info(cls):
        """
        show driver info.
        """
        cls.log.info("this is test driver for cpp test")
        return None

    @classmethod
    def __result__(cls):
        pass
Ejemplo n.º 13
0
 def __init__(self, project_rootpath):
     self.log = platform_logger("FilterTargets")
     self.project_rootpath = project_rootpath
Ejemplo n.º 14
0
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import sys

from xdevice import Console
from xdevice import platform_logger

LOG = platform_logger("Main")


def main_process(command=None):
    LOG.info("*************** xDevice Test Framework Starting ***************")
    if command:
        args = str(command).split(" ")
        args.insert(0, "xDevice")
    else:
        args = sys.argv
    console = Console()
    console.console(args)
    return


if __name__ == "__main__":
Ejemplo n.º 15
0
class TestCaseManager(object):
    case_log = platform_logger("TestCaseManager")

    def get_test_files(self, test_case_path, options):
        self.case_log.info("test case path: " + test_case_path)
        self.case_log.info("test type list: " + str(options.testtype))
        suit_file_dictionary = copy.deepcopy(TESTFILE_TYPE_DATA_DIC)
        if os.path.exists(test_case_path):
            if len(options.testtype) != 0:
                test_type_list = options.testtype
                suit_file_dictionary = self.get_test_file_data(
                    test_case_path, test_type_list, options)
        else:
            self.case_log.error("%s is not exist." % test_case_path)
        return suit_file_dictionary

    def get_test_file_data(self, test_case_path, test_type_list, options):
        suit_file_dictionary = copy.deepcopy(TESTFILE_TYPE_DATA_DIC)
        for test_type in test_type_list:
            temp_dictionary = \
                self.get_test_file_data_by_test_type(test_case_path,
                                                     test_type,
                                                     options)
            for key, value in suit_file_dictionary.items():
                suit_file_dictionary[key] = value + temp_dictionary[key]
        return suit_file_dictionary

    def get_test_file_data_by_test_type(self, test_case_path, test_type,
                                        options):
        suit_file_dictionary = copy.deepcopy(TESTFILE_TYPE_DATA_DIC)
        test_case_out_path = os.path.join(test_case_path, test_type)
        if os.path.exists(test_case_out_path):
            self.case_log.info("The test case directory: %s" %
                               test_case_out_path)
            return self.get_all_test_file(test_case_out_path, options)
        else:
            self.case_log.error("The test case directory does not exist. %s" %
                                test_case_out_path)
        return suit_file_dictionary

    def get_all_test_file(self, test_case_out_path, options):
        suite_file_dictionary = copy.deepcopy(TESTFILE_TYPE_DATA_DIC)
        filter_list_subsystem = FilterConfigManager().get_filtering_list(
            "subsystem_name", options.productform)
        filter_list_test_file = FilterConfigManager().get_filtering_list(
            "testfile_name", options.productform)

        for subsystem_name in os.listdir(test_case_out_path):
            subsystem_case_dir = os.path.join(test_case_out_path,
                                              subsystem_name)
            if not os.path.isdir(subsystem_case_dir):
                continue

            if subsystem_name in filter_list_subsystem:
                continue

            suit_file_list = get_file_list_by_postfix(subsystem_case_dir)
            for suite_file in suit_file_list:
                if -1 != suite_file.replace(
                        test_case_out_path,
                        "").find(os.sep + "resource" + os.sep):
                    continue

                file_name = os.path.basename(suite_file)
                if file_name in filter_list_test_file:
                    continue

                _, suffix_name = os.path.splitext(file_name)
                if suffix_name in FILTER_SUFFIX_NAME_LIST:
                    continue

                if not self._get_valid_suite_file(
                        test_case_out_path, suite_file, options.subsystem,
                        options.testmodule, options.testsuit):
                    continue

                if suffix_name == ".dex":
                    suite_file_dictionary["DEX"].append(suite_file)
                elif suffix_name == ".hap":
                    suite_file_dictionary["HAP"].append(suite_file)
                elif suffix_name == ".py":
                    if not self._check_python_test_file(suite_file):
                        continue
                    suite_file_dictionary["PYT"].append(suite_file)
                elif suffix_name == "":
                    suite_file_dictionary["CXX"].append(suite_file)
                elif suffix_name == ".bin":
                    suite_file_dictionary["BIN"].append(suite_file)

        return suite_file_dictionary

    @classmethod
    def _get_valid_suite_file(cls, test_case_out_path, suit_file,
                              test_subsystem, test_module, test_suit):
        is_valid_status = False
        if suit_file.startswith(test_case_out_path):
            if test_suit == "":
                suite_file_sub_path = suit_file.replace(
                    test_case_out_path, "").strip(os.sep)
                if test_subsystem != "":
                    if test_module != "":
                        if suite_file_sub_path.startswith(test_subsystem +
                                                          os.sep +
                                                          test_module +
                                                          os.sep):
                            is_valid_status = True
                    else:
                        if suite_file_sub_path.startswith(test_subsystem +
                                                          os.sep):
                            is_valid_status = True
                else:
                    if test_module != "":
                        dir_item_list = suite_file_sub_path.split(os.sep)
                        if len(dir_item_list) > 2 \
                                and test_module == dir_item_list[1]:
                            is_valid_status = True
                    else:
                        is_valid_status = True
            else:
                short_name, _ = os.path.splitext(os.path.basename(suit_file))
                if short_name == test_suit:
                    is_valid_status = True
        return is_valid_status

    @classmethod
    def _check_python_test_file(cls, suite_file):
        if suite_file.endswith(".py"):
            filename = os.path.basename(suite_file)
            if filename.startswith("test_"):
                return True
        return False
 def __init__(self):
     self.log = platform_logger("BuildManager")