-
Notifications
You must be signed in to change notification settings - Fork 11
/
test_context.py
957 lines (763 loc) · 33.6 KB
/
test_context.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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
from __future__ import annotations
import asyncio
import sys
from asyncio import get_running_loop
from collections.abc import Callable
from concurrent.futures import Executor, ThreadPoolExecutor
from inspect import isawaitable
from itertools import count
from threading import Thread, current_thread
from typing import AsyncGenerator, AsyncIterator, Dict, NoReturn, Optional, Tuple, Union
from unittest.mock import patch
import pytest
import pytest_asyncio
from async_generator import yield_
from asphalt.core import (
Context,
Dependency,
NoCurrentContext,
ResourceConflict,
ResourceNotFound,
TeardownError,
callable_name,
context_teardown,
current_context,
executor,
get_resource,
inject,
resource,
)
from asphalt.core.context import ResourceContainer, require_resource
@pytest.fixture
def context() -> Context:
return Context()
@pytest_asyncio.fixture
async def special_executor(context: Context) -> AsyncIterator[ThreadPoolExecutor]:
executor = ThreadPoolExecutor(1)
context.add_resource(executor, "special", types=[Executor])
yield executor
executor.shutdown()
class TestResourceContainer:
@pytest.mark.parametrize("thread", [False, True], ids=["eventloop", "worker"])
@pytest.mark.parametrize("context_attr", [None, "attrname"], ids=["no_attr", "has_attr"])
@pytest.mark.asyncio
async def test_generate_value(self, thread: bool, context_attr: str | None) -> None:
container = ResourceContainer(lambda ctx: "foo", (str,), "default", context_attr, True)
context = Context()
if thread:
value = await context.call_in_executor(container.generate_value, context)
else:
value = container.generate_value(context)
assert value == "foo"
assert context.get_resource(str) == "foo"
if context_attr:
assert getattr(context, context_attr) == "foo"
def test_repr(self) -> None:
container = ResourceContainer("foo", (str,), "default", "attrname", False)
assert repr(container) == (
"ResourceContainer(value='foo', types=[str], name='default', "
"context_attr='attrname')"
)
def test_repr_factory(self) -> None:
container = ResourceContainer(lambda ctx: "foo", (str,), "default", "attrname", True)
assert repr(container) == (
"ResourceContainer(factory=test_context.TestResourceContainer"
".test_repr_factory.<locals>.<lambda>, types=[str], name='default', "
"context_attr='attrname')"
)
class TestContext:
@pytest.mark.asyncio
async def test_parent(self) -> None:
"""Test that the parent property points to the parent context instance, if any."""
async with Context() as parent:
async with Context() as child:
assert parent.parent is None
assert child.parent is parent
@pytest.mark.parametrize(
"exception", [None, Exception("foo")], ids=["noexception", "exception"]
)
@pytest.mark.asyncio
async def test_close(self, context: Context, exception: Exception | None) -> None:
"""
Test that teardown callbacks are called in reverse order when a context is closed.
"""
def callback(exception=None):
called_functions.append((callback, exception))
async def async_callback(exception=None):
called_functions.append((async_callback, exception))
called_functions: list[tuple[Callable, BaseException | None]] = []
context.add_teardown_callback(callback, pass_exception=True)
context.add_teardown_callback(async_callback, pass_exception=True)
await context.close(exception)
assert called_functions == [(async_callback, exception), (callback, exception)]
@pytest.mark.asyncio
async def test_close_while_running_teardown(self, context: Context) -> None:
"""
Test that trying to close the context from a teardown callback raises a
RuntimeError.
"""
async def try_close_context() -> None:
with pytest.raises(RuntimeError, match="this context is already closing"):
await context.close()
context.add_teardown_callback(try_close_context)
await context.close()
@pytest.mark.asyncio
async def test_teardown_callback_exception(self, context: Context) -> None:
"""
Test that all callbacks are called even when some teardown callbacks raise
exceptions, and that a TeardownError is raised in such a case, containing the
exception objects.
"""
def callback1() -> None:
items.append(1)
def callback2() -> NoReturn:
raise Exception("foo")
context.add_teardown_callback(callback1)
context.add_teardown_callback(callback2)
context.add_teardown_callback(callback1)
context.add_teardown_callback(callback2)
items: list[int] = []
with pytest.raises(TeardownError) as exc:
await context.close()
assert "foo" in str(exc.value)
assert items == [1, 1]
assert len(exc.value.exceptions) == 2
@pytest.mark.asyncio
async def test_close_closed(self, context: Context) -> None:
"""Test that closing an already closed context raises a RuntimeError."""
assert not context.closed
await context.close()
assert context.closed
with pytest.raises(RuntimeError) as exc:
await context.close()
exc.match("this context has already been closed")
def test_contextmanager_exception(self, context, event_loop):
close_future = event_loop.create_future()
close_future.set_result(None)
exception = Exception("foo")
with patch.object(context, "close", return_value=close_future):
with pytest.raises(Exception) as exc, pytest.deprecated_call():
with context:
raise exception
# close.assert_called_once_with(exception)
assert exc.value is exception
@pytest.mark.asyncio
async def test_async_contextmanager_exception(self, context):
"""Test that "async with context:" calls close() with the exception raised in the block."""
close_future = get_running_loop().create_future()
close_future.set_result(None)
exception = Exception("foo")
with patch.object(context, "close", return_value=close_future) as close:
with pytest.raises(Exception) as exc:
async with context:
raise exception
close.assert_called_once_with(exception)
assert exc.value is exception
@pytest.mark.parametrize("types", [int, (int,), ()], ids=["type", "tuple", "empty"])
@pytest.mark.asyncio
async def test_add_resource(self, context, types):
"""Test that a resource is properly added in the context and listeners are notified."""
get_running_loop().call_soon(context.add_resource, 6, "foo", None, types)
event = await context.resource_added.wait_event()
assert event.resource_types == (int,)
assert event.resource_name == "foo"
assert not event.is_factory
assert context.get_resource(int, "foo") == 6
@pytest.mark.asyncio
async def test_add_resource_name_conflict(self, context: Context) -> None:
"""Test that adding a resource won't replace any existing resources."""
context.add_resource(5, "foo")
with pytest.raises(ResourceConflict) as exc:
context.add_resource(4, "foo")
exc.match("this context already contains a resource of type int using the name 'foo'")
@pytest.mark.asyncio
async def test_add_resource_none_value(self, context: Context) -> None:
"""Test that None is not accepted as a resource value."""
exc = pytest.raises(ValueError, context.add_resource, None)
exc.match('"value" must not be None')
@pytest.mark.asyncio
async def test_add_resource_context_attr(self, context: Context) -> None:
"""Test that when resources are added, they are also set as properties of the context."""
with pytest.deprecated_call():
context.add_resource(1, context_attr="foo")
assert context.foo == 1
def test_add_resource_context_attr_conflict(self, context: Context) -> None:
"""
Test that the context won't allow adding a resource with an attribute name that conflicts
with an existing attribute.
"""
context.a = 2
with pytest.raises(ResourceConflict) as exc:
context.add_resource(2, context_attr="a")
exc.match("this context already has an attribute 'a'")
assert context.get_resource(int) is None
@pytest.mark.asyncio
async def test_add_resource_type_conflict(self, context: Context) -> None:
context.add_resource(5)
with pytest.raises(ResourceConflict) as exc:
context.add_resource(6)
exc.match("this context already contains a resource of type int using the name 'default'")
@pytest.mark.parametrize("name", ["a.b", "a:b", "a b"], ids=["dot", "colon", "space"])
@pytest.mark.asyncio
async def test_add_resource_bad_name(self, context, name):
with pytest.raises(ValueError) as exc:
context.add_resource(1, name)
exc.match(
'"name" must be a nonempty string consisting only of alphanumeric characters '
"and underscores"
)
@pytest.mark.asyncio
async def test_add_resource_parametrized_generic_type(self, context: Context) -> None:
resource = {"a": 1}
resource_type = Dict[str, int]
context.add_resource(resource, types=[resource_type])
assert context.require_resource(resource_type) is resource
assert context.get_resource(resource_type) is resource
assert await context.request_resource(resource_type) is resource
assert context.get_resource(Dict) is None
assert context.get_resource(dict) is None
@pytest.mark.asyncio
async def test_add_resource_factory(self, context: Context) -> None:
"""Test that resources factory callbacks are only called once for each context."""
def factory(ctx):
assert ctx is context
return next(counter)
counter = count(1)
with pytest.deprecated_call():
context.add_resource_factory(factory, int, context_attr="foo")
assert context.foo == 1
assert context.foo == 1
assert context.__dict__["foo"] == 1
@pytest.mark.asyncio
async def test_add_resource_factory_parametrized_generic_type(self, context: Context) -> None:
resource = {"a": 1}
resource_type = Dict[str, int]
context.add_resource_factory(lambda ctx: resource, types=[resource_type])
assert context.require_resource(resource_type) is resource
assert context.get_resource(resource_type) is resource
assert await context.request_resource(resource_type) is resource
assert context.get_resource(Dict) is None
assert context.get_resource(dict) is None
@pytest.mark.parametrize("name", ["a.b", "a:b", "a b"], ids=["dot", "colon", "space"])
@pytest.mark.asyncio
async def test_add_resource_factory_bad_name(self, context, name):
with pytest.raises(ValueError) as exc:
context.add_resource_factory(lambda ctx: 1, int, name)
exc.match(
'"name" must be a nonempty string consisting only of alphanumeric characters '
"and underscores"
)
@pytest.mark.asyncio
async def test_add_resource_factory_coroutine_callback(self, context: Context) -> None:
async def factory(ctx):
return 1
with pytest.raises(TypeError) as exc:
context.add_resource_factory(factory, int)
exc.match('"factory_callback" must not be a coroutine function')
@pytest.mark.asyncio
async def test_add_resource_factory_empty_types(self, context: Context) -> None:
with pytest.raises(ValueError) as exc:
context.add_resource_factory(lambda ctx: 1, ())
exc.match("no resource types were specified")
@pytest.mark.asyncio
async def test_add_resource_factory_context_attr_conflict(self, context: Context) -> None:
with pytest.deprecated_call():
context.add_resource_factory(lambda ctx: None, str, context_attr="foo")
with pytest.raises(ResourceConflict) as exc:
await context.add_resource_factory(lambda ctx: None, str, context_attr="foo")
exc.match(
"this context already contains a resource factory for the context attribute 'foo'"
)
@pytest.mark.asyncio
async def test_add_resource_factory_type_conflict(self, context: Context) -> None:
context.add_resource_factory(lambda ctx: None, (str, int))
with pytest.raises(ResourceConflict) as exc:
await context.add_resource_factory(lambda ctx: None, int)
exc.match("this context already contains a resource factory for the type int")
@pytest.mark.asyncio
async def test_add_resource_factory_no_inherit(self, context: Context) -> None:
"""
Test that a subcontext gets its own version of a factory-generated resource even if a
parent context has one already.
"""
with pytest.deprecated_call():
context.add_resource_factory(id, int, context_attr="foo")
async with context, Context() as subcontext:
assert context.foo == id(context)
assert subcontext.foo == id(subcontext)
@pytest.mark.asyncio
async def test_add_resource_return_type_single(self, context: Context) -> None:
def factory(ctx: Context) -> str:
return "foo"
async with context:
context.add_resource_factory(factory)
assert context.require_resource(str) == "foo"
@pytest.mark.asyncio
async def test_add_resource_return_type_union(self, context: Context) -> None:
def factory(ctx: Context) -> Union[int, float]: # noqa: UP007
return 5
async with context:
context.add_resource_factory(factory)
assert context.require_resource(int) == 5
assert context.require_resource(float) == 5
@pytest.mark.skipif(sys.version_info < (3, 10), reason="Requires Python 3.10+")
@pytest.mark.asyncio
async def test_add_resource_return_type_uniontype(self, context: Context) -> None:
def factory(ctx: Context) -> int | float:
return 5
async with context:
context.add_resource_factory(factory)
assert context.require_resource(int) == 5
assert context.require_resource(float) == 5
@pytest.mark.asyncio
async def test_add_resource_return_type_optional(self, context: Context) -> None:
def factory(ctx: Context) -> Optional[str]: # noqa: UP007
return "foo"
async with context:
context.add_resource_factory(factory)
assert context.require_resource(str) == "foo"
@pytest.mark.asyncio
async def test_getattr_attribute_error(self, context: Context) -> None:
async with context, Context() as child_context:
pytest.raises(AttributeError, getattr, child_context, "foo").match(
"no such context variable: foo"
)
@pytest.mark.asyncio
async def test_getattr_parent(self, context: Context) -> None:
"""
Test that accessing a nonexistent attribute on a context retrieves the value from parent.
"""
async with context, Context() as child_context:
context.a = 2
assert child_context.a == 2
@pytest.mark.asyncio
async def test_get_resources(self, context: Context) -> None:
context.add_resource(9, "foo")
context.add_resource_factory(lambda ctx: len(ctx.context_chain), int, "bar")
context.require_resource(int, "bar")
async with context, Context() as subctx:
subctx.add_resource(4, "foo")
assert subctx.get_resources(int) == {1, 4}
@pytest.mark.asyncio
async def test_require_resource(self, context: Context) -> None:
context.add_resource(1)
assert context.require_resource(int) == 1
def test_require_resource_not_found(self, context: Context) -> None:
"""Test that ResourceNotFound is raised when a required resource is not found."""
exc = pytest.raises(ResourceNotFound, context.require_resource, int, "foo")
exc.match("no matching resource was found for type=int name='foo'")
assert exc.value.type == int
assert exc.value.name == "foo"
@pytest.mark.asyncio
async def test_request_resource_parent_add(self, context):
"""
Test that adding a resource to the parent context will satisfy a resource request in a
child context.
"""
async with context, Context() as child_context:
event_loop = get_running_loop()
task = event_loop.create_task(child_context.request_resource(int))
event_loop.call_soon(context.add_resource, 6)
resource = await task
assert resource == 6
@pytest.mark.asyncio
async def test_request_resource_factory_context_attr(self, context: Context) -> None:
"""Test that requesting a factory-generated resource also sets the context variable."""
with pytest.deprecated_call():
context.add_resource_factory(lambda ctx: 6, int, context_attr="foo")
await context.request_resource(int)
assert context.__dict__["foo"] == 6
@pytest.mark.asyncio
async def test_call_async_plain(self, context: Context) -> None:
def runs_in_event_loop(worker_thread: Thread, x: int, y: int) -> int:
assert current_thread() is not worker_thread
return x + y
def runs_in_worker_thread() -> int:
worker_thread = current_thread()
return context.call_async(runs_in_event_loop, worker_thread, 1, y=2)
assert await context.call_in_executor(runs_in_worker_thread) == 3
@pytest.mark.asyncio
async def test_call_async_coroutine(self, context: Context) -> None:
async def runs_in_event_loop(worker_thread, x, y):
assert current_thread() is not worker_thread
await asyncio.sleep(0.1)
return x + y
def runs_in_worker_thread() -> int:
worker_thread = current_thread()
return context.call_async(runs_in_event_loop, worker_thread, 1, y=2)
assert await context.call_in_executor(runs_in_worker_thread) == 3
@pytest.mark.asyncio
async def test_call_async_exception(self, context: Context) -> None:
def runs_in_event_loop() -> NoReturn:
raise ValueError("foo")
with pytest.raises(ValueError) as exc:
await context.call_in_executor(context.call_async, runs_in_event_loop)
assert exc.match("foo")
@pytest.mark.asyncio
async def test_call_in_executor(self, context: Context) -> None:
"""Test that call_in_executor actually runs the target in a worker thread."""
worker_thread = await context.call_in_executor(current_thread)
assert worker_thread is not current_thread()
@pytest.mark.parametrize("use_resource_name", [True, False], ids=["direct", "resource"])
@pytest.mark.asyncio
async def test_call_in_executor_explicit(self, context, use_resource_name):
executor = ThreadPoolExecutor(1)
context.add_resource(executor, types=[Executor])
context.add_teardown_callback(executor.shutdown)
executor_arg = "default" if use_resource_name else executor
worker_thread = await context.call_in_executor(current_thread, executor=executor_arg)
assert worker_thread is not current_thread()
@pytest.mark.asyncio
async def test_call_in_executor_context_preserved(self, context: Context) -> None:
"""
Test that call_in_executor runs the callable in a copy of the current (PEP 567)
context.
"""
async with Context() as ctx:
assert await context.call_in_executor(current_context) is ctx
@pytest.mark.asyncio
async def test_threadpool(self, context: Context) -> None:
event_loop_thread = current_thread()
async with context.threadpool():
assert current_thread() is not event_loop_thread
@pytest.mark.asyncio
async def test_threadpool_named_executor(
self, context: Context, special_executor: Executor
) -> None:
special_executor_thread = special_executor.submit(current_thread).result()
async with context.threadpool("special"):
assert current_thread() is special_executor_thread
class TestExecutor:
@pytest.mark.asyncio
async def test_no_arguments(self, context: Context) -> None:
@executor
def runs_in_default_worker() -> None:
assert current_thread() is not event_loop_thread
current_context()
event_loop_thread = current_thread()
async with context:
await runs_in_default_worker()
@pytest.mark.asyncio
async def test_named_executor(self, context: Context, special_executor: Executor) -> None:
@executor("special")
def runs_in_default_worker(ctx: Context) -> None:
assert current_thread() is special_executor_thread
assert current_context() is ctx
special_executor_thread = special_executor.submit(current_thread).result()
async with context:
await runs_in_default_worker(context)
@pytest.mark.asyncio
async def test_executor_missing_context(self, context: Context):
@executor("special")
def runs_in_default_worker() -> None:
current_context()
with pytest.raises(RuntimeError) as exc:
async with context:
await runs_in_default_worker()
exc.match(
r"the first positional argument to %s\(\) has to be a Context instance"
% callable_name(runs_in_default_worker)
)
class TestContextTeardown:
@pytest.mark.parametrize(
"expected_exc", [None, Exception("foo")], ids=["no_exception", "exception"]
)
@pytest.mark.asyncio
async def test_function(self, expected_exc: Exception | None) -> None:
phase = received_exception = None
@context_teardown
async def start(ctx: Context) -> AsyncIterator[None]:
nonlocal phase, received_exception
phase = "started"
exc = yield
phase = "finished"
received_exception = exc
context = Context()
await start(context)
assert phase == "started"
await context.close(expected_exc)
assert phase == "finished"
assert received_exception == expected_exc
@pytest.mark.parametrize(
"expected_exc", [None, Exception("foo")], ids=["no_exception", "exception"]
)
@pytest.mark.asyncio
async def test_method(self, expected_exc: Exception | None) -> None:
phase = received_exception = None
class SomeComponent:
@context_teardown
async def start(self, ctx: Context) -> AsyncIterator[None]:
nonlocal phase, received_exception
phase = "started"
exc = yield
phase = "finished"
received_exception = exc
context = Context()
await SomeComponent().start(context)
assert phase == "started"
await context.close(expected_exc)
assert phase == "finished"
assert received_exception == expected_exc
def test_plain_function(self) -> None:
def start(ctx) -> None:
pass
pytest.raises(TypeError, context_teardown, start).match(
" must be an async generator function"
)
@pytest.mark.asyncio
async def test_bad_args(self) -> None:
with pytest.deprecated_call():
@context_teardown
async def start(ctx: Context) -> None:
pass
with pytest.raises(RuntimeError) as exc:
await start(None)
exc.match(
r"the first positional argument to %s\(\) has to be a Context instance"
% callable_name(start)
)
@pytest.mark.asyncio
async def test_exception(self) -> None:
@context_teardown
async def start(ctx: Context) -> AsyncIterator[None]:
raise Exception("dummy error")
yield
context = Context()
with pytest.raises(Exception) as exc_info:
await start(context)
exc_info.match("dummy error")
@pytest.mark.asyncio
async def test_missing_yield(self) -> None:
with pytest.deprecated_call():
@context_teardown
async def start(ctx: Context) -> None:
pass
await start(Context())
@pytest.mark.asyncio
async def test_py35_generator(self) -> None:
with pytest.deprecated_call():
@context_teardown
async def start(ctx: Context) -> None:
await yield_()
await start(Context())
@pytest.mark.parametrize(
"resource_func",
[
pytest.param(Context.get_resource, id="get_resource"),
pytest.param(Context.require_resource, id="require_resource"),
pytest.param(Context.request_resource, id="request_resource"),
],
)
@pytest.mark.asyncio
async def test_get_resource_at_teardown(self, resource_func) -> None:
resource = ""
async def teardown_callback() -> None:
nonlocal resource
resource = resource_func(ctx, str)
if isawaitable(resource):
resource = await resource
async with Context() as ctx:
ctx.add_resource("blah")
ctx.add_teardown_callback(teardown_callback)
assert resource == "blah"
@pytest.mark.parametrize(
"resource_func",
[
pytest.param(Context.get_resource, id="get_resource"),
pytest.param(Context.require_resource, id="require_resource"),
pytest.param(Context.request_resource, id="request_resource"),
],
)
@pytest.mark.asyncio
async def test_generate_resource_at_teardown(self, resource_func) -> None:
resource = ""
async def teardown_callback() -> None:
nonlocal resource
resource = resource_func(ctx, str)
if isawaitable(resource):
resource = await resource
async with Context() as ctx:
ctx.add_resource_factory(lambda context: "blah", [str])
ctx.add_teardown_callback(teardown_callback)
assert resource == "blah"
class TestContextFinisher:
@pytest.mark.parametrize(
"expected_exc", [None, Exception("foo")], ids=["no_exception", "exception"]
)
@pytest.mark.asyncio
async def test_context_teardown(self, expected_exc: Exception | None) -> None:
phase = received_exception = None
@context_teardown
async def start(ctx: Context) -> AsyncIterator[None]:
nonlocal phase, received_exception
phase = "started"
exc = yield
phase = "finished"
received_exception = exc
context = Context()
await start(context)
assert phase == "started"
await context.close(expected_exc)
assert phase == "finished"
assert received_exception == expected_exc
@pytest.mark.asyncio
async def test_current_context() -> None:
pytest.raises(NoCurrentContext, current_context)
async with Context() as parent_ctx:
assert current_context() is parent_ctx
async with Context() as child_ctx:
assert current_context() is child_ctx
assert current_context() is parent_ctx
pytest.raises(NoCurrentContext, current_context)
@pytest.mark.asyncio
async def test_get_resource() -> None:
async with Context() as ctx:
ctx.add_resource("foo")
assert get_resource(str) == "foo"
assert get_resource(int) is None
@pytest.mark.asyncio
async def test_require_resource() -> None:
async with Context() as ctx:
ctx.add_resource("foo")
assert require_resource(str) == "foo"
pytest.raises(ResourceNotFound, require_resource, int)
def test_explicit_parent_deprecation() -> None:
parent_ctx = Context()
pytest.warns(DeprecationWarning, Context, parent_ctx)
@pytest.mark.asyncio
async def test_context_stack_corruption():
async def generator() -> AsyncGenerator:
async with Context():
yield
gen = generator()
await get_running_loop().create_task(gen.asend(None))
async with Context() as ctx:
with pytest.warns(UserWarning, match="Potential context stack corruption detected"):
try:
await get_running_loop().create_task(gen.asend(None))
except StopAsyncIteration:
pass
assert current_context() is ctx
pytest.raises(NoCurrentContext, current_context)
class TestDependencyInjection:
@pytest.mark.asyncio
async def test_static_resources(self) -> None:
@inject
async def injected(
foo: int, bar: str = resource(), *, baz: str = resource("alt")
) -> Tuple[int, str, str]: # noqa: UP006
return foo, bar, baz
async with Context() as ctx:
ctx.add_resource("bar_test")
ctx.add_resource("baz_test", "alt")
foo, bar, baz = await injected(2)
assert foo == 2
assert bar == "bar_test"
assert baz == "baz_test"
@pytest.mark.asyncio
async def test_sync_injection(self) -> None:
@inject
def injected(
foo: int, bar: str = resource(), *, baz: str = resource("alt")
) -> Tuple[int, str, str]: # noqa: UP006
return foo, bar, baz
async with Context() as ctx:
ctx.add_resource("bar_test")
ctx.add_resource("baz_test", "alt")
foo, bar, baz = injected(2)
assert foo == 2
assert bar == "bar_test"
assert baz == "baz_test"
@pytest.mark.asyncio
async def test_missing_annotation(self) -> None:
async def injected(foo: int, bar: str = resource(), *, baz=resource("alt")) -> None:
pass
pytest.raises(TypeError, inject, injected).match(
f"Dependency for parameter 'baz' of function "
f"'{__name__}.{self.__class__.__name__}.test_missing_annotation.<locals>"
f".injected' is missing the type annotation"
)
@pytest.mark.asyncio
async def test_missing_resource(self) -> None:
@inject
async def injected(foo: int, bar: str = resource()) -> None:
pass
with pytest.raises(ResourceNotFound) as exc:
async with Context():
await injected(2)
exc.match("no matching resource was found for type=str name='default'")
@pytest.mark.parametrize(
"annotation",
[
pytest.param(Optional[str], id="optional"),
# pytest.param(Union[str, int, None], id="union"),
pytest.param(
"str | None",
id="uniontype.10",
marks=[
pytest.mark.skipif(sys.version_info < (3, 10), reason="Requires Python 3.10+")
],
),
],
)
@pytest.mark.parametrize(
"sync",
[
pytest.param(True, id="sync"),
pytest.param(False, id="async"),
],
)
@pytest.mark.asyncio
async def test_inject_optional_resource_async(self, annotation: type, sync: bool) -> None:
if sync:
@inject
def injected(
res: annotation = resource(), # type: ignore[valid-type]
) -> annotation: # type: ignore[valid-type]
return res
else:
@inject
async def injected(
res: annotation = resource(), # type: ignore[valid-type]
) -> annotation: # type: ignore[valid-type]
return res
async with Context() as ctx:
retval = injected() if sync else (await injected())
assert retval is None
ctx.add_resource("hello")
retval = injected() if sync else (await injected())
assert retval == "hello"
def test_resource_function_not_called(self) -> None:
async def injected(foo: int, bar: str = resource) -> None:
pass
with pytest.raises(TypeError) as exc:
inject(injected)
exc.match(
f"Default value for parameter 'bar' of function "
f"{__name__}.{self.__class__.__name__}.test_resource_function_not_called"
f".<locals>.injected was the 'resource' function – did you forget to add "
f"the parentheses at the end\\?"
)
def test_missing_inject(self) -> None:
def injected(foo: int, bar: str = resource()) -> None:
bar.lower()
with pytest.raises(AttributeError) as exc:
injected(1)
exc.match(
r"Attempted to access an attribute in a resource\(\) marker – did you "
r"forget to add the @inject decorator\?"
)
def test_no_resources_declared(self) -> None:
def injected(foo: int) -> None:
pass
match = (
f"{__name__}.{self.__class__.__name__}.test_no_resources_declared.<locals>"
f".injected does not have any injectable resources declared"
)
with pytest.warns(UserWarning, match=match):
func = inject(injected)
assert func is injected
def test_dependency_deprecated() -> None:
with pytest.deprecated_call():
async def foo(res: str = Dependency()) -> None:
pass