示例#1
0
    def test_create(self, event_loop):
        """Smoketest that we can create a PubPen object"""
        pubpen = PubPen(event_loop)

        # Test internals were setup
        assert len(pubpen._event_handlers) == 0
        assert len(pubpen._event_list) == 0
示例#2
0
    def test_create_with_event_list(self, event_loop):
        """Test that creating a PubPen with an event_list stores the event_list"""
        pubpen = PubPen(event_loop, ['one', 'two'])

        # Test internals of saving the event_list worked
        assert len(pubpen._event_handlers) == 0
        assert len(pubpen._event_list) == 2
        assert 'one' in pubpen._event_list
        assert 'two' in pubpen._event_list
示例#3
0
def pubpen_multi_callback(event_loop):
    pubpen = PubPen(event_loop)

    # Fake up the internal data structures that unsubscribe uses
    pubpen._subscriptions[0] = 'test_event1'
    pubpen._subscriptions[1] = 'test_event1'
    pubpen._subscriptions[2] = 'test_event1'
    pubpen._event_handlers['test_event1'][0] = 'handler1'
    pubpen._event_handlers['test_event1'][1] = 'handler2'
    pubpen._event_handlers['test_event1'][2] = 'handler3'

    return pubpen
示例#4
0
async def start():
    if PY37:
        loop = asyncio.get_running_loop()
    else:
        loop = asyncio.get_event_loop()

    pubpen = PubPen(loop)
    server = Server(pubpen)
    # We create a client but never call it directly.  Instead, it subscribes to the `server_msg`
    # event and does something whenever that event occurs.
    client = Client(pubpen)

    await server.heartbeat()
示例#5
0
    def run(self):
        """
        Run the program.  This is the main entrypoint to the magnate client
        """
        # Create the statedir if it doesn't exist
        if not os.path.exists(self.cfg['state_dir']):
            os.makedirs(self.cfg['state_dir'])

        twiggy.dict_config(self.cfg['logging'])

        # Base data attributes
        self._load_data_definitions()

        ui_plugins = load('magnate.ui', subclasses=UserInterface)
        for UIClass in ui_plugins:  #pylint: disable=invalid-name
            if UIClass.__module__.startswith('magnate.ui.{}'.format(
                    self.cfg['ui_plugin'])):
                break
        else:
            print('Unknown user ui: {}'.format(self.cfg['ui_plugin']))
            return 1

        # Try using uvloop instead of the asyncio event loop
        if self.cfg['use_uvloop']:
            try:
                import uvloop
            except Exception:
                print(
                    'Could not import uvloop.  Falling back on asyncio event loop'
                )
            try:
                asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
            except Exception:
                print(
                    'Could not set uvloop to be the event loop.  Falling back on asyncio event loop'
                )

        loop = asyncio.get_event_loop()
        self.pubpen = PubPen(loop)
        self._setup_markets()
        self.dispatcher = Dispatcher(self, self.markets)

        # UIClass is always available because we'd have already returned (via
        # the for-else) if UIClass was not defined
        try:
            user_interface = UIClass(self.pubpen, self.cfg['ui_args'])  # pylint: disable=undefined-loop-variable
            return user_interface.run()
        except Exception as e:
            mlog.trace('error').error(
                'Exception raised while running the user interface')
            raise
示例#6
0
async def start():
    if PY37:
        loop = asyncio.get_running_loop()
    else:
        loop = asyncio.get_event_loop()

    queue = asyncio.Queue()
    loop.add_reader(sys.stdin, get_stdin_data, loop, queue)

    pubpen = PubPen(loop)
    server = Server(pubpen)
    client = Client(pubpen, queue)

    await asyncio.wait((client.await_input(), server.heartbeat()))
示例#7
0
def pubpen_handlers_dealloc(event_loop):
    pubpen = PubPen(event_loop)
    pubpen.loop = mock.MagicMock()
    pubpen._subscriptions[0] = 'test_event1'
    pubpen._subscriptions[1] = 'test_event1'
    # In the real code, we store a weakref to the handlers.  We use lambda
    # here to wrape the actual handler once to emulate the aspects of the
    # weakref that are important to this test
    pubpen._event_handlers['test_event1'][0] = lambda: handler1
    # But this one represents a weakref where the target has been deallocated.
    # In that case, calling the weakref returns None
    pubpen._event_handlers['test_event1'][1] = lambda: None
    return pubpen
