Exemplo n.º 1
0
    def restart_test(self):
        """ Restart UI, excercises X server startup and shutdown and related
        kernel paths. """
        # Ui respawn will reboot us if we restart ui too many times, so stop
        # it for the duration of the test.
        stopped_services = service_stopper.ServiceStopper(['ui-respawn'])
        stopped_services.stop_services()

        while time.time() - self._start_time < self._test_duration_secs:
            stopped_ui = service_stopper.ServiceStopper(['ui'])
            stopped_ui.stop_services()
            time.sleep(1)
            stopped_ui.restore_services()

        stopped_services.restore_services()
Exemplo n.º 2
0
    def setup(self, dumpdir=None):
        """Initializes avahi daemon on a new tap interface.

        @param dumpdir: Directory where the traffic on the new tap interface
                        is recorded. A value of None disables traffic dumping.
        """
        try:
            from lansim import tuntap
        except ImportError:
            logging.exception('Failed to import lansim.')
            raise error.TestError('Error importing lansim. Did you setup_dep '
                                  'and install_pkg lansim on your test?')

        # Ensure p2p and avahi aren't running.
        self._services = service_stopper.ServiceStopper(['p2p', 'avahi'])
        self._services.stop_services()

        # Backup p2p files.
        p2p_backup_files()

        # Initialize the TAP interface.
        self.tap = tuntap.TunTap(tuntap.IFF_TAP, name=self._tap_name)
        self.tap.set_addr(self._tap_ip, self._tap_mask)
        self.tap.up()

        # Enable traffic dump.
        if not dumpdir is None:
            dumpfile = os.path.join(dumpdir, 'dump-%s.pcap' % self.tap.name)
            self._tcpdump = tcpdump.Tcpdump(self.tap.name, dumpfile)

        # Re-launch avahi-daemon on the TAP interface only.
        avahi_utils.avahi_start_on_iface(self.tap.name)
        utils.system("start p2p")
    def test_cpu_usage(self, local_path):
        """
        Runs the video cpu usage test.

        @param local_path: the path to the video file.

        @return a dictionary that contains the test result.
        """
        def get_cpu_usage(cr):
            time.sleep(STABILIZATION_DURATION)
            cpu_usage_start = site_utils.get_cpu_usage()
            time.sleep(MEASUREMENT_DURATION)
            cpu_usage_end = site_utils.get_cpu_usage()
            return site_utils.compute_active_cpu_time(cpu_usage_start,
                                                      cpu_usage_end) * 100

        if not utils.wait_for_idle_cpu(WAIT_FOR_IDLE_CPU_TIMEOUT,
                                       CPU_IDLE_USAGE):
            raise error.TestError('Could not get idle CPU.')
        if not utils.wait_for_cool_machine():
            raise error.TestError('Could not get cool machine.')
        # Stop the thermal service that may change the cpu frequency.
        services = service_stopper.ServiceStopper(THERMAL_SERVICES)
        services.stop_services()
        # Set the scaling governor to performance mode to set the cpu to the
        # highest frequency available.
        original_governors = utils.set_high_performance_mode()
        try:
            return self.test_webrtc(local_path, get_cpu_usage)
        finally:
            services.restore_services()
            utils.restore_scaling_governor_states(original_governors)
Exemplo n.º 4
0
    def run_once(self):
        """
        Entry point of this test.
        """
        self.job.install_pkg(self.dep, 'dep', self.dep_dir)
        binary_path = os.path.join(self.dep_dir, 'bin', self.test_binary)
        test_log_file = os.path.join(
            self.resultsdir, '%s_%s' % (self.test_name, self.test_log_suffix))

        with service_stopper.ServiceStopper([self.cros_camera_service]):
            for hal in camera_utils.get_camera_hal_paths_for_test():
                cmd = [
                    binary_path,
                    '--camera_hal_path=%s' % hal,
                    ('--gtest_filter=Camera3StillCaptureTest/'
                     'Camera3SimpleStillCaptureTest.PerformanceTest/*'),
                    '--output_log=%s' % test_log_file
                ]
                cmd = ' '.join(map(utils.sh_quote_word, cmd))

                ret = utils.system(cmd,
                                   timeout=self.timeout,
                                   ignore_status=True)
                self._analyze_log(test_log_file)
                if ret != 0:
                    raise error.TestFail('Failed to execute command: %s' % cmd)
 def initialize(self):
     super(hardware_MemoryThroughput, self).initialize()
     self._results = {}
     stop = [ 'ui' ]
     stop.extend(service_stopper.ServiceStopper.POWER_DRAW_SERVICES)
     self._services = service_stopper.ServiceStopper(stop)
     self._services.stop_services()
 def initialize(self):
     # Must stop the TCSD process to be able to collect TPM status,
     # then restart TCSD process to leave system in a known good state.
     # Must also stop services which depend on tcsd.
     self._services = service_stopper.ServiceStopper(
         ['cryptohomed', 'chapsd', 'tcsd'])
     self._services.stop_services()
