Ejemplo n.º 1
0
def coordinator_example_main():

    logging_initialize()

    from akit.interop.landscaping.landscape import Landscape, startup_landscape

    startup_landscape()

    lscape = Landscape()

    s17 = lscape.checkout_a_device_by_modelNumber("S17")

    upnpcoord = lscape.upnp_coord
    firstdev = upnpcoord.watch_devices[0].upnp
    print(type(firstdev))
    print(firstdev)

    powerdev = None
    for upnpdev in upnpcoord.watch_devices:
        if upnpdev.power is not None:
            powerdev = upnpdev.power
            break

    if powerdev is not None:
        powerdev.off()
        time.sleep(2)
        powerdev.on()
        time.sleep(2)
        powerdev.off()
        time.sleep(2)
        powerdev.on()

    devProps = firstdev.serviceDeviceProperties()

    value = devProps.action_GetLEDState()

    if devProps.subscribe_to_events():
        var_zonename = devProps.lookup_event_variable("ZoneName")
        znval = var_zonename.wait_for_value(timeout=600)
        print (var_zonename)

        isbval = devProps.lookup_event_variable("IsZoneBridge")
        print (isbval)

    LEDSTATES = ["Off", "On"]

    SMALL_COUNTER = 0
    LARGE_COUNTER = 0
    while True:
        time.sleep(2)
        if SMALL_COUNTER == 0:
            print("tick")
        else:
            print("tock")

        if LARGE_COUNTER == 0:
            print("Refreshing upnp device status.")

        SMALL_COUNTER = (SMALL_COUNTER + 1) % 2
        LARGE_COUNTER = (LARGE_COUNTER + 1) % 30
Ejemplo n.º 2
0
def coordinator_example_main():

    logging_initialize()

    lscape: Landscape = startup_landscape(include_upnp=True)

    s11 = lscape.checkout_a_device_by_modelNumber("S11").upnp

    svc_avt = s11.serviceAVTransport()

    var_cur_uri = svc_avt.lookup_default_variable("AVTransportURI")

    cur_uri = var_cur_uri.value

    print("")
    print("")
    print("Bdee bdee bdee, Thats all folks!")
    print("")
    print("")
Ejemplo n.º 3
0
def command_akit_jobs_run(root, job, output, start, branch, build, flavor, console_level, logfile_level):

    # pylint: disable=unused-import,import-outside-toplevel

    # We do the imports of the automation framework code inside the action functions because
    # we don't want to startup loggin and the processing of inputs and environment variables
    # until we have entered an action method.  Thats way we know how to setup the environment.

    # IMPORTANT: We need to load the context first because it will trigger the loading
    # of the default user configuration
    from akit.environment.context import Context

    from akit.compat import import_by_name
    from akit.environment.variables import extend_path

    try:
        ctx = Context()
        ctx.insert("/environment/jobtype", 'testrun')

        test_root = os.path.abspath(os.path.expandvars(os.path.expanduser(root)))
        if not os.path.isdir(test_root):
            errmsg = "The specified root folder does not exist. root=%s" % root
            if test_root != root:
                errmsg += " expanded=%s" % test_root
            raise argparse.ArgumentError("--root", errmsg)

        # Make sure we extend PATH to include the test root
        extend_path(test_root)

        # We perform activation a little later in the testrunner.py file so we can
        # handle exceptions in the context of testrunner_main function
        import akit.activation.testrun
        from akit.xlogging.foundations import logging_initialize, getAutomatonKitLogger

        # Initialize logging
        logging_initialize()
        logger = getAutomatonKitLogger()

        from akit.extensionpoints import AKitExtensionPoints
        akep = AKitExtensionPoints()

        # At this point in the code, we either lookup an existing test job or we create a test job
        # from the includes, excludes or test_module
        TestJobType = akep.get_testplus_default_job_type()

        if job is not None:
            job_parts = job.split("@")
            if len(job_parts) != 2:
                errmsg = "A --job parameter must be of the form 'package.module@JobClass'"
                raise click.UsageError(errmsg)

            job_package, job_class = job_parts

            try:
                job_mod = import_by_name(job_package)
            except ImportError as imperr:
                errmsg = "Failure while importing job package %r"  % job_package
                raise argparse.ArgumentError("--job", errmsg) from imperr

            if not hasattr(job_mod, job_class):
                errmsg = "The job package %r does not have a job type %r." % (job_package, job_class)
                raise argparse.ArgumentError("--job", errmsg)

            TestJobType = getattr(job_mod, job_class)

        result_code = 0
        with TestJobType(logger, test_root) as tjob:
            result_code = tjob.execute()

        sys.exit(result_code)

    finally:
        pass

    return
