Example #1
0
def cry(out=None, sepchr='=', seplen=49):  # pragma: no cover
    """Return stacktrace of all active threads,
    taken from https://gist.github.com/737056."""
    import threading

    out = WhateverIO() if out is None else out
    P = partial(print, file=out)

    # get a map of threads by their ID so we can print their names
    # during the traceback dump
    tmap = {t.ident: t for t in threading.enumerate()}

    sep = sepchr * seplen
    for tid, frame in items(sys._current_frames()):
        thread = tmap.get(tid)
        if not thread:
            # skip old junk (left-overs from a fork)
            continue
        P('{0.name}'.format(thread))
        P(sep)
        traceback.print_stack(frame, file=out)
        P(sep)
        P('LOCAL VARIABLES')
        P(sep)
        pprint(frame.f_locals, stream=out)
        P('\n')
    return out.getvalue()
Example #2
0
def cry(out=None, sepchr='=', seplen=49):  # pragma: no cover
    """Return stack-trace of all active threads,
    taken from https://gist.github.com/737056."""
    import threading

    out = WhateverIO() if out is None else out
    P = partial(print, file=out)

    # get a map of threads by their ID so we can print their names
    # during the traceback dump
    tmap = {t.ident: t for t in threading.enumerate()}

    sep = sepchr * seplen
    for tid, frame in items(sys._current_frames()):
        thread = tmap.get(tid)
        if not thread:
            # skip old junk (left-overs from a fork)
            continue
        P('{0.name}'.format(thread))
        P(sep)
        traceback.print_stack(frame, file=out)
        P(sep)
        P('LOCAL VARIABLES')
        P(sep)
        pprint(frame.f_locals, stream=out)
        P('\n')
    return out.getvalue()
Example #3
0
 def test_run(self):
     out = WhateverIO()
     h = help(app=self.app, stdout=out)
     h.parser = Mock()
     self.assertEqual(h.run(), EX_USAGE)
     self.assertTrue(out.getvalue())
     self.assertTrue(h.usage('help'))
     h.parser.print_help.assert_called_with()
Example #4
0
 def test_run(self):
     out = WhateverIO()
     h = help(app=self.app, stdout=out)
     h.parser = Mock()
     assert h.run() == EX_USAGE
     assert out.getvalue()
     assert h.usage('help')
     h.parser.print_help.assert_called_with()
Example #5
0
 def test_run(self):
     out = WhateverIO()
     h = help(app=self.app, stdout=out)
     h.parser = Mock()
     assert h.run() == EX_USAGE
     assert out.getvalue()
     assert h.usage('help')
     h.parser.print_help.assert_called_with()
Example #6
0
class test_Dumper(AppCase):

    def setup(self):
        self.out = WhateverIO()
        self.dumper = Dumper(out=self.out)

    def test_humanize_type(self):
        self.assertEqual(humanize_type('worker-offline'), 'shutdown')
        self.assertEqual(humanize_type('task-started'), 'task started')

    def test_format_task_event(self):
        self.dumper.format_task_event(
            '*****@*****.**', time(), 'task-started', 'tasks.add', {})
        self.assertTrue(self.out.getvalue())

    def test_on_event(self):
        event = {
            'hostname': '*****@*****.**',
            'timestamp': time(),
            'uuid': '1ef',
            'name': 'tasks.add',
            'args': '(2, 2)',
            'kwargs': '{}',
        }
        self.dumper.on_event(dict(event, type='task-received'))
        self.assertTrue(self.out.getvalue())
        self.dumper.on_event(dict(event, type='task-revoked'))
        self.dumper.on_event(dict(event, type='worker-online'))

    @patch('celery.events.EventReceiver.capture')
    def test_evdump(self, capture):
        capture.side_effect = KeyboardInterrupt()
        evdump(app=self.app)

    def test_evdump_error_handler(self):
        app = Mock(name='app')
        with patch('celery.events.dumper.Dumper') as Dumper:
            Dumper.return_value = Mock(name='dumper')
            recv = app.events.Receiver.return_value = Mock()

            def se(*_a, **_k):
                recv.capture.side_effect = SystemExit()
                raise KeyError()
            recv.capture.side_effect = se

            Conn = app.connection_for_read.return_value = Mock(name='conn')
            conn = Conn.clone.return_value = Mock(name='cloned_conn')
            conn.connection_errors = (KeyError,)
            conn.channel_errors = ()

            evdump(app)
            conn.ensure_connection.assert_called()
            errback = conn.ensure_connection.call_args[0][0]
            errback(KeyError(), 1)
            conn.as_uri.assert_called()
Example #7
0
def override_stdouts():
    """Override `sys.stdout` and `sys.stderr` with `WhateverIO`."""
    prev_out, prev_err = sys.stdout, sys.stderr
    mystdout, mystderr = WhateverIO(), WhateverIO()
    sys.stdout = sys.__stdout__ = mystdout
    sys.stderr = sys.__stderr__ = mystderr

    yield mystdout, mystderr

    sys.stdout = sys.__stdout__ = prev_out
    sys.stderr = sys.__stderr__ = prev_err
Example #8
0
class test_Dumper(AppCase):
    def setup(self):
        self.out = WhateverIO()
        self.dumper = Dumper(out=self.out)

    def test_humanize_type(self):
        self.assertEqual(humanize_type("worker-offline"), "shutdown")
        self.assertEqual(humanize_type("task-started"), "task started")

    def test_format_task_event(self):
        self.dumper.format_task_event("*****@*****.**", time(), "task-started", "tasks.add", {})
        self.assertTrue(self.out.getvalue())

    def test_on_event(self):
        event = {
            "hostname": "*****@*****.**",
            "timestamp": time(),
            "uuid": "1ef",
            "name": "tasks.add",
            "args": "(2, 2)",
            "kwargs": "{}",
        }
        self.dumper.on_event(dict(event, type="task-received"))
        self.assertTrue(self.out.getvalue())
        self.dumper.on_event(dict(event, type="task-revoked"))
        self.dumper.on_event(dict(event, type="worker-online"))

    @patch("celery.events.EventReceiver.capture")
    def test_evdump(self, capture):
        capture.side_effect = KeyboardInterrupt()
        evdump(app=self.app)

    def test_evdump_error_handler(self):
        app = Mock(name="app")
        with patch("celery.events.dumper.Dumper") as Dumper:
            Dumper.return_value = Mock(name="dumper")
            recv = app.events.Receiver.return_value = Mock()

            def se(*_a, **_k):
                recv.capture.side_effect = SystemExit()
                raise KeyError()

            recv.capture.side_effect = se

            Conn = app.connection_for_read.return_value = Mock(name="conn")
            conn = Conn.clone.return_value = Mock(name="cloned_conn")
            conn.connection_errors = (KeyError,)
            conn.channel_errors = ()

            evdump(app)
            self.assertTrue(conn.ensure_connection.called)
            errback = conn.ensure_connection.call_args[0][0]
            errback(KeyError(), 1)
            self.assertTrue(conn.as_uri.called)
