ϪffdZddlZddlZddlZddlmZddlmZddlm Z ddl m Z m Z m Z mZmZmZmZddlmZddlmZdd lmZmZdd lmZmZmZmZmZdd lm Z dd l!m"Z"dd l#m$Z$ddl%m&Z&ddl'm(Z(m)Z)m*Z*ddl+m,Z,m-Z-m.Z.ddl/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;ddlGdde$Z?djjZBGdde$ZCy)zf Tests for the flattening portion of L{twisted.web.template}, implemented in L{twisted.web._flatten}. N) OrderedDictdedent) FunctionType)CallableDictListNoReturnOptionalTuplecast)XML) implementer) assert_thatequal_to)CancelledErrorDeferred gatherResultspassthrusucceed)Failure)XMLAssertionMixin)SynchronousTestCase) BUFFER_SIZE)FlattenerError UnfilledSlotUnsupportedType) IRenderableIRequestITemplateLoader) CDATACharRefCommentElement FlattenableTag TagLoaderflatten flattenStringrendererslottags)FlattenTestCasecHeZdZdZd$dZd$dZd$dZd$dZd$dZd e e ge fd e e ge fddfd Z d$d Zd$d Zd$dZd$dZd$dZd$dZd e e ge fddfdZd$dZd$dZd$dZd$dZdeeefdZd$dZd$dZd$dZd$dZ d$dZ!d$dZ"d$dZ#d$dZ$d$d Z%d$d!Z&d$d"Z'd$d#Z(y)%SerializationTestsz. Tests for flattening various things. returnNcx|jtjtjdddy)z: Test that nested tags flatten correctly. 42there)his'42N)assertFlattensImmediatelyr,htmlbodyselfs ?/usr/lib/python3/dist-packages/twisted/web/test/test_flatten.pytest_nestedTagsz"SerializationTests.test_nestedTags9s+ && IIdiio' 2 6 cP|jddf|jddfy)zL Test that strings will be flattened and escaped correctly. onesonez 123s<abc&&>123N)r5r8s r:test_serializeStringz'SerializationTests.test_serializeStringBs+ &&uf56 &&|5PQRr<cL|jtjdy)zP The serialized form of a self-closing tag is C{''}. sNr5r,imgr8s r:test_serializeSelfClosingTagsz0SerializationTests.test_serializeSelfClosingTagsIs &&txxz:>r<cP|jtjddy)zV The serialized form of attribute I{a} with value I{b} is C{'a="b"'}. foosrcsNrAr8s r:test_serializeAttributez*SerializationTests.test_serializeAttributeOs &&txxE':N)r,rBr attributesr5r9tags r:!test_serializedMultipleAttributesz4SerializationTests.test_serializedMultipleAttributesUs1 hhj$no%FG &&s,KLr<wrapDatawrapTagc h|j|tj|ddy)a Common implementation of L{test_serializedAttributeWithSanitization} and L{test_serializedDeferredAttributeWithSanitization}, L{test_serializedAttributeWithTransparentTag}. @param wrapData: A 1-argument callable that wraps around the attribute's value so other tests can customize it. @param wrapTag: A 1-argument callable that wraps around the outer tag so other tests can customize it. <>&"rFs!NrA)r9rPrQs r:checkAttributeSanitizationz-SerializationTests.checkAttributeSanitization^s+ && DHH&!12 3 0 r<c8|jtty)z Attribute values containing C{"<"}, C{">"}, C{"&"}, or C{'"'} have C{"<"}, C{">"}, C{"&"}, or C{"""} substituted for those bytes in the serialized output. N)rTrr8s r:(test_serializedAttributeWithSanitizationz;SerializationTests.test_serializedAttributeWithSanitizationss ''(;r<c8|jtty)z Like L{test_serializedAttributeWithSanitization}, but when the contents of the attribute are in a L{Deferred }. N)rTrrr8s r:0test_serializedDeferredAttributeWithSanitizationzCSerializationTests.test_serializedDeferredAttributeWithSanitization{s '':r<cvgdtdtffd }dtdtffd }|j||y)zS Like L{test_serializedAttributeWithSanitization} but with a slot. valuer0c<j|tdS)Nstuff)appendr+rZtosss r: insertSlotzWSerializationTests.test_serializedAttributeWithSlotWithSanitization..insertSlots KK = r<rNcD|jjS)N)r\) fillSlotspop)rNr_s r:fillSlotzUSerializationTests.test_serializedAttributeWithSlotWithSanitization..fillSlots==txxz=2 2r<N)strr%r&rT)r9r`rdr_s @r:0test_serializedAttributeWithSlotWithSanitizationzCSerializationTests.test_serializedAttributeWithSlotWithSanitizationsB !c !k ! 3# 3# 3 '' H=r<cL|jtjty)z Attribute values which are supplied via the value of a C{t:transparent} tag have the same substitution rules to them as values supplied directly. N)rTr, transparentrr8s r:*test_serializedAttributeWithTransparentTagz=SerializationTests.test_serializedAttributeWithTransparentTags ''(8(8(Cr<cGddtgdtdtffd }dtdtffd }|j ||y) z Like L{test_serializedAttributeWithTransparentTag}, but when the attribute is rendered by a renderer on an element. cVeZdZdedeeddffd Zedeede de fdZ xZ S) _SerializationTests.test_serializedAttributeWithTransparentTagWithRenderer..WithRendererrZloaderr0Nc2||_t| |yN)rZsuper__init__)r9rZrm __class__s r:rqzhSerializationTests.test_serializedAttributeWithTransparentTagWithRenderer..WithRenderer.__init__s"  (r<requestrNc|jSrorZ)r9rsrNs r:r\zeSerializationTests.test_serializedAttributeWithTransparentTagWithRenderer..WithRenderer.stuffs zz!r<) __name__ __module__ __qualname__rer r rqr*rr&r%r\ __classcell__)rrs@r: WithRendererrlsQ )c )8O3L )QU ) "Xh%7 "c "k " "r<rzrZr0cRj|tjdS)Nr\render)r]r,rhr^s r:insertRendererzaSerializationTests.test_serializedAttributeWithTransparentTagWithRenderer..insertRenderers KK ##73 3r<rNcDjt|Sro)rcr')rNrzr_s r:r}zYSerializationTests.test_serializedAttributeWithTransparentTagWithRenderer..renders IcN; ;r<N)r$rer%r&rT)r9r~r}rzr_s @@r:6test_serializedAttributeWithTransparentTagWithRendererzISerializationTests.test_serializedAttributeWithTransparentTagWithRenderersN  "7 " 4# 4+ 4 < <  < ''?r<chttGdd}|j|ty)z Like L{test_serializedAttributeWithTransparentTag}, but when the attribute is a provider of L{IRenderable} rather than a transparent tag. cVeZdZdeddfdZdeedefdZdede eee geffdZ y) LSerializationTests.test_serializedAttributeWithRenderable..ArbitraryrZr0Nc||_yroru)r9rZs r:rqzUSerializationTests.test_serializedAttributeWithRenderable..Arbitrary.__init__s " r<rsc|jSroru)r9rss r:r}zSSerializationTests.test_serializedAttributeWithRenderable..Arbitrary.renders zz!r<rJctd)NzUnexpected call)NotImplementedErrorr9rJs r:lookupRenderMethodz_SerializationTests.test_serializedAttributeWithRenderable..Arbitrary.lookupRenderMethods**;<s<>&"rGN)r,arBr5assertXMLEqualrattrib)r9rQinnerTagouterTagouterinners r:checkTagAttributeSerializationz1SerializationTests.checkTagAttributeSerializationsp66&>88 12..  O ..x9QR CJ--e4e}. N)rrr8s r:'test_serializedAttributeWithDeferredTagz:SerializationTests.test_serializedAttributeWithDeferredTags ++G4r<c|jtjtjdd}|j t |j ddy)z Similar to L{test_serializedAttributeWithTag}, but for the additional complexity where the tag which is the attribute value itself has an attribute value which contains bytes which require substitution. rS)hrefrFsVrGs"N)r5r,rBrrrr)r9 flatteneds r:,test_serializedAttributeWithTagWithAttributez?SerializationTests.test_serializedAttributeWithTagWithAttributesS 22 HHV, -     N ! !% (*O r<c:|jtddy)zI Test that comments are correctly flattened and escaped. foo barsN)r5r#r8s r:test_serializeCommentz(SerializationTests.test_serializeComments &&wy'9;LMr<cdtddffd }g}dD]9}tdt|}|j||j |;t |S)a- The data in a L{Comment} is escaped and mangled in the flattened output so that the result can be safely included in an HTML document. Test that C{>} is escaped when the sequence C{-->} is encountered within a comment, and that comments do not end with C{-}. cr0Ncdj|jd|dj|jd|djt|dk\|d|dd}d |vrj d |nj d ||rj |d d yy) Nsz% does not end with the comment suffixz# is too short to be a legal commentsfoo>-) assertTrue startswithendswithlenassertIn assertNotInassertNotEqual)rcontentr9s r: verifyCommentz>SerializationTests.test_commentEscaping..verifyComments OO W%%>?  OO 6"%<=  OOCFaKA50S)T U"gG  dG,  w/##GBK6r<)z foo > barz abracadabra-z not-->magic)bytesr)r# addCallbackr]r)r9rresultsrds` r:test_commentEscapingz'SerializationTests.test_commentEscaping se 7U 7t 7(  A dGAJ/A MM- ( NN1  W%%r<cr|jtddf|jtddy)zE Test that CDATA is correctly flattened and escaped. rsz foo ]]> bars# bar]]>N)r5r!r8s r:test_serializeCDATAz&SerializationTests.test_serializeCDATA4s6 &&uY'79OPQ && - "H r<cfd}|j|d|jtj|d|jt|d|jt |d|j t |t|j t d|dity ) z Test that unicode is encoded correctly in the appropriate places, and raises an error when it occurs in inappropriate place. ☃s☃s

