From d97bf2e9c8971764690caaf81a0914bc368d6b02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20Wywia=C5=82?= Date: Sat, 15 Feb 2014 13:45:52 +0100 Subject: [PATCH] Fixed #21765 -- Added support for comparing Context instances --- django/template/context.py | 10 ++++++++++ tests/template_tests/test_context.py | 5 +++++ tests/template_tests/tests.py | 13 +++++++++++++ 3 files changed, 28 insertions(+) diff --git a/django/template/context.py b/django/template/context.py index 0f624ff8a6..9982b85f6d 100644 --- a/django/template/context.py +++ b/django/template/context.py @@ -97,6 +97,16 @@ class BaseContext(object): new_context._reset_dicts(values) return new_context + def __eq__(self, other): + """ + Compares two contexts by comparing theirs 'dicts' attributes. + """ + if isinstance(other, BaseContext): + return self.dicts[-1] == other.dicts[-1] + + # if it's not comparable return false + return False + class Context(BaseContext): "A stack container for variable context" diff --git a/tests/template_tests/test_context.py b/tests/template_tests/test_context.py index bbf6918103..f810feda74 100644 --- a/tests/template_tests/test_context.py +++ b/tests/template_tests/test_context.py @@ -49,3 +49,8 @@ class ContextTests(TestCase): with self.assertRaises(KeyError): test_context['fruit'] self.assertIsNone(test_context.get('fruit')) + + def test_context_comparable(self): + test_data = {'x': 'y', 'v': 'z', 'd': {'o': object, 'a': 'b'}} + + self.assertEquals(Context(test_data), Context(test_data)) diff --git a/tests/template_tests/tests.py b/tests/template_tests/tests.py index 9cd29f8fa5..f10d9ea889 100644 --- a/tests/template_tests/tests.py +++ b/tests/template_tests/tests.py @@ -1928,6 +1928,19 @@ class RequestContextTests(unittest.TestCase): # [builtins, supplied context, context processor] self.assertEqual(len(ctx.dicts), 3) + @override_settings(TEMPLATE_CONTEXT_PROCESSORS=()) + def test_context_comparable(self): + test_data = {'x': 'y', 'v': 'z', 'd': {'o': object, 'a': 'b'}} + + # test comparing RequestContext to prevent problems if somebody + # adds __eq__ in the future + request = RequestFactory().get('/') + + self.assertEquals( + RequestContext(request, dict_=test_data), + RequestContext(request, dict_=test_data) + ) + class SSITests(TestCase): def setUp(self):