Exemplo n.º 7
0
    def test_power(self, local_path):
        """
        Runs the video power consumption test.

        @param local_path: the path to the video file.

        @return a dictionary that contains the test result.
        """

        self._backlight = power_utils.Backlight()
        self._backlight.set_default()

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

        self._power_status = power_status.get_status()
        # Verify that we are running on battery and the battery is sufficiently
        # charged.
        self._power_status.assert_battery_state(BATTERY_INITIAL_CHARGED_MIN)

        measurements = [power_status.SystemPower(
                self._power_status.battery_path)]

        def get_power(cr):
            power_logger = power_status.PowerLogger(measurements)
            power_logger.start()
            time.sleep(STABILIZATION_DURATION)
            start_time = time.time()
            time.sleep(MEASUREMENT_DURATION)
            power_logger.checkpoint('result', start_time)
            keyval = power_logger.calc()
            return keyval['result_' + measurements[0].domain + '_pwr']

        return self.test_playback(local_path, get_power)
Exemplo n.º 8
0
    def run_once(self):
        """
        Entry point of this test.
        """
        self.job.install_pkg(self.dep, 'dep', self.dep_dir)

        with service_stopper.ServiceStopper([self.adapter_service]):
            cmd = [os.path.join(self.dep_dir, 'bin', self.test_binary)]
            xml_content = utils.system_output(' '.join(
                ['android-sh', '-c', '\"cat',
                 self.media_profiles_path + '\"']))
            root = xml.etree.ElementTree.fromstring(xml_content)
            recording_params = Set()
            for camcorder_profiles in root.findall('CamcorderProfiles'):
                for encoder_profile in camcorder_profiles.findall(
                        'EncoderProfile'):
                    video = encoder_profile.find('Video')
                    recording_params.add(
                        '%s:%s:%s:%s' %
                        (camcorder_profiles.get('cameraId'),
                         video.get('width'), video.get('height'),
                         video.get('frameRate')))
            if recording_params:
                cmd.append('--recording_params=' + ','.join(recording_params))
            if utils.get_current_board() in self.tablet_board_list:
                cmd.append('--gtest_filter=-*SensorOrientationTest/*')

            utils.system(' '.join(cmd), timeout=self.timeout)
    def test_cpu_usage(self, local_path):
        """
        Runs the video cpu usage test.

        @param local_path: the path to the video file.

        @return a dictionary that contains the test result.
        """
        def get_cpu_usage(cr):
            time.sleep(STABILIZATION_DURATION)
            cpu_usage_start = utils.get_cpu_usage()
            time.sleep(MEASUREMENT_DURATION)
            cpu_usage_end = utils.get_cpu_usage()
            return utils.compute_active_cpu_time(cpu_usage_start,
                                                 cpu_usage_end) * 100

        # crbug/753292 - APNG login pictures increase CPU usage. Move the more
        # strict idle checks after the login phase.
        utils.wait_for_idle_cpu(WAIT_FOR_IDLE_CPU_TIMEOUT, CPU_IDLE_USAGE)
        utils.wait_for_cool_machine()
        if not utils.wait_for_idle_cpu(WAIT_FOR_IDLE_CPU_TIMEOUT,
                                       CPU_IDLE_USAGE):
            logging.warning('Could not get idle CPU pre login.')
        if not utils.wait_for_cool_machine():
            logging.warning('Could not get cold machine pre login.')

        # Stop the thermal service that may change the cpu frequency.
        self._service_stopper = service_stopper.ServiceStopper(
            THERMAL_SERVICES)
        self._service_stopper.stop_services()
        # Set the scaling governor to performance mode to set the cpu to the
        # highest frequency available.
        self._original_governors = utils.set_high_performance_mode()
        return self.test_webrtc(local_path, get_cpu_usage)
