-
Notifications
You must be signed in to change notification settings - Fork 82
/
injector_test.py
1756 lines (1243 loc) · 46.1 KB
/
injector_test.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
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# encoding: utf-8
#
# Copyright (C) 2010 Alec Thomas <[email protected]>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# Author: Alec Thomas <[email protected]>
"""Functional tests for the "Injector" dependency injection framework."""
from contextlib import contextmanager
from typing import Any, NewType, Optional, Union
import abc
import sys
import threading
import traceback
import warnings
if sys.version_info >= (3, 9):
from typing import Annotated
else:
from typing_extensions import Annotated
from typing import Dict, List, NewType
import pytest
from injector import (
Binder,
CallError,
Inject,
Injector,
NoInject,
Scope,
InstanceProvider,
ClassProvider,
get_bindings,
inject,
multiprovider,
noninjectable,
singleton,
threadlocal,
UnsatisfiedRequirement,
CircularDependency,
Module,
SingletonScope,
ScopeDecorator,
AssistedBuilder,
provider,
ProviderOf,
ClassAssistedBuilder,
Error,
UnknownArgument,
)
class EmptyClass:
pass
class DependsOnEmptyClass:
@inject
def __init__(self, b: EmptyClass):
"""Construct a new DependsOnEmptyClass."""
self.b = b
def prepare_nested_injectors():
def configure(binder):
binder.bind(str, to='asd')
parent = Injector(configure)
child = parent.create_child_injector()
return parent, child
def check_exception_contains_stuff(exception, stuff):
stringified = str(exception)
for thing in stuff:
assert thing in stringified, '%r should be present in the exception representation: %s' % (
thing,
stringified,
)
def test_child_injector_inherits_parent_bindings():
parent, child = prepare_nested_injectors()
assert child.get(str) == parent.get(str)
def test_child_injector_overrides_parent_bindings():
parent, child = prepare_nested_injectors()
child.binder.bind(str, to='qwe')
assert (parent.get(str), child.get(str)) == ('asd', 'qwe')
def test_child_injector_rebinds_arguments_for_parent_scope():
class Cls:
val = ""
class A(Cls):
@inject
def __init__(self, val: str):
self.val = val
def configure_parent(binder):
binder.bind(Cls, to=A)
binder.bind(str, to="Parent")
def configure_child(binder):
binder.bind(str, to="Child")
parent = Injector(configure_parent)
assert parent.get(Cls).val == "Parent"
child = parent.create_child_injector(configure_child)
assert child.get(Cls).val == "Child"
def test_scopes_are_only_bound_to_root_injector():
parent, child = prepare_nested_injectors()
class A:
pass
parent.binder.bind(A, to=A, scope=singleton)
assert parent.get(A) is child.get(A)
def test_get_default_injected_instances():
def configure(binder):
binder.bind(DependsOnEmptyClass)
binder.bind(EmptyClass)
injector = Injector(configure)
assert injector.get(Injector) is injector
assert injector.get(Binder) is injector.binder
def test_instantiate_injected_method():
a = DependsOnEmptyClass('Bob')
assert a.b == 'Bob'
def test_method_decorator_is_wrapped():
assert DependsOnEmptyClass.__init__.__doc__ == 'Construct a new DependsOnEmptyClass.'
assert DependsOnEmptyClass.__init__.__name__ == '__init__'
def test_decorator_works_for_function_with_no_args():
@inject
def wrapped(*args, **kwargs):
pass
def test_providers_arent_called_for_dependencies_that_are_already_provided():
def configure(binder):
binder.bind(int, to=lambda: 1 / 0)
class A:
@inject
def __init__(self, i: int):
pass
injector = Injector(configure)
builder = injector.get(AssistedBuilder[A])
with pytest.raises(ZeroDivisionError):
builder.build()
builder.build(i=3)
def test_inject_direct():
def configure(binder):
binder.bind(DependsOnEmptyClass)
binder.bind(EmptyClass)
injector = Injector(configure)
a = injector.get(DependsOnEmptyClass)
assert isinstance(a, DependsOnEmptyClass)
assert isinstance(a.b, EmptyClass)
def test_configure_multiple_modules():
def configure_a(binder):
binder.bind(DependsOnEmptyClass)
def configure_b(binder):
binder.bind(EmptyClass)
injector = Injector([configure_a, configure_b])
a = injector.get(DependsOnEmptyClass)
assert isinstance(a, DependsOnEmptyClass)
assert isinstance(a.b, EmptyClass)
def test_inject_with_missing_dependency():
def configure(binder):
binder.bind(DependsOnEmptyClass)
injector = Injector(configure, auto_bind=False)
with pytest.raises(UnsatisfiedRequirement):
injector.get(EmptyClass)
def test_inject_named_interface():
class A:
@inject
def __init__(self, b: EmptyClass):
self.b = b
def configure(binder):
binder.bind(A)
binder.bind(EmptyClass)
injector = Injector(configure)
a = injector.get(A)
assert isinstance(a, A)
assert isinstance(a.b, EmptyClass)
class TransitiveC:
pass
class TransitiveB:
@inject
def __init__(self, c: TransitiveC):
self.c = c
class TransitiveA:
@inject
def __init__(self, b: TransitiveB):
self.b = b
def test_transitive_injection():
def configure(binder):
binder.bind(TransitiveA)
binder.bind(TransitiveB)
binder.bind(TransitiveC)
injector = Injector(configure)
a = injector.get(TransitiveA)
assert isinstance(a, TransitiveA)
assert isinstance(a.b, TransitiveB)
assert isinstance(a.b.c, TransitiveC)
def test_transitive_injection_with_missing_dependency():
def configure(binder):
binder.bind(TransitiveA)
binder.bind(TransitiveB)
injector = Injector(configure, auto_bind=False)
with pytest.raises(UnsatisfiedRequirement):
injector.get(TransitiveA)
with pytest.raises(UnsatisfiedRequirement):
injector.get(TransitiveB)
def test_inject_singleton():
class A:
@inject
def __init__(self, b: EmptyClass):
self.b = b
def configure(binder):
binder.bind(A)
binder.bind(EmptyClass, scope=SingletonScope)
injector1 = Injector(configure)
a1 = injector1.get(A)
a2 = injector1.get(A)
assert a1.b is a2.b
@singleton
class SingletonB:
pass
def test_inject_decorated_singleton_class():
class A:
@inject
def __init__(self, b: SingletonB):
self.b = b
def configure(binder):
binder.bind(A)
binder.bind(SingletonB)
injector1 = Injector(configure)
a1 = injector1.get(A)
a2 = injector1.get(A)
assert a1.b is a2.b
assert a1 is not a2
def test_injecting_an_auto_bound_decorated_singleton_class():
class A:
@inject
def __init__(self, b: SingletonB):
self.b = b
injector1 = Injector()
a1 = injector1.get(A)
a2 = injector1.get(A)
assert a1.b is a2.b
assert a1 is not a2
def test_a_decorated_singleton_is_shared_between_parent_and_child_injectors_when_parent_creates_it_first():
parent_injector = Injector()
child_injector = parent_injector.create_child_injector()
assert parent_injector.get(SingletonB) is child_injector.get(SingletonB)
def test_a_decorated_singleton_is_shared_between_parent_and_child_injectors_when_child_creates_it_first():
parent_injector = Injector()
child_injector = parent_injector.create_child_injector()
assert child_injector.get(SingletonB) is parent_injector.get(SingletonB)
# Test for https://github.com/python-injector/injector/issues/207
def test_a_decorated_singleton_is_shared_among_child_injectors():
parent_injector = Injector()
child_injector_1 = parent_injector.create_child_injector()
child_injector_2 = parent_injector.create_child_injector()
assert child_injector_1.get(SingletonB) is child_injector_2.get(SingletonB)
def test_a_decorated_singleton_should_not_override_explicit_binds():
parent_injector = Injector()
child_injector = parent_injector.create_child_injector()
grand_child_injector = child_injector.create_child_injector()
bound_singleton = SingletonB()
child_injector.binder.bind(SingletonB, to=bound_singleton)
assert parent_injector.get(SingletonB) is not bound_singleton
assert child_injector.get(SingletonB) is bound_singleton
assert grand_child_injector.get(SingletonB) is bound_singleton
def test_binding_a_singleton_to_a_child_injector_does_not_affect_the_parent_injector():
parent_injector = Injector()
child_injector = parent_injector.create_child_injector()
child_injector.binder.bind(EmptyClass, scope=singleton)
assert child_injector.get(EmptyClass) is child_injector.get(EmptyClass)
assert child_injector.get(EmptyClass) is not parent_injector.get(EmptyClass)
assert parent_injector.get(EmptyClass) is not parent_injector.get(EmptyClass)
def test_a_decorated_singleton_should_not_override_a_child_provider():
parent_injector = Injector()
provided_instance = SingletonB()
class MyModule(Module):
@provider
def provide_name(self) -> SingletonB:
return provided_instance
child_injector = parent_injector.create_child_injector([MyModule])
assert child_injector.get(SingletonB) is provided_instance
assert parent_injector.get(SingletonB) is not provided_instance
assert parent_injector.get(SingletonB) is parent_injector.get(SingletonB)
# Test for https://github.com/python-injector/injector/issues/207
def test_a_decorated_singleton_is_created_as_close_to_the_root_where_dependencies_fulfilled():
class NonInjectableD:
@inject
def __init__(self, required) -> None:
self.required = required
@singleton
class SingletonC:
@inject
def __init__(self, d: NonInjectableD):
self.d = d
parent_injector = Injector()
child_injector_1 = parent_injector.create_child_injector()
child_injector_2 = parent_injector.create_child_injector()
child_injector_2_1 = child_injector_2.create_child_injector()
provided_d = NonInjectableD(required=True)
child_injector_2.binder.bind(NonInjectableD, to=provided_d)
assert child_injector_2_1.get(SingletonC) is child_injector_2.get(SingletonC)
assert child_injector_2.get(SingletonC).d is provided_d
with pytest.raises(CallError):
parent_injector.get(SingletonC)
with pytest.raises(CallError):
child_injector_1.get(SingletonC)
def test_a_bound_decorated_singleton_is_created_as_close_to_the_root_where_it_exists_when_auto_bind_is_disabled():
parent_injector = Injector(auto_bind=False)
child_injector_1 = parent_injector.create_child_injector(auto_bind=False)
child_injector_2 = parent_injector.create_child_injector(auto_bind=False)
child_injector_2_1 = child_injector_2.create_child_injector(auto_bind=False)
child_injector_2.binder.bind(SingletonB)
assert child_injector_2_1.get(SingletonB) is child_injector_2_1.get(SingletonB)
assert child_injector_2_1.get(SingletonB) is child_injector_2.get(SingletonB)
with pytest.raises(UnsatisfiedRequirement):
parent_injector.get(SingletonB)
with pytest.raises(UnsatisfiedRequirement):
child_injector_1.get(SingletonB)
def test_threadlocal():
@threadlocal
class A:
def __init__(self):
pass
def configure(binder):
binder.bind(A)
injector = Injector(configure)
a1 = injector.get(A)
a2 = injector.get(A)
assert a1 is a2
a3 = [None]
ready = threading.Event()
def inject_a3():
a3[0] = injector.get(A)
ready.set()
threading.Thread(target=inject_a3).start()
ready.wait(1.0)
assert a2 is not a3[0] and a3[0] is not None
class Interface2:
pass
def test_injecting_interface_implementation():
class Implementation:
pass
class A:
@inject
def __init__(self, i: Interface2):
self.i = i
def configure(binder):
binder.bind(A)
binder.bind(Interface2, to=Implementation)
injector = Injector(configure)
a = injector.get(A)
assert isinstance(a.i, Implementation)
class CyclicInterface:
pass
class CyclicA:
@inject
def __init__(self, i: CyclicInterface):
self.i = i
class CyclicB:
@inject
def __init__(self, a: CyclicA):
self.a = a
def test_cyclic_dependencies():
def configure(binder):
binder.bind(CyclicInterface, to=CyclicB)
binder.bind(CyclicA)
injector = Injector(configure)
with pytest.raises(CircularDependency):
injector.get(CyclicA)
class CyclicInterface2:
pass
class CyclicA2:
@inject
def __init__(self, i: CyclicInterface2):
self.i = i
class CyclicB2:
@inject
def __init__(self, a_builder: AssistedBuilder[CyclicA2]):
self.a = a_builder.build(i=self)
def test_dependency_cycle_can_be_worked_broken_by_assisted_building():
def configure(binder):
binder.bind(CyclicInterface2, to=CyclicB2)
binder.bind(CyclicA2)
injector = Injector(configure)
# Previously it'd detect a circular dependency here:
# 1. Constructing CyclicA2 requires CyclicInterface2 (bound to CyclicB2)
# 2. Constructing CyclicB2 requires assisted build of CyclicA2
# 3. Constructing CyclicA2 triggers circular dependency check
assert isinstance(injector.get(CyclicA2), CyclicA2)
class Interface5:
constructed = False
def __init__(self):
Interface5.constructed = True
def test_that_injection_is_lazy():
class A:
@inject
def __init__(self, i: Interface5):
self.i = i
def configure(binder):
binder.bind(Interface5)
binder.bind(A)
injector = Injector(configure)
assert not (Interface5.constructed)
injector.get(A)
assert Interface5.constructed
def test_module_provider():
class MyModule(Module):
@provider
def provide_name(self) -> str:
return 'Bob'
module = MyModule()
injector = Injector(module)
assert injector.get(str) == 'Bob'
def test_module_class_gets_instantiated():
name = 'Meg'
class MyModule(Module):
def configure(self, binder):
binder.bind(str, to=name)
injector = Injector(MyModule)
assert injector.get(str) == name
def test_inject_and_provide_coexist_happily():
class MyModule(Module):
@provider
def provide_weight(self) -> float:
return 50.0
@provider
def provide_age(self) -> int:
return 25
# TODO(alec) Make provider/inject order independent.
@provider
@inject
def provide_description(self, age: int, weight: float) -> str:
return 'Bob is %d and weighs %0.1fkg' % (age, weight)
assert Injector(MyModule()).get(str) == 'Bob is 25 and weighs 50.0kg'
Names = NewType('Names', List[str])
Passwords = NewType('Ages', Dict[str, str])
def test_multibind():
# First let's have some explicit multibindings
def configure(binder):
binder.multibind(List[str], to=['not a name'])
binder.multibind(Dict[str, str], to={'asd': 'qwe'})
# To make sure Lists and Dicts of different subtypes are treated distinctly
binder.multibind(List[int], to=[1, 2, 3])
binder.multibind(Dict[str, int], to={'weight': 12})
# To see that NewTypes are treated distinctly
binder.multibind(Names, to=['Bob'])
binder.multibind(Passwords, to={'Bob': 'password1'})
# Then @multiprovider-decorated Module methods
class CustomModule(Module):
@multiprovider
def provide_some_ints(self) -> List[int]:
return [4, 5, 6]
@multiprovider
def provide_some_strs(self) -> List[str]:
return ['not a name either']
@multiprovider
def provide_str_to_str_mapping(self) -> Dict[str, str]:
return {'xxx': 'yyy'}
@multiprovider
def provide_str_to_int_mapping(self) -> Dict[str, int]:
return {'height': 33}
@multiprovider
def provide_names(self) -> Names:
return ['Alice', 'Clarice']
@multiprovider
def provide_passwords(self) -> Passwords:
return {'Alice': 'aojrioeg3', 'Clarice': 'clarice30'}
injector = Injector([configure, CustomModule])
assert injector.get(List[str]) == ['not a name', 'not a name either']
assert injector.get(List[int]) == [1, 2, 3, 4, 5, 6]
assert injector.get(Dict[str, str]) == {'asd': 'qwe', 'xxx': 'yyy'}
assert injector.get(Dict[str, int]) == {'weight': 12, 'height': 33}
assert injector.get(Names) == ['Bob', 'Alice', 'Clarice']
assert injector.get(Passwords) == {'Bob': 'password1', 'Alice': 'aojrioeg3', 'Clarice': 'clarice30'}
def test_regular_bind_and_provider_dont_work_with_multibind():
# We only want multibind and multiprovider to work to avoid confusion
Names = NewType('Names', List[str])
Passwords = NewType('Passwords', Dict[str, str])
class MyModule(Module):
with pytest.raises(Error):
@provider
def provide_strs(self) -> List[str]:
return []
with pytest.raises(Error):
@provider
def provide_names(self) -> Names:
return []
with pytest.raises(Error):
@provider
def provide_strs_in_dict(self) -> Dict[str, str]:
return {}
with pytest.raises(Error):
@provider
def provide_passwords(self) -> Passwords:
return {}
injector = Injector()
binder = injector.binder
with pytest.raises(Error):
binder.bind(List[str], to=[])
with pytest.raises(Error):
binder.bind(Names, to=[])
with pytest.raises(Error):
binder.bind(Dict[str, str], to={})
with pytest.raises(Error):
binder.bind(Passwords, to={})
def test_auto_bind():
class A:
pass
injector = Injector()
assert isinstance(injector.get(A), A)
def test_auto_bind_with_newtype():
# Reported in https://github.com/alecthomas/injector/issues/117
class A:
pass
AliasOfA = NewType('AliasOfA', A)
injector = Injector()
assert isinstance(injector.get(AliasOfA), A)
class Request:
pass
class RequestScope(Scope):
def configure(self):
self.context = None
@contextmanager
def __call__(self, request):
assert self.context is None
self.context = {}
binder = self.injector.get(Binder)
binder.bind(Request, to=request, scope=RequestScope)
yield
self.context = None
def get(self, key, provider):
if self.context is None:
raise UnsatisfiedRequirement(None, key)
try:
return self.context[key]
except KeyError:
provider = InstanceProvider(provider.get(self.injector))
self.context[key] = provider
return provider
request = ScopeDecorator(RequestScope)
@request
class Handler:
def __init__(self, request):
self.request = request
class RequestModule(Module):
@provider
@inject
def handler(self, request: Request) -> Handler:
return Handler(request)
def test_custom_scope():
injector = Injector([RequestModule()], auto_bind=False)
with pytest.raises(UnsatisfiedRequirement):
injector.get(Handler)
scope = injector.get(RequestScope)
request = Request()
with scope(request):
handler = injector.get(Handler)
assert handler.request is request
with pytest.raises(UnsatisfiedRequirement):
injector.get(Handler)
def test_binder_install():
class ModuleA(Module):
def configure(self, binder):
binder.bind(str, to='hello world')
class ModuleB(Module):
def configure(self, binder):
binder.install(ModuleA())
injector = Injector([ModuleB()])
assert injector.get(str) == 'hello world'
def test_binder_provider_for_method_with_explicit_provider():
injector = Injector()
binder = injector.binder
provider = binder.provider_for(int, to=InstanceProvider(1))
assert type(provider) is InstanceProvider
assert provider.get(injector) == 1
def test_binder_provider_for_method_with_instance():
injector = Injector()
binder = injector.binder
provider = binder.provider_for(int, to=1)
assert type(provider) is InstanceProvider
assert provider.get(injector) == 1
def test_binder_provider_for_method_with_class():
injector = Injector()
binder = injector.binder
provider = binder.provider_for(int)
assert type(provider) is ClassProvider
assert provider.get(injector) == 0
def test_binder_provider_for_method_with_class_to_specific_subclass():
class A:
pass
class B(A):
pass
injector = Injector()
binder = injector.binder
provider = binder.provider_for(A, B)
assert type(provider) is ClassProvider
assert isinstance(provider.get(injector), B)
def test_binder_provider_for_type_with_metaclass():
# use a metaclass cross python2/3 way
# otherwise should be:
# class A(object, metaclass=abc.ABCMeta):
# passa
A = abc.ABCMeta('A', (object,), {})
injector = Injector()
binder = injector.binder
assert isinstance(binder.provider_for(A, None).get(injector), A)
class ClassA:
def __init__(self, parameter):
pass
class ClassB:
@inject
def __init__(self, a: ClassA):
pass
def test_injecting_undecorated_class_with_missing_dependencies_raises_the_right_error():
injector = Injector()
try:
injector.get(ClassB)
except CallError as ce:
check_exception_contains_stuff(ce, ('ClassA.__init__', 'ClassB'))
def test_call_to_method_with_legitimate_call_error_raises_type_error():
class A:
def __init__(self):
max()
injector = Injector()
with pytest.raises(TypeError):
injector.get(A)
def test_call_error_str_representation_handles_single_arg():
ce = CallError('zxc')
assert str(ce) == 'zxc'
class NeedsAssistance:
@inject
def __init__(self, a: str, b):
self.a = a
self.b = b
def test_assisted_builder_works_when_got_directly_from_injector():
injector = Injector()
builder = injector.get(AssistedBuilder[NeedsAssistance])
obj = builder.build(b=123)
assert (obj.a, obj.b) == (str(), 123)
def test_assisted_builder_works_when_injected():
class X:
@inject
def __init__(self, builder: AssistedBuilder[NeedsAssistance]):
self.obj = builder.build(b=234)
injector = Injector()
x = injector.get(X)
assert (x.obj.a, x.obj.b) == (str(), 234)
class Interface:
b = 0
def test_assisted_builder_uses_bindings():
def configure(binder):
binder.bind(Interface, to=NeedsAssistance)
injector = Injector(configure)
builder = injector.get(AssistedBuilder[Interface])
x = builder.build(b=333)
assert (type(x), x.b) == (NeedsAssistance, 333)
def test_assisted_builder_uses_concrete_class_when_specified():
class X:
pass
def configure(binder):
# meant only to show that provider isn't called
binder.bind(X, to=lambda: 1 / 0)
injector = Injector(configure)
builder = injector.get(ClassAssistedBuilder[X])
builder.build()
def test_assisted_builder_injection_is_safe_to_use_with_multiple_injectors():
class X:
@inject
def __init__(self, builder: AssistedBuilder[NeedsAssistance]):
self.builder = builder
i1, i2 = Injector(), Injector()
b1 = i1.get(X).builder
b2 = i2.get(X).builder
assert (b1._injector, b2._injector) == (i1, i2)
def test_assisted_builder_injection_is_safe_to_use_with_child_injectors():
class X:
@inject
def __init__(self, builder: AssistedBuilder[NeedsAssistance]):
self.builder = builder
i1 = Injector()
i2 = i1.create_child_injector()
b1 = i1.get(X).builder
b2 = i2.get(X).builder
assert (b1._injector, b2._injector) == (i1, i2)
class TestThreadSafety:
def setup_method(self):
self.event = threading.Event()
def configure(binder):
binder.bind(str, to=lambda: self.event.wait() and 'this is str')
class XXX:
@inject
def __init__(self, s: str):
pass
self.injector = Injector(configure)
self.cls = XXX
def gather_results(self, count):
objects = []
lock = threading.Lock()
def target():
o = self.injector.get(self.cls)
with lock:
objects.append(o)
threads = [threading.Thread(target=target) for i in range(count)]
for t in threads:
t.start()
self.event.set()
for t in threads:
t.join()
return objects
def test_injection_is_thread_safe(self):
objects = self.gather_results(2)
assert len(objects) == 2
def test_singleton_scope_is_thread_safe(self):