如何在运行Django测试时将DEBUG设置为True?

epfja78i  于 11个月前  发布在  Go
关注(0)|答案(7)|浏览(173)

我目前正在运行一些Django测试,默认情况下看起来是DEBUG=False。有没有一种方法可以运行一个特定的测试,我可以在命令行或代码中设置DEBUG=True

3xiyfsfu

3xiyfsfu1#

对于测试用例中的特定测试,您可以使用override_settings装饰器:

from django.test.utils import override_settings
from django.conf import settings
class TestSomething(TestCase):
    @override_settings(DEBUG=True)
    def test_debug(self):
        assert settings.DEBUG

字符串

dbf7pr2w

dbf7pr2w2#

从Django 1.11开始,您可以在运行测试之前使用--debug-mode将DEBUG设置为True。

0yg35tkg

0yg35tkg3#

接受的答案对我不起作用。我使用Selenium进行测试,设置@override_settings(DEBUG=True)会使测试浏览器总是在每个页面上显示404错误。而DEBUG=False不会显示异常跟踪。所以我找到了一个解决方案。
这个想法是模拟DEBUG=True行为,使用自定义的500处理程序和内置的django 500错误处理程序。
1.将此添加到 myapp.views:

import sys
from django import http
from django.views.debug import ExceptionReporter

def show_server_error(request):
    """
    500 error handler to show Django default 500 template
    with nice error information and traceback.
    Useful in testing, if you can't set DEBUG=True.

    Templates: `500.html`
    Context: sys.exc_info() results
     """
    exc_type, exc_value, exc_traceback = sys.exc_info()
    error = ExceptionReporter(request, exc_type, exc_value, exc_traceback)
    return http.HttpResponseServerError(error.get_traceback_html())

字符串
1.urls.py:

from django.conf import settings

if settings.TESTING_MODE:
    # enable this handler only for testing, 
    # so that if DEBUG=False and we're not testing,
    # the default handler is used
    handler500 = 'myapp.views.show_server_error'


1.* 设置.py:*

# detect testing mode
import sys
TESTING_MODE = 'test' in sys.argv


现在,如果您的任何Selenium测试遇到500 error,您将看到一个漂亮的错误页面,其中包含traceback和所有内容。如果您运行正常的非测试环境,则使用默认的500处理程序。
灵感来自:

4ioopgfo

4ioopgfo4#

好吧,假设你想为错误测试用例编写测试,其urls是:

url.py

if settings.DEBUG:
    urlpatterns += [
        url(r'^404/$', page_not_found_view),
        url(r'^500/$', my_custom_error_view),
        url(r'^400/$', bad_request_view),
        url(r'^403/$', permission_denied_view),
    ]

字符串

test_urls.py:-

from django.conf import settings

class ErroCodeUrl(TestCase):

    def setUp(self):
        settings.DEBUG = True

    def test_400_error(self):
        response = self.client.get('/400/')
        self.assertEqual(response.status_code, 500)

希望你有一些想法!

ndasle7k

ndasle7k5#

除了https://stackoverflow.com/a/1118271/5750078使用Python 3.7之外,其他都不适合我

breakpoint()

字符串
方法。在pycharm上运行良好

txu3uszq

txu3uszq6#

版本4.2设置一个env变量

DJANGO_LOG_LEVEL=DEBUG

字符串
https://docs.djangoproject.com/en/4.2/topics/logging/#examples

blpfk2vs

blpfk2vs7#

在运行单元测试时,您无法看到DEBUG=True的结果。页面不会显示在任何地方。没有浏览器。
更改DEBUG没有效果,因为网页(带有调试输出)在任何地方都不可见。
如果您想查看与失败的单元测试相关的调试网页,请执行此操作。
1.删除您的开发数据库。
1.重新运行syncdb以生成空的开发数据库。
1.运行各种loaddata脚本,在开发数据库中为该测试重新构建fixture。
1.运行服务器并浏览页面。
现在您可以看到调试输出。

相关问题