Example #9
0
    def test_write_reread_fails(self, open_, fdopen, osopen, getpid, fsync):
        getpid.return_value = 1816
        osopen.return_value = 13
        w = fdopen.return_value = WhateverIO()
        w.close = Mock()
        r = open_.return_value = WhateverIO()
        r.write('11816\n')
        r.seek(0)

        p = Pidfile('/var/pid')
        with self.assertRaises(LockFailed):
            p.write_pid()
Example #10
0
    def test_run(self, inspect_):
        out, err = WhateverIO(), WhateverIO()
        ins = inspect_.return_value = Mock()
        ins.run.return_value = []
        s = status(self.app, stdout=out, stderr=err)
        with self.assertRaises(Error):
            s.run()

        ins.run.return_value = ['a', 'b', 'c']
        s.run()
        self.assertIn('3 nodes online', out.getvalue())
        s.run(quiet=True)
Example #11
0
    def test_run(self, real):
        out = WhateverIO()
        i = inspect(app=self.app, stdout=out)
        with self.assertRaises(Error):
            i.run()
        with self.assertRaises(Error):
            i.run('help')
        with self.assertRaises(Error):
            i.run('xyzzybaz')

        i.run('ping')
        real.assert_called()
        i.run('ping', destination='foo,bar')
        self.assertEqual(real.call_args[1]['destination'], ['foo', 'bar'])
        self.assertEqual(real.call_args[1]['timeout'], 0.2)
        callback = real.call_args[1]['callback']

        callback({'foo': {'ok': 'pong'}})
        self.assertIn('OK', out.getvalue())

        with patch('celery.bin.celery.dumps') as dumps:
            i.run('ping', json=True)
            dumps.assert_called()

        instance = real.return_value = Mock()
        instance._request.return_value = None
        with self.assertRaises(Error):
            i.run('ping')

        out.seek(0)
        out.truncate()
        i.quiet = True
        i.say_chat('<-', 'hello')
        self.assertFalse(out.getvalue())
Example #12
0
def override_stdouts():
    """Override `sys.stdout` and `sys.stderr` with `WhateverIO`."""
    prev_out, prev_err = sys.stdout, sys.stderr
    prev_rout, prev_rerr = sys.__stdout__, sys.__stderr__
    mystdout, mystderr = WhateverIO(), WhateverIO()
    sys.stdout = sys.__stdout__ = mystdout
    sys.stderr = sys.__stderr__ = mystderr

    try:
        yield mystdout, mystderr
    finally:
        sys.stdout = prev_out
        sys.stderr = prev_err
        sys.__stdout__ = prev_rout
        sys.__stderr__ = prev_rerr
Example #13
0
    def test_run(self):
        with patch("celery.result.AsyncResult.get") as get:
            out = WhateverIO()
            r = result(app=self.app, stdout=out)
            get.return_value = "Jerry"
            r.run("id")
            assert "Jerry" in out.getvalue()

            get.return_value = "Elaine"
            r.run("id", task=self.add.name)
            assert "Elaine" in out.getvalue()

            with patch("celery.result.AsyncResult.traceback") as tb:
                r.run("id", task=self.add.name, traceback=True)
                assert str(tb) in out.getvalue()
Example #14
0
    def test_run(self):
        with patch('celery.result.AsyncResult.get') as get:
            out = WhateverIO()
            r = result(app=self.app, stdout=out)
            get.return_value = 'Jerry'
            r.run('id')
            self.assertIn('Jerry', out.getvalue())

            get.return_value = 'Elaine'
            r.run('id', task=self.add.name)
            self.assertIn('Elaine', out.getvalue())

            with patch('celery.result.AsyncResult.traceback') as tb:
                r.run('id', task=self.add.name, traceback=True)
                self.assertIn(str(tb), out.getvalue())
Example #15
0
    def test_run(self, migrate_tasks):
        out = WhateverIO()
        m = migrate(app=self.app, stdout=out, stderr=WhateverIO())
        with self.assertRaises(TypeError):
            m.run()
        migrate_tasks.assert_not_called()

        m.run('memory://foo', 'memory://bar')
        migrate_tasks.assert_called()

        state = Mock()
        state.count = 10
        state.strtotal = 30
        m.on_migrate_task(state, {'task': 'tasks.add', 'id': 'ID'}, None)
        self.assertIn('10/30', out.getvalue())
Example #16
0
    def test_get_avail_port(self, sock):
        out = WhateverIO()
        sock.return_value.accept.return_value = (Mock(), ['helu'])
        with Rdb(out=out):
            pass

        with patch('celery.contrib.rdb.current_process') as curproc:
            curproc.return_value.name = 'PoolWorker-10'
            with Rdb(out=out):
                pass

        err = sock.return_value.bind.side_effect = SockErr()
        err.errno = errno.ENOENT
        with pytest.raises(SockErr):
            with Rdb(out=out):
                pass
        err.errno = errno.EADDRINUSE
        with pytest.raises(Exception):
            with Rdb(out=out):
                pass
        called = [0]

        def effect(*a, **kw):
            try:
                if called[0] > 50:
                    return True
                raise err
            finally:
                called[0] += 1

        sock.return_value.bind.side_effect = effect
        with Rdb(out=out):
            pass
Example #17
0
    def test_run(self, purge_):
        out = WhateverIO()
        a = purge(app=self.app, stdout=out)
        purge_.return_value = 0
        a.run(force=True)
        self.assertIn('No messages purged', out.getvalue())

        purge_.return_value = 100
        a.run(force=True)
        self.assertIn('100 messages', out.getvalue())

        a.out = Mock(name='out')
        a.ask = Mock(name='ask')
        a.run(force=False)
        a.ask.assert_called_with(a.warn_prompt, ('yes', 'no'), 'no')
        a.ask.return_value = 'yes'
        a.run(force=False)
