Ejemplo n.º 1
0
def test_event_order_is_correct_for_multiple_publishes():
    stream = AsyncSingleStream()
    send_important_email, subscription = create_subscription(stream,
                                                             disconnect=False)

    payload = []

    fut1 = asyncio.ensure_future(p_subscribe(payload, subscription))
    fut2 = asyncio.ensure_future(
        send_important_email(
            Email(
                from_='*****@*****.**',
                subject='Message',
                message='Tests are good',
                unread=True,
            )))
    fut3 = asyncio.ensure_future(
        send_important_email(
            Email(
                from_='*****@*****.**',
                subject='Message 2',
                message='Tests are good 2',
                unread=True,
            )))

    asyncio.get_event_loop().run_until_complete(fut2)
    asyncio.get_event_loop().run_until_complete(fut3)
    asyncio.get_event_loop().run_until_complete(stream.aclose())

    expected_payload1 = {
        'importantEmail': {
            'email': {
                'from': '*****@*****.**',
                'subject': 'Message',
            },
            'inbox': {
                'unread': 1,
                'total': 2,
            },
        }
    }

    expected_payload2 = {
        'importantEmail': {
            'email': {
                'from': '*****@*****.**',
                'subject': 'Message 2',
            },
            'inbox': {
                'unread': 2,
                'total': 3,
            },
        }
    }

    assert len(payload) == 2
    print(payload)
    assert payload[0].data == expected_payload1
    assert payload[1].data == expected_payload2
Ejemplo n.º 2
0
    async def __asubscribe__(self, sink: AsyncObserver) -> AsyncSingleStream:
        stream = AsyncSingleStream()

        def cancel(sub):
            if self._subscription is not None:
                self._subscription.cancel()

            if self._task is not None:
                self._task.cancel()
        stream.add_done_callback(cancel)

        self._task = asyncio.ensure_future(self.worker(sink))
        return stream
Ejemplo n.º 3
0
def test_accepts_type_definition_with_sync_subscribe_function():
    SubscriptionType = GraphQLObjectType(
        name='Subscription',
        fields=OrderedDict([
            ('importantEmail',
             GraphQLField(
                 EmailEventType,
                 resolver=lambda *_: AsyncObservable.from_iterable([None]))),
        ]))
    test_schema = GraphQLSchema(query=QueryType, subscription=SubscriptionType)

    stream = AsyncSingleStream()
    send_important_email, subscription = create_subscription(
        stream, test_schema)

    email = Email(
        from_='*****@*****.**',
        subject='Alright',
        message='Tests are good',
        unread=True,
    )
    l = []

    fut1 = asyncio.ensure_future(p_subscribe(l, stream))
    fut2 = asyncio.ensure_future(send_important_email(email))

    asyncio.get_event_loop().run_until_complete(asyncio.gather(fut1, fut2))

    assert l  # [0].data == {'importantEmail': None}
Ejemplo n.º 4
0
def test_accepts_multiple_subscription_fields_defined_in_schema():
    SubscriptionTypeMultiple = GraphQLObjectType(
        name='Subscription',
        fields=OrderedDict([
            ('importantEmail', GraphQLField(EmailEventType)),
            ('nonImportantEmail', GraphQLField(EmailEventType)),
        ]))
    test_schema = GraphQLSchema(query=QueryType,
                                subscription=SubscriptionTypeMultiple)

    stream = AsyncSingleStream()
    send_important_email, subscription = create_subscription(
        stream, test_schema)

    email = Email(
        from_='*****@*****.**',
        subject='Alright',
        message='Tests are good',
        unread=True,
    )
    l = []

    fut1 = asyncio.ensure_future(p_subscribe(l, stream))
    fut2 = asyncio.ensure_future(send_important_email(email))

    asyncio.get_event_loop().run_until_complete(asyncio.gather(fut1, fut2))
    assert l[0][0] == email
Ejemplo n.º 5
0
    async def __asubscribe__(self, sink: AsyncObserver) -> AsyncSingleStream:
        task = None

        def cancel(sub):
            task.cancel()

        sub = AsyncSingleStream()
        sub.add_done_callback(cancel)

        async def async_worker() -> None:
            async for value in self.iterable:
                try:
                    await sink.asend(value)
                except Exception as ex:
                    await sink.athrow(ex)
                    return

            await sink.aclose()

        async def sync_worker() -> None:
            log.debug("sync_worker()")
            for value in self.iterable:
                try:
                    log.debug("sync_worker. asending: %s" % value)
                    await sink.asend(value)
                except Exception as ex:
                    await sink.athrow(ex)
                    return

            await sink.aclose()

        if hasattr(self.iterable, "__aiter__"):
            worker = async_worker
        elif hasattr(self.iterable, "__iter__"):
            worker = sync_worker
        else:
            raise ValueError("Argument must be iterable or async iterable.")

        try:
            task = asyncio.ensure_future(worker())
        except Exception as ex:
            log.debug("FromIterable:worker(), Exception: %s" % ex)
            await sink.athrow(ex)
        return sub
Ejemplo n.º 6
0
def test_throws_an_error_if_subscribe_does_not_return_an_iterator():
    SubscriptionType = GraphQLObjectType(name='Subscription',
                                         fields=OrderedDict([
                                             ('importantEmail',
                                              GraphQLField(
                                                  EmailEventType,
                                                  resolver=lambda *_: None)),
                                         ]))
    test_schema = GraphQLSchema(query=QueryType, subscription=SubscriptionType)

    stream = AsyncSingleStream()
    _, subscription = create_subscription(stream, test_schema)

    assert str(
        subscription.errors[0]
    ) == 'Subscription must return an AsyncObservable. Received: None'
Ejemplo n.º 7
0
    async def __asubscribe__(self, observer) -> AsyncSingleStream:
        """Start streaming."""
        async def worker(value) -> None:
            """Task for sending value."""

            try:
                log.debug("Unit:__asubscribe__:worker:sending: %s", value)
                await observer.asend(value)
            except Exception as ex:
                try:
                    await observer.athrow(ex)
                except Exception as ex:
                    log.error("Unhandled exception: ", ex)
                    return

            await observer.aclose()

        async def done() -> None:
            """Called when future resolves."""

            try:
                value = self._value.result()
            except asyncio.CancelledError:
                await observer.aclose()
            except Exception as ex:
                try:
                    await observer.athrow(ex)
                except Exception as ex:
                    log.error("Unhandled exception: ", ex)
                    return
            else:
                await worker(value)

        def done_callback(fut):
            asyncio.ensure_future(done())

        fut = AsyncSingleStream()

        # Check if plain value or Future (async value)
        if hasattr(self._value, "add_done_callback"):
            self._value.add_done_callback(done_callback)
            return chain_future(fut, self._value)
        else:
            asyncio.ensure_future(worker(self._value))

        log.debug("Unit:done")
        return fut
Ejemplo n.º 8
0
 async def __asubscribe__(self, observer: AsyncObserver) -> AsyncSingleStream:
     return AsyncSingleStream()
Ejemplo n.º 9
0
def test_produces_a_payload_per_subscription_event():
    stream = AsyncSingleStream()
    send_important_email, subscription = create_subscription(stream,
                                                             disconnect=False)

    payload = []

    fut1 = asyncio.ensure_future(p_subscribe(payload, subscription))
    fut = asyncio.ensure_future(
        send_important_email(
            Email(
                from_='*****@*****.**',
                subject='Alright',
                message='Tests are good',
                unread=True,
            )))
    expected_payload = {
        'importantEmail': {
            'email': {
                'from': '*****@*****.**',
                'subject': 'Alright',
            },
            'inbox': {
                'unread': 1,
                'total': 2,
            },
        }
    }
    asyncio.get_event_loop().run_until_complete(asyncio.gather(fut1, fut))

    assert len(payload) == 1
    assert payload[0].data == expected_payload

    fut = asyncio.ensure_future(
        send_important_email(
            Email(
                from_='*****@*****.**',
                subject='Tools',
                message='I <3 making things',
                unread=True,
            )))
    expected_payload = {
        'importantEmail': {
            'email': {
                'from': '*****@*****.**',
                'subject': 'Tools',
            },
            'inbox': {
                'unread': 2,
                'total': 3,
            },
        }
    }

    asyncio.get_event_loop().run_until_complete(asyncio.gather(fut1, fut))

    assert len(payload) == 2
    assert payload[-1].data == expected_payload

    # The client decides to disconnect
    asyncio.get_event_loop().run_until_complete(stream.aclose())

    fut = asyncio.ensure_future(
        send_important_email(
            Email(
                from_='*****@*****.**',
                subject='Important',
                message='Read me please',
                unread=True,
            )))

    asyncio.get_event_loop().run_until_complete(asyncio.gather(fut1, fut))
    assert len(payload) == 2