python - Python 在全局范围内模拟函数有效,但本地模拟失败
问题描述
我在“testing_print”目录下有一个简单的源文件“hello.py”,在“Tests”目录下有一个单元测试用例“test_hello.py”。这两个目录都在“test_hello_files”目录下。
我正在尝试为“hello.py”文件编写一个单元测试用例“test_hello.py”,并为其添加了一个模拟来伪造“sample_greet1”函数。
如果我在全局范围内添加模拟,则测试用例通过,但如果模拟是在本地定义的,则测试用例失败。
你好.py
from import_file import sample_greet1
def greet1():
s = 'hi'
greet=sample_greet1(s)
return greet
test_hello.py
import sys
import pytest
from mock import Mock
impo_class=sys.modules['import_file'] = Mock()
impo_class.sample_greet1 = Mock(return_value = "Prasad") #Test case passes if the mock is here
from testing_print import hello
def test_greet1():
print('impo_class.sample_greet1 ----', impo_class.sample_greet1())
impo_class.sample_greet1 = Mock(return_value = "Prasad") #Test case fails if the mock is here
s = hello.greet1()
assert s == 'Prasad'
我想在函数内本地模拟。请让我知道我做错了什么。
解决方案
我建议使用补丁装饰器。它会自动将函数替换为 Mock 对象,因此您不必手动导入和更改它。
模拟将作为参数传递给修饰的测试 abd 它将是本地的。一旦功能结束,Mock 将被移除并恢复原始功能。
from unittest.mock import patch
from testing_print import hello
@patch('testing_print.hello.sample_greet1', return_value='Prasad')
def test_greet1(mock):
s = hello.greet1()
assert s == 'Prasad'
推荐阅读
- jquery - 带有自定义处理程序的库在 fancybox V4 中不起作用
- mongodb - 如何使用一对多关系将数据保存在 MongoDB 中?
- node.js - 在expressjs中重定向到多次错误
- javascript - javascript异步等待不等待
- python - 填写表格时出现硒问题
- r - 使用 kable 在表格下方添加标题
- puppet - 如何使用 puppet 复制文件列表
- terraform - 等待插件启动时,terragrunt 计划因超时而失败
- python - 当我尝试使用 OOP 和类时,为什么我的代码在 python 中显示 NameError?
- firebase - Firebase 托管配置