Exemple #1
0
    def RecordPhaseTiming(self, phase, running_phase_record):
        """Context manager for the execution of a single phase.

    This method performs some pre-phase setup on self (for measurements), and
    records the start and end time based on when the context is entered/exited.

    Args:
      phase: openhtf.PhaseInfo object that is to be executed.
      running_phase_record: PhaseRecord object tracking the phase execution.

    Yields:
      An OutcomeWrapper, the outcome of the phase should be passed to its
    SetOutcome() method.
    """

        # Check for measurement descriptors and track them in the PhaseRecord.
        measurement_map = {
            measurement.name: copy.deepcopy(measurement)
            for measurement in phase.measurements
        }

        # Populate dummy measurement declaration list for frontend API.
        running_phase_record.measurements = {
            measurement.name: measurement._asdict()
            for measurement in measurement_map.itervalues()
        }
        self.measurements = measurements.Collection(measurement_map)
        self.attachments = {}
        running_phase_record.start_time_millis = util.TimeMillis()

        try:
            yield
        finally:
            # Serialize measurements and measured values, validate as we go.
            values = dict(self.measurements)

            # Initialize with already-validated and UNSET measurements.
            validated_measurements = {
                name: measurement
                for name, measurement in measurement_map.iteritems() if
                measurement.outcome is not measurements.Outcome.PARTIALLY_SET
            }

            # Validate multi-dimensional measurements now that we have all values.
            validated_measurements.update({
                name: measurement.Validate(values[name])
                for name, measurement in measurement_map.iteritems()
                if measurement.outcome is measurements.Outcome.PARTIALLY_SET
            })

            # Fill out and append the PhaseRecord to our test_record.
            running_phase_record.measured_values = values
            running_phase_record.measurements = validated_measurements
            running_phase_record.end_time_millis = util.TimeMillis()
            running_phase_record.attachments.update(self.attachments)

            # Clear these between uses for the frontend API.
            self.measurements = None
            self.attachments = {}
  def RecordPhaseTiming(self, phase, test_state):
    """Context manager for the execution of a single phase."""
    while hasattr(phase, 'wraps'):
      phase = phase.wraps

    # Check for measurement descriptors and track them in the PhaseRecord.
    measurement_map = {
        measurement.name: copy.deepcopy(measurement)
        for measurement in getattr(phase, 'measurements', [])
    }
    # Populate dummy declaration list for frontend API.
    test_state.running_phase.measurements = {
        measurement.name: measurement._asdict()
        for measurement in measurement_map.itervalues()
    }
    test_state.phase_data.measurements = (
        measurements.Collection(measurement_map))
    test_state.phase_data.attachments = {}
    test_state.running_phase.start_time_millis = util.TimeMillis()

    class ResultWrapper(object):  # pylint: disable=too-few-public-methods
      """Wrapper so we can pull the result back from something we yield."""
      def __init__(self):
        self.result = None

      def SetResult(self, result):  # pylint: disable=missing-docstring
        self.result = result
    result_wrapper = ResultWrapper()

    try:
      yield result_wrapper
    finally:
      # Serialize measurements and measured values, validate as we go.
      values = dict(test_state.phase_data.measurements)
      validated_measurements = {
          name: measurement.Validate(values.get(name, None))
          for name, measurement in measurement_map.iteritems()
      }
      # Fill out and append the PhaseRecord to our test_record.
      test_state.running_phase.measured_values = values
      test_state.running_phase.measurements = validated_measurements
      test_state.running_phase.end_time_millis = util.TimeMillis()
      test_state.running_phase.result = result_wrapper.result
      test_state.running_phase.attachments.update(self.attachments)
      self.test_record.phases.append(test_state.running_phase)

      # Clear these between uses for the frontend API.
      test_state.phase_data.measurements = None
      test_state.phase_data.attachments = None
      test_state.running_phase = None
  def GetFinishedRecord(self):
    """Get a test_record.TestRecord for the finished test.

    Should only be called once at the conclusion of a test run, and will raise
    an exception if end_time_millis is already set.

    Arguments:
      phase_result: The last phasemanager.TestPhaseResult in the test.

    Returns:  An updated test_record.TestRecord that is ready for output.

    Raises: TestRecordAlreadyFinishedError if end_time_millis already set.
    """
    if self.record.end_time_millis:
      raise TestRecordAlreadyFinishedError

    self.logger.debug('Finishing test execution with state %s.', self._state)

    if not self.record.dut_id:
      raise BlankDutIdError(
          'Blank or missing DUT ID, HTF requires a non-blank ID.')

    self.record.end_time_millis = util.TimeMillis()
    self.record.outcome = self._state
    return self.record
