Beispiel #1
0
    def start_softap_and_verify(self, band):
        """Bring-up softap and verify AP mode and in scan results.

        Args:
            band: The band to use for softAP.

        """
        config = wutils.create_softap_config()
        wutils.start_wifi_tethering(self.dut,
                                    config[wutils.WifiEnums.SSID_KEY],
                                    config[wutils.WifiEnums.PWD_KEY],
                                    band=band)
        asserts.assert_true(self.dut.droid.wifiIsApEnabled(),
                            "SoftAp is not reported as running")
        wutils.start_wifi_connection_scan_and_ensure_network_found(
            self.dut_client, config[wutils.WifiEnums.SSID_KEY])
        return config
Beispiel #2
0
def toggle_airplane_mode_on_and_off(ad):
    """Turn ON and OFF Airplane mode.

    ad: An AndroidDevice object.
    Returns: Assert if turning on/off Airplane mode fails.

    """
    ad.log.debug("Toggling Airplane mode ON.")
    asserts.assert_true(
        utils.force_airplane_mode(ad, True),
        "Can not turn on airplane mode on: %s" % ad.serial)
    time.sleep(DEFAULT_TIMEOUT)
    ad.log.debug("Toggling Airplane mode OFF.")
    asserts.assert_true(
        utils.force_airplane_mode(ad, False),
        "Can not turn on airplane mode on: %s" % ad.serial)
    time.sleep(DEFAULT_TIMEOUT)
Beispiel #3
0
    def beacon_loss(self, channel):
        setup_ap(access_point=self.ap,
                 profile_name='whirlwind',
                 channel=channel,
                 ssid=self.ssid)
        time.sleep(self.wait_ap_startup_s)
        if channel > 14:
            self.in_use_interface = self.ap.wlan_5g
        else:
            self.in_use_interface = self.ap.wlan_2g

        # TODO(b/144505723): [ACTS] update BeaconLossTest.py to handle client
        # roaming, saved networks, etc.
        self.log.info("sending associate command for ssid %s", self.ssid)
        associate(client=self.wlan_device, ssid=self.ssid)

        asserts.assert_true(self.wlan_device.is_connected(),
                            'Failed to connect.')

        time.sleep(self.wait_client_connection_setup_s)

        for _ in range(0, self.num_of_iterations):
            # Turn off AP radio
            self.log.info("turning off radio")
            self.ap.iwconfig.ap_iwconfig(self.in_use_interface, "txpower off")
            time.sleep(self.wait_after_ap_txoff_s)

            # Did we disconnect from AP?
            asserts.assert_false(self.wlan_device.is_connected(),
                                 'Failed to disconnect.')

            # Turn on AP radio
            self.log.info("turning on radio")
            self.ap.iwconfig.ap_iwconfig(self.in_use_interface, "txpower on")
            time.sleep(self.wait_to_connect_after_ap_txon_s)

            # Tell the client to connect
            self.log.info("sending associate command for ssid %s" % self.ssid)
            associate(client=self.wlan_device, ssid=self.ssid)
            time.sleep(self.wait_client_connection_setup_s)

            # Did we connect back to WiFi?
            asserts.assert_true(self.wlan_device.is_connected(),
                                'Failed to connect back.')

        return True
Beispiel #4
0
    def ensure_verity_disabled(self):
        """Ensures that verity is enabled.

        If verity is not enabled, this call will reboot the phone. Note that
        this only works on debuggable builds.
        """
        logging.debug("Disabling verity and remount for %s", self.serial_number)
        asserts.assert_true(self.adb.ensure_root(),
                            "device %s cannot run as root", self.serial_number)
        # The below properties will only exist if verity has been enabled.
        system_verity = self.adb.getprop('partition.system.verified')
        vendor_verity = self.adb.getprop('partition.vendor.verified')
        if system_verity or vendor_verity:
            self.adb.disable_verity()
            self.reboot()
        self.adb.remount()
        self.adb.wait_for_device(timeout=self.WAIT_FOR_DEVICE_TIMEOUT_SECONDS)
Beispiel #5
0
    def test_dns_server_link_properties_strict_mode(self):
        """ Verify DNS server in the link properties when set in strict mode

        Steps:
            1. Set DNS server hostname in Private DNS settings (stict mode)
            2. Verify that DNS server set in settings is in link properties
            3. Verify for WiFi as well as LTE
        """
        # start tcpdump on device
        self._start_tcp_dump(self.dut)

        # set private DNS to strict mode
        cutils.set_private_dns(
            self.dut, cconst.PRIVATE_DNS_MODE_STRICT, cconst.DNS_GOOGLE)

        # connect DUT to wifi network
        wutils.start_wifi_connection_scan_and_ensure_network_found(
            self.dut, self.ipv4_ipv6_network[SSID])
        wutils.wifi_connect(self.dut, self.ipv4_ipv6_network)
        for host in self.ping_hosts:
            wutils.validate_connection(self.dut, host)

        # DNS server in link properties for wifi network
        link_prop = self.dut.droid.connectivityGetActiveLinkProperties()
        wifi_dns_servers = link_prop['PrivateDnsServerName']
        self.log.info("Link prop: %s" % wifi_dns_servers)

        # DUT is on LTE data
        wutils.reset_wifi(self.dut)
        time.sleep(1) # wait till lte network becomes active
        for host in self.ping_hosts:
            wutils.validate_connection(self.dut, host)

        # DNS server in link properties for cell network
        link_prop = self.dut.droid.connectivityGetActiveLinkProperties()
        lte_dns_servers = link_prop['PrivateDnsServerName']
        self.log.info("Link prop: %s" % lte_dns_servers)

        # stop tcpdump on device
        pcap_file = self._stop_tcp_dump(self.dut)

        # Verify DNS server in link properties
        asserts.assert_true(cconst.DNS_GOOGLE in wifi_dns_servers,
                            "Hostname not in link properties - wifi network")
        asserts.assert_true(cconst.DNS_GOOGLE in lte_dns_servers,
                            "Hostname not in link properites - cell network")
    def test_discover_assigned_ownaddress(self):
        addr, siaddr, resp = self._request_address(self.hwaddr)

        lease_time = getopt(resp, 'lease_time')
        server_id = getopt(resp, 'server_id')
        asserts.assert_true(lease_time >= 60, "Lease time is too short")
        asserts.assert_false(addr == INET4_ANY, "Assigned address is empty")
        # Wait to test lease expiration time change
        time.sleep(3)

        # New discover, same address
        resp = self._assert_renews(self._make_discover(self.hwaddr),
                                   addr,
                                   lease_time,
                                   resp_type=OFFER)
        self._assert_unicast(resp, get_yiaddr(resp))
        self._assert_broadcastbit(resp, isset=False)
  def run_match_filters_per_spec(self, do_unsolicited_passive):
    """Validate all the match filter combinations in the Wi-Fi Aware spec,
    Appendix H.

    Args:
      do_unsolicited_passive: True to run the Unsolicited/Passive tests, False
                              to run the Solicited/Active tests.
    """
    p_dut = self.android_devices[0]
    p_dut.pretty_name = "Publisher"
    s_dut = self.android_devices[1]
    s_dut.pretty_name = "Subscriber"

    fails = []
    for i in range(len(self.match_filters)):
      test_info = self.match_filters[i]
      if do_unsolicited_passive:
        pub_type = "Unsolicited"
        sub_type = "Passive"
        pub_mf = test_info[0]
        sub_mf = test_info[1]
        expect_discovery = test_info[3]
      else:
        pub_type = "Solicited"
        sub_type = "Active"
        pub_mf = test_info[1]
        sub_mf = test_info[0]
        expect_discovery = test_info[2]

      self.log.info("Test #%d: %s Pub MF=%s, %s Sub MF=%s: Discovery %s", i,
                    pub_type, pub_mf, sub_type, sub_mf, "EXPECTED"
                    if test_info[2] else "UNEXPECTED")
      result = self.run_discovery(
          p_dut,
          s_dut,
          p_mf=pub_mf,
          s_mf=sub_mf,
          do_unsolicited_passive=do_unsolicited_passive,
          expect_discovery=expect_discovery)
      self.log.info("Test #%d %s Pub/%s Sub %s", i, pub_type, sub_type, "PASS"
                    if result else "FAIL")
      if not result:
        fails.append(i)

    asserts.assert_true(
        len(fails) == 0, "Some match filter tests are failing", extras=fails)
Beispiel #8
0
    def setup_class(self):
        super().setup_class()

        self.dut = self.android_devices[0]
        wutils.wifi_test_device_init(self.dut)

        req_params = ["iot_networks", "rvr_test_params"]
        opt_params = ["angle_params", "usb_port"]
        self.unpack_userparams(req_param_names=req_params,
                               opt_param_names=opt_params)

        asserts.assert_true(
            len(self.iot_networks) > 0,
            "Need at least one iot network with psk.")

        wutils.wifi_toggle_state(self.dut, True)
        if "rvr_test_params" in self.user_params:
            self.iperf_server = self.iperf_servers[0]
            self.MaxdB = self.rvr_test_params["rvr_atten_MaxDB"]
            self.MindB = self.rvr_test_params["rvr_atten_MinDB"]
            self.stepdB = self.rvr_test_params["rvr_atten_step"]

        if "angle_params" in self.user_params:
            self.angle = self.angle_params

        if "usb_port" in self.user_params:
            self.T1 = self.readport(self.usb_port["turntable"])
            self.ATT1 = self.readport(self.usb_port["atten1"])
            self.ATT2 = self.readport(self.usb_port["atten2"])
            self.ATT3 = self.readport(self.usb_port["atten3"])

        # create hashmap for testcase name and SSIDs
        self.iot_test_prefix = "test_iot_connection_to_"
        self.ssid_map = {}
        for network in self.iot_networks:
            SSID = network['SSID'].replace('-', '_')
            self.ssid_map[SSID] = network

        # create folder for rvr test result
        self.log_path = os.path.join(logging.log_path, "rvr_results")
        os.makedirs(self.log_path, exist_ok=True)

        Header = ("test_SSID", "Turn table (angle)", "Attenuator(dBm)",
                  "TX throughput (Mbps)", "RX throughput (Mbps)", "RSSI",
                  "Link speed", "Frequency")
        self.csv_write(Header)
