如何模拟在具有相同名称的模块内的函数中调用的函数?

2024-05-16 13:32:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用unittest.mock,但出现了一个错误:

AttributeError: does not have the attribute 'get_pledge_frequency'

我有以下文件结构:

pledges/views/
├── __init__.py
├── util.py
└── user_profile.py
pledges/tests/unit/profile
├── __init__.py
└── test_user.py

pledges/views/__init___.py我有:

from .views import *
from .account import account
from .splash import splash
from .preferences import preferences
from .user_profile import user_profile

user_profile.py内部,我有一个名为user_profile的函数,它在util.py内部调用一个名为get_pledge_frequency的函数,如下所示:

def user_profile(request, user_id):
    # some logic

    # !!!!!!!!!!!!!!!!
    a, b = get_pledge_frequency(parameter) # this is the function I want to mock

    # more logic

    return some_value

我在test_user.py中有一个测试,如下所示:

def test_name():
    with mock.patch(
        "pledges.views.user_profile.get_pledge_frequency"
    ) as get_pledge_frequency:
        get_pledge_frequency.return_value = ([], [])
        response = c.get(
            reverse("pledges:user_profile", kwargs={"user_id": user.id})
            ) # this calls the function user_profile inside pledges.user_profile

     # some asserts to verify functionality

我已经检查了其他问题,但是答案不包括什么时候有一个称为模块的函数,它被导入到__init__文件中。你知道吗

那么,有没有办法解决这个问题呢?我基本上已经将文件user_profile.py重命名为profile,然后我更改了测试以引用这个模块中的函数,但是我想知道是否有可能保持函数和模块的名称相同。你知道吗


Tags: 文件the函数frompyimportgetinit
1条回答
网友
1楼 · 发布于 2024-05-16 13:32:15

事实证明,可以模拟在具有相同名称的模块中的函数中调用的函数。 一个围绕unittest.mock.patch()的小包装器可以这样做:

代码:

from unittest import mock
import importlib

def module_patch(*args):
    target = args[0]
    components = target.split('.')
    for i in range(len(components), 0, -1):
        try:
            # attempt to import the module
            imported = importlib.import_module('.'.join(components[:i]))

            # module was imported, let's use it in the patch
            patch = mock.patch(*args)
            patch.getter = lambda: imported
            patch.attribute = '.'.join(components[i:])
            return patch
        except Exception as exc:
            pass

    # did not find a module, just return the default mock
    return mock.patch(*args)

使用方法:

而不是:

mock.patch("module.a.b")

您需要:

module_patch("module.a.b")

这是怎么回事?

基本思想是尝试从最长的模块路径向最短的路径导入模块,如果导入成功,则将该模块用作修补对象。你知道吗

测试代码:

import module

print('module.a(): ', module.a())
print('module.b(): ', module.b())
print(' ')

with module_patch("module.a.b") as module_a_b:
    module_a_b.return_value = 'new_b'
    print('module.a(): ', module.a())
    print('module.b(): ', module.b())

try:
    mock.patch("module.a.b").__enter__()
    assert False, "Attribute error was not raised, test case is broken"
except AttributeError:
    pass

module

中的测试文件
# __init__.py
from .a import a
from .a import b


# a.py
def a():
    return b()

def b():
    return 'b'

结果:

module.a():  b
module.b():  b
 
module.a():  new_b
module.b():  b

相关问题 更多 >