# HG changeset patch # User hodgestar # Date 1314994821 0 # Node ID 0f9fe59dfa00a9c017823d3a72d983bdfac24032 # Parent d1edb246cc6186fa8a8a615c6c82432353ea59a5 Add .copy() function to Context objects. Fixes #249. diff --git a/genshi/template/base.py b/genshi/template/base.py --- a/genshi/template/base.py +++ b/genshi/template/base.py @@ -247,6 +247,18 @@ def pop(self): """Pop the top-most scope from the stack.""" + def copy(self): + """Create a copy of this Context object.""" + # required to make f_locals a dict-like object + # See http://genshi.edgewall.org/ticket/249 for + # example use case in Twisted tracebacks + ctxt = Context() + ctxt.frames.pop() # pop empty dummy context + ctxt.frames.extend(self.frames) + ctxt._match_templates.extend(self._match_templates) + ctxt._choice_stack.extend(self._choice_stack) + return ctxt + def _apply_directives(stream, directives, ctxt, vars): """Apply the given directives to the stream. diff --git a/genshi/template/tests/base.py b/genshi/template/tests/base.py --- a/genshi/template/tests/base.py +++ b/genshi/template/tests/base.py @@ -14,11 +14,28 @@ import doctest import unittest -from genshi.template.base import Template +from genshi.template.base import Template, Context + + +class ContextTestCase(unittest.TestCase): + def test_copy(self): + # create a non-trivial context with some dummy + # frames, match templates and py:choice stacks. + orig_ctxt = Context(a=5, b=6) + orig_ctxt.push({'c': 7}) + orig_ctxt._match_templates.append(object()) + orig_ctxt._choice_stack.append(object()) + ctxt = orig_ctxt.copy() + self.assertNotEqual(id(orig_ctxt), id(ctxt)) + self.assertEqual(repr(orig_ctxt), repr(ctxt)) + self.assertEqual(orig_ctxt._match_templates, ctxt._match_templates) + self.assertEqual(orig_ctxt._choice_stack, ctxt._choice_stack) + def suite(): suite = unittest.TestSuite() suite.addTest(doctest.DocTestSuite(Template.__module__)) + suite.addTest(unittest.makeSuite(ContextTestCase, 'test')) return suite if __name__ == '__main__':