diff --git a/ipalib/frontend.py b/ipalib/frontend.py index 489b874ce..11d05d5fa 100644 --- a/ipalib/frontend.py +++ b/ipalib/frontend.py @@ -343,6 +343,11 @@ class Command(plugable.Plugin): print ' args =', args print ' kw =', kw + def forward(self, *args, **kw): + print '%s.execute():' % self.name + print ' args =', args + print ' kw =', kw + def __call__(self, *args, **kw): if len(args) > 0: arg_kw = self.args_to_kw(*args) @@ -353,7 +358,15 @@ class Command(plugable.Plugin): kw.update(self.get_default(**kw)) self.validate(**kw) args = tuple(kw.pop(name) for name in self.args) - self.execute(*args, **kw) + return self.run(*args, **kw) + + def run(self, *args, **kw): + if self.api.env.in_server_context: + target = self.execute + else: + target = self.forward + object.__setattr__(self, 'run', target) + return target(*args, **kw) def args_to_kw(self, *values): if self.max_args is not None and len(values) > self.max_args: diff --git a/ipalib/plugable.py b/ipalib/plugable.py index f883eb12e..8bf90ea86 100644 --- a/ipalib/plugable.py +++ b/ipalib/plugable.py @@ -691,11 +691,15 @@ class API(DictProxy): Dynamic API object through which `Plugin` instances are accessed. """ __finalized = False - server_context = True - def __init__(self, *allowed): + def __init__(self, *allowed, **kw): self.__d = dict() self.register = Registrar(*allowed) + default = dict( + in_server_context=True, + ) + default.update(kw) + self.env = MagicDict(default) super(API, self).__init__(self.__d) def finalize(self): diff --git a/ipalib/tests/test_frontend.py b/ipalib/tests/test_frontend.py index d4a70f15a..4ddf11b34 100644 --- a/ipalib/tests/test_frontend.py +++ b/ipalib/tests/test_frontend.py @@ -620,6 +620,38 @@ class test_Command(ClassChecker): assert o.kw_to_args(whatever='hello', two='Two', one='One') == \ ('One', 'Two') + def test_run(self): + """ + Test the `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?') + + # Test in server context: + api = plugable.API(self.cls, in_server_context=True) + api.finalize() + o = my_cmd() + o.set_api(api) + assert o.run.im_func is self.cls.run.im_func + assert ('execute', args, kw) == o.run(*args, **kw) + assert o.run.im_func is my_cmd.execute.im_func + + # Test in non-server context + api = plugable.API(self.cls, in_server_context=False) + api.finalize() + o = my_cmd() + o.set_api(api) + assert o.run.im_func is self.cls.run.im_func + assert ('forward', args, kw) == o.run(*args, **kw) + assert o.run.im_func is my_cmd.forward.im_func + class test_Object(ClassChecker): """