def test_list_interfaces(self):
        """Test listing all interfaces.

        Steps:
        1. Call ListInterfaces FIDL api.
        2. Verify there is at least one interface returned.

        Expected Result:
        There were no errors in retrieving the list of interfaces.
        There was at least one interface in the list.

        Returns:
          signals.TestPass if no errors
          signals.TestFailure if there are any errors during the test.

        TAGS: Netstack
        Priority: 1
        """
        interfaces = self.dut.netstack_lib.netstackListInterfaces()
        if interfaces.get('error') is not None:
            raise signals.TestFailure("Failed with {}".format(
                interfaces.get('error')))
        if len(interfaces.get('result')) < 1:
            raise signals.TestFailure("No interfaces found.")
        self.log.info("Interfaces found: {}".format(interfaces.get('result')))
        raise signals.TestPass("Success")
 def _orchestrate_single_connect_disconnect(self):
     adv_name = generate_id_by_size(10)
     adv_data = {
         "name": adv_name,
         "appearance": None,
         "service_data": None,
         "tx_power_level": None,
         "service_uuids": None,
         "manufacturer_data": None,
         "uris": None,
     }
     scan_response = None
     connectable = True
     self.fuchsia_server_dut.ble_lib.bleStartBleAdvertising(
         adv_data, scan_response, self.ble_advertise_interval, connectable)
     device = le_scan_for_device_by_name(self.fuchsia_client_dut, self.log,
                                         adv_name,
                                         self.scan_timeout_seconds)
     if device is None:
         raise signals.TestFailure("Scanner unable to find advertisement.")
     connect_result = self.fuchsia_client_dut.gattc_lib.bleConnectToPeripheral(
         device["id"])
     if connect_result.get("error") is not None:
         raise signals.TestFailure(
             self.gatt_connect_err_message.format(
                 connect_result.get("error")))
     self.log.info("Connection Successful...")
     disconnect_result = self.fuchsia_client_dut.gattc_lib.bleDisconnectPeripheral(
         device["id"])
     if disconnect_result.get("error") is not None:
         raise signals.TestFailure(
             self.gatt_disconnect_err_message.format(
                 connect_result.get("error")))
     self.log.info("Disconnection Successful...")
     self.fuchsia_server_dut.ble_lib.bleStopBleAdvertising()
Exemplo n.º 3
0
    def test_multi_downloads(self):
        download_urls = [self.url_20MB, self.url_40MB, self.url_60MB]
        download_threads = []

        try:
            # Start multiple downloads at the same time
            for index, url in enumerate(download_urls):
                self.log.info('Create and start thread %d.' % index)
                t = threading.Thread(target=self.download_thread, args=(url, ))
                download_threads.append(t)
                t.start()

            # Wait for all threads to complete or timeout
            for t in download_threads:
                t.join(self.download_timeout_s)

        finally:
            is_alive = False

            for index, t in enumerate(download_threads):
                if t.isAlive():
                    t = None
                    is_alive = True

            if is_alive:
                raise signals.TestFailure('Thread %d timedout' % index)

        for index in range(0, len(self.download_threads_result)):
            if not self.download_threads_result[index]:
                self.log.info("Download failed for %d" % index)
                raise signals.TestFailure(
                    'Thread %d failed to download' % index)
                return False

        return True
    def check_networks_after_autoupdate(self, networks):
        """Verify that all previously configured networks are presistent after
           reboot.

        Args:
            networks: List of network dicts.

        Return:
            None. Raises TestFailure.

        """
        network_info = self.dut.droid.wifiGetConfiguredNetworks()
        if len(network_info) != len(networks):
            msg = (
                "Number of configured networks before and after Auto-update "
                "don't match. \nBefore reboot = %s \n After reboot = %s" %
                (networks, network_info))
            raise signals.TestFailure(msg)
        current_count = 0
        # For each network, check if it exists in configured list after Auto-
        # update.
        for network in networks:
            exists = wutils.match_networks(
                {WifiEnums.SSID_KEY: network[WifiEnums.SSID_KEY]},
                network_info)
            if not len(exists):
                raise signals.TestFailure(
                    "%s network is not present in the"
                    " configured list after Auto-update" %
                    network[WifiEnums.SSID_KEY])
            # Get the new network id for each network after reboot.
            network[WifiEnums.NETID_KEY] = exists[0]['networkId']
def verify_wifi_connection_info(ad, expected_con):
    """Verifies that the information of the currently connected wifi network is
    as expected.

    Args:
        expected_con: A dict representing expected key-value pairs for wifi
            connection. e.g. {"SSID": "test_wifi"}
    """
    current_con = ad.droid.wifiGetConnectionInfo()
    case_insensitive = ["BSSID", "supplicant_state"]
    ad.log.debug("Current connection: %s", current_con)
    for k, expected_v in expected_con.items():
        # Do not verify authentication related fields.
        if k == "password":
            continue
        msg = "Field %s does not exist in wifi connection info %s." % (
            k, current_con)
        if k not in current_con:
            raise signals.TestFailure(msg)
        actual_v = current_con[k]
        if k in case_insensitive:
            actual_v = actual_v.lower()
            expected_v = expected_v.lower()
        msg = "Expected %s to be %s, actual %s is %s." % (k, expected_v, k,
                                                          actual_v)
        if actual_v != expected_v:
            raise signals.TestFailure(msg)
