Python对函数进行全局模拟但局部模拟失败

时间:2019-09-16 09:25:21

标签: python mocking code-coverage pytest

我在“ testing_print”目录下有一个简单的源文件“ hello.py”,在“ Tests”目录下有单元测试用例“ test_hello.py”。这两个目录都在“ test_hello_files”目录下。

我试图为“ hello.py”文件编写一个单元测试用例“ test_hello.py”,并向其中添加一个模拟来伪造“ sample_greet1”功能。

如果我全局添加模拟,则测试用例通过,但是如果模拟在本地定义,则测试用例失败。

hello.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'

我想在函数内部局部放置模拟。请让我知道我在做什么错。

1 个答案:

答案 0 :(得分:0)

我建议使用补丁装饰器。它将自动用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'