简体   繁体   English

来自另一个文件/模块的 Python 模拟补丁

[英]Python Mock Patch From Another File/Module

I have a mock that works fine as expected.我有一个按预期工作正常的模拟。

from mock import patch

def second(arg):
    return 3


def first():
    return second('arg')


@patch('test.second')
def test_test(second_mock):
    second_mock.return_value = 47  # We decide this

    call_it = first()

    second_mock.assert_called_once()
    second_mock.assert_called_with('arg')

    assert call_it == 47

But not if i move me second() method to another file...但是,如果我将 second() 方法移到另一个文件中,则不会...

from mock import patch
from test_help import second


def first():
    return second('arg')


@patch('test_help.second')
def test_test(second_mock):
    second_mock.return_value = 47  # We decide this

    call_it = first()

    second_mock.assert_called_once()
    second_mock.assert_called_with('arg')

    assert call_it == 47

I get the same error: AssertionError: Expected 'second' to have been called once.我得到了同样的错误:AssertionError: Expected 'second' to have been called once. Called 0 times.调用了 0 次。

What am I missing here?我在这里缺少什么?

I have tried a few different ways of formatting, but none seem to work.我尝试了几种不同的格式化方式,但似乎都不起作用。 Is this even the best practice/package in this case for unit testing?在这种情况下,这甚至是单元测试的最佳实践/包吗?

Don't worry, you're on right path, that is the way to mock functions.别担心,你在正确的道路上,这就是模拟函数的方法。

And about your probem, remember that you patch the namespace according to function from where the mocked function is called.关于您的probem,请记住您根据调用模拟函数的函数修补命名空间。

So, when you in your module module_where_first_is_located make an import from test_help import second then second is recognized as module_where_first_is_located.second .因此,当您在模块module_where_first_is_located from test_help import second进行from test_help import second个被识别为module_where_first_is_located.second

So instead of @patch('test_help.second') do @patch('module_of_first.second') .所以,而不是@patch('test_help.second')@patch('module_of_first.second')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM