久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

修補函數的 __call__

Patch __call__ of a function(修補函數的 __call__)
本文介紹了修補函數的 __call__的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我需要在測試中修補當前日期時間.我正在使用這個解決方案:

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()

然后在我的測試中,我會執行以下操作:

Then in my tests I do something like:

    with mock.patch('***.utils._utcnow', return_value=***):
        ...

但今天我想到了一個想法,我可以通過修補函數 utcnow__call__ 來簡化實現,而不是額外添加一個 _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=***):
        ...

如何優雅地做到這一點?

How to do this elegantly?

推薦答案

當你修補一個函數的 __call__ 時,你是在設置那個 __call__ 屬性實例.Python 實際上調用了類上定義的 __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() 不調用 a.__call__.它調用 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 文檔中記錄了此行為.

這篇關于修補函數的 __call__的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

How should I verify a log message when testing Python code under nose?(在鼻子下測試 Python 代碼時,我應該如何驗證日志消息?)
How to call self in a mock method of an object in Python?(如何在 Python 中對象的模擬方法中調用 self?)
Mocking only a single method on an object(僅模擬對象上的單個方法)
Mocking a subprocess call in Python(在 Python 中模擬子進程調用)
Checking call order across multiple mocks(檢查多個模擬的調用順序)
How to properly use mock in python with unittest setUp(如何通過 unittest setUp 在 python 中正確使用 mock)
主站蜘蛛池模板: 国产日韩一区二区三免费高清 | 最新中文字幕久久 | 在线观看国产精品一区二区 | 亚洲一区 中文字幕 | 国产欧美日韩精品一区 | 亚洲精品久久久久久宅男 | 午夜精品视频 | 欧美精品一区二区三区四区五区 | 亚洲欧美日韩国产 | 亚洲精品电影在线观看 | 欧美成人久久 | 日韩在线免费视频 | av看看| 精品三级在线观看 | 欧美精品久久久 | 99热.com| www.中文字幕.com | 欧美在线综合 | 欧美久久久久久久久 | 国产欧美在线观看 | 精品国产色 | 日韩成人影院 | 91啪影院| 欧美日韩在线一区二区 | 91看片在线观看 | 欧美1级 | 成人精品在线观看 | 久久av一区二区三区 | 久久免费视频在线 | 一区二区精品 | 国产激情片在线观看 | 黄视频在线网站 | 99精品国产在热久久 | 99热在线播放 | 在线观看亚洲一区二区 | 99热精品久久 | 中文一区二区 | 欧美福利视频 | 日韩在线中文 | 亚洲一二三在线观看 | 99亚洲|