def testUnsyncQueueClientMultipleRead(self):
        """This test operates on the unsynchronized queue.
           Mirrors testcase: UnsynchronizedWriteClient, MultipleRead.
           Server acts as a writer, and client reads the data back in batches.
        """
        chunk_size = 100
        chunk_num = 5
        num_messages = chunk_num * chunk_size
        write_data = generateSequentialData(num_messages)

        # Client has no data to read yet.
        asserts.assertEqual(self._unsync_client1.availableToRead(), 0)
        # Server writes.
        asserts.assertTrue(
            self._tests_msgq.requestWriteFmqUnsync(num_messages),
            "Server should write successfully.")

        # Client reads it back continuously.
        total_read_data = []
        for i in range(chunk_num):
            read_data = []
            asserts.assertTrue(
                self._unsync_client1.read(read_data, chunk_size),
                "Client should read successfully.")
            total_read_data.extend(read_data)

        # Check read_data and write_data are equal.
        asserts.assertEqual(write_data, total_read_data)
    def setVhalProperty(self, propertyId, value, areaId=0, expectedStatus=0):
        """Sets a specified property in the Vehicle HAL.

        Args:
            propertyId: the numeric identifier of the property to be set.
            value: the value of the property, formatted as per the Vehicle HAL
                   (use emptyValueProperty() as a helper).
            areaId: the numeric identifier of the vehicle area to set the
                    property for. 0, or omitted, for global.
            expectedStatus: the StatusCode expected to be returned from setting
                    the property. 0, or omitted, for OK.
        """
        propValue = self.emptyValueProperty(propertyId, areaId)
        for k in propValue["value"]:
            if k in value:
                if k == "stringValue":
                    propValue["value"][k] += value[k]
                else:
                    propValue["value"][k].extend(value[k])
        vp = self.vtypes.Py2Pb("VehiclePropValue", propValue)
        logging.info("0x%x set request: %s", propertyId, vp)
        status = self.vehicle.set(vp)
        logging.info("0x%x set response: %s", propertyId, status)
        if 0 == expectedStatus:
            expectedStatus = self.vtypes.StatusCode.OK
        asserts.assertEqual(expectedStatus, status, "Prop 0x%x" % propertyId)
Пример #3
0
    def _GetTheoreticalMaxFrequency(self, cpu_no):
        """Reads max value from cpufreq/scaling_available_frequencies.

        If the read operation is successful, the return value is kept in
        _theoretical_max_frequency as a cache.

        Args:
            cpu_no: integer, the CPU number.

        Returns:
            An integer which is the max frequency read from the file.
            None if the file cannot be read.
        """
        if cpu_no in self._theoretical_max_frequency:
            return self._theoretical_max_frequency[cpu_no]
        results = self._shell.Execute(
            "cat /sys/devices/system/cpu/cpu%s/"
            "cpufreq/scaling_available_frequencies" % cpu_no)
        asserts.assertEqual(1, len(results[const.EXIT_CODE]))
        if not results[const.EXIT_CODE][0]:
            freq = [int(x) for x in results[const.STDOUT][0].split()]
            self._theoretical_max_frequency[cpu_no] = max(freq)
            return self._theoretical_max_frequency[cpu_no]
        else:
            logging.warn("cpufreq/scaling_available_frequencies for cpu %s"
                         " not set.", cpu_no)
            return None
    def testUnsyncQueueLargeInputTest3(self):
        """This test operates on the unsynchronized queue.
           Mirrors testcase: UnsynchronizedWriteClient, LargeInputTest3.
           Client writes until the queue is full, and writes one more,
           which overflows the queue. Read should fail after that.
           Client writes again, and server should be able to read again.
        """
        write_data = generateSequentialData(self.MAX_NUM_MSG)

        # Client fills up the queue.
        asserts.assertTrue(
            self._unsync_client1.write(write_data, self.MAX_NUM_MSG),
            "Client should write successfully.")
        asserts.assertEqual(0, self._unsync_client1.availableToWrite())
        # Client attempts to write one more, still succeeds.
        asserts.assertTrue(
            self._unsync_client1.write([1], 1),
            "Client should write successfully " +
            "even if queue is full for unsynchronized queue.")
        # Server fails to read because queue overflows.
        asserts.assertFalse(
            self._tests_msgq.requestReadFmqUnsync(self.MAX_NUM_MSG),
            "Server should fail to read because queue overflows.")

        # Do another interaction, and both should succeed.
        asserts.assertTrue(
            self._unsync_client1.write(write_data, self.MAX_NUM_MSG),
            "Client should write successfully.")
        asserts.assertTrue(
            self._tests_msgq.requestReadFmqUnsync(self.MAX_NUM_MSG),
            "Server should read successfully.")
