def _wifi_toggle_state(ad, new_state=None):
    """Toggles the state of wifi.

    TestFailure signals are raised when something goes wrong.

    Args:
        ad: An AndroidDevice object.
        new_state: The state to set Wi-Fi to. If None, opposite of the current
                   state will be set.
    """
    if new_state is None:
        new_state = not ad.droid.wifiCheckState()
    elif new_state == ad.droid.wifiCheckState():
        # Check if the new_state is already achieved, so we don't wait for the
        # state change event by mistake.
        return
    ad.droid.wifiStartTrackingStateChange()
    ad.log.info("Setting Wi-Fi state to %s.", new_state)
    # Setting wifi state.
    ad.droid.wifiToggleState(new_state)
    fail_msg = "Failed to set Wi-Fi state to %s on %s." % (new_state,
                                                           ad.serial)
    try:
        event = ad.ed.pop_event(WifiEventNames.SUPPLICANT_CON_CHANGED,
                                SHORT_TIMEOUT)
        asserts.assert_equal(event['data']['Connected'], new_state, fail_msg)
    except Empty:
        # Supplicant connection event is not always reliable. We double check
        # here and call it a success as long as the new state equals the
        # expected state.
        time.sleep(5)
        asserts.assert_equal(new_state, ad.droid.wifiCheckState(), fail_msg)
    finally:
        ad.droid.wifiStopTrackingStateChange()