Example #18
0
    def test_run(self, purge_):
        out = WhateverIO()
        a = purge(app=self.app, stdout=out)
        purge_.return_value = 0
        a.run(force=True)
        self.assertIn('No messages purged', out.getvalue())

        purge_.return_value = 100
        a.run(force=True)
        self.assertIn('100 messages', out.getvalue())

        a.out = Mock(name='out')
        a.ask = Mock(name='ask')
        a.run(force=False)
        a.ask.assert_called_with(a.warn_prompt, ('yes', 'no'), 'no')
        a.ask.return_value = 'yes'
        a.run(force=False)
Example #19
0
    def test_run(self):
        l = list_(app=self.app, stderr=WhateverIO())
        l.run('bindings')

        with self.assertRaises(Error):
            l.run(None)

        with self.assertRaises(Error):
            l.run('foo')
Example #20
0
def wrap_logger(logger, loglevel=logging.ERROR):
    old_handlers = get_handlers(logger)
    sio = WhateverIO()
    siohandler = logging.StreamHandler(sio)
    logger.handlers = [siohandler]

    yield sio

    logger.handlers = old_handlers
    def test_run(self):
        out = WhateverIO()
        a = upgrade(app=self.app, stdout=out)

        with pytest.raises(a.UsageError, match=r'missing upgrade type'):
            a.run()

        with pytest.raises(a.UsageError, match=r'missing settings filename'):
            a.run('settings')
Example #22
0
 def setup(self):
     self.fh = WhateverIO()
     self.env = {}
     self.t = MultiTool(env=self.env, fh=self.fh)
     self.t.Cluster = Mock(name='Cluster')
     self.t.carp = Mock(name='.carp')
     self.t.usage = Mock(name='.usage')
     self.t.splash = Mock(name='.splash')
     self.t.say = Mock(name='.say')
     self.t.ok = Mock(name='.ok')
     self.cluster = self.t.Cluster.return_value
Example #23
0
    def test_rdb(self, get_avail_port):
        sock = Mock()
        get_avail_port.return_value = (sock, 8000)
        sock.accept.return_value = (Mock(), ['helu'])
        out = WhateverIO()
        with Rdb(out=out) as rdb:
            get_avail_port.assert_called()
            assert 'helu' in out.getvalue()

            # set_quit
            with patch('sys.settrace') as settrace:
                rdb.set_quit()
                settrace.assert_called_with(None)

            # set_trace
            with patch('celery.contrib.rdb.Pdb.set_trace') as pset:
                with patch('celery.contrib.rdb._frame'):
                    rdb.set_trace()
                    rdb.set_trace(Mock())
                    pset.side_effect = SockErr
                    pset.side_effect.errno = errno.ENOENT
                    with pytest.raises(SockErr):
                        rdb.set_trace()

            # _close_session
            rdb._close_session()
            rdb.active = True
            rdb._handle = None
            rdb._client = None
            rdb._sock = None
            rdb._close_session()

            # do_continue
            rdb.set_continue = Mock()
            rdb.do_continue(Mock())
            rdb.set_continue.assert_called_with()

            # do_quit
            rdb.set_quit = Mock()
            rdb.do_quit(Mock())
            rdb.set_quit.assert_called_with()
Example #24
0
    def test_rdb(self, get_avail_port):
        sock = Mock()
        get_avail_port.return_value = (sock, 8000)
        sock.accept.return_value = (Mock(), ['helu'])
        out = WhateverIO()
        with Rdb(out=out) as rdb:
            get_avail_port.assert_called()
            assert 'helu' in out.getvalue()

            # set_quit
            with patch('sys.settrace') as settrace:
                rdb.set_quit()
                settrace.assert_called_with(None)

            # set_trace
            with patch('celery.contrib.rdb.Pdb.set_trace') as pset:
                with patch('celery.contrib.rdb._frame'):
                    rdb.set_trace()
                    rdb.set_trace(Mock())
                    pset.side_effect = SockErr
                    pset.side_effect.errno = errno.ENOENT
                    with pytest.raises(SockErr):
                        rdb.set_trace()

            # _close_session
            rdb._close_session()
            rdb.active = True
            rdb._handle = None
            rdb._client = None
            rdb._sock = None
            rdb._close_session()

            # do_continue
            rdb.set_continue = Mock()
            rdb.do_continue(Mock())
            rdb.set_continue.assert_called_with()

            # do_quit
            rdb.set_quit = Mock()
            rdb.do_quit(Mock())
            rdb.set_quit.assert_called_with()
Example #25
0
    def test_run(self, send_task):
        a = call(app=self.app, stderr=WhateverIO(), stdout=WhateverIO())
        a.run(self.add.name)
        send_task.assert_called()

        a.run(self.add.name,
              args=dumps([4, 4]),
              kwargs=dumps({'x': 2, 'y': 2}))
        self.assertEqual(send_task.call_args[1]['args'], [4, 4])
        self.assertEqual(send_task.call_args[1]['kwargs'], {'x': 2, 'y': 2})

        a.run(self.add.name, expires=10, countdown=10)
        self.assertEqual(send_task.call_args[1]['expires'], 10)
        self.assertEqual(send_task.call_args[1]['countdown'], 10)

        now = datetime.now()
        iso = now.isoformat()
        a.run(self.add.name, expires=iso)
        self.assertEqual(send_task.call_args[1]['expires'], now)
        with self.assertRaises(ValueError):
            a.run(self.add.name, expires='foobaribazibar')
Example #26
0
    def test_write_pid(self, open_, fdopen, osopen, getpid, fsync):
        getpid.return_value = 1816
        osopen.return_value = 13
        w = fdopen.return_value = WhateverIO()
        w.close = Mock()
        r = open_.return_value = WhateverIO()
        r.write('1816\n')
        r.seek(0)

        p = Pidfile('/var/pid')
        p.write_pid()
        w.seek(0)
        assert w.readline() == '1816\n'
        w.close.assert_called()
        getpid.assert_called_with()
        osopen.assert_called_with(
            p.path, platforms.PIDFILE_FLAGS, platforms.PIDFILE_MODE,
        )
        fdopen.assert_called_with(13, 'w')
        fsync.assert_called_with(13)
        open_.assert_called_with(p.path)
