![](/img/trans.png)
[英]Python - TypeError: super(type, obj): obj must be an instance or subtype of type?
[英]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.