您可以覆盖测试的所有设置。它是一种更“Django”的方式 - 文档不鼓励直接更改settings
. Django 文档中有一个关于它的部分。
import os
from django.conf import settings
from django.test import TestCase, override_settings
@override_settings(MEDIA_ROOT=os.path.join(settings.PROJECT_PATH, 'fixtures/test_media/'))
class TestMedia(TestCase):
fixtures = ['fixtures/test_data.json']
def setUp(self):
# any other setup stuff you need
关于覆盖设置的更多信息。您可以使用装饰器进行整个测试:
from django.test import TestCase, override_settings
@override_settings(LOGIN_URL='/other/login/')
class LoginTestCase(TestCase):
def test_login(self):
response = self.client.get('/sekrit/')
self.assertRedirects(response, '/other/login/?next=/sekrit/')
或者您可以覆盖部分代码的设置:
from django.test import TestCase
class LoginTestCase(TestCase):
def test_login(self):
# First check for the default behavior
response = self.client.get('/sekrit/')
self.assertRedirects(response, '/accounts/login/?next=/sekrit/')
# Then override the LOGIN_URL setting
with self.settings(LOGIN_URL='/other/login/'):
response = self.client.get('/sekrit/')
self.assertRedirects(response, '/other/login/?next=/sekrit/')
请注意内联版本的不同语法。示例取自文档。