簡體   English   中英

模擬__init __(self,…):TypeError:super(type,obj):obj必須是類型的實例或子類型

[英]mock __init__(self, …): TypeError: super(type, obj): obj must be an instance or subtype of type

我嘗試模擬這樣的類的構造函數https://stackoverflow.com/a/17950141/633961

class MockedHttpResponse(django.http.response.HttpResponseBase):
    def check(self, *args, **kwargs):
        status=kwargs.get('status')
        if status is None and self.status_code==200:
            return # default 
        if not status==self.status_code:
            raise self.AssertionErrorStatusCode('%s!=%s' % (self.status_code, status))

    def __init__(self, *args, **kwargs):
        self.check(*args, **kwargs)
        django.http.response.HttpResponseBase.__init__(self, *args, **kwargs)

    class AssertionErrorStatusCode(AssertionError):
        pass

測試中的用法:

def test_assert_http_response_status__with_self_mocking(self):
    from django.http import HttpResponse
    with mock.patch('django.http.response.HttpResponse', testutils.MockedHttpResponse):
        HttpResponse(status=200)

但是我得到這個異常:

Traceback (most recent call last):
  File "/home/foo_eins_di514/src/djangotools/djangotools/tests/unit/utils/test_testutils.py", line 129, in test_assert_http_response_status__with_self_mocking
    HttpResponse(status=200)
  File "/home/foo_eins_di514/lib/python2.7/site-packages/django/http/response.py", line 258, in __init__
    super(HttpResponse, self).__init__(*args, **kwargs)
TypeError: super(type, obj): obj must be an instance or subtype of type

如何模擬類並修改其__init__()方法?

我不能肯定地說,因為我不是mock工作原理的專家,但是除非進行了令人印象深刻的體操,否則您已經將原始django.http.HttpResponse對象靜態綁定到了測試模塊范圍內的HttpResponse from django.http import HttpResponse )。 除非mock在上下文管理器中動態修改locals() \\ globals()來修補對修補程序目標的別名引用,否則模塊本身的修補數量不會影響您在測試中使用的HttpResponse對象。 我認為您至少需要采取的步驟是在patch上下文管理器中顯式引用模塊中的類,盡管看起來您也可以將其with mock.patch('django.http.response.HttpResponse', testutils.MockedHttpResponse) as HttpResponse:獲得所需的結果。 我認為您可能還想使用new_callable=testutils.MockedHttpResponse作為patch

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM