简体   繁体   English

Python 单元测试:从另一个模块模拟有问题的模块/功能

[英]Python unittest: Mock problematic module/function from another Module

B/moduleB.py is defined as: B/moduleB.py定义为:

def text_function():
    raise KeyError

text_function()

ModuleA.py is defined as: ModuleA.py定义为:

from B.moduleB import text_function

class a():
    def __init__(self):
        self.text = 'abc'

    def mul(self, a, b):
        print(text_function() + str(a*b))

if __name__ == "__main__":
    rom = a()
    rom.mul(2, 3)

This is the unit test test_module.py :这是单元测试test_module.py

from unittest.mock import MagicMock, patch
from moduleA import a

class TestmoduleA(unittest.TestCase):
    def setUp(self):
        pass

    def test_mul(self):
        print(a.mul)
        self.assertTrue(True)

Now, is there a way to mock the text_function in B/moduleB.py while importing from moduleA such that I don't get the KeyError ?现在,有没有办法在从 moduleA 导入时模拟 B/moduleB.py 中的 text_function,这样我就不会得到KeyError

Basically, I don't want anything to run from moduleB while testing for moduleA基本上,我不想在测试模块 A 时从模块 B 运行任何东西

Thanks in advance:)提前致谢:)

Your main problem is that the problematic function is called already on importing the module, so you cannot patch the function (as the patching would import the original module, and call the function).你的主要问题是有问题的 function 在导入模块时已经被调用,所以你不能修补 function (因为修补会导入原始模块,并调用函数)。 In this case you have to mock the import itself before importing your tested module:在这种情况下,您必须在导入测试模块之前模拟导入本身:

import unittest
from unittest import mock
import sys

sys.modules['B.moduleB'] = mock.Mock()

from moduleA import a

class TestmoduleA(unittest.TestCase):
    def test_mul(self):
        print(a.mul) 
        self.assertTrue(True)

See also how to mock an import for more information.另请参阅如何模拟导入以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM