实例与Taunt

发布于 2021-01-29 17:21:14

class HelloWorld(object):
def say_it(self):
return ‘Hello I am Hello World’

def i_call_hello_world(hw_obj):
    print 'here... check type: %s' %type(HelloWorld)
    if isinstance(hw_obj, HelloWorld):
        print hw_obj.say_it()

from mock import patch, MagicMock
import unittest

class TestInstance(unittest.TestCase):
    @patch('__main__.HelloWorld', spec=HelloWorld)
    def test_mock(self,MK):
        print type(MK)
        MK.say_it.return_value = 'I am fake'
        v = i_call_hello_world(MK)
        print v

if __name__ == '__main__':
    c = HelloWorld()
    i_call_hello_world(c)
    print isinstance(c, HelloWorld)
    unittest.main()

这是回溯

here... check type: <type 'type'>
Hello I am Hello World
True
<class 'mock.MagicMock'>
here... check type: <class 'mock.MagicMock'>
E
======================================================================
ERROR: test_mock (__main__.TestInstance)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/mock.py", line 1224, in patched
    return func(*args, **keywargs)
  File "t.py", line 18, in test_mock
    v = i_call_hello_world(MK)
  File "t.py", line 7, in i_call_hello_world
    if isinstance(hw_obj, HelloWorld):
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types

----------------------------------------------------------------------
Ran 1 test in 0.002s

Q1。 为什么会引发此错误?他们是<class type='MagicMock>

Q2。 我如何暂停模拟,以便在错误修复后第一行通过?

文档

通常,__class__对象的属性将返回其类型。对于具有规范的模拟对象,则__class__返回规范类。这允许模拟对象通过isinstance()对其要替换/伪装的对象的测试,使其通过:

mock = Mock(spec=3)
isinstance(mock, int)
True
关注者
0
被浏览
46
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    不要使用isinstance,而是检查say_it方法是否存在。如果该方法存在,则调用它:

    if hasattr(hw_obj, 'say_it'):
        print hw_obj.say_it()
    

    无论如何,这是一个更好的设计:依赖类型信息要脆弱得多。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看