Exemplo n.º 10
0
    def initialize(self, seconds_period=20., pdash_note=''):
        """Perform necessary initialization prior to power test run.

        @param seconds_period: float of probing interval in seconds.
        @param pdash_note: note of the current run to send to power dashboard.

        @var backlight: power_utils.Backlight object.
        @var keyvals: dictionary of result keyvals.
        @var status: power_status.SysStat object.

        @var _checkpoint_logger: power_status.CheckpointLogger to track
                                 checkpoint data.
        @var _plog: power_status.PowerLogger object to monitor power.
        @var _psr: power_utils.DisplayPanelSelfRefresh object to monitor PSR.
        @var _services: service_stopper.ServiceStopper object.
        @var _start_time: float of time in seconds since Epoch test started.
        @var _stats: power_status.StatoMatic object.
        @var _tlog: power_status.TempLogger object to monitor temperatures.
        @var _clog: power_status.CPUStatsLogger object to monitor CPU(s)
                    frequencies and c-states.
        @var _meas_logs: list of power_status.MeasurementLoggers
        """
        super(power_Test, self).initialize()
        self.backlight = power_utils.Backlight()
        self.backlight.set_default()
        self.keyvals = dict()
        self.status = power_status.get_status()

        self._checkpoint_logger = power_status.CheckpointLogger()

        measurements = []
        if not self.status.on_ac():
            measurements.append(
                power_status.SystemPower(self.status.battery_path))
        if power_utils.has_powercap_support():
            measurements += power_rapl.create_powercap()
        elif power_utils.has_rapl_support():
            measurements += power_rapl.create_rapl()
        self._plog = power_status.PowerLogger(
            measurements,
            seconds_period=seconds_period,
            checkpoint_logger=self._checkpoint_logger)
        self._psr = power_utils.DisplayPanelSelfRefresh()
        self._services = service_stopper.ServiceStopper(
            service_stopper.ServiceStopper.POWER_DRAW_SERVICES)
        self._services.stop_services()
        self._stats = power_status.StatoMatic()

        self._tlog = power_status.TempLogger(
            [],
            seconds_period=seconds_period,
            checkpoint_logger=self._checkpoint_logger)
        self._clog = power_status.CPUStatsLogger(
            seconds_period=seconds_period,
            checkpoint_logger=self._checkpoint_logger)

        self._meas_logs = [self._plog, self._tlog, self._clog]

        self._pdash_note = pdash_note
Exemplo n.º 11
0
 def _stop_thermal_throttling(self):
     """
     If exist on the platform/machine it stops the different thermal
     throttling scripts from running.
     Warning: this risks abnormal behavior if machine runs in high load.
     """
     self._service_stopper = service_stopper.ServiceStopper(
         _THERMAL_SERVICES)
Exemplo n.º 12
0
    def initialize(self):
        """Perform necessary initialization prior to test run.

        Private Attributes:
          _services: service_stopper.ServiceStopper object
        """
        # Do not switch off screen for screenshot utility.
        self._services = service_stopper.ServiceStopper(['powerd'])
        self._services.stop_services()
 def initialize(self):
     smogcheck_util.enableI2C()
     self.ttci_obj = None
     self.tpm_obj = None
     self.attr_dict = dict()  # Attributes to output
     self.perf_dict = dict()  # Performance measures to output
     self._services = service_stopper.ServiceStopper(
         ['cryptohomed', 'chapsd', 'tcsd'])
     self._services.stop_services()
