Example #1
0
 def _setup_admin_options(self, values_source_list):
     base_namespace = Namespace()
     base_namespace.admin = admin = Namespace()
     admin.add_option(
         name='print_conf',
         default=None,
         doc='write current config to stdout (%s)' %
         ', '.join(value_sources.file_extension_dispatch.keys()))
     admin.add_option(
         name='dump_conf',
         default='',
         doc='a pathname to which to write the current config',
     )
     admin.add_option(name='migration',
                      default=False,
                      doc='allow common options to migrate to lower '
                      'levels')
     admin.add_option(name='strict',
                      default=False,
                      doc='mismatched options generate exceptions rather'
                      ' than just warnings')
     # only offer the config file admin options if they've been requested in
     # the values source list
     if ConfigFileFutureProxy in values_source_list:
         default_config_pathname = self._get_config_pathname()
         admin.add_option(
             name='conf',
             default=default_config_pathname,
             doc='the pathname of the config file '
             '(path/filename)',
         )
     return base_namespace
Example #2
0
 def __init__(self):
     """
     Construct a new SallyForth execution environment.
     """
     self.stack = Stack()
     self.stream = None
     core = Namespace('core')
     user = Namespace('user', [core])
     user.include_ns(core)
     self.namespaces = {}
     self.namespaces[core.name] = core
     self.namespaces[user.name] = user
     self.ns = core
     self.core = core
     self.set_constant('forth', self)
     self.set_constant('nil', None)
     self.set_constant('true', True)
     self.set_constant('false', False)
     self.set_constant('*source*', '<<input>>')
     self.set_constant('*last-word*', None)
     sally_dir = os.path.dirname(os.path.abspath(__file__))
     self.set_constant('*sallyforth-dir*', sally_dir)
     self.ns.import_from_module('basic_words')
     self.ns.import_from_module('namespace_words')
     self.ns.import_from_module('stack_words')
     self.ns.import_from_module('operator_words')
     self.ns.import_from_module('data_words')
     self.eval_file(f'{sally_dir}/0.sf')
     self.ns = user
Example #3
0
def given_knative_serving_is_running(context):
    """
    creates a KnativeServing object to install Knative Serving using the OpenShift Serverless Operator.
    """
    knative_namespace = Namespace("knative-serving")
    assert knative_namespace.create() is True, "Knative serving namespace not created"
    assert Namespace(context.namespace.name).switch_to() is True, "Unable to switch to the context namespace"
    knative_serving = KnativeServing(namespace=knative_namespace.name)
    if not knative_serving.is_present():
        print("knative serving is not present, create knative serving")
        assert knative_serving.create() is True, "Knative serving is not created"
        assert knative_serving.is_present() is True, "Knative serving is not present"
Example #4
0
 def __init__(self,
              base_dir=None,
              name='simplecli'):
     self.name = name
     self.logger = Logger(name=name, level=INFO)
     handler = StreamHandler(sys.stdout)
     handler.setLevel(DEBUG)
     handler.setFormatter(Formatter(
         magenta('[%(asctime)s]%(message)s')))
     self.logger.addHandler(handler)
     self._config_namespaces = Namespace()
     self.menu_cache = []
     self.completer_context = None
     self.base_dir = base_dir or os.path.expanduser('~/.simplecli')
     if os.path.exists(self.base_dir):
         if not os.path.isdir(self.base_dir):
             raise ValueError('base dir provided is not a dir:"{0}'
                              .format(self.base_dir))
     else:
         os.makedirs(self.base_dir)
     self.simplecli_config_file = os.path.join(self.base_dir,
                                               str(name) + '.config')
     self.simplecli_config = None
     self.init_simplecli_config()
     self._setup_stdio()
     self._load_plugin_menus()