Example #27
0
 def test_run(self):
     out = WhateverIO()
     with patch('celery.loaders.base.BaseLoader.import_default_modules'
                ) as import_default_modules:
         with patch('celery.app.base.Celery.bugreport') as bugreport:
             # Method call order mock obj
             mco = Mock()
             mco.attach_mock(import_default_modules, 'idm')
             mco.attach_mock(bugreport, 'br')
             a = report(app=self.app, stdout=out)
             a.run()
             calls = [call.idm(), call.br()]
             mco.assert_has_calls(calls)
Example #28
0
    def setup(self):
        self.fh = WhateverIO()
        self.env = {}
        self.t = MultiTool(env=self.env, fh=self.fh)
        self.t.cluster_from_argv = Mock(name='cluster_from_argv')
        self.t._cluster_from_argv = Mock(name='cluster_from_argv')
        self.t.Cluster = Mock(name='Cluster')
        self.t.carp = Mock(name='.carp')
        self.t.usage = Mock(name='.usage')
        self.t.splash = Mock(name='.splash')
        self.t.say = Mock(name='.say')
        self.t.ok = Mock(name='.ok')
        self.cluster = self.t.Cluster.return_value

        def _cluster_from_argv(argv):
            p = self.t.OptionParser(argv)
            p.parse()
            return p, self.cluster

        self.t.cluster_from_argv.return_value = self.cluster
        self.t._cluster_from_argv.side_effect = _cluster_from_argv
Example #29
0
 def setup(self):
     self.fh = WhateverIO()
     self.adm = self.create_adm()
     self.shell = AMQShell(connect=self.adm.connect, out=self.fh)
Example #30
0
class test_AMQShell:

    def setup(self):
        self.fh = WhateverIO()
        self.adm = self.create_adm()
        self.shell = AMQShell(connect=self.adm.connect, out=self.fh)

    def create_adm(self, *args, **kwargs):
        return AMQPAdmin(app=self.app, out=self.fh, *args, **kwargs)

    def test_queue_declare(self):
        self.shell.onecmd('queue.declare foo')
        assert 'ok' in self.fh.getvalue()

    def test_missing_command(self):
        self.shell.onecmd('foo foo')
        assert 'unknown syntax' in self.fh.getvalue()

    def RV(self):
        raise Exception(self.fh.getvalue())

    def test_spec_format_response(self):
        spec = self.shell.amqp['exchange.declare']
        assert spec.format_response(None) == 'ok.'
        assert spec.format_response('NO') == 'NO'

    def test_missing_namespace(self):
        self.shell.onecmd('ns.cmd arg')
        assert 'unknown syntax' in self.fh.getvalue()

    def test_help(self):
        self.shell.onecmd('help')
        assert 'Example:' in self.fh.getvalue()

    def test_help_command(self):
        self.shell.onecmd('help queue.declare')
        assert 'passive:no' in self.fh.getvalue()

    def test_help_unknown_command(self):
        self.shell.onecmd('help foo.baz')
        assert 'unknown syntax' in self.fh.getvalue()

    def test_onecmd_error(self):
        self.shell.dispatch = Mock()
        self.shell.dispatch.side_effect = MemoryError()
        self.shell.say = Mock()
        assert not self.shell.needs_reconnect
        self.shell.onecmd('hello')
        self.shell.say.assert_called()
        assert self.shell.needs_reconnect

    def test_exit(self):
        with pytest.raises(SystemExit):
            self.shell.onecmd('exit')
        assert "don't leave!" in self.fh.getvalue()

    def test_note_silent(self):
        self.shell.silent = True
        self.shell.note('foo bar')
        assert 'foo bar' not in self.fh.getvalue()

    def test_reconnect(self):
        self.shell.onecmd('queue.declare foo')
        self.shell.needs_reconnect = True
        self.shell.onecmd('queue.delete foo')

    def test_completenames(self):
        assert self.shell.completenames('queue.dec') == ['queue.declare']
        assert (sorted(self.shell.completenames('declare')) ==
                sorted(['queue.declare', 'exchange.declare']))

    def test_empty_line(self):
        self.shell.emptyline = Mock()
        self.shell.default = Mock()
        self.shell.onecmd('')
        self.shell.emptyline.assert_called_with()
        self.shell.onecmd('foo')
        self.shell.default.assert_called_with('foo')

    def test_respond(self):
        self.shell.respond({'foo': 'bar'})
        assert 'foo' in self.fh.getvalue()

    def test_prompt(self):
        assert self.shell.prompt

    def test_no_returns(self):
        self.shell.onecmd('queue.declare foo')
        self.shell.onecmd('exchange.declare bar direct yes')
        self.shell.onecmd('queue.bind foo bar baz')
        self.shell.onecmd('basic.ack 1')

    def test_dump_message(self):
        m = Mock()
        m.body = 'the quick brown fox'
        m.properties = {'a': 1}
        m.delivery_info = {'exchange': 'bar'}
        assert dump_message(m)

    def test_dump_message_no_message(self):
        assert 'No messages in queue' in dump_message(None)

    def test_note(self):
        self.adm.silent = True
        self.adm.note('FOO')
        assert 'FOO' not in self.fh.getvalue()

    def test_run(self):
        a = self.create_adm('queue.declare', 'foo')
        a.run()
        assert 'ok' in self.fh.getvalue()

    def test_run_loop(self):
        a = self.create_adm()
        a.Shell = Mock()
        shell = a.Shell.return_value = Mock()
        shell.cmdloop = Mock()
        a.run()
        shell.cmdloop.assert_called_with()

        shell.cmdloop.side_effect = KeyboardInterrupt()
        a.run()
        assert 'bibi' in self.fh.getvalue()

    @patch('celery.bin.amqp.amqp')
    def test_main(self, Command):
        c = Command.return_value = Mock()
        main()
        c.execute_from_commandline.assert_called_with()

    @patch('celery.bin.amqp.AMQPAdmin')
    def test_command(self, cls):
        x = amqp(app=self.app)
        x.run()
        assert cls.call_args[1]['app'] is self.app
Example #31
0
 def test_to_dot(self):
     s = WhateverIO()
     self.graph1().to_dot(s)
     assert s.getvalue()
Example #32
0
 def test_list_bindings_no_support(self):
     l = list_(app=self.app, stderr=WhateverIO())
     management = Mock()
     management.get_bindings.side_effect = NotImplementedError()
     with self.assertRaises(Error):
         l.list_bindings(management)
