我认为这可以通过创建一个来实现TestCase
Monkeypatches 的子类django.http.response.HttpResponseBase.__init__()
记录堆栈跟踪并将其存储在Response
对象,然后写一个assertResponseCodeEquals(response, status_code=200)
方法,在无法显示位置时打印存储的堆栈跟踪Response
被创建。
我实际上可以自己使用一个解决方案,并且可能会考虑实施它。
更新:
这是一个 v1 实现,它可以使用一些改进(例如,仅打印堆栈跟踪的相关行)。
import mock
from traceback import extract_stack, format_list
from django.test.testcases import TestCase
from django.http.response import HttpResponseBase
orig_response_init = HttpResponseBase.__init__
def new_response_init(self, *args, **kwargs):
orig_response_init(self, *args, **kwargs)
self._init_stack = extract_stack()
class ResponseTracebackTestCase(TestCase):
@classmethod
def setUpClass(cls):
cls.patcher = mock.patch.object(HttpResponseBase, '__init__', new_response_init)
cls.patcher.start()
@classmethod
def tearDownClass(cls):
cls.patcher.stop()
def assertResponseCodeEquals(self, response, status_code=200):
self.assertEqual(response.status_code, status_code,
"Response code was '%s', expected '%s'" % (
response.status_code, status_code,
) + '\n' + ''.join(format_list(response._init_stack))
)
class MyTestCase(ResponseTracebackTestCase):
def test_index_page_returns_200(self):
response = self.client.get('/')
self.assertResponseCodeEquals(response, 200)