예제 #1
0
 def test_reboot(self):
     """Reboots all devices in the testbed."""
     for device in self.devices:
         device.reboot()
         asserts.assert_true(
             device.connected,
             f"Device {device.name} did not come back online after reboot")
예제 #2
0
    def assert_none_matching(
        self, match_fn, timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)):
        """
        Assert no events where match_fn(event) is True happen within timeout
        period

        :param match_fn: return True/False on match_fn(event)
        :param timeout: a timedelta object
        :return:
        """
        logging.debug("assert_none_matching %fs" % (timeout.total_seconds()))
        event = None
        end_time = datetime.now() + timeout
        while event is None and datetime.now() < end_time:
            remaining = self.remaining_time_delta(end_time)
            logging.debug("Waiting for event (%fs remaining)" %
                          (remaining.total_seconds()))
            try:
                current_event = self.event_queue.get(
                    timeout=remaining.total_seconds())
                if match_fn(current_event):
                    event = current_event
            except Empty:
                continue
        logging.debug("Done waiting for an event")
        if event is None:
            return  # Avoid an assert in MessageToString(None, ...)
        asserts.assert_true(
            event is None,
            msg=("Expected None matching, but got %s" %
                 text_format.MessageToString(event, as_one_line=True)))
예제 #3
0
 def _verify_logging(self):
     log_file = self.device.log_file_name
     asserts.assert_true(os.path.exists(log_file),
                         "Failed to initiate the log file")
     asserts.assert_true(
         os.stat(log_file).st_size > 0,
         "{} is not logging".format(self.device.name))
예제 #4
0
def ReliableWrite(client, server):
  """Logic for BLE reliable write.

  Args:
    client: AndroidDevice. The device that behaves as GATT client.
    server: AndroidDevice. The device that behaves as GATT server.

  Steps:
    1. Client calls beginReliableWrite & gets true.
    2. Client writes a characteristic to server & gets true.
    3. Server calls sendResponse & client gets onCharacteristicWrite.
    4. Client calls executeReliableWrite & gets true
    5. Server calls sendResponse & client gets onReliableWriteCompleted.

  Verifies:
    Client get corresponding callbacks.
  """
  begin_reliable_write_result = client.android.bleBeginReliableWrite()
  asserts.assert_true(begin_reliable_write_result,
                      'BLE reliable write failed to start')
  client.log.info('BLE reliable write started')
  WriteCharacteristic(client, server)
  execute_reliable_write_result = client.android.bleExecuteReliableWrite()
  asserts.assert_true(execute_reliable_write_result,
                      'BLE reliable write failed to execute')
  client.log.info('BLE reliable write execute started')
  client.client_callback.waitAndGet('onReliableWriteCompleted', 30)
  client.log.info('BLE reliable write finished')
예제 #5
0
def WriteCharacteristic(client, server):
  """Logic for BLE characteristic write.

  Args:
    client: AndroidDevice. The device that behaves as GATT client.
    server: AndroidDevice. The device that behaves as GATT server.

  Steps:
    1. Client writes a characteristic to server & gets true.
    2. Server calls sendResponse & client gets onCharacteristicWrite.

  Verifies:
    Client gets corresponding callback.
  """
  write_operation_result = client.android.bleWriteOperation(
      TEST_BLE_SERVICE_UUID, TEST_WRITE_UUID, WRITE_DATA)
  asserts.assert_true(write_operation_result,
                      'BLE write operation failed to start')
  server_write_operation_result = server.server_callback.waitAndGet(
      'onCharacteristicWriteRequest', 30)
  asserts.assert_equal(server_write_operation_result.data['Data'], WRITE_DATA)
  client.client_callback.waitAndGet('onCharacteristicWrite', 30)
  client.log.info('Write operation finished')
  write_operation_result = client.android.bleWriteOperation(
      TEST_BLE_SERVICE_UUID, TEST_SECOND_WRITE_UUID, SECOND_WRITE_DATA)
  asserts.assert_true(write_operation_result,
                      'BLE write operation failed to start')
  server_write_operation_result = server.server_callback.waitAndGet(
      'onCharacteristicWriteRequest', 30)
  asserts.assert_equal(server_write_operation_result.data['Data'],
                       SECOND_WRITE_DATA)
  client.client_callback.waitAndGet('onCharacteristicWrite', 30)
  client.log.info('Second write operation finished')
