简体   繁体   中英

Python3 -unittest mocking - problem with isinstance

I have some problem with mocking and testing my function/class.

I think the easiest way to explain it will be showing some code:

module.py:

import some_module

class MyClassToTest:
    def __init__():
        pass

    def f(self, a):
        if isinstance(a, some_module.someClass):
            print("true")

I want to test my module.py:

test_module.py:

import sys
from unittest import mock

sys.modules['some_module'] = mock.MagicMock() # mocking whole module

def test_my_test():
    to_test = MyClassToTest()
    to_test.f(5)

Of course here I will have an error:

TypeError: isinstance() arg 2 must be a type or tuple of types

because some_module was mocked.

I really need to mock the "some_module" - it's needed for some other tests.

And yes, I probably should unmock the module just for some tests or maybe mock the isinstance when I'm using it in specific function?

Do you have any idea how to process it?

You are in the right way, you've just forgot to set the object spec. Here is a fully functional example based in your question.

some_module.py

class SomeModule(object):
    def method(self):
        return True

module.py

import some_module


class MyClass:
    def __init__(self):
        pass

    def f(self, a):
        if isinstance(a, some_module.SomeModule):
            return True
        return False

test_module.py

from unittest import mock
from unittest import main, TestCase

import function

class MyClassTestCase(TestCase):

    def test_myclass(self):
        m = mock.MagicMock(spec=function.some_module.SomeModule)
        mc = function.MyClass()
        self.assertEqual(mc.f(1), False)

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