Пример #5
0
 def testShellEcho2(self):
     '''A simple testcase which sends two commands.'''
     results = self.shell.Execute(['echo hello', 'echo world'])
     AssertShellCommandSuccess(results, 2)
     logging.info(str(results[const.STDOUT]))
     asserts.assertEqual(results[const.STDOUT][0].strip(), 'hello')
     asserts.assertEqual(results[const.STDOUT][1].strip(), 'world')
Пример #6
0
    def IsUnderThermalThrottling(self):
        """Checks whether a target device is under thermal throttling.

        Returns:
            True if the current CPU frequency is not the theoretical max,
            False otherwise.
        """
        self.Init()
        for cpu_no in range(self._min_cpu_number, self._max_cpu_number):
            results = self._shell.Execute(
                ["cat /sys/devices/system/cpu/cpu%s/cpufreq/scaling_max_freq" % cpu_no,
                 "cat /sys/devices/system/cpu/cpu%s/cpufreq/scaling_cur_freq" % cpu_no])
            asserts.assertEqual(2, len(results[const.STDOUT]))
            if any(results[const.EXIT_CODE]):
                logging.warn("Can't check the current and/or max CPU frequency.")
                logging.warn("Stderr for scaling_max_freq: %s", results[const.STDERR][0])
                logging.warn("Stderr for scaling_cur_freq: %s", results[const.STDERR][1])
                return False
            configurable_max_frequency = results[const.STDOUT][0].strip()
            current_frequency = results[const.STDOUT][1].strip()
            if configurable_max_frequency > current_frequency:
                logging.error(
                    "CPU%s: Configurable max frequency %s > current frequency %s",
                    cpu_no, configurable_max_frequency, current_frequency)
                return True
            theoretical_max_frequency = self._GetTheoreticalMaxFrequency(cpu_no)
            if (theoretical_max_frequency is not None and
                theoretical_max_frequency > int(current_frequency)):
                logging.error(
                    "CPU%s, Theoretical max frequency %d > scaling current frequency %s",
                    cpu_no, theoretical_max_frequency, current_frequency)
                return True
        return False
Пример #7
0
    def VerifyTestResult(self, test_case, command_results):
        """Parse Gtest xml result output.

        Args:
            test_case: BinaryTestCase object, the test being run. This param
                       is not currently used in this method.
            command_results: dict of lists, shell command result
        """
        asserts.assertTrue(command_results, 'Empty command response.')
        asserts.assertEqual(len(command_results), 3,
                            'Abnormal command response.')

        for stdout in command_results[const.STDOUT]:
            if stdout and stdout.strip():
                for line in stdout.split('\n'):
                    logging.info(line)

        if any(command_results[const.EXIT_CODE]):
            # print stderr only when test fails.
            for stderr in command_results[const.STDERR]:
                if stderr and stderr.strip():
                    for line in stderr.split('\n'):
                        logging.error(line)
            asserts.fail(
                'Test {} failed with the following results: {}'.format(
                    test_case, command_results))