示例#8
0
def pubpen(event_loop):
    pubpen = PubPen(event_loop)
    pubpen.loop = mock.MagicMock()
    # In the real code, we store a weakref to the handlers.  We use lambda
    # here to wrape the actual handler once to emulate the aspects of the
    # weakref that are important to this test
    pubpen._event_handlers['test_event1'][0] = lambda: handler1
    pubpen._event_handlers['test_event2'][1] = lambda: handler2
    pubpen._event_handlers['test_event2'][2] = lambda: handler3
    return pubpen
示例#9
0
def pubpen_handlers_partially_removed(event_loop):
    """
    The handler has been deallocated (because it's a weakref) but it's only
    been removed from the _subscriptions list already.
    """
    pubpen = PubPen(event_loop)
    pubpen.loop = mock.MagicMock()
    pubpen._subscriptions[0] = 'test_event1'
    # In the real code, we store a weakref to the handlers.  We use lambda
    # here to wrape the actual handler once to emulate the aspects of the
    # weakref that are important to this test
    pubpen._event_handlers['test_event1'][0] = lambda: handler1
    # But this one represents a weakref where the target has been deallocated.
    # In that case, calling the weakref returns None
    pubpen._event_handlers['test_event1'][1] = lambda: None
    return pubpen
示例#10
0
async def start():
    if PY37:
        loop = asyncio.get_running_loop()
    else:
        loop = asyncio.get_event_loop()

    pubpen = PubPen(loop)

    with Display(pubpen) as display:
        try:
            # try Client first
            connection = loop.create_unix_connection(
                partial(TalkProtocol, pubpen), PATH)
            await connection
        except (ConnectionRefusedError, FileNotFoundError):
            # server
            connection = loop.create_unix_server(partial(TalkProtocol, pubpen),
                                                 PATH)
            await connection

        while True:
            await display.get_ch()
示例#11
0
def pubpen(event_loop):
    pubpen = PubPen(event_loop)
    return pubpen
示例#12
0
def pubpen_partially_dealloc(event_loop):
    """The event handler has been partially removed already."""
    pubpen = PubPen(event_loop)
    pubpen._subscriptions[0] = 'test_event1'
    return pubpen
示例#13
0
def pubpen_predefined(event_loop):
    pubpen = PubPen(event_loop, event_list=['test_event1', 'test_event2'])
    pubpen.loop = mock.MagicMock()
    return pubpen
示例#14
0
async def setup_db(_app, loop):
    await sqlite.make_table()
    _app.event = PubPen(loop)
示例#15
0
def pubpen(request, event_loop):
    pubpen = PubPen(event_loop)
    return pubpen
示例#16
0
def pubpen_predefined(event_loop):
    pubpen = PubPen(event_loop, event_list=['test_event1', 'test_event2'])
    return pubpen
示例#17
0
    def data_received(self, data):
        self.pubpen.publish('incoming', data.decode('utf-8', errors='replace'),
                            "<you>")

    def error_received(self, exc):
        self.pubpen.publish('error', exc)

    def connection_lost(self, exc):
        self.pubpen.publish('conn_lost', exc)
        self.pubpen.loop.stop()


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    pubpen = PubPen(loop)

    with Display(pubpen) as display:
        try:
            # try Client first
            connection = loop.create_unix_connection(
                partial(TalkProtocol, pubpen), PATH)
            loop.run_until_complete(connection)
        except ConnectionRefusedError:
            # server
            connection = loop.create_unix_server(partial(TalkProtocol, pubpen),
                                                 PATH)
            loop.run_until_complete(connection)

        task = loop.create_task(display.get_ch())
        loop.run_forever()
示例#18
0
def pubpen_emit(event_loop):
    pubpen = PubPen(event_loop)
    pubpen.publish = mock.MagicMock()
    return pubpen