Exemple #1
0
 def test_invalid_key(self):
     with self.assertRaises(conf.InvalidKeyError):
         conf.declare('_invalid')
     with self.assertRaises(conf.InvalidKeyError):
         conf.declare('Invalid')
Exemple #2
0
# 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.
"""Example plugs for OpenHTF."""

from openhtf.core import base_plugs
from openhtf.util import conf

conf.declare(
    'example_plug_increment_size',
    default_value=1,
    description='increment constant for example plug.')


class ExamplePlug(base_plugs.BasePlug):  # pylint: disable=no-init
  """Example of a simple plug.

  This plug simply keeps a value and increments it each time increment() is
  called.  You'll notice a few paradigms here:

    - @conf.inject_positional_args
      This is generally a good way to pass in any configuration that your
      plug needs, such as an IP address or serial port to connect to.  If
      You want to use your plug outside of the OpenHTF framework, you can
      still manually instantiate it, but you must pass the arguments by
      keyword (as a side effect of the way inject_positional_args is
Exemple #3
0
    '--config-value',
    'other_flag=other_value',
    # You can specify arbitrary keys, but they'll get ignored if they aren't
    # actually declared anywhere (included here to make sure of that).
    '--config_value=undeclared_flag=who_cares',
    '--config-value=true_value=true',
    '--config-value',
    'num_value=100',
])

import os.path
import unittest

from openhtf.util import conf

conf.declare('flag_key')
conf.declare('other_flag')
conf.declare('true_value')
conf.declare('num_value')
conf.declare('json_test_key')
conf.declare('yaml_test_key')
conf.declare('overridden_key')
conf.declare('none_default', default_value=None)
conf.declare('string_default', default_value='default')
conf.declare('no_default')


def tear_down_module():
    sys.argv = _old_argv

Exemple #4
0
import commands
import logging
import time

import openhtf.plugs as plugs
from openhtf.plugs.usb import adb_device
from openhtf.plugs.usb import fastboot_device
from openhtf.plugs.usb import local_usb
from openhtf.plugs.usb import usb_exceptions
from openhtf.plugs import cambrionix
from openhtf.plugs.user_input import prompt_for_test_start
from openhtf.util import conf

_LOG = logging.getLogger(__name__)

conf.declare('libusb_rsa_key', 'A private key file for use by libusb auth.')
conf.declare('remote_usb', 'ethersync or other')
conf.declare('ethersync', 'ethersync configuration')

def _open_usb_handle(**kwargs):
  """Open a UsbHandle subclass, based on configuration.

  If configuration 'remote_usb' is set, use it to connect to remote usb,
  otherwise attempt to connect locally.'remote_usb' is set to usb type,
  EtherSync or other.

  Example of Cambrionix unit in config:
  remote_usb: ethersync
  ethersync:
       mac_addr: 78:a5:04:ca:91:66
       plug_port: 5
Exemple #5
0
STATION_SERVER_TYPE = 'station'

MULTICAST_QUERY = 'OPENHTF_DISCOVERY'
TEST_STATUS_COMPLETED = 'COMPLETED'

_LOG = logging.getLogger(__name__)

# Constants related to response times within the server.
_CHECK_FOR_FINISHED_TEST_POLL_S = 0.5
_DEFAULT_FRONTEND_THROTTLE_S = 0.15
_WAIT_FOR_ANY_EVENT_POLL_S = 0.05
_WAIT_FOR_EXECUTING_TEST_POLL_S = 0.1

conf.declare('frontend_throttle_s',
             default_value=_DEFAULT_FRONTEND_THROTTLE_S,
             description=('Min wait time between successive updates to the '
                          'frontend.'))
conf.declare(
    'station_server_port',
    default_value=0,
    description=('Port on which to serve the app. If set to zero (the '
                 'default) then an arbitrary port will be chosen.'))

# These have default values in openhtf.util.multicast.py.
conf.declare('station_discovery_address')
conf.declare('station_discovery_port')
conf.declare('station_discovery_ttl')