Пример #8
0
 def testEcho1(self):
     """A simple testcase which sends a command."""
     self.dut.shell.InvokeTerminal("my_shell1")  # creates a remote shell instance.
     results = self.dut.shell.my_shell1.Execute("echo hello_world")  # runs a shell command.
     logging.info(str(results[const.STDOUT]))  # prints the stdout
     asserts.assertEqual(results[const.STDOUT][0].strip(), "hello_world")  # checks the stdout
     asserts.assertEqual(results[const.EXIT_CODE][0], 0)  # checks the exit code
 def testVerifyOverlay(self):
     """Verifies application of DT overlays."""
     overlay_idx_string = self.adb.shell(
         "cat /proc/cmdline | "
         "grep -o \"androidboot.dtbo_idx=[^ ]*\" |"
         "cut -d \"=\" -f 2")
     asserts.assertNotEqual(
         len(overlay_idx_string), 0,
         "Kernel command line missing androidboot.dtbo_idx")
     overlay_idx_list = overlay_idx_string.split(",")
     overlay_arg = []
     for idx in overlay_idx_list:
         overlay_file = "dumped_dtbo." + idx.rstrip()
         overlay_path = os.path.join(self.temp_dir, overlay_file)
         self.adb.push(overlay_path, self.device_path)
         overlay_arg.append(overlay_file)
     final_dt_path = path_utils.JoinTargetPath(self.device_path, "final_dt")
     self.shell.Execute("cp %s %s" % (FDT_PATH, final_dt_path))
     verification_test_path = path_utils.JoinTargetPath(
         self.device_path, "ufdt_verify_overlay")
     chmod_cmd = "chmod 755 %s" % verification_test_path
     results = self.shell.Execute(chmod_cmd)
     asserts.assertEqual(results[const.EXIT_CODE][0], 0, "Unable to chmod")
     cd_cmd = "cd %s" % (self.device_path)
     verify_cmd = "./ufdt_verify_overlay final_dt %s" % (
         " ".join(overlay_arg))
     cmd = str("%s && %s" % (cd_cmd, verify_cmd))
     logging.info(cmd)
     results = self.shell.Execute(cmd)
     asserts.assertEqual(results[const.EXIT_CODE][0], 0,
                         "Incorrect Overlay Application")
 def testProcPagetypeinfo(self):
     filepath = "/proc/pagetypeinfo"
     # Check that incident_helper can parse /proc/pagetypeinfo.
     result = self.shell.Execute("cat %s | incident_helper -s 2001" %
                                 filepath)
     asserts.assertEqual(result[const.EXIT_CODE][0], 0,
                         "Failed to parse %s." % filepath)
 def testClearAndAddLogicalAddress(self):
     """A simple test case which sets logical address and clears it."""
     self.dut.hal.tv_cec.clearLogicalAddress()
     result = self.dut.hal.tv_cec.addLogicalAddress(
             self.vtypes.CecLogicalAddress.PLAYBACK_3)
     asserts.assertEqual(self.vtypes.Result.SUCCESS, result)
     logging.info("addLogicalAddress result: %s", result)
    def testRebootRootRemount(self):
        """Tests if /system partition can be remounted as r/w after reboot."""
        # Disable verity if it's enabled.
        if self.verity:
            logging.info("Disable verity.")
            self.dut.adb.disable_verity()

        try:
            self.dut.reboot()
            self.dut.waitForBootCompletion()
        except utils.TimeoutError:
            asserts.fail("Reboot failed.")

        try:
            self.dut.adb.root()
            self.dut.adb.wait_for_device()
            # Remount /system partition as r/w.
            self.dut.adb.remount()
            self.dut.adb.wait_for_device()
        except adb.AdbError():
            asserts.fail("Root/remount failed.")

        # Restore verity to its original state.
        if self.verity:
            logging.info("Enable verity.")
            self.dut.adb.enable_verity()
            try:
                self.dut.reboot()
                self.dut.waitForBootCompletion()
            except utils.TimeoutError:
                asserts.fail("Reboot failed after re-enabling verity.")

        asserts.assertEqual(self.verity, self.dut.verityEnabled,
                            "Verity state was successfully restored.")
