2020-03-14 19:48:12 +03:00
|
|
|
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
|
2020-03-14 19:48:12 +03:00
|
|
|
|
|
|
|
|
|
|
|
class Query(ObjectType):
|
2020-07-11 13:51:04 +03:00
|
|
|
a = String()
|
2020-03-14 19:48:12 +03:00
|
|
|
|
2020-07-11 13:51:04 +03:00
|
|
|
|
|
|
|
class SubscriptionOptions(ObjectTypeOptions):
|
|
|
|
pass
|
2020-03-14 19:48:12 +03:00
|
|
|
|
|
|
|
|
|
|
|
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-03-14 19:48:12 +03:00
|
|
|
|
2020-07-11 13:51:04 +03:00
|
|
|
async def subscribe(root, info):
|
2020-03-14 19:48:12 +03:00
|
|
|
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)
|
2020-03-14 19:48:12 +03:00
|
|
|
|
|
|
|
|
|
|
|
@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
|