test_logging.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import logging
  2. from django.template import Engine, Variable, VariableDoesNotExist
  3. from django.test import SimpleTestCase
  4. class VariableResolveLoggingTests(SimpleTestCase):
  5. loglevel = logging.DEBUG
  6. def test_log_on_variable_does_not_exist_silent(self):
  7. class TestObject:
  8. class SilentDoesNotExist(Exception):
  9. silent_variable_failure = True
  10. @property
  11. def template_name(self):
  12. return "template_name"
  13. @property
  14. def template(self):
  15. return Engine().from_string('')
  16. @property
  17. def article(self):
  18. raise TestObject.SilentDoesNotExist("Attribute does not exist.")
  19. def __iter__(self):
  20. return (attr for attr in dir(TestObject) if attr[:2] != "__")
  21. def __getitem__(self, item):
  22. return self.__dict__[item]
  23. with self.assertLogs('django.template', self.loglevel) as cm:
  24. Variable('article').resolve(TestObject())
  25. self.assertEqual(len(cm.records), 1)
  26. log_record = cm.records[0]
  27. self.assertEqual(
  28. log_record.getMessage(),
  29. "Exception while resolving variable 'article' in template 'template_name'."
  30. )
  31. self.assertIsNotNone(log_record.exc_info)
  32. raised_exception = log_record.exc_info[1]
  33. self.assertEqual(str(raised_exception), 'Attribute does not exist.')
  34. def test_log_on_variable_does_not_exist_not_silent(self):
  35. with self.assertLogs('django.template', self.loglevel) as cm:
  36. with self.assertRaises(VariableDoesNotExist):
  37. Variable('article.author').resolve({'article': {'section': 'News'}})
  38. self.assertEqual(len(cm.records), 1)
  39. log_record = cm.records[0]
  40. self.assertEqual(
  41. log_record.getMessage(),
  42. "Exception while resolving variable 'author' in template 'unknown'."
  43. )
  44. self.assertIsNotNone(log_record.exc_info)
  45. raised_exception = log_record.exc_info[1]
  46. self.assertEqual(
  47. str(raised_exception),
  48. "Failed lookup for key [author] in {'section': 'News'}"
  49. )
  50. def test_no_log_when_variable_exists(self):
  51. with self.assertNoLogs('django.template', self.loglevel):
  52. Variable('article.section').resolve({'article': {'section': 'News'}})