예제 #1
0
    async def test_wrap_listeners_context(self) -> None:
        mock = Mock()

        with emitter.context() as ctx:
            listeners = ctx.wrap_listeners(Global)

        emitter.on("test", listeners, mock)

        self.assertTrue(await emitter.emit(None, Global, scope="test"))
        mock.assert_called_once_with(None)
        mock.reset_mock()

        self.assertTrue(await emitter.emit(None, listeners, scope="test"))
        mock.assert_called_once_with(None)
        mock.reset_mock()

        self.assertTrue(emitter.remove("test", Global, mock, ctx))
        self.assertFalse(await emitter.emit(None, Global, scope="test"))
        self.assertFalse(await emitter.emit(None, listeners, scope="test"))
        mock.assert_not_called()

        emitter.on("test", listeners, mock)

        self.assertTrue(await emitter.emit(None, Global, scope="test"))
        mock.assert_called_once_with(None)
        mock.reset_mock()

        self.assertTrue(await emitter.emit(None, listeners, scope="test"))
        mock.assert_called_once_with(None)
        mock.reset_mock()

        self.assertTrue(emitter.remove("test", listeners, mock))
        self.assertFalse(await emitter.emit(None, Global, scope="test"))
        self.assertFalse(await emitter.emit(None, listeners, scope="test"))
        mock.assert_not_called()
예제 #2
0
 async def async_main_listener1(_: T.Any) -> None:
     await asyncio.sleep(0)
     emitter.on(object, Global, lambda x: mock(5), scope="test")
     emitter.remove(None,
                    Global,
                    async_main_listener1,
                    scope="test")
예제 #3
0
    async def test_once_fail_context(self) -> None:
        mock = Mock()

        with self.assertRaisesRegex(
                ValueError, "Can't use context manager with a once listener"):
            emitter.on(Event, Global, mock, once=True, context=True)

        self.assertFalse(await emitter.emit(Event("0"), Global))
        mock.assert_not_called()
예제 #4
0
    async def test_listener_simple(self) -> None:
        listener = Mock()

        emitter.on(Event, Global, listener)

        e = Event("Wowow")
        self.assertTrue(await emitter.emit(e, Global))

        listener.assert_called_once_with(e)
예제 #5
0
    async def test_invalid_types_object(self) -> None:
        mock = Mock()

        with self.assertRaises(ValueError):
            emitter.on(object, Global, mock)

        with self.assertRaises(ValueError):
            await emitter.emit(object(), Global)

        mock.assert_not_called()
예제 #6
0
    async def test_invalid_types_base_exp(self) -> None:
        mock = Mock()

        with self.assertRaises(ValueError):
            emitter.on(BaseException, Global, mock)

        with self.assertRaises(BaseException):
            await emitter.emit(BaseException(), Global)

        mock.assert_not_called()
예제 #7
0
    async def test_superclass_listeners(self) -> None:
        class Event2(Event):
            pass

        mock = Mock()

        emitter.on(Event, Global, mock)

        e = Event2("")
        await emitter.emit(e, Global)

        mock.assert_called_once_with(e)
예제 #8
0
    async def test_invalid_types_base_exp_subclass(self) -> None:
        mock = Mock()

        class Exp(BaseException):
            pass

        with self.assertRaises(ValueError):
            emitter.on(Exp, Global, mock)

        with self.assertRaises(Exp):
            await emitter.emit(Exp(), Global)

        mock.assert_not_called()
예제 #9
0
    async def test_slotted_class_with_loop(self) -> None:
        mock = Mock()
        event = Event("")

        class Listener:
            __slots__ = tuple()

            def __call__(self, e: Event) -> None:
                mock(e)

        emitter.on(Event, Global, Listener(), loop=self.loop)
        self.assertTrue(await emitter.emit(event, Global))
        mock.assert_called_once_with(event)
예제 #10
0
    async def test_invalid_types_metaclass(self) -> None:
        mock = Mock()

        class Meta(type):
            pass

        with self.assertRaises(ValueError):
            emitter.on(Meta, Global, mock)

        with self.assertRaises(ValueError):
            await emitter.emit(Meta("", tuple(), {}), Global)

        mock.assert_not_called()
