Exemplo n.º 1
0
 def configure(self, **kwargs):
   """Update test-wide configuration options. See TestOptions for docs."""
   # These internally ensure they are safe to call multiple times with no weird
   # side effects.
   create_arg_parser(add_help=True).parse_known_args()
   logs.setup_logger()
   for key, value in kwargs.iteritems():
     setattr(self._test_options, key, value)
Exemplo n.º 2
0
 def configure(self, **kwargs):
     """Update test-wide configuration options. See TestOptions for docs."""
     # These internally ensure they are safe to call multiple times with no weird
     # side effects.
     create_arg_parser(add_help=True).parse_known_args()
     logs.setup_logger()
     for key, value in kwargs.iteritems():
         setattr(self._test_options, key, value)
Exemplo n.º 3
0
 def configure(self, **kwargs):
     """Update test-wide configuration options. See TestOptions for docs."""
     # These internally ensure they are safe to call multiple times with no weird
     # side effects.
     known_args, _ = create_arg_parser(add_help=True).parse_known_args()
     if known_args.config_help:
         sys.stdout.write(conf.help_text)
         sys.exit(0)
     logs.setup_logger()
     for key, value in six.iteritems(kwargs):
         setattr(self._test_options, key, value)
Exemplo n.º 4
0
def main():
    """Start the web gui."""
    parser = argparse.ArgumentParser(description='OpenHTF web gui server.',
                                     parents=[conf.ARG_PARSER],
                                     prog='python -m openhtf.output.web_gui')
    parser.add_argument('--port',
                        type=int,
                        default=12000,
                        help='Port on which to serve the frontend.')
    parser.add_argument('--discovery_interval_s',
                        type=int,
                        default=3,
                        help='Seconds between station discovery attempts.')
    parser.add_argument('--disable_discovery',
                        action='store_true',
                        help='Disable multicast-based station discovery.')
    parser.add_argument('--dev',
                        action='store_true',
                        help='Start in development mode.')
    parser.add_argument('--custom_frontend',
                        type=str,
                        help='Path to a custom web frontend.')
    args = parser.parse_args()

    logs.setup_logger()

    if args.custom_frontend is not None:
        frontend_path = args.custom_frontend
    else:
        frontend_path = BUILD_PATH if os.path.exists(
            BUILD_PATH) else PREBUILT_PATH
    if not os.path.exists(frontend_path):
        raise ValueError('Frontend path `%s` does not exist.' % frontend_path)
    _LOG.info('Running frontend from path `%s`' % frontend_path)

    web_server = openhtf.output.web_gui.WebGuiServer(args.discovery_interval_s,
                                                     args.disable_discovery,
                                                     args.port, frontend_path,
                                                     args.dev, args)

    def sigint_handler(*dummy):
        """Handle SIGINT by stopping running executor and handler."""
        _LOG.error('Received SIGINT. Stopping web server.')
        web_server.stop()

    signal.signal(signal.SIGINT, sigint_handler)

    print('Starting openhtf web gui server on http://localhost:%s.' %
          args.port)
    web_server.start()
Exemplo n.º 5
0
  def configure(self, **kwargs):
    """Update test-wide configuration options.

    Valid kwargs:
      output_callbacks: List of output callbacks to run, typically it's better
          to use add_output_callbacks(), but you can pass [] here to reset them.
      teardown_function: Function to run at teardown.  We pass the same
          arguments to it as a phase.
    """
    # These internally ensure they are safe to call multiple times with no weird
    # side effects.
    create_arg_parser(add_help=True).parse_known_args()
    logs.setup_logger()
    for key, value in kwargs.iteritems():
      setattr(self._test_options, key, value)
Exemplo n.º 6
0
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.
  """

  def __init__(self, *phases):
    """Creates a new Test to be executed.

    Args:
      *phases: The ordered list of phases to execute for this test.
    """
    self.loop = False
    self.phases = [TestPhaseInfo.WrapOrReturn(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]))
    self.code = inspect.getsource(frame_record[0])

  @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."""
    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
    conf.Load()

    config = conf.Config()
    rundata.RunData(config.station_id,
                    self.filename,
                    socket.gethostname(),
                    FLAGS.http_port,
                    os.getpid()).SaveToFile(FLAGS.rundir)

    _LOG.info('Executing test: %s', self.filename)
    executor = exe.TestExecutor(config, self, test_start, test_stop)
    server = http_api.Server(executor)

    def sigint_handler(*dummy):
      """Handle SIGINT by stopping running executor and handler."""
      print "Received SIGINT. Stopping everything."
      executor.Stop()
      server.Stop()
    signal.signal(signal.SIGINT, sigint_handler)

    server.Start()
    executor.Start()

    executor.Wait()
    server.Stop()
    return
Exemplo n.º 7
0
 def setUp(self):
   logs.setup_logger()
   self.test_plug_type = UnittestPlug
Exemplo n.º 8
0
    def post(self, host, port, prompt_id):
        msg = json.JSONEncoder().encode({"id": prompt_id, "response": self.request.body})
        self.store.MessageFramework(host, port, method="POST", message=msg)
        self.write("SENT")


def main(argv):
    """Start the frontend."""
    try:
        argv = FLAGS(argv)  # parse flags
    except gflags.FlagsError, e:
        print("%s\nUsage: %s ARGS\n%s" % (e, sys.argv[0], FLAGS))
        sys.exit(1)

    logs.setup_logger()

    store = StationStore()

    routes = [
        (r"/(stations/)?", MainHandler, dict(store=store)),
        (r"/stations/((?:[0-9]{1,3}\.){3}[0-9]{1,3})/([0-9]{1,5})/", StationStateHandler, dict(store=store)),
        (
            r"/stations/((?:[0-9]{1,3}\.){3}[0-9]{1,3})/([0-9]{1,5})/" "template/([a-z]*)/",
            StationPieceHandler,
            dict(store=store),
        ),
        (r"/stations/((?:[0-9]{1,3}\.){3}[0-9]{1,3})/([0-9]{1,5})/prompt/", PromptHandler, dict(store=store)),
        (
            r"/stations/((?:[0-9]{1,3}\.){3}[0-9]{1,3})/([0-9]{1,5})/prompt/(.*)/",
            PromptResponseHandler,