在 python-mock 中调用原始函数而不是模拟

In python-mock the original function is being invoked instead of the mock

鉴于以下代码试图将 shell_with_tag() 配置为由 `mock_shell_with_tag():

mocked
#!/usr/bin/env python3

import pytest

def shell(cmdline, debug=True):
    return f"Original Shell command for {cmdline}.", None

def shell_with_tag(cmdline, debug=True, test_tag=None):
    return shell(cmdline, debug)

def mock_shell_with_tag(cmd, test_tag=None):
    if 'udf delete' in cmd:
        return ['MOCK Record deleted' if test_tag == 'success' else 'Not Found. ', None]
    elif 'udf show' in cmd:
        return ['MOCK Record shown' if test_tag == 'success' else 'Not Found. ', None]
    else:
        raise Exception(f"mock_shell: what function is this {cmd}")

def testUdfs(mocker):
    mocker.patch('tests.mocked.test_mock.shell_with_tag', mock_shell_with_tag)

    def testDelete(name, expected_delete='true'):
        out,err=shell_with_tag(f"udf delete --name {name}", test_tag ='success' if expected_delete else 'failure')
        print(f"Results from UDF delete: {out} err: {err}")
        assert 'MOCK Record' in out, "We went to the real one not the mock"

    testDelete('abc')

请注意,已找到模拟函数 tests.mocked.test_udfs.shell_with_tag() :如果未找到,则会生成一条错误消息:在正确获取此消息之前需要一些努力。

但是当 运行 testDelete 时,我们会调用 original 函数而不是模拟函数。缺少什么导致模拟功能激活?

@KlausD 专注于进口,走在了正确的轨道上。使其工作的关键变化:

    from tests.mocked import test_mock 
    mocker.patch('tests.mocked.test_mock.shell_with_tag', mock_shell_with_tag)

这是更新后的代码段。

#!/usr/bin/env python3

import pytest

def shell(cmdline, debug=True):
    return f"Original Shell command for {cmdline}.", None

def shell_with_tag(cmdline, debug=True, test_tag=None):
    return shell(cmdline, debug)

def mock_shell_with_tag(cmd, test_tag=None):
    if 'udf delete' in cmd:
        return ['MOCK Record deleted' if test_tag == 'success' else 'Not Found. ', None]
    elif 'udf show' in cmd:
        return ['MOCK Record shown' if test_tag == 'success' else 'Not Found. ', None]
    else:
        raise(f"mock_shell: what function is this {cmd}")

def testUdfs(mocker):
    from tests.mocked import test_mock
    mocker.patch('tests.mocked.test_mock.shell_with_tag', mock_shell_with_tag)

    # def testDelete(name, expected_delete='true'):
    # out,err=shell_with_tag(f"udf delete --name {name}", test_tag ='success' if expected_delete else 'failure')
    out,err=test_mock.shell_with_tag(f"udf delete --name abc", test_tag ='success')
    print(f"Results from UDF delete: {out} err: {err}")
    assert 'MOCK Record' in out, "We went to the real one not the mock"

    # testDelete('abc')

print(__name__)

Import resolves to its containing file