Exemplo n.º 1
0
    def test_run(self):
        """
        Test the `ipalib.frontend.Command.run` method.
        """
        class my_cmd(self.cls):
            def execute(self, *args, **kw):
                return ('execute', args, kw)

            def forward(self, *args, **kw):
                return ('forward', args, kw)

        args = ('Hello,', 'world,')
        kw = dict(how_are='you', on_this='fine day?', version=API_VERSION)

        # Test in server context:
        api, _home = create_test_api(in_server=True)
        api.finalize()
        o = my_cmd(api)
        if six.PY2:
            assert o.run.__func__ is self.cls.run.__func__
        else:
            assert o.run.__func__ is self.cls.run
        out = o.run(*args, **kw)
        assert ('execute', args, kw) == out

        # Test in non-server context
        api, _home = create_test_api(in_server=False)
        api.finalize()
        o = my_cmd(api)
        if six.PY2:
            assert o.run.__func__ is self.cls.run.__func__
        else:
            assert o.run.__func__ is self.cls.run
        assert ('forward', args, kw) == o.run(*args, **kw)
Exemplo n.º 2
0
    def test_run(self):
        """
        Test the `ipalib.frontend.Command.run` method.
        """
        class my_cmd(self.cls):
            def execute(self, *args, **kw):
                return ('execute', args, kw)

            def forward(self, *args, **kw):
                return ('forward', args, kw)

        args = ('Hello,', 'world,')
        kw = dict(how_are='you', on_this='fine day?', version=API_VERSION)

        # Test in server context:
        (api, home) = create_test_api(in_server=True)
        api.finalize()
        o = my_cmd(api)
        assert o.run.__func__ is self.cls.run.__func__
        out = o.run(*args, **kw)
        assert ('execute', args, kw) == out

        # Test in non-server context
        (api, home) = create_test_api(in_server=False)
        api.finalize()
        o = my_cmd(api)
        assert o.run.__func__ is self.cls.run.__func__
        assert ('forward', args, kw) == o.run(*args, **kw)
Exemplo n.º 3
0
    def test_run(self):
        """
        Test the `ipalib.frontend.LocalOrRemote.run` method.
        """
        class example(self.cls):
            takes_args = 'key?'

            def forward(self, *args, **options):
                return dict(result=('forward', args, options))

            def execute(self, *args, **options):
                return dict(result=('execute', args, options))

        # Test when in_server=False:
        (api, home) = create_test_api(in_server=False)
        api.add_plugin(example)
        api.finalize()
        cmd = api.Command.example
        assert cmd(version=u'2.47') == dict(
            result=('execute', (None,), dict(version=u'2.47', server=False))
        )
        assert cmd(u'var', version=u'2.47') == dict(
            result=('execute', (u'var',), dict(version=u'2.47', server=False))
        )
        assert cmd(server=True, version=u'2.47') == dict(
            result=('forward', (None,), dict(version=u'2.47', server=True))
        )
        assert cmd(u'var', server=True, version=u'2.47') == dict(
            result=('forward', (u'var',), dict(version=u'2.47', server=True))
        )

        # Test when in_server=True (should always call execute):
        (api, home) = create_test_api(in_server=True)
        api.add_plugin(example)
        api.finalize()
        cmd = api.Command.example
        assert cmd(version=u'2.47') == dict(
            result=('execute', (None,), dict(version=u'2.47', server=False))
        )
        assert cmd(u'var', version=u'2.47') == dict(
            result=('execute', (u'var',), dict(version=u'2.47', server=False))
        )
        assert cmd(server=True, version=u'2.47') == dict(
            result=('execute', (None,), dict(version=u'2.47', server=True))
        )
        assert cmd(u'var', server=True, version=u'2.47') == dict(
            result=('execute', (u'var',), dict(version=u'2.47', server=True))
        )