Пример #13
0
    def _ListOpenFiles(self, pids, file_filter):
        """Finds open files whose names match the filter.

        Args:
            pids: A collection of strings, the PIDs to list open files.
            file_filter: A function that takes a file path as argument and
                         returns whether the path matches the condition.

        Returns:
            A dict of {pid: [file, ...]} where pid and file are strings.
        """
        lsof_cmd = "lsof -p " + ",".join(pids)
        result = self._shell.Execute(lsof_cmd)
        asserts.assertEqual(result[const.EXIT_CODE][0], 0)
        lines = result[const.STDOUT][0].split("\n")
        pid_end = lines[0].index("PID") + len("PID")
        name_begin = lines[0].index("NAME")
        files = {}
        for line in lines[1:]:
            name = line[name_begin:]
            if not file_filter(name):
                continue
            pid_begin = line.rindex(" ", 0, pid_end) + 1
            pid = line[pid_begin:pid_end]
            if pid in files:
                files[pid].append(name)
            else:
                files[pid] = [name]
        return files
    def CheckImageHeader(self, boot_image, is_recovery=False):
        """Verifies the boot image header version, header size and recovery dtbo size.

        Args:
            boot_image: Path to the boot image.
            is_recovery: Indicates that the image is recovery if true.
        """
        try:
            with open(boot_image, "rb") as image_file:
                image_file.read(8)  # read boot magic
                host_image_header_version = unpack("10I",
                                                   image_file.read(10 * 4))[8]
                asserts.assertEqual(
                    host_image_header_version, 1,
                    "Device does not have boot image of version 1")
                image_file.seek(BOOT_HEADER_DTBO_SIZE_OFFSET)
                recovery_dtbo_size = unpack("I", image_file.read(4))[0]
                image_file.read(8)  # ignore recovery dtbo load address
                if is_recovery:
                    asserts.assertNotEqual(
                        recovery_dtbo_size, 0,
                        "recovery partition for non-A/B devices must contain the recovery DTBO"
                    )
                boot_header_size = unpack("I", image_file.read(4))[0]
                expected_header_size = image_file.tell()
                asserts.assertEqual(
                    boot_header_size, expected_header_size,
                    "Test failure due to boot header size mismatch. Expected %s Actual %s"
                    % (expected_header_size, boot_header_size))
        except IOError as e:
            logging.exception(e)
            asserts.fail("Unable to open boot image file")
Пример #15
0
    def _runBenchmark(self, bits):
        """Runs the native binary and parses its result.

        Args:
            bits: integer (32 or 64), the bitness of the binary to run.

        Returns:
            dict, the benchmarking result converted from native binary's JSON
            output.
        """
        logging.info("Start %d-bit hwbinder latency test with HIDL mode=%s",
                     bits, self.hidl_hal_mode)
        binary = "/data/local/tmp/%s/libhwbinder_latency%s" % (bits, bits)
        min_cpu, max_cpu = self._cpu_freq.GetMinAndMaxCpuNo()
        iterations = 1000 // (max_cpu - min_cpu)
        results = self.dut.shell.one.Execute([
            "chmod 755 %s" % binary,
            "VTS_ROOT_PATH=/data/local/tmp " \
            "LD_LIBRARY_PATH=/system/lib%s:/data/local/tmp/%s/hw:"
            "/data/local/tmp/%s:$LD_LIBRARY_PATH "
            "%s -raw_data -pair %d -i %d -m %s" % (bits, bits, bits,
                binary, max_cpu - min_cpu, iterations,
                self.hidl_hal_mode.encode("utf-8"))])
        # Parses the result.
        asserts.assertEqual(len(results[const.STDOUT]), 2)
        logging.info("stderr: %s", results[const.STDERR][1])
        logging.info("stdout: %s", results[const.STDOUT][1])
        asserts.assertFalse(any(results[const.EXIT_CODE]),
                            "testRunBenchmark%sBit failed." % (bits))
        json_result = json.loads(results[const.STDOUT][1])
        asserts.assertTrue(json_result[self._INHERITANCE] == "PASS",
                           "Scheduler does not support priority inheritance.")
        return json_result
Пример #16
0
def AssertShellCommandSuccess(command_results, num_of_commands):
    '''Check shell command result with assertions.

    Given a shell command output, this command checks several things:
    1. result is not None
    2. result is not empty
    3. number of results is consistant with number of commands
    4. there is no error message on STDERR
    5. return code of commands are all 0

    Args:
        command_results: dict, shell command results
        num_of_commands: int, number of commands
    '''
    asserts.assertTrue(command_results is not None,
                       'command result cannot be None')
    asserts.assertEqual(len(command_results), 3, 'command result is empty')
    for item in command_results:
        asserts.assertEqual(
            len(command_results[item]), num_of_commands,
            'number of command result is not %s: %s' % (num_of_commands,
                                                        command_results))
    asserts.assertFalse(
        any(command_results[const.STDERR]),
        'received error message from stderr: %s' % command_results)
    asserts.assertFalse(
        any(command_results[const.EXIT_CODE]),
        'received non zero return code: %s' % command_results)