def _get_executing_test():
    """Get the currently executing test and its state.
Exemple #6
0
import threading

import contextlib2 as contextlib

import openhtf
from openhtf.core import phase_executor
from openhtf.core import phase_group
from openhtf.core import test_state
from openhtf.util import conf
from openhtf.util import threads

_LOG = logging.getLogger(__name__)

conf.declare(
    'cancel_timeout_s',
    default_value=2,
    description='Timeout (in seconds) when the test has been cancelled'
    'to wait for the running phase to exit.')


class TestExecutionError(Exception):
    """Raised when there's an internal error during test execution."""


class TestStopError(Exception):
    """Test is being stopped."""


# pylint: disable=too-many-instance-attributes
class TestExecutor(threads.KillableThread):
    """Encompasses the execution of a single test."""
Exemple #7
0
from openhtf.core import base_plugs
from openhtf.plugs import cambrionix
from openhtf.plugs.usb import adb_device
from openhtf.plugs.usb import adb_protocol
from openhtf.plugs.usb import fastboot_device
from openhtf.plugs.usb import fastboot_protocol
from openhtf.plugs.usb import local_usb
from openhtf.plugs.usb import usb_exceptions
from openhtf.plugs.user_input import prompt_for_test_start
from openhtf.util import conf
from openhtf.util import functions

_LOG = logging.getLogger(__name__)

conf.declare('libusb_rsa_key', 'A private key file for use by libusb auth.')
conf.declare('remote_usb', 'ethersync or other')
conf.declare('ethersync', 'ethersync configuration')


@functions.call_once
def init_dependent_flags():
    parser = argparse.ArgumentParser(
        'USB Plug flags',
        parents=[adb_protocol.ARG_PARSER, fastboot_protocol.ARG_PARSER],
        add_help=False)
    parser.parse_known_args()


def _open_usb_handle(serial_number=None, **kwargs):
    """Open a UsbHandle subclass, based on configuration.
Exemple #8
0
from openhtf import plugs
from openhtf.core import station_api
from openhtf.util import classproperty
from openhtf.util import conf
from openhtf.util import logs
from openhtf.util.data import convert_to_base_types


_LOG = logging.getLogger(__name__)

UNKNOWN_STATION_ID = "UNKNOWN_STATION"
BUILD_PATH = os.path.join(os.path.dirname(__file__), "src", "dist")
PREBUILT_PATH = os.path.join(os.path.dirname(__file__), "prebuilt")

conf.declare("stations", default_value=[], description="List of manually declared stations.")


Hostport = collections.namedtuple("Hostport", ["host", "port"])


class TestWatcher(threading.Thread):
    """Watches a RemoteTest for updates and executes a callback with new state.

  Args:
    hostport: Tuple of (host, port) describing the station being watched.
    test: The RemoteTest instance to watch.
    callback: Callback function to invoke on updates. Gets passed the updated
              RemoteState.
    wait_timeout_s: Seconds to wait for an update before timeout and retry.
  """
Exemple #9
0
import cloudant

from openhtf.util import data, format_string
from openhtf.core import test_record

from openhtf.util import conf

conf.declare('db_url',
             default_value='http://db:5984',
             description='URL of the database to upload test records.')
conf.declare('db_user')
conf.declare('db_pass', )
conf.declare('db_name',
             default_value='test_records',
             description='Name of the database to upload test records to.')


class CouchDBUploader():
    """Return an output callback that writes test records to CouchDB or Cloudant.

    Example test_id might be:
    '{dut_id}_{metadata[test_name]}_{start_time_millis}'

    Args:
        id_pattern: A format string specifying database ID will be formated with
            TestRecord as a dictionary. 
        upload_attachements: Whether attachements should be uploaded to a database 
            together with TestRecord.
        db_url: URL of the database to upload test records.
        db_name: Name of the database to upload test records to.
        db_user: Username used to connect to the database.
Exemple #10
0
from openhtf.util import threads
from openhtf.util import timeouts
from openhtf.util import xmlrpcutil