Exemplo n.º 4
0
    def test_default_from_chaining(self):
        """
        Test chaining of parameters through default_from.
        """
        class my_cmd(self.cls):
            takes_options = (
                Str('option0'),
                Str('option1', default_from=lambda option0: option0),
                Str('option2', default_from=lambda option1: option1),
            )

            def run(self, *args, **options):
                return dict(result=options)

        kw = dict(option0=u'some value')

        (api, home) = create_test_api()
        api.finalize()
        o = my_cmd()
        o.set_api(api)
        o.finalize()
        e = o(**kw)  # pylint: disable=not-callable
        assert type(e) is dict
        assert 'result' in e
        assert 'option2' in e['result']
        assert e['result']['option2'] == u'some value'
Exemplo n.º 5
0
    def test_args_options_2_entry(self):
        """
        Test `ipalib.frontend.Command.args_options_2_entry` method.
        """
        class my_cmd(self.cls):
            takes_args = (
                parameters.Str('one', attribute=True),
                parameters.Str('two', attribute=False),
            )
            takes_options = (
                parameters.Str('three', attribute=True, multivalue=True),
                parameters.Str('four', attribute=True, multivalue=False),
            )

            def run(self, *args, **kw):
                return self.args_options_2_entry(*args, **kw)

        args = ('one', 'two')
        kw = dict(three=('three1', 'three2'), four='four')

        api, _home = create_test_api()
        api.finalize()
        o = my_cmd(api)
        o.finalize()
        e = o.run(*args, **kw)
        assert type(e) is dict
        assert 'one' in e
        assert 'two' not in e
        assert 'three' in e
        assert 'four' in e
        assert e['one'] == 'one'
        assert e['three'] == ['three1', 'three2']
        assert e['four'] == 'four'
Exemplo n.º 6
0
    def test_default_from_chaining(self):
        """
        Test chaining of parameters through default_from.
        """
        class my_cmd(self.cls):
            takes_options = (
                Str('option0'),
                Str('option1', default_from=lambda option0: option0),
                Str('option2', default_from=lambda option1: option1),
            )

            def run(self, *args, **options):
                return dict(result=options)

        kw = dict(option0=u'some value')

        (api, home) = create_test_api()
        api.finalize()
        o = my_cmd(api)
        o.finalize()
        e = o(**kw)  # pylint: disable=not-callable
        assert type(e) is dict
        assert 'result' in e
        assert 'option2' in e['result']
        assert e['result']['option2'] == u'some value'
Exemplo n.º 7
0
    def test_args_options_2_entry(self):
        """
        Test `ipalib.frontend.Command.args_options_2_entry` method.
        """
        class my_cmd(self.cls):
            takes_args = (
                parameters.Str('one', attribute=True),
                parameters.Str('two', attribute=False),
            )
            takes_options = (
                parameters.Str('three', attribute=True, multivalue=True),
                parameters.Str('four', attribute=True, multivalue=False),
            )

            def run(self, *args, **kw):
                return self.args_options_2_entry(*args, **kw)

        args = ('one', 'two')
        kw = dict(three=('three1', 'three2'), four='four')

        (api, home) = create_test_api()
        api.finalize()
        o = my_cmd(api)
        o.finalize()
        e = o.run(*args, **kw)
        assert type(e) is dict
        assert 'one' in e
        assert 'two' not in e
        assert 'three' in e
        assert 'four' in e
        assert e['one'] == 'one'
        assert e['three'] == ['three1', 'three2']
        assert e['four'] == 'four'
Exemplo n.º 8
0
    def test_messages(self):
        """
        Test correct handling of messages
        """
        class TestMessage(messages.PublicMessage):
            type = 'info'
            format = 'This is a message.'
            errno = 1234

        class my_cmd(self.cls):
            def execute(self, *args, **kw):
                result = {'name': 'execute'}
                messages.add_message(kw['version'], result, TestMessage())
                return result

            def forward(self, *args, **kw):
                result = {'name': 'forward'}
                messages.add_message(kw['version'], result, TestMessage())
                return result

        args = ('Hello,', 'world,')
        kw = dict(how_are='you', on_this='fine day?', version=API_VERSION)

        expected = [TestMessage().to_dict()]

        # Test in server context:
        api, _home = create_test_api(in_server=True)
        api.finalize()
        o = my_cmd(api)
        if six.PY2:
            assert o.run.__func__ is self.cls.run.__func__
        else:
            assert o.run.__func__ is self.cls.run
        assert {'name': 'execute', 'messages': expected} == o.run(*args, **kw)

        # Test in non-server context
        api, _home = create_test_api(in_server=False)
        api.finalize()
        o = my_cmd(api)
        if six.PY2:
            assert o.run.__func__ is self.cls.run.__func__
        else:
            assert o.run.__func__ is self.cls.run
        assert {'name': 'forward', 'messages': expected} == o.run(*args, **kw)
Exemplo n.º 9
0
    def test_messages(self):
        """
        Test correct handling of messages
        """
        class TestMessage(messages.PublicMessage):
            type = 'info'
            format = 'This is a message.'
            errno = 1234

        class my_cmd(self.cls):
            def execute(self, *args, **kw):
                result = {'name': 'execute'}
                messages.add_message(kw['version'], result, TestMessage())
                return result

            def forward(self, *args, **kw):
                result = {'name': 'forward'}
                messages.add_message(kw['version'], result, TestMessage())
                return result

        args = ('Hello,', 'world,')
        kw = dict(how_are='you', on_this='fine day?', version=API_VERSION)

        expected = [TestMessage().to_dict()]

        # Test in server context:
        (api, home) = create_test_api(in_server=True)
        api.finalize()
        o = my_cmd(api)
        if six.PY2:
            assert o.run.__func__ is self.cls.run.__func__
        else:
            assert o.run.__func__ is self.cls.run
        assert {'name': 'execute', 'messages': expected} == o.run(*args, **kw)

        # Test in non-server context
        (api, home) = create_test_api(in_server=False)
        api.finalize()
        o = my_cmd(api)
        if six.PY2:
            assert o.run.__func__ is self.cls.run.__func__
        else:
            assert o.run.__func__ is self.cls.run
        assert {'name': 'forward', 'messages': expected} == o.run(*args, **kw)
Exemplo n.º 10
0
    def test_run(self):
        """
        Test the `ipalib.frontend.LocalOrRemote.run` method.
        """
        class example(self.cls):
            takes_args = 'key?'

            def forward(self, *args, **options):
                return dict(result=('forward', args, options))

            def execute(self, *args, **options):
                return dict(result=('execute', args, options))

        # Test when in_server=False:
        api, _home = create_test_api(in_server=False)
        api.add_plugin(example)
        api.finalize()
        cmd = api.Command.example
        assert cmd(version=u'2.47') == dict(result=('execute', (),
                                                    dict(version=u'2.47')))
        assert cmd(u'var',
                   version=u'2.47') == dict(result=('execute', (u'var', ),
                                                    dict(version=u'2.47')))
        assert cmd(server=True, version=u'2.47') == dict(
            result=('forward', (), dict(version=u'2.47', server=True)))
        assert cmd(u'var', server=True, version=u'2.47') == dict(
            result=('forward', (u'var', ), dict(version=u'2.47', server=True)))

        # Test when in_server=True (should always call execute):
        api, _home = create_test_api(in_server=True)
        api.add_plugin(example)
        api.finalize()
        cmd = api.Command.example
        assert cmd(version=u'2.47') == dict(
            result=('execute', (), dict(version=u'2.47', server=False)))
        assert cmd(u'var', version=u'2.47') == dict(
            result=('execute', (u'var', ),
                    dict(version=u'2.47', server=False)))
        assert cmd(server=True, version=u'2.47') == dict(
            result=('execute', (), dict(version=u'2.47', server=True)))
        assert cmd(u'var', server=True, version=u'2.47') == dict(
            result=('execute', (u'var', ), dict(version=u'2.47', server=True)))