def find_p2p_device(ad1, ad2):
    """Check an Android device ad1 can discover an Android device ad2

    Args:
        ad1: The android device
        ad2: The android device
    """
    ad1.droid.wifiP2pDiscoverPeers()
    ad2.droid.wifiP2pDiscoverPeers()
    p2p_find_result = False
    while not p2p_find_result:
        ad1_event = ad1.ed.pop_event(p2pconsts.PEER_AVAILABLE_EVENT,
                                     p2pconsts.P2P_FIND_TIMEOUT)
        ad1.log.debug(ad1_event['data'])
        p2p_find_result = is_discovered(ad1_event, ad2)
    asserts.assert_true(p2p_find_result,
                        "DUT didn't discovered peer:%s device" % (ad2.name))
    def proces_and_valid_batch_scan_result(self, scan_resutls, scan_rt,
                                           result_rt, scan_setting):
        """This function process scan results and validate against settings used
        while starting the scan.

        There are two steps for the verification. First it checks that all the
        wifi networks in results are of the correct frequencies set by scan setting
        params. Then it checks that the delta between the batch of scan results less
        than the time required for scanning channel set by scan setting params.

        Args:
            scan_results: scan results reported.
            scan_rt: Elapsed real time on start scan.
            result_rt: Elapsed ral time on results reported.
            scan_setting: The params for the single scan.

        Returns:
            bssids: total number of bssids scan result have
            validity: True if the all scan result are valid.
        """
        bssids = 0
        validity = True
        scan_time_mic = 0
        scan_channels = []
        scan_time, scan_channels = wutils.get_scan_time_and_channels(
            self.wifi_chs, scan_setting, self.stime_channel)
        scan_time_mic = scan_time * 1000
        for i, batch in enumerate(scan_resutls, start=1):
            asserts.assert_true(
                batch["ScanResults"],
                "At least one scan result is required to validate")
            max_scan_interval = batch["ScanResults"][0][
                "timestamp"] + scan_time_mic
            self.log.debug("max_scan_interval: %s", max_scan_interval)
            for result in batch["ScanResults"]:
                if (result["frequency"] not in scan_channels
                        or result["timestamp"] > max_scan_interval
                        or result["timestamp"] < scan_rt * 1000
                        or result["timestamp"] > result_rt * 1000):
                    self.log.error("Result didn't match requirement: %s",
                                   result)
                    validity = False
            self.log.info("Number of scan result in batch %s: %s", i,
                          len(batch["ScanResults"]))
            bssids += len(batch["ScanResults"])
        return bssids, validity
    def run_iperf_client(self, params):
        """Run iperf traffic after connection.

        Args:
            params: A tuple of network info and AndroidDevice object.
        """
        if "iperf_server_address" in self.user_params:
            wait_time = 5
            network, ad = params
            SSID = network[WifiEnums.SSID_KEY]
            self.log.info("Starting iperf traffic through {}".format(SSID))
            time.sleep(wait_time)
            port_arg = "-p {}".format(self.iperf_server_port)
            success, data = ad.run_iperf_client(self.iperf_server_address,
                                                port_arg)
            self.log.debug(pprint.pformat(data))
            asserts.assert_true(success, "Error occurred in iPerf traffic.")
    def setup_class(self):
        super().setup_class()

        self.dut = self.android_devices[0]
        wutils.wifi_test_device_init(self.dut)
        req_params = []
        opt_param = ["reference_networks"]
        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(
            len(self.reference_networks) > 0,
            "Need at least one reference network with psk.")
        self.network = self.reference_networks[0]["2g"]
    def setup_class(self):
        super().setup_class()

        self.dut = self.android_devices[0]
        wutils.wifi_test_device_init(self.dut)
        req_params = []
        opt_param = ["open_network"]
        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()
        wutils.wifi_toggle_state(self.dut, True)
        asserts.assert_true(
            len(self.open_network) > 0,
            "Need at least one open network.")
        self.open_network = self.open_network[0]["2g"]
Beispiel #14
0
def apply_transport_mode_transforms_socket(ad, socket, transforms):
    """ Apply transport mode transform to Socket object

    Args:
      1. ad - android device object
      2. socket - Socket object key
      3. transforms - list of in and out transforms
    """
    in_tfrm_status = ad.droid.ipSecApplyTransportModeTransformSocket(
        socket, cconst.DIRECTION_IN, transforms[0])
    out_tfrm_status = ad.droid.ipSecApplyTransportModeTransformSocket(
        socket, cconst.DIRECTION_OUT, transforms[1])
    asserts.assert_true(in_tfrm_status and out_tfrm_status,
                        "Failed to apply transform")

    ip_xfrm_state = ad.adb.shell("ip -s xfrm state")
    ad.log.info("XFRM STATE:\n%s\n" % ip_xfrm_state)
    def setup_class(self):
        super().setup_class()

        self.dut = self.android_devices[0]
        wutils.wifi_test_device_init(self.dut)
        req_params = []
        opt_param = [
            "open_network", "reference_networks", "radius_conf_2g", "radius_conf_5g", "ca_cert",
            "eap_identity", "eap_password", "hidden_networks"
        ]
        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(
                wpa_network=True, ent_network=True,
                radius_conf_2g=self.radius_conf_2g,
                radius_conf_5g=self.radius_conf_5g,)

        asserts.assert_true(
            len(self.reference_networks) > 0,
            "Need at least one reference network with psk.")
        if hasattr(self, "reference_networks"):
            self.wpa_psk_2g = self.reference_networks[0]["2g"]
            self.wpa_psk_5g = self.reference_networks[0]["5g"]
        if hasattr(self, "open_network"):
            self.open_2g = self.open_network[0]["2g"]
            self.open_5g = self.open_network[0]["5g"]
        if hasattr(self, "ent_networks"):
            self.ent_network_2g = self.ent_networks[0]["2g"]
            self.ent_network_5g = self.ent_networks[0]["5g"]
            self.config_aka = {
                Ent.EAP: int(EAP.AKA),
                WifiEnums.SSID_KEY: self.ent_network_2g[WifiEnums.SSID_KEY],
            }
            self.config_ttls = {
                Ent.EAP: int(EAP.TTLS),
                Ent.CA_CERT: self.ca_cert,
                Ent.IDENTITY: self.eap_identity,
                Ent.PASSWORD: self.eap_password,
                Ent.PHASE2: int(EapPhase2.MSCHAPV2),
                WifiEnums.SSID_KEY: self.ent_network_2g[WifiEnums.SSID_KEY],
            }
        if hasattr(self, "hidden_networks"):
            self.hidden_network = self.hidden_networks[0]
        self.dut.droid.wifiRemoveNetworkSuggestions([])
Beispiel #16
0
 def _measure_and_process_result(self):
     """ Measure the current drawn by the device for the period of
         self.duration, at the frequency of self.hz.
     """
     tag = self.current_test_name
     result = self.mon.measure_power(self.hz,
                                     self.duration,
                                     tag=tag,
                                     offset=self.offset)
     asserts.assert_true(result,
                         "Got empty measurement data set in %s." % tag)
     self.log.info(repr(result))
     data_path = os.path.join(self.mon_data_path, "%s.txt" % tag)
     monsoon.MonsoonData.save_to_text_file([result], data_path)
     actual_current = result.average_current
     actual_current_str = "%.2fmA" % actual_current
     result_extra = {"Average Current": actual_current_str}
    def test_wifi_tracking_bssid_multi_listeners_found(self):
        """Test bssid tracking for multiple listeners
            1. Start BSSID tracking for 5g bssids
            2. Start BSSID tracking for 2g bssids
            3. Start WifiScanner scan on both bands.
            4. Valid the environment and check the APs are not in range.
            5. Attenuate the signal to make the APs in range.
            6. Verify onFound event triggered on both APs.
        """
        # Attenuate the signal to make APs invisible.
        self.attenuators[self.attenuator_id].set_atten(90)
        scan_setting = { "band": WifiEnums.WIFI_BAND_BOTH_WITH_DFS,
                         "periodInMs": SCANTIME,
                         "reportEvents": WifiEnums.REPORT_EVENT_AFTER_EACH_SCAN,
                         "numBssidsPerScan": 32}
        track_setting_5g = {"bssidInfos":[self.bssid_5g], "apLostThreshold":3}
        data_5g = start_wifi_track_bssid(self.dut, track_setting_5g)
        idx_5g = data_5g["Index"]

        track_setting_2g = {"bssidInfos":[self.bssid_2g], "apLostThreshold":3}
        data_2g = start_wifi_track_bssid(self.dut, track_setting_2g)
        idx_2g = data_2g["Index"]

        valid_env = self.start_scan_and_validate_environment(
            scan_setting, self.combineBssids(track_setting_5g, track_setting_2g))
        try:
            asserts.assert_true(valid_env,
                                "Test environment is not valid, AP is in range")
            self.attenuators[self.attenuator_id].set_atten(0)
            event_name = "{}{}{}{}onFound".format(BSSID_EVENT_TAG, idx_5g, BSSID_EVENT_TAG, idx_2g)
            self.log.info("Waiting for the BSSID event {}".format(event_name))
            #waiting for 2x time to make sure
            event = self.dut.ed.pop_event(event_name, BSSID_EVENT_WAIT * 2)
            self.log.debug(event)
            found = self.check_bssid_in_found_result(
                self.combineBssids(track_setting_5g, track_setting_2g),
                event["data"]["Results"])
            asserts.assert_true(found,
                                "Test failed because Bssid onFound event is not triggered")
        finally:
            self.dut.droid.wifiScannerStopBackgroundScan(self.scan_idx)
            if idx_5g:
                self.dut.droid.wifiScannerStopTrackingBssids(idx_5g)
            if idx_2g:
                self.dut.droid.wifiScannerStopTrackingBssids(idx_2g);
    def do_location_scan(self, num_times=1):
        scan_settings = {
            "band": wutils.WifiEnums.WIFI_BAND_BOTH,
            "periodInMs": 0,
            "reportEvents": wutils.WifiEnums.REPORT_EVENT_AFTER_EACH_SCAN
        }

        wifi_chs = wutils.WifiChannelUS(self.dut.model)
        stime_channel = 47  # dwell time plus 2ms
        leeway = 10

        for i in range(num_times):
            self.log.info("Scan count: {}".format(i))
            data = wutils.start_wifi_single_scan(self.dut, scan_settings)
            idx = data["Index"]
            scan_rt = data["ScanElapsedRealtime"]
            self.log.debug(
                "Wifi single shot scan started index: %s at real time: %s",
                idx, scan_rt)
            # generating event wait time from scan setting plus leeway
            scan_time, scan_channels = wutils.get_scan_time_and_channels(
                wifi_chs, scan_settings, stime_channel)
            wait_time = int(scan_time / 1000) + leeway
            # track number of result received
            result_received = 0
            try:
                for _ in range(1, 3):
                    event_name = "{}{}onResults".format("WifiScannerScan", idx)
                    self.log.debug("Waiting for event: %s for time %s",
                                   event_name, wait_time)
                    event = self.dut.ed.pop_event(event_name, wait_time)
                    self.log.debug("Event received: %s", event)
                    result_received += 1
            except queue.Empty as error:
                asserts.assert_true(
                    result_received >= 1,
                    "Event did not triggered for single shot {}".format(error))
            finally:
                self.dut.droid.wifiScannerStopScan(idx)
                # For single shot number of result received and length of result
                # should be one
                asserts.assert_true(
                    result_received == 1,
                    "Test fail because received result {}".format(
                        result_received))