Exemplo n.º 6
0
    def connect_to_network(self, wlan_network_params, fd):
        """ Connects the Fuchsia device to the specified network

        Args:
            wlan_network_params: A dictionary containing wlan information.
            fd: A fuchsia device

        Raises:
            signals.TestFailure: if the device fails to connect
        """
        target_ssid = wlan_network_params["SSID"]
        target_pwd = wlan_network_params.get("password")
        # TODO(mnck): use the Policy version of this call, when it is available.
        connection_response = fd.wlan_lib.wlanConnectToNetwork(
            target_ssid, target_pwd)
        if connection_response.get("error") is None:
            # the command did not get an error response - go ahead and
            # check the result
            connection_result = connection_response.get("result")
            if connection_result:
                self.log.info("connection to network successful")
            else:
                # ideally, we would have the actual error...  but logging
                # here to cover that error case
                raise signals.TestFailure("Connect call failed, aborting test")
        else:
            # the response indicates an error - log and raise failure
            raise signals.TestFailure("Aborting test - Connect call failed "
                                      "with error: %s" %
                                      connection_response.get("error"))
Exemplo n.º 7
0
    def run_iperf_tx_rx(self, usb_speed, criteria):
        """Run iperf tx and rx.

        Args:
            usb_speed: string which contains the speed info.
            criteria: usb performance criteria.

        Raises:
            Signals.TestFailure is raised by usb tethering under criteria.
        """
        self.enable_usb_tethering()
        self.dut.adb.wait_for_device()
        self.ip_server.start()
        pc_ip = self.get_pc_tethering_ip()
        tx_success, tx_rate, tx_unit = self.run_iperf_client(
            pc_ip, '-t{} -i1 -w2M'.format(self.iperf_test_sec))
        rx_success, rx_rate, rx_unit = self.run_iperf_client(
            pc_ip, '-t{} -i1 -w2M -R'.format(self.iperf_test_sec))
        self.log.info('TestResult iperf_{}_rx'.format(usb_speed) + rx_rate +
                      ' ' + rx_unit + 'bits/sec')
        self.log.info('TestResult iperf_{}_tx'.format(usb_speed) + tx_rate +
                      ' ' + tx_unit + 'bits/sec')
        self.ip_server.stop()
        if not tx_success or (float(tx_rate) < criteria and tx_unit != "G"):
            raise signals.TestFailure('Iperf {}_tx test is {} {}bits/sec, '
                                      'the throughput result failed.'.format(
                                          usb_speed, tx_rate, tx_unit))
        if not rx_success or (float(rx_rate) < criteria and rx_unit != "G"):
            raise signals.TestFailure('Iperf {}_rx test is {} {}bits/sec, '
                                      'the throughput result failed.'.format(
                                          usb_speed, rx_rate, rx_unit))
Exemplo n.º 8
0
    def test_mac_randomization_multiple_networks(self):
        """Connect to multiple networks and verify same MAC.

        Steps:
            1. Connect to network A, get randomizd MAC.
            2. Conenct to network B, get randomized MAC.
            3. Connect back to network A and verify same MAC.
            4. Connect back to network B and verify same MAC.

        """
        mac_list = list()

        # Connect to two different networks and get randomized MAC addresses.
        self.verify_mac_randomization_and_add_to_list(self.wpapsk_2g, mac_list)
        self.verify_mac_randomization_and_add_to_list(self.open_2g, mac_list)

        # Connect to the previous network and check MAC is persistent.
        mac_wpapsk = self.connect_to_network_and_verify_mac_randomization(
            self.wpapsk_2g)
        msg = (
            'Randomized MAC is not persistent for this network %s. Old MAC = '
            '%s \nNew MAC = %s')
        if mac_wpapsk != mac_list[0]:
            raise signals.TestFailure(
                msg % (self.wpapsk_5g, mac_list[0], mac_wpapsk))
        mac_open = self.connect_to_network_and_verify_mac_randomization(
            self.open_2g)
        if mac_open != mac_list[1]:
            raise signals.TestFailure(msg %
                                      (self.open_5g, mac_list[1], mac_open))