Exemplo n.º 14
0
 def initialize(self):
     self.__take_tpm_ownership()
     # Stop services that access to the TPM, to be able to use tpmc.
     # Note: for TPM2 the order of re-starting services (they are started
     # in the reversed listed order) is important: e.g. tpm_managerd must
     # start after trunksd, and cryptohomed after attestationd.
     self._services = service_stopper.ServiceStopper([
         'cryptohomed', 'chapsd', 'attestationd', 'tpm_managerd', 'tcsd',
         'trunksd'
     ])
     self._services.stop_services()
    def initialize(self):
        super(graphics_VideoRenderingPower, self).initialize()

        self._backlight = power_utils.Backlight()
        self._backlight.set_default()

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

        self._power_status = power_status.get_status()
    def initialize(self):
        """Perform necessary initialization prior to test run.

        Private Attributes:
          _backlight: power_utils.Backlight object
          _services: service_stopper.ServiceStopper object
        """
        super(hardware_Backlight, self).initialize()
        self._backlight = None
        # Stop powerd to avoid it adjusting backlight levels
        self._services = service_stopper.ServiceStopper(['powerd'])
        self._services.stop_services()
 def initialize(self):
     # Must stop the TCSD process to be able to collect TPM status,
     # then restart TCSD process to leave system in a known good state.
     # Must also stop services which depend on tcsd.
     # Note: for TPM2 the order of re-starting services (they are started
     # in the reversed listed order) is important: e.g. tpm_managerd must
     # start after trunksd, and cryptohomed after attestationd.
     self._services = service_stopper.ServiceStopper([
         'cryptohomed', 'chapsd', 'attestationd', 'tpm_managerd', 'tcsd',
         'trunksd'
     ])
     self._services.stop_services()
Exemplo n.º 18
0
    def initialize(self):
        """Perform necessary initialization prior to test run.

        Private Attributes:
          _backlight: power_utils.Backlight object
          _services: service_stopper.ServiceStopper object
        """
        super(power_Idle, self).initialize()
        self._backlight = None
        self._services = service_stopper.ServiceStopper(
            service_stopper.ServiceStopper.POWER_DRAW_SERVICES)
        self._services.stop_services()
Exemplo n.º 19
0
def get_dictionary_attack_counter():
    """Returns the current dictionary attack counter."""
    tpm_command_info = {
        '0x49465800': {  # Infineon
            'command': ('00 c1 '         # Tag = TPM_TAG_RQU_COMMAND
                        '00 00 00 16 '   # Size = 22
                        '00 00 00 65 '   # Ordinal = TPM_ORD_GetCapability
                        '00 00 00 10 '   # Capability Area = TPM_CAP_MFR
                        '00 00 00 04 '   # Size = 4
                        '00 00 08 02'),  # Vendor-specific
            'response_offset': 23},      # Vendor-specific
        '0x57454300': {  # Nuvoton
            'command': ('00 c1 '         # Tag = TPM_TAG_RQU_COMMAND
                        '00 00 00 14 '   # Size = 20
                        '00 00 00 65 '   # Ordinal = TPM_ORD_GetCapability
                        '00 00 00 19 '   # Capability Area = TPM_CAP_DA_LOGIC
                        '00 00 00 02 '   # Size = 2
                        '00 04'),        # Entity Type = TPM_ET_SRK
            'response_offset': 18},      # TPM_DA_INFO.currentCount LSB
        '0x53544d20': {  # STMicro
            'command': ('00 c1 '         # Tag = TPM_TAG_RQU_COMMAND
                        '00 00 00 14 '   # Size = 20
                        '00 00 00 65 '   # Ordinal = TPM_ORD_GetCapability
                        '00 00 00 19 '   # Capability Area = TPM_CAP_DA_LOGIC
                        '00 00 00 02 '   # Size = 2
                        '00 04'),        # Entity Type = TPM_ET_SRK
            'response_offset': 18}}      # TPM_DA_INFO.currentCount LSB
    caps_file='/sys/class/misc/tpm0/device/caps'
    if not os.path.exists(caps_file):
        caps_file='/sys/class/tpm/tpm0/device/caps'
    try:
        with open(caps_file, 'r') as fp:
            caps = fp.read()
    except IOError:
        return 'Could not read TPM device caps.'
    match = re.search(r'Manufacturer: (0x[0-9A-Fa-f]*)', caps)
    if not match:
        return 'Could not find TPM manufacturer.'
    manufacturer = match.group(1)
    if manufacturer not in tpm_command_info:
        return 'TPM manufacturer not supported.'
    with service_stopper.ServiceStopper(['cryptohomed',
                                         'chapsd',
                                         'tcsd']):
        # The output of 'tpmc raw' is a series of bytes in the form
        # '0x00 0x01 0x02 ...'.
        tpm_response = utils.system_output(
                'tpmc raw %s' % tpm_command_info[manufacturer]['command'],
                ignore_status=True).split()
    offset = tpm_command_info[manufacturer]['response_offset']
    if (len(tpm_response) <= offset):
        return 'Unexpected TPM response (length = %d).' % len(tpm_response)
    return int(tpm_response[offset], base=16)
    def initialize(self, ac_ok=False):
        """Initialize test.

        Args:
            ac_ok: boolean to allow running on AC
        """
        # Objects that need to be taken care of in cleanup() are initialized
        # here to None. Otherwise we run the risk of AttributeError raised in
        # cleanup() masking a real error that caused the test to fail during
        # initialize() before those variables were assigned.
        self._backlight = None
        self._tmp_keyvals = {}

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


        # Time to exclude from calculation after firing a task [seconds]
        self._stabilization_seconds = 5
        self._power_status = power_status.get_status()
        self._tmp_keyvals['b_on_ac'] = self._power_status.on_ac()

        if not ac_ok:
            # Verify that we are running on battery and the battery is
            # sufficiently charged
            self._power_status.assert_battery_state(30)

        # Find the battery capacity to report expected battery life in hours
        batinfo = self._power_status.battery[0]
        self.energy_full_design = batinfo.energy_full_design
        logging.info("energy_full_design = %0.3f Wh", self.energy_full_design)

        # Local data and web server settings. Tarballs with traditional names
        # like *.tgz don't get copied to the image by ebuilds (see
        # AUTOTEST_FILE_MASK in autotest-chrome ebuild).
        self._static_sub_dir = 'static_sites'
        utils.extract_tarball_to_dir(
                'static_sites.tgz.keep',
                os.path.join(self.bindir, self._static_sub_dir))
        self._media_dir = '/home/chronos/user/Downloads/'
        self._httpd_port = 8000
        self._url_base = 'http://localhost:%s/' % self._httpd_port
        self._test_server = httpd.HTTPListener(self._httpd_port,
                                               docroot=self.bindir)

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


        logging.info('initialize() finished')
Exemplo n.º 21
0
    def test_power(self, local_path):
        """
        Runs the video power consumption test.

        @param local_path: the path to the video file.

        @return a dictionary that contains the test result.
        """
        self._backlight = power_utils.Backlight()
        self._backlight.set_default()
        self._service_stopper = service_stopper.ServiceStopper(
                service_stopper.ServiceStopper.POWER_DRAW_SERVICES)
        self._service_stopper.stop_services()

        current_power_status = power_status.get_status()
        # We expect the DUT is powered by battery now. But this is not always
        # true due to other bugs. Disable this test temporarily as workaround.
        # TODO(kcwu): remove this workaround after AC control is stable
        #             crbug.com/723968
        if current_power_status.on_ac():
            logging.warning('Still powered by AC. Skip this test')
            return {}
        # Verify that the battery is sufficiently charged.
        current_power_status.assert_battery_state(BATTERY_INITIAL_CHARGED_MIN)

        measurements = [power_status.SystemPower(
                current_power_status.battery_path)]

        def get_power(cr):
            power_logger = power_status.PowerLogger(measurements)
            power_logger.start()
            time.sleep(STABILIZATION_DURATION)
            start_time = time.time()
            time.sleep(MEASUREMENT_DURATION)
            power_logger.checkpoint('result', start_time)
            keyval = power_logger.calc()
            # save_results() will save <fname_prefix>_raw.txt and
            # <fname_prefix>_summary.txt, where the former contains raw data.
            fname_prefix = 'result_%.0f' % time.time()
            power_logger.save_results(self.resultsdir, fname_prefix)
            metric_name = 'result_' + measurements[0].domain
            with open(os.path.join(
                    self.resultsdir, fname_prefix + '_raw.txt')) as f:
                for line in f.readlines():
                    if line.startswith(metric_name):
                        split_data = line.split('\t')
                        # split_data[0] is metric_name, [1:] are raw data.
                        return [float(data) for data in split_data[1:]]
            # Return a list contains the average power only for fallback.
            return [keyval[metric_name + '_pwr_avg']]

        return self.test_webrtc(local_path, get_power)
    def initialize(self):
        if not power_utils.has_battery():
            raise error.TestNAError('DUT has no battery. Test Skipped')

        self.status = power_status.get_status()

        if not self.status.on_ac():
            raise error.TestNAError(
                  'This test needs to be run with the AC power online')

        self._services = service_stopper.ServiceStopper(
            service_stopper.ServiceStopper.POWER_DRAW_SERVICES + ['ui'])
        self._services.stop_services()
    def initialize(self):
        """Perform necessary initialization prior to test run.

        Private Attributes:
          _results: dict containing keyvals with latency measurements
          _services: service_stopper.ServiceStopper object
        """
        super(hardware_MemoryLatency, self).initialize()
        self._results = {}
        stop = ['ui']
        stop.extend(service_stopper.ServiceStopper.POWER_DRAW_SERVICES)
        self._services = service_stopper.ServiceStopper(stop)
        self._services.stop_services()
