简体   繁体   中英

Python unittest: Mock problematic module/function from another Module

B/moduleB.py is defined as:

def text_function():
    raise KeyError

text_function()

ModuleA.py is defined as:

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 :

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 ?

Basically, I don't want anything to run from moduleB while testing for moduleA

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). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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