Beispiel #19
0
    def setup_class(self):
        """ Setup devices for tests and unpack params """
        self.dut = self.android_devices[0]
        self.tethered_devices = self.android_devices[1:]
        wutils.reset_wifi(self.dut)
        self.dut.droid.telephonyToggleDataConnection(True)
        wait_for_cell_data_connection(self.log, self.dut, True)
        asserts.assert_true(
            verify_http_connection(self.log, self.dut),
            "HTTP verification failed on cell data connection")

        # unpack user params
        req_params = ("wifi_network", "download_file", "file_size", "network")
        self.unpack_userparams(req_params)
        self.file_path = DOWNLOAD_PATH + self.download_file.split('/')[-1]
        self.file_size = int(self.file_size)
        self.sub_id = str(self.dut.droid.telephonyGetSubscriberId())
        self.android_os_uid = self.dut.droid.getUidForPackage(android_os_class)
        self.conn_test_uid = self.dut.droid.getUidForPackage(conn_test_class)
        for ad in self.android_devices:
            try:
                ad.adb.shell(instr_cmd)
            except adb.AdbError:
                self.log.warn("adb cmd %s failed on %s" %
                              (instr_cmd, ad.serial))

        # Set chrome browser start with no-first-run verification
        # Give permission to read from and write to storage
        commands = [
            "pm grant com.android.chrome "
            "android.permission.READ_EXTERNAL_STORAGE",
            "pm grant com.android.chrome "
            "android.permission.WRITE_EXTERNAL_STORAGE",
            "rm /data/local/chrome-command-line",
            "am set-debug-app --persistent com.android.chrome",
            'echo "chrome --no-default-browser-check --no-first-run '
            '--disable-fre" > /data/local/tmp/chrome-command-line'
        ]
        for cmd in commands:
            for dut in self.android_devices:
                try:
                    dut.adb.shell(cmd)
                except adb.AdbError:
                    self.log.warn("adb command %s failed on %s" %
                                  (cmd, dut.serial))