예제 #11
0
    async def test_emit_none(self) -> None:
        mock = Mock()
        emitter.on("test", Global, mock)

        with self.assertRaisesRegex(
                ValueError,
                "Event type can only be None when accompanied of a scope"):
            await emitter.emit(None, Global)

        mock.assert_not_called()

        self.assertTrue(await emitter.emit(None, Global, scope="test"))

        mock.assert_called_once_with(None)
예제 #12
0
    async def test_listener_callable_class(self) -> None:
        mock = Mock()
        this = self

        class Listener:
            def __call__(self, event: Event) -> None:
                this.assertEqual("Wowow", event.data)
                mock(event)

        emitter.on(Event, Global, Listener())

        e = Event("Wowow")
        self.assertTrue(await emitter.emit(e, Global))

        mock.assert_called_once_with(e)
예제 #13
0
    async def test_once_emit_after_remove(self) -> None:
        mock = Mock()

        emitter.on(Event, Global, mock, once=True)
        emitter.remove(None, Global)

        e = Event("0")
        results = await asyncio.gather(
            emitter.emit(e, Global),
            emitter.emit(e, Global),
            emitter.emit(e, Global),
            emitter.emit(e, Global),
            emitter.emit(e, Global),
        )
        self.assertListEqual([False, False, False, False, False], results)
        mock.assert_not_called()
예제 #14
0
    async def test_once(self) -> None:
        mock = Mock()

        emitter.on(Event, Global, mock, once=True)

        e = Event("0")
        self.assertTrue(await emitter.emit(e, Global))
        mock.assert_called_once_with(e)
        mock.reset_mock()

        self.assertFalse(await emitter.emit(Event("1"), Global))
        mock.assert_not_called()

        self.assertFalse(await emitter.emit(Event("2"), Global))
        mock.assert_not_called()

        self.assertFalse(await emitter.emit(Event("3"), Global))
        mock.assert_not_called()
예제 #15
0
    async def test_once_emit_before_remove(self) -> None:
        e = Event("0")
        mock = Mock()

        emitter.on(Event, Global, mock, once=True)
        emit_task = asyncio.gather(
            emitter.emit(e, Global),
            emitter.emit(e, Global),
            emitter.emit(e, Global),
            emitter.emit(e, Global),
            emitter.emit(e, Global),
        )
        emitter.remove(None, Global)

        results = await emit_task
        self.assertIn(True, results)
        results.remove(True)
        self.assertListEqual([False, False, False, False], results)
        mock.assert_called_once_with(e)
예제 #16
0
    def test_invalid_types_not_callable(self) -> None:
        with self.assertRaisesRegex(ValueError, "Listener must be callable"):
            emitter.on(str, Global, "")

        with self.assertRaisesRegex(ValueError, "Listener must be callable"):
            emitter.on(str, Global, 1)

        with self.assertRaisesRegex(ValueError, "Listener must be callable"):
            emitter.on(str, Global, [])

        with self.assertRaisesRegex(ValueError, "Listener must be callable"):
            emitter.on(str, Global, {})
예제 #17
0
    async def test_listener_handle_raise_error(self) -> None:
        exc = RuntimeError("Ooops...")
        mock = Mock()
        mock1 = Mock()

        self.loop.set_exception_handler(mock1)

        @emitter.on(Event, Global, raise_on_exc=True)
        async def listener(_: T.Any) -> None:
            await asyncio.sleep(0)
            raise exc

        emitter.on(RuntimeError, listener, mock)

        await emitter.emit(Event("Wowow"), Global)

        # Allow the loop to cycle once
        await asyncio.sleep(0)
        mock1.assert_not_called()
        mock.assert_called_once_with(exc)
예제 #18
0
    async def test_listener_context(self) -> None:
        listener = Mock()

        ctx = emitter.on(Event, Global, listener, context=True)
        self.assertIsInstance(ctx, T.ContextManager)
        with ctx:
            e = Event("Wowow")
            self.assertTrue(await emitter.emit(e, Global))

            listener.assert_called_once_with(e)

        self.assertFalse(emitter.remove(Event, Global, listener))