# Fix for xmlrpclib to use <i8> for longs instead of <int>, because our
# timestamps are in millis, which are too big for 4-byte ints.
xmlrpclib.Marshaller.dispatch[long] = (
    lambda _, v, w: w('<value><i8>%d</i8></value>' % v))

_LOG = logging.getLogger(__name__)

# We export this so external users (ie the frontend server) know what key
# to use for station discovery, even if it's overridden in the config.
DEFAULT_DISCOVERY_STRING = 'OPENHTF_DISCOVERY'

conf.declare('enable_station_discovery', default_value=True)
conf.declare('station_api_bind_address', default_value='0.0.0.0')
conf.declare('station_api_port', default_value=8888)
conf.declare('station_discovery_string', default_value=DEFAULT_DISCOVERY_STRING)

# These have defaults in util.multicast, we'll use those if not set.
conf.declare('station_discovery_address')
conf.declare('station_discovery_port')
conf.declare('station_discovery_ttl')

# Build multicast kwargs based on conf, otherwise use defaults.
MULTICAST_KWARGS = lambda: {
    attr: conf['station_discovery_%s' % attr]
    for attr in ('address', 'port', 'ttl')
    if 'station_discovery_%s' % attr in conf
}
Exemple #11
0
import contextlib2 as contextlib

import openhtf
from openhtf import plugs
from openhtf import util
from openhtf.core import phase_executor
from openhtf.core import station_api
from openhtf.core import test_record
from openhtf.core import test_state
from openhtf.util import conf
from openhtf.util import threads

_LOG = logging.getLogger(__name__)

conf.declare('teardown_timeout_s',
             default_value=30,
             description='Timeout (in seconds) for test teardown functions.')


class TestExecutionError(Exception):
    """Raised when there's an internal error during test execution."""


class TestStopError(Exception):
    """Test is being stopped."""


