forked from facebook/TestSlide
/
strict_mock.py
902 lines (792 loc) · 32.9 KB
/
strict_mock.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
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import copy
import dis
import inspect
import os.path
from types import FrameType
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Optional,
Type,
Union,
get_type_hints,
)
from . import lib, mock_callable
if TYPE_CHECKING:
# Hack to enable typing information for mypy
from testslide.core.mock_callable import _CallableMock, _YieldValuesRunner # noqa: F401
class UndefinedAttribute(BaseException):
"""
Tentative access of an attribute from a StrictMock that is not defined yet.
Inherits from BaseException to avoid being caught by tested code.
"""
def __init__(
self, strict_mock: "StrictMock", name: str, extra_msg: Optional[str] = None
) -> None:
super().__init__(strict_mock, name)
self.strict_mock = strict_mock
self.name = name
self.extra_msg = extra_msg
def __str__(self) -> str:
message = (
f"'{self.name}' is not set.\n"
f"{repr(self.strict_mock)} must have a value set for this attribute "
"if it is going to be accessed."
)
if self.extra_msg is not None:
message += f"\n{self.extra_msg}"
return message
class NonExistentAttribute(BaseException):
"""
Tentative of setting of an attribute from a StrictMock that is not present
at the template class.
Inherits from BaseException to avoid being caught by tested code.
"""
def __init__(self, strict_mock: "StrictMock", name: str) -> None:
super().__init__(strict_mock, name)
self.strict_mock = strict_mock
self.name = name
def __str__(self) -> str:
return (
f"'{self.name}' is not part of the API.\n"
f"{self.strict_mock} template class API does not have this "
"attribute so the mock can not have it as well.\n"
"If you are inheriting StrictMock, you can define private "
"attributes, that will not interfere with the API, by prefixing "
"them with '__' (and at most one '_' suffix) "
" (https://docs.python.org/3/tutorial/classes.html#tut-private).\n"
"See also: 'runtime_attrs' at StrictMock.__init__."
)
class NonCallableValue(BaseException):
"""
Raised when trying to set a non callable value to a callable attribute of
a StrictMock instance.
"""
def __init__(self, strict_mock: "StrictMock", name: str) -> None:
super().__init__(strict_mock, name)
self.strict_mock = strict_mock
self.name = name
def __str__(self) -> str:
return (
f"'{self.name}' can not be set with a non-callable value.\n"
f"{self.strict_mock} template class requires this attribute to "
"be callable."
)
class NonAwaitableReturn(BaseException):
"""
Raised when a coroutine method at a StrictMock is assigned a not coroutine
callable function.
"""
def __init__(self, strict_mock: "StrictMock", name: str) -> None:
super().__init__(strict_mock, name)
self.strict_mock = strict_mock
self.name = name
def __str__(self) -> str:
return (
f"'{self.name}' can not be set with a callable that does not "
"return an awaitable.\n"
f"{self.strict_mock} template class requires this attribute to "
"be a callable that returns an awaitable (eg: a 'async def' "
"function)."
)
class UnsupportedMagic(BaseException):
"""
Raised when trying to set an unsupported magic attribute to a StrictMock
instance.
"""
def __init__(self, strict_mock: "StrictMock", name: str) -> None:
super().__init__(strict_mock, name)
self.strict_mock = strict_mock
self.name = name
def __str__(self) -> str:
return f"setting '{self.name}' is not supported."
class _DefaultMagic:
CONTEXT_MANAGER_METHODS = ["__enter__", "__exit__", "__aenter__", "__aexit__"]
def __init__(self, strict_mock: "StrictMock", name: str):
self.strict_mock = strict_mock
self.name = name
def __call__(self, *args: Any, **kwargs: Any) -> None:
message = None
if self.name in self.CONTEXT_MANAGER_METHODS:
message = (
"Tip: most context managers can be automatically configured "
"with 'default_context_manager=True'."
)
raise UndefinedAttribute(self.strict_mock, self.name, message)
def __copy__(self) -> "_DefaultMagic":
return type(self)(strict_mock=self.strict_mock, name=self.name)
def __deepcopy__(self, memo: Optional[Dict[Any, Any]] = None) -> "_DefaultMagic":
if memo is None:
memo = {}
self_copy = type(self)(strict_mock=self.strict_mock, name=self.name)
memo[id(self)] = self_copy
return self_copy
class _MethodProxy:
"""
When setting callable attributes, the new value is wrapped by another
function that does signature and async validations. We then need this proxy
around it, so that when the attribute is called, the mock value is called
(the wrapper function which then calls the new value) but all attribute
access is forwarded to the new value.
"""
def __init__(self, value: Any, callable_value: Optional[Callable] = None) -> None:
self.__dict__["_value"] = value
self.__dict__["_callable_value"] = callable_value or value
def __get__(
self, instance: "StrictMock", owner: Optional[Type["StrictMock"]] = None
) -> Union[object, Callable]:
if self.__dict__["_value"] is self.__dict__["_callable_value"]:
return self.__dict__["_callable_value"]
else:
return self
def __getattr__(self, name: str) -> str:
return getattr(self.__dict__["_value"], name)
def __setattr__(self, name: str, value: str) -> None:
return setattr(self.__dict__["_value"], name, value)
def __delattr__(self, name: str) -> None:
return delattr(self.__dict__["_value"], name)
def __call__(self, *args: Any, **kwargs: Any) -> Optional[Any]:
return self.__dict__["_callable_value"](*args, **kwargs)
def __copy__(self) -> "_MethodProxy":
return type(self)(
callable_value=self.__dict__["_callable_value"],
value=self.__dict__["_value"],
)
def __deepcopy__(self, memo: Optional[Dict[Any, Any]] = None) -> "_MethodProxy":
if memo is None:
memo = {}
self_copy = type(self)(
callable_value=copy.deepcopy(self.__dict__["_callable_value"]),
value=copy.deepcopy(self.__dict__["_value"]),
)
memo[id(self)] = self_copy
return self_copy
def __repr__(self) -> str:
# Override repr to have a representation that provides information
# about the wrapped method
return repr(self.__dict__["_value"])
class StrictMock:
"""
Mock object that won't allow any attribute access or method call, unless its
behavior has been explicitly defined. This is meant to be a safer
alternative to Python's standard Mock object, that will always return
another mock when referred by default.
StrictMock is "safe by default", meaning that it will never misbehave by
lack of configuration. It will raise in the following situations:
- Get/Set attribute that's not part of the specification (template or
runtime_attrs).
- Get attribute that is part of the specification, but has not yet been
defined.
- Call a method with different signature from the template.
When appropriate, raised exceptions inherits from BaseException, in order to
let exceptions raise the test, outside tested code, so we can get a clear
signal of what is happening: either the mock is missing a required behavior
or the tested code is misbehaving.
"""
TRIM_PATH_PREFIX = ""
# All of these magic should be OK to be set at the mock and they are
# expected to work as they should. If implemented by the template class,
# they will have default values assigned to them, that raise
# UndefinedAttribute until configured.
__SETTABLE_MAGICS = [
"__abs__",
"__add__",
"__aenter__",
"__aexit__",
"__aiter__",
"__and__",
"__anext__",
"__await__",
"__bool__",
"__bytes__",
"__call__",
"__ceil__",
"__complex__",
"__contains__",
"__delete__",
"__delitem__",
"__divmod__",
"__enter__",
"__enter__",
"__eq__",
"__exit__",
"__exit__",
"__float__",
"__floor__",
"__floordiv__",
"__format__",
"__ge__",
"__get__",
"__getformat__",
"__getinitargs__",
"__getitem__",
"__getnewargs__",
"__getnewargs_ex__",
"__getstate__",
"__gt__",
"__iadd__",
"__iand__",
"__ifloordiv__",
"__ilshift__",
"__imatmul__",
"__imod__",
"__imul__",
"__index__",
"__instancecheck__",
"__int__",
"__invert__",
"__ior__",
"__ipow__",
"__irshift__",
"__isub__",
"__iter__",
"__iter__",
"__iter__",
"__itruediv__",
"__ixor__",
"__le__",
"__len__",
"__length_hint__",
"__lshift__",
"__lt__",
"__matmul__",
"__missing__",
"__mod__",
"__mul__",
"__name__",
"__ne__",
"__neg__",
"__next__",
"__or__",
"__pos__",
"__pow__",
"__qualname__",
"__radd__",
"__rand__",
"__rdivmod__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__rfloordiv__",
"__rlshift__",
"__rmatmul__",
"__rmod__",
"__rmul__",
"__ror__",
"__round__",
"__rpow__",
"__rrshift__",
"__rshift__",
"__rsub__",
"__rtruediv__",
"__rxor__",
"__set__",
"__set_name__",
"__setformat__",
"__setitem__",
"__setstate__",
"__sizeof__",
"__str__",
"__sub__",
"__subclasscheck__",
"__truediv__",
"__trunc__",
"__xor__",
]
# These magics either won't work or makes no sense to be set for mock after
# an instance of a class. Trying to set them will raise UnsupportedMagic.
__UNSETTABLE_MAGICS = [
"__bases__",
"__class__",
"__class_getitem__",
"__copy__",
"__deepcopy__",
"__del__",
"__delattr__",
"__dict__",
"__dir__",
"__getattr__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__mro__",
"__new__",
"__setattr__",
"__slots__",
"__subclasses__",
]
def __new__(
cls,
template: Optional[type] = None,
runtime_attrs: Optional[List[Any]] = None,
name: Optional[str] = None,
default_context_manager: bool = False,
type_validation: bool = True,
attributes_to_skip_type_validation: List[str] = [],
) -> "StrictMock":
"""
For every new instance of StrictMock we dynamically create a subclass of
StrictMock and return an instance of it. This allows us to use this new
subclass dictionary for all attributes, including magic ones, that must
be defined at the class to work.
"""
name = f"{template.__name__}{cls.__name__}" if template else cls.__name__
strict_mock_subclass = type(name, (cls,), {})
return object.__new__(strict_mock_subclass)
def __setup_magic_methods(self) -> None:
"""
Populate all template's magic methods with expected default behavior.
This is important as things such as bool() depend on they existing
on the object's class __dict__.
https://github.com/facebook/TestSlide/issues/23
"""
if not self._template:
return
implemented_magic_methods = []
for klass in type(self).mro():
if klass is object:
continue
for name in klass.__dict__:
if name.startswith("__") and name.endswith("__"):
implemented_magic_methods.append(name)
for klass in self._template.mro():
if klass is object:
continue
for name in klass.__dict__:
if name in type(self).__dict__:
continue
if name == "__hash__":
if klass.__dict__["__hash__"] is None:
setattr(self, name, None)
else:
setattr(self, name, lambda: id(self))
continue
if (
callable(klass.__dict__[name])
and name in self.__SETTABLE_MAGICS
and name not in self.__UNSETTABLE_MAGICS
and name not in implemented_magic_methods
):
setattr(self, name, _DefaultMagic(self, name))
# THE PROBLEM:
# Certain idiomatic python use-cases (*cough* (Async)ExitStack *cough*)
# invoke context managers with roughly the following code:
#
# enter_fn = cm.__class__.__aenter__
# await enter_fn(cm)
#
# While fine for 'normal' python objects, this is problematic for how our
# MethodProxy builds functions; as they don't end up properly bound
# (i.e. via __get__) to the object; and end up failing with cryptic errors
# like:
#
# 'aenter invoked with 1 arguments; expected 0'.
#
# To fix this; let's properly define these as real method on the object so
# they get bound. They still will not be visible to outside code due to our
# validating in __getattr__ that they match relevant entries in the template
def __enter_default_context_manager_helper__(self):
return self
def __exit_default_context_manager_helper__(self, exc_type, exc_value, traceback):
pass
async def __aenter_default_context_manager_helper__(self):
return self
async def __aexit_default_context_manager_helper__(
self, exc_type, exc_value, traceback
):
pass
def __setup_default_context_manager(self, default_context_manager: bool) -> None:
if self._template and default_context_manager:
if hasattr(self._template, "__enter__") and hasattr(
self._template, "__exit__"
):
# Use setattr(type(self)) to explicitly avoid any MethodProxy
# magic which breaks the method-bind.
# Also needed for getattr to bypass our template class check.
setattr( # noqa: B010
type(self),
"__enter__",
getattr( # noqa: B009
type(self), "__enter_default_context_manager_helper__"
),
)
setattr( # noqa: B010
type(self),
"__exit__",
getattr( # noqa: B009
type(self), "__exit_default_context_manager_helper__"
),
)
if hasattr(self._template, "__aenter__") and hasattr(
self._template, "__aexit__"
):
# Use setattr(type(self)) to explicitly avoid any MethodProxy
# magic which breaks the method-bind.
# Also needed for getattr to bypass our template class check.
setattr( # noqa: B010
type(self),
"__aenter__",
getattr( # noqa: B009
type(self), "__aenter_default_context_manager_helper__"
),
)
setattr( # noqa: B010
type(self),
"__aexit__",
getattr( # noqa: B009
type(self), "__aexit_default_context_manager_helper__"
),
)
def __get_caller_frame(self, depth: int) -> FrameType:
# Adding extra 3 to account for the stack:
# __get_caller_frame
# __get_caller
# __init__
depth += 3
current_frame = inspect.currentframe()
while current_frame:
depth -= 1
if not depth:
break
current_frame = current_frame.f_back
return current_frame # type: ignore
def __get_caller(self, depth: int) -> Optional[str]:
# Doing inspect.stack will retrieve the whole stack, including context
# and that is really slow, this only retrieves the minimum, and does
# not read the file contents.
caller_frame = self.__get_caller_frame(depth)
# loading the context ends up reading files from disk and that might block
# the event loop, so we don't do it.
frameinfo = inspect.getframeinfo(caller_frame, context=0)
filename = frameinfo.filename
lineno = frameinfo.lineno
if self.TRIM_PATH_PREFIX:
split = filename.split(self.TRIM_PATH_PREFIX)
if len(split) == 2 and not split[0]:
filename = split[1]
if os.path.exists(filename):
return "{}:{}".format(filename, lineno)
else:
return None
def __setup_subclass(self):
"""
When StrictMock is subclassed, any attributes defined at the subclass
will override any of StrictMock's validations. In order to overcome
this, for attributes that makes sense, we set them at StrictMock's
dynamically created subclass from __new__ using __setattr__, so that
all validations work.
"""
if type(self).mro()[1] == StrictMock:
return
for klass in type(self).mro()[1:]:
if klass == StrictMock:
break
for name in klass.__dict__.keys():
if name in [
"__doc__",
"__init__",
"__module__",
]:
continue
# https://docs.python.org/3/tutorial/classes.html#tut-private
if name.startswith(f"_{type(self).__name__}__") and not name.endswith(
"__"
):
continue
if name == "__hash__" and klass.__dict__["__hash__"] is None:
continue
StrictMock.__setattr__(self, name, getattr(self, name))
def __init__(
self,
template: Optional[type] = None,
runtime_attrs: Optional[List[Any]] = None,
name: Optional[str] = None,
default_context_manager: bool = False,
type_validation: bool = True,
attributes_to_skip_type_validation: List[str] = [],
) -> None:
"""
template: Template class to be used as a template for the mock.
runtime_attrs: Often attributes are created within an instance's
lifecycle, typically from __init__(). To allow mocking such attributes,
specify their names here.
name: an optional name for this mock instance.
default_context_manager: If the template class is a context manager,
setup a mock for __enter__/__aenter__ that yields itself and an empty function
for __exit__/__aexit__.
type_validation: validate callable attributes calls against the
template's method signature and use type hinting information from template
to validate that mock attribute types match them. Type validation also
happens forcallable attributes (instance/static/class methods) calls.
_attributes_to_skip_type_validation: do not validate type for these attributes
of the strictmock instance.
"""
if template is not None and not inspect.isclass(template):
raise ValueError("Template must be a class.")
self.__dict__["_template"] = template
self.__dict__["_runtime_attrs"] = runtime_attrs or []
self.__dict__["_name"] = name
self.__dict__["_type_validation"] = type_validation
self.__dict__["__caller"] = self.__get_caller(1)
# black on py3.7 formats this differently to black on py3.8+ -_-
# fmt: off
self.__dict__["_attributes_to_skip_type_validation"] = (
attributes_to_skip_type_validation
)
# fmt: on
caller_frame = inspect.currentframe().f_back # type: ignore
# loading the context ends up reading files from disk and that might block
# the event loop, so we don't do it.
caller_frame_info = inspect.getframeinfo(caller_frame, context=0) # type: ignore
self.__dict__["_caller_frame_info"] = caller_frame_info
self.__setup_magic_methods()
self.__setup_default_context_manager(default_context_manager)
self.__setup_subclass()
@property # type: ignore
def __class__(self) -> type:
return self._template if self._template is not None else type(self)
@property
def _template(self) -> None:
import testslide.mock_constructor # Avoid cyclic dependencies
# If the template class was mocked with mock_constructor(), this will
# return the mocked subclass, which contains all attributes we need for
# introspection.
return testslide.mock_constructor._get_class_or_mock(self.__dict__["_template"])
# FIXME change to __runtime_attrs
@property
def _runtime_attrs(self) -> Optional[List[Any]]:
return self.__dict__["_runtime_attrs"]
def __template_has_attr(self, name: str) -> bool:
def get_class_init(klass: type) -> Callable:
import testslide.mock_constructor # Avoid cyclic dependencies
if not testslide.mock_constructor._is_mocked_class(klass):
return klass.__init__ # type: ignore
# If klass is the mocked subclass, pull the original version of
# __init__ so we can introspect into its implementation (and
# not the __init__ wrapper at the mocked class).
mocked_class = klass
original_class = mocked_class.mro()[1]
return testslide.mock_constructor._get_original_init(
original_class, instance=None, owner=mocked_class
)
def is_runtime_attr() -> bool:
if self._template:
for klass in self._template.mro():
template_init = get_class_init(klass)
if not inspect.isfunction(template_init):
continue
for instruction in dis.get_instructions(template_init):
if (
instruction.opname == "STORE_ATTR"
and name == instruction.argval
):
return True
return False
return (
hasattr(self._template, name)
or name in self._runtime_attrs # type: ignore
or name in getattr(self._template, "__slots__", [])
or is_runtime_attr()
)
@staticmethod
def __is_magic_method(name: str) -> bool:
return name.startswith("__") and name.endswith("__")
def __validate_attribute_type(self, name: str, value: Any) -> None:
if (
not self.__dict__["_type_validation"]
or name in self.__dict__["_attributes_to_skip_type_validation"]
):
return
if self._template is not None:
try:
annotations = get_type_hints(self._template)
except Exception:
# Some modules can throw KeyError : https://bugs.python.org/issue41515
annotations = {}
if name in annotations:
lib._validate_argument_type(annotations[name], name, value)
def __validate_and_wrap_mock_value(self, name: str, value: Any) -> Any:
if self._template:
if not self.__template_has_attr(name):
if not (
name.startswith(f"_{type(self).__name__}__")
and not name.endswith("__")
):
raise NonExistentAttribute(self, name)
self.__validate_attribute_type(name, value)
if hasattr(self._template, name):
template_value = getattr(self._template, name)
if callable(template_value):
if not callable(value):
raise NonCallableValue(self, name)
if self.__dict__["_type_validation"]:
signature_validation_wrapper = (
lib._wrap_signature_and_type_validation(
value,
self._template,
name,
self.__dict__["_type_validation"],
)
)
if inspect.iscoroutinefunction(template_value):
async def awaitable_return_validation_wrapper(
*args, **kwargs
):
result_awaitable = signature_validation_wrapper(
*args, **kwargs
)
if not inspect.isawaitable(result_awaitable):
raise NonAwaitableReturn(self, name)
return_value = await result_awaitable
if not lib._is_wrapped_for_signature_and_type_validation(
# The original value was already wrapped for type
# validation. Skipping additional validation to
# allow, for example, mock_callable to disable
# validation for a very specific mock call rather
# for the whole StrictMock instance
value
) and not isinstance(
# If the return value is a _BaseRunner then type
# validation, if needed, has already been performed
return_value,
mock_callable._BaseRunner,
):
lib._validate_return_type(
template_value,
return_value,
self.__dict__["_caller_frame_info"],
)
return return_value
callable_value = awaitable_return_validation_wrapper
else:
def return_validation_wrapper(*args, **kwargs):
return_value = signature_validation_wrapper(
*args, **kwargs
)
if not lib._is_wrapped_for_signature_and_type_validation(
# The original value was already wrapped for type
# validation. Skipping additional validation to
# allow, for example, mock_callable to disable
# validation for a very specific mock call rather
# for the whole StrictMock instance
value
) and not isinstance(
# If the return value is a _BaseRunner then type
# validation, if needed, has already been performed
return_value,
mock_callable._BaseRunner,
):
lib._validate_return_type(
template_value,
return_value,
self.__dict__["_caller_frame_info"],
)
return return_value
callable_value = return_validation_wrapper
else:
callable_value = None
return _MethodProxy(value=value, callable_value=callable_value)
else:
if callable(value):
# We don't really need the proxy here, but it serves the
# double purpose of swallowing self / cls when needed.
return _MethodProxy(value=value)
else:
if callable(value):
# We don't really need the proxy here, but it serves the
# double purpose of swallowing self / cls when needed.
return _MethodProxy(value=value)
return value
def __setattr__(self, name: str, value: Any) -> None:
if self.__is_magic_method(name):
# ...check whether we're allowed to mock...
if (
name in self.__UNSETTABLE_MAGICS
or (name in StrictMock.__dict__ and name not in self.__SETTABLE_MAGICS)
) and name != "__hash__":
raise UnsupportedMagic(self, name)
# ...or if it is something unsupported.
if name not in self.__SETTABLE_MAGICS and name != "__hash__":
raise NotImplementedError(
f"StrictMock does not implement support for {name}"
)
if name == "__hash__" and name in type(self).__dict__:
raise UnsupportedMagic(self, name)
mock_value = self.__validate_and_wrap_mock_value(name, value)
setattr(type(self), name, mock_value)
def __getattr__(self, name: str) -> Any:
if self._template and self.__template_has_attr(name):
raise UndefinedAttribute(self, name)
else:
raise AttributeError(f"'{name}' was not set for {repr(self)}.")
def __delattr__(self, name: str) -> None:
if name in type(self).__dict__:
delattr(type(self), name)
def __repr__(self) -> str:
template_str = (
" template={}.{}".format(self._template.__module__, self._template.__name__) # type: ignore
if self._template
else ""
)
if self.__dict__["_name"]:
name_str = " name={}".format(repr(self.__dict__["_name"]))
else:
name_str = ""
if self.__dict__["__caller"]:
caller_str = " {}".format(self.__dict__["__caller"])
else:
caller_str = ""
return "<StrictMock 0x{:02X}{name}{template}{caller}>".format(
id(self), name=name_str, template=template_str, caller=caller_str
)
def __str__(self) -> str:
return self.__repr__()
def __get_copy(self) -> "StrictMock":
self_copy = StrictMock(
template=self._template,
runtime_attrs=self._runtime_attrs,
name=self._name,
type_validation=self._type_validation,
attributes_to_skip_type_validation=self._attributes_to_skip_type_validation,
)
self_copy.__dict__["__caller"] = self.__get_caller(2)
return self_copy
def __get_copyable_attrs(self, self_copy: "StrictMock") -> List[str]:
return [
name
for name in type(self).__dict__
if name not in self_copy.__dict__
and (
not name.startswith("__")
or not name.endswith("__")
or name in self.__SETTABLE_MAGICS
)
]
def __copy__(self) -> "StrictMock":
self_copy = self.__get_copy()
for name in self.__get_copyable_attrs(self_copy):
setattr(type(self_copy), name, type(self).__dict__[name])
return self_copy
def __deepcopy__(self, memo: Optional[Dict[Any, Any]] = None) -> "StrictMock":
if memo is None:
memo = {}
self_copy = self.__get_copy()
memo[id(self)] = self_copy
for name in self.__get_copyable_attrs(self_copy):
value = copy.deepcopy(type(self).__dict__[name], memo)
setattr(type(self_copy), name, value)
return self_copy
def _extract_StrictMock_template(mock_obj: StrictMock) -> Optional[Any]:
if "_template" in mock_obj.__dict__ and mock_obj._template is not None:
return mock_obj._template
return None
lib.MOCK_TEMPLATE_EXTRACTORS[StrictMock] = _extract_StrictMock_template # type: ignore