Exemplo n.º 11
0
 def test_load_plugins(self):
     """
     Test the `ipalib.plugable.API.load_plugins` method.
     """
     (o, home) = create_test_api()
     assert o.isdone('bootstrap') is False
     assert o.isdone('load_plugins') is False
     o.load_plugins()
     assert o.isdone('bootstrap') is True
     assert o.isdone('load_plugins') is True
     e = raises(StandardError, o.load_plugins)
     assert str(e) == 'API.load_plugins() already called'
Exemplo n.º 12
0
 def test_load_plugins(self):
     """
     Test the `ipalib.plugable.API.load_plugins` method.
     """
     (o, home) = create_test_api()
     assert o.isdone('bootstrap') is False
     assert o.isdone('load_plugins') is False
     o.load_plugins()
     assert o.isdone('bootstrap') is True
     assert o.isdone('load_plugins') is True
     e = raises(Exception, o.load_plugins)
     assert str(e) == 'API.load_plugins() already called'
Exemplo n.º 13
0
 def test_load_plugins(self):
     """
     Test the `ipalib.plugable.API.load_plugins` method.
     """
     (o, home) = create_test_api()
     assert o.isdone("bootstrap") is False
     assert o.isdone("load_plugins") is False
     o.load_plugins()
     assert o.isdone("bootstrap") is True
     assert o.isdone("load_plugins") is True
     e = raises(StandardError, o.load_plugins)
     assert str(e) == "API.load_plugins() already called"
Exemplo n.º 14
0
    def test_primary_key(self):
        """
        Test the `ipalib.frontend.Object.primary_key` attribute.
        """
        (api, home) = create_test_api()
        api.finalize()

        # Test with no primary keys:
        class example1(self.cls):
            takes_params = (
                'one',
                'two',
            )

        o = example1()
        o.set_api(api)
        assert o.primary_key is None

        # Test with 1 primary key:
        class example2(self.cls):
            takes_params = (
                'one',
                'two',
                parameters.Str('three', primary_key=True),
                'four',
            )

        o = example2()
        o.set_api(api)
        pk = o.primary_key
        assert type(pk) is parameters.Str
        assert pk.name == 'three'
        assert pk.primary_key is True
        assert o.params[2] is o.primary_key
        assert isinstance(o.params_minus_pk, plugable.NameSpace)
        assert list(o.params_minus_pk) == ['one', 'two', 'four']

        # Test with multiple primary_key:
        class example3(self.cls):
            takes_params = (
                parameters.Str('one', primary_key=True),
                parameters.Str('two', primary_key=True),
                'three',
                parameters.Str('four', primary_key=True),
            )

        o = example3()
        o.set_api(api)
        e = raises(ValueError, o.finalize)
        assert str(e) == \
            'example3 (Object) has multiple primary keys: one, two, four'
Exemplo n.º 15
0
 def test_bootstrap(self):
     """
     Test the `ipalib.plugable.API.bootstrap` method.
     """
     (o, home) = create_test_api()
     assert o.env._isdone('_bootstrap') is False
     assert o.env._isdone('_finalize_core') is False
     assert o.isdone('bootstrap') is False
     o.bootstrap(my_test_override='Hello, world!')
     assert o.isdone('bootstrap') is True
     assert o.env._isdone('_bootstrap') is True
     assert o.env._isdone('_finalize_core') is True
     assert o.env.my_test_override == 'Hello, world!'
     e = raises(StandardError, o.bootstrap)
     assert str(e) == 'API.bootstrap() already called'
Exemplo n.º 16
0
 def test_bootstrap(self):
     """
     Test the `ipalib.plugable.API.bootstrap` method.
     """
     (o, home) = create_test_api()
     assert o.env._isdone("_bootstrap") is False
     assert o.env._isdone("_finalize_core") is False
     assert o.isdone("bootstrap") is False
     o.bootstrap(my_test_override="Hello, world!")
     assert o.isdone("bootstrap") is True
     assert o.env._isdone("_bootstrap") is True
     assert o.env._isdone("_finalize_core") is True
     assert o.env.my_test_override == "Hello, world!"
     e = raises(StandardError, o.bootstrap)
     assert str(e) == "API.bootstrap() already called"