Exemplo n.º 9
0
    def test_roaming_mac_randomization(self):
        """test MAC randomization in the roaming scenario.

        Steps:
            1. Connect to network A on AP1, get randomized MAC.
            2. Set AP1 to MAX attenuation so that we roam to AP2.
            3. Wait for device to roam to AP2 and get randomized MAC.
            4. Veirfy that the device uses same AMC for both APs.

        """
        AP1_network = self.reference_networks[0]["5g"]
        AP2_network = self.reference_networks[1]["5g"]
        wutils.set_attns(self.attenuators, "AP1_on_AP2_off")
        mac_before_roam = self.connect_to_network_and_verify_mac_randomization(
            AP1_network)
        wutils.trigger_roaming_and_validate(self.dut, self.attenuators,
                                            "AP1_off_AP2_on", AP2_network)
        mac_after_roam = self.get_randomized_mac(AP2_network)
        if mac_after_roam != mac_before_roam:
            raise signals.TestFailure(
                "Randomized MAC address changed after "
                "roaming from AP1 to AP2.\nMAC before roam = %s\nMAC after "
                "roam = %s" % (mac_before_roam, mac_after_roam))
        wutils.trigger_roaming_and_validate(self.dut, self.attenuators,
                                            "AP1_on_AP2_off", AP1_network)
        mac_after_roam = self.get_randomized_mac(AP1_network)
        if mac_after_roam != mac_before_roam:
            raise signals.TestFailure(
                "Randomized MAC address changed after "
                "roaming from AP1 to AP2.\nMAC before roam = %s\nMAC after "
                "roam = %s" % (mac_before_roam, mac_after_roam))
    def add_suggestions_and_ensure_connection(self, network_suggestions,
                                              expected_ssid,
                                              expect_post_connection_broadcast):
        if expect_post_connection_broadcast is not None:
            self.dut.droid.wifiStartTrackingNetworkSuggestionStateChange()

        self.dut.log.info("Adding network suggestions");
        asserts.assert_true(
            self.dut.droid.wifiAddNetworkSuggestions(network_suggestions),
            "Failed to add suggestions")
        # Enable suggestions by the app.
        self.dut.log.debug("Enabling suggestions from test");
        self.set_approved(True)
        wutils.start_wifi_connection_scan_and_return_status(self.dut)
        wutils.wait_for_connect(self.dut, expected_ssid)

        if expect_post_connection_broadcast is None:
            return;

        # Check if we expected to get the broadcast.
        try:
            event = self.dut.ed.pop_event(
                wifi_constants.WIFI_NETWORK_SUGGESTION_POST_CONNECTION, 60)
        except queue.Empty:
            if expect_post_connection_broadcast:
                raise signals.TestFailure(
                    "Did not receive post connection broadcast")
        else:
            if not expect_post_connection_broadcast:
                raise signals.TestFailure(
                    "Received post connection broadcast")
        finally:
            self.dut.droid.wifiStopTrackingNetworkSuggestionStateChange()
        self.dut.ed.clear_all_events()
    def basic_scan_request(self, fd):
        """ Initiates a basic scan on a Fuchsia device
            Args:
                fd: A fuchsia device
        """
        start_time = datetime.now()

        scan_response = fd.wlan_lib.wlanStartScan()

        # first check if we received an error
        if scan_response.get("error") is None:
            # the scan command did not get an error response - go ahead
            # and check for scan results
            scan_results = scan_response["result"]
        else:
            # the response indicates an error - log and raise failure
            raise signals.TestFailure("Aborting test - scan failed with "
                                      "error: %s" % scan_response.get("error"))

        self.log.info("scan contained %d results", len(scan_results))

        total_time_ms = (datetime.now() - start_time).total_seconds() * 1000
        self.log.info("scan time: %d ms", total_time_ms)

        if len(scan_results) > 0:
            raise signals.TestPass(details="",
                                   extras={"Scan time": "%d" % total_time_ms})
        else:
            raise signals.TestFailure("Scan failed or did not "
                                      "find any networks")
Exemplo n.º 12
0
def avrcp_actions(pri_ad, buds_device):
    """Performs avrcp controls like volume up, volume down

    Args:
        pri_ad: Android device.
        buds_device: serial device object to perform avrcp actions.

    Returns:
        True if successful, otherwise otherwise raises Exception. 
    """
    pri_ad.log.debug("Setting voume to 0")
    pri_ad.droid.setMediaVolume(0)
    current_volume = pri_ad.droid.getMediaVolume()
    pri_ad.log.info('Current volume to {}'.format(current_volume))
    for _ in range(5):
        buds_device.volume('Up')
        time.sleep(AVRCP_WAIT_TIME)
    pri_ad.log.info('Volume increased to {}'.format(
        pri_ad.droid.getMediaVolume()))
    if current_volume == pri_ad.droid.getMediaVolume():
        pri_ad.log.error('Increase volume failed')
        raise signals.TestFailure("Increase volume failed")
    current_volume = pri_ad.droid.getMediaVolume()
    for _ in range(5):
        buds_device.volume('Down')
        time.sleep(AVRCP_WAIT_TIME)
    pri_ad.log.info('Volume decreased to {}'.format(
        pri_ad.droid.getMediaVolume()))
    if current_volume == pri_ad.droid.getMediaVolume():
        pri_ad.log.error('Decrease volume failed')
        raise signals.TestFailure("Decrease volume failed")
    return True