예제 #19
0
    async def test_listener_coro_handle_error(self) -> None:
        exc = RuntimeError("Ooops...")
        mock = Mock()
        future_error = self.loop.create_future()

        @self.loop.set_exception_handler
        def handle_error(_, ctx) -> None:
            future_error.set_exception(ctx["exception"])

        @emitter.on(Event, Global)
        async def listener(_: T.Any) -> None:
            await asyncio.sleep(0)
            raise exc

        emitter.on(RuntimeError, listener, mock)

        await emitter.emit(Event("Wowow"), Global)

        # Allow the loop to cycle once
        await asyncio.sleep(0)
        self.assertFalse(future_error.done())

        mock.assert_called_once_with(exc)
예제 #20
0
    async def test_listener_cancellation(self) -> None:
        mock = Mock()
        future_error = self.loop.create_future()

        @self.loop.set_exception_handler
        def handle_error(_, ctx) -> None:
            future_error.set_exception(ctx["exception"])

        @emitter.on(Event, Global)
        def listener(_: T.Any) -> None:
            fut = self.loop.create_future()
            fut.cancel()
            return fut

        emitter.on(Event, Global, mock)

        e = Event("Wowow")
        await emitter.emit(e, Global)

        with self.assertRaises(CancelledError):
            await future_error

        mock.assert_called_once_with(e)
예제 #21
0
    async def test_context_stack(self) -> None:
        mock = Mock()

        with emitter.context() as ctx0:
            emitter.on("test", Global, lambda x: mock(1))

            @emitter.on("test", Global)
            async def async_main_listener0(_: T.Any) -> None:
                await asyncio.sleep(0)
                emitter.on("test", Global, lambda x: mock(2))
                emitter.remove("test", Global, async_main_listener0)

        with emitter.context() as ctx1:
            emitter.on("test", Global, lambda x: mock(3))

            with emitter.context() as ctx2:
                emitter.on("test", Global, lambda x: mock(4))

            with emitter.context():

                @emitter.on("test", Global)
                async def async_main_listener1(_: T.Any) -> None:
                    await asyncio.sleep(0)
                    emitter.on("test", Global, lambda x: mock(5))
                    emitter.remove("test", Global, async_main_listener1)

                with emitter.context():
                    emitter.on("test", Global, lambda x: mock(6))

        with emitter.context() as ctx3:
            listener0 = ctx3.wrap_listeners(Global)

        with emitter.context():
            emitter.on("test", listener0, lambda x: mock(7))

            with emitter.context() as ctx5:
                listener1 = ctx5.wrap_listeners(Global)

            @emitter.on("test", Global)
            async def setup_remove(_: T.Any) -> None:
                await asyncio.sleep(0)
                emitter.remove("test", Global)

        emitter.on("test", listener1, lambda x: mock(8))

        self.assertTrue(await emitter.emit(None, Global, scope="test"))
        mock.assert_has_calls(
            [call(1), call(3),
             call(4), call(6),
             call(7), call(8)])
        mock.reset_mock()
        self.assertTrue(await emitter.emit(None, Global, scope="test"))
        mock.assert_has_calls(
            [call(1), call(3),
             call(4), call(6),
             call(2), call(5)])
        mock.reset_mock()
        emitter.remove(None, Global, context=ctx2)
        self.assertTrue(await emitter.emit(None, Global, scope="test"))
        mock.assert_has_calls([call(1), call(3), call(6), call(2), call(5)])
        mock.reset_mock()
        emitter.remove(None, Global, context=ctx0)
        self.assertTrue(await emitter.emit(None, Global, scope="test"))
        mock.assert_has_calls([call(3), call(6), call(5)])
        mock.reset_mock()
        emitter.remove(None, Global, context=ctx1)
        self.assertFalse(await emitter.emit(None, Global, scope="test"))
        mock.assert_not_called()
예제 #22
0
 async def async_main_listener1(_: T.Any) -> None:
     await asyncio.sleep(0)
     emitter.on("test", Global, lambda x: mock(5))
     emitter.remove("test", Global, async_main_listener1)
예제 #23
0
 def main_listener(_: T.Any) -> None:
     emitter.on(object, Global, mock, scope=scope)
예제 #24
0
 def main_listener(_: T.Any) -> None:
     emitter.on("test", Global, mock)
예제 #25
0
 def main_listener(_: T.Any) -> None:
     emitter.on(scope, Global, mock)