Exemplo n.º 17
0
 def test_bootstrap(self):
     """
     Test the `ipalib.plugable.API.bootstrap` method.
     """
     (o, home) = create_test_api()
     assert o.env._isdone('_bootstrap') is False
     assert o.env._isdone('_finalize_core') is False
     assert o.isdone('bootstrap') is False
     o.bootstrap(my_test_override='Hello, world!')
     assert o.isdone('bootstrap') is True
     assert o.env._isdone('_bootstrap') is True
     assert o.env._isdone('_finalize_core') is True
     assert o.env.my_test_override == 'Hello, world!'
     e = raises(Exception, o.bootstrap)
     assert str(e) == 'API.bootstrap() already called'
Exemplo n.º 18
0
 def test_backend(self):
     """
     Test the `ipalib.frontend.Object.backend` attribute.
     """
     (api, home) = create_test_api()
     class ldap(backend.Backend):
         whatever = 'It worked!'
     api.add_plugin(ldap)
     class user(frontend.Object):
         backend_name = 'ldap'
     api.add_plugin(user)
     api.finalize()
     b = api.Object.user.backend
     assert isinstance(b, ldap)
     assert b.whatever == 'It worked!'
Exemplo n.º 19
0
    def test_primary_key(self):
        """
        Test the `ipalib.frontend.Object.primary_key` attribute.
        """
        (api, home) = create_test_api()
        api.finalize()

        # Test with no primary keys:
        class example1(self.cls):
            takes_params = (
                'one',
                'two',
            )
        o = example1()
        o.set_api(api)
        assert o.primary_key is None

        # Test with 1 primary key:
        class example2(self.cls):
            takes_params = (
                'one',
                'two',
                parameters.Str('three', primary_key=True),
                'four',
            )
        o = example2()
        o.set_api(api)
        pk = o.primary_key
        assert type(pk) is parameters.Str
        assert pk.name == 'three'
        assert pk.primary_key is True
        assert o.params[2] is o.primary_key
        assert isinstance(o.params_minus_pk, plugable.NameSpace)
        assert list(o.params_minus_pk) == ['one', 'two', 'four']

        # Test with multiple primary_key:
        class example3(self.cls):
            takes_params = (
                parameters.Str('one', primary_key=True),
                parameters.Str('two', primary_key=True),
                'three',
                parameters.Str('four', primary_key=True),
            )
        o = example3()
        o.set_api(api)
        e = raises(ValueError, o.finalize)
        assert str(e) == \
            'example3 (Object) has multiple primary keys: one, two, four'
Exemplo n.º 20
0
 def test_params_minus(self):
     """
     Test the `ipalib.frontend.Object.params_minus` method.
     """
     class example(self.cls):
         takes_params = ('one', 'two', 'three', 'four')
     (api, home) = create_test_api()
     api.finalize()
     o = example(api)
     p = o.params
     assert tuple(o.params_minus()) == tuple(p())
     assert tuple(o.params_minus([])) == tuple(p())
     assert tuple(o.params_minus('two', 'three')) == (p.one, p.four)
     assert tuple(o.params_minus(['two', 'three'])) == (p.one, p.four)
     assert tuple(o.params_minus(p.two, p.three)) == (p.one, p.four)
     assert tuple(o.params_minus([p.two, p.three])) == (p.one, p.four)
     ns = NameSpace([p.two, p.three])
     assert tuple(o.params_minus(ns)) == (p.one, p.four)
Exemplo n.º 21
0
    def test_backend(self):
        """
        Test the `ipalib.frontend.Object.backend` attribute.
        """
        api, _home = create_test_api()

        class ldap(backend.Backend):
            whatever = 'It worked!'

        api.add_plugin(ldap)

        class user(frontend.Object):
            backend_name = 'ldap'

        api.add_plugin(user)
        api.finalize()
        b = api.Object.user.backend
        assert isinstance(b, ldap)
        assert b.whatever == 'It worked!'