Exemplo n.º 13
0
    def stress_toggle_airplane_and_wifi(self, stress_count):
        """Toggle Airplane and WiFi modes in a loop.

        Args:
            stress_count: Number of times to perform Airplane mode ON, WiFi ON,
                          Airplane mode OFF, in a sequence.

        """
        for count in range(stress_count):
            self.log.debug("stress_toggle_airplane_and_wifi: Iteration %d" %
                           count)
            self.log.debug("Toggling Airplane mode ON")
            asserts.assert_true(
                acts.utils.force_airplane_mode(self.dut, True),
                "Can not turn on airplane mode on: %s" % self.dut.serial)
            # Sleep for atleast 500ms so that, call to enable wifi is not deferred.
            time.sleep(1)
            self.log.debug("Toggling wifi ON")
            wifi_utils.wifi_toggle_state(self.dut, True)
            # Sleep for 1s before getting new WiFi state.
            time.sleep(1)
            if not self.dut.droid.wifiGetisWifiEnabled():
                raise signals.TestFailure(
                    "WiFi did not turn on after turning ON"
                    " Airplane mode")
            asserts.assert_true(
                acts.utils.force_airplane_mode(self.dut, False),
                "Can not turn on airplane mode on: %s" % self.dut.serial)

        if not self.dut.droid.wifiGetisWifiEnabled():
            raise signals.TestFailure("WiFi did not turn on after toggling it"
                                      " %d times" % self.stress_count)
    def test_toggle_wlan_interface(self):
        """Test toggling the wlan interface if it exists.

        Steps:
        1. Call ListInterfaces FIDL api.
        2. Find the wlan interface.
        3. Disable the interface.
        4. Verify interface attributes in a down state.
        5. Enable the interface.
        6. Verify interface attributes in an up state.

        Expected Result:
        WLAN interface was successfully brought down and up again.

        Returns:
          signals.TestPass if no errors
          signals.TestFailure if there are any errors during the test.

        TAGS: Netstack
        Priority: 1
        """
        interfaces = self.dut.netstack_lib.netstackListInterfaces()
        for item in interfaces.get('result'):
            # Find the WLAN interface
            if "wlan" in item.get('name'):
                identifier = item.get('id')
                # Disable the interface by ID.
                result = self.dut.netstack_lib.disableInterface(identifier)
                if result.get('error') is not None:
                    raise signals.TestFailure(
                        "Unable to disable wlan interface: {}".format(
                            result.get('error')))

                # Check the current state of the interface.
                interface_info_result = self.dut.netstack_lib.getInterfaceInfo(
                    identifier)
                interface_info = interface_info_result.get('result')

                if len(interface_info.get('ipv4_addresses')) > 0:
                    raise signals.TestFailure(
                        "No Ipv4 Address should be present: {}".format(
                            interface_info))

                # TODO (35981): Verify other values when interface down.

                # Re-enable the interface
                result = self.dut.netstack_lib.enableInterface(identifier)
                if result.get('error') is not None:
                    raise signals.TestFailure(
                        "Unable to enable wlan interface: {}".format(
                            result.get('error')))

                # TODO (35981): Verify other values when interface up.

                raise signals.TestPass("Success")

        raise signals.TestSkip("No WLAN interface found.")
Exemplo n.º 15
0
 def setup_class(self):
     super().setup_class()
     if len(self.fuchsia_devices) < 1:
         raise signals.TestFailure("No fuchsia devices found.")
     for fd in self.fuchsia_devices:
         # Initialize the Policy client controller for each Fuchsia device
         fd.wlan_policy_lib.wlanCreateClientController()
     if len(self.access_points) < 1:
         raise signals.TestFailure("No access points found.")
     # Prepare the AP
     self.access_point = self.access_points[0]
     self.access_point.stop_all_aps()
     # Generate network params.
     bss_settings_2g = []
     bss_settings_5g = []
     open_network = self.get_open_network(False, [])
     self.open_network_2g = open_network["2g"]
     self.open_network_5g = open_network["5g"]
     wpa2_settings = self.get_psk_network(False, [])
     self.wpa2_network_2g = wpa2_settings["2g"]
     self.wpa2_network_5g = wpa2_settings["5g"]
     bss_settings_2g.append(
         hostapd_bss_settings.BssSettings(
             name=self.wpa2_network_2g["SSID"],
             ssid=self.wpa2_network_2g["SSID"],
             security=hostapd_security.Security(
                 security_mode=self.wpa2_network_2g["security"],
                 password=self.wpa2_network_2g["password"])))
     bss_settings_5g.append(
         hostapd_bss_settings.BssSettings(
             name=self.wpa2_network_5g["SSID"],
             ssid=self.wpa2_network_5g["SSID"],
             security=hostapd_security.Security(
                 security_mode=self.wpa2_network_5g["security"],
                 password=self.wpa2_network_5g["password"])))
     self.ap_2g = hostapd_ap_preset.create_ap_preset(
         iface_wlan_2g=self.access_points[0].wlan_2g,
         iface_wlan_5g=self.access_points[0].wlan_5g,
         channel=hostapd_constants.AP_DEFAULT_CHANNEL_2G,
         ssid=self.open_network_2g["SSID"],
         bss_settings=bss_settings_2g)
     self.ap_5g = hostapd_ap_preset.create_ap_preset(
         iface_wlan_2g=self.access_points[0].wlan_2g,
         iface_wlan_5g=self.access_points[0].wlan_5g,
         channel=hostapd_constants.AP_DEFAULT_CHANNEL_5G,
         ssid=self.open_network_5g["SSID"],
         bss_settings=bss_settings_5g)
     # Start the networks
     self.access_point.start_ap(hostapd_config=self.ap_2g)
     self.access_point.start_ap(hostapd_config=self.ap_5g)
     # Save the SSIDs
     self.all_ssids = [
         self.open_network_2g["SSID"],
         self.wpa2_network_2g["SSID"],
         self.open_network_5g["SSID"],
         self.wpa2_network_5g["SSID"],
     ]
 def test_repeated_case_with_failures(self, attempt_number):
     """The end result of this test is the last failure to occur."""
     returned_results = [
         signals.TestPass('Pass msg!', extras={'current': 3.5}),
         signals.TestFailure('Fail msg!', extras={'current': 100.0}),
         signals.TestFailure('Fail msg!', extras={'current': 58.1}),
         signals.TestFailure('Fail msg!', extras={'current': 74.2}),
     ]
     raise returned_results[(attempt_number - 1) % 4]
