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