Exemple #2
0
    def setup_class(self):
        self.dut = self.android_devices[0]
        self.dut_softap = self.android_devices[1]
        wutils.wifi_test_device_init(self.dut)
        wutils.wifi_test_device_init(self.dut_softap)

        self.reset_mac_address_to_factory_mac()
        self.dut.adb.shell(TURN_ON_MAC_RANDOMIZATION)
        asserts.assert_equal(
            self.dut.adb.shell(GET_MAC_RANDOMIZATION_STATUS), "1",
            "Failed to enable Connected MAC Randomization on dut.")

        req_params = ["reference_networks"]
        opt_param = []
        self.unpack_userparams(req_param_names=req_params,
                               opt_param_names=opt_param)

        if "AccessPoint" in self.user_params:
            self.legacy_configure_ap_and_start()

        asserts.assert_true(
            self.reference_networks[0]["2g"],
            "Need at least 1 2.4Ghz reference network with psk.")
        asserts.assert_true(
            self.reference_networks[0]["5g"],
            "Need at least 1 5Ghz reference network with psk.")
        self.wpapsk_2g = self.reference_networks[0]["2g"]
        self.wpapsk_5g = self.reference_networks[0]["5g"]
    def _test_link_probe_does_not_crash_device(self, network):
        """
        Connect to a network, send link probes, and verify that the device did
        not crash. Also verify that at least one link probe succeeded.

        Steps:
        1. Connect to a network.
        2. Send a few link probes.
        3. Verify that at least one link probe succeeded.
        4. Ensure that the device did not crash (by checking that it is
           connected to the expected network).
        """
        wutils.wifi_connect(self.dut, network, num_of_tries=3)

        results = wutils.send_link_probes(self.dut, NUM_LINK_PROBES,
                                          PROBE_DELAY_SEC)

        asserts.assert_true(any(result.is_success for result in results),
                            "Expect at least 1 probe success: " + str(results))

        wifi_info = self.dut.droid.wifiGetConnectionInfo()
        expected = network[WifiEnums.SSID_KEY]
        actual = wifi_info[WifiEnums.SSID_KEY]
        asserts.assert_equal(
            expected, actual,
            "Device did not remain connected after sending link probes!")
    def test_play_pause(self):
        """
        Test the Play/Pause passthrough commands.

        Step:
        1. Invoke Play/Pause from controller.
        2. Wait to receive corresponding received event from target.
        3. Check current playback state on target.

        Expected Result:
        Passthrough command received and music play then pause.

        Returns:
          Pass if True
          Fail if False
        """
        self.play_from_controller()
        time.sleep(DEFAULT_TIMEOUT)
        state = (
            self.dut.droid.bluetoothMediaGetCurrentPlaybackState())['state']
        assert_equal(state, PlaybackState.PLAY,
                     'Current playback state is not Play, is {}'.format(state))

        self.pause_from_controller()
        time.sleep(DEFAULT_TIMEOUT)
        state = (
            self.dut.droid.bluetoothMediaGetCurrentPlaybackState())['state']
        assert_equal(
            state, PlaybackState.PAUSE,
            'Current playback state is not Pause, is {}'.format(state))
    def test_eap_connect(self):
        """Test connecting to enterprise networks of different authentication
        types.

        The authentication types tested are:
            EAP-TLS
            EAP-PEAP with different phase2 types.
            EAP-TTLS with different phase2 types.

        Procedures:
            For each enterprise wifi network
            1. Connect to the network.
            2. Send a GET request to a website and check response.

        Expect:
            Successful connection and Internet access through the enterprise
            networks.
        """
        eap_configs = self.gen_eap_configs()
        self.log.info("Testing %d different configs." % len(eap_configs))
        random.shuffle(eap_configs)
        failed = self.run_generated_testcases(wutils.eap_connect,
                                              eap_configs,
                                              args=(self.dut, ),
                                              name_func=self.gen_eap_test_name)
        msg = ("The following configs failed EAP connect test: %s" %
               pprint.pformat(failed))
        asserts.assert_equal(len(failed), 0, msg)
    def _test_link_probe_ap_attenuated(self, network):
        """
        Connect to a network, significantly attenuate the signal, and verify
        that the device did not crash.

        Steps:
        1. Connect to a network.
        2. Attenuate the signal.
        3. Send a few link probes.
        4. Stop attenuating the signal.
        5. Ensure that the device did not crash (by checking that it is
           connected to the expected network).
        """
        wutils.wifi_connect(self.dut, network, num_of_tries=3)
        self.attenuators[0].set_atten(ATTENUATION)

        wutils.send_link_probes(self.dut, NUM_LINK_PROBES, PROBE_DELAY_SEC)

        # we cannot assert for failed link probe when attenuated, this would
        # depend too much on the attenuator setup => too flaky

        self.attenuators[0].set_atten(0)
        time.sleep(PROBE_DELAY_SEC * 3)
        wifi_info = self.dut.droid.wifiGetConnectionInfo()
        expected = network[WifiEnums.SSID_KEY]
        actual = wifi_info[WifiEnums.SSID_KEY]
        asserts.assert_equal(
            expected, actual,
            "Device did not remain connected after sending link probes!")
    def connect_and_verify_connected_bssid(self, expected_bssid):
        """Start a scan to get the DUT connected to an AP and verify the DUT
        is connected to the correct BSSID.

        Args:
            expected_bssid: Network bssid to which connection.

        Returns:
            True if connection to given network happen, else return False.
        """
        #wait for the attenuator to stablize
        time.sleep(10)
        #force start a single scan so we don't have to wait for the
        #WCM scheduled scan.
        wutils.start_wifi_connection_scan(self.dut)
        #wait for connection
        time.sleep(20)
        #verify connection
        actual_network = self.dut.droid.wifiGetConnectionInfo()
        logging.info("Actual network: %s", actual_network)
        try:
            asserts.assert_equal(expected_bssid,
                                 actual_network[WifiEnums.BSSID_KEY])
        except:
           msg = "Device did not connect to any network."
           raise signals.TestFailure(msg)
 def setup_class(self):
     self.dut = self.android_devices[0]
     self.dut_client = self.android_devices[1]
     wutils.wifi_test_device_init(self.dut)
     wutils.wifi_test_device_init(self.dut_client)
     utils.require_sl4a((self.dut, self.dut_client))
     utils.sync_device_time(self.dut)
     utils.sync_device_time(self.dut_client)
     # Set country code explicitly to "US".
     self.dut.droid.wifiSetCountryCode(wutils.WifiEnums.CountryCode.US)
     self.dut_client.droid.wifiSetCountryCode(wutils.WifiEnums.CountryCode.US)
     # Enable verbose logging on the duts
     self.dut.droid.wifiEnableVerboseLogging(1)
     asserts.assert_equal(self.dut.droid.wifiGetVerboseLoggingLevel(), 1,
         "Failed to enable WiFi verbose logging on the softap dut.")
     self.dut_client.droid.wifiEnableVerboseLogging(1)
     asserts.assert_equal(self.dut_client.droid.wifiGetVerboseLoggingLevel(), 1,
         "Failed to enable WiFi verbose logging on the client dut.")
     req_params = []
     opt_param = ["iperf_server_address", "reference_networks"]
     self.unpack_userparams(
         req_param_names=req_params, opt_param_names=opt_param)
     if "iperf_server_address" in self.user_params:
         self.iperf_server = self.iperf_servers[0]
     if hasattr(self, 'iperf_server'):
         self.iperf_server.start()