Exemplo n.º 22
0
 def get_api(self, args=tuple(), options=tuple()):
     """
     Return a finalized `ipalib.plugable.API` instance.
     """
     (api, home) = create_test_api()
     class user(frontend.Object):
         takes_params = (
             'givenname',
             'sn',
             frontend.Param('uid', primary_key=True),
             'initials',
         )
     class user_verb(self.cls):
         takes_args = args
         takes_options = options
     api.add_plugin(user)
     api.add_plugin(user_verb)
     api.finalize()
     return api
Exemplo n.º 23
0
    def test_params_minus(self):
        """
        Test the `ipalib.frontend.Object.params_minus` method.
        """
        class example(self.cls):
            takes_params = ('one', 'two', 'three', 'four')

        api, _home = create_test_api()
        api.finalize()
        o = example(api)
        p = o.params
        assert tuple(o.params_minus()) == tuple(p())
        assert tuple(o.params_minus([])) == tuple(p())
        assert tuple(o.params_minus('two', 'three')) == (p.one, p.four)
        assert tuple(o.params_minus(['two', 'three'])) == (p.one, p.four)
        assert tuple(o.params_minus(p.two, p.three)) == (p.one, p.four)
        assert tuple(o.params_minus([p.two, p.three])) == (p.one, p.four)
        ns = NameSpace([p.two, p.three])
        assert tuple(o.params_minus(ns)) == (p.one, p.four)
Exemplo n.º 24
0
    def get_api(self, args=tuple(), options=tuple()):
        """
        Return a finalized `ipalib.plugable.API` instance.
        """
        api, _home = create_test_api()

        class user(frontend.Object):
            takes_params = (
                'givenname',
                'sn',
                frontend.Param('uid', primary_key=True),
                'initials',
            )

        class user_verb(self.cls):
            takes_args = args
            takes_options = options

        api.add_plugin(user)
        api.add_plugin(user_verb)
        api.finalize()
        return api
Exemplo n.º 25
0
    def test_execute(self):
        """
        Test the `ipalib.backend.Executioner.execute` method.
        """
        (api, home) = create_test_api(in_server=True)

        class echo(Command):
            takes_args = ("arg1", "arg2+")
            takes_options = ("option1?", "option2?")

            def execute(self, *args, **options):
                assert type(args[1]) is tuple
                return dict(result=args + (options,))

        api.add_plugin(echo)

        class good(Command):
            def execute(self, **options):
                raise errors.ValidationError(name="nurse", error=u"Not naughty!")

        api.add_plugin(good)

        class bad(Command):
            def execute(self, **options):
                raise ValueError("This is private.")

        api.add_plugin(bad)

        class with_name(Command):
            """
            Test that a kwarg named 'name' can be used.
            """

            takes_options = "name"

            def execute(self, **options):
                return dict(result=options["name"].upper())

        api.add_plugin(with_name)

        api.finalize()
        o = self.cls(api)
        o.finalize()

        # Test that CommandError is raised:
        conn = Connection("The connection.", Disconnect("someconn"))
        context.someconn = conn
        print(str(list(context.__dict__)))
        e = raises(errors.CommandError, o.execute, "nope")
        assert e.name == "nope"
        assert conn.disconnect.called is True  # Make sure destroy_context() was called
        print(str(list(context.__dict__)))
        assert list(context.__dict__) == []

        # Test with echo command:
        arg1 = unicode_str
        arg2 = (u"Hello", unicode_str, u"world!")
        args = (arg1,) + arg2
        options = dict(option1=u"How are you?", option2=unicode_str, version=API_VERSION)

        conn = Connection("The connection.", Disconnect("someconn"))
        context.someconn = conn
        print(o.execute("echo", arg1, arg2, **options))
        print(dict(result=(arg1, arg2, options)))
        assert o.execute("echo", arg1, arg2, **options) == dict(result=(arg1, arg2, options))
        assert conn.disconnect.called is True  # Make sure destroy_context() was called
        assert list(context.__dict__) == []

        conn = Connection("The connection.", Disconnect("someconn"))
        context.someconn = conn
        assert o.execute("echo", *args, **options) == dict(result=(arg1, arg2, options))
        assert conn.disconnect.called is True  # Make sure destroy_context() was called
        assert list(context.__dict__) == []

        # Test with good command:
        conn = Connection("The connection.", Disconnect("someconn"))
        context.someconn = conn
        e = raises(errors.ValidationError, o.execute, "good")
        assert e.name == "nurse"
        assert e.error == u"Not naughty!"
        assert conn.disconnect.called is True  # Make sure destroy_context() was called
        assert list(context.__dict__) == []

        # Test with bad command:
        conn = Connection("The connection.", Disconnect("someconn"))
        context.someconn = conn
        e = raises(errors.InternalError, o.execute, "bad")
        assert conn.disconnect.called is True  # Make sure destroy_context() was called
        assert list(context.__dict__) == []

        # Test with option 'name':
        conn = Connection("The connection.", Disconnect("someconn"))
        context.someconn = conn
        expected = dict(result=u"TEST")
        assert expected == o.execute("with_name", name=u"test", version=API_VERSION)
