【问题标题】:mock doesn't work in objects on kwargsmock 在 kwargs 上的对象中不起作用
【发布时间】:2023-03-13 06:34:02
【问题描述】:

似乎 kwarg 分配没有在 mock.patch 中被模拟,但如果它在函数内部被调用,它就是。

有什么想法吗?

import platform
import mock


def test(arch=platform.machine()):
    print "arch = %s" % arch
    print "machine = %s" % platform.machine()

with mock.patch.object(platform, "machine", return_value="TEST"):
    test()


# This outputs
# arch = x86_64
# machine = TEST

【问题讨论】:

标签: python mocking


【解决方案1】:

函数默认值在函数定义执行时与函数对象一起设置和存储。

模拟platform.machine 工作正常,但arch 参数的默认值早已通过调用platform.machine() 并使用返回值来设置。调用test()使用该表达式。

请参阅 "Least Astonishment" in Python: The Mutable Default Argument 了解原因。

您需要在导入定义函数的模块之前对platform 打补丁;您可以将函数移动到新模块,然后执行以下操作:

import sys

if 'modulename' in sys.modules:
    del sys.modules['modulename']  # ensure the cached module is cleared

with mock.patch.object(platform, "machine", return_value="TEST"):
    from modulename import sys
    test()

del sys.modules['modulename']  # clear the module with the mocked value again

这相当麻烦,如果你在线程中运行测试会失败。

您可以使用None 作为默认值,并在调用test 时创建默认值:

def test(arch=None):
    if arch is None:
        arch = platform.machine()
    print "arch = %s" % arch
    print "machine = %s" % platform.machine()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 2017-04-24
    • 2016-07-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多