Exemple #4
0
  def GetFinishedRecord(self):
    """Get a test_record.TestRecord for the finished test.

    Should only be called once at the conclusion of a test run, and will raise
    an exception if end_time_millis is already set.

    Returns:  An updated test_record.TestRecord that is ready for output.

    Raises: TestRecordAlreadyFinishedError if end_time_millis already set.
    """
    if self.record.end_time_millis:
      raise TestRecordAlreadyFinishedError('Test already finished at',
                                           self.record.end_time_millis)

    if not self.record.dut_id:
      raise BlankDutIdError(
          'Blank or missing DUT ID, HTF requires a non-blank ID.')

    if not self.record.outcome:
      raise FrameworkError(
          'Internal framework error, test outcome unset!')

    self.logger.debug('Finishing test execution with outcome %s.',
                      self.record.outcome.name)

    self.record.end_time_millis = util.TimeMillis()
    self.logger.removeHandler(self._record_handler)
    return self.record
Exemple #5
0
def SetupLogger():
    """Configure logging for OpenHTF."""
    record_logger = logging.getLogger(RECORD_LOGGER)
    record_logger.propagate = False
    record_logger.setLevel(logging.DEBUG)
    record_logger.addHandler(logging.StreamHandler(stream=sys.stdout))

    logger = logging.getLogger(LOGGER_PREFIX)
    logger.propagate = False
    logger.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    if LOGFILE:
        try:
            cur_time = str(util.TimeMillis())
            file_handler = logging.FileHandler('%s.%s' % (LOGFILE, cur_time))
            file_handler.setFormatter(formatter)
            file_handler.setLevel(DEFAULT_LOGFILE_LEVEL.upper())
            file_handler.addFilter(MAC_FILTER)
            logger.addHandler(file_handler)
        except IOError as exception:
            print('Failed to set up log file due to error: %s. '
                  'Continuing anyway.' % exception)

    if not QUIET:
        console_handler = logging.StreamHandler(stream=sys.stderr)
        console_handler.setFormatter(formatter)
        console_handler.setLevel(DEFAULT_LEVEL.upper())
        console_handler.addFilter(MAC_FILTER)
        logger.addHandler(console_handler)
    def RecordPhaseTiming(self, phase, test_state):
        """Context manager for the execution of a single phase."""

        # Check for measurement descriptors and track them in the PhaseRecord.
        measurement_map = {
            measurement.name: copy.deepcopy(measurement)
            for measurement in phase.measurements
        }

        # Populate dummy declaration list for frontend API.
        test_state.running_phase_record.measurements = {
            measurement.name: measurement._asdict()
            for measurement in measurement_map.itervalues()
        }
        test_state.phase_data.measurements = (
            measurements.Collection(measurement_map))
        test_state.phase_data.attachments = {}
        test_state.running_phase_record.start_time_millis = util.TimeMillis()

        outcome_wrapper = OutcomeWrapper()

        try:
            yield outcome_wrapper
        finally:
            # Serialize measurements and measured values, validate as we go.
            values = dict(test_state.phase_data.measurements)
            validated_measurements = {
                name: measurement.Validate(values.get(name, None))
                for name, measurement in measurement_map.iteritems()
            }
            # Fill out and append the PhaseRecord to our test_record.
            test_state.running_phase_record.measured_values = values
            test_state.running_phase_record.measurements = validated_measurements
            test_state.running_phase_record.end_time_millis = util.TimeMillis()
            test_state.running_phase_record.result = outcome_wrapper.outcome
            test_state.running_phase_record.attachments.update(
                self.attachments)
            self.test_record.phases.append(test_state.running_phase_record)

            # Clear these between uses for the frontend API.
            test_state.phase_data.measurements = None
            test_state.phase_data.attachments = {}
            test_state.running_phase_record = None