Пример #17
0
    def CheckImageHeader(self, boot_image, is_recovery=False):
        """Verifies the boot image format.

        Args:
            boot_image: Path to the boot image.
            is_recovery: Indicates that the image is recovery if true.
        """
        try:
            with open(boot_image, "rb") as image_file:
                image_file.read(8)  # read boot magic
                (kernel_size, _, ramdisk_size, _, _, _, _, page_size,
                 host_image_header_version) = unpack("9I",
                                                     image_file.read(9 * 4))

                asserts.assertNotEqual(
                    kernel_size, 0,
                    "boot.img/recovery.img must contain kernel")

                if self.launch_api_level > api.PLATFORM_API_LEVEL_P:
                    asserts.assertTrue(
                        host_image_header_version >= 2,
                        "Device must atleast have a boot image of version 2")

                    asserts.assertNotEqual(ramdisk_size, 0,
                                           "boot.img must contain ramdisk")

                    # ramdisk comes after the header and kernel pages
                    num_kernel_pages = self.get_number_of_pages(
                        kernel_size, page_size)
                    ramdisk_offset = page_size * (1 + num_kernel_pages)
                    image_file.seek(ramdisk_offset)
                    ramdisk_buf = image_file.read(ramdisk_size)
                    self.checkValidRamdisk(ramdisk_buf)
                else:
                    asserts.assertTrue(
                        host_image_header_version >= 1,
                        "Device must atleast have a boot image of version 1")
                image_file.seek(BOOT_HEADER_DTBO_SIZE_OFFSET)
                recovery_dtbo_size = unpack("I", image_file.read(4))[0]
                image_file.read(8)  # ignore recovery dtbo load address
                if is_recovery:
                    asserts.assertNotEqual(
                        recovery_dtbo_size, 0,
                        "recovery partition for non-A/B devices must contain the recovery DTBO"
                    )
                boot_header_size = unpack("I", image_file.read(4))[0]
                if host_image_header_version > 1:
                    dtb_size = unpack("I", image_file.read(4))[0]
                    asserts.assertNotEqual(
                        dtb_size, 0, "Boot/recovery image must contain DTB")
                    image_file.read(8)  # ignore DTB physical load address
                expected_header_size = image_file.tell()
                asserts.assertEqual(
                    boot_header_size, expected_header_size,
                    "Test failure due to boot header size mismatch. Expected %s Actual %s"
                    % (expected_header_size, boot_header_size))
        except IOError as e:
            logging.exception(e)
            asserts.fail("Unable to open boot image file")
Пример #18
0
 def testSimpleReadWrite(self):
     """Test a simple read/write interaction between reader and writer. """
     write_data = "Hello World!"
     asserts.assertEqual(
         len(write_data), self._writer.writeFile(write_data,
                                                 len(write_data)))
     read_data = self._reader.readFile(len(write_data))
     asserts.assertEqual(write_data, read_data)
Пример #19
0
 def testShellEcho1(self):
     '''A simple testcase which sends a command.'''
     results = self.shell.Execute(
         "echo hello_world")  # runs a shell command.
     AssertShellCommandSuccess(results, 1)
     logging.info(str(results[const.STDOUT]))  # prints the stdout
     asserts.assertEqual(results[const.STDOUT][0].strip(),
                         "hello_world")  # checks the stdout
Пример #20
0
 def testUnsyncQueueReadWhenEmpty(self):
     """This test operates on the unsynchronized queue.
        Mirrors testcase: UnsynchronizedWriteClient, ReadWhenEmpty.
        Read should fail when queue is empty.
     """
     asserts.assertEqual(self._unsync_client1.availableToRead(), 0)
     asserts.assertFalse(
         self._unsync_client1.read([], 2),
         "Client should fail to read because queue is empty.")
Пример #21
0
 def testEcho1(self):
     """A simple testcase which sends a command."""
     results = self.shell.Execute(
         "echo hello_world")  # runs a shell command.
     logging.info(str(results[const.STDOUT]))  # prints the stdout
     asserts.assertEqual(results[const.STDOUT][0].strip(),
                         "hello_world")  # checks the stdout
     asserts.assertEqual(results[const.EXIT_CODE][0],
                         0)  # checks the exit code