예제 #6
0
 def test_example(self):
     for device in self.devices:
         device.reboot()
         asserts.assert_true(
             device.is_connected(),
             "Device {} did not come back up after reboot".format(
                 device.name))
예제 #7
0
def NOT_FOR_YOU_assert_event_occurs(
    istream,
    match_fn,
    at_least_times=1,
    timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)):
    logging.debug("assert_event_occurs %d %fs" %
                  (at_least_times, timeout.total_seconds()))
    event_list = []
    end_time = datetime.now() + timeout
    while len(event_list) < at_least_times and datetime.now() < end_time:
        remaining = static_remaining_time_delta(end_time)
        logging.debug("Waiting for event (%fs remaining)" %
                      (remaining.total_seconds()))
        try:
            current_event = istream.get_event_queue().get(
                timeout=remaining.total_seconds())
            logging.debug("current_event: %s", current_event)
            if match_fn(current_event):
                event_list.append(current_event)
        except Empty:
            continue
    logging.debug("Done waiting for event, received %d", len(event_list))
    asserts.assert_true(len(event_list) >= at_least_times,
                        msg=("Expected at least %d events, but got %d" %
                             (at_least_times, len(event_list))))
    def test_5502_send_file_to_device(self):
        device_dir = self._get_writable_directory()

        local_file_path = os.path.join(self.log_path,
                                       "send_file_to_device.txt")
        catch_phrase = "The quick brown dog jumps over the lazy fox"
        with open(local_file_path, 'w') as open_file:
            open_file.write(catch_phrase + "\n")
        output = subprocess.check_output(["cat",
                                          local_file_path]).decode("utf-8")
        asserts.assert_true(
            catch_phrase in output,
            "writing to local file did not work. Unable to set up test. Output: {}"
            .format(output))
        try:
            device_path = os.path.join(device_dir, "send_file_to_device.txt")
            self.device.file_transfer.send_file_to_device(
                local_file_path, device_dir)
            output = self.device.shell("cat " + device_path)
            asserts.assert_true(
                catch_phrase in output,
                "Expected catchphrase in transferred file, got: {}".format(
                    output))

        finally:
            self.device.shell("rm " + device_path)
            os.remove(local_file_path)
예제 #9
0
    def test_local_hotspot_process(self):
        """Test for basic local hotspot process flow.

    Steps:
      1. Ap sets up a local hotspot and retrieves the credentials.
      2. Station connects to the hotspot.

    Verifies:
      Station can connect to the local hotspot created by ap.
    """
        wifi_on_before = self.ap.android.wifiIsEnabled()
        start_localhotspot_callback = self.ap.android.startLocalHotspot()
        start_result = start_localhotspot_callback.waitAndGet('onStarted', 30)
        local_hotspot_info = start_result.data
        self.ap.log.info('Local hotspot started')
        network_found = self.station.android.wifiScanAndFindSsid(
            local_hotspot_info[SSID], SCAN_TIMEOUT)
        asserts.assert_true(network_found,
                            'Network is not found within 30 seconds')
        self.station.android.wifiConnectByUpdate(
            local_hotspot_info[SSID], local_hotspot_info['Password'])
        self.station.log.info('Connected to the network %s.' %
                              local_hotspot_info[SSID])
        self.ap.android.stopLocalHotspot()
        time.sleep(RESTORE_TIME)
        wifi_on_after = self.ap.android.wifiIsEnabled()
        asserts.assert_equal(wifi_on_before, wifi_on_after)
        self.ap.log.info('Wifi state restored')