Example #5
0
def given_namespace_is_used(context, namespace_name):
    namespace = Namespace(namespace_name)
    if not namespace.is_present():
        print("Namespace is not present, creating namespace: {}...".format(namespace_name))
        assert namespace.create(), f"Unable to create namespace '{namespace_name}'"
    print("Namespace {} is created!!!".format(namespace_name))
    context.namespace = namespace
Example #6
0
class GroundOverlay(KMLObject):
    defaults = Namespace(
        name='',
        drawOrder=1,
        href='',
        viewBoundScale=0.75,
        north=None,
        east=None,
        west=None,
        south=None,
        rotation=0,
        data=Data(),
        description='',
        colour='ffffffff',
    )

    def __init__(self, north, east, south, west, href, **kwargs):
        self.args = GroundOverlay.defaults
        self.args.update(north=north,
                         east=east,
                         south=south,
                         west=west,
                         href=href,
                         **kwargs)

    def add_data(self, data):
        self.args.data.append(data)

    def write(self):
        self.args.update(data=self.args.data.write())
        return Formats.GroundOverlay.format(**self.args.asdict())
Example #7
0
class ScreenOverlay(KMLObject):
    defaults = Namespace(
        name='',
        description='',
        href='',
        xOverlay=0,
        yOverlay=1,
        xunitsOverlay='fraction',
        yunitsOverlay='fraction',
        xScreen=0.01,
        yScreen=0.99,
        xunitsScreen='fraction',
        yunitsScreen='fraction',
        xsize=0.5,
        ysize=0.1,
        xunits='fraction',
        yunits='fraction',
        xRotation=0.5,
        yRotation=0.5,
        xunitsRotation='fraction',
        yunitsRotation='fraction',
        rotation=0,
    )

    def __init__(self, href, **kwargs):
        self.args = ScreenOverlay.defaults
        self.args.update(href=href, **kwargs)

    def write(self):
        return Formats.ScreenOverlay.format(**self.args.asdict())
Example #8
0
    def __init__(self, factory, fuzz_spec):
        assert factory, 'Factory not set.'
        self._factory = factory
        self._label = fuzz_spec['label']
        self._package = fuzz_spec['package']
        self._package_url = fuzz_spec['package_url']
        self._package_path = None
        if 'fuzzer' in fuzz_spec:
            self._executable = fuzz_spec['fuzzer']
            manifest = fuzz_spec['manifest']
            self._is_test = False
        elif 'fuzzer_test' in fuzz_spec:
            # Infer the associated fuzzer metadata if it is currently being built as a fuzzer test.
            self._executable = re.sub(r'_test$', '', fuzz_spec['fuzzer_test'])
            manifest = re.sub(r'_test\.cmx$', '.cmx',
                              fuzz_spec['test_manifest'])
            self._is_test = True

        self._executable_url = '{}#meta/{}'.format(self._package_url, manifest)
        self._ns = Namespace(self)
        self._corpus = Corpus(self, fuzz_spec.get('corpus'))
        self._dictionary = Dictionary(self)
        self._options = {'artifact_prefix': self.ns.data()}
        self._libfuzzer_opts = {}
        self._libfuzzer_inputs = []
        self._subprocess_args = []
        self._debug = False
        self._foreground = False
        self._output = None
        self._logbase = None
        self._last_known_pid = 0
        self._clusterfuzz_gcs_url = \
            'gs://corpus.internal.clusterfuzz.com/libFuzzer/fuchsia_{}-{}'.format(
                self._package, self._executable)
        self._realm_label = ''
Example #9
0
class Placemark(KMLObject):
    yellow_pushpin = IconStyle('yellow-pushpin')
    defaults = Namespace(
        name='Placemark',
        lon='',
        lat='',
        altitude=0,
        heading=0,
        tilt=0,
        range=0,
        styleUrl='',
        LookAt=None,
    )

    def __init__(self, name, lat, lon, style=yellow_pushpin, **kwargs):
        self.args = Placemark.defaults
        self.args.update(name=name, lat=lat, lon=lon, **kwargs)
        self.args.update(styleUrl=style.tag)

        if not self.args.LookAt:
            lookat = LookAt(self.args.lat, self.args.lon)
            self.args.LookAt = lookat

    def write(self):
        self.args.update
        self.args.update(LookAt=self.args.LookAt.write())
        placemark = Formats.placemark.format(**self.args.asdict())
        return placemark
