You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
mitogen/tests/service_test.py

155 lines
5.0 KiB
Python

import mitogen.core
import mitogen.service
import testlib
class MyService(mitogen.service.Service):
def __init__(self, router):
super(MyService, self).__init__(router)
self._counter = 0
@mitogen.service.expose(policy=mitogen.service.AllowParents())
def get_id(self):
self._counter += 1
return self._counter, id(self)
@mitogen.service.expose(policy=mitogen.service.AllowParents())
@mitogen.service.arg_spec({
'foo': int
})
def test_arg_spec(self, foo):
return foo
@mitogen.service.expose(policy=mitogen.service.AllowParents())
def privileged_op(self):
return 'privileged!'
@mitogen.service.expose(policy=mitogen.service.AllowAny())
def unprivileged_op(self):
return 'unprivileged!'
class MyService2(MyService):
"""
A uniquely named service that lets us test framework activation and class
activation separately.
"""
def call_service_in(context, service_name, method_name):
return context.call_service(service_name, method_name)
class CallTest(testlib.RouterMixin, testlib.TestCase):
def test_local(self):
pool = mitogen.service.get_or_create_pool(router=self.router)
self.assertEqual(
'privileged!',
mitogen.service.call(MyService, 'privileged_op')
)
pool.stop()
def test_remote_bad_arg(self):
c1 = self.router.local()
self.assertRaises(
mitogen.core.CallError,
lambda: mitogen.service.call(
MyService.name(),
'test_arg_spec',
foo='x',
call_context=c1
)
)
def test_local_unicode(self):
pool = mitogen.service.get_or_create_pool(router=self.router)
self.assertEqual(
'privileged!',
mitogen.service.call(MyService.name(), 'privileged_op')
)
pool.stop()
def test_remote(self):
c1 = self.router.local()
self.assertEqual(
'privileged!',
mitogen.service.call(MyService, 'privileged_op',
call_context=c1)
)
class ActivationTest(testlib.RouterMixin, testlib.TestCase):
def test_parent_can_activate(self):
l1 = self.router.local()
counter, id_ = l1.call_service(MyService, 'get_id')
self.assertEqual(1, counter)
self.assertIsInstance(id_, int)
def test_sibling_cannot_activate_framework(self):
Refactor Stream, introduce quasi-asynchronous connect, much more Split Stream into many, many classes * mitogen.parent.Connection: Handles connection setup logic only. * Maintain references to stdout and stderr streams. * Manages TimerList timer to cancel connection attempt after deadline * Blocking setup code replaced by async equivalents running on the broker * mitogen.parent.Options: Tracks connection-specific options. This keeps the connection class small, but more importantly, it is generic to the future desire to build and execute command lines without starting a full connection. * mitogen.core.Protocol: Handles program behaviour relating to events on a stream. Protocol performs no IO of its own, instead deferring it to Stream and Side. This makes testing much easier, and means libssh can reimplement Stream and Side to reuse MitogenProtocol * mitogen.core.MitogenProtocol: Guts of the old Mitogen stream implementtion * mitogen.core.BufferedWriter: Guts of the old Mitogen buffered transmit implementation, made generic * mitogen.core.DelineatedProtocol: Guts of the old IoLogger, knows how to split up input and pass it on to a on_line_received()/on_partial_line_received() callback. * mitogen.parent.BootstrapProtocol: Asynchronous equivalent of the old blocking connect code. Waits for various prompts (MITO001 etc) and writes the bootstrap using a BufferedWriter. On success, switches the stream to MitogenProtocol. * mitogen.core.Message: move encoding parts of MitogenProtocol out to Message (where it belongs) and write a bunch of new tests for pickling. * The bizarre Stream.construct() is gone now, Option.__init__ is its own constructor. Should fix many LGTM errors. * Update all connection methods: Every connection method is updated to use async logic, defining protocols as required to handle interactive prompts like in SSH or su. Add new real integration tests for at least doas and su. * Eliminate manual fd management: File descriptors are trapped in file objects at their point of origin, and Side is updated to use file objects rather than raw descriptors. This eliminates a whole class of bugs where unrelated FDs could be closed by the wrong component. Now an FD's open/closed status is fused to it everywhere in the library. * Halve file descriptor usage: now FD open/close state is tracked by its file object, we don't need to duplicate FDs everywhere so that receive/transmit side can be closed independently. Instead both sides back on to the same file object. Closes #26, Closes #470. * Remove most uses of dup/dup2: Closes #256. File descriptors are trapped in a common file object and shared among classes. The remaining few uses for dup/dup2 are as close to minimal as possible. * Introduce mitogen.parent.Process: uniform interface for subprocesses created either via mitogen.fork or the subprocess module. Remove all the crap where we steal a pid from subprocess guts. Now we use subprocess to manage its processes as it should be. Closes #169 by using the new Timers facility to poll for a slow-to-exit subprocess. * Fix su password race: Closes #363. DelineatedProtocol naturally retries partially received lines, preventing the cause of the original race. * Delete old blocking IO utility functions iter_read()/write_all()/discard_until(). Closes #26 Closes #147 Closes #169 Closes #256 Closes #363 Closes #419 Closes #470
6 years ago
l1 = self.router.local(name='l1')
l2 = self.router.local(name='l2')
exc = self.assertRaises(mitogen.core.CallError,
lambda: l2.call(call_service_in, l1, MyService2.name(), 'get_id'))
self.assertIn(mitogen.core.Router.refused_msg, exc.args[0])
def test_sibling_cannot_activate_service(self):
l1 = self.router.local()
l2 = self.router.local()
l1.call_service(MyService, 'get_id') # force framework activation
capture = testlib.LogCapturer()
capture.start()
try:
exc = self.assertRaises(mitogen.core.CallError,
lambda: l2.call(call_service_in, l1, MyService2.name(), 'get_id'))
finally:
capture.stop()
msg = mitogen.service.Activator.not_active_msg % (MyService2.name(),)
self.assertIn(msg, exc.args[0])
def test_activates_only_once(self):
l1 = self.router.local()
counter, id_ = l1.call_service(MyService, 'get_id')
counter2, id_2 = l1.call_service(MyService, 'get_id')
self.assertEqual(1, counter)
self.assertEqual(2, counter2)
self.assertEqual(id_, id_2)
class PermissionTest(testlib.RouterMixin, testlib.TestCase):
def test_sibling_unprivileged_ok(self):
l1 = self.router.local()
l1.call_service(MyService, 'get_id')
l2 = self.router.local()
self.assertEqual('unprivileged!',
l2.call(call_service_in, l1, MyService.name(), 'unprivileged_op'))
def test_sibling_privileged_bad(self):
l1 = self.router.local()
l1.call_service(MyService, 'get_id')
l2 = self.router.local()
capture = testlib.LogCapturer()
capture.start()
try:
exc = self.assertRaises(mitogen.core.CallError, lambda:
l2.call(call_service_in, l1, MyService.name(), 'privileged_op'))
finally:
capture.stop()
msg = mitogen.service.Invoker.unauthorized_msg % (
u'privileged_op',
MyService.name(),
)
self.assertIn(msg, exc.args[0])
class CloseTest(testlib.RouterMixin, testlib.TestCase):
klass = mitogen.service.Pool
def test_receiver_closed(self):
pool = self.klass(router=self.router, services=[])
pool.stop()
self.assertEqual(None, pool._receiver.handle)
e = self.assertRaises(mitogen.core.ChannelError,
lambda: self.router.myself().call_service(MyService, 'foobar'))
self.assertEqual(e.args[0], self.router.invalid_handle_msg)