Exemplo n.º 17
0
 def get_configured_passpoint_and_delete(self):
     """Get configured Passpoint network and delete using its FQDN."""
     passpoint_config = self.dut.droid.getPasspointConfigs()
     if not len(passpoint_config):
         raise signals.TestFailure("Failed to fetch the list of configured"
                                   "passpoint networks.")
     if not wutils.delete_passpoint(self.dut, passpoint_config[0]):
         raise signals.TestFailure(
             "Failed to delete Passpoint configuration"
             " with FQDN = %s" % passpoint_config[0])
Exemplo n.º 18
0
    def test_stress_wifi_failover(self):
        """This test does aggressive failover to several networks in list.

           Steps:
               1. Add and enable few networks.
               2. Let device auto-connect.
               3. Remove the connected network.
               4. Repeat 2-3.
               5. Device should connect to a network until all networks are
                  exhausted.

        """
        for count in range(int(self.stress_count / 4)):
            wutils.reset_wifi(self.dut)
            ssids = list()
            for network in self.networks:
                ssids.append(network[WifiEnums.SSID_KEY])
                ret = self.dut.droid.wifiAddNetwork(network)
                asserts.assert_true(ret != -1,
                                    "Add network %r failed" % network)
                self.dut.droid.wifiEnableNetwork(ret, 0)
            self.dut.droid.wifiStartScan()
            time.sleep(WAIT_FOR_AUTO_CONNECT)
            cur_network = self.dut.droid.wifiGetConnectionInfo()
            cur_ssid = cur_network[WifiEnums.SSID_KEY]
            self.log.info("Cur_ssid = %s" % cur_ssid)
            for i in range(0, len(self.networks)):
                self.log.debug("Forget network %s" % cur_ssid)
                wutils.wifi_forget_network(self.dut, cur_ssid)
                time.sleep(WAIT_FOR_AUTO_CONNECT)
                cur_network = self.dut.droid.wifiGetConnectionInfo()
                cur_ssid = cur_network[WifiEnums.SSID_KEY]
                self.log.info("Cur_ssid = %s" % cur_ssid)
                if i == len(self.networks) - 1:
                    break
                if cur_ssid not in ssids:
                    raise signals.TestFailure("Device did not failover to the "
                                              "expected network. SSID = %s" %
                                              cur_ssid)
            network_config = self.dut.droid.wifiGetConfiguredNetworks()
            self.log.info("Network Config = %s" % network_config)
            if len(network_config):
                raise signals.TestFailure(
                    "All the network configurations were not "
                    "removed. Configured networks = %s" % network_config,
                    extras={
                        "Iterations": "%d" % self.stress_count,
                        "Pass": "******" % (count * 4)
                    })
        raise signals.TestPass(details="",
                               extras={
                                   "Iterations": "%d" % self.stress_count,
                                   "Pass": "******" % ((count + 1) * 4)
                               })
Exemplo n.º 19
0
def _wifi_connect(ad, network, num_of_tries=1):
    """Connect an Android device to a wifi network.

    Initiate connection to a wifi network, wait for the "connected" event, then
    confirm the connected ssid is the one requested.

    This will directly fail a test if anything goes wrong.

    Args:
        ad: android_device object to initiate connection on.
        network: A dictionary representing the network to connect to. The
                 dictionary must have the key "SSID".
        num_of_tries: An integer that is the number of times to try before
                      delaring failure. Default is 1.
    """
    asserts.assert_true(WifiEnums.SSID_KEY in network,
                        "Key '%s' must be present in network definition." %
                        WifiEnums.SSID_KEY)
    ad.droid.wifiStartTrackingStateChange()
    expected_ssid = network[WifiEnums.SSID_KEY]
    ad.droid.wifiConnectByConfig(network)
    ad.log.info("Starting connection process to %s", expected_ssid)
    try:
        event = ad.ed.pop_event(wifi_constants.CONNECT_BY_CONFIG_SUCCESS, 30)
        connect_result = wait_for_connect(ad, ssid=expected_ssid, tries=num_of_tries)
        asserts.assert_true(connect_result,
                            "Failed to connect to Wi-Fi network %s on %s" %
                            (network, ad.serial))
        ad.log.debug("Wi-Fi connection result: %s.", connect_result)
        actual_ssid = connect_result['data'][WifiEnums.SSID_KEY]
        asserts.assert_equal(actual_ssid, expected_ssid,
                             "Connected to the wrong network on %s." %
                             ad.serial)
        ad.log.info("Connected to Wi-Fi network %s.", actual_ssid)

        # Wait for data connection to stabilize.
        time.sleep(5)

        internet = validate_connection(ad, DEFAULT_PING_ADDR)
        if not internet:
            raise signals.TestFailure("Failed to connect to internet on %s" %
                                      expected_ssid)
    except Empty:
        asserts.fail("Failed to start connection process to %s on %s" %
                     (network, ad.serial))
    except Exception as error:
        ad.log.error("Failed to connect to %s with error %s", expected_ssid,
                     error)
        raise signals.TestFailure("Failed to connect to %s network" % network)

    finally:
        ad.droid.wifiStopTrackingStateChange()
