我试图模拟一个类函数,该函数在其内部使用一个c扩展类,如下所示,但我得到TypeError: can't set attributes of built-in/extension type 'y.cExtensionClass'
py是一个遗留代码,我真的不想改变它。有什么建议吗?
代码.py:

from x.y import cExtensionClass

class CodeClass():

    @staticmethod
    def code_function():
         cExtensionClass().cExtensionFunc()

测试.py:
import code
from x.y import cExtensionClass

class test(unittest.TestCase):

    def test_code_function(self)
        with patch.object(cExtensionClass, 'cExtensionFunc') as cExtensionFuncMock:
            cExtensionFuncMock.return_value = None
            code.CodeClass.code_function()
            cExtensionFuncMock.assert_called_with()

谢谢

最佳答案

补丁code.cExtensionClass(不x.y.cExtensionClass)。
import code而不是from code cExtensionClass

import unittest

from mock import patch, Mock

import code

class test(unittest.TestCase):
    def test_code_function(self):
        with patch('code.cExtensionClass') as m:
            m.return_value.cExtensionFunc = func = Mock()
            code.CodeClass.code_function()
            func.assert_called_with()

    #@patch('code.cExtensionClass')
    #def test_code_function(self, m):
    #    m.return_value.cExtensionFunc = func = Mock()
    #    code.CodeClass.code_function()
    #    func.assert_called_with()

08-18 09:24