diff --git a/django/test/utils.py b/django/test/utils.py index b846fa2655..b24f2e8c80 100644 --- a/django/test/utils.py +++ b/django/test/utils.py @@ -74,6 +74,12 @@ class ContextList(list): else: return super(ContextList, self).__getitem__(key) + def get(self, key, default=None): + try: + return self.__getitem__(key) + except KeyError: + return default + def __contains__(self, key): try: self[key] diff --git a/tests/test_client_regress/tests.py b/tests/test_client_regress/tests.py index 2c1a9b346a..1e30017d5a 100644 --- a/tests/test_client_regress/tests.py +++ b/tests/test_client_regress/tests.py @@ -961,6 +961,15 @@ class ContextTests(TestDataMixin, TestCase): # in every Context without needing to be added. self.assertEqual({'None', 'True', 'False', 'hello', 'goodbye', 'python', 'dolly'}, k.keys()) + def test_contextlist_get(self): + c1 = Context({'hello': 'world', 'goodbye': 'john'}) + c2 = Context({'goodbye': 'world', 'python': 'rocks'}) + k = ContextList([c1, c2]) + self.assertEqual(k.get('hello'), 'world') + self.assertEqual(k.get('goodbye'), 'john') + self.assertEqual(k.get('python'), 'rocks') + self.assertEqual(k.get('nonexistent', 'default'), 'default') + def test_15368(self): # Need to insert a context processor that assumes certain things about # the request instance. This triggers a bug caused by some ways of