Refs #32508 -- Raised Type/ValueError instead of using "assert" in django.core.

This commit is contained in:
Daniyal 2021-03-16 21:11:27 +05:30 committed by Mariusz Felisiak
parent 37044817f9
commit 474cc420bf
8 changed files with 76 additions and 11 deletions

View File

@ -9,7 +9,8 @@ CRITICAL = 50
class CheckMessage: class CheckMessage:
def __init__(self, level, msg, hint=None, obj=None, id=None): def __init__(self, level, msg, hint=None, obj=None, id=None):
assert isinstance(level, int), "The first argument should be level." if not isinstance(level, int):
raise TypeError('The first argument should be level.')
self.level = level self.level = level
self.msg = msg self.msg = msg
self.hint = hint self.hint = hint

View File

@ -75,9 +75,12 @@ class CheckRegistry:
for check in checks: for check in checks:
new_errors = check(app_configs=app_configs, databases=databases) new_errors = check(app_configs=app_configs, databases=databases)
assert is_iterable(new_errors), ( if not is_iterable(new_errors):
"The function %r did not return a list. All functions registered " raise TypeError(
"with the checks registry must return a list." % check) 'The function %r did not return a list. All functions '
'registered with the checks registry must return a list.'
% check,
)
errors.extend(new_errors) errors.extend(new_errors)
return errors return errors

View File

@ -294,7 +294,8 @@ class FileSystemStorage(Storage):
return str(name).replace('\\', '/') return str(name).replace('\\', '/')
def delete(self, name): def delete(self, name):
assert name, "The name argument is not allowed to be empty." if not name:
raise ValueError('The name must be given to delete().')
name = self.path(name) name = self.path(name)
# If the file or directory exists, delete it from the filesystem. # If the file or directory exists, delete it from the filesystem.
try: try:

View File

@ -296,11 +296,15 @@ class EmailMessage:
mimetype to DEFAULT_ATTACHMENT_MIME_TYPE and don't decode the content. mimetype to DEFAULT_ATTACHMENT_MIME_TYPE and don't decode the content.
""" """
if isinstance(filename, MIMEBase): if isinstance(filename, MIMEBase):
assert content is None if content is not None or mimetype is not None:
assert mimetype is None raise ValueError(
'content and mimetype must not be given when a MIMEBase '
'instance is provided.'
)
self.attachments.append(filename) self.attachments.append(filename)
elif content is None:
raise ValueError('content must be provided.')
else: else:
assert content is not None
mimetype = mimetype or mimetypes.guess_type(filename)[0] or DEFAULT_ATTACHMENT_MIME_TYPE mimetype = mimetype or mimetypes.guess_type(filename)[0] or DEFAULT_ATTACHMENT_MIME_TYPE
basetype, subtype = mimetype.split('/', 1) basetype, subtype = mimetype.split('/', 1)
@ -428,8 +432,8 @@ class EmailMultiAlternatives(EmailMessage):
def attach_alternative(self, content, mimetype): def attach_alternative(self, content, mimetype):
"""Attach an alternative content representation.""" """Attach an alternative content representation."""
assert content is not None if content is None or mimetype is None:
assert mimetype is not None raise ValueError('Both content and mimetype must be provided.')
self.alternatives.append((content, mimetype)) self.alternatives.append((content, mimetype))
def _create_message(self, msg): def _create_message(self, msg):

View File

@ -355,6 +355,13 @@ Miscellaneous
to ``reorder_tests()``. It now accepts an iterable of tests rather than a to ``reorder_tests()``. It now accepts an iterable of tests rather than a
test suite, and returns an iterator of tests. test suite, and returns an iterator of tests.
* Calling ``FileSystemStorage.delete()`` with an empty ``name`` now raises
``ValueError`` instead of ``AssertionError``.
* Calling ``EmailMultiAlternatives.attach_alternative()`` or
``EmailMessage.attach()`` with an invalid ``content`` or ``mimetype``
arguments now raise ``ValueError`` instead of ``AssertionError``.
.. _deprecated-features-4.0: .. _deprecated-features-4.0:
Features deprecated in 4.0 Features deprecated in 4.0

View File

