Here are the examples of the python api django.test.override_settings taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
145 Examples
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_defaults_sameorigin(self):
"""
If the X_FRAME_OPTIONS setting is not set then it defaults to
SAMEORIGIN.
"""
with override_settings(X_FRAME_OPTIONS=None):
del settings.X_FRAME_OPTIONS # restored by override_settings
r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())
self.astertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
@skipUnlessDBFeature('has_bulk_insert')
def test_large_batch_efficiency(self):
with override_settings(DEBUG=True):
connection.queries_log.clear()
TwoFields.objects.bulk_create([
TwoFields(f1=i, f2=i + 1) for i in range(0, 1001)
])
self.astertLess(len(connection.queries), 10)
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
@skipUnlessDBFeature('has_bulk_insert')
def test_large_batch_mixed_efficiency(self):
"""
Test inserting a large batch with objects having primary key set
mixed together with objects without PK set.
"""
with override_settings(DEBUG=True):
connection.queries_log.clear()
TwoFields.objects.bulk_create([
TwoFields(id=i if i % 2 == 0 else None, f1=i, f2=i + 1)
for i in range(100000, 101000)])
self.astertLess(len(connection.queries), 10)
3
View Complete Implementation : test_compilation.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_nofuzzy_compiling(self):
with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]):
call_command('compilemessages', locale=[self.LOCALE], stdout=StringIO())
with translation.override(self.LOCALE):
self.astertEqual(gettext('Lenin'), 'Ленин')
self.astertEqual(gettext('Vodka'), 'Vodka')
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_same_origin(self):
"""
The X_FRAME_OPTIONS setting can be set to SAMEORIGIN to have the
middleware use that value for the HTTP header.
"""
with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):
r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())
self.astertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
with override_settings(X_FRAME_OPTIONS='sameorigin'):
r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())
self.astertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_debug(self):
url = '/debug/'
# We should have the debug flag in the template.
response = self.client.get(url)
self.astertContains(response, 'Have debug')
# And now we should not
with override_settings(DEBUG=False):
response = self.client.get(url)
self.astertNotContains(response, 'Have debug')
3
View Complete Implementation : test_extraction.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_media_static_dirs_ignored(self):
with override_settings(STATIC_ROOT=os.path.join(self.test_dir, 'static/'),
MEDIA_ROOT=os.path.join(self.test_dir, 'media_root/')):
out, _ = self._run_makemessages()
self.astertIn("ignoring directory static", out)
self.astertIn("ignoring directory media_root", out)
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_wsgirequest_with_force_script_name(self):
"""
The FORCE_SCRIPT_NAME setting takes precedence over the request's
SCRIPT_NAME environment parameter (#20169).
"""
with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX/'):
request = WSGIRequest({
'PATH_INFO': '/somepath/',
'SCRIPT_NAME': '/PREFIX/',
'REQUEST_METHOD': 'get',
'wsgi.input': BytesIO(b''),
})
self.astertEqual(request.path, '/FORCED_PREFIX/somepath/')
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_complex_override_warning(self):
"""Regression test for #19031"""
msg = 'Overriding setting TEST_WARN can lead to unexpected behavior.'
with self.astertWarnsMessage(UserWarning, msg) as cm:
with override_settings(TEST_WARN='override'):
self.astertEqual(settings.TEST_WARN, 'override')
self.astertEqual(cm.filename, __file__)
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_wsgirequest_with_force_script_name(self):
"""
The FORCE_SCRIPT_NAME setting takes precedence over the request's
SCRIPT_NAME environment parameter (#20169).
"""
with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX/'):
request = WSGIRequest({
'PATH_INFO': '/somepath/',
'SCRIPT_NAME': '/PREFIX/',
'REQUEST_METHOD': 'get',
'wsgi.input': BytesIO(b''),
})
self.astertEqual(request.path, '/FORCED_PREFIX/somepath/')
3
View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_no_warning_for_empty_staticdir(self):
stdout = StringIO()
with tempfile.TemporaryDirectory(prefix='collectstatic_empty_staticdir_test') as static_dir:
with override_settings(STATIC_ROOT=static_dir):
call_command('collectstatic', interactive=True, stdout=stdout)
output = stdout.getvalue()
self.astertNotIn(self.overwrite_warning_msg, output)
self.astertNotIn(self.delete_warning_msg, output)
self.astertIn(self.files_copied_msg, output)
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_context_manager(self):
with self.astertRaises(AttributeError):
getattr(settings, 'TEST')
override = override_settings(TEST='override')
with self.astertRaises(AttributeError):
getattr(settings, 'TEST')
override.enable()
self.astertEqual('override', settings.TEST)
override.disable()
with self.astertRaises(AttributeError):
getattr(settings, 'TEST')
3
View Complete Implementation : test_translation.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_invalid_language_code(self):
tags = (
'eü', # non-latin characters.
'en_US', # locale format.
'en--us', # empty subtag.
'-en', # leading separator.
'en-', # trailing separator.
'en-US.UTF-8', # language tag w/ locale encoding.
'en_US.UTF-8', # locale format - languate w/ region and encoding.
'[email protected]', # locale format - language w/ region and variant.
# FIXME: The following should be invalid:
# '[email protected]', # locale instead of language tag.
)
for tag in tags:
with self.subTest(tag), override_settings(LANGUAGE_CODE=tag):
result = check_setting_language_code(None)
self.astertEqual(result, [E001])
self.astertEqual(result[0].id, 'translation.E001')
self.astertEqual(result[0].msg, 'You have provided an invalid value for the LANGUAGE_CODE setting.')
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
@skipUnlessDBFeature('has_bulk_insert')
def test_large_batch_efficiency(self):
with override_settings(DEBUG=True):
connection.queries_log.clear()
TwoFields.objects.bulk_create([
TwoFields(f1=i, f2=i + 1) for i in range(0, 1001)
])
self.astertLess(len(connection.queries), 10)
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_context_manager(self):
with self.astertRaises(AttributeError):
getattr(settings, 'TEST')
override = override_settings(TEST='override')
with self.astertRaises(AttributeError):
getattr(settings, 'TEST')
override.enable()
self.astertEqual('override', settings.TEST)
override.disable()
with self.astertRaises(AttributeError):
getattr(settings, 'TEST')
3
View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_location_empty(self):
msg = 'without having set the STATIC_ROOT setting to a filesystem path'
err = StringIO()
for root in ['', None]:
with override_settings(STATIC_ROOT=root):
with self.astertRaisesMessage(ImproperlyConfigured, msg):
call_command('collectstatic', interactive=False, verbosity=0, stderr=err)
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_dont_set_if_set(self):
"""
If the X-Frame-Options header is already set then the middleware does
not attempt to override it.
"""
with override_settings(X_FRAME_OPTIONS='DENY'):
response = HttpResponse()
response['X-Frame-Options'] = 'SAMEORIGIN'
r = XFrameOptionsMiddleware().process_response(HttpRequest(), response)
self.astertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):
response = HttpResponse()
response['X-Frame-Options'] = 'DENY'
r = XFrameOptionsMiddleware().process_response(HttpRequest(), response)
self.astertEqual(r['X-Frame-Options'], 'DENY')
3
View Complete Implementation : test_compilation.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_multiple_locales(self):
with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]):
call_command('compilemessages', locale=['hr', 'fr'], stdout=StringIO())
self.astertTrue(os.path.exists(self.MO_FILE_HR))
self.astertTrue(os.path.exists(self.MO_FILE_FR))
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_wsgirequest_path_with_force_script_name_trailing_slash(self):
"""
The request's path is correctly astembled, regardless of whether or not
the FORCE_SCRIPT_NAME setting has a trailing slash (#20169).
"""
# With trailing slash
with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX/'):
request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')})
self.astertEqual(request.path, '/FORCED_PREFIX/somepath/')
# Without trailing slash
with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX'):
request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')})
self.astertEqual(request.path, '/FORCED_PREFIX/somepath/')
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_override_settings_exit(self):
"""Receiver fails on exit only."""
with self.astertRaises(SettingChangeExitException):
with override_settings(SETTING_Past='EXIT', SETTING_EXIT='EXIT'):
past
self.check_settings()
# Two settings were touched, so expect two calls of `spy_receiver`.
self.check_spy_receiver_exit_calls(call_count=2)
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_deny(self):
"""
The X_FRAME_OPTIONS setting can be set to DENY to have the middleware
use that value for the HTTP header.
"""
with override_settings(X_FRAME_OPTIONS='DENY'):
r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())
self.astertEqual(r['X-Frame-Options'], 'DENY')
with override_settings(X_FRAME_OPTIONS='deny'):
r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())
self.astertEqual(r['X-Frame-Options'], 'DENY')
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_dont_set_if_set(self):
"""
If the X-Frame-Options header is already set then the middleware does
not attempt to override it.
"""
with override_settings(X_FRAME_OPTIONS='DENY'):
response = HttpResponse()
response['X-Frame-Options'] = 'SAMEORIGIN'
r = XFrameOptionsMiddleware().process_response(HttpRequest(), response)
self.astertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):
response = HttpResponse()
response['X-Frame-Options'] = 'DENY'
r = XFrameOptionsMiddleware().process_response(HttpRequest(), response)
self.astertEqual(r['X-Frame-Options'], 'DENY')
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_cursor_executemany_with_iterator(self):
# Test executemany accepts iterators #10320
args = iter((i, i ** 2) for i in range(-3, 2))
self.create_squares_with_executemany(args)
self.astertEqual(Square.objects.count(), 5)
args = iter((i, i ** 2) for i in range(3, 7))
with override_settings(DEBUG=True):
# same test for DebugCursorWrapper
self.create_squares_with_executemany(args)
self.astertEqual(Square.objects.count(), 9)
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
@skipUnlessDBFeature('supports_paramstyle_pyformat')
def test_cursor_executemany_with_pyformat_iterator(self):
args = iter({'root': i, 'square': i ** 2} for i in range(-3, 2))
self.create_squares(args, 'pyformat', multiple=True)
self.astertEqual(Square.objects.count(), 5)
args = iter({'root': i, 'square': i ** 2} for i in range(3, 7))
with override_settings(DEBUG=True):
# same test for DebugCursorWrapper
self.create_squares(args, 'pyformat', multiple=True)
self.astertEqual(Square.objects.count(), 9)
3
View Complete Implementation : test_multidb.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_create_model4(self):
"""
Test multiple routers.
"""
with override_settings(DATABASE_ROUTERS=[AgnosticRouter(), AgnosticRouter()]):
self._test_create_model("test_mltdb_crmo4", should_run=True)
with override_settings(DATABASE_ROUTERS=[MigrateNothingRouter(), MigrateEverythingRouter()]):
self._test_create_model("test_mltdb_crmo4", should_run=False)
with override_settings(DATABASE_ROUTERS=[MigrateEverythingRouter(), MigrateNothingRouter()]):
self._test_create_model("test_mltdb_crmo4", should_run=True)
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_response_exempt(self):
"""
If the response has an xframe_options_exempt attribute set to False
then it still sets the header, but if it's set to True then it doesn't.
"""
with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):
response = HttpResponse()
response.xframe_options_exempt = False
r = XFrameOptionsMiddleware().process_response(HttpRequest(), response)
self.astertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
response = HttpResponse()
response.xframe_options_exempt = True
r = XFrameOptionsMiddleware().process_response(HttpRequest(), response)
self.astertIsNone(r.get('X-Frame-Options'))
3
View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_404_response(self):
command = runserver.Command()
handler = command.get_handler(use_static_handler=True, insecure_serving=True)
missing_static_file = os.path.join(settings.STATIC_URL, 'unknown.css')
req = RequestFactory().get(missing_static_file)
with override_settings(DEBUG=False):
response = handler.get_response(req)
self.astertEqual(response.status_code, 404)
with override_settings(DEBUG=True):
response = handler.get_response(req)
self.astertEqual(response.status_code, 404)
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_deny(self):
"""
The X_FRAME_OPTIONS setting can be set to DENY to have the middleware
use that value for the HTTP header.
"""
with override_settings(X_FRAME_OPTIONS='DENY'):
r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())
self.astertEqual(r['X-Frame-Options'], 'DENY')
with override_settings(X_FRAME_OPTIONS='deny'):
r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())
self.astertEqual(r['X-Frame-Options'], 'DENY')
3
View Complete Implementation : test_liveserver.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
@clastmethod
def setUpClast(cls):
# Override settings
cls.settings_override = override_settings(**TEST_SETTINGS)
cls.settings_override.enable()
super().setUpClast()
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
@skipUnlessDBFeature('supports_paramstyle_pyformat')
def test_cursor_executemany_with_pyformat_iterator(self):
args = iter({'root': i, 'square': i ** 2} for i in range(-3, 2))
self.create_squares(args, 'pyformat', multiple=True)
self.astertEqual(Square.objects.count(), 5)
args = iter({'root': i, 'square': i ** 2} for i in range(3, 7))
with override_settings(DEBUG=True):
# same test for DebugCursorWrapper
self.create_squares(args, 'pyformat', multiple=True)
self.astertEqual(Square.objects.count(), 9)
3
View Complete Implementation : test_loader.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_load_module_file(self):
with override_settings(MIGRATION_MODULES={"migrations": "migrations.faulty_migrations.file"}):
loader = MigrationLoader(connection)
self.astertIn(
"migrations", loader.unmigrated_apps,
"App with migrations module file not in unmigrated apps."
)
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_naturalday_uses_localtime(self):
# Regression for #18504
# This is 2012-03-08HT19:30:00-06:00 in America/Chicago
dt = datetime.datetime(2012, 3, 9, 1, 30, tzinfo=utc)
orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime
try:
with override_settings(TIME_ZONE="America/Chicago", USE_TZ=True):
with translation.override('en'):
self.humanize_tester([dt], ['yesterday'], 'naturalday')
finally:
humanize.datetime = orig_humanize_datetime
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_override_settings_enter(self):
"""Receiver fails on enter only."""
with self.astertRaises(SettingChangeEnterException):
with override_settings(SETTING_Past='ENTER', SETTING_ENTER='ENTER'):
past
self.check_settings()
# Two settings were touched, so expect two calls of `spy_receiver`.
self.check_spy_receiver_exit_calls(call_count=2)
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_wsgirequest_path_with_force_script_name_trailing_slash(self):
"""
The request's path is correctly astembled, regardless of whether or not
the FORCE_SCRIPT_NAME setting has a trailing slash (#20169).
"""
# With trailing slash
with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX/'):
request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')})
self.astertEqual(request.path, '/FORCED_PREFIX/somepath/')
# Without trailing slash
with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX'):
request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')})
self.astertEqual(request.path, '/FORCED_PREFIX/somepath/')
3
View Complete Implementation : test_compilation.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_fuzzy_compiling(self):
with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]):
call_command('compilemessages', locale=[self.LOCALE], fuzzy=True, stdout=StringIO())
with translation.override(self.LOCALE):
self.astertEqual(gettext('Lenin'), 'Ленин')
self.astertEqual(gettext('Vodka'), 'Водка')
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_clast_decorator(self):
# SimpleTestCase can be decorated by override_settings, but not ut.TestCase
clast SimpleTestCaseSubclast(SimpleTestCase):
past
clast UnittestTestCaseSubclast(unittest.TestCase):
past
decorated = override_settings(TEST='override')(SimpleTestCaseSubclast)
self.astertIsInstance(decorated, type)
self.astertTrue(issubclast(decorated, SimpleTestCase))
with self.astertRaisesMessage(Exception, "Only subclastes of Django SimpleTestCase"):
decorated = override_settings(TEST='override')(UnittestTestCaseSubclast)
3
View Complete Implementation : test_extraction.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_media_static_dirs_ignored(self):
"""
Regression test for #23583.
"""
with override_settings(STATIC_ROOT=os.path.join(self.test_dir, 'static/'),
MEDIA_ROOT=os.path.join(self.test_dir, 'media_root/')):
_, po_contents = self._run_makemessages(domain='djangojs')
self.astertMsgId("Static content inside app should be included.", po_contents)
self.astertNotMsgId("Content from STATIC_ROOT should not be included", po_contents)
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_clast_decorator(self):
# SimpleTestCase can be decorated by override_settings, but not ut.TestCase
clast SimpleTestCaseSubclast(SimpleTestCase):
past
clast UnittestTestCaseSubclast(unittest.TestCase):
past
decorated = override_settings(TEST='override')(SimpleTestCaseSubclast)
self.astertIsInstance(decorated, type)
self.astertTrue(issubclast(decorated, SimpleTestCase))
with self.astertRaisesMessage(Exception, "Only subclastes of Django SimpleTestCase"):
decorated = override_settings(TEST='override')(UnittestTestCaseSubclast)
3
View Complete Implementation : test_loader.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_load_empty_dir(self):
with override_settings(MIGRATION_MODULES={"migrations": "migrations.faulty_migrations.namespace"}):
loader = MigrationLoader(connection)
self.astertIn(
"migrations", loader.unmigrated_apps,
"App missing __init__.py in migrations module not in unmigrated apps."
)
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_cursor_executemany_with_iterator(self):
# Test executemany accepts iterators #10320
args = iter((i, i ** 2) for i in range(-3, 2))
self.create_squares_with_executemany(args)
self.astertEqual(Square.objects.count(), 5)
args = iter((i, i ** 2) for i in range(3, 7))
with override_settings(DEBUG=True):
# same test for DebugCursorWrapper
self.create_squares_with_executemany(args)
self.astertEqual(Square.objects.count(), 9)
3
View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_location_empty(self):
msg = 'without having set the STATIC_ROOT setting to a filesystem path'
err = StringIO()
for root in ['', None]:
with override_settings(STATIC_ROOT=root):
with self.astertRaisesMessage(ImproperlyConfigured, msg):
call_command('collectstatic', interactive=False, verbosity=0, stderr=err)
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
@skipUnlessDBFeature('has_bulk_insert')
def test_large_batch_mixed_efficiency(self):
"""
Test inserting a large batch with objects having primary key set
mixed together with objects without PK set.
"""
with override_settings(DEBUG=True):
connection.queries_log.clear()
TwoFields.objects.bulk_create([
TwoFields(id=i if i % 2 == 0 else None, f1=i, f2=i + 1)
for i in range(100000, 101000)])
self.astertLess(len(connection.queries), 10)
3
View Complete Implementation : test_compilation.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_nofuzzy_compiling(self):
with override_settings(LOCALE_PATHS=[os.path.join(self.test_dir, 'locale')]):
call_command('compilemessages', locale=[self.LOCALE], stdout=StringIO())
with translation.override(self.LOCALE):
self.astertEqual(gettext('Lenin'), 'Ленин')
self.astertEqual(gettext('Vodka'), 'Vodka')
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_naturalday_uses_localtime(self):
# Regression for #18504
# This is 2012-03-08HT19:30:00-06:00 in America/Chicago
dt = datetime.datetime(2012, 3, 9, 1, 30, tzinfo=utc)
orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime
try:
with override_settings(TIME_ZONE="America/Chicago", USE_TZ=True):
with translation.override('en'):
self.humanize_tester([dt], ['yesterday'], 'naturalday')
finally:
humanize.datetime = orig_humanize_datetime
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_response_exempt(self):
"""
If the response has an xframe_options_exempt attribute set to False
then it still sets the header, but if it's set to True then it doesn't.
"""
with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):
response = HttpResponse()
response.xframe_options_exempt = False
r = XFrameOptionsMiddleware().process_response(HttpRequest(), response)
self.astertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
response = HttpResponse()
response.xframe_options_exempt = True
r = XFrameOptionsMiddleware().process_response(HttpRequest(), response)
self.astertIsNone(r.get('X-Frame-Options'))
3
View Complete Implementation : test_multidb.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_create_model4(self):
"""
Test multiple routers.
"""
with override_settings(DATABASE_ROUTERS=[AgnosticRouter(), AgnosticRouter()]):
self._test_create_model("test_mltdb_crmo4", should_run=True)
with override_settings(DATABASE_ROUTERS=[MigrateNothingRouter(), MigrateEverythingRouter()]):
self._test_create_model("test_mltdb_crmo4", should_run=False)
with override_settings(DATABASE_ROUTERS=[MigrateEverythingRouter(), MigrateNothingRouter()]):
self._test_create_model("test_mltdb_crmo4", should_run=True)
3
View Complete Implementation : test_management.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_404_response(self):
command = runserver.Command()
handler = command.get_handler(use_static_handler=True, insecure_serving=True)
missing_static_file = os.path.join(settings.STATIC_URL, 'unknown.css')
req = RequestFactory().get(missing_static_file)
with override_settings(DEBUG=False):
response = handler.get_response(req)
self.astertEqual(response.status_code, 404)
with override_settings(DEBUG=True):
response = handler.get_response(req)
self.astertEqual(response.status_code, 404)
3
View Complete Implementation : test_translation.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_valid_language_code(self):
tags = (
'en', # language
'mas', # language
'sgn-ase', # language+extlang
'fr-CA', # language+region
'es-419', # language+region
'zh-Hans', # language+script
'ca-ES-valencia', # language+region+variant
# FIXME: The following should be invalid:
'[email protected]', # language+script
)
for tag in tags:
with self.subTest(tag), override_settings(LANGUAGE_CODE=tag):
self.astertEqual(check_setting_language_code(None), [])
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_same_origin(self):
"""
The X_FRAME_OPTIONS setting can be set to SAMEORIGIN to have the
middleware use that value for the HTTP header.
"""
with override_settings(X_FRAME_OPTIONS='SAMEORIGIN'):
r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())
self.astertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
with override_settings(X_FRAME_OPTIONS='sameorigin'):
r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse())
self.astertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_debug(self):
url = '/debug/'
# We should have the debug flag in the template.
response = self.client.get(url)
self.astertContains(response, 'Have debug')
# And now we should not
with override_settings(DEBUG=False):
response = self.client.get(url)
self.astertNotContains(response, 'Have debug')