def _verify_ipv6_tethering(self, dut):
        """Verify IPv6 tethering.

    Args:
      dut: Android device that is being checked
    """

        # httpRequestString() returns the IP address when visiting the URL
        http_response = dut.droid.httpRequestString(self.url)
        self.log.info("IP address %s " % http_response)
        active_link_addrs = dut.droid.connectivityGetAllAddressesOfActiveLink()

        if dut == self.hotspot_device and nutils.carrier_supports_ipv6(dut) \
          or nutils.supports_ipv6_tethering(self.hotspot_device):
            asserts.assert_true(
                nutils.is_ipaddress_ipv6(http_response),
                "The http response did not return IPv6 address")
            asserts.assert_true(
                active_link_addrs and http_response in str(active_link_addrs),
                "Could not find IPv6 address in link properties")
            asserts.assert_true(
                dut.droid.connectivityHasIPv6DefaultRoute(),
                "Could not find IPv6 default route in link properties")
        else:
            asserts.assert_false(
                dut.droid.connectivityHasIPv6DefaultRoute(),
                "Found IPv6 default route in link properties")
 def test_discover_srcaddr_outside_subnet(self):
     srcaddr = OTHER_NETADDR_PREFIX + '200'
     resp = self._get_response(
         self._make_discover(self.hwaddr, ip_src=srcaddr))
     self._assert_offer(resp)
     asserts.assert_false(srcaddr == get_yiaddr(resp),
                          'Server offered invalid address')
 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 test_autojoin_Ap2_2g(self):
        """Test wifi auto join functionality move in low range of AP2.

         1. Attenuate the signal to move in range of AP2 and Ap1 not visible at all.
         2. Wake up the device.
         3. Check that device is connected to right BSSID and maintain stable
            connection to BSSID in range.
        """
        att0, att1, att2, attn3 = self.atten_val["Ap2_2g"]
        variance = 5
        attenuations = ([att0, att1 + variance * 2, att2,
                         attn3], [att0, att1 + variance, att2,
                                  attn3], [att0, att1, att2, attn3],
                        [att0, att1 - variance, att2, attn3])
        name_func = lambda att_value, bssid: (
            "test_autojoin_Ap2_2g_AP1_{}_AP2"
            "_{}_AP3_{}").format(att_value[0], att_value[1], att_value[2])
        failed = self.run_generated_testcases(
            self.set_attn_and_validate_connection,
            attenuations,
            args=(self.reference_networks[1]["2g"]['bssid'], ),
            name_func=name_func)
        asserts.assert_false(
            failed,
            "Number of test_autojoin_Ap2_2g failed {}".format(len(failed)))
    def test_nmi_randomization_on_interval(self):
        """Validate randomization of the NMI (NAN management interface) on a set
    interval. Default value is 30 minutes - change to a small value to allow
    testing in real-time"""
        RANDOM_INTERVAL = 120  # minimal value in current implementation

        dut = self.android_devices[0]

        # set randomization interval to 120 seconds
        autils.configure_mac_random_interval(dut, RANDOM_INTERVAL)

        # attach and wait for first identity
        id = dut.droid.wifiAwareAttach(True)
        autils.wait_for_event(dut, aconsts.EVENT_CB_ON_ATTACHED)
        ident_event = autils.wait_for_event(
            dut, aconsts.EVENT_CB_ON_IDENTITY_CHANGED)
        mac1 = ident_event["data"]["mac"]

        # wait for second identity callback
        # Note: exact randomization interval is not critical, just approximate,
        # hence giving a few more seconds.
        ident_event = autils.wait_for_event(
            dut,
            aconsts.EVENT_CB_ON_IDENTITY_CHANGED,
            timeout=RANDOM_INTERVAL + 5)
        mac2 = ident_event["data"]["mac"]

        # validate MAC address is randomized
        asserts.assert_false(
            mac1 == mac2,
            "Randomized MAC addresses (%s, %s) should be different" %
            (mac1, mac2))

        # clean-up
        dut.droid.wifiAwareDestroy(id)
    def test_fail_to_connect_to_wpa_psk_2g_after_user_forgot_network(self):
        """
        Adds a network suggestion and ensures that the device does not
        connect to it after the user forgot the network previously.

        Steps:
        1. Send a network suggestion to the device with
           isAppInteractionRequired set.
        2. Wait for the device to connect to it.
        3. Ensure that we did receive the post connection broadcast
           (isAppInteractionRequired = True).
        4. Simulate user forgetting the network and the device does not
           connecting back even though the suggestion is active from the app.
        """
        network_suggestion = self.wpa_psk_2g
        network_suggestion[WifiEnums.IS_APP_INTERACTION_REQUIRED] = True
        self.add_suggestions_and_ensure_connection(
            [network_suggestion], self.wpa_psk_2g[WifiEnums.SSID_KEY],
            True)

        # Simulate user forgetting the ephemeral network.
        self.dut.droid.wifiDisableEphemeralNetwork(
            self.wpa_psk_2g[WifiEnums.SSID_KEY])
        wutils.wait_for_disconnect(self.dut)
        self.dut.log.info("Disconnected from network %s", self.wpa_psk_2g)
        self.dut.ed.clear_all_events()

        # Now ensure that we don't connect back even though the suggestion
        # is still active.
        asserts.assert_false(
            wutils.wait_for_connect(self.dut,
                                    self.wpa_psk_2g[WifiEnums.SSID_KEY],
                                    assert_on_fail=False),
            "Device should not connect back")