@ -4,6 +4,7 @@ from io import StringIO
from django.apps import apps from django.apps import apps
from django.core import checks from django.core import checks
from django.core.checks import Error, Warning from django.core.checks import Error, Warning
from django.core.checks.messages import CheckMessage
from django.core.checks.registry import CheckRegistry from django.core.checks.registry import CheckRegistry
from django.core.management import call_command from django.core.management import call_command
from django.core.management.base import CommandError from django.core.management.base import CommandError
@ -74,6 +75,20 @@ class SystemCheckFrameworkTests(SimpleTestCase):
def no_kwargs(app_configs, databases): def no_kwargs(app_configs, databases):
pass pass
def test_register_run_checks_non_iterable(self):
registry = CheckRegistry()
@registry.register
def return_non_iterable(**kwargs):
return Error('Message')
msg = (
'The function %r did not return a list. All functions registered '
'with the checks registry must return a list.' % return_non_iterable
)
with self.assertRaisesMessage(TypeError, msg):
registry.run_checks()
class MessageTests(SimpleTestCase): class MessageTests(SimpleTestCase):
@ -132,6 +147,11 @@ class MessageTests(SimpleTestCase):
e = Error("Error", obj=DummyObj()) e = Error("Error", obj=DummyObj())
self.assertNotEqual(e, 'a string') self.assertNotEqual(e, 'a string')
def test_invalid_level(self):
msg = 'The first argument should be level.'
with self.assertRaisesMessage(TypeError, msg):
CheckMessage('ERROR', 'Message')
def simple_system_check(**kwargs): def simple_system_check(**kwargs):
simple_system_check.kwargs = kwargs simple_system_check.kwargs = kwargs

View File

@ -501,7 +501,10 @@ class FileStorageTests(SimpleTestCase):
Calling delete with an empty name should not try to remove the base Calling delete with an empty name should not try to remove the base
storage directory, but fail loudly (#20660). storage directory, but fail loudly (#20660).
""" """
with self.assertRaises(AssertionError): msg = 'The name must be given to delete().'
with self.assertRaisesMessage(ValueError, msg):
self.storage.delete(None)
with self.assertRaisesMessage(ValueError, msg):
self.storage.delete('') self.storage.delete('')
def test_delete_deletes_directories(self): def test_delete_deletes_directories(self):

View File

@ -529,6 +529,24 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
self.assertEqual(content, b'\xff') self.assertEqual(content, b'\xff')
self.assertEqual(mimetype, 'application/octet-stream') self.assertEqual(mimetype, 'application/octet-stream')
def test_attach_mimetext_content_mimetype(self):
email_msg = EmailMessage()
txt = MIMEText('content')
msg = (
'content and mimetype must not be given when a MIMEBase instance '
'is provided.'
)
with self.assertRaisesMessage(ValueError, msg):
email_msg.attach(txt, content='content')
with self.assertRaisesMessage(ValueError, msg):
email_msg.attach(txt, mimetype='text/plain')
def test_attach_content_none(self):
email_msg = EmailMessage()
msg = 'content must be provided.'
with self.assertRaisesMessage(ValueError, msg):
email_msg.attach('file.txt', mimetype="application/pdf")
def test_dummy_backend(self): def test_dummy_backend(self):
""" """
Make sure that dummy backends returns correct number of sent messages Make sure that dummy backends returns correct number of sent messages
@ -835,6 +853,14 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
with self.assertRaisesMessage(ValueError, msg): with self.assertRaisesMessage(ValueError, msg):
sanitize_address(email_address, encoding='utf-8') sanitize_address(email_address, encoding='utf-8')
def test_email_multi_alternatives_content_mimetype_none(self):
email_msg = EmailMultiAlternatives()
msg = 'Both content and mimetype must be provided.'
with self.assertRaisesMessage(ValueError, msg):
email_msg.attach_alternative(None, 'text/html')
with self.assertRaisesMessage(ValueError, msg):
email_msg.attach_alternative('<p>content</p>', None)
@requires_tz_support @requires_tz_support
class MailTimeZoneTests(SimpleTestCase): class MailTimeZoneTests(SimpleTestCase):