Beispiel #1
0
    def run_once(self):
        """Test body."""
        wpa_config = xmlrpc_security_types.WPAConfig(
                psk='chromeos',
                wpa_mode=xmlrpc_security_types.WPAConfig.MODE_MIXED_WPA,
                wpa_ciphers=[xmlrpc_security_types.WPAConfig.CIPHER_TKIP,
                             xmlrpc_security_types.WPAConfig.CIPHER_CCMP],
                wpa2_ciphers=[xmlrpc_security_types.WPAConfig.CIPHER_CCMP],
                use_strict_rekey=True,
                wpa_gtk_rekey_period=self.GTK_REKEY_PERIOD,
                wpa_gmk_rekey_period=self.GMK_REKEY_PERIOD)
        ap_config = hostap_config.HostapConfig(
                frequency=2412,
                mode=hostap_config.HostapConfig.MODE_11G,
                security_config=wpa_config)
        client_conf = xmlrpc_datatypes.AssociationParameters(
                security_config=wpa_config)
        self.context.configure(ap_config)
        client_conf.ssid = self.context.router.get_ssid()
        self.context.assert_connect_wifi(client_conf)
        # Sanity check ourselves with some unicast pings.
        self.context.assert_ping_from_dut()
        # Now check that network traffic goes through.
        if (not self.check_client_can_recv_broadcast_traffic() or
                not self.check_client_can_send_broadcast_traffic()):
            raise error.TestFail('Not all arping passes were successful.')

        self.context.client.shill.disconnect(client_conf.ssid)
        self.context.router.deconfig()
Beispiel #2
0
 def run_once(self):
     """Test body."""
     wpa_config = xmlrpc_security_types.WPAConfig(
             psk='chromeos',
             wpa_mode=xmlrpc_security_types.WPAConfig.MODE_MIXED_WPA,
             wpa_ciphers=[xmlrpc_security_types.WPAConfig.CIPHER_TKIP,
                          xmlrpc_security_types.WPAConfig.CIPHER_CCMP],
             wpa2_ciphers=[xmlrpc_security_types.WPAConfig.CIPHER_CCMP],
             wpa_ptk_rekey_period=self.REKEY_PERIOD)
     ap_config = hostap_config.HostapConfig(
                 frequency=2412,
                 mode=hostap_config.HostapConfig.MODE_11N_PURE,
                 security_config=wpa_config)
     # TODO(wiley) This is just until we find the source of these
     #             test failures.
     self.context.router.start_capture(ap_config.frequency)
     self.context.configure(ap_config)
     assoc_params = xmlrpc_datatypes.AssociationParameters(
             ssid=self.context.router.get_ssid(),
             security_config=wpa_config)
     self.context.assert_connect_wifi(assoc_params)
     ping_config = ping_runner.PingConfig(self.context.get_wifi_addr(),
                                          count=self.PING_COUNT,
                                          interval=self.PING_INTERVAL)
     logging.info('Pinging DUT for %d seconds and rekeying '
                  'every %d seconds.',
                  self.PING_COUNT * self.PING_INTERVAL,
                  self.REKEY_PERIOD)
     self.context.assert_ping_from_dut(ping_config=ping_config)
     self.context.client.shill.disconnect(assoc_params.ssid)
     self.context.router.deconfig()
