Django测试中,settings.DEBUG的值在settings和url之间发生变化。

7 浏览
0 Comments

Django测试中,settings.DEBUG的值在settings和url之间发生变化。

我正在尝试为一些仅在调试模式下设置的URL设置测试。它们没有设置,因为显然在我的设置文件和urls.py之间,DEBUG的值变为了False。我以前从未遇到过这个问题,并且我不记得做过任何特别复杂涉及DEBUG值的事情。

这是我的urls.py:

from django.conf import settings
from my_views import dnfp
print "settings.DEBUG in url: {}".format(settings.DEBUG)
if settings.DEBUG:
    urlpatterns += [url(r'^dnfp/$', dnfp, name="debug_not_found_page"...

这是我的设置文件:

DEBUG=True
print "DEBUG at the end of the settings: {}".format(DEBUG)

在我的测试中失败的内容:

 reverse("debug_not_found_page"), 

这是测试的输出:

DEBUG at the end of the settings: True
settings.DEBUG in url: False
Creating test database for alias 'default'...
.E
(...)
NoReverseMatch: Reverse for 'debug_not_found_page' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

如果我在urls.py中自己更改值,URL将再次设置,并且测试会使用以下的urls.py正常工作:

from django.conf import settings
from my_views import dnfp
settings.DEBUG = True
if settings.DEBUG:
    urlpatterns += [url(r'^dnfp/$', dnfp, name="debug_not_found_page"...

有任何关于为什么和何时我的DEBUG值在设置和urls之间改变的想法吗?

0
0 Comments

问题出现的原因是在设置DEBUG = True之后,已经将所有的URL添加到urlpatterns[]中,并且在添加URL时,Django实际上会将控制转移到urls.py进行语法验证。这就是为什么在urls.py中获得不同的值的原因。

解决方法是在这一行之前设置DEBUG的值。

另一种解决方法是创建一个单独的应用程序来处理所有这些类型的URL,并根据debug变量的值将该应用程序添加到INSTALLED_APPS中。

0
0 Comments

在Django测试中,无论配置文件中的DEBUG设置的值是什么,所有的Django测试都会以DEBUG=False的方式运行。这是为了确保代码的输出与在生产环境中看到的输出一致。

根据上述信息,我们可以得出出现(Value of settings.DEBUG changing between settings and url in Django Test)问题的原因是在Django测试中,无论配置文件中的DEBUG设置的值是什么,都会被设置为False,而不会根据配置文件中的值进行改变。因此,在测试过程中,无法通过修改配置文件来改变DEBUG设置的值。

解决这个问题的方法是通过在测试代码中显式地设置DEBUG的值为True。可以使用以下代码来实现:

from django.test import TestCase
from django.conf import settings
class MyTestCase(TestCase):
    def test_something(self):
        settings.DEBUG = True
        # 进行测试的代码

通过在测试代码中设置DEBUG的值为True,可以解决在测试过程中无法修改DEBUG设置的问题。这样,就可以在测试中使用DEBUG=True来进行调试和观察输出结果,以便更好地理解代码的运行情况。

0