如何制作Django LiveServerTestCase日志请求

时间:2017-08-31 12:37:01

标签: django

Django有log each http request的功能。例如:

INFO 2017-08-31 11:52:40,725 arnaud basehttp "GET /design/projects/ HTTP/1.1" 200 3852

不幸的是,它似乎在运行LiveServerTestCase时被禁用。为了简化端到端测试的调试,我希望此功能保持激活状态。

1 个答案:

答案 0 :(得分:2)

事实证明,这种行为似乎并不可配置。我无法找到关于这个主题的任何文档,并在Django内部进行潜水。

解决方案

免责声明:这是非官方的,因此很脆弱)

覆盖server_thread_class

LiveServerTestCase属性
from django.core.servers.basehttp import WSGIServer, WSGIRequestHandler
from django.test.testcases import LiveServerTestCase, LiveServerThread

class End2End(LiveServerTestCase):

    class VersboseLiveServerThread(LiveServerThread):
        def _create_server(self):
            return WSGIServer((self.host, self.port), WSGIRequestHandler, allow_reuse_address=False)

    server_thread_class = VersboseLiveServerThread

更多细节

这个解决方案以及无法正确配置该行为的感觉源于观察LiveServerTestCase的构建方式(Django 1.11):

class LiveServerTestCase(TransactionTestCase):
    # [...]
    server_thread_class = LiveServerThread

class LiveServerThread(threading.Thread):
    # [...]
    def _create_server(self):
        # an extension point returning the WSGIRequestHandler would have been nice :)
        return WSGIServer((self.host, self.port), QuietWSGIRequestHandler, allow_reuse_address=False)

class QuietWSGIRequestHandler(WSGIRequestHandler):
    def log_message(*args):
        pass