def GetTraceFiles(self, dut, host_profiling_trace_path, trace_file_tool): """Pulls the trace file and save it under the profiling trace path. Args: dut: the testing device. host_profiling_trace_path: directory that stores trace files on host. trace_file_tool: tools that used to store the trace file. Returns: Name list of trace files that stored on host. """ if not os.path.exists(LOCAL_PROFILING_TRACE_PATH): os.makedirs(LOCAL_PROFILING_TRACE_PATH) if not host_profiling_trace_path: host_profiling_trace_path = LOCAL_PROFILING_TRACE_PATH dut.shell.InvokeTerminal("profiling_shell") target_trace_file = path_utils.JoinTargetPath( TARGET_PROFILING_TRACE_PATH, "*.vts.trace") results = dut.shell.profiling_shell.Execute("ls " + target_trace_file) asserts.assertTrue(results, "failed to find trace file") stdout_lines = results[const.STDOUT][0].split("\n") logging.info("stdout: %s", stdout_lines) trace_files = [] for line in stdout_lines: if line: temp_file_name = os.path.join(LOCAL_PROFILING_TRACE_PATH, os.path.basename(line.strip())) dut.adb.pull("%s %s" % (line, temp_file_name)) trace_file_name = os.path.join(host_profiling_trace_path, os.path.basename(line.strip())) logging.info("Saving profiling traces: %s" % trace_file_name) if temp_file_name != trace_file_name: file_cmd = "" if trace_file_tool: file_cmd += trace_file_tool file_cmd += " cp " + temp_file_name + " " + trace_file_name results = cmd_utils.ExecuteShellCommand(file_cmd) if results[const.EXIT_CODE][0] != 0: logging.error(results[const.STDERR][0]) logging.error("Fail to execute command: %s" % file_cmd) trace_files.append(temp_file_name) return trace_files
def testUnsyncQueueLargeInputTest1(self): """This test operates on the unsynchronized queue. Mirrors testcase: UnsynchronizedWriteClient, LargeInputTest1. Server writes to the queue and client reads the data back. """ # Server writes. asserts.assertTrue( self._tests_msgq.requestWriteFmqUnsync(self.MAX_NUM_MSG), "Server should write successfully.") write_data = generateSequentialData(self.MAX_NUM_MSG) read_data = [] # Client reads. asserts.assertEqual(self._unsync_client1.availableToRead(), self.MAX_NUM_MSG) asserts.assertTrue( self._unsync_client1.read(read_data, self.MAX_NUM_MSG), "Client should read successfully.") asserts.assertEqual(write_data, read_data)
def VerifyTestResult(self, test_case, command_results): '''Parse Gtest xml result output. Sample <testsuites tests="1" failures="1" disabled="0" errors="0" timestamp="2017-05-24T18:32:10" time="0.012" name="AllTests"> <testsuite name="ConsumerIrHidlTest" tests="1" failures="1" disabled="0" errors="0" time="0.01"> <testcase name="TransmitTest" status="run" time="0.01" classname="ConsumerIrHidlTest"> <failure message="hardware/interfaces..." type=""> <![CDATA[hardware/interfaces...]]> </failure> </testcase> </testsuite> </testsuites> Args: test_case: GtestTestCase 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 item in command_results[const.STDOUT]: if item and item.strip(): logging.info(item) for item in command_results[const.STDERR]: if item and item.strip(): logging.error(item) asserts.assertFalse( command_results[const.EXIT_CODE][1], 'Failed to show Gtest XML output: %s' % command_results) xml_str = command_results[const.STDOUT][1].strip() root = xml.etree.ElementTree.fromstring(xml_str) asserts.assertEqual(root.get('tests'), '1', 'No tests available') if root.get('errors') != '0' or root.get('failures') != '0': messages = [x.get('message') for x in root.findall('.//failure')] asserts.fail('\n'.join([x for x in messages if x])) asserts.skipIf(root.get('disabled') == '1', 'Gtest test case disabled')
def testExportedPlatformPropertyIntegrity(self): """Ensures public property contexts isn't modified at all. Public property contexts must not be modified. """ logging.info("Checking existence of %s", self._SYSTEM_PROPERTY_CONTEXTS_FILE_PATH) target_file_utils.assertPermissionsAndExistence( self.shell, self._SYSTEM_PROPERTY_CONTEXTS_FILE_PATH, target_file_utils.IsReadable) # Pull system property contexts file from device. self.dut.adb.pull( "%s %s" % (self._SYSTEM_PROPERTY_CONTEXTS_FILE_PATH, self._temp_dir)) logging.info("Adb pull %s to %s", self._SYSTEM_PROPERTY_CONTEXTS_FILE_PATH, self._temp_dir) with open(os.path.join(self._temp_dir, "plat_property_contexts"), "r") as property_contexts_file: sys_property_dict = self._ParsePropertyDictFromPropertyContextsFile( property_contexts_file, True) logging.info( "Found %d exact-matching properties " "in system property contexts", len(sys_property_dict)) pub_property_contexts_file_path = os.path.join( self.data_file_path, self._PUBLIC_PROPERTY_CONTEXTS_FILE_PATH) with open(pub_property_contexts_file_path, "r") as property_contexts_file: pub_property_dict = self._ParsePropertyDictFromPropertyContextsFile( property_contexts_file, True) for name in pub_property_dict: public_tokens = pub_property_dict[name] asserts.assertTrue(name in sys_property_dict, "Exported property (%s) doesn't exist" % name) if name in self._MODIFIABLE_PROPERTIES: continue system_tokens = sys_property_dict[name] asserts.assertEqual(public_tokens, system_tokens, "Exported property (%s) is modified" % name)
def _ParseResultXmlString(self, xml_str): """Parses the xml result string into elements. Args: xml_str: string, result xml text content. Returns: xml.etree.ElementTree, parsed xml content. Raises: assertion failure if xml format is not expected. """ asserts.assertTrue(xml_str is not None, 'Test command result not received.') xml_str = xml_str.strip() asserts.assertTrue(xml_str, 'Test command result is empty.') try: return xml.etree.ElementTree.fromstring(xml_str) except: asserts.fail('Result xml content is corrupted.')
def __call__(self): asserts.assertTrue(self.test.isPropertySupported(self.propertyId), "error") request = { 'prop': self.propertyId, 'timestamp': 0, 'areaId': self.areaId, 'value': { 'int32Values': [], 'floatValues': [], 'int64Values': [], 'bytes': [], 'stringValue': "" } } request = self.prepareRequest(request) requestPropValue = self.test.vtypes.Py2Pb("VehiclePropValue", request) status = self.test.vehicle.set(requestPropValue) return self.validateSet(status)
def testSyncQueueWriteWhenFull(self): """This test operates on the synchronized queue. Mirrors testcase: SynchronizedReadWriteClient, WriteWhenFull. Write should fail when queue is full. """ write_data = generateSequentialData(self.MAX_NUM_MSG) # Client writes. asserts.assertTrue( self._sync_client.write(write_data, self.MAX_NUM_MSG), "Client should write successfully.") asserts.assertEqual(self._sync_client.availableToWrite(), 0) # Client tries to write more, fails. asserts.assertFalse( self._sync_client.write([1], 1), "Client should fail to write because queue is full.") # Server should read data back correctly. asserts.assertTrue( self._tests_msgq.requestReadFmqSync(self.MAX_NUM_MSG), "Server should read successfully")
def IsReadOnly(self, path): '''Check whether a given path is read only. Assertion will fail if given path does not exist or is not read only. ''' permission = '' try: permission = file_utils.GetPermission(path, self.shell) except IOError as e: logging.exception(e) asserts.fail('Path "%s" does not exist or has invalid ' 'permission bits' % path) try: asserts.assertTrue(file_utils.IsReadOnly(permission), 'path %s is not read only' % path) except IOError as e: logging.exception(e) asserts.fail('Got invalid permission bits "%s" for path "%s"' % (permission, path))
def testProcSysAbiSwpInstruction(self): """Tests /proc/sys/abi/swp. /proc/sys/abi/swp sets the execution behaviour for the obsoleted ARM instruction SWP. As per the setting in /proc/sys/abi/swp, the usage of SWP{B} can either generate an undefined instruction abort or use software emulation or hardware execution. """ asserts.skipIf(not ("arm" in self.dut.cpu_abi and self.dut.is64Bit), "file not present on non-ARM64 device") target_file_utils.assertPermissionsAndExistence( self.shell, self._PROC_SYS_ABI_SWP_FILE_PATH, target_file_utils.IsReadWrite) file_content = self.ReadFileContent(self._PROC_SYS_ABI_SWP_FILE_PATH) try: swp_state = int(file_content) except ValueError as e: asserts.fail("Failed to parse %s" % self._PROC_SYS_ABI_SWP_FILE_PATH) asserts.assertTrue(swp_state >= 0 and swp_state <= 2, "%s contains incorrect value: %d" % (self._PROC_SYS_ABI_SWP_FILE_PATH, swp_state))
def getProp(self, prop, required=True): """Helper to retrieve a property from device.""" results = self.dut.shell.Execute("getprop " + prop) if required: asserts.assertEqual(results[const.EXIT_CODE][0], 0, "getprop must succeed") asserts.assertTrue( len(results[const.STDOUT][0].strip()) > 0, "getprop must return a value") else: if (results[const.EXIT_CODE][0] != 0 or len(results[const.STDOUT][0].strip()) == 0): logging.info("sysprop %s undefined", prop) return None result = results[const.STDOUT][0].strip() logging.info("getprop {}={}".format(prop, result)) return result
def testSyncQueueLargeInputTest3(self): """This test operates on the synchronized queue. Mirrors testcase: SynchronizedReadWriteClient, LargeInputTest3. Client writes until the queue is full, attempts to write one more, and fails. """ write_data = generateSequentialData(self.MAX_NUM_MSG) # Client fills up the queue. asserts.assertTrue( self._sync_client.write(write_data, self.MAX_NUM_MSG), "Client should write successfully.") asserts.assertEqual(0, self._sync_client.availableToWrite()) # Client attempts to write one more, fails. asserts.assertFalse( self._sync_client.write([1], 1), "Client should fail to write because queue is full.") # Server reads back data from client. asserts.assertTrue( self._tests_msgq.requestReadFmqSync(self.MAX_NUM_MSG), "Server should read successfully.")
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 testWakeLock(self): '''Check that locking and unlocking a wake lock works.''' _WAKE_LOCK_PATH = '/sys/power/wake_lock' _WAKE_UNLOCK_PATH = '/sys/power/wake_unlock' lock_name = 'KernelApiSysfsTestWakeLock' + uuid.uuid4().hex # Enable wake lock self.shell.Execute('echo %s > %s' % (lock_name, _WAKE_LOCK_PATH)) # Confirm wake lock is enabled results = self.shell.Execute('cat %s' % _WAKE_LOCK_PATH) active_sources = results[const.STDOUT][0].split() asserts.assertTrue( lock_name in active_sources, 'active wake lock not reported in %s' % _WAKE_LOCK_PATH) # Disable wake lock self.shell.Execute('echo %s > %s' % (lock_name, _WAKE_UNLOCK_PATH)) # Confirm wake lock is no longer enabled results = self.shell.Execute('cat %s' % _WAKE_LOCK_PATH) active_sources = results[const.STDOUT][0].split() asserts.assertTrue( lock_name not in active_sources, 'inactive wake lock reported in %s' % _WAKE_LOCK_PATH) results = self.shell.Execute('cat %s' % _WAKE_UNLOCK_PATH) inactive_sources = results[const.STDOUT][0].split() asserts.assertTrue( lock_name in inactive_sources, 'inactive wake lock not reported in %s' % _WAKE_UNLOCK_PATH)
def setUp(self): """Initialize a writer and a reader for each test case. We open the file with w+ in every test case, which will create the file if it doesn't exist, or truncate the file if it exists, because some test case won't fully read the content of the file, causing dependency between test cases. """ self._writer = self.dut.resource.InitHidlHandleForSingleFile( self.TEST_FILE_PATH, "w+", client=self.dut.hal.GetTcpClient("dumpstate")) self._reader = self.dut.resource.InitHidlHandleForSingleFile( self.TEST_FILE_PATH, "r", client=self.dut.hal.GetTcpClient("dumpstate")) asserts.assertTrue(self._writer is not None, "Writer should be initialized successfully.") asserts.assertTrue(self._reader is not None, "Reader should be initialized successfully.") asserts.assertNotEqual(self._writer.handleId, -1) asserts.assertNotEqual(self._reader.handleId, -1)
def checkKernelVersion(self): """Validate the kernel version of DUT is a valid O kernel version. Returns: string, kernel version of device """ cmd = "uname -a" results = self.shell.Execute(cmd) logging.info("Shell command '%s' results: %s", cmd, results) match = re.search(r"\d+\.\d+", results[const.STDOUT][0]) if match is None: asserts.fail("Failed to detect kernel version of device.") else: kernel_version = match.group(0) logging.info("Detected kernel version: %s", kernel_version) asserts.assertTrue(kernel_version in self.SUPPORTED_KERNEL_VERSIONS, "Detected kernel version '%s' is not one of %s" % (kernel_version, self.SUPPORTED_KERNEL_VERSIONS)) return kernel_version
def testUnsyncQueueWriteWhenFull(self): """This test operates on the unsynchronized queue. Mirrors testcase: UnsynchronizedWriteClient, WriteWhenFull. Write should still succeed because unsynchronized queue allows overflow. Subsequent read should fail. """ write_data = generateSequentialData(self.MAX_NUM_MSG) # Client writes. asserts.assertTrue( self._unsync_client1.write(write_data, self.MAX_NUM_MSG), "Client should write successfully.") asserts.assertEqual(self._unsync_client1.availableToWrite(), 0) # Client tries to write more, still succeeds. asserts.assertTrue( self._unsync_client1.write([1], 1), "Client should write successfully " + "even if queue is full for unsynchronized queue.") # Server should fail because queue overflows. asserts.assertFalse( self._tests_msgq.requestReadFmqUnsync(self.MAX_NUM_MSG), "Server should fail to read because queue overflows.")
def testUnsyncQueueClientMultipleWrite(self): """This test operates on the unsynchronized queue. Mirrors testcase: UnsynchronizedWriteClient, MultipleWrite. Client writes the data in batches, and server reads it back together. """ chunk_size = 100 chunk_num = 5 num_messages = chunk_num * chunk_size write_data = generateSequentialData(num_messages) # Client should see an empty queue. asserts.assertEqual(self._unsync_client1.availableToWrite(), self.MAX_NUM_MSG) for i in range(chunk_num): # Client keeps writing. curr_write_data = write_data[i * chunk_size:(i + 1) * chunk_size] asserts.assertTrue( self._unsync_client1.write(curr_write_data, chunk_size), "Client should write successfully.") # Server reads data back correctly. asserts.assertTrue(self._tests_msgq.requestReadFmqUnsync(num_messages), "Server should read successfully.")
def setUp(self): # Initialize a FMQ on the target-side driver. self._sync_client = self.dut.resource.InitFmq( data_type="uint16_t", sync=True, queue_size=self.MAX_NUM_MSG, blocking=True, client=self.dut.hal.GetTcpClient("tests_msgq")) asserts.assertNotEqual(self._sync_client.queueId, -1) # Prepare a VariableSpecificationMessage to specify the FMQ that will be # passed into the HAL service. var_msg = CompSpecMsg.VariableSpecificationMessage() var_msg.type = CompSpecMsg.TYPE_FMQ_SYNC fmq_val = var_msg.fmq_value.add() fmq_val.fmq_id = self._sync_client.queueId fmq_val.scalar_type = "uint16_t" fmq_val.type = CompSpecMsg.TYPE_SCALAR # Call API in the HAL server. sync_init_result = self._tests_msgq.configureFmqSyncReadWrite(var_msg) asserts.assertTrue( sync_init_result, "Hal should configure a synchronized queue without error.") # Initialize an unsynchronized queue on the server. [success, self._unsync_client1] = self._tests_msgq.getFmqUnsyncWrite(True) asserts.assertTrue( success, "Hal should configure an unsynchronized queue without error.") # An unsynchronized queue is registered successfully on the target driver. asserts.assertNotEqual(self._unsync_client1, None) asserts.assertNotEqual(self._unsync_client1.queueId, -1) # Register another reader. self._unsync_client2 = self.dut.resource.InitFmq( existing_queue=self._unsync_client1, client=self.dut.hal.GetTcpClient("tests_msgq")) asserts.assertNotEqual(self._unsync_client2.queueId, -1)
def testBlockingReadWrite(self): """Test blocking read/write. This test operates on queue 2, and tests blocking read/write. Writer waits 0.05s and writes. Reader blocks for at most 0.1s, and should read successfully. TODO: support this when reader and writer operates in parallel. """ write_data = self.GetRandomIntegers(2048) read_data = [] # Writer waits for 0.05s and writes. time.sleep(0.05) asserts.assertTrue( self._queue2_writer.writeBlocking(write_data, 2048, 1000000), "Writer should write successfully.") # Reader reads. read_success = self._queue2_reader.readBlocking( read_data, 2048, 1000 * 1000000) asserts.assertTrue(read_success, "Reader should read successfully after blocking.") asserts.assertEqual(write_data, read_data)
def CheckResult(self, cmd_results, result=None, note=None): """Check a test result and emit exceptions if test failed or skipped. If the shell command result is not yet interpreted, self.Verify will be called to interpret the results. Args: cmd_results: dict([str],[str],[int]), command results from shell. result: int, which is one of the values of _PASS, _SKIP, and _FAIL note: string, reason why a test failed or get skipped """ asserts.assertTrue(cmd_results, "No response received. Socket timeout") logging.info("stdout: %s", cmd_results[const.STDOUT]) logging.info("stderr: %s", cmd_results[const.STDERR]) logging.info("exit_code: %s", cmd_results[const.EXIT_CODE]) if result is None: result, note = self.Verify(cmd_results) logging.info("verify result: %s", result) logging.info("note: %s", note) asserts.skipIf(result == self._SKIP, note) asserts.assertEqual(result, self._PASS, note)
def testBasic(self): """Tests correctness of basic util methods. """ # Check the correctness on queue 1, which uses primitive type uint32_t. asserts.assertEqual(self._queue1_writer.getQuantumSize(), 2) asserts.assertEqual(self._queue1_writer.getQuantumCount(), 2048) asserts.assertEqual(self._queue1_writer.availableToWrite(), 2048) asserts.assertEqual(self._queue1_reader.availableToRead(), 0) asserts.assertTrue(self._queue1_writer.isValid(), "Queue 1 writer should be valid.") asserts.assertTrue(self._queue1_reader.isValid(), "Queue 1 reader should be valid.") # Also check the correctness on queue 4, which uses predefined type # in audio HAL service. asserts.assertEqual(self._queue4_writer.getQuantumCount(), 2048) asserts.assertEqual(self._queue4_writer.availableToWrite(), 2048) asserts.assertEqual(self._queue4_reader.availableToRead(), 0) asserts.assertTrue(self._queue4_writer.isValid(), "Queue 4 writer should be valid.") asserts.assertTrue(self._queue4_reader.isValid(), "Queue 4 reader should be valid.")
def testAcpioPartition(self): """Validates ACPIO partition using mkdtboimg.py.""" temp_SSDT_dump = "SSDT.dump" temp_SSDT_dump_hashes = [] current_SSDT = "SSDT" current_SSDT_hashes = [] slot_suffix = str(self.dut.getProp(PROPERTY_SLOT_SUFFIX)) current_acpio_partition = "acpio" + slot_suffix acpio_path = target_file_utils.FindFiles(self.shell, BLOCK_DEV_PATH, current_acpio_partition, "-type l") if not acpio_path: asserts.fail("Unable to find path to acpio image on device.") logging.debug("ACPIO path %s", acpio_path) host_acpio_image = os.path.join(self.temp_dir, "acpio") self.adb.pull("%s %s" % (acpio_path[0], host_acpio_image)) mkdtimg_bin_path = os.path.join("host", "bin", "mkdtboimg.py") unpacked_acpio_file = os.path.join(self.temp_dir, temp_SSDT_dump) acpio_dump_cmd = [ "%s" % mkdtimg_bin_path, "dump", "%s" % host_acpio_image, "-b", "%s" % unpacked_acpio_file ] try: subprocess.check_call(acpio_dump_cmd) except Exception as e: logging.exception(e) asserts.fail("Invalid ACPIO Image") asserts.assertTrue( acpio_idx_string, "Kernel command line missing androidboot.acpio_idx") acpio_idx_list = acpio_idx_string.split(",") for idx in acpio_idx_list: temp_SSDT_dump_file = "SSDT.dump." + idx.rstrip() temp_SSDT_dump_file_hash = self.getSha1( os.path.join(self.temp_dir, temp_SSDT_dump_file)) temp_SSDT_dump_hashes.append(temp_SSDT_dump_file_hash) SSDT_path = target_file_utils.FindFiles(self.shell, SSDT_PATH, "SSDT*") for current_SSDT_file in SSDT_path: host_SSDT_file = os.path.join(self.temp_dir, current_SSDT) self.adb.pull("%s %s" % (current_SSDT_file, host_SSDT_file)) SSDT_file_hash = self.getSha1(host_SSDT_file) current_SSDT_hashes.append(SSDT_file_hash) asserts.assertTrue(current_SSDT_hashes, "No get current SSDT hash.") asserts.assertTrue( set(temp_SSDT_dump_hashes) & set(current_SSDT_hashes), "Hash is not the same.")
def testSyncQueueReadWriteWrapAround(self): """This test operates on the synchronized queue. Mirrors testcase: SynchronizedReadWriteClient, ReadWriteWrapAround1. Client writes half of the queue and server reads back. Client writes the max capacity, which will cause a wrap around in the queue, server should still read back correctly. """ num_messages = self.MAX_NUM_MSG / 2 write_data = generateSequentialData(self.MAX_NUM_MSG) # Client writes half of the queue capacity, and server reads it. asserts.assertTrue(self._sync_client.write(write_data, num_messages), "Client should write successfully.") asserts.assertTrue(self._tests_msgq.requestReadFmqSync(num_messages), "Server should read successfully.") # Client writes the max queue capacity, causes a wrap around asserts.assertTrue( self._sync_client.write(write_data, self.MAX_NUM_MSG), "Client should write successfully.") # Server reads back data correctly asserts.assertTrue( self._tests_msgq.requestReadFmqSync(self.MAX_NUM_MSG), "Server should read successfully.")
def testUnsynchronizedReadWrite(self): """Test separate read from two readers. This test operates on queue3, and tests that two readers can read back what writer writes. """ # Prepare write data. write_data = self.GetRandomFloats(2048) read_data1 = [] read_data2 = [] asserts.assertTrue( self._queue3_writer.write(write_data, 2048), "Writer should write successfully.") read_success1 = self._queue3_reader1.read(read_data1, 2048) read_success2 = self._queue3_reader2.read(read_data2, 2048) asserts.assertTrue(read_success1, "Reader 1 should read successfully.") asserts.assertTrue(read_success2, "Reader 2 should read successfully.") asserts.assertEqual(write_data, read_data1) asserts.assertEqual(write_data, read_data2)
def testUnsyncQueueSmallInputMultipleReaderTest(self): """This test operates on the unsynchronized queue. Mirrors testcase: UnsynchronizedWriteClient, SmallInputMultipleReaderTest. Server writes once, and two readers read the data back separately. """ data_len = 16 # Server writes. asserts.assertTrue(self._tests_msgq.requestWriteFmqUnsync(data_len), "Server should write successfully.") write_data = generateSequentialData(data_len) # Client 1 reads back data correctly. read_data1 = [] asserts.assertTrue(self._unsync_client1.read(read_data1, data_len), "Client 1 should read successfully.") asserts.assertEqual(write_data, read_data1) # Client 2 reads back data correctly. read_data2 = [] asserts.assertTrue(self._unsync_client2.read(read_data2, data_len), "Client 2 should read successfully.") asserts.assertEqual(write_data, read_data2)
def testAbiCompatibility(self): """Checks ABI compliance of VNDK libraries.""" primary_abi = self._dut.getCpuAbiList()[0] binder_bitness = self._dut.getBinderBitness() asserts.assertTrue(binder_bitness, "Cannot determine binder bitness.") dump_version = (self._vndk_version if self._vndk_version else vndk_data.LoadDefaultVndkVersion(self.data_file_path)) asserts.assertTrue(dump_version, "Cannot load default VNDK version.") dump_dir = vndk_data.GetAbiDumpDirectory(self.data_file_path, dump_version, binder_bitness, primary_abi, self.abi_bitness) asserts.assertTrue( dump_dir, "No dump files. version: %s ABI: %s bitness: %s" % (self._vndk_version, primary_abi, self.abi_bitness)) logging.info("dump dir: %s", dump_dir) odm_lib_dir = os.path.join(self._temp_dir, "odm_lib_dir_" + self.abi_bitness) vendor_lib_dir = os.path.join(self._temp_dir, "vendor_lib_dir_" + self.abi_bitness) system_lib_dir = os.path.join(self._temp_dir, "system_lib_dir_" + self.abi_bitness) logging.info("host lib dir: %s %s %s", odm_lib_dir, vendor_lib_dir, system_lib_dir) self._PullOrCreateDir( getattr(self, "_ODM_LIB_DIR_" + self.abi_bitness), odm_lib_dir) self._PullOrCreateDir( getattr(self, "_VENDOR_LIB_DIR_" + self.abi_bitness), vendor_lib_dir) self._PullOrCreateDir( getattr(self, "_SYSTEM_LIB_DIR_" + self.abi_bitness), system_lib_dir) error_count = self._ScanLibDirs( dump_dir, [odm_lib_dir, vendor_lib_dir, system_lib_dir], dump_version) asserts.assertEqual(error_count, 0, "Total number of errors: " + str(error_count))
def testSimpleReadWriteStructType(self): """Test read/write on queue with predefined type in HAL service. This test operates on queue 4, and tests reader and writer can interact in a queue with predefined type ReadParameters defined in IStreamIn.hal. """ write_data = [{ "command": self._stream_in_types.ReadCommand.READ, "params": { "read": 100 } }, { "command": self._stream_in_types.ReadCommand.READ, "params": { "read": 1000 } }, { "command": self._stream_in_types.ReadCommand.GET_CAPTURE_POSITION, "params": {} }] # Convert each item into a VariableSpecificationMessage using Py2Pb library. read_param_type = self._stream_in_types.GetAttribute("ReadParameters") converted_write_data = map( lambda item: py2pb.Convert(read_param_type, item), write_data) asserts.assertTrue( self._queue4_writer.write(converted_write_data, 3), "Writer should write successfully.") # Reader reads the data back, result is a list of dict. read_data = [] asserts.assertTrue( self._queue4_reader.read(read_data, 3), "Reader should read successfully.") for i in range(len(write_data)): asserts.assertTrue( self.VerifyDict(write_data[i], read_data[i]), "Dictionary item %d mismatch.", i)
def testKernelConfigs(self): """Ensures all kernel configs conform to Android requirements. Detects kernel version of device and validates against appropriate Common Android Kernel android-base.cfg and Android Treble requirements. """ logging.info("Testing existence of %s" % self.PROC_FILE_PATH) target_file_utils.assertPermissionsAndExistence( self.shell, self.PROC_FILE_PATH, target_file_utils.IsReadOnly) logging.info("Validating kernel version of device.") kernel_version = self.checkKernelVersion() # Pull configs from the universal config file. configs = dict() config_file_path = os.path.join(self.data_file_path, self.KERNEL_CONFIG_FILE_PATH, "android-" + kernel_version, "android-base.cfg") with open(config_file_path, 'r') as config_file: configs = self.parseConfigFileToDict(config_file, configs) # Pull configs from device. device_configs = dict() self.dut.adb.pull("%s %s" % (self.PROC_FILE_PATH, self._temp_dir)) logging.info("Adb pull %s to %s", self.PROC_FILE_PATH, self._temp_dir) localpath = os.path.join(self._temp_dir, "config.gz") with gzip.open(localpath, "rb") as device_config_file: device_configs = self.parseConfigFileToDict( device_config_file, device_configs) # Check device architecture and pull arch-specific configs. kernelArch = self.checkKernelArch(device_configs) if kernelArch is not "": config_file_path = os.path.join(self.data_file_path, self.KERNEL_CONFIG_FILE_PATH, "android-" + kernel_version, "android-base-%s.cfg" % kernelArch) if os.path.isfile(config_file_path): with open(config_file_path, 'r') as config_file: configs = self.parseConfigFileToDict(config_file, configs) # Determine any deviations from the required configs. should_be_enabled = [] should_not_be_set = [] incorrect_config_state = [] for config_name, config_state in configs.iteritems(): if (config_state == "y" and (config_name not in device_configs or device_configs[config_name] not in ("y", "m"))): should_be_enabled.append(config_name) elif (config_state == "n" and (config_name in device_configs) and device_configs[config_name] != "n"): should_not_be_set.append(config_name + "=" + device_configs[config_name]) elif (config_name in device_configs and device_configs[config_name] != config_state): incorrect_config_state.append(config_name + "=" + device_configs[config_name]) if ("CONFIG_OF" not in device_configs and "CONFIG_ACPI" not in device_configs): should_be_enabled.append("CONFIG_OF | CONFIG_ACPI") asserts.assertTrue( len(should_be_enabled) == 0 and len(should_not_be_set) == 0 and len(incorrect_config_state) == 0, ("The following kernel configs should be enabled: [%s]\n" "The following kernel configs should not be set: [%s]\n" "THe following kernel configs have incorrect state: [%s]") % (", ".join(should_be_enabled), ", ".join(should_not_be_set), ", ".join(incorrect_config_state)))
def execOneTest(self, test_name, test_func, args, **kwargs): """Executes one test case and update test results. Executes one test case, create a records.TestResultRecord object with the execution information, and add the record to the test class's test results. Args: test_name: Name of the test. test_func: The test function. args: A tuple of params. kwargs: Extra kwargs. """ is_silenced = False tr_record = records.TestResultRecord(test_name, self.test_module_name) tr_record.testBegin() logging.info("%s %s", TEST_CASE_TOKEN, test_name) verdict = None finished = False try: ret = self._testEntry(tr_record) asserts.assertTrue(ret is not False, "Setup test entry for %s failed." % test_name) self.filterOneTest(test_name) if self.collect_tests_only: asserts.explicitPass("Collect tests only.") try: ret = self._setUp(test_name) asserts.assertTrue(ret is not False, "Setup for %s failed." % test_name) if args or kwargs: verdict = test_func(*args, **kwargs) else: verdict = test_func() finished = True finally: self._tearDown(test_name) except (signals.TestFailure, acts_signals.TestFailure, AssertionError) as e: tr_record.testFail(e) self._exec_procedure_func(self._onFail) finished = True except (signals.TestSkip, acts_signals.TestSkip) as e: # Test skipped. tr_record.testSkip(e) self._exec_procedure_func(self._onSkip) finished = True except (signals.TestAbortClass, acts_signals.TestAbortClass) as e: # Abort signals, pass along. tr_record.testFail(e) finished = True raise signals.TestAbortClass, e, sys.exc_info()[2] except (signals.TestAbortAll, acts_signals.TestAbortAll) as e: # Abort signals, pass along. tr_record.testFail(e) finished = True raise signals.TestAbortAll, e, sys.exc_info()[2] except (signals.TestPass, acts_signals.TestPass) as e: # Explicit test pass. tr_record.testPass(e) self._exec_procedure_func(self._onPass) finished = True except (signals.TestSilent, acts_signals.TestSilent) as e: # Suppress test reporting. is_silenced = True self._exec_procedure_func(self._onSilent) self.results.removeRecord(tr_record) finished = True except Exception as e: # Exception happened during test. logging.exception(e) tr_record.testError(e) self._exec_procedure_func(self._onException) self._exec_procedure_func(self._onFail) finished = True else: # Keep supporting return False for now. # TODO(angli): Deprecate return False support. if verdict or (verdict is None): # Test passed. tr_record.testPass() self._exec_procedure_func(self._onPass) return # Test failed because it didn't return True. # This should be removed eventually. tr_record.testFail() self._exec_procedure_func(self._onFail) finished = True finally: if not finished: for device in self.android_devices: # if shell has not been set up yet if device.shell is not None: device.shell.DisableShell() logging.error('Test timed out.') tr_record.testError() self._exec_procedure_func(self._onException) self._exec_procedure_func(self._onFail) if not is_silenced: self.results.addRecord(tr_record) self._testExit()
def testDeviceTotalMem(self): '''Test AndroidDevice class total_memory getter function''' asserts.assertTrue(self.dut.total_memory > 0, 'Failed to get device memory info.')