def runProcFileTest(self, test_object):
        """Reads from the file and checks that it parses and the content is valid.

        Args:
            test_object: inherits KernelProcFileTestBase, contains the test functions
        """
        asserts.skipIf(test_object in TEST_OBJECTS_64 and not self.dut.is64Bit,
                       "Skip test for 64-bit kernel.")
        filepath = test_object.get_path()
        asserts.skipIf(
            not target_file_utils.Exists(filepath, self.shell)
            and test_object.file_optional(),
            "%s does not exist and is optional." % filepath)
        target_file_utils.assertPermissionsAndExistence(
            self.shell, filepath, test_object.get_permission_checker())

        logging.info("Testing format of %s", filepath)

        asserts.assertTrue(test_object.prepare_test(self.shell, self.dut),
                           "Setup failed!")

        if not test_object.test_format():
            return

        file_content = self.ReadFileContent(filepath)
        try:
            parse_result = test_object.parse_contents(file_content)
        except (SyntaxError, ValueError, IndexError) as e:
            asserts.fail("Failed to parse! " + str(e))
        asserts.assertTrue(test_object.result_correct(parse_result),
                           "Results not valid!")
    def runSelinuxFileTest(self, test_object):
        """Reads the file and checks that its content and permissions are valid.

        Args:
            test_object: inherits KernelSelinuxFileTestBase, contains the test functions
        """
        logging.info("Testing existence of %s" % (test_object.get_path()))

        asserts.assertTrue(
            target_file_utils.Exists(test_object.get_path(), self.shell),
            "%s: File does not exist." % test_object.get_path())

        logging.info("Testing permissions of %s" % (test_object.get_path()))
        try:
            permissions = target_file_utils.GetPermission(
                test_object.get_path(), self.shell)
            asserts.assertTrue(
                test_object.get_permission_checker()(permissions),
                "%s: File has invalid permissions (%s)" %
                (test_object.get_path(), permissions))
        except (ValueError, IOError) as e:
            asserts.fail("Failed to assert permissions: %s" % str(e))

        logging.info("Testing format of %s" % (test_object.get_path()))
        file_content = target_file_utils.ReadFileContent(
            test_object.get_path(), self.shell)
        asserts.assertTrue(test_object.result_correct(file_content),
                           "Results not valid!")
    def _ListFiles(self, dir_path):
        """Lists all files in a directory except subdirectories.

        Args:
            dir_path: A string, path to the directory on device.

        Returns:
            A list of strings, the file paths in the directory.
        """
        if not target_file_utils.Exists(dir_path, self._shell):
            logging.info("%s not found", dir_path)
            return []
        return target_file_utils.FindFiles(self._shell, dir_path, "*",
                                           "! -type d")
예제 #4
0
    def testHwbinderExistence(self):
        """Checks that hwbinder node exists.
        """
        logging.info("Testing existence of %s", HWBINDER_PATH)
        asserts.assertTrue(target_file_utils.Exists(HWBINDER_PATH, self.shell),
                           "%s: File does not exist." % HWBINDER_PATH)

        try:
            permissions = target_file_utils.GetPermission(
                HWBINDER_PATH, self.shell)
            asserts.assertTrue(
                target_file_utils.IsReadWrite(permissions),
                "%s: File has invalid permissions (%s)" %
                (HWBINDER_PATH, permissions))
        except (ValueError, IOError) as e:
            asserts.fail("Failed to assert permissions: %s" % str(e))
예제 #5
0
    def testOpenNonexistingFile(self):
        """Test opening a nonexisting file with read-only flag should fail.

        This test case first checks if the file exists. If it exists, it skips
        this test case. If it doesn't, it will try to open the non-existing file
        with 'r' flag.
        """
        if not target_file_utils.Exists(self.TEST_DIR_PATH + "abc.txt",
                                        self.dut.shell):
            logging.info("Test opening a non-existing file with 'r' flag.")
            failed_reader = self.dut.resource.InitHidlHandleForSingleFile(
                self.TEST_DIR_PATH + "abc.txt",
                "r",
                client=self.dut.hal.GetTcpClient("dumpstate"))
            asserts.assertTrue(
                failed_reader is None,
                "Open a non-existing file with 'r' flag should fail.")
