22👍
✅
The warning is coming from here:
https://github.com/django/django/blob/main/django/core/handlers/base.py
What you want to do is set the logging threshold of the ‘django.request’ module to something above WARNING (e.g. ERROR) at the beginning of the test, and then set it back afterward.
Try something like this:
import logging
#before tests
logger = logging.getLogger('django.request')
previous_level = logger.getEffectiveLevel()
logger.setLevel(logging.ERROR)
#after tests
logger.setLevel(previous_level)
22👍
I know some years passed by but for others looking for this question the following might be helpful.
Based on @jterrace solution you could easily implement a decorator function like this:
import logging
def prevent_request_warnings(original_function):
"""
If we need to test for 404s or 405s this decorator can prevent the
request class from throwing warnings.
"""
def new_function(*args, **kwargs):
# raise logging level to ERROR
logger = logging.getLogger('django.request')
previous_logging_level = logger.getEffectiveLevel()
logger.setLevel(logging.ERROR)
# trigger original function that would throw warning
original_function(*args, **kwargs)
# lower logging level back to previous
logger.setLevel(previous_logging_level)
return new_function
Using this you could write your code like this:
@prevent_request_warnings
def test_foo(self):
response = self.client.get('/foo/bar/')
self.assertEqual(response.status_code, 200)
response = self.client.get('/foo/bar2/')
self.assertEqual(response.status_code, 404)
- [Django]-How do you get PyPy, Django and PostgreSQL to work together?
- [Django]-Django allauth example [Errno 61] Connection refused
- [Django]-Unit Testing a Django Form with a FileField
8👍
A solution implementing @jterrace’s solution is to decrease the log level in the setUp and tearDown methods:
class NotFoundTests(TestCase):
def setUp(self) -> None:
"""Reduce the log level to avoid errors like 'not found'"""
logger = logging.getLogger("django.request")
self.previous_level = logger.getEffectiveLevel()
logger.setLevel(logging.ERROR)
def tearDown(self) -> None:
"""Reset the log level back to normal"""
logger = logging.getLogger("django.request")
logger.setLevel(self.previous_level)
Just copy/paste to the TestCase class with tests that check for pages that don’t get found.
- [Django]-Count number of records by date in Django
- [Django]-How to set another Inline title in Django Admin?
- [Django]-Replacing a Django image doesn't delete original
Source:stackexchange.com