예제 #10
0
    def test_wifi_direct_legacy_connection(self):
        """Test for basic Wifi Direct process flow.

    Steps:
      1. Group owner sets up a wifi p2p group.
      2. Station connects to the group as a regular hotspot.

    Verifies:
      Station can connect to the wifi p2p group created by group owner.
    """
        callback = self.group_owner.android.wifiP2pSetChannel(CHANNEL, CHANNEL)
        assert_utils.AssertAsyncSuccess(callback)
        self.group_owner.log.info('Wifi direct channel set.')
        callback = self.group_owner.android.wifiP2pStartGroup()
        group_info = assert_utils.AssertAsyncSuccess(callback)
        self.group_owner.log.info(
            'Wifi direct group started as a temporary group.')
        network_found = self.station.android.wifiScanAndFindSsid(
            group_info.data[SSID], SCAN_TIMEOUT)
        asserts.assert_true(network_found,
                            'Network is not found within 30 seconds')
        asserts.assert_equal(network_found['frequency'], FREQUENCY)
        self.station.log.info('Network is found, connecting...')
        connect_result = self.station.android.wifiConnectByUpdate(
            group_info.data[SSID], group_info.data['Password'])
        asserts.assert_true(connect_result, 'Failed to connect to the network')
        self.station.log.info('Connected to the network')
        callback = self.group_owner.android.wifiP2pRemoveGroup()
        assert_utils.AssertAsyncSuccess(callback)
        self.group_owner.log.info('Wifi direct group removed')
예제 #11
0
    def assert_event_occurs_at_most(
        self,
        match_fn,
        at_most_times,
        timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)):
        """
        Assert at most |at_most_times| instances of events happen where
        match_fn(event) returns True within timeout period

        :param match_fn: returns True/False on match_fn(event)
        :param at_most_times: how many times at most a matching event should
                               happen
        :param timeout:a timedelta object
        :return:
        """
        logging.debug("assert_event_occurs_at_most")
        event_list = []
        end_time = datetime.now() + timeout
        while len(event_list) <= at_most_times and datetime.now() < end_time:
            remaining = static_remaining_time_delta(end_time)
            logging.debug("Waiting for event iteration (%fs remaining)" %
                          (remaining.total_seconds()))
            try:
                current_event = self.event_queue.get(
                    timeout=remaining.total_seconds())
                if match_fn(current_event):
                    event_list.append(current_event)
            except Empty:
                continue
        logging.debug("Done waiting, got %d events" % len(event_list))
        asserts.assert_true(len(event_list) <= at_most_times,
                            msg=("Expected at most %d events, but got %d" %
                                 (at_most_times, len(event_list))))
예제 #12
0
    def test_1117_get_event_related_methods_return_appropriate_results(self):
        """Verify Parser accepts valid event label for get_last_event* methods.
        """

        event_data = self.device.event_parser.get_last_event(
            ["optional_description.my_message"])
        asserts.assert_false(
            event_data.results_list,
            "Expecting empty list for 'optional_description.my_message' "
            "event label but found {!r} instead.".format(event_data))

        event_data = self.device.event_parser.get_last_event()
        asserts.assert_false(event_data.timedout,
                             "Expecting EventResult with .timedout == False")

        event_history = self.device.event_parser.get_event_history(
            ["optional_description.my_message"])
        asserts.assert_false(
            event_history.results_list, "Expecting empty list for history of "
            "'optional_description.my_message' event label "
            "but found {!r} instead.".format(event_history))

        event_history = self.device.event_parser.get_event_history(count=1)
        asserts.assert_false(event_data.timedout,
                             "Expecting EventResult with .timedout == False")

        event_history_count = self.device.event_parser.get_event_history_count(
            "optional_description.my_message")
        asserts.assert_true(
            event_history_count.count == 0,
            "Expecting event history count of 0 for "
            "'optional_description.my_message' event label "
            "but found {} instead.".format(event_history_count))
    def test_01_list_packages(self):
        """Verify the capability to list all packages on a device."""

        packages_on_device = self.device.package_management.list_packages()
        # Not sure what packages are on device, but guaranteed to be not empty.
        asserts.assert_true(packages_on_device,
                            'Cannot list packages on the device.')
예제 #14
0
 def test_1002_get_serial_number(self):
     try:
         asserts.assert_true(self.device.serial_number is not None,
                             "serial number should not be None")
     except Exception:
         traceback_message = traceback.format_exc()
         asserts.fail("Error happened during get serial number: " +
                      traceback_message)
예제 #15
0
 def _verify_firmware_version(self):
     try:
         asserts.assert_true(self.device.firmware_version is not None,
                             "firmware version should not be None")
     except Exception:
         traceback_message = traceback.format_exc()
         asserts.fail("Error happened during get firmware version: " +
                      traceback_message)
