From ee352ec21fdf753eff85e5d02631567d8c45a6d0 Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Tue, 24 May 2011 16:40:23 +0200 Subject: [PATCH] Added test for mappings. This fixes #35 --- CHANGES | 2 ++ jinja2/tests.py | 15 +++++++++++++++ jinja2/testsuite/tests.py | 10 ++++++++-- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/CHANGES b/CHANGES index 2cdedf4..9fdfba2 100644 --- a/CHANGES +++ b/CHANGES @@ -32,6 +32,8 @@ Version 2.6 - like sum and sort, join now also is able to join attributes of objects as string. - the internal eval context now has a reference to the environment. +- added a mapping test to see if an object is a dict or an object with + a similar interface. Version 2.5.5 ------------- diff --git a/jinja2/tests.py b/jinja2/tests.py index d257eca..50510b0 100644 --- a/jinja2/tests.py +++ b/jinja2/tests.py @@ -11,6 +11,12 @@ import re from jinja2.runtime import Undefined +try: + from collections import Mapping as MappingType +except ImportError: + import UserDict + MappingType = (UserDict.UserDict, UserDict.DictMixin, dict) + # nose, nothing here to test __test__ = False @@ -83,6 +89,14 @@ def test_string(value): return isinstance(value, basestring) +def test_mapping(value): + """Return true if the object is a mapping (dict etc.). + + .. versionadded:: 2.6 + """ + return isinstance(value, MappingType) + + def test_number(value): """Return true if the variable is a number.""" return isinstance(value, (int, long, float, complex)) @@ -137,6 +151,7 @@ TESTS = { 'lower': test_lower, 'upper': test_upper, 'string': test_string, + 'mapping': test_mapping, 'number': test_number, 'sequence': test_sequence, 'iterable': test_iterable, diff --git a/jinja2/testsuite/tests.py b/jinja2/testsuite/tests.py index cd5006f..3ece7a8 100644 --- a/jinja2/testsuite/tests.py +++ b/jinja2/testsuite/tests.py @@ -48,10 +48,16 @@ class TestsTestCase(JinjaTestCase): {{ range is callable }} {{ 42 is callable }} {{ range(5) is iterable }} + {{ {} is mapping }} + {{ mydict is mapping }} + {{ [] is mapping }} ''') - assert tmpl.render().split() == [ + class MyDict(dict): + pass + assert tmpl.render(mydict=MyDict()).split() == [ 'False', 'True', 'False', 'True', 'True', 'False', - 'True', 'True', 'True', 'True', 'False', 'True' + 'True', 'True', 'True', 'True', 'False', 'True', + 'True', 'True', 'False' ] def test_sequence(self): -- 2.26.2