【问题标题】:What do @mock.patch decorators do in Python when there are more than the number of parameters of the decorated method/function?当装饰的方法/函数的参数数量超过时,@mock.patch 装饰器在 Python 中做了什么?
【发布时间】:2020-04-13 05:12:10
【问题描述】:

例如:

@patch('my.project.trading.getEnrichedTradeData', lambda: TEST_TRADE_DATA)
@patch('my.project.subledger.getSubledgerData', getTestSubledgerData)
@patch('my.project.metadata.getSubledgerCodes', return_value=TEST_CODES)
@patch('my.project.reports.storeReport')
def test(self, storeReport):
    buildReport()
    storeReport.assert_called_with(EXPECTED_REPORT)
def buildReport():
    trades = getEnrichedTradeData()
    subledger = getSubledgerData()
    codes = getSubledgerCodes()
    report = Report(trades, subledger, codes)
    storeReport(report)

我认为@patch 将其返回值作为参数传递,所以最底层的装饰器会发生这种情况。另外3个呢? 免责声明:python 语言中相当绿色。精通Java和C++。请尽可能详细...

【问题讨论】:

    标签: python mocking decorator


    【解决方案1】:

    摘自unittest.mock.patch的文档:

    如果 new 被省略,则目标将替换为 AsyncMock if 修补的对象是异步函数或 MagicMock 否则。如果 patch() 用作装饰器并省略 new,创建的模拟是 作为装饰函数的额外参数传入。

    由于在您的情况下,所有 3 个顶部 patch 装饰器都使用 new 参数调用,3 个目标对象将简单地替换为 new 参数中的对象,底部 patch没有new 参数的装饰器将用MagicMock 实例替换目标对象,并将其作为额外参数storeReport 传递给您的test 函数。

    【讨论】:

    • 您的意思是我必须更改函数签名还是装饰器最终添加/插入额外参数?我看到工作代码不添加参数,并且使用的装饰器数量多于我发送的示例中的参数数量。
    • 我的错。我完全忘记了如果为 patch 装饰器指定了 new 参数,则不会传入额外的参数。我已经相应地更新了我的答案。
    • 现在知道了...基本上@patch 仅在省略new 时将创建的模拟对象作为参数传递。否则,它只是用new 修补target。谢谢!
    猜你喜欢
    • 2014-07-21
    • 2017-01-04
    • 2016-09-27
    • 2019-10-02
    • 1970-01-01
    • 2018-01-21
    • 2015-10-19
    • 1970-01-01
    • 2011-06-25
    相关资源
    最近更新 更多