考虑到以下代码试图将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 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时,我们将调用原始函数而不是模拟函数。缺少什么来激活模拟函数?
发布于 2022-02-21 12:34:19
@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__)导入解析为其包含的文件
https://stackoverflow.com/questions/71204029
复制相似问题