Exemplo n.º 26
0
    def test_execute(self):
        """
        Test the `ipalib.backend.Executioner.execute` method.
        """
        (api, home) = create_test_api(in_server=True)

        class echo(Command):
            takes_args = ('arg1', 'arg2+')
            takes_options = ('option1?', 'option2?')

            def execute(self, *args, **options):
                assert type(args[1]) is tuple
                return dict(result=args + (options, ))

        api.register(echo)

        class good(Command):
            def execute(self, **options):
                raise errors.ValidationError(
                    name='nurse',
                    error=u'Not naughty!',
                )

        api.register(good)

        class bad(Command):
            def execute(self, **options):
                raise ValueError('This is private.')

        api.register(bad)

        class with_name(Command):
            """
            Test that a kwarg named 'name' can be used.
            """
            takes_options = 'name'

            def execute(self, **options):
                return dict(result=options['name'].upper())

        api.register(with_name)

        api.finalize()
        o = self.cls()
        o.set_api(api)
        o.finalize()

        # Test that CommandError is raised:
        conn = Connection('The connection.', Disconnect('someconn'))
        context.someconn = conn
        print str(context.__dict__.keys())
        e = raises(errors.CommandError, o.execute, 'nope')
        assert e.name == 'nope'
        assert conn.disconnect.called is True  # Make sure destroy_context() was called
        print str(context.__dict__.keys())
        assert context.__dict__.keys() == []

        # Test with echo command:
        arg1 = unicode_str
        arg2 = (u'Hello', unicode_str, u'world!')
        args = (arg1, ) + arg2
        options = dict(option1=u'How are you?',
                       option2=unicode_str,
                       version=API_VERSION)

        conn = Connection('The connection.', Disconnect('someconn'))
        context.someconn = conn
        print o.execute('echo', arg1, arg2, **options)
        print dict(result=(arg1, arg2, options))
        assert o.execute('echo', arg1, arg2,
                         **options) == dict(result=(arg1, arg2, options))
        assert conn.disconnect.called is True  # Make sure destroy_context() was called
        assert context.__dict__.keys() == []

        conn = Connection('The connection.', Disconnect('someconn'))
        context.someconn = conn
        assert o.execute('echo', *args,
                         **options) == dict(result=(arg1, arg2, options))
        assert conn.disconnect.called is True  # Make sure destroy_context() was called
        assert context.__dict__.keys() == []

        # Test with good command:
        conn = Connection('The connection.', Disconnect('someconn'))
        context.someconn = conn
        e = raises(errors.ValidationError, o.execute, 'good')
        assert e.name == 'nurse'
        assert e.error == u'Not naughty!'
        assert conn.disconnect.called is True  # Make sure destroy_context() was called
        assert context.__dict__.keys() == []

        # Test with bad command:
        conn = Connection('The connection.', Disconnect('someconn'))
        context.someconn = conn
        e = raises(errors.InternalError, o.execute, 'bad')
        assert conn.disconnect.called is True  # Make sure destroy_context() was called
        assert context.__dict__.keys() == []

        # Test with option 'name':
        conn = Connection('The connection.', Disconnect('someconn'))
        context.someconn = conn
        expected = dict(result=u'TEST')
        assert expected == o.execute('with_name',
                                     name=u'test',
                                     version=API_VERSION)