예제 #16
0
 def _test_100_enable(self):
     """Test case for enable()"""
     try:
         self.device.ethernet_switch_api.enable()
         asserts.assert_true(self.device.ethernet_switch_api.status,
                             "status should be True")
     except Exception:
         traceback_message = traceback.format_exc()
         asserts.fail("Error happened during lock: " + traceback_message)
 def test_hello(self):
     expected = "hello!"
     status, payload = self.dut.rpcs().EchoService.Echo(msg=expected)
     asserts.assert_true(status.ok(), "Status is %s" % status)
     asserts.assert_equal(
         payload.msg,
         expected,
         'Returned payload is "%s" expected "%s"' % (payload.msg, expected),
     )
 def test_1003_get_ftdi_serial_number(self):
     if hasattr(type(self.device), "ftdi_serial_number"):
         try:
             asserts.assert_true(self.device.ftdi_serial_number is not None,
                                 "ftdi serial number should not be None")
         except Exception:
             traceback_message = traceback.format_exc()
             asserts.fail("Error happened during get ftdi serial number: " +
                          traceback_message)
 def test_1005_get_build_date(self):
     if hasattr(type(self.device), "build_date"):
         try:
             asserts.assert_true(self.device.build_date is not None,
                                 "build date should not be None")
         except Exception:
             traceback_message = traceback.format_exc()
             asserts.fail("Error happened during get build date: " +
                          traceback_message)
예제 #20
0
 def _verify_boot_up_log(self, start_time):
     parser_result = self.device.event_parser.get_last_event(
         ["basic.bootup"])
     asserts.assert_true(parser_result.count > 0,
                         "Error: event label 'basic.bootup' not found.")
     timestamp = parser_result.results_list[0]["system_timestamp"]
     asserts.assert_true(
         timestamp > start_time,
         "Expected basic bootup timestamp {} to be > start time {}".format(
             timestamp, start_time))
예제 #21
0
def NOT_FOR_YOU_assert_none(
    istream, timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)):
    logging.debug("assert_none %fs" % (timeout.total_seconds()))
    try:
        event = istream.get_event_queue().get(timeout=timeout.total_seconds())
        asserts.assert_true(event is None,
                            msg='Expected None, but got {}'.format(
                                pretty_print(event)))
    except Empty:
        return
예제 #22
0
def NOT_FOR_YOU_assert_none(
    istream, timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)):
    logging.debug("assert_none %fs" % (timeout.total_seconds()))
    try:
        event = istream.get_event_queue().get(timeout=timeout.total_seconds())
        asserts.assert_true(
            event is None,
            msg=("Expected None, but got %s" %
                 text_format.MessageToString(event, as_one_line=True)))
    except Empty:
        return
예제 #23
0
 def test_1000_close_device(self):
     self.logger.info("Testing close device stops logging")
     log_file = self.device.log_file_name
     asserts.assert_true(os.path.exists(log_file),
                         "Cannot test close as device is not logging")
     self.device.close()
     time.sleep(1)
     size = os.stat(log_file).st_size
     time.sleep(.1)
     asserts.assert_true(size == os.stat(log_file).st_size,
                         "Log has updated after device is closed")
예제 #24
0
 def test_1016_do_and_expect_some_func_is_called(self):
     switch = PowerSwitch()
     expect_result = self.device.switchboard.do_and_expect(
         turn_everything_on, [[switch]], {},
         ["fake_string, won't match anything"],
         timeout=.1)
     asserts.assert_true(
         expect_result.timedout,
         "Expected do_and_expect to timeout, but timedout was False")
     asserts.assert_true(
         switch.power_is_on, "turn_everything_on function did not execute, "
         "the power state is still off for switch.")
