Here are the examples of the python api django.test.utils.override_settings taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
84 Examples
3
Source : testcases.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def setUpClass(cls):
super().setUpClass()
if cls._overridden_settings:
cls._cls_overridden_context = override_settings(**cls._overridden_settings)
cls._cls_overridden_context.enable()
if cls._modified_settings:
cls._cls_modified_context = modify_settings(cls._modified_settings)
cls._cls_modified_context.enable()
if not cls.allow_database_queries:
for alias in connections:
connection = connections[alias]
connection.cursor = _CursorFailure(cls.__name__, connection.cursor)
connection.chunked_cursor = _CursorFailure(cls.__name__, connection.chunked_cursor)
@classmethod
3
Source : testcases.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def settings(self, **kwargs):
"""
A context manager that temporarily sets a setting and reverts to the
original value when exiting the context.
"""
return override_settings(**kwargs)
def modify_settings(self, **kwargs):
3
Source : testcases.py
with MIT License
from Air-999
with MIT License
from Air-999
def setUpClass(cls):
super().setUpClass()
if cls._overridden_settings:
cls._cls_overridden_context = override_settings(**cls._overridden_settings)
cls._cls_overridden_context.enable()
if cls._modified_settings:
cls._cls_modified_context = modify_settings(cls._modified_settings)
cls._cls_modified_context.enable()
cls._add_databases_failures()
@classmethod
3
Source : test_url_checker.py
with GNU General Public License v3.0
from AliSayyah
with GNU General Public License v3.0
from AliSayyah
def test_correct_urls():
"""Test that no errors are raised when the urlconf is correct.
Returns:
None
"""
with override_settings(ROOT_URLCONF='tests.dummy_project.urls.correct_urls'):
errors = check_url_signatures(None)
assert not errors
def test_incorrect_urls():
3
Source : test_url_checker.py
with GNU General Public License v3.0
from AliSayyah
with GNU General Public License v3.0
from AliSayyah
def test_all_urls_checked():
"""Test that all urls are checked.
Returns:
None
"""
with override_settings(ROOT_URLCONF='tests.dummy_project.urls.correct_urls'):
resolver = get_resolver()
routes = get_all_routes(resolver)
assert len(list(routes)) == 3
def test_child_urls_checked():
3
Source : test_url_checker.py
with GNU General Public License v3.0
from AliSayyah
with GNU General Public License v3.0
from AliSayyah
def test_child_urls_checked():
"""Test that child urls are checked.
Returns:
None
"""
with override_settings(ROOT_URLCONF='tests.dummy_project.urls.parent_urls'):
resolver = get_resolver()
routes = get_all_routes(resolver)
assert len(list(routes)) == 3
3
Source : testcases.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def setUpClass(cls):
super(SimpleTestCase, cls).setUpClass()
if cls._overridden_settings:
cls._cls_overridden_context = override_settings(**cls._overridden_settings)
cls._cls_overridden_context.enable()
if cls._modified_settings:
cls._cls_modified_context = modify_settings(cls._modified_settings)
cls._cls_modified_context.enable()
if not cls.allow_database_queries:
for alias in connections:
connection = connections[alias]
connection.cursor = _CursorFailure(cls.__name__, connection.cursor)
connection.chunked_cursor = _CursorFailure(cls.__name__, connection.chunked_cursor)
@classmethod
3
Source : testcases.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def settings(self, **kwargs):
"""
A context manager that temporarily sets a setting and reverts to the original value when exiting the context.
"""
return override_settings(**kwargs)
def modify_settings(self, **kwargs):
3
Source : tests.py
with BSD 2-Clause "Simplified" License
from django-auth-ldap
with BSD 2-Clause "Simplified" License
from django-auth-ldap
def _override_settings(**settings):
def decorator(func):
@functools.wraps(func)
def wrapped_test(self, *args, **kwargs):
cm = override_settings(**settings)
cm.enable()
self.addCleanup(cm.disable)
return func(self, *args, **kwargs)
return wrapped_test
return decorator
def spy_ldap(name):
3
Source : tests.py
with BSD 2-Clause "Simplified" License
from django-auth-ldap
with BSD 2-Clause "Simplified" License
from django-auth-ldap
def _init_settings(self, **kwargs):
kwargs.setdefault("SERVER_URI", self.server.ldap_uri)
settings = {}
for key, value in kwargs.items():
settings["AUTH_LDAP_%s" % key] = value
cm = override_settings(**settings)
cm.enable()
self.addCleanup(cm.disable)
def _init_groups(self):
3
Source : tests.py
with BSD 2-Clause "Simplified" License
from django-otp
with BSD 2-Clause "Simplified" License
from django-otp
def test_config_url_no_issuer(self):
with override_settings(OTP_HOTP_ISSUER=None):
url = self.device.config_url
parsed = urlsplit(url)
params = parse_qs(parsed.query)
self.assertEqual(parsed.scheme, 'otpauth')
self.assertEqual(parsed.netloc, 'hotp')
self.assertEqual(parsed.path, '/alice')
self.assertIn('secret', params)
self.assertNotIn('issuer', params)
def test_config_url_issuer(self):
3
Source : tests.py
with BSD 2-Clause "Simplified" License
from django-otp
with BSD 2-Clause "Simplified" License
from django-otp
def test_config_url_issuer(self):
with override_settings(OTP_HOTP_ISSUER='example.com'):
url = self.device.config_url
parsed = urlsplit(url)
params = parse_qs(parsed.query)
self.assertEqual(parsed.scheme, 'otpauth')
self.assertEqual(parsed.netloc, 'hotp')
self.assertEqual(parsed.path, '/example.com%3Aalice')
self.assertIn('secret', params)
self.assertIn('issuer', params)
self.assertEqual(params['issuer'][0], 'example.com')
def test_config_url_issuer_spaces(self):
3
Source : tests.py
with BSD 2-Clause "Simplified" License
from django-otp
with BSD 2-Clause "Simplified" License
from django-otp
def test_config_url_issuer_spaces(self):
with override_settings(OTP_HOTP_ISSUER='Very Trustworthy Source'):
url = self.device.config_url
parsed = urlsplit(url)
params = parse_qs(parsed.query)
self.assertEqual(parsed.scheme, 'otpauth')
self.assertEqual(parsed.netloc, 'hotp')
self.assertEqual(parsed.path, '/Very%20Trustworthy%20Source%3Aalice')
self.assertIn('secret', params)
self.assertIn('issuer', params)
self.assertEqual(params['issuer'][0], 'Very Trustworthy Source')
def test_config_url_issuer_method(self):
3
Source : tests.py
with BSD 2-Clause "Simplified" License
from django-otp
with BSD 2-Clause "Simplified" License
from django-otp
def test_config_url_issuer_method(self):
with override_settings(OTP_HOTP_ISSUER=lambda d: d.user.email):
url = self.device.config_url
parsed = urlsplit(url)
params = parse_qs(parsed.query)
self.assertEqual(parsed.scheme, 'otpauth')
self.assertEqual(parsed.netloc, 'hotp')
self.assertEqual(parsed.path, '/alice%40example.com%3Aalice')
self.assertIn('secret', params)
self.assertIn('issuer', params)
self.assertEqual(params['issuer'][0], '[email protected]')
class AuthFormTest(TestCase):
3
Source : tests.py
with BSD 2-Clause "Simplified" License
from django-otp
with BSD 2-Clause "Simplified" License
from django-otp
def test_config_url(self):
with override_settings(OTP_TOTP_ISSUER=None):
url = self.device.config_url
parsed = urlsplit(url)
params = parse_qs(parsed.query)
self.assertEqual(parsed.scheme, 'otpauth')
self.assertEqual(parsed.netloc, 'totp')
self.assertEqual(parsed.path, '/alice')
self.assertIn('secret', params)
self.assertNotIn('issuer', params)
def test_config_url_issuer(self):
3
Source : tests.py
with BSD 2-Clause "Simplified" License
from django-otp
with BSD 2-Clause "Simplified" License
from django-otp
def test_config_url_issuer(self):
with override_settings(OTP_TOTP_ISSUER='example.com'):
url = self.device.config_url
parsed = urlsplit(url)
params = parse_qs(parsed.query)
self.assertEqual(parsed.scheme, 'otpauth')
self.assertEqual(parsed.netloc, 'totp')
self.assertEqual(parsed.path, '/example.com%3Aalice')
self.assertIn('secret', params)
self.assertIn('issuer', params)
self.assertEqual(params['issuer'][0], 'example.com')
def test_config_url_issuer_spaces(self):
3
Source : tests.py
with BSD 2-Clause "Simplified" License
from django-otp
with BSD 2-Clause "Simplified" License
from django-otp
def test_config_url_issuer_spaces(self):
with override_settings(OTP_TOTP_ISSUER='Very Trustworthy Source'):
url = self.device.config_url
parsed = urlsplit(url)
params = parse_qs(parsed.query)
self.assertEqual(parsed.scheme, 'otpauth')
self.assertEqual(parsed.netloc, 'totp')
self.assertEqual(parsed.path, '/Very%20Trustworthy%20Source%3Aalice')
self.assertIn('secret', params)
self.assertIn('issuer', params)
self.assertEqual(params['issuer'][0], 'Very Trustworthy Source')
def test_config_url_issuer_method(self):
3
Source : tests.py
with BSD 2-Clause "Simplified" License
from django-otp
with BSD 2-Clause "Simplified" License
from django-otp
def test_config_url_issuer_method(self):
with override_settings(OTP_TOTP_ISSUER=lambda d: d.user.email):
url = self.device.config_url
parsed = urlsplit(url)
params = parse_qs(parsed.query)
self.assertEqual(parsed.scheme, 'otpauth')
self.assertEqual(parsed.netloc, 'totp')
self.assertEqual(parsed.path, '/alice%40example.com%3Aalice')
self.assertIn('secret', params)
self.assertIn('issuer', params)
self.assertEqual(params['issuer'][0], '[email protected]')
class TOTPAdminTest(TestCase):
3
Source : snippet.py
with Apache License 2.0
from dockerizeme
with Apache License 2.0
from dockerizeme
def handle_app(self, app, **options):
for model in models.get_models(app):
meta = model._meta
self.stdout.write(u"%s.%s: " % (meta.app_label, meta.object_name))
if meta.proxy:
self.stdout.write(u"OK (proxy model)\n")
continue
fields = [f.name for f in meta.local_fields if isinstance(f, models.DateTimeField)]
if not fields:
self.stdout.write(u"OK (no datetime fields)\n")
continue
self.stdout.write(u"fields to convert: %s\n" % u" ".join(fields))
with transaction.commit_on_success():
with override_settings(USE_TZ=False):
for obj in model.objects.all().only(*fields).iterator():
with override_settings(USE_TZ=True):
# Bypass model.save() to preserve auto_now fields
values = dict((f, getattr(obj, f)) for f in fields)
model.objects.filter(pk=obj.pk).update(**values)
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
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
def test_naturaltime(self):
3
Source : testcases.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def settings(self, **kwargs):
"""
A context manager that temporarily sets a setting and reverts
back to the original value when exiting the context.
"""
return override_settings(**kwargs)
def assertRedirects(self, response, expected_url, status_code=302,
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_cursor_executemany_with_iterator(self):
#10320: executemany accepts iterators
args = iter((i, i**2) for i in range(-3, 2))
self.create_squares_with_executemany(args)
self.assertEqual(models.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.assertEqual(models.Square.objects.count(), 9)
@skipUnlessDBFeature('supports_paramstyle_pyformat')
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
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.assertEqual(models.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.assertEqual(models.Square.objects.count(), 9)
def test_unicode_fetches(self):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_large_batch(self):
with override_settings(DEBUG=True):
connection.queries = []
TwoFields.objects.bulk_create([
TwoFields(f1=i, f2=i+1) for i in range(0, 1001)
])
self.assertEqual(TwoFields.objects.count(), 1001)
self.assertEqual(
TwoFields.objects.filter(f1__gte=450, f1__lte=550).count(),
101)
self.assertEqual(TwoFields.objects.filter(f2__gte=901).count(), 101)
@skipUnlessDBFeature('has_bulk_insert')
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_large_batch_efficiency(self):
with override_settings(DEBUG=True):
connection.queries = []
TwoFields.objects.bulk_create([
TwoFields(f1=i, f2=i+1) for i in range(0, 1001)
])
self.assertTrue(len(connection.queries) < 10)
def test_large_batch_mixed(self):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_large_batch_mixed(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 = []
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.assertEqual(TwoFields.objects.count(), 1000)
# We can't assume much about the ID's created, except that the above
# created IDs must exist.
id_range = range(100000, 101000, 2)
self.assertEqual(TwoFields.objects.filter(id__in=id_range).count(), 500)
self.assertEqual(TwoFields.objects.exclude(id__in=id_range).count(), 500)
@skipUnlessDBFeature('has_bulk_insert')
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
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 = []
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.assertTrue(len(connection.queries) < 10)
def test_explicit_batch_size(self):
3
Source : test_comment_utils_moderators.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def testEmailNotification(self):
with override_settings(MANAGERS=("[email protected]",)):
moderator.register(Entry, EntryModerator1)
self.createSomeComments()
self.assertEqual(len(mail.outbox), 2)
def testCommentsEnabled(self):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def setUp(self):
super(FileBackendTests, self).setUp()
self.tmp_dir = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.tmp_dir)
self._settings_override = override_settings(EMAIL_FILE_PATH=self.tmp_dir)
self._settings_override.enable()
def tearDown(self):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def setUpClass(cls):
cls.server = FakeSMTPServer(('127.0.0.1', 0), None)
cls._settings_override = override_settings(
EMAIL_HOST="127.0.0.1",
EMAIL_PORT=cls.server.socket.getsockname()[1])
cls._settings_override.enable()
cls.server.start()
@classmethod
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_same_origin(self):
"""
Tests that 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.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
with override_settings(X_FRAME_OPTIONS='sameorigin'):
r = XFrameOptionsMiddleware().process_response(HttpRequest(),
HttpResponse())
self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
def test_deny(self):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_deny(self):
"""
Tests that 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.assertEqual(r['X-Frame-Options'], 'DENY')
with override_settings(X_FRAME_OPTIONS='deny'):
r = XFrameOptionsMiddleware().process_response(HttpRequest(),
HttpResponse())
self.assertEqual(r['X-Frame-Options'], 'DENY')
def test_defaults_sameorigin(self):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_defaults_sameorigin(self):
"""
Tests that 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.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
def test_dont_set_if_set(self):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_wsgirequest_with_force_script_name(self):
"""
Ensure that the FORCE_SCRIPT_NAME setting takes precedence over the
request's SCRIPT_NAME environment parameter.
Refs #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.assertEqual(request.path, '/FORCED_PREFIX/somepath/')
def test_wsgirequest_path_with_force_script_name_trailing_slash(self):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_wsgirequest_path_with_force_script_name_trailing_slash(self):
"""
Ensure that the request's path is correctly assembled, regardless of
whether or not the FORCE_SCRIPT_NAME setting has a trailing slash.
Refs #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.assertEqual(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.assertEqual(request.path, '/FORCED_PREFIX/somepath/')
def test_wsgirequest_repr(self):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def setUpClass(cls):
# Override settings
cls.settings_override = override_settings(**TEST_SETTINGS)
cls.settings_override.enable()
super(LiveServerBase, cls).setUpClass()
@classmethod
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_context_manager(self):
self.assertRaises(AttributeError, getattr, settings, 'TEST')
override = override_settings(TEST='override')
self.assertRaises(AttributeError, getattr, settings, 'TEST')
override.enable()
self.assertEqual('override', settings.TEST)
override.disable()
self.assertRaises(AttributeError, getattr, settings, 'TEST')
def test_class_decorator(self):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_class_decorator(self):
# SimpleTestCase can be decorated by override_settings, but not ut.TestCase
class SimpleTestCaseSubclass(SimpleTestCase):
pass
class UnittestTestCaseSubclass(unittest.TestCase):
pass
decorated = override_settings(TEST='override')(SimpleTestCaseSubclass)
self.assertIsInstance(decorated, type)
self.assertTrue(issubclass(decorated, SimpleTestCase))
with six.assertRaisesRegex(self, Exception,
"Only subclasses of Django SimpleTestCase*"):
decorated = override_settings(TEST='override')(UnittestTestCaseSubclass)
def test_signal_callback_context_manager(self):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_location_empty(self):
err = six.StringIO()
for root in ['', None]:
with override_settings(STATIC_ROOT=root):
with six.assertRaisesRegex(
self, ImproperlyConfigured,
'without having set the STATIC_ROOT setting to a filesystem path'):
call_command('collectstatic', interactive=False, verbosity=0, stderr=err)
def test_local_storage_detection_helper(self):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_allowed_paths(self):
acceptable_path = os.path.join(self.ssi_dir, "..", "first", "test.html")
with override_settings(ALLOWED_INCLUDE_ROOTS=(self.ssi_dir,)):
self.assertEqual(self.render_ssi(acceptable_path), 'First template\n')
def test_relative_include_exploit(self):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_relative_include_exploit(self):
"""
May not bypass ALLOWED_INCLUDE_ROOTS with relative paths
e.g. if ALLOWED_INCLUDE_ROOTS = ("/var/www",), it should not be
possible to do {% ssi "/var/www/../../etc/passwd" %}
"""
disallowed_paths = [
os.path.join(self.ssi_dir, "..", "ssi_include.html"),
os.path.join(self.ssi_dir, "..", "second", "test.html"),
]
with override_settings(ALLOWED_INCLUDE_ROOTS=(self.ssi_dir,)):
for path in disallowed_paths:
self.assertEqual(self.render_ssi(path), '')
3
Source : test_timezone.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_now(self):
with override_settings(USE_TZ=True):
self.assertTrue(timezone.is_aware(timezone.now()))
with override_settings(USE_TZ=False):
self.assertTrue(timezone.is_naive(timezone.now()))
def test_override(self):
3
Source : test_debug.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_template_loader_postmortem(self):
"""Tests for not existing file"""
template_name = "notfound.html"
with NamedTemporaryFile(prefix=template_name) as tempfile:
tempdir = os.path.dirname(tempfile.name)
template_path = os.path.join(tempdir, template_name)
with override_settings(TEMPLATE_DIRS=(tempdir,)):
response = self.client.get(reverse('raises_template_does_not_exist', kwargs={"path": template_name}))
self.assertContains(response, "%s (File does not exist)" % template_path, status_code=500, count=1)
@skipIf(sys.platform == "win32", "Python on Windows doesn't have working os.chmod() and os.access().")
3
Source : test_debug.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_template_loader_postmortem_notreadable(self):
"""Tests for not readable file"""
with NamedTemporaryFile() as tempfile:
template_name = tempfile.name
tempdir = os.path.dirname(tempfile.name)
template_path = os.path.join(tempdir, template_name)
os.chmod(template_path, 0o0222)
with override_settings(TEMPLATE_DIRS=(tempdir,)):
response = self.client.get(reverse('raises_template_does_not_exist', kwargs={"path": template_name}))
self.assertContains(response, "%s (File is not readable)" % template_path, status_code=500, count=1)
def test_template_loader_postmortem_notafile(self):
3
Source : test_debug.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_template_loader_postmortem_notafile(self):
"""Tests for not being a file"""
try:
template_path = mkdtemp()
template_name = os.path.basename(template_path)
tempdir = os.path.dirname(template_path)
with override_settings(TEMPLATE_DIRS=(tempdir,)):
response = self.client.get(reverse('raises_template_does_not_exist', kwargs={"path": template_name}))
self.assertContains(response, "%s (Not a file)" % template_path, status_code=500, count=1)
finally:
shutil.rmtree(template_path)
def test_no_template_source_loaders(self):
3
Source : test_imagefield.py
with BSD 3-Clause "New" or "Revised" License
from matthiask
with BSD 3-Clause "New" or "Revised" License
from matthiask
def test_no_validate_on_save(self):
"""Broken images are rejected early"""
with override_settings(IMAGEFIELD_VALIDATE_ON_SAVE=False):
m = Model(image="broken.png")
m._skip_generate_files = True
m.save() # Doesn't crash
def test_silent_failure(self):
3
Source : test_imagefield.py
with BSD 3-Clause "New" or "Revised" License
from matthiask
with BSD 3-Clause "New" or "Revised" License
from matthiask
def test_silent_failure(self):
Model.objects.create(image="python-logo.jpg")
Model.objects.update(image="broken.png") # DB-only update
m = Model.objects.get()
with self.assertRaises(Exception):
m.image.process("desktop")
with override_settings(IMAGEFIELD_SILENTFAILURE=True):
self.assertEqual(m.image.process("desktop"), "broken.png")
def test_cmyk_validation(self):
3
Source : test_imagefield.py
with BSD 3-Clause "New" or "Revised" License
from matthiask
with BSD 3-Clause "New" or "Revised" License
from matthiask
def test_bogus_without_formats(self):
with override_settings(IMAGEFIELD_FORMATS={"testapp.model.image": {}}):
m = Model(image="python-logo.tiff")
with self.assertRaises(Exception):
m.image.save("stuff.jpg", io.BytesIO(b"anything"), save=True)
with openimage("python-logo.tiff") as f:
m = Model()
m.image.save("stuff.png", ContentFile(f.read()), save=True)
def test_empty_image(self):
3
Source : test_contacts.py
with MIT License
from matthiask
with MIT License
from matthiask
def test_organization_detail(self):
"""The organization detail page contains a few additional headings
depending on the CONTROLLING feature"""
organization = factories.OrganizationFactory.create()
self.client.force_login(organization.primary_contact)
response = self.client.get(organization.urls["detail"])
self.assertContains(response, "Recent projects")
self.assertContains(response, "Recent invoices")
self.assertContains(response, "Recent offers")
with override_settings(FEATURES={FEATURES.CONTROLLING: F.NEVER}):
response = self.client.get(organization.urls["detail"])
self.assertContains(response, "Recent projects")
self.assertNotContains(response, "Recent invoices")
self.assertNotContains(response, "Recent offers")
def test_vcard_export(self):
3
Source : test_projects.py
with MIT License
from matthiask
with MIT License
from matthiask
def test_no_flat_rate(self):
"""Uses without CONTROLLING do not see the flat rate field"""
project = factories.ProjectFactory.create()
self.client.force_login(project.owned_by)
response = self.client.get(project.urls["update"])
self.assertContains(response, "id_flat_rate")
with override_settings(FEATURES={FEATURES.CONTROLLING: F.NEVER}):
response = self.client.get(project.urls["update"])
self.assertNotContains(response, "id_flat_rate")
def test_project_closing_reopening(self):
See More Examples