django测试的覆盖设置似乎不起作用

时间:2017-09-06 23:54:32

标签: python django

我必须在Django的测试中覆盖设置

@override_settings(XYZ_REDIRECT="http://localhost:8000")
@override_settings(TOKEN_TIMEOUT=0)
class CustomTestCase(TestCase):

    def setUp(self):
        self.token = self._generate_auth_token()
        self.client = Client()

    def test_token_expiry(self):
        feoken_count = 0
        client = Client()
        client.post('/api/v1/auth/login/', {'token': 'AF'})
        # Over HERE TOKEN_TIMEOUT is not changed
        self.assertEqual(ABCN.objects.count(), feoken_count)

覆盖设置装饰器似乎不起作用。在路线的另一边,我有这个代码。

from fetchcore_server.settings import AUTH0_SERVER_URL, TOKEN_TIMEOUT
....
def post(self, request, *args, **kwargs):
    if 'token' in request.data:
        FetchcoreToken.objects.filter(expiry_time__lte=timezone.now()).delete()
        print TOKEN_TIMEOUT # this is still original value
        token = request.data['token']
        try:
            fetchcore_token = FetchcoreToken.objects.get(token=token)
            user = fetchcore_token.user
            user_id = user.id

我尝试使用with self.settings(TOKEN_TIMEOUT=0),但即使这样也行不通。

我不确定我是如何使用这个错误的

Django关于这个主题的文档:https://docs.djangoproject.com/en/1.11/topics/testing/tools/

如果它是相关的,这就是我运行测试的方式

python manage.py test api.tests.integration.v1.users.AuthUserTestCase

1 个答案:

答案 0 :(得分:3)

您的问题是您直接使用import设置

from fetchcore_server.settings import AUTH0_SERVER_URL, TOKEN_TIMEOUT

但您应该使用django https://docs.djangoproject.com/en/1.11/topics/settings/#using-settings-in-python-code

提供的settings对象
from django.conf import settings
....
def post(self, request, *args, **kwargs):
    if 'token' in request.data:
        FetchcoreToken.objects.filter(expiry_time__lte=timezone.now()).delete()
        print settings.TOKEN_TIMEOUT # this is still original value
        token = request.data['token']
        try:
            fetchcore_token = FetchcoreToken.objects.get(token=token)
            user = fetchcore_token.user
            user_id = user.id

另外,作为旁注,您可以一次性提供所有重载设置

@override_settings(XYZ_REDIRECT="http://localhost:8000", TOKEN_TIMEOUT=0)
class CustomTestCase(TestCase):