Ejemplo n.º 4
0
def generic_test_entrypoint():
    """
        This is the generic test entry point for test modules.  It provides a standardized set of
        commanline parameters that can be used to run test files as scripts.

    .. note::
       The `generic_test_entrypoint` is a useful tool to place at the bottom of test files to allow
       them to easily be run for debugging purposes.
    """
    # We must exit with a result code, initialize it to 0 here
    result_code = 0

    base_parser = argparse.ArgumentParser()

    base_parser.add_argument("-i",
                             "--include",
                             dest="includes",
                             action="append",
                             default=[],
                             help="Add an include search statement.")
    base_parser.add_argument("-x",
                             "--exclude",
                             dest="excludes",
                             action="append",
                             default=[],
                             help="Add an exclude filter statement.")
    base_parser.add_argument("--console-level",
                             dest="consolelevel",
                             action="store",
                             default="INFO",
                             choices=LOG_LEVEL_NAMES,
                             help="The logging level for console output.")
    base_parser.add_argument("--logfile-level",
                             dest="logfilelevel",
                             action="store",
                             default="DEBUG",
                             choices=LOG_LEVEL_NAMES,
                             help="The logging level for logfile output.")

    test_module = sys.modules["__main__"]

    ctx = Context()
    env = ctx.lookup("/environment")

    # Set the jobtype
    env["jobtype"] = "testrun"

    test_results_dir = get_path_for_testresults()
    if not os.path.exists(test_results_dir):
        os.makedirs(test_results_dir)
    env["output_directory"] = test_results_dir

    test_root = find_testmodule_root(test_module)
    module_fullname = find_testmodule_fullname(test_module)

    # Copy the test module to the name of the module_fullname name so the loader won't reload it
    sys.modules[module_fullname] = test_module

    if test_module.__name__ == "__main__":
        test_module.__name__ = module_fullname

        # Re-map the object classes from the module over to the module name we just registered the test
        # module under.
        test_class_coll = inspect.getmembers(test_module, inspect.isclass)
        for testclass_name, testclass_obj in test_class_coll:
            tcobj_module_name = testclass_obj.__module__
            if tcobj_module_name == "__main__":
                testclass_obj.__module__ = module_fullname

    args = base_parser.parse_args()

    logging_initialize()

    includes = args.includes
    excludes = args.excludes
    if len(includes) == 0:
        includes.append("*")

    result_code = 0
    with DefaultTestJob(logger,
                        test_root,
                        includes=includes,
                        excludes=excludes,
                        test_module=test_module) as tjob:
        result_code = tjob.execute()

    sys.exit(result_code)

    return
