Permalink
Browse files

Fixed #20404 -- Added a keys() method to ContextList.

It's useful to be able to list all the (flattened) keys of a
ContextList, to help you figure out why the variable that's supposed
to be there is not.

No .values() or .items() added as the definition for those aren't clear.

The patch is Chris Wilson's patch from pull request 1065 with some
modifications by committer.
  • Loading branch information...
1 parent 5090c7b commit fa7cb4ef3cc5f4c3514857bd25b43d31815eba94 @qris qris committed with akaariai May 13, 2013
Showing with 26 additions and 2 deletions.
  1. +10 −0 django/test/utils.py
  2. +16 −2 tests/test_client_regress/tests.py
View
@@ -60,6 +60,16 @@ def __contains__(self, key):
return False
return True
+ def keys(self):
+ """
+ Flattened keys of subcontexts.
+ """
+ keys = set()
+ for subcontext in self:
+ for dict in subcontext:
+ keys |= set(dict.keys())
@martsberger
martsberger Nov 12, 2015

Not every subcontext necessarily has a keys() method. The subcontext can be a RequestContext (django/template/context.py) which does not have a keys() method. Where necessary, you should flatten the subcontext before calling keys() on it.

+ return keys
+
def instrumented_test_render(self, context):
"""
@@ -6,9 +6,8 @@
import os
-from django.conf import settings
from django.core.urlresolvers import reverse
-from django.template import (TemplateDoesNotExist, TemplateSyntaxError,
+from django.template import (TemplateSyntaxError,
Context, Template, loader)
import django.template.context
from django.test import Client, TestCase
@@ -897,6 +896,21 @@ def test_inherited_context(self):
except KeyError as e:
self.assertEqual(e.args[0], 'does-not-exist')
+ def test_contextlist_keys(self):
+ c1 = Context()
+ c1.update({'hello': 'world', 'goodbye': 'john'})
+ c1.update({'hello': 'dolly', 'dolly': 'parton'})
+ c2 = Context()
+ c2.update({'goodbye': 'world', 'python': 'rocks'})
+ c2.update({'goodbye': 'dolly'})
+
+ l = ContextList([c1, c2])
+ # None, True and False are builtins of BaseContext, and present
+ # in every Context without needing to be added.
+ self.assertEqual(set(['None', 'True', 'False', 'hello', 'goodbye',
+ 'python', 'dolly']),
+ l.keys())
+
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

0 comments on commit fa7cb4e

Please sign in to comment.