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

问题描述 投票:2回答:1

我想使用unittest.mock,但我收到一个错误:

AttributeError:没有属性'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,然后我更改了测试以引用此模块中的函数,但我想知道是否可以保持函数和模块具有相同的名称。

python mocking python-unittest
1个回答
3
投票

事实证明,可以模拟在具有相同名称的模块内的函数中调用的函数。围绕unittest.mock.patch()的一个小包装可以使这种情况发生:

Code:

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)

To use:

代替:

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

你需要:

module_patch("module.a.b")

How does this work?

基本思想是尝试以最长的模块路径开始向最短路径开始模块导入,如果导入成功,则使用该模块作为修补对象。

Test Code:

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

Test files in module

# __init__.py
from .a import a
from .a import b


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

def b():
    return 'b'

Results:

module.a():  b
module.b():  b
--
module.a():  new_b
module.b():  b
© www.soinside.com 2019 - 2024. All rights reserved.