Exemple #9
0
    def setup_class(self):
        super().setup_class()

        self.dut = self.android_devices[0]
        self.dut_client = self.android_devices[1]
        wutils.wifi_test_device_init(self.dut)
        wutils.wifi_test_device_init(self.dut_client)
        utils.require_sl4a((self.dut, self.dut_client))
        utils.sync_device_time(self.dut)
        utils.sync_device_time(self.dut_client)
        # Set country code explicitly to "US".
        wutils.set_wifi_country_code(self.dut, wutils.WifiEnums.CountryCode.US)
        wutils.set_wifi_country_code(self.dut_client,
                                     wutils.WifiEnums.CountryCode.US)
        # Enable verbose logging on the duts
        self.dut.droid.wifiEnableVerboseLogging(1)
        asserts.assert_equal(
            self.dut.droid.wifiGetVerboseLoggingLevel(), 1,
            "Failed to enable WiFi verbose logging on the softap dut.")
        self.dut_client.droid.wifiEnableVerboseLogging(1)
        asserts.assert_equal(
            self.dut_client.droid.wifiGetVerboseLoggingLevel(), 1,
            "Failed to enable WiFi verbose logging on the client dut.")
        req_params = []
        opt_param = [
            "iperf_server_address", "reference_networks", "iperf_server_port"
        ]
        self.unpack_userparams(req_param_names=req_params,
                               opt_param_names=opt_param)
        self.chan_map = {
            v: k
            for k, v in hostapd_constants.CHANNEL_MAP.items()
        }
        self.pcap_procs = None
    def test_ipv6_tethering(self):
        """ IPv6 tethering test

        Steps:
            1. Start wifi tethering on provider
            2. Client connects to wifi tethering SSID
            3. Verify IPv6 address on the client's link properties
            4. Verify ping on client using ping6 which should pass
            5. Disable mobile data on provider and verify that link properties
               does not have IPv6 address and default route
        """
        # Start wifi tethering on the hotspot device
        self.log.info("Start tethering on provider: {}".format(
            self.hotspot_device.serial))
        wifi_test_utils.start_wifi_tethering(self.hotspot_device, self.ssid,
                                             self.password)
        time.sleep(tel_defines.WAIT_TIME_ANDROID_STATE_SETTLING)
        asserts.assert_true(
            tel_data_utils.verify_http_connection(self.log,
                                                  self.hotspot_device),
            "Could not verify http connection on the provider")

        # Verify link properties on hotspot device
        self.log.info("Check IPv6 properties on the hotspot device")
        self._verify_ipv6_tethering(self.hotspot_device)

        # Connect the client to the SSID
        asserts.assert_true(
            tel_test_utils.WifiUtils.wifi_connect(self.log,
                                                  self.tethered_device,
                                                  self.ssid, self.password),
            "Unable to connect to the hotspot SSID")

        # Need to wait atleast 2 seconds for IPv6 address to
        # show up in the link properties
        time.sleep(2)

        # Verify link properties on tethered device
        self.log.info("Check IPv6 properties on the tethered device")
        self._verify_ipv6_tethering(self.tethered_device)

        # Verify ping6 on tethered device
        ping_result = self.tethered_device.droid.pingHost(
            "www.google.com", 5, "ping6")
        if self._supports_ipv6_tethering(self.hotspot_device):
            asserts.assert_true(ping_result, "Ping6 failed on the client")
        else:
            asserts.assert_true(not ping_result, "Ping6 failed as expected")

        # Disable mobile data on hotspot device
        # and verify the link properties on tethered device
        self.log.info("Disabling mobile data on hotspot device")
        self.hotspot_device.droid.telephonyToggleDataConnection(False)
        asserts.assert_equal(
            self.hotspot_device.droid.telephonyGetDataConnectionState(),
            tel_defines.DATA_STATE_CONNECTED, "Could not disable cell data")
        time.sleep(2)  # wait until the IPv6 is removed from link properties
        asserts.assert_true(
            not self._find_ipv6_default_route(self.tethered_device),
            "Found IPv6 default route in link properties - Data off")
Exemple #11
0
def wifi_test_device_init(ad):
    """Initializes an android device for wifi testing.

    0. Make sure SL4A connection is established on the android device.
    1. Disable location service's WiFi scan.
    2. Turn WiFi on.
    3. Clear all saved networks.
    4. Set country code to US.
    5. Enable WiFi verbose logging.
    6. Sync device time with computer time.
    7. Turn off cellular data.
    8. Turn off ambient display.
    """
    utils.require_sl4a((ad, ))
    ad.droid.wifiScannerToggleAlwaysAvailable(False)
    msg = "Failed to turn off location service's scan."
    asserts.assert_true(not ad.droid.wifiScannerIsAlwaysAvailable(), msg)
    wifi_toggle_state(ad, True)
    reset_wifi(ad)
    ad.droid.wifiEnableVerboseLogging(1)
    msg = "Failed to enable WiFi verbose logging."
    asserts.assert_equal(ad.droid.wifiGetVerboseLoggingLevel(), 1, msg)
    # We don't verify the following settings since they are not critical.
    # Set wpa_supplicant log level to EXCESSIVE.
    output = ad.adb.shell("wpa_cli -i wlan0 -p -g@android:wpa_wlan0 IFNAME="
                          "wlan0 log_level EXCESSIVE")
    ad.log.info("wpa_supplicant log change status: %s", output)
    utils.sync_device_time(ad)
    ad.droid.telephonyToggleDataConnection(False)
    # TODO(angli): need to verify the country code was actually set. No generic
    # way to check right now.
    ad.adb.shell("halutil -country %s" % WifiEnums.CountryCode.US)
    utils.set_ambient_display(ad, False)
 def _assert_unicast(self, packet, ipAddr=None):
     asserts.assert_false(None == packet, "No packet")
     asserts.assert_false(
         packet.getlayer(Ether).dst == BROADCAST_MAC,
         "Layer 2 packet destination address was broadcast")
     if ipAddr:
         asserts.assert_equal(packet.getlayer(IP).dst, ipAddr)