Exemplo n.º 20
0
def _wifi_connect_by_id(ad, network_id, num_of_tries=1):
    """Connect an Android device to a wifi network using it's network id.

    Start connection to the wifi network, with the given network id, wait for
    the "connected" event, then verify the connected network is the one requested.

    Args:
        ad: android_device object to initiate connection on.
        network_id: Integer specifying the network id of the network.
        num_of_tries: An integer that is the number of times to try before
                      delaring failure. Default is 1.
    """
    ad.droid.wifiStartTrackingStateChange()
    # Clear all previous events.
    ad.ed.clear_all_events()
    ad.droid.wifiConnectByNetworkId(network_id)
    ad.log.info("Starting connection to network with id %d", network_id)
    try:
        event = ad.ed.pop_event(wifi_constants.CONNECT_BY_NETID_SUCCESS, 60)
        connect_result = wait_for_connect(ad, id=network_id, tries=num_of_tries)
        asserts.assert_true(connect_result,
                            "Failed to connect to Wi-Fi network using network id")
        ad.log.debug("Wi-Fi connection result: %s", connect_result)
        actual_id = connect_result['data'][WifiEnums.NETID_KEY]
        asserts.assert_equal(actual_id, network_id,
                             "Connected to the wrong network on %s."
                             "Expected network id = %d, but got %d." %
                             (ad.serial, network_id, actual_id))
        expected_ssid = connect_result['data'][WifiEnums.SSID_KEY]
        ad.log.info("Connected to Wi-Fi network %s with %d network id.",
                     expected_ssid, network_id)

        # Wait for data connection to stabilize.
        time.sleep(5)

        internet = validate_connection(ad, DEFAULT_PING_ADDR)
        if not internet:
            raise signals.TestFailure("Failed to connect to internet on %s" %
                                      expected_ssid)
    except Empty:
        asserts.fail("Failed to connect to network with id %d on %s" %
                    (network_id, ad.serial))
    except Exception as error:
        ad.log.error("Failed to connect to network with id %d with error %s",
                      network_id, error)
        raise signals.TestFailure("Failed to connect to network with network"
                                  " id %d" % network_id)
    finally:
        ad.droid.wifiStopTrackingStateChange()
Exemplo n.º 21
0
    def start_subscription_provisioning(self, state):
        """Start subscription provisioning with a default provider."""

        self.unpack_userparams(('osu_configs', ))
        asserts.assert_true(
            len(self.osu_configs) > 0, "Need at least one osu config.")
        osu_config = self.osu_configs[OSU_BOINGO]
        # Clear all previous events.
        self.dut.ed.clear_all_events()
        self.dut.droid.startSubscriptionProvisioning(osu_config)
        start_time = time.time()
        while time.time() < start_time + OSU_TEST_TIMEOUT:
            dut_event = self.dut.ed.pop_event("onProvisioningCallback",
                                              DEFAULT_TIMEOUT * 18)
            if dut_event['data']['tag'] == 'success':
                self.log.info("Passpoint Provisioning Success")
                # Reset WiFi after provisioning success.
                if state == RESET:
                    wutils.reset_wifi(self.dut)
                    time.sleep(DEFAULT_TIMEOUT)
                # Toggle WiFi after provisioning success.
                elif state == TOGGLE:
                    wutils.toggle_wifi_off_and_on(self.dut)
                    time.sleep(DEFAULT_TIMEOUT)
                break
            if dut_event['data']['tag'] == 'failure':
                raise signals.TestFailure(
                    "Passpoint Provisioning is failed with %s" %
                    dut_event['data']['reason'])
                break
            if dut_event['data']['tag'] == 'status':
                self.log.info("Passpoint Provisioning status %s" %
                              dut_event['data']['status'])
                if int(dut_event['data']['status']) == 7:
                    self.ui.run(self.dut.serial, self.passpoint_workflow)
        # Clear all previous events.
        self.dut.ed.clear_all_events()

        # Verify device connects to the Passpoint network.
        time.sleep(DEFAULT_TIMEOUT)
        current_passpoint = self.dut.droid.wifiGetConnectionInfo()
        if current_passpoint[
                WifiEnums.SSID_KEY] not in osu_config["expected_ssids"]:
            raise signals.TestFailure("Device did not connect to the %s"
                                      " passpoint network" %
                                      osu_config["expected_ssids"])
        # Delete the Passpoint profile.
        self.get_configured_passpoint_and_delete()
        wutils.wait_for_disconnect(self.dut)
