Ejemplo n.º 1
0
 class Meta:
     label = "app-%s" % rando()[:12]
     config_files = []
     argv = []
     base_controller = None
     arguments = []
     exit_on_close = False
Ejemplo n.º 2
0
"""Tests for cement.core.output."""

import os
from tempfile import mkdtemp
from cement.core import exc, backend, output
from cement.utils import test
from cement.utils.misc import init_defaults, rando

APP = rando()[:12]


class TestOutputHandler(output.TemplateOutputHandler):
    class Meta:
        label = 'test_output_handler'

    def render(self, data, template):
        content = self.load_template(template)
        return content % data


TEST_TEMPLATE = "%(foo)s"


class OutputTestCase(test.CementCoreTestCase):
    def setUp(self):
        self.app = self.make_app()

    def test_load_template_from_file(self):
        tmpdir = mkdtemp()
        template = os.path.join(tmpdir, 'mytemplate.txt')
Ejemplo n.º 3
0
"""Tests for cement.utils.misc."""

from cement.utils import test, misc

APP = misc.rando()[:12]


class BackendTestCase(test.CementCoreTestCase):
    def test_defaults(self):
        defaults = misc.init_defaults("APPp", "section2", "section3")
        defaults["APPp"]["debug"] = True
        defaults["section2"]["foo"] = "bar"
        self.app = self.make_app("APPp", config_defaults=defaults)
        self.app.setup()
        self.eq(self.app.config.get("APPp", "debug"), True)
        self.ok(self.app.config.get_section_dict("section2"))

    def test_minimal_logger(self):
        log = misc.minimal_logger(__name__)
        log = misc.minimal_logger(__name__, debug=True)
        log.info("info test")
        log.warn("warn test")
        log.error("error test")
        log.fatal("fatal test")
        log.debug("debug test")

        log.info("info test with namespce", "test_namespace")

        log.info("info test with extra kwargs", extra=dict(foo="bar"))

        log.info("info test with extra kwargs", extra=dict(namespace="foo"))
Ejemplo n.º 4
0
"""Tests for cement.core.plugin."""

import os
import sys
import shutil
from tempfile import mkdtemp
from cement.core import exc, backend, plugin, handler
from cement.utils import test
from cement.utils.misc import init_defaults, rando

APP = rando()[:12]

CONF = """
[myplugin]
enable_plugin = true
foo = bar

"""

CONF2 = """
[myplugin]
enable_plugin = false
foo = bar
"""

CONF3 = """
[bogus_plugin]
foo = bar
"""