예제 #26
0
import emitter
import tkinter
import json

# key valid for 24 hours
key = "m6IK_VC94AAIqOVZZRe-x8NSED2PMfeg"
channel = "camarao-iot"

emitter = emitter.Emitter()

options = {"secure": True}
emitter.connect(options)
emitter.on("connect", lambda: print("Connected\n\n"))
emitter.on("disconnect", lambda: print("Disconnected\n\n"))
emitter.on("presence", lambda p: print("Presence message : '" + str(p) + "'\n\n"))
emitter.on("message", lambda m: print("Message received: " + m.asString() + "\n\n"))
emitter.loopStart()

emitter.publish(key, channel, json.dumps({"test": "test 123"}))

import time, sys

while True:
    try:
        time.sleep(.3)
    except KeyboardInterrupt:
        print("Shutting down...")
        emitter.unsubscribe(key, channel)
        emitter.loopStop()
        emitter.disconnect()
        sys.exit()
예제 #27
0
 async def async_main_listener(_: T.Any) -> None:
     await asyncio.sleep(0)
     emitter.on(object, Global, mock2, scope="test")
예제 #28
0
 async def async_main_listener(_: T.Any) -> None:
     await asyncio.sleep(0)
     emitter.on(scope, Global, mock2)
예제 #29
0
    async def test_listener_scope(self) -> None:
        mock = Mock()
        new_listener = Mock()

        emitter.on(emitter.NewListener,
                   Global,
                   lambda nl: new_listener(nl.type),
                   scope="scope.test")
        emitter.on(Event, Global, lambda _: mock(0))
        emitter.on(object, Global, lambda _: mock(1), scope="scope")
        emitter.on(Exception, Global, lambda _: mock(2), scope="scope")
        emitter.on(object, Global, lambda _: mock(3), scope="scope.test")
        emitter.on(object, Global, lambda _: mock(4), scope="scope...test.")
        emitter.on(RuntimeError,
                   Global,
                   lambda _: mock(5),
                   scope="scope.test.")
        emitter.on(object, Global, lambda _: mock(6), scope="scope.test.deep")
        emitter.on(object,
                   Global,
                   lambda _: mock(7),
                   scope="scope.test.deep.owo")
        emitter.on(ValueError,
                   Global,
                   lambda _: mock(8),
                   scope="scope..test....deep..owo.")
        emitter.on(object,
                   Global,
                   lambda _: mock(9),
                   scope="scope..test....deep..owo.")

        new_listener.assert_has_calls([
            call(object),
            call(object),
            call(RuntimeError),
            call(object),
            call(object),
            call(ValueError),
            call(object),
        ])
        new_listener.reset_mock()

        e = Event("Wowow")
        self.assertTrue(await emitter.emit(e, Global))
        mock.assert_called_once_with(0)
        mock.reset_mock()
        self.assertTrue(await
                        emitter.emit(e,
                                     Global,
                                     scope=("scope", "test", "deep", "owo")))
        mock.assert_has_calls(
            [call(7),
             call(9),
             call(6),
             call(3),
             call(4),
             call(1),
             call(0)])
        mock.reset_mock()
        self.assertTrue(await emitter.emit(e, Global, scope="..scope.test..."))
        mock.assert_has_calls([call(3), call(4), call(1), call(0)])
        mock.reset_mock()
        with self.assertRaises(ValueError):
            await emitter.emit(ValueError(), Global)
        self.assertTrue(await emitter.emit(ValueError(), Global,
                                           scope="scope"))
        mock.assert_has_calls([call(2)])
        mock.reset_mock()
        self.assertTrue(await
                        emitter.emit(RuntimeError(),
                                     Global,
                                     scope=("scope", "test", "deep", "owo")))
        mock.assert_has_calls([
            call(7),
            call(9),
            call(6),
            call(5),
            call(3),
            call(4),
            call(2),
            call(1)
        ])
        mock.reset_mock()
        self.assertTrue(await emitter.emit(ValueError(),
                                           Global,
                                           scope=".scope.test.deep.owo"))
        mock.assert_has_calls([
            call(8),
            call(7),
            call(9),
            call(6),
            call(3),
            call(4),
            call(2),
            call(1)
        ])
        mock.reset_mock()
        new_listener.assert_not_called()