問題描述
我需要在測試中修補當前日期時間.我正在使用這個解決方案:
I need to patch current datetime in tests. I am using this solution:
def _utcnow():
return datetime.datetime.utcnow()
def utcnow():
"""A proxy which can be patched in tests.
"""
# another level of indirection, because some modules import utcnow
return _utcnow()
然后在我的測試中,我會執(zhí)行以下操作:
Then in my tests I do something like:
with mock.patch('***.utils._utcnow', return_value=***):
...
但今天我想到了一個想法,我可以通過修補函數(shù) utcnow
的 __call__
來簡化實現(xiàn),而不是額外添加一個 _utcnow
.
But today an idea came to me, that I could make the implementation simpler by patching __call__
of function utcnow
instead of having an additional _utcnow
.
這對我不起作用:
from ***.utils import utcnow
with mock.patch.object(utcnow, '__call__', return_value=***):
...
如何優(yōu)雅地做到這一點?
How to do this elegantly?
推薦答案
當你修補一個函數(shù)的 __call__
時,你是在設置那個 的 __call__
屬性實例.Python 實際上調(diào)用了類上定義的 __call__
方法.
When you patch __call__
of a function, you are setting the __call__
attribute of that instance. Python actually calls the __call__
method defined on the class.
例如:
>>> class A(object):
... def __call__(self):
... print 'a'
...
>>> a = A()
>>> a()
a
>>> def b(): print 'b'
...
>>> b()
b
>>> a.__call__ = b
>>> a()
a
>>> a.__call__ = b.__call__
>>> a()
a
將任何東西分配給 a.__call__
是沒有意義的.
Assigning anything to a.__call__
is pointless.
但是:
>>> A.__call__ = b.__call__
>>> a()
b
TLDR;
a()
不調(diào)用 a.__call__
.它調(diào)用 type(a).__call__(a)
.
TLDR;
a()
does not call a.__call__
. It calls type(a).__call__(a)
.
回答為什么type(x).__enter__(x)
而不是 Python 標準 contextlib 中的 x.__enter__()
?".
There is a good explanation of why that happens in answer to "Why type(x).__enter__(x)
instead of x.__enter__()
in Python standard contextlib?".
特殊方法查找的 Python 文檔中記錄了此行為.
這篇關于修補函數(shù)的 __call__的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!