Beispiel #3
0
 def run_once(self):
     """Test body."""
     wpa_config = xmlrpc_security_types.WPAConfig(
             psk='chromeos',
             wpa_mode=xmlrpc_security_types.WPAConfig.MODE_MIXED_WPA,
             wpa_ciphers=[xmlrpc_security_types.WPAConfig.CIPHER_TKIP,
                          xmlrpc_security_types.WPAConfig.CIPHER_CCMP],
             wpa2_ciphers=[xmlrpc_security_types.WPAConfig.CIPHER_CCMP])
     ap_config = hostap_config.HostapConfig(
                 ssid=self.TEST_SSID,
                 frequency=2412,
                 mode=hostap_config.HostapConfig.MODE_11B,
                 security_config=wpa_config)
     self.context.configure(ap_config)
     assoc_params = xmlrpc_datatypes.AssociationParameters(
             ssid=self.context.router.get_ssid(),
             security_config=wpa_config)
     self.context.assert_connect_wifi(assoc_params)
     self.context.assert_ping_from_dut()
     self.context.client.shill.disconnect(assoc_params.ssid)
     # This deconfig erases the state stored in the router around WPA.
     self.context.router.deconfig()
     # Now we change the same SSID to be an open network.
     ap_config = hostap_config.HostapConfig(
                 ssid=self.TEST_SSID,
                 frequency=2412,
                 mode=hostap_config.HostapConfig.MODE_11B)
     self.context.configure(ap_config)
     assoc_params = xmlrpc_datatypes.AssociationParameters(
             ssid=self.context.router.get_ssid())
     self.context.assert_connect_wifi(assoc_params)
     self.context.assert_ping_from_dut()
     self.context.client.shill.disconnect(assoc_params.ssid)
     self.context.router.deconfig()
 def run_once(self):
     """Test body."""
     wpa_config = xmlrpc_security_types.WPAConfig(
         psk='chromeos',
         wpa_mode=xmlrpc_security_types.WPAConfig.MODE_PURE_WPA,
         wpa_ciphers=[xmlrpc_security_types.WPAConfig.CIPHER_CCMP])
     ap_config0 = hostap_config.HostapConfig(
         ssid=self.TEST_SSID,
         frequency=2412,
         mode=hostap_config.HostapConfig.MODE_11G,
         scenario_name='open_network')
     client_config0 = xmlrpc_datatypes.AssociationParameters(
         ssid=self.TEST_SSID)
     ap_config1 = hostap_config.HostapConfig(
         ssid=self.TEST_SSID,
         frequency=2412,
         mode=hostap_config.HostapConfig.MODE_11G,
         security_config=wpa_config,
         scenario_name='wpa_network')
     client_config1 = xmlrpc_datatypes.AssociationParameters(
         ssid=self.TEST_SSID, security_config=wpa_config)
     self.context.configure(ap_config0)
     self.context.configure(ap_config1, multi_interface=True)
     self.context.assert_connect_wifi(client_config0)
     self.context.assert_ping_from_dut(ap_num=0)
     self.context.assert_connect_wifi(client_config1)
     self.context.assert_ping_from_dut(ap_num=1)
    def get_association_parameters(self):
        """
        Creates an AssociationParameters from the configured AP.

        @returns AssociationParameters for the configured AP.

        """
        security_config = None
        if self.ap_spec.security in [
                ap_spec.SECURITY_TYPE_WPAPSK, ap_spec.SECURITY_TYPE_WPA2PSK
        ]:
            # Not all of this is required but doing it just in case.
            security_config = xmlrpc_security_types.WPAConfig(
                psk=self.ap_spec.password,
                wpa_mode=xmlrpc_security_types.WPAConfig.MODE_MIXED_WPA,
                wpa_ciphers=[
                    xmlrpc_security_types.WPAConfig.CIPHER_CCMP,
                    xmlrpc_security_types.WPAConfig.CIPHER_TKIP
                ],
                wpa2_ciphers=[xmlrpc_security_types.WPAConfig.CIPHER_CCMP])
        return xmlrpc_datatypes.AssociationParameters(
            ssid=self._ssid,
            security_config=security_config,
            discovery_timeout=45,
            association_timeout=30,
            configuration_timeout=30,
            is_hidden=not self.ap_spec.visible)
    def get_association_parameters(self):
        """
        Creates an AssociationParameters from the configured AP.

        @returns AssociationParameters for the configured AP.

        """
        security_config = None
        if (ap_spec.SECURITY_TYPE_WPAPSK in self.security
                or ap_spec.SECURITY_TYPE_WPA2PSK in self.security):
            # Not all of this is required but doing it just in case.
            security_config = xmlrpc_security_types.WPAConfig(
                psk=self.psk,
                wpa_mode=xmlrpc_security_types.WPAConfig.MODE_MIXED_WPA,
                wpa_ciphers=[
                    xmlrpc_security_types.WPAConfig.CIPHER_CCMP,
                    xmlrpc_security_types.WPAConfig.CIPHER_TKIP
                ],
                wpa2_ciphers=[xmlrpc_security_types.WPAConfig.CIPHER_CCMP])
        # TODO(jabele) Allow StaticAPs configured as hidden
        #              by way of the ap_config file
        return xmlrpc_datatypes.AssociationParameters(
            ssid=self._ssid,
            security_config=security_config,
            discovery_timeout=45,
            association_timeout=30,
            configuration_timeout=30,
            is_hidden=False)