def requestServiceAndCheckResultWithRetry(ad_serviceProvider,
                                          ad_serviceReceiver,
                                          serviceType,
                                          queryString1,
                                          queryString2,
                                          retryCount=3):
    """ allow failures for requestServiceAndCheckResult. Service
        discovery might fail unexpectedly because the request packet might not be
        recevied by the service responder due to p2p state switch.

    Args:
        ad_serviceProvider: The android device which provide p2p local service
        ad_serviceReceiver: The android device which query p2p local service
        serviceType: P2p local service type, Upnp or Bonjour
        queryString1: Query String, NonNull
        queryString2: Query String, used for Bonjour, Nullable
        retryCount: maximum retry count, default is 3
    """
    ret = 0
    while retryCount > 0:
        ret = requestServiceAndCheckResult(ad_serviceProvider,
                                           ad_serviceReceiver, serviceType,
                                           queryString1, queryString2)
        if (ret == 0):
            break
        retryCount -= 1

    asserts.assert_equal(0, ret, "cannot find any services with retries.")
    def test_eap_connect_negative(self):
        """Test connecting to enterprise networks.

        Procedures:
            For each enterprise wifi network
            1. Connect to the network with invalid credentials.

        Expect:
            Fail to establish connection.
        """
        neg_eap_configs = self.gen_negative_eap_configs()
        self.log.info("Testing %d different configs.", len(neg_eap_configs))
        random.shuffle(neg_eap_configs)

        def name_gen(config, ad):
            name = self.gen_eap_test_name(config, ad)
            name += "-with_wrong-{}".format(config["invalid_field"])
            return name

        failed = self.run_generated_testcases(self.eap_negative_connect_logic,
                                              neg_eap_configs,
                                              args=(self.dut, ),
                                              name_func=name_gen)
        msg = ("The following configs failed negative EAP connect test: %s" %
               pprint.pformat(failed))
        asserts.assert_equal(len(failed), 0, msg)
    def test_connection_to_legacy_vpn(self):
        """ Verify VPN connection for all configurations.
            Supported VPN configurations are
            1.) PPTP            2.) L2TP IPSEC PSK
            3.) IPSEC XAUTH PSK 4.) L2TP IPSEC RSA
            5.) IPSEC XAUTH RSA 6.) IPSec Hybrid RSA

            Steps:
                1. Call legacy_vpn_connection_test_logic() for each VPN which
                tests the connection to the corresponding server

            Return:
                Pass: if all VPNs pass
                Fail: if any one VPN fails
        """
        def gen_name(vpn_type):
            return "test_legacy_vpn_%s" % vpn_type.name

        result = self.run_generated_testcases(
            self.legacy_vpn_connection_test_logic,
            VPN_TYPE,
            name_func=gen_name,
        )
        msg = ("The following configs failed vpn connection %s" %
               pprint.pformat(result))
        asserts.assert_equal(len(result), 0, msg)