Beispiel #20
0
    def test_wifi_tethering_data_usage_limit_downlink(self):
        """ Verify connectivity when data usage limit reached

        Steps:
            1. Set the data usage limit to current data usage + 10MB
            2. Start wifi tethering and connect a dut to the SSID
            3. Download 20MB data on tethered device
            4. File download stops and data limit reached
            5. Verify data usage limit
        """
        # connect device to wifi hotspot
        ad = self.tethered_devices[0]
        wutils.toggle_wifi_off_and_on(self.dut)
        wutils.start_wifi_tethering(self.dut,
                                    self.network[wutils.WifiEnums.SSID_KEY],
                                    self.network[wutils.WifiEnums.PWD_KEY],
                                    ttutils.WIFI_CONFIG_APBAND_2G)
        wutils.wifi_connect(ad, self.network)

        # get pre mobile data usage
        total_pre = self._get_total_data_usage_for_device(cconst.TYPE_MOBILE)

        # set data usage limit to current usage limit + 10MB
        self.log.info("Setting data usage limit to %sMB" %
                      (total_pre + INC_DATA))
        self.dut.droid.connectivitySetDataUsageLimit(
            self.sub_id, str(int((total_pre + INC_DATA) * BYTE_TO_MB_ANDROID)))

        # download file from tethered device
        http_file_download_by_chrome(ad,
                                     self.download_file,
                                     self.file_size,
                                     timeout=120)
        total_pst = self._get_total_data_usage_for_device(cconst.TYPE_MOBILE)

        # verify data usage
        connectivity_status = wutils.validate_connection(ad)
        self.dut.droid.connectivityFactoryResetNetworkPolicies(self.sub_id)
        wutils.stop_wifi_tethering(self.dut)
        self.log.info("Expected data usage: %s" % (total_pre + INC_DATA))
        self.log.info("Actual data usage: %s" % total_pst)
        asserts.assert_true(
            not connectivity_status,
            "Device has internet connectivity after reaching data limit")
        return total_pst - total_pre - INC_DATA < DATA_USG_ERR
Beispiel #21
0
    def run_iperf_server(self, network):
        """Run iperf RX throughput after connection.

        Args:
            params: Dictionary with network info.

        Returns:
            iot_result: dict containing iot_results
        """
        if "iperf_server_address" in self.user_params:

            # Add iot_result
            iot_result = []
            self.iperf_server.start(
                tag="RX_client_{}".format(self.current_test_name))
            wait_time = 5
            SSID = network[WifiEnums.SSID_KEY]
            self.log.info("Starting iperf traffic RX through {}".format(SSID))
            time.sleep(wait_time)
            port_arg = "-p {} -J -R {}".format(self.iperf_server.port,
                                               self.iperf_port_arg)
            success, data = self.dut.run_iperf_client(
                self.iperf_server_address, port_arg)
            client_output_path = os.path.join(
                self.iperf_server.log_path,
                "IperfDUT,{},RX_server_{}".format(self.iperf_server.port,
                                                  self.current_test_name))
            with open(client_output_path, 'w') as out_file:
                out_file.write("\n".join(data))
            self.iperf_server.stop()

            iperf_file = client_output_path
            try:
                iperf_result = ipf.IPerfResult(iperf_file)
                curr_throughput = math.fsum(iperf_result.instantaneous_rates)
            except:
                self.log.warning(
                    "ValueError: Cannot get iperf result. Setting to 0")
                curr_throughput = 0
            iot_result.append(curr_throughput)
            self.log.info("Throughput is {0:.2f} Mbps".format(curr_throughput))

            self.log.debug(pprint.pformat(data))
            asserts.assert_true(success, "Error occurred in iPerf traffic.")
            return iot_result
    def wifi_scanner_single_scan(self, scan_setting):
        """Common logic for an enumerated wifi scanner single scan test case.

         1. Start WifiScanner single scan for scan_setting.
         2. Wait for the scan result event, wait time depend on scan settings
            parameter.
         3. Verify that scan results match with scan settings parameters.
         4. Also verify that only one scan result event trigger.

        Args:
            scan_setting: The params for the single scan.
        """
        data = wutils.start_wifi_single_scan(self.dut, scan_setting)
        idx = data["Index"]
        scan_rt = data["ScanElapsedRealtime"]
        self.log.info(
            "Wifi single shot scan started index: %s at real time: %s", idx,
            scan_rt)
        results = []
        #generating event wait time from scan setting plus leeway
        scan_time, scan_channels = wutils.get_scan_time_and_channels(
            self.wifi_chs, scan_setting, self.stime_channel)
        wait_time = int(scan_time / 1000) + self.leeway
        validity = False
        #track number of result received
        result_received = 0
        try:
            for snumber in range(1, 3):
                event_name = "{}{}onResults".format(EVENT_TAG, idx)
                self.log.debug("Waiting for event: %s for time %s", event_name,
                               wait_time)
                event = self.dut.ed.pop_event(event_name, wait_time)
                self.log.debug("Event received: %s", event)
                results = event["data"]["Results"]
                result_received += 1
                bssids, validity = self.proces_and_valid_batch_scan_result(
                    results, scan_rt, event["data"][KEY_RET], scan_setting)
                asserts.assert_equal(
                    len(results), 1,
                    "Test fail because number of scan result %s" %
                    len(results))
                asserts.assert_true(bssids > 0, EMPTY_RESULT)
                asserts.assert_true(validity, INVALID_RESULT)
                self.log.info("Scan number Buckets: %s\nTotal BSSID: %s",
                              len(results), bssids)
        except queue.Empty as error:
            asserts.assert_true(
                result_received >= 1,
                "Event did not triggered for single shot {}".format(error))
        finally:
            self.dut.droid.wifiScannerStopScan(idx)
            #For single shot number of result received and length of result should be one
            asserts.assert_true(
                result_received == 1,
                "Test fail because received result {}".format(result_received))