CONF4 = """
Ejemplo n.º 5
0
    def _setup_parsers(self):
        # this should only be run by the base controller
        from cement.utils.misc import rando

        _rando = rando()[:12]
        self._dispatch_option = '--dispatch-%s' % _rando
        self._controller_option = '--controller-namespace-%s' % _rando

        # parents are sub-parser namespaces (that we can add subparsers to)
        # where-as parsers are the actual root parser and sub-parsers to
        # add arguments to
        parents = self._sub_parser_parents
        parsers = self._sub_parsers
        parsers['base'] = self.app.args
        # parsers['base'] = ArgumentParser()
        # sub1 = parsers['base'].add_subparsers(title='sub-commands')
        # sub1.add_parser('johnny')
        # parsers['base'].parse_args()

        kwargs = self._get_subparser_options(self)
        sub = self.app.args.add_subparsers(**kwargs)
        parents['base'] = sub
        base_parser_options = self._get_parser_options(self)
        for key, val in base_parser_options.items():
            setattr(self.app.args, key, val)

        # handle base controller separately
        parsers['base'].add_argument(self._controller_option,
                                     action='store',
                                     default='base',
                                     nargs='?',
                                     help=SUPPRESS,
                                     dest='__controller_namespace__',
                                     )
        self._parser = parsers['base']
        self._parser.formatter_class = self._meta.argument_formatter

        # and if only base controller registered... go ahead and return
        if len(self.app.handler.list('controller')) <= 1:
            return    # pragma: nocover

        # note that the order of self._controllers was already organized by
        # stacking/embedding order in self._setup_controllers ... order is
        # important here otherwise argparse does wierd things
        for contr in self._controllers:
            label = contr._meta.label
            stacked_on = contr._meta.stacked_on
            stacked_type = contr._meta.stacked_type

            if stacked_type == 'nested':
                # if the controller is nested, we need to create a new parser
                # parent using the one that it is stacked on, as well as as a
                # new parser
                kwargs = self._get_parser_options(contr)
                parsers[label] = parents[stacked_on].add_parser(
                    _clean_label(label),
                    **kwargs
                )

                contr._parser = parsers[label]

                # we need to add subparsers to this parser so we can
                # attach commands and other nested controllers to it
                kwargs = self._get_subparser_options(contr)
                parents[label] = parsers[label].add_subparsers(**kwargs)

                # add an invisible controller option so we can figure out what
                # to call later in self._dispatch
                parsers[label].add_argument(self._controller_option,
                                            action='store',
                                            default=contr._meta.label,
                                            help=SUPPRESS,
                                            dest='__controller_namespace__',
                                            )
                parsers[label].formatter_class = contr._meta.argument_formatter

            elif stacked_type == 'embedded':
                # if it's embedded, then just set it to use the same as the
                # controller its stacked on
                parents[label] = parents[stacked_on]
                parsers[label] = parsers[stacked_on]
Ejemplo n.º 6
0
"""Tests for cement.ext.ext_smtp."""

import mock
import smtplib
from cement.utils import test
from cement.utils.misc import rando, init_defaults

APP = "app-%s" % rando()[:12]


class SMTPMailHandlerTestCase(test.CementTestCase):
    def setUp(self):
        super(SMTPMailHandlerTestCase, self).setUp()
        self.app = self.make_app(APP,
            extensions=['smtp'],
            mail_handler='smtp',
            argv=[],
            )

    def test_smtp_defaults(self):
        defaults = init_defaults(APP, 'mail.smtp')
        defaults['mail.smtp']['to'] = 'nobody@localhost'
        defaults['mail.smtp']['from_addr'] = 'nobody@localhost'
        defaults['mail.smtp']['cc'] = 'nobody@localhost'
        defaults['mail.smtp']['bcc'] = 'nobody@localhost'
        defaults['mail.smtp']['subject'] = 'Test Email To nobody@localhost'
        defaults['mail.smtp']['subject_prefix'] = 'PREFIX >'

        with mock.patch('smtplib.SMTP') as mock_smtp:
            self.app = self.make_app(APP,
                config_defaults=defaults,
Ejemplo n.º 7
0
"""Tests for cement.utils.misc."""

from cement.utils import test, misc

APP = misc.rando()[:12]

class BackendTestCase(test.CementCoreTestCase):
    def test_defaults(self):
        defaults = misc.init_defaults('APPp', 'section2', 'section3')
        defaults['APPp']['debug'] = True
        defaults['section2']['foo'] = 'bar'
        self.app = self.make_app('APPp', config_defaults=defaults)
        self.app.setup()
        self.eq(self.app.config.get('APPp', 'debug'), True)
        self.ok(self.app.config.get_section_dict('section2'))

    def test_minimal_logger(self):
        log = misc.minimal_logger(__name__)
        log = misc.minimal_logger(__name__, debug=True)
        log.info('info test')
        log.warn('warn test')
        log.error('error test')
        log.fatal('fatal test')
        log.debug('debug test')

        log.info('info test with namespce', 'test_namespace')

        log.info('info test with extra kwargs', extra=dict(foo='bar'))

        log.info('info test with extra kwargs', extra=dict(namespace='foo'))
Ejemplo n.º 8
0
 class Meta:
     label = "boss-test-%s" % rando()[:12]
     argv = []
     config_files = []
Ejemplo n.º 9
0
    def _setup_parsers(self):
        # this should only be run by the base controller
        from cement.utils.misc import rando

        _rando = rando()[:12]
        self._dispatch_option = '--dispatch-%s' % _rando
        self._controller_option = '--controller-namespace-%s' % _rando

        # parents are sub-parser namespaces (that we can add subparsers to)
        # where-as parsers are the actual root parser and sub-parsers to
        # add arguments to
        parents = self._sub_parser_parents
        parsers = self._sub_parsers
        parsers['base'] = self.app.args
        # parsers['base'] = ArgumentParser()
        # sub1 = parsers['base'].add_subparsers(title='sub-commands')
        # sub1.add_parser('johnny')
        # parsers['base'].parse_args()

        kwargs = self._get_subparser_options(self)
        sub = self.app.args.add_subparsers(**kwargs)
        parents['base'] = sub
        base_parser_options = self._get_parser_options(self)
        for key, val in base_parser_options.items():
            setattr(self.app.args, key, val)

        # handle base controller separately
        parsers['base'].add_argument(self._controller_option,
                                     action='store',
                                     default='base',
                                     nargs='?',
                                     help=SUPPRESS,
                                     dest='__controller_namespace__',
                                     )
        self._parser = parsers['base']

        # and if only base controller registered... go ahead and return
        if len(handler.list('controller')) <= 1:
            return    # pragma: nocover

        # note that the order of self._controllers was already organized by
        # stacking/embedding order in self._setup_controllers ... order is
        # important here otherwise argparse does wierd things
        for contr in self._controllers:
            label = contr._meta.label
            stacked_on = contr._meta.stacked_on
            stacked_type = contr._meta.stacked_type

            if stacked_type == 'nested':
                # if the controller is nested, we need to create a new parser
                # parent using the one that it is stacked on, as well as as a
                # new parser
                kwargs = self._get_parser_options(contr)
                parsers[label] = parents[stacked_on].add_parser(
                    _clean_label(label),
                    **kwargs
                )

                contr._parser = parsers[label]

                # we need to add subparsers to this parser so we can
                # attach commands and other nested controllers to it
                kwargs = self._get_subparser_options(contr)
                parents[label] = parsers[label].add_subparsers(**kwargs)

                # add an invisible controller option so we can figure out what
                # to call later in self._dispatch
                parsers[label].add_argument(self._controller_option,
                                            action='store',
                                            default=contr._meta.label,
                                            help=SUPPRESS,
                                            dest='__controller_namespace__',
                                            )

            elif stacked_type == 'embedded':
                # if it's embedded, then just set it to use the same as the
                # controller its stacked on
                parents[label] = parents[stacked_on]
                parsers[label] = parsers[stacked_on]
Ejemplo n.º 10
0
    def _setup_parsers(self):
        # this should only be run by the base controller
        from cement.utils.misc import rando

        _rando = rando()[:12]
        self._dispatch_option = f"--dispatch-{_rando}"
        self._controller_option = f"--controller-namespace-{_rando}"

        # parents are sub-parser namespaces (that we can add subparsers to)
        # where-as parsers are the actual root parser and sub-parsers to
        # add arguments to
        parents = self._sub_parser_parents
        parsers = self._sub_parsers
        parsers["base"] = self.app.args

        kwargs = self._get_subparser_options(self)

        # only create a subparser if there are commands or nested
        # controllers
        cmds = self._collect_commands()
        contrs = [
            x for x in self._controllers if x._meta.label != self._meta.label
            and x._meta.stacked_on == self._meta.label
        ]

        if len(cmds) > 0 or len(contrs) > 0:
            sub = self.app.args.add_subparsers(**kwargs)
            parents["base"] = sub

        base_parser_options = self._get_parser_options(self)
        for key, value in base_parser_options.items():
            setattr(self.app.args, key, value)

        # handle base controller separately
        parsers["base"].add_argument(
            self._controller_option,
            action="store",
            default="base",
            nargs="?",
            help=SUPPRESS,
            dest="__controller_namespace__",
        )
        self._parser = parsers["base"]

        # and if only base controller registered... go ahead and return
        if len(self.app.handler.list("controller")) <= 1:
            return  # pragma: nocover

        # note that the order of self._controllers was already organized by
        # stacking/embedding order in self._setup_controllers ... order is
        # important here otherwise argparse does wierd things
        for contr in self._controllers:
            label = contr._meta.label
            stacked_on = contr._meta.stacked_on
            stacked_type = contr._meta.stacked_type

            if stacked_type == "nested":
                # if the controller is nested, we need to create a new parser
                # parent using the one that it is stacked on, as well as as a
                # new parser
                kwargs = self._get_parser_options(contr)
                parsers[label] = parents[stacked_on].add_parser(
                    _clean_label(label), **kwargs)
                parsers[label]._setup(self.app)

                contr._parser = parsers[label]

                # we need to add subparsers to this parser so we can
                # attach commands and other nested controllers to it
                kwargs = self._get_subparser_options(contr)

                # only create a subparser if there are commands or nested
                # controllers
                cmds = contr._collect_commands()
                contrs = [
                    x for x in self._controllers
                    if x._meta.label != label and x._meta.stacked_on == label
                ]

                if len(cmds) > 0 or len(contrs) > 0:
                    parents[label] = parsers[label].add_subparsers(**kwargs)

                # add an invisible controller option so we can figure out what
                # to call later in self._dispatch
                parsers[label].add_argument(
                    self._controller_option,
                    action="store",
                    default=contr._meta.label,
                    help=SUPPRESS,
                    dest="__controller_namespace__",
                )

            elif stacked_type == "embedded":
                # if it's embedded, then just set it to use the same as the
                # controller its stacked on
                parents[label] = parents[stacked_on]
                parsers[label] = parsers[stacked_on]