# pylint: disable=too-many-instance-attributes
class TestExecutor(threads.KillableThread):
    """Encompasses the execution of a single test."""
    def __init__(self,
Exemple #12
0
import logging
import sys
import threading

import contextlib2 as contextlib

import openhtf
from openhtf.core import phase_executor
from openhtf.core import test_state
from openhtf.util import conf
from openhtf.util import threads

_LOG = logging.getLogger(__name__)

conf.declare('teardown_timeout_s',
             default_value=30,
             description='Timeout (in seconds) for test teardown functions.')
conf.declare(
    'cancel_timeout_s',
    default_value=15,
    description='Timeout (in seconds) when the test has been cancelled'
    'to wait for the running phase to exit.')


class TestExecutionError(Exception):
    """Raised when there's an internal error during test execution."""


class TestStopError(Exception):
    """Test is being stopped."""
from openhtf.core import base_plugs
from openhtf.util import conf

try:
    # pylint: disable=g-import-not-at-top
    import serial  # pytype: disable=import-error
    # pylint: enable=g-import-not-at-top
except ImportError:
    logging.error(
        'Failed to import pyserial. Please install the `serial_collection_plug` extra, '
        'e.g. via `pip install openhtf[serial_collection_plug]`.')
    raise

conf.declare('serial_collection_port',
             description='Port on which to collect serial data.',
             default_value='/dev/ttyACM0')
conf.declare('serial_collection_baud',
             description='Baud rate for serial data collection.',
             default_value=115200)


class SerialCollectionPlug(base_plugs.BasePlug):
    """Plug that collects data from a serial port.

  Spawns a thread that will open the configured serial port, continuously
  poll the port for data, and write the data to the destination file as it is
  received. If any serial errors are encountered during the lifetime of the
  polling thread, data collection stops and an error message is logged.
  Otherwise, data collection stops and the serial port is closed when
  stop_collection() is called.
Exemple #14
0
import logging
import threading

try:
  import serial
except ImportError:
  logging.error('Failed to import pyserial. Please install the `serial_collection_plug` extra, '
                'e.g. via `pip install openhtf[serial_collection_plug]`.')
  raise

import openhtf
from openhtf.util import conf


conf.declare(
    'serial_collection_port',
    description='Port on which to collect serial data.',
    default_value='/dev/ttyACM0')
conf.declare(
    'serial_collection_baud',
    description='Baud rate for serial data collection.',
    default_value=115200)


class SerialCollectionPlug(openhtf.plugs.BasePlug):
  """Plug that collects data from a serial port.

  Spawns a thread that will open the configured serial port, continuously
  poll the port for data, and write the data to the destination file as it is
  received. If any serial errors are encountered during the lifetime of the
  polling thread, data collection stops and an error message is logged.
  Otherwise, data collection stops and the serial port is closed when
Exemple #15
0
import logging
import sys
import threading

from openhtf.core import phase_executor
from openhtf.core import phase_group
from openhtf.core import test_state
from openhtf.util import conf
from openhtf.util import threads


_LOG = logging.getLogger(__name__)

conf.declare('cancel_timeout_s', default_value=2,
             description='Timeout (in seconds) when the test has been cancelled'
             'to wait for the running phase to exit.')


class TestExecutionError(Exception):
  """Raised when there's an internal error during test execution."""


class TestStopError(Exception):
  """Test is being stopped."""


# pylint: disable=too-many-instance-attributes
class TestExecutor(threads.KillableThread):
  """Encompasses the execution of a single test."""
  daemon = True
Exemple #16
0
MIMETYPE_REVERSE_MAP = {
    v: k for k, v in six.iteritems(mfg_inspector.MIMETYPE_MAP)
}
MULTICAST_QUERY = 'OPENHTF_DISCOVERY'
TEST_STATUS_COMPLETED = 'COMPLETED'

_LOG = logging.getLogger(__name__)

# Constants related to response times within the server.
_CHECK_FOR_FINISHED_TEST_POLL_S = 0.5
_DEFAULT_FRONTEND_THROTTLE_S = 0.15
_WAIT_FOR_ANY_EVENT_POLL_S = 0.05
_WAIT_FOR_EXECUTING_TEST_POLL_S = 0.1

conf.declare('frontend_throttle_s', default_value=_DEFAULT_FRONTEND_THROTTLE_S,
             description=('Min wait time between successive updates to the '
                          'frontend.'))
conf.declare('station_server_port', default_value=0,
             description=('Port on which to serve the app. If set to zero (the '
                          'default) then an arbitrary port will be chosen.'))

# These have default values in openhtf.util.multicast.py.
conf.declare('station_discovery_address')
conf.declare('station_discovery_port')
conf.declare('station_discovery_ttl')


def _get_executing_test():
  """Get the currently executing test and its state.

  When this function returns, it is not guaranteed that the returned test is
Exemple #17
0
from enum import Enum

import mutablerecords

import openhtf

from openhtf import plugs
from openhtf import util
from openhtf.core import measurements
from openhtf.core import phase_executor
from openhtf.core import test_record
from openhtf.util import conf
from openhtf.util import logs

conf.declare('allow_unset_measurements',
             default_value=False,
             description='If True, unset measurements do not cause Tests to '
             'FAIL.')
# 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.load_from_dict({..., 'station_id': 'My_Station'}).  If none of those
# are provided then we'll fall back to the machine's hostname.
conf.declare('station_id',
             'The name of this test station',
             default_value=socket.gethostname())

_LOG = logging.getLogger(__name__)


class BlankDutIdError(Exception):
    """DUT serial cannot be blank at the end of a test."""
Exemple #18
0
from openhtf import util
from openhtf.util import conf
from openhtf.util import data
from openhtf.util import logs

import six

if TYPE_CHECKING:
    from openhtf.core import diagnoses_lib  # pylint: disable=g-import-not-at-top
    from openhtf.core import measurements as htf_measurements  # pylint: disable=g-import-not-at-top
    from openhtf.core import phase_descriptor  # pylint: disable=g-import-not-at-top
    from openhtf.core import phase_executor  # pylint: disable=g-import-not-at-top
    from openhtf.core import phase_branches  # pylint: disable=g-import-not-at-top

conf.declare(
    'attachments_directory',
    default_value=None,
    description='Directory where temprorary files can be safely stored.')

_LOG = logging.getLogger(__name__)


@attr.s(slots=True, frozen=True)
class OutcomeDetails(object):
    code = attr.ib(type=Union[Text, int])
    description = attr.ib(type=Text)


class Outcome(enum.Enum):
    PASS = '******'
    FAIL = 'FAIL'
    ERROR = 'ERROR'
Exemple #19
0
import openhtf
from openhtf import util
from openhtf.util import classproperty
from openhtf.util import conf
from openhtf.util import logs
from openhtf.util import threads
from openhtf.util import xmlrpcutil
import six


_LOG = logging.getLogger(__name__)


conf.declare('plug_teardown_timeout_s', default_value=0, description=
             'Timeout (in seconds) for each plug tearDown function if > 0; '
             'otherwise, will wait an unlimited time.')


PlugDescriptor = collections.namedtuple('PlugDescriptor', ['mro'])  # pylint: disable=invalid-name

# Placeholder for a specific plug to be provided before test execution.
#
# Use the with_plugs() method to provide the plug before test execution. The
# with_plugs() method checks to make sure the substitute plug is a subclass of
# the PlugPlaceholder's base_class.
PlugPlaceholder = collections.namedtuple('PlugPlaceholder', ['base_class'])  # pylint: disable-invalid-name


class PlugOverrideError(Exception):
  """Raised when a plug would be overridden by a kwarg."""
Exemple #20
0
This module is essentially an LRU cache for OpenHTF tests, with some
intelligence around Test object metadata and eviction policies.
"""

import collections
import logging
import sys
import threading

from openhtf.util import conf
from openhtf.util import data
from openhtf.util import threads

_LOG = logging.getLogger(__name__)

conf.declare('max_history_size_mb', default_value=256)


class HistorySyncError(Exception):
    """Raised when some part of the history gets out of sync with the rest."""


HistoryEntry = collections.namedtuple('HistoryEntry', ['test_uid', 'record'])


class TestHistory(object):
    """This class encapsulates a history of TestRecords from completed tests.

  This class provides basic deque functionality, with some additional
  approximate size tracking.
  """
Exemple #21
0
import tornado.web

from openhtf import plugs
from openhtf.core import station_api
from openhtf.util import classproperty
from openhtf.util import conf
from openhtf.util import threads
from openhtf.util import data


_LOG = logging.getLogger(__name__)

UNKNOWN_STATION_ID = 'UNKNOWN_STATION'

conf.declare('stations',
             default_value=[],
             description='List of manually declared stations.')

Hostport = collections.namedtuple('Hostport', ['host', 'port'])


class PlugWatcher(threading.Thread):
  """Watches a plug for updates.

  Args:
    test: The RemoteTest instance to watch.
    plug_name: The plug to watch.
    callback: Callback function to invoke on updates.
    wait_timeout_s: Seconds to wait for an update before timeout and retry.
  """
  daemon = True
Exemple #22
0
from openhtf.core import test_record
from openhtf.plugs import plug
from openhtf.util import conf
from openhtf.util import data
from openhtf.util import functions
from openhtf.util import logs
from openhtf.util import units


__version__ = util.get_version()
_LOG = logging.getLogger(__name__)

conf.declare('capture_source', description=textwrap.dedent(
    '''Whether to capture the source of phases and the test module.  This
    defaults to False since this potentially reads many files and makes large
    string copies.

    Set to 'true' if you want to capture your test's source.'''),
    default_value=False)


class UnrecognizedTestUidError(Exception):
  """Raised when information is requested about an unknown Test UID."""


class InvalidTestPhaseError(Exception):
  """Raised when an invalid method is decorated."""


class InvalidTestStateError(Exception):
  """Raised when an operation is attempted in an invalid state."""
Exemple #23
0
This module is essentially an LRU cache for OpenHTF tests, with some
intelligence around Test object metadata and eviction policies.
"""

import collections
import logging
import sys
import threading

from openhtf.util import conf
from openhtf.util import data
from openhtf.util import threads

_LOG = logging.getLogger(__name__)

conf.declare('max_history_size_mb', default_value=256)


class HistorySyncError(Exception):
  """Raised when some part of the history gets out of sync with the rest."""


HistoryEntry = collections.namedtuple('HistoryEntry', ['test_uid', 'record'])


class TestHistory(object):
  """This class encapsulates a history of TestRecords from completed tests.

  This class provides basic deque functionality, with some additional
  approximate size tracking.
  """
Exemple #24
0
from openhtf.core import phase_group
from openhtf.core import test_executor
from openhtf.core import test_record

from openhtf.util import conf
from openhtf.util import console_output
from openhtf.util import logs

import six

_LOG = logging.getLogger(__name__)

conf.declare('capture_source', description=textwrap.dedent(
    '''Whether to capture the source of phases and the test module.  This
    defaults to False since this potentially reads many files and makes large
    string copies.

    Set to 'true' if you want to capture your test's source.'''),
             default_value=False)
# TODO(arsharma): Deprecate this configuration after removing the old teardown
# specification.
conf.declare('teardown_timeout_s', default_value=30, description=
             'Default timeout (in seconds) for test teardown functions; '
             'this option is deprecated and only applies to the deprecated '
             'Test level teardown function.')


class UnrecognizedTestUidError(Exception):
  """Raised when information is requested about an unknown Test UID."""

Exemple #25
0
from enum import Enum

import mutablerecords

import openhtf

from openhtf import plugs
from openhtf import util
from openhtf.core import phase_executor
from openhtf.core import measurements
from openhtf.core import test_record
from openhtf.util import conf
from openhtf.util import logs
from openhtf.util import threads

conf.declare('allow_unset_measurements', default_value=False, description=\
  'If True, unset measurements do not cause Tests to FAIL.')
# 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.load_from_dict({..., 'station_id': 'My_Station'}).  If none of those
# are provided then we'll fall back to the machine's hostname.
conf.declare('station_id', 'The name of this test station',
             default_value=socket.gethostname())

_LOG = logging.getLogger(__name__)


class BlankDutIdError(Exception):
  """DUT serial cannot be blank at the end of a test."""

Exemple #26
0
import sys
import threading

from openhtf.core import phase_descriptor
from openhtf.core import phase_executor
from openhtf.core import phase_group
from openhtf.core import test_record
from openhtf.core import test_state
from openhtf.util import conf
from openhtf.util import threads

_LOG = logging.getLogger(__name__)

conf.declare(
    'cancel_timeout_s',
    default_value=2,
    description='Timeout (in seconds) when the test has been cancelled'
    'to wait for the running phase to exit.')

conf.declare('stop_on_first_failure',
             default_value=False,
             description='Stop current test execution and return Outcome FAIL'
             'on first phase with failed measurement.')


class TestExecutionError(Exception):
    """Raised when there's an internal error during test execution."""


class TestStopError(Exception):
    """Test is being stopped."""
Exemple #27
0
from openhtf.core import test_executor
from openhtf.core import test_record

from openhtf.util import conf
from openhtf.util import console_output
from openhtf.util import logs

import six

_LOG = logging.getLogger(__name__)

conf.declare(
    'capture_source',
    description=textwrap.dedent(
        '''Whether to capture the source of phases and the test module.  This
    defaults to False since this potentially reads many files and makes large
    string copies.

    Set to 'true' if you want to capture your test's source.'''),
    default_value=False)
# TODO(arsharma): Deprecate this configuration after removing the old teardown
# specification.
conf.declare(
    'teardown_timeout_s',
    default_value=30,
    description='Default timeout (in seconds) for test teardown functions; '
    'this option is deprecated and only applies to the deprecated '
    'Test level teardown function.')


class UnrecognizedTestUidError(Exception):
Exemple #28
0
# 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.


"""Example plug for OpenHTF."""


import time

import openhtf.plugs as plugs
from openhtf.util import conf


conf.declare('example_plug_increment_size', default_value=1,
             description='increment constant for example plug.')


class ExamplePlug(plugs.BasePlug):   # pylint: disable=no-init
  """Example of a simple plug.

  This plug simply keeps a value and increments it each time increment() is
  called.  You'll notice a few paradigms here:

    - @conf.inject_positional_args
      This is generally a good way to pass in any configuration that your
      plug needs, such as an IP address or serial port to connect to.  If
      You want to use your plug outside of the OpenHTF framework, you can
      still manually instantiate it, but you must pass the arguments by
      keyword (as a side effect of the way inject_positional_args is
      implemented).
Exemple #29
0
 def test_multiple_declaration(self):
     conf.declare('multiple')
     with self.assertRaises(conf.KeyAlreadyDeclaredError):
         conf.declare('multiple')
Exemple #30
0
sys.argv.extend([
    '--config-value=flag_key=flag_value',
    '--config-value', 'other_flag=other_value',
    # You can specify arbitrary keys, but they'll get ignored if they aren't
    # actually declared anywhere (included here to make sure of that).
    '--config_value=undeclared_flag=who_cares',
    '--config-value=true_value=true',
    '--config-value', 'num_value=100',
])

import os.path
import unittest

from openhtf.util import conf

conf.declare('flag_key')
conf.declare('other_flag')
conf.declare('true_value')
conf.declare('num_value')
conf.declare('json_test_key')
conf.declare('yaml_test_key')
conf.declare('overridden_key')
conf.declare('none_default', default_value=None)
conf.declare('string_default', default_value='default')
conf.declare('no_default')


def tear_down_module():
    sys.argv = _old_argv

Exemple #31
0
from enum import Enum

import contextlib2 as contextlib

import openhtf
from openhtf import plugs
from openhtf import util
from openhtf.core import phase_executor
from openhtf.core import test_record
from openhtf.core import test_state
from openhtf.util import conf
from openhtf.util import threads

_LOG = logging.getLogger(__name__)

conf.declare('teardown_timeout_s', default_value=3, description=
             'Timeout (in seconds) for test teardown functions.')


class TestExecutionError(Exception):
  """Raised when there's an internal error during test execution."""


class TestStopError(Exception):
  """Test is being stopped."""


# pylint: disable=too-many-instance-attributes
class TestExecutor(threads.KillableThread):
  """Encompasses the execution of a single test."""

  def __init__(self, test_descriptor, test_start, teardown_function=None):
Exemple #32
0
 def test_multiple_declaration(self):
   conf.declare('multiple')
   with self.assertRaises(conf.KeyAlreadyDeclaredError):
     conf.declare('multiple')
Exemple #33
0
import mutablerecords

from openhtf import util
import openhtf.core.phase_descriptor
from openhtf.util import classproperty
from openhtf.util import conf
from openhtf.util import logs
from openhtf.util import threads
import six

_LOG = logging.getLogger(__name__)

conf.declare(
    'plug_teardown_timeout_s',
    default_value=0,
    description='Timeout (in seconds) for each plug tearDown function if > 0; '
    'otherwise, will wait an unlimited time.')

PlugDescriptor = collections.namedtuple('PlugDescriptor', ['mro'])  # pylint: disable=invalid-name

# Placeholder for a specific plug to be provided before test execution.
#
# Use the with_plugs() method to provide the plug before test execution. The
# with_plugs() method checks to make sure the substitute plug is a subclass of
# the PlugPlaceholder's base_class.
PlugPlaceholder = collections.namedtuple('PlugPlaceholder', ['base_class'])  # pylint: disable=invalid-name


class PhasePlug(
        mutablerecords.Record('PhasePlug', ['name', 'cls'],
Exemple #34
0
 def test_invalid_key(self):
   with self.assertRaises(conf.InvalidKeyError):
     conf.declare('_invalid')
   with self.assertRaises(conf.InvalidKeyError):
     conf.declare('Invalid')
Exemple #35
0
from openhtf.core import test_executor
from openhtf.core import test_record

from openhtf.util import conf
from openhtf.util import console_output
from openhtf.util import logs

import six

_LOG = logging.getLogger(__name__)

conf.declare(
    'capture_source',
    description=textwrap.dedent(
        '''Whether to capture the source of phases and the test module.  This
    defaults to False since this potentially reads many files and makes large
    string copies.

    Set to 'true' if you want to capture your test's source.'''),
    default_value=False)


class UnrecognizedTestUidError(Exception):
    """Raised when information is requested about an unknown Test UID."""


class InvalidTestPhaseError(Exception):
    """Raised when an invalid method is decorated."""


class InvalidTestStateError(Exception):
Exemple #36
0
import tornado.ioloop
import tornado.web

from openhtf import plugs
from openhtf.core import station_api
from openhtf.util import classproperty
from openhtf.util import conf
from openhtf.util import threads
from openhtf.util import data

_LOG = logging.getLogger(__name__)

UNKNOWN_STATION_ID = 'UNKNOWN_STATION'

conf.declare('stations',
             default_value=[],
             description='List of manually declared stations.')

Hostport = collections.namedtuple('Hostport', ['host', 'port'])


class PlugWatcher(threading.Thread):
    """Watches a plug for updates.

  Args:
    test: The RemoteTest instance to watch.
    plug_name: The plug to watch.
    callback: Callback function to invoke on updates.
    wait_timeout_s: Seconds to wait for an update before timeout and retry.
  """
    daemon = True
Exemple #37
0
from openhtf.util import timeouts
from openhtf.util import xmlrpcutil
from past.builtins import long

# Fix for xmlrpclib to use <i8> for longs and ints instead of <int>, because our
# timestamps are in millis, which are too big for 4-byte ints.
xmlrpc.client.Marshaller.dispatch[long] = xmlrpc.client.Marshaller.dispatch[
    int] = (lambda _, v, w: w('<value><i8>%d</i8></value>' % v))

_LOG = logging.getLogger(__name__)

# We export this so external users (ie the frontend server) know what key
# to use for station discovery, even if it's overridden in the config.
DEFAULT_DISCOVERY_STRING = 'OPENHTF_DISCOVERY'

conf.declare('enable_station_discovery', default_value=True)
conf.declare('station_api_bind_address', default_value='0.0.0.0')
conf.declare('station_api_port', default_value=8888)
conf.declare('station_discovery_string',
             default_value=DEFAULT_DISCOVERY_STRING)

# These have defaults in util.multicast, we'll use those if not set.
conf.declare('station_discovery_address')
conf.declare('station_discovery_port')
conf.declare('station_discovery_ttl')

# Build multicast kwargs based on conf, otherwise use defaults.
MULTICAST_KWARGS = lambda: {
    attr: conf['station_discovery_%s' % attr]
    for attr in ('address', 'port', 'ttl')
    if 'station_discovery_%s' % attr in conf
Exemple #38
0
from openhtf.util import multicast
from openhtf.util import threads
from openhtf.util import timeouts
from openhtf.util import xmlrpcutil

# Fix for xmlrpclib to use <i8> for longs instead of <int>, because our
# timestamps are in millis, which are too big for 4-byte ints.
xmlrpclib.Marshaller.dispatch[long] = lambda _, v, w: w("<value><i8>%d</i8></value>" % v)

_LOG = logging.getLogger(__name__)

# We export this so external users (ie the frontend server) know what key
# to use for station discovery, even if it's overridden in the config.
DEFAULT_DISCOVERY_STRING = "OPENHTF_DISCOVERY"

conf.declare("enable_station_discovery", default_value=True)
conf.declare("station_api_bind_address", default_value="0.0.0.0")
conf.declare("station_api_port", default_value=8888)
conf.declare("station_discovery_string", default_value=DEFAULT_DISCOVERY_STRING)

# These have defaults in util.multicast, we'll use those if not set.
conf.declare("station_discovery_address")
conf.declare("station_discovery_port")
conf.declare("station_discovery_ttl")

# Build multicast kwargs based on conf, otherwise use defaults.
MULTICAST_KWARGS = lambda: {
    attr: conf["station_discovery_%s" % attr]
    for attr in ("address", "port", "ttl")
    if "station_discovery_%s" % attr in conf
}