Example #10
0
 def test_info_without_install(self):
     with pytest.raises(
             StateCheckError,
             message=
             'Executing info action without install should raise an error'):
         ns = Namespace(name='namespace', data=self.valid_data)
         ns.info()
Example #11
0
def given_namespace_is_used(context, namespace_name):
    namespace = Namespace(namespace_name)
    if not namespace.is_present():
        print("Namespace is not present, creating namespace: {}...".format(namespace_name))
        namespace.create() | should.be_truthy.desc("Namespace {} is created".format(namespace_name))
    print("Namespace {} is created!!!".format(namespace_name))
    context.namespace = namespace
Example #12
0
 def test_valid_data(self):
     ns = Namespace(name='namespace', data=self.valid_data)
     ns.api.services.get = MagicMock()
     ns.validate()
     data = self.valid_data.copy()
     data['zerodb'] = ''
     data['nsName'] = ''
     assert ns.data == data
Example #13
0
 def test_uninstall(self):
     ns = Namespace(name='namespace', data=self.valid_data)
     ns.data['nsName'] = 'nsName'
     ns.state.set('actions', 'install', 'ok')
     ns.api = MagicMock()
     ns.uninstall()
     ns._zerodb.schedule_action.assert_called_once_with(
         'namespace_delete', args={'name': 'nsName'})
Example #14
0
def namespace_maybe_create(context, namespace_name):
    namespace = Namespace(namespace_name)
    if not namespace.is_present():
        print("Namespace is not present, creating namespace: {}...".format(
            namespace_name))
        assert namespace.create(
        ), f"Unable to create namespace '{namespace_name}'"
    print("Namespace {} is created!!!".format(namespace_name))
    return namespace
class IndustrialAge(Era):
    __metaclass__ = Namespace(ColonialAge)

    class GameUnit:
        def move(self):
            return "IndustrialAge.GameUnit.move()"

    class RangedUnit:
        def aim(self):
            return "IndustrialAge.RangedUnit.aim()"
Example #16
0
    def test_private_url(self):
        ns = Namespace(name='namespace', data=self.valid_data)
        ns.data['nsName'] = 'nsName'
        ns.state.set('actions', 'install', 'ok')
        ns.api = MagicMock()
        ns._zerodb.schedule_action = MagicMock(return_value=task_mock('url'))

        assert ns.private_url() == 'url'
        ns._zerodb.schedule_action.assert_called_once_with(
            'namespace_private_url', args={'name': 'nsName'})
Example #17
0
 def test_connection_info(self):
     ns = Namespace(name='namespace', data=self.valid_data)
     ns.state.set('actions', 'install', 'ok')
     ns.state.set('status', 'running', 'ok')
     ns.api = MagicMock()
     result = {'ip': '127.0.0.1', 'port': 9900}
     task = task_mock(result)
     ns._zerodb.schedule_action = MagicMock(return_value=task)
     assert ns.connection_info() == result
     ns._zerodb.schedule_action.assert_called_once_with('connection_info')
Example #18
0
    def __init__(self, world_id, world_init_prop):
        self.name = Namespace(namespace='world/', name=world_id)
        self.__init_properties = world_init_prop

        self.launch = None
        self.__init_launch()

        self.__env = Environment(owner=self, properties=self.__init_properties)

        self.__env.launch()