Example #33
0
class test_AMQShell:
    def setup(self):
        self.fh = WhateverIO()
        self.adm = self.create_adm()
        self.shell = AMQShell(connect=self.adm.connect, out=self.fh)

    def create_adm(self, *args, **kwargs):
        return AMQPAdmin(app=self.app, out=self.fh, *args, **kwargs)

    def test_queue_declare(self):
        self.shell.onecmd('queue.declare foo')
        assert 'ok' in self.fh.getvalue()

    def test_missing_command(self):
        self.shell.onecmd('foo foo')
        assert 'unknown syntax' in self.fh.getvalue()

    def RV(self):
        raise Exception(self.fh.getvalue())

    def test_spec_format_response(self):
        spec = self.shell.amqp['exchange.declare']
        assert spec.format_response(None) == 'ok.'
        assert spec.format_response('NO') == 'NO'

    def test_missing_namespace(self):
        self.shell.onecmd('ns.cmd arg')
        assert 'unknown syntax' in self.fh.getvalue()

    def test_help(self):
        self.shell.onecmd('help')
        assert 'Example:' in self.fh.getvalue()

    def test_help_command(self):
        self.shell.onecmd('help queue.declare')
        assert 'passive:no' in self.fh.getvalue()

    def test_help_unknown_command(self):
        self.shell.onecmd('help foo.baz')
        assert 'unknown syntax' in self.fh.getvalue()

    def test_onecmd_error(self):
        self.shell.dispatch = Mock()
        self.shell.dispatch.side_effect = MemoryError()
        self.shell.say = Mock()
        assert not self.shell.needs_reconnect
        self.shell.onecmd('hello')
        self.shell.say.assert_called()
        assert self.shell.needs_reconnect

    def test_exit(self):
        with pytest.raises(SystemExit):
            self.shell.onecmd('exit')
        assert "don't leave!" in self.fh.getvalue()

    def test_note_silent(self):
        self.shell.silent = True
        self.shell.note('foo bar')
        assert 'foo bar' not in self.fh.getvalue()

    def test_reconnect(self):
        self.shell.onecmd('queue.declare foo')
        self.shell.needs_reconnect = True
        self.shell.onecmd('queue.delete foo')

    def test_completenames(self):
        assert self.shell.completenames('queue.dec') == ['queue.declare']
        assert (sorted(self.shell.completenames('declare')) == sorted(
            ['queue.declare', 'exchange.declare']))

    def test_empty_line(self):
        self.shell.emptyline = Mock()
        self.shell.default = Mock()
        self.shell.onecmd('')
        self.shell.emptyline.assert_called_with()
        self.shell.onecmd('foo')
        self.shell.default.assert_called_with('foo')

    def test_respond(self):
        self.shell.respond({'foo': 'bar'})
        assert 'foo' in self.fh.getvalue()

    def test_prompt(self):
        assert self.shell.prompt

    def test_no_returns(self):
        self.shell.onecmd('queue.declare foo')
        self.shell.onecmd('exchange.declare bar direct yes')
        self.shell.onecmd('queue.bind foo bar baz')
        self.shell.onecmd('basic.ack 1')

    def test_dump_message(self):
        m = Mock()
        m.body = 'the quick brown fox'
        m.properties = {'a': 1}
        m.delivery_info = {'exchange': 'bar'}
        assert dump_message(m)

    def test_dump_message_no_message(self):
        assert 'No messages in queue' in dump_message(None)

    def test_note(self):
        self.adm.silent = True
        self.adm.note('FOO')
        assert 'FOO' not in self.fh.getvalue()

    def test_run(self):
        a = self.create_adm('queue.declare', 'foo')
        a.run()
        assert 'ok' in self.fh.getvalue()

    def test_run_loop(self):
        a = self.create_adm()
        a.Shell = Mock()
        shell = a.Shell.return_value = Mock()
        shell.cmdloop = Mock()
        a.run()
        shell.cmdloop.assert_called_with()

        shell.cmdloop.side_effect = KeyboardInterrupt()
        a.run()
        assert 'bibi' in self.fh.getvalue()

    @patch('celery.bin.amqp.amqp')
    def test_main(self, Command):
        c = Command.return_value = Mock()
        main()
        c.execute_from_commandline.assert_called_with()

    @patch('celery.bin.amqp.AMQPAdmin')
    def test_command(self, cls):
        x = amqp(app=self.app)
        x.run()
        assert cls.call_args[1]['app'] is self.app
Example #34
0
 def setup(self):
     self.fh = WhateverIO()
     self.adm = self.create_adm()
     self.shell = AMQShell(connect=self.adm.connect, out=self.fh)
Example #35
0
 def setup(self):
     self.fh = WhateverIO()
     self.env = {}
     self.t = MultiTool(env=self.env, fh=self.fh)
