Debian Codegraph @

tests/test_user_registry.py

raw
1 """User registry demo.
2
3 This is an additional end-to-end test and demo for running the basic GraphQL
4 operations on a simulated user registry database backend.
5 """
6
7 from asyncio import sleep, wait
8 from collections import defaultdict
9 from enum import Enum
10 from inspect import isawaitable
11 from typing import Any, Dict, List, NamedTuple, Optional
12
13 try:
14 from asyncio import create_task
15 except ImportError: # Python < 3.7
16 create_task = None # type: ignore
17
18 from graphql import (
19 GraphQLArgument,
20 GraphQLBoolean,
21 GraphQLEnumType,
22 GraphQLField,
23 GraphQLID,
24 GraphQLInputField,
25 GraphQLInputObjectType,
26 GraphQLInt,
27 GraphQLNonNull,
28 GraphQLObjectType,
29 GraphQLSchema,
30 GraphQLString,
31 graphql,
32 parse,
33 subscribe,
34 )
35 from graphql.execution.map_async_iterator import MapAsyncIterator
36 from graphql.pyutils import SimplePubSub, SimplePubSubIterator
37 from pytest import fixture, mark
38
39
40 class User(NamedTuple):
41 """A simple user object class."""
42
43 firstName: str
44 lastName: str
45 tweets: Optional[int]
46 id: Optional[str] = None
47 verified: bool = False
48
49
50 class MutationEnum(Enum):
51 """Mutation event type"""
52
53 CREATED = "created"
54 UPDATED = "updated"
55 DELETED = "deleted"
56
57
58 class UserRegistry:
59 """Simulation of a user registry with asynchronous database backend access."""
60
61 def __init__(self, **users):
62 self._registry: Dict[str, User] = users
63 self._pubsub = defaultdict(SimplePubSub)
64
65 async def get(self, id_: str) -> Optional[User]:
66 """Get a user object from the registry"""
67 await sleep(0)
68 return self._registry.get(id_)
69
70 async def create(self, **kwargs) -> User:
71 """Create a user object in the registry"""
72 await sleep(0)
73 id_ = str(len(self._registry))
74 user = User(id=id_, **kwargs)
75 self._registry[id_] = user
76 self.emit_event(MutationEnum.CREATED, user)
77 return user
78
79 async def update(self, id_: str, **kwargs) -> User:
80 """Update a user object in the registry"""
81 await sleep(0)
82 # noinspection PyProtectedMember
83 user = self._registry[id_]._replace(**kwargs)
84 self._registry[id_] = user
85 self.emit_event(MutationEnum.UPDATED, user)
86 return user
87
88 async def delete(self, id_: str) -> User:
89 """Delete a user object in the registry"""
90 await sleep(0)
91 user = self._registry.pop(id_)
92 self.emit_event(MutationEnum.DELETED, user)
93 return user
94
95 def emit_event(self, mutation: MutationEnum, user: User) -> None:
96 """Emit mutation events for the given object and its class"""
97 payload = {"user": user, "mutation": mutation.value}
98 self._pubsub[None].emit(payload) # notify all user subscriptions
99 self._pubsub[user.id].emit(payload) # notify single user subscriptions
100
101 def event_iterator(self, id_: Optional[str]) -> SimplePubSubIterator:
102 return self._pubsub[id_].get_subscriber()
103
104
105 mutation_type = GraphQLEnumType("MutationType", MutationEnum)
106
107 user_type = GraphQLObjectType(
108 "UserType",
109 {
110 "id": GraphQLField(GraphQLNonNull(GraphQLID)),
111 "firstName": GraphQLField(GraphQLNonNull(GraphQLString)),
112 "lastName": GraphQLField(GraphQLNonNull(GraphQLString)),
113 "tweets": GraphQLField(GraphQLInt),
114 "verified": GraphQLField(GraphQLNonNull(GraphQLBoolean)),
115 },
116 )
117
118 user_input_type = GraphQLInputObjectType(
119 "UserInputType",
120 {
121 "firstName": GraphQLInputField(GraphQLNonNull(GraphQLString)),
122 "lastName": GraphQLInputField(GraphQLNonNull(GraphQLString)),
123 "tweets": GraphQLInputField(GraphQLInt),
124 "verified": GraphQLInputField(GraphQLBoolean),
125 },
126 )
127
128 subscription_user_type = GraphQLObjectType(
129 "SubscriptionUserType",
130 {"mutation": GraphQLField(mutation_type), "user": GraphQLField(user_type)},
131 )
132
133
134 async def resolve_user(_root, info, **args):
135 """Resolver function for fetching a user object"""
136 return await info.context["registry"].get(args["id"])
137
138
139 async def resolve_create_user(_root, info, data):
140 """Resolver function for creating a user object"""
141 user = await info.context["registry"].create(**data)
142 return user
143
144
145 # noinspection PyShadowingBuiltins
146 async def resolve_update_user(_root, info, id, data):
147 """Resolver function for updating a user object"""
148 user = await info.context["registry"].update(id, **data)
149 return user
150
151
152 # noinspection PyShadowingBuiltins
153 async def resolve_delete_user(_root, info, id):
154 """Resolver function for deleting a user object"""
155 user = await info.context["registry"].get(id)
156 await info.context["registry"].delete(user.id)
157 return True
158
159
160 # noinspection PyShadowingBuiltins
161 async def subscribe_user(_root, info, id=None):
162 """Subscribe to mutations of a specific user object or all user objects"""
163 async_iterator = info.context["registry"].event_iterator(id)
164 async for event in async_iterator:
165 yield await event if isawaitable(event) else event # pragma: no cover exit
166
167
168 # noinspection PyShadowingBuiltins,PyUnusedLocal
169 async def resolve_subscription_user(event, info, id):
170 """Resolver function for user subscriptions"""
171 user = event["user"]
172 mutation = MutationEnum(event["mutation"]).value
173 return {"user": user, "mutation": mutation}
174
175
176 schema = GraphQLSchema(
177 query=GraphQLObjectType(
178 "RootQueryType",
179 {
180 "User": GraphQLField(
181 user_type, args={"id": GraphQLArgument(GraphQLID)}, resolve=resolve_user
182 )
183 },
184 ),
185 mutation=GraphQLObjectType(
186 "RootMutationType",
187 {
188 "createUser": GraphQLField(
189 user_type,
190 args={"data": GraphQLArgument(GraphQLNonNull(user_input_type))},
191 resolve=resolve_create_user,
192 ),
193 "deleteUser": GraphQLField(
194 GraphQLBoolean,
195 args={"id": GraphQLArgument(GraphQLNonNull(GraphQLID))},
196 resolve=resolve_delete_user,
197 ),
198 "updateUser": GraphQLField(
199 user_type,
200 args={
201 "id": GraphQLArgument(GraphQLNonNull(GraphQLID)),
202 "data": GraphQLArgument(GraphQLNonNull(user_input_type)),
203 },
204 resolve=resolve_update_user,
205 ),
206 },
207 ),
208 subscription=GraphQLObjectType(
209 "RootSubscriptionType",
210 {
211 "subscribeUser": GraphQLField(
212 subscription_user_type,
213 args={"id": GraphQLArgument(GraphQLID)},
214 subscribe=subscribe_user,
215 resolve=resolve_subscription_user,
216 )
217 },
218 ),
219 )
220
221
222 @fixture
223 def context():
224 return {"registry": UserRegistry()}
225
226
227 def describe_query():
228 @mark.asyncio
229 async def query_user(context):
230 user = await context["registry"].create(
231 firstName="John", lastName="Doe", tweets=42, verified=True
232 )
233
234 query = """
235 query ($userId: ID!) {
236 User(id: $userId) {
237 id, firstName, lastName, tweets, verified
238 }
239 }
240 """
241
242 variables = {"userId": user.id}
243 result = await graphql(
244 schema, query, context_value=context, variable_values=variables
245 )
246
247 assert not result.errors
248 assert result.data == {
249 "User": {
250 "id": user.id,
251 "firstName": user.firstName,
252 "lastName": user.lastName,
253 "tweets": user.tweets,
254 "verified": user.verified,
255 }
256 }
257
258
259 def describe_mutation():
260 @mark.asyncio
261 async def create_user(context):
262 received = {}
263
264 def subscriber(event_name):
265 def receive(msg):
266 received[event_name] = msg
267
268 return receive
269
270 # noinspection PyProtectedMember
271 pubsub = context["registry"]._pubsub
272 pubsub[None].subscribers.add(subscriber("User"))
273 pubsub["0"].subscribers.add(subscriber("User 0"))
274
275 query = """
276 mutation ($userData: UserInputType!) {
277 createUser(data: $userData) {
278 id, firstName, lastName, tweets, verified
279 }
280 }
281 """
282 user_data = dict(firstName="John", lastName="Doe", tweets=42, verified=True)
283 variables = {"userData": user_data}
284 result = await graphql(
285 schema, query, context_value=context, variable_values=variables
286 )
287
288 user = await context["registry"].get("0")
289 assert user == User(id="0", **user_data) # type: ignore
290
291 assert result.errors is None
292 assert result.data == {
293 "createUser": {
294 "id": user.id,
295 "firstName": user.firstName,
296 "lastName": user.lastName,
297 "tweets": user.tweets,
298 "verified": user.verified,
299 }
300 }
301
302 assert received == {
303 "User": {"user": user, "mutation": MutationEnum.CREATED.value},
304 "User 0": {"user": user, "mutation": MutationEnum.CREATED.value},
305 }
306
307 @mark.asyncio
308 async def update_user(context):
309 received = {}
310
311 def subscriber(event_name):
312 def receive(msg):
313 received[event_name] = msg
314
315 return receive
316
317 # noinspection PyProtectedMember
318 pubsub = context["registry"]._pubsub
319 pubsub[None].subscribers.add(subscriber("User"))
320 pubsub["0"].subscribers.add(subscriber("User 0"))
321
322 user = await context["registry"].create(
323 firstName="John", lastName="Doe", tweets=42, verified=True
324 )
325 user_data = {
326 "firstName": "Jane",
327 "lastName": "Roe",
328 "tweets": 210,
329 "verified": False,
330 }
331
332 query = """
333 mutation ($userId: ID!, $userData: UserInputType!) {
334 updateUser(id: $userId, data: $userData) {
335 id, firstName, lastName, tweets, verified
336 }
337 }"""
338
339 variables = {"userId": user.id, "userData": user_data}
340 result = await graphql(
341 schema, query, context_value=context, variable_values=variables
342 )
343
344 user = await context["registry"].get("0")
345 assert user == User(id="0", **user_data) # type: ignore
346
347 assert result.errors is None
348 assert result.data == {
349 "updateUser": {
350 "id": user.id,
351 "firstName": user.firstName,
352 "lastName": user.lastName,
353 "tweets": user.tweets,
354 "verified": user.verified,
355 }
356 }
357
358 assert received == {
359 "User": {"user": user, "mutation": MutationEnum.UPDATED.value},
360 "User 0": {"user": user, "mutation": MutationEnum.UPDATED.value},
361 }
362
363 @mark.asyncio
364 async def delete_user(context):
365 received = {}
366
367 def subscriber(name):
368 def receive(msg):
369 received[name] = msg
370
371 return receive
372
373 # noinspection PyProtectedMember
374 pubsub = context["registry"]._pubsub
375 pubsub[None].subscribers.add(subscriber("User"))
376 pubsub["0"].subscribers.add(subscriber("User 0"))
377
378 user = await context["registry"].create(
379 firstName="John", lastName="Doe", tweets=42, verified=True
380 )
381
382 query = """
383 mutation ($userId: ID!) {
384 deleteUser(id: $userId)
385 }
386 """
387
388 variables = {"userId": user.id}
389 result = await graphql(
390 schema, query, context_value=context, variable_values=variables
391 )
392
393 assert result.errors is None
394 assert result.data == {"deleteUser": True}
395
396 assert await context["registry"].get(user.id) is None
397
398 assert received == {
399 "User": {"user": user, "mutation": MutationEnum.DELETED.value},
400 "User 0": {"user": user, "mutation": MutationEnum.DELETED.value},
401 }
402
403
404 def describe_subscription():
405 @mark.asyncio
406 async def subscribe_to_user_mutations(context):
407 query = """
408 subscription ($userId: ID!) {
409 subscribeUser(id: $userId) {
410 mutation
411 user { id, firstName, lastName, tweets, verified }
412 }
413 }
414 """
415
416 variables = {"userId": "0"}
417 subscription_one = await subscribe(
418 schema, parse(query), context_value=context, variable_values=variables
419 )
420 assert isinstance(subscription_one, MapAsyncIterator)
421
422 query = """
423 subscription {
424 subscribeUser(id: null) {
425 mutation
426 user { id, firstName, lastName, tweets, verified }
427 }
428 }
429 """
430
431 subscription_all = await subscribe(schema, parse(query), context_value=context)
432 assert isinstance(subscription_all, MapAsyncIterator)
433
434 received_one = []
435 received_all = []
436
437 async def mutate_users():
438 await sleep(0) # make sure subscribers are running
439 await graphql(
440 schema,
441 """
442 mutation {createUser(data: {
443 firstName: "John"
444 lastName: "Doe"
445 tweets: 42
446 verified: true}) { id }
447 }""",
448 context_value=context,
449 )
450 await graphql(
451 schema,
452 """
453 mutation {createUser(data: {
454 firstName: "James"
455 lastName: "Doe"
456 tweets: 4
457 verified: false}) { id }
458 }""",
459 context_value=context,
460 )
461 await graphql(
462 schema,
463 """
464 mutation {updateUser(id: 0, data: {
465 firstName: "Jane"
466 lastName: "Roe"
467 tweets: 210
468 verified: false}) { id }
469 }""",
470 context_value=context,
471 )
472 await graphql(
473 schema,
474 """
475 mutation {updateUser(id: 1, data: {
476 firstName: "Janette"
477 lastName: "Roe"
478 tweets: 20
479 verified: true}) { id }
480 }""",
481 context_value=context,
482 )
483 await graphql(
484 schema,
485 """
486 mutation {deleteUser(id: "0")}
487 """,
488 context_value=context,
489 )
490 await graphql(
491 schema,
492 """
493 mutation {deleteUser(id: "1")}
494 """,
495 context_value=context,
496 )
497
498 async def receive_one():
499 async for result in subscription_one: # pragma: no cover
500 received_one.append(result)
501 if len(received_one) == 3: # pragma: no cover else
502 break
503
504 async def receive_all():
505 async for result in subscription_all: # pragma: no cover
506 received_all.append(result)
507 if len(received_all) == 6: # pragma: no cover else
508 break
509
510 tasks = [
511 create_task(task()) if create_task else task() # type: ignore
512 for task in (mutate_users, receive_one, receive_all)
513 ]
514 done, pending = await wait(tasks, timeout=1)
515 assert len(done) == len(tasks)
516 assert not pending
517
518 expected_data: List[Dict[str, Any]] = [
519 {
520 "mutation": "CREATED",
521 "user": {
522 "id": "0",
523 "firstName": "John",
524 "lastName": "Doe",
525 "tweets": 42,
526 "verified": True,
527 },
528 },
529 {
530 "mutation": "CREATED",
531 "user": {
532 "id": "1",
533 "firstName": "James",
534 "lastName": "Doe",
535 "tweets": 4,
536 "verified": False,
537 },
538 },
539 {
540 "mutation": "UPDATED",
541 "user": {
542 "id": "0",
543 "firstName": "Jane",
544 "lastName": "Roe",
545 "tweets": 210,
546 "verified": False,
547 },
548 },
549 {
550 "mutation": "UPDATED",
551 "user": {
552 "id": "1",
553 "firstName": "Janette",
554 "lastName": "Roe",
555 "tweets": 20,
556 "verified": True,
557 },
558 },
559 {
560 "mutation": "DELETED",
561 "user": {
562 "id": "0",
563 "firstName": "Jane",
564 "lastName": "Roe",
565 "tweets": 210,
566 "verified": False,
567 },
568 },
569 {
570 "mutation": "DELETED",
571 "user": {
572 "id": "1",
573 "firstName": "Janette",
574 "lastName": "Roe",
575 "tweets": 20,
576 "verified": True,
577 },
578 },
579 ]
580
581 assert received_one == [
582 ({"subscribeUser": data}, None)
583 for data in expected_data
584 if data["user"]["id"] == "0"
585 ]
586 assert received_all == [
587 ({"subscribeUser": data}, None) for data in expected_data
588 ]
589
590 await sleep(0)