Exemplo n.º 27
0
    def test_execute(self):
        """
        Test the `ipalib.backend.Executioner.execute` method.
        """
        api, _home = create_test_api(in_server=True)

        class echo(Command):
            takes_args = ('arg1', 'arg2+')
            takes_options = ('option1?', 'option2?')
            def execute(self, *args, **options):
                assert type(args[1]) is tuple
                return dict(result=args + (options,))
        api.add_plugin(echo)

        class good(Command):
            def execute(self, **options):
                raise errors.ValidationError(
                    name='nurse',
                    error=u'Not naughty!',
                )
        api.add_plugin(good)

        class bad(Command):
            def execute(self, **options):
                raise ValueError('This is private.')
        api.add_plugin(bad)

        class with_name(Command):
            """
            Test that a kwarg named 'name' can be used.
            """
            takes_options = 'name'
            def execute(self, **options):
                return dict(result=options['name'].upper())
        api.add_plugin(with_name)

        api.finalize()
        o = self.cls(api)
        o.finalize()

        # Test that CommandError is raised:
        conn = Connection('The connection.', Disconnect('someconn'))
        context.someconn = conn
        print(str(list(context.__dict__)))
        e = raises(errors.CommandError, o.execute, 'nope')
        assert e.name == 'nope'
        assert conn.disconnect.called is True  # Make sure destroy_context() was called
        print(str(list(context.__dict__)))
        assert list(context.__dict__) == []

        # Test with echo command:
        arg1 = unicode_str
        arg2 = (u'Hello', unicode_str, u'world!')
        args = (arg1,) + arg2
        options = dict(option1=u'How are you?', option2=unicode_str,
                       version=API_VERSION)

        conn = Connection('The connection.', Disconnect('someconn'))
        context.someconn = conn
        print(o.execute('echo', arg1, arg2, **options))
        print(dict(
            result=(arg1, arg2, options)
        ))
        assert o.execute('echo', arg1, arg2, **options) == dict(
            result=(arg1, arg2, options)
        )
        assert conn.disconnect.called is True  # Make sure destroy_context() was called
        assert list(context.__dict__) == []

        conn = Connection('The connection.', Disconnect('someconn'))
        context.someconn = conn
        assert o.execute('echo', *args, **options) == dict(
            result=(arg1, arg2, options)
        )
        assert conn.disconnect.called is True  # Make sure destroy_context() was called
        assert list(context.__dict__) == []

        # Test with good command:
        conn = Connection('The connection.', Disconnect('someconn'))
        context.someconn = conn
        e = raises(errors.ValidationError, o.execute, 'good')
        assert e.name == 'nurse'
        assert e.error == u'Not naughty!'
        assert conn.disconnect.called is True  # Make sure destroy_context() was called
        assert list(context.__dict__) == []

        # Test with bad command:
        conn = Connection('The connection.', Disconnect('someconn'))
        context.someconn = conn
        e = raises(errors.InternalError, o.execute, 'bad')
        assert conn.disconnect.called is True  # Make sure destroy_context() was called
        assert list(context.__dict__) == []

        # Test with option 'name':
        conn = Connection('The connection.', Disconnect('someconn'))
        context.someconn = conn
        expected = dict(result=u'TEST')
        assert expected == o.execute('with_name', name=u'test',
                                     version=API_VERSION)