Ejemplo n.º 5
0
def command_akit_landscape_verify(credentials_file, landscape_file,
                                  runtime_file):

    # pylint: disable=unused-import,import-outside-toplevel

    # We do the imports of the automation framework code inside the action functions because
    # we don't want to startup loggin and the processing of inputs and environment variables
    # until we have entered an action method.  Thats way we know how to setup the environment.

    # IMPORTANT: We need to load the context first because it will trigger the loading
    # of the default user configuration
    from akit.environment.context import Context
    from akit.environment.contextpaths import ContextPaths

    from akit.environment.variables import JOB_TYPES, AKIT_VARIABLES

    from akit.environment.optionoverrides import (override_config_credentials,
                                                  override_config_landscape,
                                                  override_config_runtime)

    ctx = Context()
    env = ctx.lookup("/environment")

    # We need to set the job type before we trigger activation.
    env["jobtype"] = JOB_TYPES.COMMAND

    # Activate the AutomationKit environment with characteristics of a console application
    import akit.activation.console

    from akit.xlogging.foundations import logging_initialize, getAutomatonKitLogger

    # Initialize logging
    logging_initialize()
    logger = getAutomatonKitLogger()

    if credentials_file is not None:
        override_config_credentials(credentials_file)

    if landscape_file is not None:
        override_config_landscape(landscape_file)

    if runtime_file is not None:
        override_config_runtime(runtime_file)

    from akit.interop.landscaping.landscape import Landscape, startup_landscape
    from akit.interop.landscaping.landscapedevice import LandscapeDevice

    lscape: Landscape = startup_landscape(include_ssh=True, include_upnp=True)

    upnp_device_configs = lscape.get_upnp_device_configs()
    if len(upnp_device_configs):
        print("======================= UPNP DEVICES =======================")

        for dev in upnp_device_configs:
            skip_dev = True if "skip" in dev and dev["skip"] else False

            upnp_info = dev["upnp"]
            usn = upnp_info["USN"]
            modelName = upnp_info["modelName"]
            modelNumber = upnp_info["modelNumber"]

            status = "Down"
            lscape_dev: LandscapeDevice = lscape.lookup_device_by_keyid(usn)
            if lscape_dev is not None:
                status = lscape_dev.verify_status()

            dev_info_lines = [
                "    Model: {} - {}".format(modelName, modelNumber),
                "      USN: {}".format(usn), "     Skip: {}".format(skip_dev),
                "   Status: {}".format(status)
            ]
            dev_info = os.linesep.join(dev_info_lines)

            print(dev_info)
            print("")

    ssh_devices_configs = lscape.get_ssh_device_configs(exclude_upnp=True)
    if len(ssh_devices_configs):
        print("======================= SSH DEVICES =======================")

        for dev in ssh_devices_configs:
            skip_dev = True if "skip" in dev and dev["skip"] else False

            host = dev["host"]

            status = "Down"
            lscape_dev: LandscapeDevice = lscape.lookup_device_by_keyid(host)
            if lscape_dev is not None:
                status = lscape_dev.verify_status()

            dev_info_lines = [
                "    HOST: {}".format(host), "   Status: {}".format(status)
            ]
            dev_info = os.linesep.join(dev_info_lines)

            print(dev_info)
            print("")

    return