Example #19
0
        class InnerClassList(RequiredConfig):
            """This nested class is a proxy list for the classes.  It collects
            all the config requirements for the listed classes and places them
            each into their own Namespace.
            """
            # we're dynamically creating a class here.  The following block of
            # code is actually adding class level attributes to this new class
            required_config = Namespace()  # 1st requirement for configman
            subordinate_namespace_names = []  # to help the programmer know
            # what Namespaces we added
            namespace_template = template_for_namespace  # save the template
            # for future reference
            class_option_name = name_of_class_option  # save the class's option
            # name for the future
            # for each class in the class list
            for namespace_index, a_class in enumerate(class_list):
                # figure out the Namespace name
                namespace_name = template_for_namespace % namespace_index
                subordinate_namespace_names.append(namespace_name)
                # create the new Namespace
                required_config[namespace_name] = Namespace()
                # add the option for the class itself
                required_config[namespace_name].add_option(
                    name_of_class_option,
                    #doc=a_class.__doc__  # not helpful if too verbose
                    default=a_class,
                    from_string_converter=class_converter)
                if instantiate_classes:
                    # add an aggregator to instantiate the class
                    required_config[namespace_name].add_aggregation(
                        "%s_instance" % name_of_class_option,
                        lambda c, lc, a: lc[name_of_class_option](lc))

            @classmethod
            def to_str(cls):
                """this method takes this inner class object and turns it back
                into the original string of classnames.  This is used
                primarily as for the output of the 'help' option"""
                return ', '.join(
                    py_obj_to_str(v[name_of_class_option].value)
                    for v in cls.get_required_config().values()
                    if isinstance(v, Namespace))
Example #20
0
    def test_no_node_installed(self):
        with pytest.raises(
                RuntimeError,
                message=
                'template should fail to install if no service node is installed'
        ):
            ns = Namespace(name='namespace', data=self.valid_data)
            ns.api.services.get = MagicMock(side_effect=ServiceNotFoundError)
            ns.validate()

        with pytest.raises(
                RuntimeError,
                message=
                'template should fail to install if no service node is installed'
        ):
            ns = Namespace(name='namespace', data=self.valid_data)
            node = MagicMock()
            node.state.check = MagicMock(side_effect=StateCheckError)
            ns.api.services.get = MagicMock(return_value=node)
            ns.validate()
Example #21
0
    def test_info(self):
        ns = Namespace(name='namespace', data=self.valid_data)
        ns.data['nsName'] = 'nsName'
        ns.state.set('actions', 'install', 'ok')
        ns.api = MagicMock()
        task = task_mock('info')
        ns._zerodb.schedule_action = MagicMock(return_value=task)

        assert ns.info() == 'info'
        ns._zerodb.schedule_action.assert_called_once_with(
            'namespace_info', args={'name': ns.data['nsName']})
Example #22
0
 def test_invalid_data(self):
     with pytest.raises(
             ValueError,
             message=
             'template should fail to instantiate if data dict is missing the size'
     ):
         data = self.valid_data.copy()
         data.pop('size')
         ns = Namespace(name='namespace', data=data)
         ns.api.services.get = MagicMock()
         ns.validate()
Example #23
0
 def __call__(self, *arg_vals):
     num_args = len(arg_vals)
     if num_args == self.arity:
         obj_dict = dict(zip(self.args, arg_vals))
         local_scope = Namespace(parent=self.scope, obj_dict=obj_dict)
         for statement in self.statements:
             statement.exec(local_scope)
     else:
         raise TypeError(
             "attempted to pass {0} arguments to function {1} of arity {2}".
             format(num_args, self.name, self.arity))
Example #24
0
def given_knative_serving_is_running(context):
    """
    creates a KnativeServing object to install Knative Serving using the OpenShift Serverless Operator.
    """
    knative_namespace = Namespace("knative-serving")
    if not knative_namespace.is_present():
        assert knative_namespace.create() is True, "Failed to create namespace for Knative Serving"
    knative_serving = KnativeServing(namespace=knative_namespace.name)
    if not knative_serving.is_present():
        print("knative serving is not present, create knative serving")
        assert knative_serving.create() is True, "Failed to create Knative Serving"
        assert knative_serving.is_present() is True, "Knative Serving is not present"