Exemple #16
0
 def sync_device_time(self):
     self.adb.shell("settings put global auto_time 0")
     self.adb.shell("settings put global auto_time_zone 0")
     device_tz = self.adb.shell("date +%z")
     asserts.assert_true(device_tz, "date +%z must return device timezone, "
                         "but returned {} instead".format(device_tz))
     host_tz = time.strftime("%z")
     if device_tz != host_tz:
         target_timezone = utils.get_timezone_olson_id()
         logging.debug("Device timezone %s does not match host timezone %s, "
                       "syncing them by setting timezone to %s" % (device_tz, host_tz, target_timezone))
         self.adb.shell("setprop persist.sys.timezone %s" % target_timezone)
         self.reboot()
         device_tz = self.adb.shell("date +%z")
         asserts.assert_equal(
             host_tz, device_tz, "Device timezone %s still does not match host "
             "timezone %s after reset" % (device_tz, host_tz))
     self.adb.shell("date %s" % time.strftime("%m%d%H%M%Y.%S"))
     datetime_format = "%Y-%m-%dT%H:%M:%S%z"
     try:
         device_time = datetime.strptime(self.adb.shell("date +'%s'" % datetime_format), datetime_format)
     except ValueError:
         asserts.fail("Failed to get time after sync")
         return
     # Include ADB delay that might be longer in SSH environment
     max_delta_seconds = 3
     host_time = datetime.now(tz=device_time.tzinfo)
     asserts.assert_almost_equal(
         (device_time - host_time).total_seconds(),
         0,
         msg="Device time %s and host time %s off by >%dms after sync" %
         (device_time.isoformat(), host_time.isoformat(), int(max_delta_seconds * 1000)),
         delta=max_delta_seconds)
    def test_eap_connect_config_store(self):
        """Test connecting to enterprise networks of different authentication
        types after wifi toggle.

        The authentication types tested are:
            EAP-TLS
            EAP-PEAP with different phase2 types.
            EAP-TTLS with different phase2 types.

        Procedures:
            For each enterprise wifi network
            1. Connect to the network.
            2. Send a GET request to a website and check response.
            3. Toggle wifi.
            4. Ensure that the device reconnects to the same network.

        Expect:
            Successful connection and Internet access through the enterprise
            networks.
        """
        eap_configs = self.gen_eap_configs()
        self.log.info("Testing %d different configs.", len(eap_configs))
        random.shuffle(eap_configs)
        failed = self.run_generated_testcases(
            self.eap_connect_toggle_wifi,
            eap_configs,
            args=(self.dut, ),
            name_func=self.gen_eap_test_name_for_config_store)
        asserts.assert_equal(
            len(failed), 0,
            "The following configs failed EAP connect test: %s" %
            pprint.pformat(failed))
    def legacy_vpn_connection_test_logic(self, vpn_type):
        """ Test logic for each legacy VPN connection

            Steps:
                1. Generate profile for the VPN type
                2. Establish connection to the server
                3. Verify that connection is established using LegacyVpnInfo
                4. Verify the connection by pinging the IP behind VPN
                5. Stop the VPN connection
                6. Check the connection status
                7. Verify that ping to IP behind VPN fails

            Args:
                VpnProfileType (1 of the 6 types supported by Android)
        """
        vpn_profile = self.generate_legacy_vpn_profile(vpn_type)
        logging.info("Connecting to: %s", vpn_profile)
        self.dut.droid.vpnStartLegacyVpn(vpn_profile)
        time.sleep(connectivity_const.VPN_TIMEOUT)
        connected_vpn_info = self.dut.droid.vpnGetLegacyVpnInfo()
        asserts.assert_equal(
            connected_vpn_info["state"],
            connectivity_const.VPN_STATE_CONNECTED,
            "Unable to establish VPN connection for %s" % vpn_profile)
        self.verify_ping_to_vpn_ip(connected_vpn_info)
        self.dut.droid.vpnStopLegacyVpn()
        connected_vpn_info = self.dut.droid.vpnGetLegacyVpnInfo()
        asserts.assert_true(
            not connected_vpn_info,
            "Unable to terminate VPN connection for %s" % vpn_profile)
        self.verify_ping_to_vpn_ip(connected_vpn_info)
    def test_reconnect_to_better_saved_network(self):
        """
        2 saved APs, one attenuated, one unattenuated, Wifi Wake should connect
        to the unattenuated AP
        """
        wutils.wifi_connect(self.dut, self.ap_a, num_of_tries=5)
        wutils.wifi_connect(self.dut, self.ap_b, num_of_tries=5)
        self.dut.ed.clear_all_events()
        self.ap_a_off()
        self.ap_b_off()
        wutils.wait_for_disconnect(self.dut)
        self.log.info("Wifi Disconnected")
        time.sleep(LAST_DISCONNECT_TIMEOUT_SEC * 1.2)
        wutils.wifi_toggle_state(self.dut, new_state=False)
        time.sleep(PRESCAN_DELAY_SEC)
        self.do_location_scan(CONSECUTIVE_MISSED_SCANS_REQUIRED_TO_EVICT + 2)

        self.ap_a_on()
        self.ap_b_on()
        self.ap_a_atten.set_atten(30)
        self.ap_b_atten.set_atten(0)

        self.do_location_scan()
        asserts.assert_true(
            self.dut.droid.wifiCheckState(),
            "Expect Wifi Wake to enable Wifi, but Wifi is disabled.")
        expected_ssid = self.ap_b[wutils.WifiEnums.SSID_KEY]
        actual_ssid = self.dut.droid.wifiGetConnectionInfo()[
            wutils.WifiEnums.SSID_KEY]
        asserts.assert_equal(
            expected_ssid, actual_ssid,
            ("Expected to connect to SSID '{}', but actually connected to "
             "'{}' instead.").format(expected_ssid, actual_ssid))
    def test_passpoint_connect_negative(self):
        """Test connecting to enterprise networks.

        Procedures:
            For each enterprise wifi network
            1. Connect to the network with invalid credentials.

        Expect:
            Fail to establish connection.
        """
        asserts.skip_if(
            not self.dut.droid.wifiIsPasspointSupported(),
            "Passpoint is not supported on device %s" % self.dut.model)
        neg_passpoint_configs = self.gen_negative_passpoint_configs()
        self.log.info("Testing %d different configs.",
                      len(neg_passpoint_configs))
        random.shuffle(neg_passpoint_configs)

        def name_gen(config, ad):
            name = self.gen_passpoint_test_name(config, ad)
            name += "-with_wrong-{}".format(config["invalid_field"])
            return name

        failed = self.run_generated_testcases(self.eap_negative_connect_logic,
                                              neg_passpoint_configs,
                                              args=(self.dut, ),
                                              name_func=name_gen)
        asserts.assert_equal(
            len(failed), 0,
            "The following configs failed negative passpoint connect test: %s"
            % pprint.pformat(failed))
    def test_passpoint_connect_config_store(self):
        """Test connecting to enterprise networks of different authentication
        types with passpoint support after wifi toggle.

        The authentication types tested are:
            EAP-TLS
            EAP-TTLS with MSCHAPV2 as phase2.

        Procedures:
            For each enterprise wifi network
            1. Connect to the network.
            2. Send a GET request to a website and check response.
            3. Toggle wifi.
            4. Ensure that the device reconnects to the same network.

        Expect:
            Successful connection and Internet access through the enterprise
            networks with passpoint support.
        """
        asserts.skip_if(
            not self.dut.droid.wifiIsPasspointSupported(),
            "Passpoint is not supported on device %s" % self.dut.model)
        passpoint_configs = self.gen_passpoint_configs()
        self.log.info("Testing %d different configs.", len(passpoint_configs))
        random.shuffle(passpoint_configs)
        failed = self.run_generated_testcases(
            self.eap_connect_toggle_wifi,
            passpoint_configs,
            args=(self.dut, ),
            name_func=self.gen_passpoint_test_name_for_config_store)
        asserts.assert_equal(
            len(failed), 0,
            "The following configs failed passpoint connect test: %s" %
            pprint.pformat(failed))
    def test_rtt_supporting_ap_only(self):
        """Scan for APs and perform RTT only to those which support 802.11mc.

    Stress test: repeat ranging to the same AP. Verify rate of success and
    stability of results.
    """
        dut = self.android_devices[0]
        rtt_supporting_aps = rutils.scan_with_rtt_support_constraint(dut,
                                                                     True,
                                                                     repeat=10)
        dut.log.debug("RTT Supporting APs=%s", rtt_supporting_aps)

        num_iter = self.stress_test_min_iteration_count

        max_peers = dut.droid.wifiRttMaxPeersInRequest()
        asserts.assert_true(
            len(rtt_supporting_aps) > 0,
            "Need at least one AP which supports 802.11mc!")
        if len(rtt_supporting_aps) > max_peers:
            rtt_supporting_aps = rtt_supporting_aps[0:max_peers]

        events = rutils.run_ranging(dut, rtt_supporting_aps, num_iter, 0,
                                    self.stress_test_target_run_time_sec)
        stats = rutils.analyze_results(events,
                                       self.rtt_reference_distance_mm,
                                       self.rtt_reference_distance_margin_mm,
                                       self.rtt_min_expected_rssi_dbm,
                                       self.lci_reference,
                                       self.lcr_reference,
                                       summary_only=True)
        dut.log.debug("Stats=%s", stats)

        for bssid, stat in stats.items():
            asserts.assert_true(stat['num_no_results'] == 0,
                                "Missing (timed-out) results",
                                extras=stats)
            asserts.assert_false(stat['any_lci_mismatch'],
                                 "LCI mismatch",
                                 extras=stats)
            asserts.assert_false(stat['any_lcr_mismatch'],
                                 "LCR mismatch",
                                 extras=stats)
            asserts.assert_equal(stat['num_invalid_rssi'],
                                 0,
                                 "Invalid RSSI",
                                 extras=stats)
            asserts.assert_true(
                stat['num_failures'] <=
                self.rtt_max_failure_rate_two_sided_rtt_percentage *
                stat['num_results'] / 100,
                "Failure rate is too high",
                extras=stats)
            asserts.assert_true(
                stat['num_range_out_of_margin'] <=
                self.rtt_max_margin_exceeded_rate_two_sided_rtt_percentage *
                stat['num_success_results'] / 100,
                "Results exceeding error margin rate is too high",
                extras=stats)
        asserts.explicit_pass("RTT test done", extras=stats)
    def test_discover_knownaddress_giaddr_outside_subnet(self):
        addr, siaddr, _ = self._request_address(self.hwaddr)

        # New discover, same client, through relay in invalid subnet
        giaddr = OTHER_NETADDR_PREFIX + '200'
        resp = self._get_response(
            self._make_discover(self.hwaddr, giaddr=giaddr))
        asserts.assert_equal(resp, None)