예제 #6
0
def CanRunHidlHalTest(test_instance,
                      dut,
                      shell=None,
                      run_as_compliance_test=False):
    """Checks HAL precondition of a test instance.

    Args:
        test_instance: the test instance which inherits BaseTestClass.
        dut: the AndroidDevice under test.
        shell: the ShellMirrorObject to execute command on the device.
               If not specified, the function creates one from dut.
        run_as_compliance_test: boolean, whether it is a compliance test.

    Returns:
        True if the precondition is satisfied; False otherwise.
    """
    if shell is None:
        dut.shell.InvokeTerminal("check_hal_preconditions")
        shell = dut.shell.check_hal_preconditions

    opt_params = [
        keys.ConfigKeys.IKEY_ABI_BITNESS,
        keys.ConfigKeys.IKEY_PRECONDITION_HWBINDER_SERVICE,
        keys.ConfigKeys.IKEY_PRECONDITION_FEATURE,
        keys.ConfigKeys.IKEY_PRECONDITION_FILE_PATH_PREFIX,
        keys.ConfigKeys.IKEY_PRECONDITION_LSHAL,
    ]
    test_instance.getUserParams(opt_param_names=opt_params)

    bitness = str(getattr(test_instance, keys.ConfigKeys.IKEY_ABI_BITNESS, ""))

    hwbinder_service_name = str(
        getattr(test_instance,
                keys.ConfigKeys.IKEY_PRECONDITION_HWBINDER_SERVICE, ""))
    if hwbinder_service_name:
        if not hwbinder_service_name.startswith("android.hardware."):
            logging.error("The given hwbinder service name %s is invalid.",
                          hwbinder_service_name)
        else:
            cmd_results = shell.Execute("ps -A")
            hwbinder_service_name += "@"
            if (any(cmd_results[const.EXIT_CODE]) or
                    hwbinder_service_name not in cmd_results[const.STDOUT][0]):
                logging.warn("The required hwbinder service %s not found.",
                             hwbinder_service_name)
                return False

    feature = str(
        getattr(test_instance, keys.ConfigKeys.IKEY_PRECONDITION_FEATURE, ""))
    if feature:
        if not feature.startswith("android.hardware."):
            logging.error("The given feature name %s is invalid for HIDL HAL.",
                          feature)
        else:
            cmd_results = shell.Execute("pm list features")
            if (any(cmd_results[const.EXIT_CODE]) or
                    feature not in cmd_results[const.STDOUT][0]):
                logging.warn("The required feature %s not found.", feature)
                return False

    file_path_prefix = getattr(test_instance, "file_path_prefix", "")
    if file_path_prefix and bitness:
        logging.info("FILE_PATH_PREFIX: %s", file_path_prefix)
        logging.info("Test bitness: %s", bitness)
        tag = "_" + bitness + "bit"
        if tag in file_path_prefix:
            for path_prefix in file_path_prefix[tag]:
                if not target_file_utils.Exists(path_prefix, shell):
                    msg = (
                        "The required file (prefix: {}) for {}-bit testcase "
                        "not found.").format(path_prefix, bitness)
                    logging.warn(msg)
                    return False

    hal = str(
        getattr(test_instance, keys.ConfigKeys.IKEY_PRECONDITION_LSHAL, ""))
    if hal:
        testable, _ = hal_service_name_utils.GetHalServiceName(
            shell, hal, bitness, run_as_compliance_test)
        return testable

    logging.info("Precondition check pass.")
    return True
예제 #7
0
    def setUpClass(self):
        """Necessary setup for the test environment.

        We need to start dumpstate HAL service manually because it is a lazy
        HAL service, then load it in our target-side driver.
        Create a tmp directory in /data to create test files in it if the tmp
        directory doesn't exist.
        We also need to set SELinux permission to permissive because
        HAL server and host side are communicating via a file.
        We will recover SELinux permission during tearDown of this class.
        """
        self.dut = self.android_devices[0]
        # Execute shell command to start dumpstate HAL service because
        # it is a lazy HAL service.
        self.dut.shell.Execute(self.START_COMMAND)

        start_hal_success = False
        # Wait until service is started.
        # Retry at most three times.
        for _ in range(self.MAX_RETRY):
            result = self.dut.shell.Execute(self.CHECK_COMMAND)
            if result[const.STDOUT][0] != "":
                start_hal_success = True  # setup successful
                break
            time.sleep(1)  # wait one second.
        # Dumpstate HAL service is still not started after waiting for
        # self.MAX_RETRY times, stop the testcase.
        if not start_hal_success:
            logging.error("Failed to start dumpstate HAL service.")
            return False

        # Initialize a hal driver to start all managers on the target side,
        # not used for other purposes.
        self.dut.hal.InitHidlHal(
            target_type="dumpstate",
            target_basepaths=self.dut.libPaths,
            target_version_major=1,
            target_version_minor=0,
            target_package="android.hardware.dumpstate",
            target_component_name="IDumpstateDevice",
            bits=int(self.abi_bitness))
        # Make a shortcut name for the dumpstate HAL server.
        self._dumpstate = self.dut.hal.dumpstate

        # In order for dumpstate service to write to file, need to set
        # SELinux to permissive.
        permission_result = self.dut.shell.Execute("getenforce")
        self._permission = permission_result[const.STDOUT][0].strip()
        if self._permission == "Enforcing":
            self.dut.shell.Execute("setenforce permissive")

        # Check if a tmp directory under /data exists.
        self._created = False
        if not target_file_utils.Exists(self.TEST_DIR_PATH, self.dut.shell):
            # Create a tmp directory under /data.
            self.dut.shell.Execute("mkdir " + self.TEST_DIR_PATH)
            # Verify it succeeds. Stop test if it fails.
            if not target_file_utils.Exists(self.TEST_DIR_PATH,
                                            self.dut.shell):
                logging.error("Failed to create " + self.TEST_DIR_PATH +
                              " directory. Stopping test.")
                return False
            # Successfully created the directory.
            logging.info("Manually created " + self.TEST_DIR_PATH +
                         " for the test.")
            self._created = True