Beispiel #7
0
    def run_once(self):
        """Sets up a router, connects to it, pings it, and repeats."""
        CIPHER_CCMP = xmlrpc_security_types.WPAConfig.CIPHER_CCMP
        WPA_MODE = xmlrpc_security_types.WPAConfig.MODE_PURE_WPA
        get_ap_config = lambda ssid, password: hostap_config.HostapConfig(
            ssid=ssid,
            channel=1,
            security_config=xmlrpc_security_types.WPAConfig(
                psk=password, wpa_mode=WPA_MODE, wpa_ciphers=[CIPHER_CCMP]))
        get_client_config = lambda ap_config: \
                xmlrpc_datatypes.AssociationParameters(
                        ssid=self.context.router.get_ssid(),
                        security_config=ap_config.security_config,
                        guid=self.TEST_GUID,
                        autoconnect=True)
        ap_config = get_ap_config(None, self.TEST_PASSWORD0)
        self.context.configure(ap_config)
        assoc_params = get_client_config(ap_config)
        self.context.client.shill.configure_wifi_service(assoc_params)
        self._assert_connection(assoc_params.ssid)
        # Expect the GUID property to be set.
        self._assert_guid_value(assoc_params.ssid, assoc_params.guid)
        if not self.context.client.shill.delete_entries_for_ssid(
                assoc_params.ssid):
            raise error.TestFail('Failed to delete profile entry for %s' %
                                 assoc_params.ssid)

        # GUID property should be missing, since we don't have an entry.
        self._assert_guid_value(assoc_params.ssid,
                                assoc_params.guid,
                                expect_missing=True)

        # Change the password on the AP, do everything again.
        ap_config = get_ap_config(assoc_params.ssid, self.TEST_PASSWORD1)
        self.context.configure(ap_config)
        assoc_params = get_client_config(ap_config)
        self.context.client.shill.configure_wifi_service(assoc_params)
        self._assert_connection(assoc_params.ssid)
        # Expect the GUID property to be set.
        self._assert_guid_value(assoc_params.ssid, assoc_params.guid)
        # Change the security configuration again.
        ap_config = get_ap_config(assoc_params.ssid, self.TEST_PASSWORD2)
        self.context.configure(ap_config)
        # Connect again, but do so by configuring the existing entry.
        # We'll address it by its GUID here.
        if not self.context.client.shill.configure_service_by_guid(
                xmlrpc_datatypes.ConfigureServiceParameters(
                    assoc_params.guid,
                    autoconnect=True,
                    passphrase=self.TEST_PASSWORD2)):
            raise error.TestFail('Failed to configure service by GUID.')

        self._assert_connection(assoc_params.ssid)
 def run_once(self):
     """Test body."""
     wpa_config = xmlrpc_security_types.WPAConfig(
         psk='chromeos',
         wpa_mode=xmlrpc_security_types.WPAConfig.MODE_MIXED_WPA,
         wpa_ciphers=[
             xmlrpc_security_types.WPAConfig.CIPHER_TKIP,
             xmlrpc_security_types.WPAConfig.CIPHER_CCMP
         ],
         wpa2_ciphers=[xmlrpc_security_types.WPAConfig.CIPHER_CCMP],
         wpa_ptk_rekey_period=self.REKEY_PERIOD)
     ap_config = hostap_config.HostapConfig(
         frequency=2412,
         mode=hostap_config.HostapConfig.MODE_11N_PURE,
         security_config=wpa_config)
     # TODO(wiley) This is just until we find the source of these
     #             test failures.
     self.context.capture_host.start_capture(ap_config.frequency)
     self.context.configure(ap_config)
     assoc_params = xmlrpc_datatypes.AssociationParameters(
         ssid=self.context.router.get_ssid(), security_config=wpa_config)
     self.context.assert_connect_wifi(assoc_params)
     ping_config = ping_runner.PingConfig(self.context.get_wifi_addr(),
                                          count=self.PING_COUNT,
                                          interval=self.PING_INTERVAL,
                                          ignore_result=True)
     logging.info(
         'Pinging DUT for %d seconds and rekeying '
         'every %d seconds.', self.PING_COUNT * self.PING_INTERVAL,
         self.REKEY_PERIOD)
     ping_result = self.context.client.ping(ping_config=ping_config)
     logging.info('Ping loss percentage: %d.', ping_result.loss)
     self.output_perf_value(description='Network_wifi_PTK_PingLoss',
                            value=ping_result.loss,
                            units='percent',
                            higher_is_better=False)
     if ping_result.loss > self.PING_LOSS_THRESHOLD:
         raise error.TestNAError('Lost ping packets %r percentage.' %
                                 ping_result.loss)
     self.context.client.shill.disconnect(assoc_params.ssid)
     self.context.router.deconfig()
     self.context.capture_host.stop_capture()