Beispiel #23
0
    def track_bssid_with_vaild_scan_for_found(self, track_setting):
        """Common logic for tracking a bssid for Found event.

         1. Starts Wifi Scanner bssid tracking for interested bssids in track_setting.
         2. Start Wifi Scanner scan with default scan settings.
         3. Validate the environment to check AP is not in range.
         4. Attenuate the signal to make AP in range.
         5. Verified that onFound event is triggered for interested bssids in
            track setting.

        Args:
            track_setting: Setting for bssid tracking.

        Returns:
            True if found event occur for interested BSSID.
        """
        self.attenuators[self.attenuator_id].set_atten(90)
        data = start_wifi_track_bssid(self.dut, track_setting)
        idx = data["Index"]
        valid_env = self.start_scan_and_validate_environment(
            self.default_scan_setting, track_setting["bssidInfos"])
        try:
            asserts.assert_true(
                valid_env, "Test environment is not valid, AP is in range")
            self.attenuators[self.attenuator_id].set_atten(0)
            event_name = "{}{}onFound".format(BSSID_EVENT_TAG, idx)
            self.log.info("Waiting for the BSSID event {}".format(event_name))
            event = self.dut.ed.pop_event(event_name, BSSID_EVENT_WAIT)
            self.log.debug(event)
            found = self.check_bssid_in_found_result(
                track_setting["bssidInfos"], event["data"]["Results"])
            asserts.assert_true(
                found, "Test fail because Bssid is not found in event results")
        except Empty as error:
            self.log.error("{}".format(error))
            # log scan result for debugging
            results = self.fetch_scan_result(self.scan_idx,
                                             self.default_scan_setting)
            self.log.debug("scan result {}".format(results))
            raise AssertionError(
                "Event {} did not triggered for {}\n{}".format(
                    event_name, track_setting["bssidInfos"], error))
        finally:
            self.dut.droid.wifiScannerStopBackgroundScan(self.scan_idx)
            self.dut.droid.wifiScannerStopTrackingBssids(idx)
Beispiel #24
0
    def test_randomized_mac_persistent_between_connections(self):
        """Tests that randomized MAC address assigned to each network is
        persistent between connections.

        Steps:
        1. Connect to a 2GHz network.
        2. Connect to a 5GHz network.
        3. Reconnect to the 2GHz network using its network id.
        4. Verify that MAC addresses in Steps 1 and 3 are equal.
        5. Reconnect to the 5GHz network using its network id.
        6. Verify that MAC addresses in Steps 2 and 5 are equal.
        """
        connect_data_2g = self.get_connection_data(self.dut, self.wpapsk_2g)
        old_mac_2g = self.get_current_mac_address(self.dut)
        self.is_valid_randomized_mac_address(old_mac_2g)

        connect_data_5g = self.get_connection_data(self.dut, self.wpapsk_5g)
        old_mac_5g = self.get_current_mac_address(self.dut)
        self.is_valid_randomized_mac_address(old_mac_5g)

        asserts.assert_true(
            old_mac_2g != old_mac_5g,
            "Randomized MAC addresses for 2G and 5G networks are equal.")

        reconnect_2g = wutils.connect_to_wifi_network_with_id(
            self.dut, connect_data_2g[WifiEnums.NETID_KEY],
            connect_data_2g[WifiEnums.SSID_KEY])
        if not reconnect_2g:
            raise signals.TestFailure("Device did not connect to the correct"
                                      " 2GHz network.")
        new_mac_2g = self.get_current_mac_address(self.dut)
        asserts.assert_equal(
            old_mac_2g, new_mac_2g,
            "Randomized MAC for 2G is not persistent between connections.")

        reconnect_5g = wutils.connect_to_wifi_network_with_id(
            self.dut, connect_data_5g[WifiEnums.NETID_KEY],
            connect_data_5g[WifiEnums.SSID_KEY])
        if not reconnect_5g:
            raise signals.TestFailure("Device did not connect to the correct"
                                      " 5GHz network.")
        new_mac_5g = self.get_current_mac_address(self.dut)
        asserts.assert_equal(
            old_mac_5g, new_mac_5g,
            "Randomized MAC for 5G is not persistent between connections.")
    def setup_class(self):
        """Initializes common test hardware and parameters.

        This function initializes hardwares and compiles parameters that are
        common to all tests in this class.
        """
        self.dut = self.android_devices[-1]
        req_params = [
            'RetailAccessPoints', 'rvr_test_params', 'testbed_params',
            'RemoteServer', 'main_network'
        ]
        opt_params = ['golden_files_list', 'OTASniffer']
        self.unpack_userparams(req_params, opt_params)
        self.testclass_params = self.rvr_test_params
        self.num_atten = self.attenuators[0].instrument.num_atten
        self.iperf_server = self.iperf_servers[0]
        self.remote_server = ssh.connection.SshConnection(
            ssh.settings.from_config(self.RemoteServer[0]['ssh_config']))
        self.iperf_client = self.iperf_clients[0]
        self.access_point = retail_ap.create(self.RetailAccessPoints)[0]
        if hasattr(self,
                   'OTASniffer') and self.testbed_params['sniffer_enable']:
            self.sniffer = ota_sniffer.create(self.OTASniffer)[0]
        self.log.info('Access Point Configuration: {}'.format(
            self.access_point.ap_settings))
        self.log_path = os.path.join(logging.log_path, 'results')
        os.makedirs(self.log_path, exist_ok=True)
        if not hasattr(self, 'golden_files_list'):
            if 'golden_results_path' in self.testbed_params:
                self.golden_files_list = [
                    os.path.join(self.testbed_params['golden_results_path'],
                                 file) for file in
                    os.listdir(self.testbed_params['golden_results_path'])
                ]
            else:
                self.log.warning('No golden files found.')
                self.golden_files_list = []
        self.testclass_results = []

        # Turn WiFi ON
        if self.testclass_params.get('airplane_mode', 1):
            self.log.info('Turning on airplane mode.')
            asserts.assert_true(utils.force_airplane_mode(self.dut, True),
                                "Can not turn on airplane mode.")
        wutils.wifi_toggle_state(self.dut, True)
    def test_full_tether_startup_2G_with_airplane_mode_on(self):
        """Test full startup of wifi tethering in 2G band with
        airplane mode on.

        1. Turn on airplane mode.
        2. Report current state.
        3. Switch to AP mode.
        4. verify SoftAP active.
        5. Shutdown wifi tethering.
        6. verify back to previous mode.
        7. Turn off airplane mode.
        """
        self.dut.log.debug("Toggling Airplane mode ON.")
        asserts.assert_true(
            utils.force_airplane_mode(self.dut, True),
            "Can not turn on airplane mode: %s" % self.dut.serial)
        wutils.wifi_toggle_state(self.dut, True)
        self.validate_full_tether_startup(WIFI_CONFIG_APBAND_2G)