Example #36
0
class test_MultiTool(AppCase):

    def setup(self):
        self.fh = WhateverIO()
        self.env = {}
        self.t = MultiTool(env=self.env, fh=self.fh)

    def test_note(self):
        self.t.note('hello world')
        self.assertEqual(self.fh.getvalue(), 'hello world\n')

    def test_note_quiet(self):
        self.t.quiet = True
        self.t.note('hello world')
        self.assertFalse(self.fh.getvalue())

    def test_carp(self):
        self.t.say = Mock()
        self.t.carp('foo')
        self.t.say.assert_called_with('foo', True, self.t.stderr)

    def test_info(self):
        self.t.verbose = True
        self.t.info('hello info')
        self.assertEqual(self.fh.getvalue(), 'hello info\n')

    def test_info_not_verbose(self):
        self.t.verbose = False
        self.t.info('hello info')
        self.assertFalse(self.fh.getvalue())

    def test_error(self):
        self.t.carp = Mock()
        self.t.usage = Mock()
        self.assertEqual(self.t.error('foo'), 1)
        self.t.carp.assert_called_with('foo')
        self.t.usage.assert_called_with()

        self.t.carp = Mock()
        self.assertEqual(self.t.error(), 1)
        self.assertFalse(self.t.carp.called)

        self.assertEqual(self.t.retcode, 1)

    @patch('celery.bin.multi.Popen')
    def test_waitexec(self, Popen):
        self.t.note = Mock()
        pipe = Popen.return_value = Mock()
        pipe.wait.return_value = -10
        self.assertEqual(self.t.waitexec(['-m', 'foo'], 'path'), 10)
        Popen.assert_called_with(['path', '-m', 'foo'], env=self.t.env)
        self.t.note.assert_called_with('* Child was terminated by signal 10')

        pipe.wait.return_value = 2
        self.assertEqual(self.t.waitexec(['-m', 'foo'], 'path'), 2)
        self.t.note.assert_called_with(
            '* Child terminated with errorcode 2',
        )

        pipe.wait.return_value = 0
        self.assertFalse(self.t.waitexec(['-m', 'foo', 'path']))

    def test_nosplash(self):
        self.t.nosplash = True
        self.t.splash()
        self.assertFalse(self.fh.getvalue())

    def test_splash(self):
        self.t.nosplash = False
        self.t.splash()
        self.assertIn('celery multi', self.fh.getvalue())

    def test_usage(self):
        self.t.usage()
        self.assertTrue(self.fh.getvalue())

    def test_help(self):
        self.t.help([])
        self.assertIn(doc, self.fh.getvalue())

    def test_expand(self):
        self.t.expand(['foo%n', 'ask', 'klask', 'dask'])
        self.assertEqual(
            self.fh.getvalue(), 'fooask\nfooklask\nfoodask\n',
        )

    def test_restart(self):
        stop = self.t._stop_nodes = Mock()
        self.t.restart(['jerry', 'george'], 'celery worker')
        waitexec = self.t.waitexec = Mock()
        self.assertTrue(stop.called)
        callback = stop.call_args[1]['callback']
        self.assertTrue(callback)

        waitexec.return_value = 0
        callback('jerry', ['arg'], 13)
        waitexec.assert_called_with(['arg'], path=sys.executable)
        self.assertIn('OK', self.fh.getvalue())
        self.fh.seek(0)
        self.fh.truncate()

        waitexec.return_value = 1
        callback('jerry', ['arg'], 13)
        self.assertIn('FAILED', self.fh.getvalue())

    def test_stop(self):
        self.t.getpids = Mock()
        self.t.getpids.return_value = [2, 3, 4]
        self.t.shutdown_nodes = Mock()
        self.t.stop(['a', 'b', '-INT'], 'celery worker')
        self.t.shutdown_nodes.assert_called_with(
            [2, 3, 4], sig=signal.SIGINT, retry=None, callback=None,

        )

    @skip_unless_symbol('signal.SIGKILL')
    def test_kill(self):
        self.t.getpids = Mock()
        self.t.getpids.return_value = [
            ('a', None, 10),
            ('b', None, 11),
            ('c', None, 12)
        ]
        sig = self.t.signal_node = Mock()

        self.t.kill(['a', 'b', 'c'], 'celery worker')

        sigs = sig.call_args_list
        self.assertEqual(len(sigs), 3)
        self.assertEqual(sigs[0][0], ('a', 10, signal.SIGKILL))
        self.assertEqual(sigs[1][0], ('b', 11, signal.SIGKILL))
        self.assertEqual(sigs[2][0], ('c', 12, signal.SIGKILL))

    def prepare_pidfile_for_getpids(self, Pidfile):
        class pids(object):

            def __init__(self, path):
                self.path = path

            def read_pid(self):
                try:
                    return {'foo.pid': 10,
                            'bar.pid': 11}[self.path]
                except KeyError:
                    raise ValueError()
        Pidfile.side_effect = pids

    @patch('celery.bin.multi.Pidfile')
    @patch('celery.bin.multi.gethostname')
    def test_getpids(self, gethostname, Pidfile):
        gethostname.return_value = 'e.com'
        self.prepare_pidfile_for_getpids(Pidfile)
        callback = Mock()

        p = NamespacedOptionParser(['foo', 'bar', 'baz'])
        nodes = self.t.getpids(p, 'celery worker', callback=callback)
        node_0, node_1 = nodes
        self.assertEqual(node_0[0], '*****@*****.**')
        self.assertEqual(
            sorted(node_0[1]),
            sorted(('celery worker', '--pidfile=foo.pid',
                    '-n [email protected]', '')),
        )
        self.assertEqual(node_0[2], 10)

        self.assertEqual(node_1[0], '*****@*****.**')
        self.assertEqual(
            sorted(node_1[1]),
            sorted(('celery worker', '--pidfile=bar.pid',
                    '-n [email protected]', '')),
        )
        self.assertEqual(node_1[2], 11)
        self.assertTrue(callback.called)
        cargs, _ = callback.call_args
        self.assertEqual(cargs[0], '*****@*****.**')
        self.assertItemsEqual(
            cargs[1],
            ['celery worker', '--pidfile=baz.pid', '-n [email protected]', ''],
        )
        self.assertIsNone(cargs[2])
        self.assertIn('DOWN', self.fh.getvalue())

        # without callback, should work
        nodes = self.t.getpids(p, 'celery worker', callback=None)

    @patch('celery.bin.multi.Pidfile')
    @patch('celery.bin.multi.gethostname')
    @patch('celery.bin.multi.sleep')
    def test_shutdown_nodes(self, slepp, gethostname, Pidfile):
        gethostname.return_value = 'e.com'
        self.prepare_pidfile_for_getpids(Pidfile)
        self.assertIsNone(self.t.shutdown_nodes([]))
        self.t.signal_node = Mock()
        node_alive = self.t.node_alive = Mock()
        self.t.node_alive.return_value = False

        callback = Mock()
        self.t.stop(['foo', 'bar', 'baz'], 'celery worker', callback=callback)
        sigs = sorted(self.t.signal_node.call_args_list)
        self.assertEqual(len(sigs), 2)
        self.assertIn(
            ('*****@*****.**', 10, signal.SIGTERM),
            {tup[0] for tup in sigs},
        )
        self.assertIn(
            ('*****@*****.**', 11, signal.SIGTERM),
            {tup[0] for tup in sigs},
        )
        self.t.signal_node.return_value = False
        self.assertTrue(callback.called)
        self.t.stop(['foo', 'bar', 'baz'], 'celery worker', callback=None)

        def on_node_alive(pid):
            if node_alive.call_count > 4:
                return True
            return False
        self.t.signal_node.return_value = True
        self.t.node_alive.side_effect = on_node_alive
        self.t.stop(['foo', 'bar', 'baz'], 'celery worker', retry=True)

    @patch('os.kill')
    def test_node_alive(self, kill):
        kill.return_value = True
        self.assertTrue(self.t.node_alive(13))
        esrch = OSError()
        esrch.errno = errno.ESRCH
        kill.side_effect = esrch
        self.assertFalse(self.t.node_alive(13))
        kill.assert_called_with(13, 0)

        enoent = OSError()
        enoent.errno = errno.ENOENT
        kill.side_effect = enoent
        with self.assertRaises(OSError):
            self.t.node_alive(13)

    @patch('os.kill')
    def test_signal_node(self, kill):
        kill.return_value = True
        self.assertTrue(self.t.signal_node('foo', 13, 9))
        esrch = OSError()
        esrch.errno = errno.ESRCH
        kill.side_effect = esrch
        self.assertFalse(self.t.signal_node('foo', 13, 9))
        kill.assert_called_with(13, 9)
        self.assertIn('Could not signal foo', self.fh.getvalue())

        enoent = OSError()
        enoent.errno = errno.ENOENT
        kill.side_effect = enoent
        with self.assertRaises(OSError):
            self.t.signal_node('foo', 13, 9)

    def test_start(self):
        self.t.waitexec = Mock()
        self.t.waitexec.return_value = 0
        self.assertFalse(self.t.start(['foo', 'bar', 'baz'], 'celery worker'))

        self.t.waitexec.return_value = 1
        self.assertFalse(self.t.start(['foo', 'bar', 'baz'], 'celery worker'))

    def test_show(self):
        self.t.show(['foo', 'bar', 'baz'], 'celery worker')
        self.assertTrue(self.fh.getvalue())

    @patch('celery.bin.multi.gethostname')
    def test_get(self, gethostname):
        gethostname.return_value = 'e.com'
        self.t.get(['*****@*****.**', 'foo', 'bar', 'baz'], 'celery worker')
        self.assertFalse(self.fh.getvalue())
        self.t.get(['*****@*****.**', 'foo', 'bar', 'baz'], 'celery worker')
        self.assertTrue(self.fh.getvalue())

    @patch('celery.bin.multi.gethostname')
    def test_names(self, gethostname):
        gethostname.return_value = 'e.com'
        self.t.names(['foo', 'bar', 'baz'], 'celery worker')
        self.assertIn('[email protected]\[email protected]\[email protected]', self.fh.getvalue())

    def test_execute_from_commandline(self):
        start = self.t.commands['start'] = Mock()
        self.t.error = Mock()
        self.t.execute_from_commandline(['multi', 'start', 'foo', 'bar'])
        self.assertFalse(self.t.error.called)
        start.assert_called_with(['foo', 'bar'], 'celery worker')

        self.t.error = Mock()
        self.t.execute_from_commandline(['multi', 'frob', 'foo', 'bar'])
        self.t.error.assert_called_with('Invalid command: frob')

        self.t.error = Mock()
        self.t.execute_from_commandline(['multi'])
        self.t.error.assert_called_with()

        self.t.error = Mock()
        self.t.execute_from_commandline(['multi', '-foo'])
        self.t.error.assert_called_with()

        self.t.execute_from_commandline(
            ['multi', 'start', 'foo',
             '--nosplash', '--quiet', '-q', '--verbose', '--no-color'],
        )
        self.assertTrue(self.t.nosplash)
        self.assertTrue(self.t.quiet)
        self.assertTrue(self.t.verbose)
        self.assertTrue(self.t.no_color)

    def test_stopwait(self):
        self.t._stop_nodes = Mock()
        self.t.stopwait(['foo', 'bar', 'baz'], 'celery worker')
        self.assertEqual(self.t._stop_nodes.call_args[1]['retry'], 2)

    @patch('celery.bin.multi.MultiTool')
    def test_main(self, MultiTool):
        m = MultiTool.return_value = Mock()
        with self.assertRaises(SystemExit):
            main()
        m.execute_from_commandline.assert_called_with(sys.argv)