Ejemplo n.º 6
0
def command_akit_testing_run(root, includes, excludes, output, start, runid,
                             branch, build, flavor, credentials_file,
                             landscape_file, landscape_name, runtime_file,
                             runtime_name, topology_file, topology_name,
                             console_level, logfile_level, debugger,
                             breakpoints, time_travel, timeportals,
                             prerun_diagnostic, postrun_diagnostic):

    # pylint: disable=unused-import,import-outside-toplevel

    # We do the imports of the automation framework code inside the action functions because
    # we don't want to startup loggin and the processing of inputs and environment variables
    # until we have entered an action method.  Thats way we know how to setup the environment.

    # IMPORTANT: We need to load the context first because it will trigger the loading
    # of the default user configuration
    from akit.environment.context import Context
    from akit.environment.contextpaths import ContextPaths

    from akit.environment.variables import extend_path, JOB_TYPES, AKIT_VARIABLES

    from akit.environment.optionoverrides import (
        override_build_branch, override_build_flavor, override_build_name,
        override_config_credentials, override_config_landscape,
        override_config_landscape_name, override_config_runtime,
        override_config_runtime_name, override_config_topology,
        override_config_topology_name, override_loglevel_console,
        override_loglevel_file, override_output_directory, override_runid,
        override_starttime, override_testroot, override_debug_breakpoints,
        override_debug_debugger, override_timetravel, override_timeportals)

    ctx = Context()
    env = ctx.lookup("/environment")

    # We need to set the job type before we trigger activation.
    env["jobtype"] = JOB_TYPES.TESTRUN

    # We perform activation a little later in the testrunner.py file so we can
    # handle exceptions in the context of testrunner_main function
    import akit.activation.testrun
    from akit.xlogging.foundations import logging_initialize, getAutomatonKitLogger

    if branch is not None:
        override_build_branch(branch)

    if build is not None:
        override_build_name(build)

    if flavor is not None:
        override_build_flavor(flavor)

    if credentials_file is not None:
        override_config_credentials(credentials_file)

    if landscape_file is not None and landscape_name is not None:
        errmsg = "The '--landscape-file' and '--landscape-name' options should not be used together."
        raise click.BadOptionUsage("landscape-name", errmsg)

    if landscape_file is not None:
        override_config_landscape(landscape_file)

    if landscape_name is not None:
        override_config_landscape_name(landscape_name)

    if landscape_file is not None or landscape_name is not None:
        landscape_filename = AKIT_VARIABLES.AKIT_CONFIG_LANDSCAPE
        option_name = "landscape" if landscape_file is not None else "landscape-name"
        if not os.path.exists(landscape_filename):
            errmsg = "The specified landscape file does not exist. filename={}".format(
                landscape_filename)
            raise click.BadOptionUsage(option_name, errmsg)

    if runtime_file is not None and runtime_name is not None:
        errmsg = "The '--runtime-file' and '--runtime-name' options should not be used together."
        raise click.BadOptionUsage("runtime-name", errmsg)

    if runtime_file is not None:
        override_config_runtime(runtime_file)

    if runtime_name is not None:
        override_config_runtime_name(runtime_name)

    if runtime_file is not None or runtime_name is not None:
        runtime_filename = AKIT_VARIABLES.AKIT_CONFIG_RUNTIME
        option_name = "runtime" if runtime_file is not None else "runtime-name"
        if not os.path.exists(runtime_filename):
            errmsg = "The specified runtime file does not exist. filename={}".format(
                runtime_filename)
            raise click.BadOptionUsage(option_name, errmsg)

    if topology_file is not None and topology_name is not None:
        errmsg = "The '--topology-file' and '--topology-name' options should not be used together."
        raise click.BadOptionUsage("option_name", errmsg)

    if topology_file is not None:
        override_config_topology(topology_file)

    if topology_name is not None:
        override_config_topology_name(topology_name)

    if topology_file is not None or topology_name is not None:
        topology_filename = AKIT_VARIABLES.AKIT_CONFIG_TOPOLOGY
        option_name = "topology" if topology_file is not None else "topology-name"
        if not os.path.exists(topology_filename):
            errmsg = "The specified topology file does not exist. filename={}".format(
                topology_filename)
            raise click.BadOptionUsage(option_name, errmsg)

    if console_level is not None:
        override_loglevel_console(console_level)

    if logfile_level is not None:
        override_loglevel_file(logfile_level)

    if output is not None:
        override_output_directory(output)

    if start is not None:
        override_starttime(start)

    if runid is not None:
        override_runid(runid)

    # Process the commandline args here and then set the variables on the environment
    # as necessary.  We need to do this before we import activate.
    if breakpoints is not None:
        override_debug_breakpoints(breakpoints)

        # If a breakpoint was passed bug the debugger was not, use 'debugpy' for the
        # default debugger.
        if debugger is None:
            override_debug_debugger('debugpy')

    if debugger is not None:
        override_debug_debugger('debugpy')

    if time_travel is not None:
        override_timetravel(time_travel)

    if timeportals is not None:
        override_timeportals(timeportals)

    if prerun_diagnostic:
        ctx.insert("/environment/configuration/diagnostics/prerun-diagnostic",
                   {})

    if postrun_diagnostic:
        ctx.insert("/environment/configuration/diagnostics/postrun-diagnostic",
                   {})

    if root is None:
        if AKIT_VARIABLES.AKIT_TESTROOT is not None:
            root = AKIT_VARIABLES.AKIT_TESTROOT
        elif ctx.lookup(ContextPaths.TESTROOT) is not None:
            root = ctx.lookup(ContextPaths.TESTROOT)
        else:
            root = "."

    test_root = os.path.abspath(os.path.expandvars(os.path.expanduser(root)))
    if not os.path.isdir(test_root):
        errmsg = "The specified root folder does not exist. root=%s" % root
        if test_root != root:
            errmsg += " expanded=%s" % test_root
        raise click.BadParameter(errmsg)

    override_testroot(root)

    # Make sure we extend PATH to include the test root
    extend_path(test_root)

    # Initialize logging
    logging_initialize()
    logger = getAutomatonKitLogger()

    from akit.extensionpoints import AKitExtensionPoints
    akep = AKitExtensionPoints()

    # At this point in the code, we either lookup an existing test job or we create a test job
    # from the includes, excludes or test_module
    TestJobType = akep.get_testplus_default_job_type()
    result_code = 0
    with TestJobType(logger,
                     test_root,
                     includes=includes,
                     excludes=excludes,
                     branch=branch,
                     build=build,
                     flavor=flavor) as tjob:
        result_code = tjob.execute()

    sys.exit(result_code)

    return