def disconnect_wifi(wd):
    """Disconnect wifi on arduino wifi dongle

    Args:
        wd - wifi dongle object

    Returns:
        True - if wifi is disconnected
        False - if not
    """
    wd.log.info("Flashing disconnect_wifi.ino onto dongle")
    cmd = "locate %s" % DISCONNECT_WIFI
    file_path = utils.exe_cmd(cmd).decode("utf-8", "ignore").rstrip()
    write_status = wd.write(ARDUINO, file_path)
    asserts.assert_true(write_status, "Failed to flash disconnect wifi")
    wd.log.info("Flashing complete")
    wifi_status = wd.wifi_status(False)
    asserts.assert_true(not wifi_status, "Failed to disconnect wifi")
    def run_iperf(self, q, dut, peer_dut, peer_aware_if, dut_ipv6, port):
        """Runs iperf and places results in the queue.

    Args:
      q: The queue into which to place the results
      dut: The DUT on which to run the iperf server command.
      peer_dut: The DUT on which to run the iperf client command.
      peer_aware_if: The interface on the DUT.
      dut_ipv6: The IPv6 address of the server.
      port: The port to use for the server and client.
    """
        result, data = dut.run_iperf_server("-D -p %d" % port)
        asserts.assert_true(result, "Can't start iperf3 server")

        result, data = peer_dut.run_iperf_client("%s" % dut_ipv6,
                                                 "-6 -J -p %d" % port)
        self.log.debug(data)
        q.put((result, data))
 def test_reconnect_if_both_ap_evicted_from_wakeup_lock(self):
     """
     2 APs in Wakeup Lock, user moves out of range of both APs, should
     reconnect when user moves back in range of either 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)
     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_off()
     self.ap_b_off()
     self.do_location_scan(CONSECUTIVE_MISSED_SCANS_REQUIRED_TO_EVICT + 2)
     self.ap_a_on()
     self.do_location_scan()
     asserts.assert_true(
         self.dut.droid.wifiCheckState(),
         "Expect Wifi Wake to enable Wifi, but Wifi is disabled.")
 def test_reconnect_wifi_move_back_in_range(self):
     """
     Tests that Wifi Wake re-enables Wifi if the device moves 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)
     # init Wakeup Lock with AP A
     self.do_location_scan(CONSECUTIVE_MISSED_SCANS_REQUIRED_TO_EVICT + 2)
     self.ap_a_off()
     # evict AP A from Wakeup Lock
     self.do_location_scan(CONSECUTIVE_MISSED_SCANS_REQUIRED_TO_EVICT + 2)
     self.ap_a_on()
     self.do_location_scan()
     asserts.assert_true(
         self.dut.droid.wifiCheckState(),
         "Expect Wifi Wake to enable Wifi, but Wifi is disabled.")