@@ -314,12 +314,16 @@ def __getattr__(self, name):
314
314
name.
315
315
"""
316
316
if name .startswith ("_" ) or name in _RESERVED_MOCK_ATTRIBUTES :
317
+ # Special attributes are handled as normal attributes.
317
318
return self .__dict__ .get (name )
318
319
elif name in self .__dict__ :
320
+ # Existing attributes are returned as is.
319
321
return self .__dict__ [name ]
320
322
elif "_spec" in self .__dict__ and name not in self ._spec :
323
+ # If the attribute is not in the spec then raise an AttributeError.
321
324
raise AttributeError (f"Mock object has no attribute '{ name } '." )
322
325
else :
326
+ # Otherwise, create a new mock object for the attribute.
323
327
new_mock = Mock ()
324
328
setattr (self , name , new_mock )
325
329
return new_mock
@@ -574,14 +578,18 @@ def __getattr__(self, name):
574
578
name.
575
579
"""
576
580
if name .startswith ("_" ) or name in _RESERVED_MOCK_ATTRIBUTES :
581
+ # Special attributes are handled as normal attributes.
577
582
return self .__dict__ .get (name )
578
583
elif name in self .__dict__ :
584
+ # Existing attributes are returned as is.
579
585
return self .__dict__ [name ]
580
586
elif "_spec" in self .__dict__ and name not in self ._spec :
587
+ # If the attribute is not in the spec then raise an AttributeError.
581
588
raise AttributeError (
582
589
f"AsyncMock object has no attribute '{ name } '."
583
590
)
584
591
else :
592
+ # Otherwise, create a new mock object for the attribute.
585
593
new_mock = AsyncMock ()
586
594
setattr (self , name , new_mock )
587
595
return new_mock
@@ -625,7 +633,10 @@ def wrapper(*args, **kwargs):
625
633
626
634
def __enter__ (self ):
627
635
"""
628
- Replace the target attribute with new.
636
+ Replace the target attribute with self.new.
637
+
638
+ If self.new is None, a new Mock object is created with the supplied
639
+ kwargs and bound to self.new before the target is replaced.
629
640
"""
630
641
self .new = self .new or Mock (** self .kwargs )
631
642
self ._old = patch_target (self .target , self .new )
@@ -669,9 +680,9 @@ def patch_target(target, replacement):
669
680
parts = attributes .split ("." )
670
681
for part in parts [:- 1 ]:
671
682
parent = getattr (parent , part )
672
- # Get the original object that we're going to replace (so we can return
673
- # it).
683
+ # Get the original target object that we're going to replace (so we can
684
+ # return it).
674
685
old_object = getattr (parent , target_name )
675
- # Replace the target attribute with the replacement.
686
+ # Replace the target with the replacement.
676
687
setattr (parent , target_name , replacement )
677
688
return old_object
0 commit comments