Beispiel #9
0
    def run_once(self, host):
        helper = privet_helper.PrivetHelper(host=host)
        logging.info('Looking for privet bootstrapping network from DUT.')
        scan_interface = self._router.get_wlanif(2437, 'managed')
        self._router.host.run('%s link set %s up' %
                              (self._router.cmd_ip, scan_interface))
        start_time = time.time()
        privet_bss = None
        while time.time() - start_time < PRIVET_AP_STARTUP_TIMEOUT_SECONDS:
            bss_list = self._router.iw_runner.scan(scan_interface)
            for bss in bss_list or []:
                if helper.is_softap_ssid(bss.ssid):
                    privet_bss = bss
        if privet_bss is None:
            raise error.TestFail('Device did not start soft AP in time.')
        self._router.release_interface(scan_interface)

        # Get the netblock of the interface running the AP.
        dut_iw_runner = iw_runner.IwRunner(remote_host=host)
        devs = dut_iw_runner.list_interfaces(desired_if_type='AP')
        if not devs:
            raise error.TestFail('No AP devices on DUT?')
        ap_interface = interface.Interface(devs[0].if_name, host=host)
        ap_netblock = netblock.from_addr(ap_interface.ipv4_address_and_prefix)

        # Set up an AP on the router in the 5Ghz range with WPA2 security.
        wpa_config = xmlrpc_security_types.WPAConfig(
                psk=PASSPHRASE,
                wpa_mode=xmlrpc_security_types.WPAConfig.MODE_PURE_WPA2,
                wpa2_ciphers=[xmlrpc_security_types.WPAConfig.CIPHER_CCMP])
        router_conf = hostap_config.HostapConfig(
                frequency=5240, security_config=wpa_config,
                mode=hostap_config.HostapConfig.MODE_11N_PURE)
        self._router.hostap_configure(router_conf)

        # Connect the other interface on the router to the AP on the client
        # at a hardcoded IP address.
        self._router.configure_managed_station(
                privet_bss.ssid, privet_bss.frequency,
                ap_netblock.get_addr_in_block(200))
        station_interface = self._router.get_station_interface(instance=0)
        logging.debug('Set up station on %s', station_interface)
        self._router.ping(ping_runner.PingConfig(ap_netblock.addr, count=3))

        logging.info('Looking for privet webserver in mDNS records.')
        start_time = time.time()
        while time.time() - start_time < PRIVET_MDNS_RECORD_TIMEOUT_SECONDS:
            all_records = avahi_utils.avahi_browse(host=self._router.host)
            records = [record for record in all_records
                       if (record.interface == station_interface and
                           record.record_type == '_privet._tcp')]
            if records:
                break
            time.sleep(POLLING_PERIOD)
        if not records:
            raise error.TestFail('Did not find privet mDNS records in time.')
        if len(records) > 1:
            raise error.TestFail('Should not see multiple privet records.')
        privet_record = records[0]
        # TODO(wiley) pull the HTTPs port number out of the /info API.
        helper = privet_helper.PrivetdHelper(
                host=self._router.host,
                hostname=privet_record.address,
                http_port=int(privet_record.port))
        helper.ping_server()

        # Now configure the client with WiFi credentials.
        auth_token = helper.privet_auth()
        ssid = self._router.get_ssid()
        data = helper.setup_add_wifi_credentials(ssid, PASSPHRASE)
        helper.setup_start(data, auth_token)

        logging.info('Waiting for DUT to connect to router network.')
        start_time = time.time()
        # Wait for the DUT to take down the AP.
        while time.time() - start_time < PRIVET_CONNECT_TIMEOUT_SECONDS:
            if not dut_iw_runner.list_interfaces(desired_if_type='AP'):
                break
            time.sleep(POLLING_PERIOD)
        else:
            raise error.TestFail('Timeout waiting for DUT to take down AP.')

        # But we should be able to ping the client from the router's AP.
        while time.time() - start_time < PRIVET_CONNECT_TIMEOUT_SECONDS:
            if dut_iw_runner.list_interfaces(desired_if_type='managed'):
                break
            time.sleep(POLLING_PERIOD)
        else:
            raise error.TestFail('Timeout waiting for DUT managerd interface.')

        while time.time() - start_time < PRIVET_CONNECT_TIMEOUT_SECONDS:
            devs = dut_iw_runner.list_interfaces(desired_if_type='managed')
            if devs:
                managed_interface = interface.Interface(devs[0].if_name,
                                                        host=host)
                # Check if we have an IP yet.
                if managed_interface.ipv4_address_and_prefix:
                    break
            time.sleep(POLLING_PERIOD)
        else:
            raise error.TestFail('Timeout waiting for DUT managerd interface.')

        managed_netblock = netblock.from_addr(
                managed_interface.ipv4_address_and_prefix)
        while time.time() - start_time < PRIVET_CONNECT_TIMEOUT_SECONDS:
            PING_COUNT = 3
            result = self._router.ping(
                    ping_runner.PingConfig(managed_netblock.addr,
                                           ignore_result=True,
                                           count=PING_COUNT))
            if result.received == PING_COUNT:
                break
            time.sleep(POLLING_PERIOD)
        else:
            raise error.TestFail('Timeout before ping was successful.')

        # And buffet should think it is online as well.
        helper = privet_helper.PrivetdHelper(
                host=host, hostname=managed_netblock.addr,
                http_port=int(privet_record.port))
        helper.ping_server()
        if not helper.wifi_setup_was_successful(ssid, auth_token):
            raise error.TestFail('Device claims to be offline, but is online.')
    def initialize(self, percent_initial_charge_min=None,
                 check_network=True, loop_time=3600, loop_count=1,
                 should_scroll='true', should_scroll_up='true',
                 scroll_loop='false', scroll_interval_ms='10000',
                 scroll_by_pixels='600', test_low_batt_p=3,
                 verbose=True, force_wifi=False, wifi_ap='', wifi_sec='none',
                 wifi_pw='', wifi_timeout=60, tasks='',
                 volume_level=10, mic_gain=10, low_batt_margin_p=2,
                 ac_ok=False, log_mem_bandwidth=False, gaia_login=None,
                 force_discharge=False, pdash_note=''):
        """
        percent_initial_charge_min: min battery charge at start of test
        check_network: check that Ethernet interface is not running
        loop_time: length of time to run the test for in each loop
        loop_count: number of times to loop the test for
        should_scroll: should the extension scroll pages
        should_scroll_up: should scroll in up direction
        scroll_loop: continue scrolling indefinitely
        scroll_interval_ms: how often to scoll
        scroll_by_pixels: number of pixels to scroll each time
        test_low_batt_p: percent battery at which test should stop
        verbose: add more logging information
        force_wifi: should we force to test to run on wifi
        wifi_ap: the name (ssid) of the wifi access point
        wifi_sec: the type of security for the wifi ap
        wifi_pw: password for the wifi ap
        wifi_timeout: The timeout for wifi configuration
        volume_level: percent audio volume level
        mic_gain: percent audio microphone gain level
        low_batt_margin_p: percent low battery margin to be added to
            sys_low_batt_p to guarantee test completes prior to powerd shutdown
        ac_ok: boolean to allow running on AC
        log_mem_bandwidth: boolean to log memory bandwidth during the test
        gaia_login: whether real GAIA login should be attempted.  If 'None'
            (default) then boolean is determined from URL.
        force_discharge: boolean of whether to tell ec to discharge battery even
            when the charger is plugged in.
        pdash_note: note of the current run to send to power dashboard.
        """
        self._backlight = None
        self._services = None
        self._browser = None
        self._loop_time = loop_time
        self._loop_count = loop_count
        self._mseconds = self._loop_time * 1000
        self._verbose = verbose

        self._sys_low_batt_p = 0.
        self._sys_low_batt_s = 0.
        self._test_low_batt_p = test_low_batt_p
        self._should_scroll = should_scroll
        self._should_scroll_up = should_scroll_up
        self._scroll_loop = scroll_loop
        self._scroll_interval_ms = scroll_interval_ms
        self._scroll_by_pixels = scroll_by_pixels
        self._tmp_keyvals = {}
        self._power_status = None
        self._force_wifi = force_wifi
        self._testServer = None
        self._tasks = tasks.replace(' ','')
        self._backchannel = None
        self._shill_proxy = None
        self._volume_level = volume_level
        self._mic_gain = mic_gain
        self._ac_ok = ac_ok
        self._log_mem_bandwidth = log_mem_bandwidth
        self._wait_time = 60
        self._stats = collections.defaultdict(list)
        self._force_discharge = force_discharge
        self._pdash_note = pdash_note

        if not power_utils.has_battery():
            if ac_ok and (power_utils.has_powercap_support() or
                          power_utils.has_rapl_support()):
                logging.info("Device has no battery but has powercap data.")
            else:
                rsp = "Skipping test for device without battery and powercap."
                raise error.TestNAError(rsp)
        self._power_status = power_status.get_status()
        self._tmp_keyvals['b_on_ac'] = self._power_status.on_ac()

        self._gaia_login = gaia_login
        if gaia_login is None:
            self._gaia_login = power_load_util.use_gaia_login()

        self._username = power_load_util.get_username()
        self._password = power_load_util.get_password()

        if not ac_ok:
            self._power_status.assert_battery_state(percent_initial_charge_min)

        if force_discharge:
            if not power_utils.charge_control_by_ectool(False):
                raise error.TestError('Could not run battery force discharge.')

        # If force wifi enabled, convert eth0 to backchannel and connect to the
        # specified WiFi AP.
        if self._force_wifi:
            sec_config = None
            # TODO(dbasehore): Fix this when we get a better way of figuring out
            # the wifi security configuration.
            if wifi_sec == 'rsn' or wifi_sec == 'wpa':
                sec_config = xmlrpc_security_types.WPAConfig(
                        psk=wifi_pw,
                        wpa_mode=xmlrpc_security_types.WPAConfig.MODE_PURE_WPA2,
                        wpa2_ciphers=
                                [xmlrpc_security_types.WPAConfig.CIPHER_CCMP])
            wifi_config = xmlrpc_datatypes.AssociationParameters(
                    ssid=wifi_ap, security_config=sec_config,
                    configuration_timeout=wifi_timeout)
            # If backchannel is already running, don't run it again.
            self._backchannel = backchannel.Backchannel()
            if not self._backchannel.setup():
                raise error.TestError('Could not setup Backchannel network.')

            self._shill_proxy = wifi_proxy.WifiProxy()
            self._shill_proxy.remove_all_wifi_entries()
            for i in xrange(1,4):
                raw_output = self._shill_proxy.connect_to_wifi_network(
                        wifi_config.ssid,
                        wifi_config.security,
                        wifi_config.security_parameters,
                        wifi_config.save_credentials,
                        station_type=wifi_config.station_type,
                        hidden_network=wifi_config.is_hidden,
                        discovery_timeout_seconds=
                                wifi_config.discovery_timeout,
                        association_timeout_seconds=
                                wifi_config.association_timeout,
                        configuration_timeout_seconds=
                                wifi_config.configuration_timeout * i)
                result = xmlrpc_datatypes.AssociationResult. \
                        from_dbus_proxy_output(raw_output)
                if result.success:
                    break
                logging.warn('wifi connect: disc:%d assoc:%d config:%d fail:%s',
                             result.discovery_time, result.association_time,
                             result.configuration_time, result.failure_reason)
            else:
                raise error.TestError('Could not connect to WiFi network.')

        else:
            # Find all wired ethernet interfaces.
            ifaces = [ iface for iface in interface.get_interfaces()
                if (not iface.is_wifi_device() and
                    iface.name.startswith('eth')) ]
            logging.debug(str([iface.name for iface in ifaces]))
            for iface in ifaces:
                if check_network and iface.is_lower_up:
                    raise error.TestError('Ethernet interface is active. ' +
                                          'Please remove Ethernet cable')

        # record the max backlight level
        self._backlight = power_utils.Backlight()
        self._tmp_keyvals['level_backlight_max'] = \
            self._backlight.get_max_level()

        self._services = service_stopper.ServiceStopper(
            service_stopper.ServiceStopper.POWER_DRAW_SERVICES)
        self._services.stop_services()

        self._detachable_handler = power_utils.BaseActivitySimulator()

        # fix up file perms for the power test extension so that chrome
        # can access it
        os.system('chmod -R 755 %s' % self.bindir)

        # setup a HTTP Server to listen for status updates from the power
        # test extension
        self._testServer = httpd.HTTPListener(8001, docroot=self.bindir)
        self._testServer.run()

        # initialize various interesting power related stats
        self._statomatic = power_status.StatoMatic()

        self._power_status.refresh()
        self._sys_low_batt_p = float(utils.system_output(
                 'check_powerd_config --low_battery_shutdown_percent'))
        self._sys_low_batt_s = int(utils.system_output(
                 'check_powerd_config --low_battery_shutdown_time'))

        if self._sys_low_batt_p and self._sys_low_batt_s:
            raise error.TestError(
                    "Low battery percent and seconds are non-zero.")

        min_low_batt_p = min(self._sys_low_batt_p + low_batt_margin_p, 100)
        if self._sys_low_batt_p and (min_low_batt_p > self._test_low_batt_p):
            logging.warning("test low battery threshold is below system " +
                         "low battery requirement.  Setting to %f",
                         min_low_batt_p)
            self._test_low_batt_p = min_low_batt_p

        if self._power_status.battery:
            self._ah_charge_start = self._power_status.battery[0].charge_now
            self._wh_energy_start = self._power_status.battery[0].energy
    def initialize(self,
                   percent_initial_charge_min=None,
                   check_network=True,
                   loop_time=3600,
                   loop_count=1,
                   should_scroll='true',
                   should_scroll_up='true',
                   scroll_loop='false',
                   scroll_interval_ms='10000',
                   scroll_by_pixels='600',
                   test_low_batt_p=3,
                   verbose=True,
                   force_wifi=False,
                   wifi_ap='',
                   wifi_sec='none',
                   wifi_pw='',
                   wifi_timeout=60,
                   tasks='',
                   kblight_percent=10,
                   volume_level=10,
                   mic_gain=10,
                   low_batt_margin_p=2,
                   ac_ok=False,
                   log_mem_bandwidth=False):
        """
        percent_initial_charge_min: min battery charge at start of test
        check_network: check that Ethernet interface is not running
        loop_time: length of time to run the test for in each loop
        loop_count: number of times to loop the test for
        should_scroll: should the extension scroll pages
        should_scroll_up: should scroll in up direction
        scroll_loop: continue scrolling indefinitely
        scroll_interval_ms: how often to scoll
        scroll_by_pixels: number of pixels to scroll each time
        test_low_batt_p: percent battery at which test should stop
        verbose: add more logging information
        force_wifi: should we force to test to run on wifi
        wifi_ap: the name (ssid) of the wifi access point
        wifi_sec: the type of security for the wifi ap
        wifi_pw: password for the wifi ap
        wifi_timeout: The timeout for wifi configuration
        kblight_percent: percent brightness of keyboard backlight
        volume_level: percent audio volume level
        mic_gain: percent audio microphone gain level
        low_batt_margin_p: percent low battery margin to be added to
            sys_low_batt_p to guarantee test completes prior to powerd shutdown
        ac_ok: boolean to allow running on AC
        log_mem_bandwidth: boolean to log memory bandwidth during the test
        """
        self._backlight = None
        self._services = None
        self._browser = None
        self._loop_time = loop_time
        self._loop_count = loop_count
        self._mseconds = self._loop_time * 1000
        self._verbose = verbose

        self._sys_low_batt_p = 0.
        self._sys_low_batt_s = 0.
        self._test_low_batt_p = test_low_batt_p
        self._should_scroll = should_scroll
        self._should_scroll_up = should_scroll_up
        self._scroll_loop = scroll_loop
        self._scroll_interval_ms = scroll_interval_ms
        self._scroll_by_pixels = scroll_by_pixels
        self._tmp_keyvals = {}
        self._power_status = power_status.get_status()
        self._tmp_keyvals['b_on_ac'] = self._power_status.on_ac()
        self._force_wifi = force_wifi
        self._testServer = None
        self._tasks = tasks.replace(' ', '')
        self._backchannel = None
        self._shill_proxy = None
        self._kblight_percent = kblight_percent
        self._volume_level = volume_level
        self._mic_gain = mic_gain
        self._ac_ok = ac_ok
        self._log_mem_bandwidth = log_mem_bandwidth
        self._wait_time = 60
        self._stats = collections.defaultdict(list)

        with tempfile.NamedTemporaryFile() as pltp:
            file_utils.download_file(self._pltp_url, pltp.name)
            self._password = pltp.read().rstrip()

        if not ac_ok:
            self._power_status.assert_battery_state(percent_initial_charge_min)
        # If force wifi enabled, convert eth0 to backchannel and connect to the
        # specified WiFi AP.
        if self._force_wifi:
            sec_config = None
            # TODO(dbasehore): Fix this when we get a better way of figuring out
            # the wifi security configuration.
            if wifi_sec == 'rsn' or wifi_sec == 'wpa':
                sec_config = xmlrpc_security_types.WPAConfig(
                    psk=wifi_pw,
                    wpa_mode=xmlrpc_security_types.WPAConfig.MODE_PURE_WPA2,
                    wpa2_ciphers=[xmlrpc_security_types.WPAConfig.CIPHER_CCMP])
            wifi_config = xmlrpc_datatypes.AssociationParameters(
                ssid=wifi_ap,
                security_config=sec_config,
                configuration_timeout=wifi_timeout)
            # If backchannel is already running, don't run it again.
            self._backchannel = backchannel.Backchannel()
            if not self._backchannel.setup():
                raise error.TestError('Could not setup Backchannel network.')

            self._shill_proxy = wifi_proxy.WifiProxy()
            self._shill_proxy.remove_all_wifi_entries()
            for i in xrange(1, 4):
                raw_output = self._shill_proxy.connect_to_wifi_network(
                    wifi_config.ssid,
                    wifi_config.security,
                    wifi_config.security_parameters,
                    wifi_config.save_credentials,
                    station_type=wifi_config.station_type,
                    hidden_network=wifi_config.is_hidden,
                    discovery_timeout_seconds=wifi_config.discovery_timeout,
                    association_timeout_seconds=wifi_config.
                    association_timeout,
                    configuration_timeout_seconds=wifi_config.
                    configuration_timeout * i)
                result = xmlrpc_datatypes.AssociationResult. \
                        from_dbus_proxy_output(raw_output)
                if result.success:
                    break
                logging.warn(
                    'wifi connect: disc:%d assoc:%d config:%d fail:%s',
                    result.discovery_time, result.association_time,
                    result.configuration_time, result.failure_reason)
            else:
                raise error.TestError('Could not connect to WiFi network.')

        else:
            # Find all wired ethernet interfaces.
            # TODO: combine this with code in network_DisableInterface, in a
            # common library somewhere.
            ifaces = [
                nic.strip() for nic in os.listdir('/sys/class/net/')
                if ((not os.path.exists('/sys/class/net/' + nic + '/phy80211'))
                    and nic.find('eth') != -1)
            ]
            logging.debug(str(ifaces))
            for iface in ifaces:
                if check_network and self._is_network_iface_running(iface):
                    raise error.TestError('Ethernet interface is active. ' +
                                          'Please remove Ethernet cable')

        # record the max backlight level
        self._backlight = power_utils.Backlight()
        self._tmp_keyvals['level_backlight_max'] = \
            self._backlight.get_max_level()

        self._services = service_stopper.ServiceStopper(
            service_stopper.ServiceStopper.POWER_DRAW_SERVICES)
        self._services.stop_services()

        # fix up file perms for the power test extension so that chrome
        # can access it
        os.system('chmod -R 755 %s' % self.bindir)

        # setup a HTTP Server to listen for status updates from the power
        # test extension
        self._testServer = httpd.HTTPListener(8001, docroot=self.bindir)
        self._testServer.run()

        # initialize various interesting power related stats
        self._statomatic = power_status.StatoMatic()

        self._power_status.refresh()
        (self._sys_low_batt_p, self._sys_low_batt_s) = \
            self._get_sys_low_batt_values()
        min_low_batt_p = min(self._sys_low_batt_p + low_batt_margin_p, 100)
        if self._sys_low_batt_p and (min_low_batt_p > self._test_low_batt_p):
            logging.warning(
                "test low battery threshold is below system " +
                "low battery requirement.  Setting to %f", min_low_batt_p)
            self._test_low_batt_p = min_low_batt_p

        self._ah_charge_start = self._power_status.battery[0].charge_now
        self._wh_energy_start = self._power_status.battery[0].energy