Exemplo n.º 22
0
    def mmi_iut_initiate_connection(self):
        autoconnect = False
        transport = gatt_transport['le']
        adv_name = "PTS"
        self.peer_identifier = self.dut.le_scan_with_name_filter(
            "PTS", self.scan_timeout_seconds)
        if self.peer_identifier is None:
            raise signals.TestFailure("Scanner unable to find advertisement.")
        tries = 3
        for _ in range(tries):
            if self.dut.gatt_connect(self.peer_identifier, transport,
                                     autoconnect):
                return

        raise signals.TestFailure("Unable to connect to peripheral.")
Exemplo n.º 23
0
    def test_passpoint_failover(self):
        """Add a pair of passpoint networks and test failover when one of the"
           profiles is removed.

        1. Install a Passpoint Profile A and B.
        2. Verify device connects to a Passpoint network and get SSID.
        3. Delete the current Passpoint profile using its FQDN.
        4. Verify device fails over and connects to the other Passpoint SSID.
        5. Delete Passpoint configuration using its FQDN.

        """
        # Install both Passpoint profiles on the device.
        passpoint_ssid = list()
        for passpoint_config in self.passpoint_networks:
            passpoint_ssid.append(passpoint_config[WifiEnums.SSID_KEY])
            self.install_passpoint_profile(passpoint_config)
            time.sleep(DEFAULT_TIMEOUT)

        # Get the current network and the failover network.
        wutils.wait_for_connect(self.dut)
        current_passpoint = self.dut.droid.wifiGetConnectionInfo()
        current_ssid = current_passpoint[WifiEnums.SSID_KEY]
        if current_ssid not in passpoint_ssid:
            raise signals.TestFailure("Device did not connect to any of the "
                                      "configured Passpoint networks.")

        expected_ssid = self.passpoint_networks[0][WifiEnums.SSID_KEY]
        if current_ssid == expected_ssid:
            expected_ssid = self.passpoint_networks[1][WifiEnums.SSID_KEY]

        # Remove the current Passpoint profile.
        for network in self.passpoint_networks:
            if network[WifiEnums.SSID_KEY] == current_ssid:
                if not wutils.delete_passpoint(self.dut, network["fqdn"]):
                    raise signals.TestFailure("Failed to delete Passpoint"
                                              " configuration with FQDN = %s" %
                                              network["fqdn"])
        # Verify device fails over and connects to the other passpoint network.
        time.sleep(DEFAULT_TIMEOUT)

        current_passpoint = self.dut.droid.wifiGetConnectionInfo()
        if current_passpoint[WifiEnums.SSID_KEY] != expected_ssid:
            raise signals.TestFailure("Device did not failover to the %s"
                                      " passpoint network" % expected_ssid)

        # Delete the remaining Passpoint profile.
        self.get_configured_passpoint_and_delete()
        wutils.wait_for_disconnect(self.dut)
Exemplo n.º 24
0
    def check_passpoint_connection(self, passpoint_network):
        """Verify the device is automatically able to connect to the Passpoint
           network.

           Args:
               passpoint_network: SSID of the Passpoint network.

        """
        ad = self.dut
        ad.ed.clear_all_events()
        wutils.start_wifi_connection_scan(ad)
        scan_results = ad.droid.wifiGetScanResults()
        # Wait for scan to complete.
        time.sleep(5)
        ssid = passpoint_network
        wutils.assert_network_in_list({WifiEnums.SSID_KEY: ssid}, scan_results)
        # Passpoint network takes longer time to connect than normal networks.
        # Every try comes with a timeout of 30s. Setting total timeout to 120s.
        wutils.wifi_passpoint_connect(self.dut,
                                      passpoint_network,
                                      num_of_tries=4)
        # Re-verify we are connected to the correct network.
        network_info = self.dut.droid.wifiGetConnectionInfo()
        if network_info[WifiEnums.SSID_KEY] != passpoint_network:
            raise signals.TestFailure("Device did not connect to the passpoint"
                                      " network.")
Exemplo n.º 25
0
    def __call__(self, *args, **kwargs):
        """Called when the test is executed."""
        full_args = self.instance_args + list(args)

        try:
            if self.arg_modifier:
                full_args, kwargs = self.arg_modifier(self.inner, *full_args,
                                                      **kwargs)

            if self.before:
                self.before(self.inner, *full_args, **kwargs)

            result = 'UNKNOWN ERROR'
            try:
                result = self.inner(*full_args, **kwargs)
            finally:
                if self.after:
                    self.after(self.inner, result, *full_args, **kwargs)

            if result or result is None:
                new_signal = signals.TestPass('')
            else:
                new_signal = signals.TestFailure('')
        except signals.TestSignal as signal:
            new_signal = signal

        if self.signal_modifier:
            new_signal = self.signal_modifier(self.inner, new_signal,
                                              *full_args,
                                              **kwargs)

        raise new_signal
    def enable_usb_tethering(self, attempts=3):
        """Stop SL4A service and enable usb tethering.

        Logic steps are
        1. Stop SL4A service.
        2. Enable usb tethering.
        3. Restart SL4A service.
        4. Check usb tethering enabled.
        5. Attempt if fail to enable usb tethering.

        Args:
            attempts: number of times for enable usb tethering.

        Raises:
            TestFailure when unable to find rndis string.
        """
        for i in range(attempts):
            self.dut.stop_services()
            self.dut.adb.shell(USB_TETHERING_MODE, ignore_status=True)
            self.dut.adb.wait_for_device()
            self.dut.start_services()
            if 'rndis' in self.dut.adb.shell(DEVICE_IP_ADDRESS):
                self.log.info('Usb tethering is enabled.')
                return
            else:
                self.log.info('Enable usb tethering - attempt %d' % (i + 1))
        raise signals.TestFailure('Unable to enable USB tethering.')
Exemplo n.º 27
0
    def test_toggle_wifi_reboot_configstore_reconnect(self):
        """Connect to multiple networks, disable WiFi, reboot, then
           reconnect to previously connected network.

        Steps:
        1. Connect to a 2GHz network.
        2. Connect to a 5GHz network.
        3. Turn WiFi OFF.
        4. Reboot device.
        5. Turn WiFi ON.
        4. Verify all networks are persistent after reboot.
        5. Reconnect to the non-current network.

        """
        network_list = self.connect_multiple_networks(self.dut)
        self.log.debug("Toggling wifi OFF")
        wutils.wifi_toggle_state(self.dut, False)
        time.sleep(DEFAULT_TIMEOUT)
        self.dut.reboot()
        time.sleep(DEFAULT_TIMEOUT)
        self.log.debug("Toggling wifi ON")
        wutils.wifi_toggle_state(self.dut, True)
        time.sleep(DEFAULT_TIMEOUT)
        self.check_configstore_networks(network_list)
        reconnect_to = self.get_enabled_network(network_list[BAND_2GHZ],
                                                network_list[BAND_5GHZ])
        reconnect = self.connect_to_wifi_network_with_id(
            reconnect_to[WifiEnums.NETID_KEY],
            reconnect_to[WifiEnums.SSID_KEY])
        if not reconnect:
            msg = ("Device failed to reconnect to the correct network after"
                   " toggling WiFi and rebooting.")
            raise signals.TestFailure(msg)
Exemplo n.º 28
0
    def test_reboot_configstore_reconnect(self):
        """Connect to multiple networks, reboot then reconnect to previously
           connected network.

        Steps:
        1. Connect to a 2GHz network.
        2. Connect to a 5GHz network.
        3. Reboot device.
        4. Verify all networks are persistent after reboot.
        5. Reconnect to the non-current network.

        """
        network_list = self.connect_multiple_networks(self.dut)
        self.dut.reboot()
        time.sleep(DEFAULT_TIMEOUT)
        self.check_configstore_networks(network_list)

        reconnect_to = self.get_enabled_network(network_list[BAND_2GHZ],
                                                network_list[BAND_5GHZ])

        reconnect = self.connect_to_wifi_network_with_id(
            reconnect_to[WifiEnums.NETID_KEY],
            reconnect_to[WifiEnums.SSID_KEY])
        if not reconnect:
            raise signals.TestFailure(
                "Device failed to reconnect to the correct"
                " network after reboot.")
    def test_retrieve_config_wifi_disabled(self):
        """ Test if config can be retrieved when wifi is disabled.

            1. Disable wifi
            2. Create and save a random config
            3. Retrieve the config
            4. Remove the config (clean up from the test)
        """
        wutils.wifi_toggle_state(self.dut, False)
        test_network = self.create_and_save_wifi_network_config()
        if not self.check_network_config_saved(
                test_network[self.CONFIG_ELEMENT]):
            raise signals.TestFailure(
                "Test network not found in list of configured networks.")
        if not self.forget_network(test_network[self.NETWORK_ID_ELEMENT]):
            raise signals.TestFailure("Failed to delete network.")
Exemplo n.º 30
0
    def __call__(self, *args, **kwargs):
        """
        When called runs the underlying func and then attaches test info
        to a signal.
        """
        try:
            result = self.func(*args, **kwargs)

            if result or result is None:
                new_signal = signals.TestPass('')
            else:
                new_signal = signals.TestFailure('')
        except signals.TestSignal as signal:
            new_signal = signal

        if not isinstance(new_signal.extras, dict) and new_signal.extras:
            raise ValueError('test_info can only append to signal data '
                             'that has a dict as the extra value.')
        elif not new_signal.extras:
            new_signal.extras = {}

        gathered_extras = self._gather_local_info(None, *args, **kwargs)
        for k, v in gathered_extras.items():
            if k not in new_signal.extras:
                new_signal.extras[k] = v
            else:
                if not isinstance(new_signal.extras[k], list):
                    new_signal.extras[k] = [new_signal.extras[k]]

                new_signal.extras[k].insert(0, v)

        raise new_signal