2013-06-24 2 views
2

다음과 같이 c 확장 클래스를 사용하는 클래스 함수를 모의하려고합니다. 그러나 TypeError: can't set attributes of built-in/extension type 'y.cExtensionClass'이 있습니다. code.py는 기존 코드이므로 실제로 변경하지 않아도됩니다. 어떠한 제안?파이썬에서 c 확장 클래스를 조롱하는 법?

code.py :

from x.y import cExtensionClass 

class CodeClass(): 

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

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

감사

답변

2

패치 code.cExtensionClass (안 x.y.cExtensionClass). from code cExtensionClass 대신 import code을 입력하십시오.

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() 
+0

지금이 오류를 받고 있어요 : 역 추적 (마지막으로 가장 최근 통화) : 파일 "test.py", 줄 196, test_code_function 에 패치 (code.cExtensionClass) m로 : 파일 " ./../../test/mock/mock.py ", 1551 줄, 패치 getter, attribute = _get_target (target) 파일"./../../test/mock/mock.py " , 줄 1389, _get_target에서 대상, 특성 = target.rsplit ('.', 1)AttributeError : 형식 개체 'y.cExtensionClass'특성이 없습니다 'rsplit' – user1819676

+0

문제가 발견되었습니다, 클래스 대신 문자열을 사용해야합니다. . – user1819676

+0

''code.cExtensionClass'' 대신'code.cExtensionClass'를 사용 했습니까? – falsetru

0

전체 cExtensionClass 객체보다는 단지 하나의 메소드를 교체합니다.

1

당신은 forbidden fruit

금단의 열매

enter image description here

This project aims to help you reach heaven while writing tests, but it may lead you to hell if used on production code.

It basically allows you to patch built-in objects, declared in C through python. Just like this:

>>> from forbiddenfruit import curse 
>>> def words_of_wisdom(self): 
...  return self * "blah " 
>>> curse(int, "words_of_wisdom", words_of_wisdom) 
>>> assert (2).words_of_wisdom() == "blah blah " 

Boom! That's it, your int class now has the words_of_wisdom method. Do you want to add a classmethod to a built-in class? No problem, just do this:

을 시도 할 수 있습니다
>>> from forbiddenfruit import curse 
>>> def hello(self): 
...  return "blah" 
>>> curse(str, "hello", classmethod(hello)) 
>>> assert str.hello() == "blah" 
관련 문제