def assert_bootp_response(resp, req):
    bootp = resp.getlayer(BOOTP)
    asserts.assert_equal(2, bootp.op, 'Invalid BOOTP op')
    asserts.assert_equal(1, bootp.htype, 'Invalid BOOTP htype')
    asserts.assert_equal(6, bootp.hlen, 'Invalid BOOTP hlen')
    asserts.assert_equal(0, bootp.hops, 'Invalid BOOTP hops')
    asserts.assert_equal(req.getlayer(BOOTP).xid, bootp.xid, 'Invalid XID')
    return bootp
 def test_discover_requestaddress_giaddr_outside_subnet(self):
     addr = NETADDR_PREFIX + '200'
     giaddr = OTHER_NETADDR_PREFIX + '201'
     req = self._make_discover(self.hwaddr, [('requested_addr', addr)],
                               ip_src=giaddr,
                               giaddr=giaddr)
     resp = self._get_response(req)
     asserts.assert_equal(resp, None)
 def test_request_selecting_giaddr_outside_subnet(self):
     addr = NETADDR_PREFIX + '200'
     giaddr = OTHER_NETADDR_PREFIX + '201'
     resp = self._get_response(
         self._make_request(self.hwaddr,
                            addr,
                            siaddr=self.server_addr,
                            giaddr=giaddr))
     asserts.assert_equal(resp, None)
    def test_rtt_mixed_80211mc_supporting_aps_wo_privilege(self):
        """Scan for APs and perform RTT on one supporting and one non-supporting
    IEEE 802.11mc APs with the device not having privilege access (expect
    failures)."""
        dut = self.android_devices[0]
        rutils.config_privilege_override(dut, True)
        rtt_aps = rutils.scan_with_rtt_support_constraint(dut, True)
        non_rtt_aps = rutils.scan_with_rtt_support_constraint(dut, False)
        mix_list = [rtt_aps[0], non_rtt_aps[0]]
        dut.log.debug("Visible non-IEEE 802.11mc APs=%s", mix_list)
        events = rutils.run_ranging(dut, mix_list, self.NUM_ITER,
                                    self.TIME_BETWEEN_ITERATIONS)
        stats = rutils.analyze_results(events, self.rtt_reference_distance_mm,
                                       self.rtt_reference_distance_margin_mm,
                                       self.rtt_min_expected_rssi_dbm,
                                       self.lci_reference, self.lcr_reference)
        dut.log.debug("Stats=%s", stats)

        for bssid, stat in stats.items():
            asserts.assert_true(stat['num_no_results'] == 0,
                                "Missing (timed-out) results",
                                extras=stats)
            if bssid == rtt_aps[0][wutils.WifiEnums.BSSID_KEY]:
                asserts.assert_false(stat['any_lci_mismatch'],
                                     "LCI mismatch",
                                     extras=stats)
                asserts.assert_false(stat['any_lcr_mismatch'],
                                     "LCR mismatch",
                                     extras=stats)
                asserts.assert_equal(stat['num_invalid_rssi'],
                                     0,
                                     "Invalid RSSI",
                                     extras=stats)
                asserts.assert_true(
                    stat['num_failures'] <=
                    self.rtt_max_failure_rate_two_sided_rtt_percentage *
                    stat['num_results'] / 100,
                    "Failure rate is too high",
                    extras=stats)
                asserts.assert_true(
                    stat['num_range_out_of_margin'] <=
                    self.rtt_max_margin_exceeded_rate_two_sided_rtt_percentage
                    * stat['num_success_results'] / 100,
                    "Results exceeding error margin rate is too high",
                    extras=stats)
            else:
                asserts.assert_true(
                    stat['num_failures'] == self.NUM_ITER,
                    "All one-sided RTT requests must fail when executed without privilege",
                    extras=stats)
                for code in stat['status_codes']:
                    asserts.assert_true(
                        code == rconsts.
                        EVENT_CB_RANGING_STATUS_RESPONDER_DOES_NOT_SUPPORT_IEEE80211MC,
                        "Expected non-support error code",
                        extras=stats)
        asserts.explicit_pass("RTT test done", extras=stats)