Ejemplo n.º 7
0
def command_akit_testing_query(root, includes, excludes, debug):
    # pylint: disable=unused-import,import-outside-toplevel

    # We do the imports of the automation framework code inside the action functions because
    # we don't want to startup loggin and the processing of inputs and environment variables
    # until we have entered an action method.  Thats way we know how to setup the environment.

    # IMPORTANT: We need to load the context first because it will trigger the loading
    # of the default user configuration
    from akit.environment.context import Context
    from akit.environment.variables import extend_path, AKIT_VARIABLES

    ctx = Context()
    env = ctx.lookup("/environment")

    # Set the jobtype
    env["jobtype"] = "testrun"

    test_root = None
    if root is not None:
        AKIT_VARIABLES.AKIT_TESTROOT = root
    elif AKIT_VARIABLES.AKIT_TESTROOT is not None:
        root = AKIT_VARIABLES.AKIT_TESTROOT
    else:
        root = "."

    test_root = os.path.abspath(os.path.expandvars(os.path.expanduser(root)))
    if not os.path.isdir(test_root):
        errmsg = "The specified root folder does not exist. root=%s" % root
        if test_root != root:
            errmsg += " expanded=%s" % test_root
        raise click.BadParameter(errmsg)
    env["testroot"] = test_root

    # Make sure we extend PATH to include the test root
    extend_path(test_root)

    # We use console activation because all our input output is going through the terminal
    import akit.activation.console
    from akit.xlogging.foundations import logging_initialize, getAutomatonKitLogger

    # Initialize logging
    logging_initialize()
    logger = getAutomatonKitLogger()

    from akit.extensionpoints import AKitExtensionPoints
    akep = AKitExtensionPoints()

    # At this point in the code, we either lookup an existing test job or we create a test job
    # from the includes, excludes or test_module
    TestJobType = akep.get_testplus_default_job_type()
    result_code = 0
    with TestJobType(logger, test_root, includes=includes,
                     excludes=excludes) as tjob:
        query_results = tjob.query()

        test_names = [tn for tn in query_results.keys()]
        test_names.sort()
        print()
        print("Tests:")
        for tname in test_names:
            tref = query_results[tname]
            print("    " + tname)
            param_names = [pn for pn in tref.subscriptions.keys()]
            param_names.sort()
            for pname in param_names:
                pinfo = tref.subscriptions[pname]
                print("        {}: {}".format(pname, pinfo.describe_source()))

        print()

        if len(tjob.import_errors) > 0:
            print("IMPORT ERRORS:", file=sys.stderr)
            for ifilename in tjob.import_errors:
                imperr_msg = ifilename
                print("    " + imperr_msg, file=sys.stderr)
            print("", file=sys.stderr)

    return
Ejemplo n.º 8
0
        AKIT_VARIABLES.AKIT_ACTIVATION_PROFILE)
    raise AKitSemanticError(errmsg)

AKIT_VARIABLES.AKIT_ACTIVATION_PROFILE = ActivationProfile.Service

if "AKIT_SERVICE_NAME" not in os.environ:
    errmsg = "To use the AutomationKit to provide a service, you must " \
             "set the AKIT_SERVICE_NAME environment variable."
    raise AKitConfigurationError(errmsg)

service_name = os.environ["AKIT_SERVICE_NAME"]

AKIT_VARIABLES.AKIT_LOG_LEVEL_CONSOLE = "INFO"
AKIT_VARIABLES.AKIT_SERVICE_NAME = service_name
AKIT_VARIABLES.AKIT_JOBTYPE = "service"
AKIT_VARIABLES.AKIT_OUTPUT_DIRECTORY = "~/akit/services/{}".format(
    service_name)

# For console activation we don't want to log to the console and we want
# to point the logs to a different output folder
os.environ["AKIT_LOG_LEVEL_CONSOLE"] = AKIT_VARIABLES.AKIT_LOG_LEVEL_CONSOLE
os.environ["AKIT_JOBTYPE"] = AKIT_VARIABLES.AKIT_JOBTYPE
os.environ["AKIT_OUTPUT_DIRECTORY"] = AKIT_VARIABLES.AKIT_OUTPUT_DIRECTORY

import akit.activation.base  # pylint: disable=unused-import,wrong-import-position

from akit.xlogging.foundations import logging_initialize, LoggingDefaults  # pylint: disable=wrong-import-position

LoggingDefaults.DefaultFileLoggingHandler = RotatingFileHandler
logging_initialize()