# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for the flattening portion of L{twisted.web.template}, implemented in L{twisted.web._flatten}. """ import sys import traceback from xml.etree.cElementTree import XML from collections import OrderedDict from zope.interface import implementer from twisted.python.compat import _PY35PLUS from twisted.trial.unittest import TestCase from twisted.test.testutils import XMLAssertionMixin from twisted.internet.defer import passthru, succeed, gatherResults from twisted.web.iweb import IRenderable from twisted.web.error import UnfilledSlot, UnsupportedType, FlattenerError from twisted.web.template import tags, Tag, Comment, CDATA, CharRef, slot from twisted.web.template import Element, renderer, TagLoader, flattenString from twisted.web.test._util import FlattenTestCase class SerializationTests(FlattenTestCase, XMLAssertionMixin): """ Tests for flattening various things. """ def test_nestedTags(self): """ Test that nested tags flatten correctly. """ return self.assertFlattensTo( tags.html(tags.body('42'), hi='there'), b'
42') def test_serializeString(self): """ Test that strings will be flattened and escaped correctly. """ return gatherResults([ self.assertFlattensTo('one', b'one'), self.assertFlattensTo('\xe2\x98\x83
'), self.assertFlattensTo(Comment(snowman), b''), self.assertFlattensTo(CDATA(snowman), b''), self.assertFlatteningRaises( Tag(snowman), UnicodeEncodeError), self.assertFlatteningRaises( Tag('p', attributes={snowman: ''}), UnicodeEncodeError), ]) def test_serializeCharRef(self): """ A character reference is flattened to a string using the I{NNNN;} syntax. """ ref = CharRef(ord(u"\N{SNOWMAN}")) return self.assertFlattensTo(ref, b"☃") def test_serializeDeferred(self): """ Test that a deferred is substituted with the current value in the callback chain when flattened. """ return self.assertFlattensTo(succeed('two'), b'two') def test_serializeSameDeferredTwice(self): """ Test that the same deferred can be flattened twice. """ d = succeed('three') return gatherResults([ self.assertFlattensTo(d, b'three'), self.assertFlattensTo(d, b'three'), ]) def test_serializeCoroutine(self): """ Test that a coroutine returning a value is substituted with the that value when flattened. """ from textwrap import dedent namespace = {} exec(dedent( """ async def coro(x): return x """ ), namespace) coro = namespace["coro"] return self.assertFlattensTo(coro('four'), b'four') if not _PY35PLUS: test_serializeCoroutine.skip = ( "coroutines not available before Python 3.5" ) def test_serializeCoroutineWithAwait(self): """ Test that a coroutine returning an awaited deferred value is substituted with that value when flattened. """ from textwrap import dedent namespace = dict(succeed=succeed) exec(dedent( """ async def coro(x): return await succeed(x) """ ), namespace) coro = namespace["coro"] return self.assertFlattensTo(coro('four'), b'four') if not _PY35PLUS: test_serializeCoroutineWithAwait.skip = ( "coroutines not available before Python 3.5" ) def test_serializeIRenderable(self): """ Test that flattening respects all of the IRenderable interface. """ @implementer(IRenderable) class FakeElement(object): def render(ign,ored): return tags.p( 'hello, ', tags.transparent(render='test'), ' - ', tags.transparent(render='test')) def lookupRenderMethod(ign, name): self.assertEqual(name, 'test') return lambda ign, node: node('world') return gatherResults([ self.assertFlattensTo(FakeElement(), b'hello, world - world
'), ]) def test_serializeSlots(self): """ Test that flattening a slot will use the slot value from the tag. """ t1 = tags.p(slot('test')) t2 = t1.clone() t2.fillSlots(test='hello, world') return gatherResults([ self.assertFlatteningRaises(t1, UnfilledSlot), self.assertFlattensTo(t2, b'hello, world
'), ]) def test_serializeDeferredSlots(self): """ Test that a slot with a deferred as its value will be flattened using the value from the deferred. """ t = tags.p(slot('test')) t.fillSlots(test=succeed(tags.em('four>'))) return self.assertFlattensTo(t, b'four>
') def test_unknownTypeRaises(self): """ Test that flattening an unknown type of thing raises an exception. """ return self.assertFlatteningRaises(None, UnsupportedType) # Use the co_filename mechanism (instead of the __file__ mechanism) because # it is the mechanism traceback formatting uses. The two do not necessarily # agree with each other. This requires a code object compiled in this file. # The easiest way to get a code object is with a new function. I'll use a # lambda to avoid adding anything else to this namespace. The result will # be a string which agrees with the one the traceback module will put into a # traceback for frames associated with functions defined in this file. HERE = (lambda: None).__code__.co_filename class FlattenerErrorTests(TestCase): """ Tests for L{FlattenerError}. """ def test_renderable(self): """ If a L{FlattenerError} is created with an L{IRenderable} provider root, the repr of that object is included in the string representation of the exception. """ @implementer(IRenderable) class Renderable(object): def __repr__(self): return "renderable repr" self.assertEqual( str(FlattenerError( RuntimeError("reason"), [Renderable()], [])), "Exception while flattening:\n" " renderable repr\n" "RuntimeError: reason\n") def test_tag(self): """ If a L{FlattenerError} is created with a L{Tag} instance with source location information, the source location is included in the string representation of the exception. """ tag = Tag( 'div', filename='/foo/filename.xhtml', lineNumber=17, columnNumber=12) self.assertEqual( str(FlattenerError(RuntimeError("reason"), [tag], [])), "Exception while flattening:\n" " File \"/foo/filename.xhtml\", line 17, column 12, in \"div\"\n" "RuntimeError: reason\n") def test_tagWithoutLocation(self): """ If a L{FlattenerError} is created with a L{Tag} instance without source location information, only the tagName is included in the string representation of the exception. """ self.assertEqual( str(FlattenerError(RuntimeError("reason"), [Tag('span')], [])), "Exception while flattening:\n" " Tag \n" "RuntimeError: reason\n") def test_traceback(self): """ If a L{FlattenerError} is created with traceback frames, they are included in the string representation of the exception. """ # Try to be realistic in creating the data passed in for the traceback # frames. def f(): g() def g(): raise RuntimeError("reason") try: f() except RuntimeError as e: # Get the traceback, minus the info for *this* frame tbinfo = traceback.extract_tb(sys.exc_info()[2])[1:] exc = e else: self.fail("f() must raise RuntimeError") self.assertEqual( str(FlattenerError(exc, [], tbinfo)), "Exception while flattening:\n" " File \"%s\", line %d, in f\n" " g()\n" " File \"%s\", line %d, in g\n" " raise RuntimeError(\"reason\")\n" "RuntimeError: reason\n" % ( HERE, f.__code__.co_firstlineno + 1, HERE, g.__code__.co_firstlineno + 1))