graphene/tests_asyncio/test_subscribe.py

58 lines
1.4 KiB
Python
Raw Normal View History

from pytest import mark
2020-07-11 13:51:04 +03:00
from graphene import ObjectType, Int, String, Schema
from graphene.types.objecttype import ObjectTypeOptions
from graphene.utils.get_unbound_function import get_unbound_function
class Query(ObjectType):
2020-07-11 13:51:04 +03:00
a = String()
2020-07-11 13:51:04 +03:00
class SubscriptionOptions(ObjectTypeOptions):
pass
class Subscription(ObjectType):
2020-07-11 13:51:04 +03:00
@classmethod
def __init_subclass_with_meta__(
cls,
resolver=None,
_meta=None,
**options,
):
if not _meta:
_meta = SubscriptionOptions(cls)
if not resolver:
subscribe = getattr(cls, "subscribe", None)
assert subscribe, "The Subscribe class must define a subscribe method"
resolver = get_unbound_function(subscribe)
_meta.resolver = resolver
super().__init_subclass_with_meta__(_meta=_meta, **options)
class MySubscription(Subscription):
count_to_ten = Int()
2020-07-11 13:51:04 +03:00
async def subscribe(root, info):
count = 0
while count < 10:
count += 1
yield {"count_to_ten": count}
2020-07-11 13:51:04 +03:00
schema = Schema(query=Query, subscription=MySubscription)
@mark.asyncio
async def test_subscription():
subscription = "subscription { countToTen }"
result = await schema.subscribe(subscription)
count = 0
async for item in result:
count = item.data["countToTen"]
assert count == 10