Python 全局模拟函数有效,但本地模拟失败

标签 python mocking code-coverage pytest

我在“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'

关于Python 全局模拟函数有效,但本地模拟失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57953909/

相关文章:

code-coverage - 我们如何将 gcovr 与 -g 选项一起使用?

c# - MS 测试代码覆盖率返回不正确的结果

python - Django:禁止直接赋值给相关集合的反面。使用 username.set() 代替

python - 在 Python 中如何调用不同用户下的子进程?

python-2.7 - 从上下文管理器创建的对象中模拟函数

c - 如何对涉及 IO 的 c 函数进行单元测试?

maven - Jacoco 代码覆盖 Sonar 和 Maven,用于单独模块中的集成测试

python - 什么被传递给 scrapy DownloaderStats 中间件?

python - Pandas OLS - 拉动参数不起作用

c# - 有没有办法告诉 Autofixture 只设置具有特定属性的属性?