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
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'
7条答案
按热度按时间3xiyfsfu1#
对于测试用例中的特定测试,您可以使用override_settings装饰器:
字符串
dbf7pr2w2#
从Django 1.11开始,您可以在运行测试之前使用
--debug-mode
将DEBUG设置为True。0yg35tkg3#
接受的答案对我不起作用。我使用Selenium进行测试,设置
@override_settings(DEBUG=True)
会使测试浏览器总是在每个页面上显示404
错误。而DEBUG=False
不会显示异常跟踪。所以我找到了一个解决方案。这个想法是模拟
DEBUG=True
行为,使用自定义的500
处理程序和内置的django500
错误处理程序。1.将此添加到 myapp.views:
字符串
1.urls.py:
型
1.* 设置.py:*
型
现在,如果您的任何Selenium测试遇到500 error,您将看到一个漂亮的错误页面,其中包含traceback和所有内容。如果您运行正常的非测试环境,则使用默认的500处理程序。
灵感来自:
4ioopgfo4#
好吧,假设你想为错误测试用例编写测试,其urls是:
url.py
字符串
test_urls.py:-
型
希望你有一些想法!
ndasle7k5#
除了https://stackoverflow.com/a/1118271/5750078使用Python 3.7之外,其他都不适合我
字符串
方法。在pycharm上运行良好
txu3uszq6#
版本4.2设置一个env变量
字符串
https://docs.djangoproject.com/en/4.2/topics/logging/#examples
blpfk2vs7#
在运行单元测试时,您无法看到
DEBUG=True
的结果。页面不会显示在任何地方。没有浏览器。更改
DEBUG
没有效果,因为网页(带有调试输出)在任何地方都不可见。如果您想查看与失败的单元测试相关的调试网页,请执行此操作。
1.删除您的开发数据库。
1.重新运行
syncdb
以生成空的开发数据库。1.运行各种
loaddata
脚本,在开发数据库中为该测试重新构建fixture。1.运行服务器并浏览页面。
现在您可以看到调试输出。