s spr)rLN)r5r,rr#r!assertFlatteningRaisesr&UnicodeEncodeError)r9snowmans r:test_serializeUnicodez(SerializationTests.test_serializeUnicode=s   &&w@ &&tvvg8NO &&ww'79OP &&uW~7RS ##CL2DE ## " .0B r<cPttd}|j|dy)ze A character reference is flattened to a string using the I{&#NNNN;} syntax. rs☃N)r"ordr5)r9refs r:test_serializeCharRefz(SerializationTests.test_serializeCharRefLs# c-() &&sJ7r<c:|jtddy)zz Test that a deferred is substituted with the current value in the callback chain when flattened. twostwoN)r5rr8s r:test_serializeDeferredz)SerializationTests.test_serializeDeferredTs &&wu~v>r<cbtd}|j|d|j|dy)zE Test that the same deferred can be flattened twice. threesthreeN)rr5)r9rs r:test_serializeSameDeferredTwicez2SerializationTests.test_serializeSameDeferredTwice[s. G  &&q(3 &&q(3r<crddlm}i}t|d||d}|j|ddy)zt Test that a coroutine returning a value is substituted with the that value when flattened. rrzE async def coro(x): return x corofourfourN)textwraprexecr5r9r namespacers r:test_serializeCoroutinez*SerializationTests.test_serializeCoroutinecsF $-/       &&tF|W=r<cddlm}tt}t |d||d}|j |ddy) z Test that a coroutine returning an awaited deferred value is substituted with that value when flattened. rrrzT async def coro(x): return await succeed(x) rrrN)rrdictrrr5rs r: test_serializeCoroutineWithAwaitz3SerializationTests.test_serializeCoroutineWithAwaitxsK $)       &&tF|W=r<cpttGfdd}j|dy)zQ Test that flattening respects all of the IRenderable interface. cFeZdZdedefdZdedeee ege fffd Z y)ASerializationTests.test_serializeIRenderable..FakeElementoredr0ctjdtjddtjdS)Nzhello, testr|z - )r,rrh)ignrs r:r}zHSerializationTests.test_serializeIRenderable..FakeElement.renders5vv$$F3$$F3 r<rJc.j|ddS)Nrc|dS)Nworldr)rnodes r:zfSerializationTests.test_serializeIRenderable..FakeElement.lookupRenderMethod..s gr<) assertEqual)rrJr9s r:rzTSerializationTests.test_serializeIRenderable..FakeElement.lookupRenderMethods  v.66r<N) rvrwrxobjectr&r}rerr rr%rr8sr: FakeElementrs? & S  7 78H-s3[@A 7r<rs

hello, world - world

N)rrr5)r9rs` r:test_serializeIRenderablez,SerializationTests.test_serializeIRenderables6 [ ! 7 7 " 7 &&{}6TUr<cX|jtjdty)z Test that flattening a tag with a C{render} attribute when no render factory is available in the context raises an exception. rr|N)rr,rh ValueErrorr8s r:"test_serializeMissingRenderFactoryz5SerializationTests.test_serializeMissingRenderFactorys ##D$4$4F$CZPr<ctjtd}|j}|j d|j |t |j|dy)zS Test that flattening a slot will use the slot value from the tag. rz hello, worldrs

hello, world

N)r,rr+clonerbrrr5)r9t1t2s r:test_serializeSlotsz&SerializationTests.test_serializeSlotssPVVDL ! XXZ . ) ##B 5 &&r+ABr<ctjtd}|jt tj d|j |dy)z| Test that a slot with a deferred as its value will be flattened using the value from the deferred. rzfour>rs

four>

N)r,rr+rbremr5)r9ts r:test_serializeDeferredSlotsz.SerializationTests.test_serializeDeferredSlotssC FF4<  !12 3 &&q*EFr<c0|jdty)zT Test that flattening an unknown type of thing raises an exception. N)rrr8s r:test_unknownTypeRaisesz)SerializationTests.test_unknownTypeRaisess ##D/:r<r0N))rvrwrx__doc__r;r?rCrHrOrrer%r&rTrVrXrfrirrrrrrrrr rrrrrrrrrrrrrrrr<r:r/r/4s S? R M C5+-. 3%,-    *<; >D@4=,={ 23= =465 $N '&htE{&;'&R   8?4>*>*V.QCG;r<r/cfeZdZdZd dZd dZdeegee eege fffddfdZ d dZ d d Z y) FlattenChunkingTestszi Tests for the way pieces of the result are chunked together in calls to the write function. r0Ncg}|jtdgd|jt|t dgy)z If the entire value to be flattened is available synchronously and fits into the buffer it is all passed to a single call to the write function. N)123s123)successResultOfr(r]rr)r9outputs r:test_oneSmallChunkz'FlattenChunkingTests.test_oneSmallChunks5 ! WT?FMMJKFHfX./r<c dgtz}dgtz}dgtz}g}|jtd|||g|jt |t dtzdtzdtzgy)z If the entire value to be flattened is available synchronously but does not fit into the buffer then it is chunked into buffer-sized pieces and these are passed to the write function. xyzNxyz)rrr(r]rr)r9somesomeMoreevenMorers r:test_someLargeChunksz)FlattenChunkingTests.test_someLargeChunkssx u{"5;&5;&  WTD(H+Ev}}UV  d[($*PQ R r<startc|d\}}|d\}}dd|dd|ddg}g}td||j}|||j|t|t gd y) a# Assert that flattening with a L{Deferred} returned by C{start} results in the expected buffering behavior. The L{Deferred} need not have a result by it is returned by C{start} but must have a result after the callable returned along with it is called. The expected buffering behavior is that flattened values up to the L{Deferred} are written together and then the result of the L{Deferred} is written together with values following it up to the next L{Deferred}. zfirst-zsecond-zalready-availablez-chunkszchunks-already-computedz more-chunks-N)salready-available-chunkssfirst-chunks-already-computeds$second-more-chunks-already-available)r(r]rrr) r9r first_wait first_finish second_wait second_finishrZrrs r:_chunksSeparatedByAsyncTestz0FlattenChunkingTests._chunksSeparatedByAsyncTests&$)? L%*9%5" ]          ! D% / Q    r<cxdtdttttgdfffd}|j |y)a When a fired L{Deferred} is encountered any buffered data is passed to the write function. Then the L{Deferred}'s result is passed to another write along with following synchronous values. This exact buffering behavior should be considered an implementation detail and can be replaced by some other better behavior in the future if someone wants. vr0Nct|dfS)Ncyrorrr<r:rz^FlattenChunkingTests.test_chunksSeparatedByFiredDeferred..sync_start..$r<r)rs r: sync_startzLFlattenChunkingTests.test_chunksSeparatedByFiredDeferred..sync_start!sAJ - -r<r%r rrr)r9rs r:#test_chunksSeparatedByFiredDeferredz8FlattenChunkingTests.test_chunksSeparatedByFiredDeferreds? . . 8K((2t8*<< = . ((4r<cxdtdttttgdfffd}|j |y)a When an unfired L{Deferred} is encountered any buffered data is passed to the write function. After the result of the L{Deferred} is available it is passed to another write along with following synchronous values. rr0Nc*tfdfS)Nc&jSro)callback)rrsr:rzaFlattenChunkingTests.test_chunksSeparatedByUnfiredDeferred..async_start..4sqzz!}r<)r)rrs`@r: async_startzOFlattenChunkingTests.test_chunksSeparatedByUnfiredDeferred..async_start0s(0zA,- -r<r)r9r"s r:%test_chunksSeparatedByUnfiredDeferredz:FlattenChunkingTests.test_chunksSeparatedByUnfiredDeferred(s? . . 8K((2t8*<< = . ((5r<r)rvrwrxrrr rr%r rrrrr#rr<r:rrsZ 0 "-  M5+!6V8L!LM M -  - ^5$6r<rcyrorrr<r:rrArr<c@eZdZdZd dZd dZd dZd dZd dZd dZ y) FlattenerErrorTestsz& Tests for L{FlattenerError}. Nc ttGdd}|jtt t d|ggdy)z 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. ceZdZdefdZy)7FlattenerErrorTests.test_renderable..Renderabler0cy)Nzrenderable reprrr8s r:__repr__z@FlattenerErrorTests.test_renderable..Renderable.__repr__Rs(r<N)rvrwrxrer+rr<r: Renderabler)Ps )# )r<r,reasonzCException while flattening: renderable repr RuntimeError: reason N)rrrrer RuntimeError)r9r,s r:test_renderablez#FlattenerErrorTests.test_renderableIsO [ ! ) ) " )  |H5 ~rJ K % r<c tdddd}|jttt d|ggdy) z 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. divz/foo/filename.xhtml )filename lineNumber columnNumberr-zlException while flattening: File "/foo/filename.xhtml", line 17, column 12, in "div" RuntimeError: reason N)r&rrerr.rMs r:test_tagzFlattenerErrorTests.test_tag\sA %"7BUWX  |H5ubA B % r<c v|jtttdt dggdy)z 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. r-spanz>Exception while flattening: Tag RuntimeError: reason N)rrerr.r&r8s r:test_tagWithoutLocationz+FlattenerErrorTests.test_tagWithoutLocationks1  |H5F }bI J U r<c d fd }dtfd ||jd|jttgdt|jjdztjjdzfzy#t$r9}tjt j ddd}|}Yd}~d}~wwxYw) z If a L{FlattenerError} is created with traceback frames, they are included in the string representation of the exception. r0Ncyror)gsr:fz-FlattenerErrorTests.test_traceback..f~s Cr<ctd)Nr-)r.rr<r:r=z-FlattenerErrorTests.test_traceback..gs x( (r<zf() must raise RuntimeErrorzException while flattening: File "%s", line %d, in f g() File "%s", line %d, in g raise RuntimeError("reason") RuntimeError: reason r) r failr. traceback extract_tbsysexc_inforrerHERE__code__co_firstlineno)r9r>etbinfoexcr=s @r:test_tracebackz"FlattenerErrorTests.test_tracebackvs  )8 ) 5 C II3 4  sB/ 0 % ))A- ))A-    ))#,,.*;.NotActuallyRenderablez#No methods provided; this will failr0cy)Nzrr8s r:r+zYFlattenerErrorTests.test_asynchronousFlattenError..NotActuallyRenderable.__repr__s'r<rJcyrorrs r:rzcFlattenerErrorTests.test_asynchronousFlattenError..NotActuallyRenderable.lookupRenderMethodsr<rscSror)r9rsfailings r:r}zWFlattenerErrorTests.test_asynchronousFlattenError..NotActuallyRenderable.rendersr<N) rvrwrxrrer+rr rr&r%rr})rTsr:NotActuallyRenderablerPsS 1 (# (  8H-s3[@A   hx&8 [ r<rUNexampleav Exception while flattening: \[\] > File ".*", line \d*, in _flattenTree element = await element.* )flagszRuntimeError: example)rrrr)assertNoResultr.errbackfailureResultOfr assertRegexrerZrecompiler MULTILINEr)r9rU flatteningrLfailurerTs @r:test_asynchronousFlattenErrorz1FlattenerErrorTests.test_asynchronousFlattenErrors %-J [ !   " #4*?*A)BC  J'9%&&z>B    JJ ll  -s7==/AB Wl3r<cJ dddttddffd }d dtddf fd }t|}td|}|j ||j ||j |j|t}|jd|j||j t|jtt jt|jjd}|j|ty) z@ The flattening of a Deferred can be cancelled. rN cancelledr0c|dz y)NrAr)rc cancelArg cancelCounts r: checkCancelz4FlattenerErrorTests.test_cancel..checkCancels!I 1 Kr<r`c |yror)r`errs r:saveErrz0FlattenerErrorTests.test_cancel..saveErrsCr<rA)rrrr)rX addErrbackcancelrZrrassertIsassertIsInstancer rZrargs) r9rgrjrr_r`rLrerfris @@@r: test_cancelzFlattenerErrorTests.test_cancels   8F#3    W  '{3"4+  J' W&&z>B a( i# c7+ d7C066Gmm  # c>2r<r) rvrwrxrr/r7r:rMrarprr<r:r&r&Ds' &    % N.4`$3r<r&)Drr\rErC collectionsrrrtypesrtypingrrr r r r r xml.etree.ElementTreerzope.interfacerhamcrestrrtwisted.internet.deferrrrrrtwisted.python.failurertwisted.test.testutilsrtwisted.trial.unittestrtwisted.web._flattenrtwisted.web.errorrrrtwisted.web.iwebrrr twisted.web.templater!r"r#r$r%r&r'r(r)r*r+r,twisted.web.test._utilr-r/rrH co_filenamerGr&rr<r:rs  #HHH%&*+46,KKCC    3O;*;O;d p6.p6v **m3-m3r<