Example #7
0
 def turn_location_off_and_scan_toggle_off(self):
     """Turns off wifi location scans."""
     utils.set_location_service(self.dut, False)
     self.dut.droid.wifiScannerToggleAlwaysAvailable(False)
     msg = "Failed to turn off location service's scan."
     asserts.assert_false(self.dut.droid.wifiScannerIsAlwaysAvailable(),
                          msg)
Example #8
0
def validate_forbidden_callbacks(ad, limited_cb=None):
    """Validate that the specified callbacks have not been called more then permitted.

  In addition to the input configuration also validates that forbidden callbacks
  have never been called.

  Args:
    ad: Device on which to run.
    limited_cb: Dictionary of CB_EV_* ids and maximum permitted calls (0
                meaning never).
  """
    cb_data = json.loads(ad.adb.shell('cmd wifiaware native_cb get_cb_count'))

    if limited_cb is None:
        limited_cb = {}
    # add callbacks which should never be called
    limited_cb[aconsts.CB_EV_MATCH_EXPIRED] = 0

    fail = False
    for cb_event in limited_cb.keys():
        if cb_event in cb_data:
            if cb_data[cb_event] > limited_cb[cb_event]:
                fail = True
                ad.log.info(
                    'Callback %s observed %d times: more then permitted %d times',
                    cb_event, cb_data[cb_event], limited_cb[cb_event])

    asserts.assert_false(fail, 'Forbidden callbacks observed', extras=cb_data)
    def setup_class(self):
        self.dut = self.android_devices[0]
        self.USB_TETHERED = False
        self.next_hwaddr_index = 0
        self.stop_arp = Event()

        conf.checkIPaddr = 0
        conf.checkIPsrc = 0
        # Allow using non-67 server ports as long as client uses 68
        bind_layers(UDP, BOOTP, dport=CLIENT_PORT)

        iflist_before = get_if_list()
        self._start_usb_tethering(self.dut)
        self.iface = self._wait_for_new_iface(iflist_before)
        self.real_hwaddr = get_if_raw_hwaddr(self.iface)

        # Start a thread to answer to all ARP "who-has"
        thread = Thread(target=self._sniff_arp, args=(self.stop_arp, ))
        thread.start()

        # Discover server IP and device hwaddr
        hwaddr = self._next_hwaddr()
        resp = self._get_response(self._make_discover(hwaddr))
        asserts.assert_false(None == resp,
                             "Device did not reply to first DHCP discover")
        self.server_addr = getopt(resp, 'server_id')
        self.dut_hwaddr = resp.getlayer(Ether).src
        asserts.assert_false(None == self.server_addr,
                             "DHCP server did not specify server identifier")
        # Ensure that we don't depend on assigned route/gateway on the host
        conf.route.add(host=self.server_addr, dev=self.iface, gw="0.0.0.0")
    def test_autojoin_swtich_AP2toAp1(self):
        """Test wifi auto join functionality move from low range of AP2 to better
           range of AP1.

         1. Attenuate the signal to low range of AP2 and medium range of AP1.
         2. Wake up the device.
         3. Check that device is connected to right BSSID and maintain stable
            connection to BSSID in range.
        """
        att0, att1, att2 = self.atten_val["Swtich_AP2toAp1"]
        variance = 5
        attenuations = ([att0 + variance, att1 - variance,
                         att2], [att0, att1, att2],
                        [att0 - variance, att1 + variance, att2])
        name_func = lambda att_value, bssid: (
            "test_autojoin_swtich_AP2toAp1_AP1_{}_AP2"
            "_{}_AP3_{}").format(att_value[0], att_value[1], att_value[2])
        failed = self.run_generated_testcases(
            self.set_attn_and_validate_connection,
            attenuations,
            args=(self.reference_networks[0]["2g"]['bssid'], ),
            name_func=name_func)
        asserts.assert_false(
            failed, "Number of test_autojoin_swtich_AP2toAp1 failed {}".format(
                len(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_requestaddress_wrongsubnet(self):
     addr = OTHER_NETADDR_PREFIX + '200'
     resp = self._get_response(
         self._make_discover(self.hwaddr, [('requested_addr', addr)]))
     self._assert_offer(resp)
     self._assert_unicast(resp)
     asserts.assert_false(
         get_yiaddr(resp) == addr, 'Server offered invalid address')
    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)
    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")
Example #15
0
 def test_toggle_location_setting_off_not_report_location(self):
     """
         1. Toggle location setting off.
         2. Open Google Map and ask for location.
         3. Validate there is no location fix in logcat.
     """
     self.ad.adb.shell('settings put secure location_mode 0')
     gutils.launch_google_map(self.ad)
     asserts.assert_false(gutils.check_location_api(self.ad, retries=1),
                          'DUT Still receive location fix')
Example #16
0
 def test_toggle_location_permission_off(self):
     """
         1. Toggle Google Map location permission off.
         2. Open Google Map and ask for location.
         3. Validate there is no location fix in logcat.
     """
     gutils.grant_location_permission(self.ad, False)
     gutils.launch_google_map(self.ad)
     asserts.assert_false(gutils.check_location_api(self.ad, retries=1),
                          'DUT still receive location fix')
 def test_tdls_supported(self):
     model = acts.utils.trim_model_name(self.dut.model)
     self.log.debug("Model is %s" % model)
     if model in self.tdls_models:
         asserts.assert_true(self.dut.droid.wifiIsTdlsSupported(), (
             "TDLS should be supported on %s, but device is "
             "reporting not supported.") % model)
     else:
         asserts.assert_false(self.dut.droid.wifiIsTdlsSupported(), (
             "TDLS should not be supported on %s, but device "
             "is reporting supported.") % model)
 def test_tdls_supported(self):
     model = self.dut.model
     self.log.debug("Model is %s" % model)
     if not model.startswith("volantis"):
         asserts.assert_true(self.dut.droid.wifiIsTdlsSupported(), (
             "TDLS should be supported on %s, but device is "
             "reporting not supported.") % model)
     else:
         asserts.assert_false(self.dut.droid.wifiIsTdlsSupported(), (
             "TDLS should not be supported on %s, but device "
             "is reporting supported.") % model)
 def test_request_selecting_wrongsiaddr(self):
     addr = NETADDR_PREFIX + '200'
     wrong_siaddr = NETADDR_PREFIX + '201'
     asserts.assert_false(
         wrong_siaddr == self.server_addr,
         'Test assumption not met: server addr is ' + wrong_siaddr)
     resp = self._get_response(
         self._make_request(self.hwaddr, addr, siaddr=wrong_siaddr))
     asserts.assert_true(
         resp == None,
         'Received response for request with incorrect siaddr')
    def test_request_initreboot_incorrectlease(self):
        otheraddr = NETADDR_PREFIX + '123'
        addr, siaddr, _ = self._request_address(self.hwaddr)
        asserts.assert_false(
            addr == otheraddr,
            "Test assumption not met: server assigned " + otheraddr)

        resp = self._get_response(
            self._make_request(self.hwaddr, otheraddr, siaddr=None))
        self._assert_nak(resp)
        self._assert_broadcast(resp)
    def run_test_rtt_non_80211mc_supporting_aps(self,
                                                dut,
                                                accuracy_evaluation=False):
        """Scan for APs and perform RTT on non-IEEE 802.11mc supporting APs
        Args:
            dut: test device
            accuracy_evaluation: False - only evaluate success rate.
                                 True - evaluate both success rate and accuracy
                                 default is False.
        """
        asserts.skip_if(
            not dut.rtt_capabilities[rconsts.CAP_RTT_ONE_SIDED_SUPPORTED],
            "Device does not support one-sided RTT")

        non_rtt_aps = rutils.select_best_scan_results(
            rutils.scan_with_rtt_support_constraint(dut, False),
            select_count=1)
        dut.log.debug("Visible non-IEEE 802.11mc APs=%s", non_rtt_aps)
        asserts.assert_true(len(non_rtt_aps) > 0, "Need at least one AP!")
        events = rutils.run_ranging(dut, non_rtt_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, [], [])
        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_one_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_one_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)
Example #22
0
 def set_power_mode_parameters(self, ad):
     """Set the power configuration DW parameters for the device based on any
 configuration overrides (if provided)"""
     if self.aware_default_power_mode == "INTERACTIVE":
         autils.config_dw_high_power(ad)
     elif self.aware_default_power_mode == "NON_INTERACTIVE":
         autils.config_dw_low_power(ad)
     else:
         asserts.assert_false(
             "The 'aware_default_power_mode' configuration must be INTERACTIVE or "
             "NON_INTERACTIVE")
    def test_discover_assigned_otherhost(self):
        addr, siaddr, _ = self._request_address(self.hwaddr)

        # New discover, same address, different client
        resp = self._get_response(
            self._make_discover(self.other_hwaddr, [('requested_addr', addr)]))

        self._assert_offer(resp)
        asserts.assert_false(
            get_yiaddr(resp) == addr, "Already assigned address offered")
        self._assert_unicast(resp, get_yiaddr(resp))
        self._assert_broadcastbit(resp, isset=False)
Example #24
0
    def run_infra_assoc_oob_ndp_stress(self, with_ndp_traffic):
        """Validates that Wi-Fi Aware NDP does not interfere with infrastructure
    (AP) association.

    Test assumes (and verifies) that device is already associated to an AP.

    Args:
      with_ndp_traffic: True to run traffic over the NDP.
    """
        init_dut = self.android_devices[0]
        resp_dut = self.android_devices[1]

        # check that associated and start tracking
        init_dut.droid.wifiStartTrackingStateChange()
        resp_dut.droid.wifiStartTrackingStateChange()
        asserts.assert_true(self.is_associated(init_dut),
                            "DUT is not associated to an AP!")
        asserts.assert_true(self.is_associated(resp_dut),
                            "DUT is not associated to an AP!")

        # set up NDP
        (init_req_key, resp_req_key, init_aware_if, resp_aware_if, init_ipv6,
         resp_ipv6) = autils.create_oob_ndp(init_dut, resp_dut)
        self.log.info("Interface names: I=%s, R=%s", init_aware_if,
                      resp_aware_if)
        self.log.info("Interface addresses (IPv6): I=%s, R=%s", init_ipv6,
                      resp_ipv6)

        # wait for any disassociation change events
        q = queue.Queue()
        init_thread = threading.Thread(target=self.wait_for_disassociation,
                                       args=(q, init_dut))
        resp_thread = threading.Thread(target=self.wait_for_disassociation,
                                       args=(q, resp_dut))

        init_thread.start()
        resp_thread.start()

        any_disassociations = False
        try:
            q.get(True, self.TEST_DURATION_SECONDS)
            any_disassociations = True  # only happens on any disassociation
        except queue.Empty:
            pass
        finally:
            # TODO: no way to terminate thread (so even if we fast fail we still have
            # to wait for the full timeout.
            init_dut.droid.wifiStopTrackingStateChange()
            resp_dut.droid.wifiStopTrackingStateChange()

        asserts.assert_false(any_disassociations,
                             "Wi-Fi disassociated during test run")
    def test_config_store(self):
        params = list(itertools.product(self.config_store_networks,
                                        self.android_devices))

        def name_gen(p):
            return "test_connection_to-%s-for_config_store" % p[0][
                WifiEnums.SSID_KEY]

        failed = self.run_generated_testcases(
            self.connect_to_wifi_network_toggle_wifi_and_run_iperf,
            params,
            name_func=name_gen)
        asserts.assert_false(failed, "Failed ones: {}".format(failed))
    def test_nmi_ndi_randomization_on_enable(self):
        """Validate randomization of the NMI (NAN management interface) and all NDIs
    (NAN data-interface) on each enable/disable cycle"""
        dut = self.android_devices[0]

        # re-enable randomization interval (since if disabled it may also disable
        # the 'randomize on enable' feature).
        autils.configure_mac_random_interval(dut, 1800)

        # DUT: attach and wait for confirmation & identity 10 times
        mac_addresses = {}
        for i in range(self.NUM_ITERATIONS):
            id = dut.droid.wifiAwareAttach(True)
            autils.wait_for_event(dut, aconsts.EVENT_CB_ON_ATTACHED)
            ident_event = autils.wait_for_event(
                dut, aconsts.EVENT_CB_ON_IDENTITY_CHANGED)

            # process NMI
            mac = ident_event["data"]["mac"]
            dut.log.info("NMI=%s", mac)
            if mac in mac_addresses:
                mac_addresses[mac] = mac_addresses[mac] + 1
            else:
                mac_addresses[mac] = 1

            # process NDIs
            time.sleep(5)  # wait for NDI creation to complete
            for j in range(
                    dut.aware_capabilities[aconsts.CAP_MAX_NDI_INTERFACES]):
                ndi_interface = "%s%d" % (aconsts.AWARE_NDI_PREFIX, j)
                ndi_mac = autils.get_mac_addr(dut, ndi_interface)
                dut.log.info("NDI %s=%s", ndi_interface, ndi_mac)
                if ndi_mac in mac_addresses:
                    mac_addresses[ndi_mac] = mac_addresses[ndi_mac] + 1
                else:
                    mac_addresses[ndi_mac] = 1

            dut.droid.wifiAwareDestroy(id)

        # Test for uniqueness
        for mac in mac_addresses.keys():
            if mac_addresses[mac] != 1:
                asserts.fail("MAC address %s repeated %d times (all=%s)" %
                             (mac, mac_addresses[mac], mac_addresses))

        # Verify that infra interface (e.g. wlan0) MAC address is not used for NMI
        infra_mac = autils.get_wifi_mac_address(dut)
        asserts.assert_false(
            infra_mac in mac_addresses,
            "Infrastructure MAC address (%s) is used for Aware NMI (all=%s)" %
            (infra_mac, mac_addresses))
    def validate_full_tether_startup(self,
                                     band=None,
                                     hidden=None,
                                     test_ping=False,
                                     test_clients=None):
        """Test full startup of wifi tethering

        1. Report current state.
        2. Switch to AP mode.
        3. verify SoftAP active.
        4. Shutdown wifi tethering.
        5. verify back to previous mode.
        """
        initial_wifi_state = self.dut.droid.wifiCheckState()
        initial_cell_state = tel_utils.is_sim_ready(self.log, self.dut)
        self.dut.log.info("current state: %s", initial_wifi_state)
        self.dut.log.info("is sim ready? %s", initial_cell_state)
        if initial_cell_state:
            self.check_cell_data_and_enable()
        config = self.create_softap_config()
        wutils.start_wifi_tethering(self.dut,
                                    config[wutils.WifiEnums.SSID_KEY],
                                    config[wutils.WifiEnums.PWD_KEY], band,
                                    hidden)
        if hidden:
            # First ensure it's not seen in scan results.
            self.confirm_softap_not_in_scan_results(
                config[wutils.WifiEnums.SSID_KEY])
            # If the network is hidden, it should be saved on the client to be
            # seen in scan results.
            config[wutils.WifiEnums.HIDDEN_KEY] = True
            ret = self.dut_client.droid.wifiAddNetwork(config)
            asserts.assert_true(ret != -1, "Add network %r failed" % config)
            self.dut_client.droid.wifiEnableNetwork(ret, 0)
        self.confirm_softap_in_scan_results(config[wutils.WifiEnums.SSID_KEY])
        if test_ping:
            self.validate_ping_between_softap_and_client(config)
        if test_clients:
            if hasattr(self, 'arduino_wifi_dongles'):
                self.validate_traffic_between_softap_clients(config)
            if len(self.android_devices) > 2:
                self.validate_ping_between_two_clients(config)
        wutils.stop_wifi_tethering(self.dut)
        asserts.assert_false(self.dut.droid.wifiIsApEnabled(),
                             "SoftAp is still reported as running")
        if initial_wifi_state:
            wutils.wait_for_wifi_state(self.dut, True)
        elif self.dut.droid.wifiCheckState():
            asserts.fail(
                "Wifi was disabled before softap and now it is enabled")
 def test_no_reconnect_manual_disable_wifi(self):
     """
     Tests that Wifi Wake does not reconnect to a network if the user turned
     off Wifi while connected to that network and the user has not moved
     (i.e. moved out of range of the AP then came back).
     """
     wutils.wifi_connect(self.dut, self.ap_a, num_of_tries=5)
     wutils.wifi_toggle_state(self.dut, new_state=False)
     time.sleep(PRESCAN_DELAY_SEC)
     self.do_location_scan(2 * CONSECUTIVE_MISSED_SCANS_REQUIRED_TO_EVICT +
                           2)
     asserts.assert_false(
         self.dut.droid.wifiCheckState(),
         "Expect Wifi Wake to not enable Wifi, but Wifi was enabled.")
    def test_softap_auto_shut_off(self):
        """Test for softap auto shut off

        1. Turn off hotspot
        2. Register softap callback
        3. Let client connect to the hotspot
        4. Start wait [wifi_constants.DEFAULT_SOFTAP_TIMEOUT_S] seconds
        5. Check hotspot doesn't shut off
        6. Let client disconnect to the hotspot
        7. Start wait [wifi_constants.DEFAULT_SOFTAP_TIMEOUT_S] seconds
        8. Check hotspot auto shut off
        """
        config = wutils.start_softap_and_verify(self, WIFI_CONFIG_APBAND_AUTO)
        # Register callback after softap enabled to avoid unnecessary callback
        # impact the test
        callbackId = self.dut.droid.registerSoftApCallback()
        # Verify clients will update immediately after register callback
        wutils.wait_for_expected_number_of_softap_clients(
            self.dut, callbackId, 0)
        wutils.wait_for_expected_softap_state(
            self.dut, callbackId, wifi_constants.WIFI_AP_ENABLED_STATE)

        # Force DUTs connect to Network
        wutils.wifi_connect(self.dut_client, config, check_connectivity=False)
        wutils.wait_for_expected_number_of_softap_clients(
            self.dut, callbackId, 1)

        self.dut.log.info("Start waiting %s seconds with 1 clients ",
                          wifi_constants.DEFAULT_SOFTAP_TIMEOUT_S * 1.1)
        time.sleep(wifi_constants.DEFAULT_SOFTAP_TIMEOUT_S * 1.1)

        # When client connected, softap should keep as enabled
        asserts.assert_true(self.dut.droid.wifiIsApEnabled(),
                            "SoftAp is not reported as running")

        wutils.wifi_toggle_state(self.dut_client, False)
        wutils.wait_for_expected_number_of_softap_clients(
            self.dut, callbackId, 0)
        self.dut.log.info("Start waiting %s seconds with 0 client",
                          wifi_constants.DEFAULT_SOFTAP_TIMEOUT_S * 1.1)
        time.sleep(wifi_constants.DEFAULT_SOFTAP_TIMEOUT_S * 1.1)
        # Softap should stop since no client connected
        # doesn't disconnect before softap stop
        wutils.wait_for_expected_softap_state(
            self.dut, callbackId, wifi_constants.WIFI_AP_DISABLING_STATE)
        wutils.wait_for_expected_softap_state(
            self.dut, callbackId, wifi_constants.WIFI_AP_DISABLED_STATE)
        asserts.assert_false(self.dut.droid.wifiIsApEnabled(),
                             "SoftAp is not reported as running")
        self.dut.droid.unregisterSoftApCallback(callbackId)
    def test_request_rebinding_wrongaddr(self):
        otheraddr = NETADDR_PREFIX + '123'
        addr, siaddr, _ = self._request_address(self.hwaddr)
        asserts.assert_false(
            addr == otheraddr,
            "Test assumption not met: server assigned " + otheraddr)

        resp = self._get_response(
            self._make_request(self.hwaddr,
                               reqaddr=None,
                               siaddr=siaddr,
                               ciaddr=otheraddr))
        self._assert_nak(resp)
        self._assert_broadcast(resp)