首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在python-mock中,调用的是原始函数,而不是模拟。

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

Stack Overflow用户
提问于 2022-02-21 09:36:57
回答 1查看 81关注 0票数 0

考虑到以下代码试图将shell_with_tag()配置为由`mock_shell_with_tag()模拟的代码:

代码语言:javascript
复制
#!/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时,我们将调用原始函数而不是模拟函数。缺少什么来激活模拟函数?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-21 12:34:19

@KlausD专注于进口,走上了正确的轨道。要使它发挥作用,关键的改变是:

代码语言:javascript
复制
    from tests.mocked import test_mock 
    mocker.patch('tests.mocked.test_mock.shell_with_tag', mock_shell_with_tag)

以下是更新的片段。

代码语言:javascript
复制
#!/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__)

导入解析为其包含的文件

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71204029

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档