From ca370e56d5557b81c6ac5609488aa5e31416b018 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20P=C3=A9ters?= Date: Wed, 24 Feb 2016 16:47:31 +0100 Subject: [PATCH] ezt: allow easy access to array/dict elements (#10074) --- tests/test_ezt.py | 26 ++++++++++++++++++++++++++ wcs/qommon/ezt.py | 8 +++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/tests/test_ezt.py b/tests/test_ezt.py index d411b68..83ef3c2 100644 --- a/tests/test_ezt.py +++ b/tests/test_ezt.py @@ -90,3 +90,29 @@ def test_unmatched_end(): template.parse('

[if foo]Test[end]

') except UnmatchedEndError as e: assert e.column == 15 and e.line == 0 + +def test_array_index(): + template = Template() + template.parse('

[foo.0]

') + output = StringIO() + template.generate(output, {'foo': ['bar']}) + assert output.getvalue() == '

bar

' + + template = Template() + template.parse('

[foo.bar]

') + output = StringIO() + template.generate(output, {'foo': ['bar']}) + assert output.getvalue() == '

[foo.bar]

' + +def test_dict_index(): + template = Template() + template.parse('

[foo.a]

') + output = StringIO() + template.generate(output, {'foo': {'a': 'bar'}}) + assert output.getvalue() == '

bar

' + + template = Template() + template.parse('

[foo.b]

') + output = StringIO() + template.generate(output, {'foo': {'a': 'bar'}}) + assert output.getvalue() == '

[foo.b]

' diff --git a/wcs/qommon/ezt.py b/wcs/qommon/ezt.py index 396b283..8e6aedb 100644 --- a/wcs/qommon/ezt.py +++ b/wcs/qommon/ezt.py @@ -638,7 +638,13 @@ def _get_value((refname, start, rest), ctx): try: ob = getattr(ob, attr) except AttributeError: - raise UnknownReference(refname) + try: + ob = ob[attr] + except (TypeError, KeyError): + try: + ob = ob[int(attr)] + except (ValueError, TypeError): + raise UnknownReference(refname) # make sure we return a string instead of some various Python types if isinstance(ob, IntType) \ -- 2.7.0