Example #25
0
 def add_namespace(self, name):
     '''
     Adds a blank configuration namespace using 'name' to the
     local _config_namespaces list.
     Raises ValueError if the name already exists
     Returns the new namespace object
     '''
     if getattr(self._config_namespaces, name, None):
         raise ValueError('Config Namespace already exists for:"{0}"'
                          .format(name))
     newnamespace = Namespace()
     setattr(self._config_namespaces, name, newnamespace)
     return newnamespace
Example #26
0
class PolyStyle(KMLObject):
    defaults = Namespace(fillcolour='ffa9a9a9',
                         linecolour='ffa9a9a9',
                         linewidth=1,
                         style='')

    def __init__(self, id, **kwargs):
        self.args = PolyStyle.defaults
        self.args.update(style=id, **kwargs)
        self.tag = Formats.StyleUrl.format(url=id)

    def write(self):
        return Formats.PolyStyle.format(**self.args.asdict())
Example #27
0
class Polygon(KMLObject):
    defaults = Namespace(
        name='',
        description='',
        styleUrl='',
        altitudeMode='relativeToGround',
        tessellate='1',
        outerBoundary='',
        innerBoundary='',
        extrude=0,
        data='',
        LookAt=None,
    )

    def __init__(self,
                 outerBoundary,
                 innerBoundary=None,
                 style=None,
                 **kwargs):
        outerBoundary = _OuterBoundary(outerBoundary)

        self.args = Polygon.defaults.copy()
        self.args.update(**kwargs)
        self.args.update(outerBoundary=outerBoundary.write())
        self.data = Data()

        if style:
            self.style = style
            self.args.update(styleUrl=style.tag)

        if innerBoundary:
            innerBoundary = _InnerBoundary(innerBoundary)
            self.args.update(innerBoundary=innerBoundary.write())

    def add_data(self, data):
        if hasattr(data, '__iter__'):
            for dta in data:
                self.data.add_data_field(dta)
        else:
            self.data.add_data_field(data)

    def write(self):
        print "Writing polygon", self.args.name
        lookat = self.args.LookAt
        if lookat:
            lookat = lookat.write()
        else:
            lookat = ''
        self.args.update(LookAt=lookat)
        self.args.update(data=self.data.write())
        return Formats.Polygon.format(**self.args.asdict())
Example #28
0
 def _start_run(self, output, parent, errors):
     if not errors:
         errors = SuiteRunErrors(self._run_mode_exit_on_failure,
                                 self._run_mode_skip_teardowns_on_exit)
     self.run_errors = errors
     self.run_errors.start_suite()
     self.status = 'RUNNING'
     self.starttime = utils.get_timestamp()
     parent_vars = parent.context.get_current_vars() if parent else None
     self.context = ExecutionContext(Namespace(self, parent_vars), output,
                                     self._run_mode_dry_run)
     self._set_variable_dependent_metadata(self.context)
     output.start_suite(self)
     return self.context
class MedievalAge(Era):
    __metaclass__ = Namespace()

    class GameUnit(object):
        def move(self):
            return "Medieval.GameUnit.move()"

    class CombatUnit(GameUnit):
        def fight(self):
            return "Medieval.CombatUnit.fight()"

    class RangedUnit(CombatUnit):
        def aim(self):
            return "Medieval.RangedUnit.aim()"
Example #30
0
class LineStyle(KMLObject):
    defaults = Namespace(
        colour='ffffffff',
        id='StyleID',
        width=2,
    )

    def __init__(self, **kwargs):
        self.args = LineStyle.defaults
        self.args.update(**kwargs)
        self.tag = Formats.StyleUrl.format(url=self.args.id)

    def write(self):
        return Formats.LineStyle.format(**self.args.asdict())