Exemplo n.º 24
0
 def run_once(self):
     """Test body."""
     with service_stopper.ServiceStopper(
             services_to_stop=self.RELATED_SERVICES):
         # AP configuration parameters, only configuring SSID.
         ap_config = {apmanager_constants.CONFIG_SSID: 'testap'}
         manager = apmanager_proxy.ApmanagerProxy()
         service = manager.start_service(ap_config)
         self._verify_process('hostapd', True)
         self._verify_process('dnsmasq', True)
         manager.terminate_service(service)
         self._verify_process('hostapd', False)
         self._verify_process('dnsmasq', False)
    def __enter__(self):
        # Stop the thermal service that may change the cpu frequency.
        self._service_stopper = service_stopper.ServiceStopper(THERMAL_SERVICES)
        self._service_stopper.stop_services()

        if not utils.wait_for_idle_cpu(
                WAIT_FOR_IDLE_CPU_TIMEOUT, CPU_IDLE_USAGE):
            raise error.TestError('Could not get idle CPU.')
        if not utils.wait_for_cool_machine():
            raise error.TestError('Could not get cold machine.')

        # Set the scaling governor to performance mode to set the cpu to the
        # highest frequency available.
        self._original_governors = utils.set_high_performance_mode()
        return self
    def test_generated_screenshots_match_expectation(self):
        """Draws a texture with a soft ellipse twice and captures each image.
        Compares the output fuzzily against reference images.
        """
        self._services = service_stopper.ServiceStopper(['ui'])
        self._services.stop_services()

        screenshot1_reference = os.path.join(self.bindir,
                                             'screenshot1_reference.png')
        screenshot1_generated = os.path.join(self.resultsdir,
                                             'screenshot1_generated.png')
        screenshot1_resized = os.path.join(
            self.resultsdir, 'screenshot1_generated_resized.png')
        screenshot2_reference = os.path.join(self.bindir,
                                             'screenshot2_reference.png')
        screenshot2_generated = os.path.join(self.resultsdir,
                                             'screenshot2_generated.png')
        screenshot2_resized = os.path.join(
            self.resultsdir, 'screenshot2_generated_resized.png')

        exefile = os.path.join(self.autodir, 'deps/glbench/windowmanagertest')

        # Delay before screenshot: 1 second has caused failures.
        options = ' --screenshot1_sec 2'
        options += ' --screenshot2_sec 1'
        options += ' --cooldown_sec 1'
        # perceptualdiff can handle only 8 bit images.
        screenshot_cmd = ' "/usr/local/autotest/bin/screenshot.py %s"'
        options += ' --screenshot1_cmd' + screenshot_cmd % screenshot1_generated
        options += ' --screenshot2_cmd' + screenshot_cmd % screenshot2_generated

        cmd = exefile + ' ' + options
        utils.run(cmd,
                  stdout_tee=utils.TEE_TO_LOGS,
                  stderr_tee=utils.TEE_TO_LOGS)

        convert_cmd = ('convert -channel RGB -colorspace RGB -depth 8'
                       " -resize '100x100!' %s %s")
        utils.system(convert_cmd %
                     (screenshot1_generated, screenshot1_resized))
        utils.system(convert_cmd %
                     (screenshot2_generated, screenshot2_resized))
        os.remove(screenshot1_generated)
        os.remove(screenshot2_generated)

        diff_cmd = 'perceptualdiff -verbose %s %s'
        utils.system(diff_cmd % (screenshot1_reference, screenshot1_resized))
        utils.system(diff_cmd % (screenshot2_reference, screenshot2_resized))