Example #37
0
 def setup(self):
     self.out = WhateverIO()
     self.dumper = Dumper(out=self.out)
Example #38
0
 def test_run(self):
     out = WhateverIO()
     r = report(app=self.app, stdout=out)
     self.assertEqual(r.run(), EX_OK)
     self.assertTrue(out.getvalue())
Example #39
0
 def test_run(self):
     out = WhateverIO()
     r = report(app=self.app, stdout=out)
     assert r.run() == EX_OK
     assert out.getvalue()
Example #40
0
 def test_to_dot(self):
     s = WhateverIO()
     self.graph1().to_dot(s)
     assert s.getvalue()
Example #41
0
 def setup(self):
     self.out = WhateverIO()
     self.err = WhateverIO()
     self.cmd = Command(self.app, stdout=self.out, stderr=self.err)
Example #42
0
class test_MultiTool_functional(AppCase):
    def setup(self):
        self.fh = WhateverIO()
        self.env = {}
        self.t = MultiTool(env=self.env, fh=self.fh)

    def test_note(self):
        self.t.note('hello world')
        self.assertEqual(self.fh.getvalue(), 'hello world\n')

    def test_note_quiet(self):
        self.t.quiet = True
        self.t.note('hello world')
        self.assertFalse(self.fh.getvalue())

    def test_carp(self):
        self.t.say = Mock()
        self.t.carp('foo')
        self.t.say.assert_called_with('foo', True, self.t.stderr)

    def test_info(self):
        self.t.verbose = True
        self.t.info('hello info')
        self.assertEqual(self.fh.getvalue(), 'hello info\n')

    def test_info_not_verbose(self):
        self.t.verbose = False
        self.t.info('hello info')
        self.assertFalse(self.fh.getvalue())

    def test_error(self):
        self.t.carp = Mock()
        self.t.usage = Mock()
        self.assertEqual(self.t.error('foo'), 1)
        self.t.carp.assert_called_with('foo')
        self.t.usage.assert_called_with()

        self.t.carp = Mock()
        self.assertEqual(self.t.error(), 1)
        self.t.carp.assert_not_called()

    def test_nosplash(self):
        self.t.nosplash = True
        self.t.splash()
        self.assertFalse(self.fh.getvalue())

    def test_splash(self):
        self.t.nosplash = False
        self.t.splash()
        self.assertIn('celery multi', self.fh.getvalue())

    def test_usage(self):
        self.t.usage()
        self.assertTrue(self.fh.getvalue())

    def test_help(self):
        self.t.help([])
        self.assertIn(doc, self.fh.getvalue())

    def test_expand(self):
        self.t.expand('foo%n', 'ask', 'klask', 'dask')
        self.assertEqual(
            self.fh.getvalue(),
            'fooask\nfooklask\nfoodask\n',
        )

    @patch('celery.apps.multi.gethostname')
    def test_get(self, gethostname):
        gethostname.return_value = 'e.com'
        self.t.get('*****@*****.**', 'foo', 'bar', 'baz')
        self.assertFalse(self.fh.getvalue())
        self.t.get('*****@*****.**', 'foo', 'bar', 'baz')
        self.assertTrue(self.fh.getvalue())

    @patch('celery.apps.multi.gethostname')
    def test_names(self, gethostname):
        gethostname.return_value = 'e.com'
        self.t.names('foo', 'bar', 'baz')
        self.assertIn('[email protected]\[email protected]\[email protected]', self.fh.getvalue())

    def test_execute_from_commandline(self):
        start = self.t.commands['start'] = Mock()
        self.t.error = Mock()
        self.t.execute_from_commandline(['multi', 'start', 'foo', 'bar'])
        self.t.error.assert_not_called()
        start.assert_called_with('foo', 'bar')

        self.t.error = Mock()
        self.t.execute_from_commandline(['multi', 'frob', 'foo', 'bar'])
        self.t.error.assert_called_with('Invalid command: frob')

        self.t.error = Mock()
        self.t.execute_from_commandline(['multi'])
        self.t.error.assert_called_with()

        self.t.error = Mock()
        self.t.execute_from_commandline(['multi', '-foo'])
        self.t.error.assert_called_with()

        self.t.execute_from_commandline([
            'multi', 'start', 'foo', '--nosplash', '--quiet', '-q',
            '--verbose', '--no-color'
        ], )
        self.assertTrue(self.t.nosplash)
        self.assertTrue(self.t.quiet)
        self.assertTrue(self.t.verbose)
        self.assertTrue(self.t.no_color)

    @patch('celery.bin.multi.MultiTool')
    def test_main(self, MultiTool):
        m = MultiTool.return_value = Mock()
        with self.assertRaises(SystemExit):
            main()
        m.execute_from_commandline.assert_called_with(sys.argv)
