简体   繁体   English

Python3 -unittest mocking - isinstance 问题

[英]Python3 -unittest mocking - problem with isinstance

I have some problem with mocking and testing my function/class.我在 mocking 和测试我的函数/类时遇到了一些问题。

I think the easiest way to explain it will be showing some code:我认为解释它的最简单方法是显示一些代码:

module.py:模块.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:我想测试我的 module.py:

test_module.py:测试模块.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.因为 some_module 被嘲笑了。

I really need to mock the "some_module" - it's needed for some other tests.我真的需要模拟“some_module”——其他一些测试需要它。

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?是的,我可能应该只为某些测试取消模拟模块,或者当我在特定的 function 中使用它时模拟 isinstance?

Do you have any idea how to process it?你知道如何处理它吗?

You are in the right way, you've just forgot to set the object spec.您的方法是正确的,您只是忘记设置 object 规格。 Here is a fully functional example based in your question.这是一个基于您的问题的功能齐全的示例。

some_module.py一些模块.py

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

module.py模块.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测试模块.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)

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

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