Exemplo n.º 27
0
    def test_power(self, local_path):
        """
        Runs the video power consumption test.

        @param local_path: the path to the video file.

        @return a dictionary that contains the test result.
        """

        self._backlight = power_utils.Backlight()
        self._backlight.set_default()

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

        self._power_status = power_status.get_status()
        # We expect the DUT is powered by battery now. But this is not always
        # true due to other bugs. Disable this test temporarily as workaround.
        # TODO(kcwu): remove this workaround after AC control is stable
        #             crbug.com/723968
        if self._power_status.on_ac():
            logging.warning('Still powered by AC. Skip this test')
            return {}
        # Verify that the battery is sufficiently charged.
        self._power_status.assert_battery_state(BATTERY_INITIAL_CHARGED_MIN)

        measurements = [
            power_status.SystemPower(self._power_status.battery_path)
        ]
        if power_utils.has_rapl_support():
            measurements += power_rapl.create_rapl()

        def get_power(cr):
            power_logger = power_status.PowerLogger(measurements)
            power_logger.start()
            time.sleep(STABILIZATION_DURATION)
            start_time = time.time()
            time.sleep(MEASUREMENT_DURATION)
            power_logger.checkpoint('result', start_time)
            keyval = power_logger.calc()
            keyval = {
                key: keyval[key]
                for key in keyval if key.endswith('_pwr')
            }
            return keyval

        return self.test_playback(local_path, get_power)
    def __enter__(self):
        self._backlight = power_utils.Backlight()
        self._backlight.set_default()

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

        status = power_status.get_status()

        # Verify that we are running on battery and the battery is sufficiently
        # charged.
        status.assert_battery_state(BATTERY_INITIAL_CHARGED_MIN)
        self._system_power = power_status.SystemPower(status.battery_path)
        self._power_logger = power_status.PowerLogger([self._system_power])
        return self
Exemplo n.º 29
0
    def run_power_test(self, browser, test_url, ac_ok):
        """Runs the webgl power consumption test and reports the perf results.

        @param browser: The Browser object to run the test with.
        @param test_url: The URL to the aquarium test site.
        @param ac_ok: Boolean on whether its ok to have AC power supplied.
        """

        self._backlight = power_utils.Backlight()
        self._backlight.set_default()

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

        if not ac_ok:
            self._power_status = power_status.get_status()
            # Verify that we are running on battery and the battery is
            # sufficiently charged.
            self._power_status.assert_battery_state(
                BATTERY_INITIAL_CHARGED_MIN)

            measurements = [
                power_status.SystemPower(self._power_status.battery_path)
            ]

        def get_power():
            power_logger = power_status.PowerLogger(measurements)
            power_logger.start()
            time.sleep(STABILIZATION_DURATION)
            start_time = time.time()
            time.sleep(MEASUREMENT_DURATION)
            power_logger.checkpoint('result', start_time)
            keyval = power_logger.calc()
            logging.info('Power output %s', keyval)
            return keyval['result_' + measurements[0].domain + '_pwr']

        self.run_fish_test(browser, test_url, 1000, perf_log=False)
        if not ac_ok:
            energy_rate = get_power()
            # This is a power specific test so we are not capturing
            # avg_fps and avg_render_time in this test.
            self.perf_keyval[POWER_DESCRIPTION] = energy_rate
            self.output_perf_value(description=POWER_DESCRIPTION,
                                   value=energy_rate,
                                   units='W',
                                   higher_is_better=False)
Exemplo n.º 30
0
    def _setup_avahi(self):
        """Initializes avahi daemon on a new tap interface."""
        from lansim import tuntap
        # Ensure p2p and avahi aren't running.
        self._services = service_stopper.ServiceStopper(['p2p', 'avahi'])
        self._services.stop_services()

        # Initialize avahi-daemon listenning only on the fake TAP interface.
        self._tap = tuntap.TunTap(tuntap.IFF_TAP, name='faketap')

        # The network 169.254/16 shouldn't clash with other real services. We
        # use a /24 subnet of it here.
        self._tap.set_addr('169.254.10.1', mask=24)
        self._tap.up()

        # Re-launch avahi-daemon on the tap interface.
        avahi_utils.avahi_start_on_iface(self._tap.name)