Exemple #28
0
    def run_test_rtt_80211mc_supporting_aps(self,
                                            dut,
                                            accuracy_evaluation=False):
        """Scan for APs and perform RTT only to those which support 802.11mc
        Args:
            dut: test device
            accuracy_evaluation: False - only evaluate success rate.
                                 True - evaluate both success rate and accuracy
                                 default is False.
        """
        rtt_supporting_aps = rutils.select_best_scan_results(
            rutils.scan_with_rtt_support_constraint(dut, True, repeat=10),
            select_count=2)
        dut.log.debug("RTT Supporting APs=%s", rtt_supporting_aps)
        events = rutils.run_ranging(dut, rtt_supporting_aps, self.NUM_ITER,
                                    self.TIME_BETWEEN_ITERATIONS)
        stats = rutils.analyze_results(events, self.rtt_reference_distance_mm,
                                       self.rtt_reference_distance_margin_mm,
                                       self.rtt_min_expected_rssi_dbm,
                                       self.lci_reference, self.lcr_reference)
        dut.log.debug("Stats=%s", stats)

        for bssid, stat in stats.items():
            asserts.assert_true(stat['num_no_results'] == 0,
                                "Missing (timed-out) results",
                                extras=stats)
            asserts.assert_false(stat['any_lci_mismatch'],
                                 "LCI mismatch",
                                 extras=stats)
            asserts.assert_false(stat['any_lcr_mismatch'],
                                 "LCR mismatch",
                                 extras=stats)
            asserts.assert_false(stat['invalid_num_attempted'],
                                 "Invalid (0) number of attempts",
                                 extras=stats)
            asserts.assert_false(stat['invalid_num_successful'],
                                 "Invalid (0) number of successes",
                                 extras=stats)
            asserts.assert_equal(stat['num_invalid_rssi'],
                                 0,
                                 "Invalid RSSI",
                                 extras=stats)
            asserts.assert_true(
                stat['num_failures'] <=
                self.rtt_max_failure_rate_two_sided_rtt_percentage *
                stat['num_results'] / 100,
                "Failure rate is too high",
                extras=stats)
            if accuracy_evaluation:
                asserts.assert_true(
                    stat['num_range_out_of_margin'] <=
                    self.rtt_max_margin_exceeded_rate_two_sided_rtt_percentage
                    * stat['num_success_results'] / 100,
                    "Results exceeding error margin rate is too high",
                    extras=stats)
        asserts.explicit_pass("RTT test done", extras=stats)
    def run_disable_rtt(self, disable_mode):
        """Validate the RTT disabled flows: whether by disabling Wi-Fi or entering
    doze mode.

    Args:
      disable_mode: The particular mechanism in which RTT is disabled. One of
                    the MODE_* constants.
    """
        dut = self.android_devices[0]

        # validate start-up conditions
        asserts.assert_true(dut.droid.wifiIsRttAvailable(),
                            "RTT is not available")

        # scan to get some APs to be used later
        all_aps = rutils.select_best_scan_results(
            rutils.scan_networks(dut), select_count=1)
        asserts.assert_true(len(all_aps) > 0, "Need at least one visible AP!")

        # disable RTT and validate broadcast & API
        if disable_mode == self.MODE_DISABLE_WIFI:
            # disabling Wi-Fi is not sufficient: since scan mode (and hence RTT) will
            # remain enabled - we need to disable the Wi-Fi chip aka Airplane Mode
            asserts.assert_true(
                utils.force_airplane_mode(dut, True),
                "Can not turn on airplane mode on: %s" % dut.serial)
        elif disable_mode == self.MODE_ENABLE_DOZE:
            asserts.assert_true(utils.enable_doze(dut), "Can't enable doze")
        elif disable_mode == self.MODE_DISABLE_LOCATIONING:
            utils.set_location_service(dut, False)

        rutils.wait_for_event(dut, rconsts.BROADCAST_WIFI_RTT_NOT_AVAILABLE)
        asserts.assert_false(dut.droid.wifiIsRttAvailable(),
                             "RTT is available")

        # request a range and validate error
        id = dut.droid.wifiRttStartRangingToAccessPoints(all_aps[0:1])
        event = rutils.wait_for_event(
            dut, rutils.decorate_event(rconsts.EVENT_CB_RANGING_ON_FAIL, id))
        asserts.assert_equal(
            event["data"][rconsts.EVENT_CB_RANGING_KEY_STATUS],
            rconsts.RANGING_FAIL_CODE_RTT_NOT_AVAILABLE, "Invalid error code")

        # enable RTT and validate broadcast & API
        if disable_mode == self.MODE_DISABLE_WIFI:
            asserts.assert_true(
                utils.force_airplane_mode(dut, False),
                "Can not turn off airplane mode on: %s" % dut.serial)
        elif disable_mode == self.MODE_ENABLE_DOZE:
            asserts.assert_true(utils.disable_doze(dut), "Can't disable doze")
        elif disable_mode == self.MODE_DISABLE_LOCATIONING:
            utils.set_location_service(dut, True)

        rutils.wait_for_event(dut, rconsts.BROADCAST_WIFI_RTT_AVAILABLE)
        asserts.assert_true(dut.droid.wifiIsRttAvailable(),
                            "RTT is not available")
Exemple #30
0
    def run_message_no_queue(self, payload_size):
        """Validate L2 message exchange between publisher & subscriber with no
    queueing - i.e. wait for an ACK on each message before sending the next
    message.

    Args:
      payload_size: min, typical, or max (PAYLOAD_SIZE_xx).
    """
        discovery_info = self.prep_message_exchange()
        p_dut = discovery_info["p_dut"]
        s_dut = discovery_info["s_dut"]
        p_disc_id = discovery_info["p_disc_id"]
        s_disc_id = discovery_info["s_disc_id"]
        peer_id_on_sub = discovery_info["peer_id_on_sub"]

        for i in range(self.NUM_MSGS_NO_QUEUE):
            msg = self.create_msg(s_dut.aware_capabilities, payload_size, i)
            msg_id = self.get_next_msg_id()
            s_dut.droid.wifiAwareSendMessage(s_disc_id, peer_id_on_sub, msg_id,
                                             msg, 0)
            tx_event = autils.wait_for_event(
                s_dut, aconsts.SESSION_CB_ON_MESSAGE_SENT)
            rx_event = autils.wait_for_event(
                p_dut, aconsts.SESSION_CB_ON_MESSAGE_RECEIVED)
            asserts.assert_equal(
                msg_id, tx_event["data"][aconsts.SESSION_CB_KEY_MESSAGE_ID],
                "Subscriber -> Publisher message ID corrupted")
            autils.assert_equal_strings(
                msg,
                rx_event["data"][aconsts.SESSION_CB_KEY_MESSAGE_AS_STRING],
                "Subscriber -> Publisher message %d corrupted" % i)

        peer_id_on_pub = rx_event["data"][aconsts.SESSION_CB_KEY_PEER_ID]
        for i in range(self.NUM_MSGS_NO_QUEUE):
            msg = self.create_msg(s_dut.aware_capabilities, payload_size,
                                  1000 + i)
            msg_id = self.get_next_msg_id()
            p_dut.droid.wifiAwareSendMessage(p_disc_id, peer_id_on_pub, msg_id,
                                             msg, 0)
            tx_event = autils.wait_for_event(
                p_dut, aconsts.SESSION_CB_ON_MESSAGE_SENT)
            rx_event = autils.wait_for_event(
                s_dut, aconsts.SESSION_CB_ON_MESSAGE_RECEIVED)
            asserts.assert_equal(
                msg_id, tx_event["data"][aconsts.SESSION_CB_KEY_MESSAGE_ID],
                "Publisher -> Subscriber message ID corrupted")
            autils.assert_equal_strings(
                msg,
                rx_event["data"][aconsts.SESSION_CB_KEY_MESSAGE_AS_STRING],
                "Publisher -> Subscriber message %d corrupted" % i)

        # verify there are no more events
        time.sleep(autils.EVENT_TIMEOUT)
        autils.verify_no_more_events(p_dut, timeout=0)
        autils.verify_no_more_events(s_dut, timeout=0)