Пример #22
0
 def testCommandSequenceMktemp(self):
     """A simple test case that emulates using mktemp bash command sequence
        connected by '&&' under normal usage pattern.
     """
     self.dut.shell.InvokeTerminal("command_sequence_mktemp")
     results = self.dut.shell.command_sequence_mktemp.Execute(
         "TMPFILE=`mktemp /data/local/tmp/test.XXXXXXXXXXXX` "
         "&& ls $TMPFILE")
     asserts.assertEqual(results[const.EXIT_CODE][0], 0)
    def testActionableCompatiblePropertyEnabled(self):
        """Ensures the feature of actionable compatible property is enforced.

        ro.actionable_compatible_property.enabled must be true to enforce the
        feature of actionable compatible property.
        """
        asserts.assertEqual(
            self.dut.getProp("ro.actionable_compatible_property.enabled"),
            "true", "ro.actionable_compatible_property.enabled must be true")
Пример #24
0
 def testEcho2(self):
     """A simple testcase which sends two commands."""
     results = self.shell.Execute(["echo hello", "echo world"])
     logging.info(str(results[const.STDOUT]))
     asserts.assertEqual(len(results[const.STDOUT]),
                         2)  # check the number of processed commands
     asserts.assertEqual(results[const.STDOUT][0].strip(), "hello")
     asserts.assertEqual(results[const.STDOUT][1].strip(), "world")
     asserts.assertEqual(results[const.EXIT_CODE][0], 0)
     asserts.assertEqual(results[const.EXIT_CODE][1], 0)
Пример #25
0
    def testLargeReadWrite(self):
        """Test consecutive reads/writes between reader and writer. """
        write_data = "Android VTS"

        for i in range(10):
            asserts.assertEqual(
                len(write_data),
                self._writer.writeFile(write_data, len(write_data)))
            curr_read_data = self._reader.readFile(len(write_data))
            asserts.assertEqual(curr_read_data, write_data)
    def setUpClass(self):
        logging.info('number of device: %s', self.android_devices)

        asserts.assertEqual(
            len(self.android_devices), 2, 'number of device is wrong.')

        self.dut1 = self.android_devices[0]
        self.dut2 = self.android_devices[1]
        self.shell1 = self.dut1.shell
        self.shell2 = self.dut2.shell
        def validateSet(self, status):
            """Validate the result of IVehicle.set.
            Reading back the written-to property to ensure a consistent
            value is fair game for this method.

            Args:
                status: the StatusCode returned from Vehicle HAL.

            Returns: None."""
            asserts.assertEqual(self.test.vtypes.StatusCode.OK, status)
 def getValueIfPropSupported(self, propertyId):
     """Returns tuple of boolean (indicating value supported or not) and the value itself"""
     if (propertyId in self.propToConfig):
         propValue = self.readVhalProperty(propertyId)
         asserts.assertNotEqual(None, propValue,
                                "expected value, prop: 0x%x" % propertyId)
         asserts.assertEqual(propertyId, propValue['prop'])
         return True, self.extractValue(propValue)
     else:
         return False, None
    def testMandatoryProperties(self):
        """Verifies that all mandatory properties are supported."""
        # 1 property so far
        mandatoryProps = set([self.vtypes.VehicleProperty.DRIVING_STATUS])
        logging.info(self.vtypes.VehicleProperty.DRIVING_STATUS)

        for config in self.configList:
            mandatoryProps.discard(config['prop'])

        asserts.assertEqual(0, len(mandatoryProps))
Пример #30
0
 def testCommandSequenceExport(self):
     """A simple test case that emulates using export bash command sequence
        connected by '&&' under normal usage pattern.
     """
     self.dut.shell.InvokeTerminal("command_sequence_export")
     var_value = "helloworld"
     results = self.dut.shell.command_sequence_export.Execute(
         "export {var_name}={var_value} && echo ${var_name}".format(
             var_name="TESTTMPVAR", var_value=var_value))
     asserts.assertEqual(results[const.EXIT_CODE][0], 0)
     asserts.assertEqual(results[const.STDOUT][0].strip(), var_value)