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