예제 #25
0
def CancelOpen(client, server):
  """Logic for BLE client cancel open and reconnect.

  Args:
    client: AndroidDevice. The device that behaves as GATT client.
    server: AndroidDevice. The device that behaves as GATT server.

  Steps:
    1. Server starts and service added properly.
    2. Client stars to connect to server via Gatt, but the connection has not
    been established.
    3. Client calls disconnect to cancel the connection.
    4. Client connects to server, connection completes with GATT_SUCCESS within
    some TIMEOUT, onConnectionStateChange/STATE_CONNECTEDcalled EXACTLY once.

  Verifies:
    Client gets corresponding callback.
  """
  server.server_callback = server.android.bleStartServer([SERVICE])
  start_server_result = server.server_callback.waitAndGet('onServiceAdded', 30)
  asserts.assert_equal(start_server_result.data[STATUS], GATT_SUCCESS)
  uuids = [
      characteristic[UUID]
      for characteristic in start_server_result.data['Service'][
          'Characteristics']
  ]
  for uuid in [
      characteristic[UUID] for characteristic in SERVICE['Characteristics']
  ]:
    asserts.assert_true(uuid in uuids, 'Failed to find uuid %s.' % uuid)
  server.log.info('BLE server started')
  client.client_callback = client.android.bleConnectGatt(
      client.connect_to_address)
  time.sleep(CANCEL_CONNECTION_WAIT_TIME)
  start_client_results = client.client_callback.getAll(
      'onConnectionStateChange')
  if not start_client_results:
    client.android.bleDisconnect()
    client.log.info('BLE client cancel open')
    time.sleep(CANCEL_CONNECTION_WAIT_TIME)
    client.client_callback = client.android.bleConnectGatt(
        client.connect_to_address)
    time.sleep(CONNECTION_TIMEOUT)
    start_client_results = client.client_callback.getAll(
        'onConnectionStateChange')
    asserts.assert_equal(len(start_client_results), 1)
    for start_client_result in start_client_results:
      asserts.assert_equal(start_client_result.data[STATUS], GATT_SUCCESS)
      asserts.assert_equal(start_client_result.data[STATE], 'STATE_CONNECTED')
      client.log.info('BLE client connected')
예제 #26
0
 def _verify_expect_log(self):
     self.logger.info("Expecting logline {!r}".format(
         self.test_config["known_logline"]))
     try:
         res = self.device.switchboard.expect(
             [self.test_config["known_logline"]], timeout=30)
     except Exception:
         traceback_message = traceback.format_exc()
         asserts.fail("Error happened during expect: " + traceback_message)
     asserts.assert_true(res.index is not None, "Expect returned None")
     asserts.assert_true(
         res.index == 0,
         "Phrase {} should have been found in the log lines".format(
             self.test_config["known_logline"]))
    def test_device_power_on_off(self):
        """Verifies on and off works."""
        original_mode = self.device.device_power.port_mode

        try:
            self.device.device_power.off()
            asserts.assert_equal(self.device.device_power.port_mode, "off",
                                 f'{self.device.name} port {self.device.device_power.port_number} should have been set to off')
            self.device.device_power.on()
            asserts.assert_true(self.device.device_power.port_mode in ["on", "charge", "sync"],
                                f'{self.device.name} port {self.device.device_power.port_number} should have been set to on')
        finally:
            if original_mode == "off":
                self.logger.info("restoring device power back to its original mode of off")
                self.device.device_power.off()
예제 #28
0
    def test_4500_port_map_finds_device(self):
        """Verifies the device is in the port map."""
        device_name = self.device.name
        port_map = self.manager.port_map()
        device_found = False
        for device_or_hub in port_map:
            if device_or_hub['hub_device']:
                for device in device_or_hub['port_list']:
                    if device and device_name in device['Discovered']:
                        device_found = True
            else:
                if device_name in device_or_hub['Discovered']:
                    device_found = True

        asserts.assert_true(device_found,
                            "device {} was not found by port-map.".format(device_name))
예제 #29
0
    def assert_none(self, timeout=timedelta(seconds=DEFAULT_TIMEOUT_SECONDS)):
        """
        Assert no event happens within timeout period

        :param timeout: a timedelta object
        :return:
        """
        logging.debug("assert_none %fs" % (timeout.total_seconds()))
        try:
            event = self.event_queue.get(timeout=timeout.total_seconds())
            asserts.assert_true(
                event is None,
                msg=("Expected None, but got %s" %
                     text_format.MessageToString(event, as_one_line=True)))
        except Empty:
            return
예제 #30
0
파일: expects.py 프로젝트: yxususe/mobly
def expect_true(condition, msg, extras=None):
    """Expects an expression evaluates to True.

    If the expectation is not met, the test is marked as fail after its
    execution finishes.

    Args:
        expr: The expression that is evaluated.
        msg: A string explaining the details in case of failure.
        extras: An optional field for extra information to be included in test
            result.
    """
    try:
        asserts.assert_true(condition, msg, extras)
    except signals.TestSignal as e:
        logging.exception('Expected a `True` value, got `False`.')
        recorder.add_error(e)