<NME> __init__.py
<BEF> # Copyright 2014 Google Inc. All Rights Reserved.

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The main OpenHTF entry point."""

import signal
import typing

from openhtf import plugs
from openhtf.core import phase_executor
from openhtf.core import test_record
import openhtf.core.base_plugs
import openhtf.core.diagnoses_lib
import openhtf.core.measurements
import openhtf.core.monitors
import openhtf.core.phase_branches
import openhtf.core.phase_collections
import openhtf.core.phase_descriptor
import openhtf.core.phase_group
import openhtf.core.phase_nodes
import openhtf.core.test_descriptor
import openhtf.util
from openhtf.util import configuration
from openhtf.util import console_output
from openhtf.util import data
from openhtf.util import functions
from openhtf.util import logs
from openhtf.util import units
from openhtf.util import logs
from openhtf.util import measurements

FLAGS = gflags.FLAGS
__version__ = util.get_version()
_LOG = logging.getLogger(__name__)
    'plug',
    'monitors',
    'diagnose',
    'measures',
    # Public Classes.
    'BasePlug',
    'DiagnosesStore',
    'Diagnosis',
    'DiagnosisComponent',
    'DiagPriority',
    'DiagResultEnum',
    'PhaseDiagnoser',
    'TestDiagnoser',
    'Dimension',
    'Measurement',
    'BranchSequence',
    'DiagnosisCheckpoint',
    'DiagnosisCondition',
    'PhaseFailureCheckpoint',
    'PhaseSequence',
    'Subtest',
    'PhaseDescriptor',
    'PhaseNameCase',
    'PhaseOptions',
    'PhaseResult',
    'PhaseGroup',
    'PhaseNode',
    'Test',
    'TestApi',
    'TestDescriptor',
    'PhaseRecord',
    'TestRecord',
    # Globals.
    'conf',
)

plug = plugs.plug
BasePlug = openhtf.core.base_plugs.BasePlug

DiagnosesStore = openhtf.core.diagnoses_lib.DiagnosesStore
Diagnosis = openhtf.core.diagnoses_lib.Diagnosis
DiagnosisComponent = openhtf.core.diagnoses_lib.DiagnosisComponent
DiagPriority = openhtf.core.diagnoses_lib.DiagPriority
DiagResultEnum = openhtf.core.diagnoses_lib.DiagResultEnum
PhaseDiagnoser = openhtf.core.diagnoses_lib.PhaseDiagnoser
TestDiagnoser = openhtf.core.diagnoses_lib.TestDiagnoser

Dimension = openhtf.core.measurements.Dimension
Measurement = openhtf.core.measurements.Measurement

monitors = openhtf.core.monitors.monitors

BranchSequence = openhtf.core.phase_branches.BranchSequence
DiagnosisCheckpoint = openhtf.core.phase_branches.DiagnosisCheckpoint
DiagnosisCondition = openhtf.core.phase_branches.DiagnosisCondition
PhaseFailureCheckpoint = openhtf.core.phase_branches.PhaseFailureCheckpoint

PhaseSequence = openhtf.core.phase_collections.PhaseSequence
Subtest = openhtf.core.phase_collections.Subtest

diagnose = openhtf.core.phase_descriptor.diagnose
measures = openhtf.core.phase_descriptor.measures
PhaseDescriptor = openhtf.core.phase_descriptor.PhaseDescriptor
PhaseNameCase = openhtf.core.phase_descriptor.PhaseNameCase
PhaseOptions = openhtf.core.phase_descriptor.PhaseOptions
PhaseResult = openhtf.core.phase_descriptor.PhaseResult

PhaseGroup = openhtf.core.phase_group.PhaseGroup

PhaseNode = openhtf.core.phase_nodes.PhaseNode

Test = openhtf.core.test_descriptor.Test
TestApi = openhtf.core.test_descriptor.TestApi
TestDescriptor = openhtf.core.test_descriptor.TestDescriptor

PhaseRecord = test_record.PhaseRecord
TestRecord = test_record.TestRecord

conf = configuration.CONF


def get_version():
  """Returns the version string of the 'openhtf' package.

  Note: the version number doesn't seem to get properly set when using ipython.
  """
  try:
    return pkg_resources.get_distribution('openhtf')
  except pkg_resources.DistributionNotFound:
    return 'Unknown - Perhaps openhtf was not installed via setup.py or pip.'


__version__ = get_version()

# Register signal handler to stop all tests on SIGINT.
Test.DEFAULT_SIGINT_HANDLER = signal.signal(signal.SIGINT, Test.handle_sig_int)
    return self.func(phase_data, **plug_kwargs)


def StopOnSigInt(callbacks):
  """Handles SigInt by calling the given callbacks."""
  def _Handler(*_):
    for cb in callbacks:
      cb()
  signal.signal(signal.SIGINT, _Handler)

<MSG> load --config-file on import, default station_id to hostname

<DFF> @@ -39,6 +39,14 @@ from openhtf.io import test_record
 from openhtf.util import logs
 from openhtf.util import measurements
 
+# All tests require a station_id.  This can be via the --config-file
+# automatically loaded by OpenHTF, provided explicitly to the config with
+# conf.Load(station_id='My_OpenHTF_Station'), or alongside other configs loaded
+# with conf.LoadFromDict({..., 'station_id': 'My_Station'}).  If none of those
+# are provided (no conf value is available) when Test.Execute() is called, then
+# we'll fall back to the machine's hostname.
+conf.Declare('station_id', 'The name of this test station')
+
 FLAGS = gflags.FLAGS
 __version__ = util.get_version()
 _LOG = logging.getLogger(__name__)
@@ -258,6 +266,7 @@ class PhaseInfo(mutablerecords.Record(
     return self.func(phase_data, **plug_kwargs)
 
 
+<<<<<<< HEAD
 def StopOnSigInt(callbacks):
   """Handles SigInt by calling the given callbacks."""
   def _Handler(*_):
@@ -266,3 +275,111 @@ def StopOnSigInt(callbacks):
     for cb in callbacks:
       cb()
   signal.signal(signal.SIGINT, _Handler)
+=======
+class Test(object):
+  """An object that represents an OpenHTF test.
+
+  This object encapsulates the static test state including an ordered tuple of
+  phases to execute.
+
+  Args:
+    *phases: The ordered list of phases to execute for this test.
+    **metadata: Any metadata that should be associated with test records.
+  """
+
+  def __init__(self, *phases, **metadata):
+    """Creates a new Test to be executed.
+
+    Args:
+      *phases: The ordered list of phases to execute for this test.
+    """
+    self.metadata = metadata
+    self.loop = False
+    self.phases = [PhaseInfo.WrapOrCopy(phase) for phase in phases]
+    self.output_callbacks = []
+
+    # Pull some metadata from the frame in which this Test was created.
+    frame_record = inspect.stack()[1]
+    self.filename = os.path.basename(frame_record[1])
+    self.docstring = inspect.getdoc(inspect.getmodule(frame_record[0]))
+    if FLAGS.capture_test_source:
+      self.code = inspect.getsource(frame_record[0])
+    else:
+      self.code = ''
+
+  @property
+  def plug_type_map(self):
+    """Returns dict mapping name to plug type for all phases."""
+    plug_type_map = {}
+    for plug, plug_type in itertools.chain.from_iterable(
+        ((plug.name, plug.cls) for plug in phase.plugs)
+        for phase in self.phases):
+      if (plug in plug_type_map and
+          plug_type is not plug_type_map[plug]):
+        raise plugs.DuplicatePlugError(
+            'Duplicate plug with different type: %s' % plug)
+      plug_type_map[plug] = plug_type
+    return plug_type_map
+
+  def AddOutputCallback(self, callback):
+    """Add the given function as an output module to this test."""
+    self.output_callbacks.append(callback)
+
+  def OutputTestRecord(self, test_record):
+    """Feed the record of this test to all output modules."""
+    test_record.metadata.update(self.metadata)
+    for output_cb in self.output_callbacks:
+      output_cb(test_record)
+
+  def Execute(self, loop=None, test_start=triggers.AutoStart,
+              test_stop=triggers.AutoStop):
+    """Start the OpenHTF framework running with the given test.
+
+    Executes this test, iterating over self.phases and executing them.
+
+    Example:
+
+      def PhaseOne(test):
+        # Integrate more widgets
+
+      def PhaseTwo(test):
+        # Analyze widget integration status
+
+      Test(PhaseOne, PhaseTwo).Execute()
+
+    Returns:
+      None when the test framework has exited.
+    """
+    try:
+      FLAGS(sys.argv)  # parse flags
+    except gflags.FlagsError, e:  # pylint: disable=invalid-name
+      print '%s\nUsage: %s ARGS\n%s' % (e, sys.argv[0], FLAGS)
+      sys.exit(1)
+
+    logs.setup_logger()
+
+    if loop is not None:
+      self.loop = loop
+
+    # If not provided via any config means by now, we default to hostname.
+    if 'station_id' not in conf:
+      conf.Load(station_id=socket.gethostname())
+
+    _LOG.info('Executing test: %s', self.filename)
+    executor = exe.TestExecutor(self, test_start, test_stop)
+    server = http_api.Server(executor)
+
+    def sigint_handler(*dummy):
+      """Handle SIGINT by stopping running executor and handler."""
+      _LOG.error('Received SIGINT. Stopping everything.')
+      executor.Stop()
+      server.Stop()
+    signal.signal(signal.SIGINT, sigint_handler)
+
+    server.Start()
+    executor.Start()
+
+    executor.Wait()
+    server.Stop()
+    return
+>>>>>>> 51779d4... load --config-file on import, default station_id to hostname

{'addition_count': 117, 'commit_subject': 'load --config-file on import, default station_id to hostname', 'deletion_count': 0, 'file_extension': '.py', 'lang': 'py', 'license': 'apache-2.0', 'repo_name': 'google/openhtf'}