Example #43
0
 def setup(self):
     self.fh = WhateverIO()
     self.env = {}
     self.t = MultiTool(env=self.env, fh=self.fh)
Example #44
0
class test_MultiTool_functional(AppCase):

    def setup(self):
        self.fh = WhateverIO()
        self.env = {}
        self.t = MultiTool(env=self.env, fh=self.fh)

    def test_note(self):
        self.t.note('hello world')
        self.assertEqual(self.fh.getvalue(), 'hello world\n')

    def test_note_quiet(self):
        self.t.quiet = True
        self.t.note('hello world')
        self.assertFalse(self.fh.getvalue())

    def test_carp(self):
        self.t.say = Mock()
        self.t.carp('foo')
        self.t.say.assert_called_with('foo', True, self.t.stderr)

    def test_info(self):
        self.t.verbose = True
        self.t.info('hello info')
        self.assertEqual(self.fh.getvalue(), 'hello info\n')

    def test_info_not_verbose(self):
        self.t.verbose = False
        self.t.info('hello info')
        self.assertFalse(self.fh.getvalue())

    def test_error(self):
        self.t.carp = Mock()
        self.t.usage = Mock()
        self.assertEqual(self.t.error('foo'), 1)
        self.t.carp.assert_called_with('foo')
        self.t.usage.assert_called_with()

        self.t.carp = Mock()
        self.assertEqual(self.t.error(), 1)
        self.t.carp.assert_not_called()

    def test_nosplash(self):
        self.t.nosplash = True
        self.t.splash()
        self.assertFalse(self.fh.getvalue())

    def test_splash(self):
        self.t.nosplash = False
        self.t.splash()
        self.assertIn('celery multi', self.fh.getvalue())

    def test_usage(self):
        self.t.usage()
        self.assertTrue(self.fh.getvalue())

    def test_help(self):
        self.t.help([])
        self.assertIn(doc, self.fh.getvalue())

    def test_expand(self):
        self.t.expand('foo%n', 'ask', 'klask', 'dask')
        self.assertEqual(
            self.fh.getvalue(), 'fooask\nfooklask\nfoodask\n',
        )

    @patch('celery.apps.multi.gethostname')
    def test_get(self, gethostname):
        gethostname.return_value = 'e.com'
        self.t.get('*****@*****.**', 'foo', 'bar', 'baz')
        self.assertFalse(self.fh.getvalue())
        self.t.get('*****@*****.**', 'foo', 'bar', 'baz')
        self.assertTrue(self.fh.getvalue())

    @patch('celery.apps.multi.gethostname')
    def test_names(self, gethostname):
        gethostname.return_value = 'e.com'
        self.t.names('foo', 'bar', 'baz')
        self.assertIn('[email protected]\[email protected]\[email protected]', self.fh.getvalue())

    def test_execute_from_commandline(self):
        start = self.t.commands['start'] = Mock()
        self.t.error = Mock()
        self.t.execute_from_commandline(['multi', 'start', 'foo', 'bar'])
        self.t.error.assert_not_called()
        start.assert_called_with('foo', 'bar')

        self.t.error = Mock()
        self.t.execute_from_commandline(['multi', 'frob', 'foo', 'bar'])
        self.t.error.assert_called_with('Invalid command: frob')

        self.t.error = Mock()
        self.t.execute_from_commandline(['multi'])
        self.t.error.assert_called_with()

        self.t.error = Mock()
        self.t.execute_from_commandline(['multi', '-foo'])
        self.t.error.assert_called_with()

        self.t.execute_from_commandline(
            ['multi', 'start', 'foo',
             '--nosplash', '--quiet', '-q', '--verbose', '--no-color'],
        )
        self.assertTrue(self.t.nosplash)
        self.assertTrue(self.t.quiet)
        self.assertTrue(self.t.verbose)
        self.assertTrue(self.t.no_color)

    @patch('celery.bin.multi.MultiTool')
    def test_main(self, MultiTool):
        m = MultiTool.return_value = Mock()
        with self.assertRaises(SystemExit):
            main()
        m.execute_from_commandline.assert_called_with(sys.argv)