PK76^RI))EGG-INFO/PKG-INFOMetadata-Version: 1.0 Name: PyProtocols Version: 1.0a0dev-r2302 Summary: Open Protocols and Component Adaptation for Python Home-page: http://peak.telecommunity.com/PyProtocols.html Author: Phillip J. Eby Author-email: peak@eby-sarna.com License: PSF or ZPL Description: UNKNOWN Platform: UNKNOWN PK76ɑEGG-INFO/SOURCES.txt.cvsignore CHANGES.txt README.txt TODO.txt UPGRADING.txt setup.cfg setup.py docs/ref/.cvsignore docs/ref/libprotocols.tex docs/ref/ref.tex ez_setup/README.txt ez_setup/__init__.py src/PyProtocols.egg-info/PKG-INFO src/PyProtocols.egg-info/SOURCES.txt src/PyProtocols.egg-info/dependency_links.txt src/PyProtocols.egg-info/native_libs.txt src/PyProtocols.egg-info/requires.txt src/PyProtocols.egg-info/top_level.txt src/PyProtocols.egg-info/zip-safe src/protocols/__init__.py src/protocols/_speedups.c src/protocols/_speedups.pyx src/protocols/adapters.py src/protocols/advice.py src/protocols/api.py src/protocols/classic.py src/protocols/generate.py src/protocols/interfaces.py src/protocols/twisted_support.py src/protocols/zope_support.py src/protocols/tests/__init__.py src/protocols/tests/checks.py src/protocols/tests/doctest.py src/protocols/tests/test_advice.py src/protocols/tests/test_classes.py src/protocols/tests/test_direct.py src/protocols/tests/test_twisted.py src/protocols/tests/test_zope.py src/setup/common.py PK762EGG-INFO/dependency_links.txt PK863ntEGG-INFO/native_libs.txtprotocols/_speedups.so PK76. EGG-INFO/requires.txtDecoratorTools>=1.3PK76; EGG-INFO/top_level.txtprotocols PK952EGG-INFO/zip-safe PK˃95d)yyprotocols/__init__.py"""Trivial Interfaces and Adaptation""" from api import * from adapters import NO_ADAPTER_NEEDED,DOES_NOT_SUPPORT,Adapter,StickyAdapter from adapters import AdaptationFailure from interfaces import * from advice import metamethod, supermeta from classic import ProviderMixin from generate import protocolForType, protocolForURI from generate import sequenceOf, IBasicSequence PK86LkUEEprotocols/__init__.pyc; Ec@sdZdkTdklZlZlZlZdklZdkTdk l Z l Z dk l Z dklZlZdklZlZdS( s!Trivial Interfaces and Adaptation(s*(sNO_ADAPTER_NEEDEDsDOES_NOT_SUPPORTsAdapters StickyAdapter(sAdaptationFailure(s metamethods supermeta(s ProviderMixin(sprotocolForTypesprotocolForURI(s sequenceOfsIBasicSequenceN(s__doc__sapisadapterssNO_ADAPTER_NEEDEDsDOES_NOT_SUPPORTsAdapters StickyAdaptersAdaptationFailures interfacessadvices metamethods supermetasclassics ProviderMixinsgeneratesprotocolForTypesprotocolForURIs sequenceOfsIBasicSequence( sIBasicSequencesAdaptationFailures sequenceOfsAdapters StickyAdaptersprotocolForTypesprotocolForURIsDOES_NOT_SUPPORTs ProviderMixins supermetas metamethodsNO_ADAPTER_NEEDED((s7build/bdist.darwin-8.9.1-i386/egg/protocols/__init__.pys?s  PK86"protocols/_speedups.pydef __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__,'_speedups.so') del __bootstrap__, __loader__ imp.load_dynamic(__name__,__file__) __bootstrap__() PK86i<<protocols/_speedups.pyc; k7Fc@sdatdS(cCsGdk}dk}dk}|itdabb|ittdS(Ns _speedups.so( ssyss pkg_resourcessimpsresource_filenames__name__s__file__s __bootstrap__s __loader__s load_dynamic(s pkg_resourcesssyssimp((s8build/bdist.darwin-8.9.1-i386/egg/protocols/_speedups.pys __bootstrap__s N(s __bootstrap__(((s8build/bdist.darwin-8.9.1-i386/egg/protocols/_speedups.pys?s PK8666protocols/_speedups.soH__TEXT``__text__TEXTH NH __picsymbol_stub__TEXT\\__cstring__TEXT\\__textcoal_nt__TEXT__ __DATA``__data__DATA``__dyld__DATAdd__bss__DATAe__IMPORTpp__jump_table__IMPORTpp__pointers__IMPORTp8p)8__LINKEDIT 4 C/usr/lib/libgcc_s.1.dylib 4 (FX/usr/lib/libSystem.B.dylibSXhN P7|7sXRWXWUVS0REXEED$ED$ WD$ IPD$ED$E $YbthEEEut,Et 0[^]ËEP$R0[^]ËEP$REu10[^]UVS0QE XEED$ED$MVD$ OD$ED$E $at3EEbEt%Et 0[^]ËEP$REP$REuUVS0QuEED$UD$ ND$ED$E $`EEFtLUVt"t 10[^]ËEP$RF4$PUuًFP$RUVuȸ0[^]US%PED$$aP[]UVuVt tFu^]FP$RFu^]UE@tUT$$U t1UVS}OuVt tf`F1[^]ËFP$Rf`F1[^]UWVS<$OE؉֍LD$HU$=_DžuEDU$_ƅ6_EUT$D$t$ U؉T$MD$<$D_ƋU܅tU܋tKt1EtUu B$P<[^_]E믋G<$P1렋B$P1<[^_]$^E܅tE1EuUWVSIǃ:IAB1BI>Iǃ:IҋBI>Iǃ:I붋F4$PBI>Iǃ:It끋F4$PqBI>Iǃ:IUWVSL@EĉUMEtQBdQ9sT$$ Q_`QU9BFD$Eĉ$PEȅtQUȋ$aPƅEF t$Uȉ$]PDžtQ;tQ$uȉ}ЋtQUԋF4$PUЋB$PUԋB$PUċB$PUB$PUċB9EUT$$O{EăljuЉuԋCUЋLUԋUUċ^UgUu B$PL[^_]ÉvQU9BED$$FNUă׋tQuЉu?F4$PAB$PHFFǃFGG|$F$NƅO$&NNjuJuȋtQUԉUЍ?r1B$PUȋYB$PK?7.…oFt$F$hMDž[D$${ME؅&$KMDžD$E؉$(ME܅U؋bKGD$E܉$LDžU܋XWtQE9-GLH4P8@<$$8u1q1ǃm1VF4$PF4$PL|$><$7u1q1ǃm1  UWVS|g'EEED$ED$O,D$ &D$ED$E $=7EEP8Ud89BB-|$-$P7ƅD$E$77Nj_P8`>}B@89T$$ 7U<89B-D$E$6ƅ~P8h3u;.D$E$]6E̅‹?.D$$>6EŰP8]UB889tT$$;6PE@EЅG}E$5E̅p D$E$5Eą"ŰP89E!EuE9Ew UiB$P[rP8QuB@89EtP8WB$Pu;.D$E$4E̅N--ǃ-rP8EljE&1UB$PG<$PUB$PUB$PUB$PEEP$R1|[^_]ËB$PuUu B$PP8UUEljƋU UU(U1E:E;EP$R|[^_]ËB$PP8jB$PEF4$PG<$P}B$PUBX89tT$$2CURUE|$]2EGp D$E$[2DžEUP8;P8VEuU9UNUB Uԋ4UcB$PUB$PB$Pr--ǃ-rP8EljEE̅ŰB$PF4$PuE$0Eur$1E̅ p D$E$1E ŰP8u9}uE$0ƅn UoB$PaB$PpB$PM|$`8$0--ǃ-)P8}}}}B$P$/ƅP8dEx…Od8UȃT$4$/1UȋL8EȃD$4$/UȋUȋB$PuD8$T/e/EpEP-9tD$$M/1/-t$-$.Eȅ $.E$.E̅EỦB EBT$Uȉ$.ƅUȋŰtB$PfG<$P}B$PZƅP8-H4P8@uދ t2 GD$G$i# 7uԋ$!%)- $4$#t$mD$ $H#{$p"ƅaV aeV eBiV iB}V }B V BqV qByV yBmV mBt$MD$ $C"$!ƅQV Q򋃅Dž*QD$<$!ƅD$QD$ $!$ DžUW UqƅUD$4$ DžD$UD$ $ $$ ƅYV YYDžYD$<$< ƅED$YD$ $H du F4$Pu G<$PYt$ $Dž{-:-|$ $ƅ D$$Džqu F4$Pu B$P$ƅ!!$ƅz%u B$P%$ƅ%D$]D$ $u F4$P$Hƅ?))$159=t$ $At$ $<Et$ $I,[^_]Ëǃ,[^_]ǃ^,[^_]ǃ몋ǃ@됋F4$Pǃ1tYUFG<$P8ǃ@붋ǃ@믋F4$P뜋F4$PǃAG<$PF4$PǃA-G<$PǃAǃD|$ $ƅ$Nj$…Fu B$P|$ $Pƅ_$DžaF4$PSF4$PkG<$PNF4$POǃDG<$PF4$P\ǃDu F4$PuB$P|$$$&ǃIǃFǃJuǃI|$$$ǃF'ǃGǃLǃKB$P=t$$$ǃE?t$$$ǃ`|$$$ǃG/ǃL1t$$$Vǃt$$$%ǃB$PǃMUWVS,UwEU E:|$ $ƅ$Dž>>G |$4$E11ҋE螺U ǃ lJ踼UU tlUu B$P,[^_]Ë ǃ lWtwG<$PiB$P뉋B$PmEU :|$ $Vƅ$ODžBBG |$4$EEH+11ҋE-U ǃ ojGUtU B$PU B$P7G<$P F4$PF4$P ǃ ogXG<$PJ|$$ ǃ lB$PG<$PF4$PF4$Pr|$$Y ǃ o_speedups.metamethodWrapper for metaclass method that might be confused w/instance methodAdaptationFailureAttributeErrorDOES_NOT_SUPPORTExtensionClassFalseImportErrorNO_ADAPTER_NEEDEDProtocol__adapt__Protocol__call__TypeError_Protocol__adapters__all____bases____class__mro__adaptclassicMROexc_infoextClassMROgetgetMROmetamethodobjectsystb_next_speedups.pyxobjprotocolO|OfuncO__import__OOOOraise: arg 3 must be a traceback or Noneraising a string exception is deprecatedinstance exception may not have a separate value_speedups.metamethod.__get___speedups.buildClassicMRO_speedups.buildECMROobextendedClassic_speedups.extClassMRO_speedups._adaptselfdefaultOO|O_speedups.Protocol__call___speedups.adapt_speedups.classicMRO_speedups.getMROOO_speedups.Protocol__adapt___speedups__builtin____builtins___speedups.metamethod.__set___speedups.metamethod.__delete__$\ e@e eeE$\KredX__mro____class____adapt____conform__fafafaf|a fhaNot a classic classCan't adaptRead-only attributeRead-only attributeprotocols.adaptershfl\f\xf\lf\f\f\tf\f\f\f]f]`f$]f,]pf8]f@]|fH]fP]df\]fh]ft]fx]f]f]f]f]C Speedups for commonly-used operations\j Pd\2$dH]u/c\P.pcP]0h]x]4\8Adapt to this protocolPEP 246-alike: Adapt 'obj' to 'protocol', return 'default' If 'default' is not supplied and no implementation is found, raise 'AdaptationFailure'.Prevent 'obj' from supporting 'protocol'Assume 'obj' implements 'protocol' directly]]]]]]^^_^ _]] _^^^^_]`ddddddddddddddddddd|dTcPcDc@c4c0c$c cccc cccbbbbbbbbbbbbbbbb|bxbtbpblbhbdb`b\bXbTbPbLbHbDb@b%?%[%$N.DDDD\%$%% %%@%@%%%%%$2N.DDDD%D*D,D8DDDI%$&!&&@&$NNK.KDKDQD[DlDnDp&$K&& &&@&&')'@2'K3'r4'$'Nr.rDrDDDDDD5'$ra'j'@s'$XNt'.DD' fDDD!'fD"!D$)D%1D'9D*cD+xD,D.D"D+D%D*DD.DD'$''@'@''@'@ ((%(&('($9N((.D8D9D;&D<.D=JD>]DPhDQzDRDTDRDTDQDPD@DDDEDFDG+DH1DI7DJ=DK@DLGDMNDNUDDaDFuDEDADB;($8T(9_(9k(9t(@:(;(((***+"+@+d+--.../8/K/i// 1V1W1X1$NY1.DVDWDXDYD[D_D`D5DNDaDD\DbDeDjDlDmDnDpDqD4DJDuRDyzDzDgDDD\DDDDDf1$Vy1@V1V1V1$ON1.DD1(fD(D0D:DBDSD[DiDqDD1$fDDDDDD(D?DMD`DoDDDDDDDDD1$1@1 2@2.2@A2T2d2u22222$ N.DD&D4D9D?DBDEDIDkDtDDDDDDD2,fD2$22 223@3@33 3$N 3 . D D D)D,DADPDSD[DaDzDDDDDDDDDD D D*D3DPD^Dv?3$ i3@~33333344)5@<5@K5@Z5 [5\5$N]5.D7D=D>DADDDEDFDH DIDMDR-DSADFLDHNDI[DJ_D[DSDFDMDRD[DDDYD\D_#D`.DbED_ODEZDZrDFDADUDWDU|5$757575@85@95@:5@;6<666$EN6d.DeDfDm.6XfDnD4Do>DpDDqJDtSDuiDzxD{D~DDDDDDDDDDD,D2D5DJDgDxDuD{DtDDzD~DDD*DI96$e_6eq6e 6e6f6g6@h6@i6@j6@k7&ld787@eJ7@e\7]7c^7$Nc_7c.cD'cD1zD2}D3D6D9DMDfz74fDjDnDoDtDz D{& D|, D}/ D~H DW Dl Dx DY DZ D[ D\ D] D=!DA%DL%D]%D4k%D%D%D4%D%D%D&D2 &D3&D'&D1&D@&DSH&DY&Dh&D}&D&D&D&D&D&D&D&D&D&D&D&DT'DU5'D`'Dn'D|'D'D'D'D'D2'D3'D'D'D 'D (D /(D A(D S(Do(D~(D(D(D(D(D(D(D(D(D(D(D(D(DS*)DT9)DR)Dj)DT)D)D )D#)D6)70fDL)D)D)D)D)D *D*D"*DS0*D>*Dg*D*D)*D**D*D*D*D*D*D*D*D+D0+D43+DG+Dp+D ~+D+D+D+D9,D2,D3",D:*,D;A,D<J,D=V,D>\,D?_,D@e,DAk,DB,DC,DD,DE,DF,D ,D*,D -D0-D-D'-D 5-D4U-Di-D)-D -DA-DE .D4.DC4.DBB.7$'c7'8'8'38@)G8*\8+n8@,}8@-8@.8/808c8@8B"8^"8@8"8#8@8k%8%8@8%8%8@8 &8'&8@ 9' 9' 9@93+9G+99%9,&9*,'9@39U-49i-599@9.A94.B9P.C9$NP.D9d.P.DP.D].Dd.Dk.Y9PfDt.D.D.D.D.D.D.D.D/D/D#/D//DK/Dc/d9$P.99 99999@:@:&d5:Q:@c:@u:P.v:u/w:$%Nu/x:d.u/Ddu/De/Df/Dk/:LfDl/D/Dm/Dn/Do/Dr/D~ 0D0D%0D?0D~H0DT0Drp0D{0:$du/:d:d :d:e;f;g-;@h<;@iK;&jdc;;@d;@d;u/;0;$%N0;d.0D0D0D0;TfD0D0D0D1D 1D1D2!1D351D=1DT1D]1Di1Do1Du1D 1D!1D"1D#1D$1D,1D/1D02D12D3,2D62D382DB2D)`2D*k2D02D/2D#2D!2D 2D)2D2D3D3D)3D83DL3DN3D4X3Dq3Dw3Dz3D3D3D 3D 3D 3D3D3D3D3D4D64DS4Dw4D 4;$0;; <!<2<P<@c<@r<@<@<<@<&d<<@<@=0=@=!1==1=@ =X3!=q3"=4#=$N4$=d.4D4D4D49=\fD4D5D 5D5D5D!5D>5DZ5Dl5D5D5D5D5D=@fD5D25D35D5D5D5D6D6D 6D6D.6DE6DV6Dn6D}6D6D6D6D26D36D6D6D6D7D7D 7D7D.7DE7DW7D]7Dj7D{7D7D7D7D7D7D7D7D4 8D8D:8DH8D4V8Dj8a=$4== ====@=>@>@">&d:>V>@h>@z>4{>@>5>5>@>6>6>@> 8>8>@>V8>j8>8>$N8>d.8D8D8D8D8D8D8D8D8D8D(9D2 9D3 9D)(9D*99D.H9D2P9D3S9D8h9DSw9D]|9Ds9D9>D >D+>D.>D1>DJ>D\>Dq>D}>D>D>D>D>D>D>Dd?D,?D0=?D<T?D=k?D>n?D?q?D@?DA?DG?D0?D2?D3?D7?D?D@D4@D(#@DL;@DR@Dv`@Dwv@D|@D}@D@D@D@D@D@D@D@DAD;(AD<8AD?@ADBEADPADtADyAD2AD3ADADADADADADADADBDA'BD@5BDLCBDMRBDgBDlBDoBDrBDuBD|BDBDBDSBDBD BDBD-CDDCD^CDpCDCDCDCDCDCDwCD}CD DDDD/DD4DD7DD:DD=DDDDDKDDRDDbDDDDbDDcDDbDDEDv1EDIEDJ_EDKvEDLEDMEDNEDOEDPEDQEDREDUFD0/FD|LFD rFDFDbFDFDFDFDGDGD*GD 0GD!9GD"SGD#eGDGDGDGDM#HDL1HDNHDJHD4HDHDHDHDIDID4AID<{IDIDID? JD3JDMPJDL|JDJDJDJDJDKJDKDU*KDR;KDQIKDWKDPKD#KD"KD!K>$8?"? 4?F?Y?k?{??@????@? ? @ @ !@/@&dG@c@@u@@@8@@(@ 9@(9@@(@@@#@@@@A@A@@@H@H@L@$~NL.LDNLD LDTLDUWLDV_LDWsLDX{LDLDLDLDLDLDLDYLDLDLDMDMD[ MD\MD]!MD^'MD_-MD`8MDaJMDbZMDc~MDfMDgMDhMDiMDjMDkMDlMDmMDnMDoMDpMDqNDr NDsNDt NDu,NDv5NDwANDxeND{tND|ND}ND~NDNDNDNDODOD"OD8ODAODLODcODrODODODODODODODODPD PDF(:HfOF(;Lf`F(<PfqF(=TfF(>XfF(?\fF&GaF&H`F&I`F&J`F&K`G(M`fG(Ndf2G(OhfSG(PlfqG(QpfG(RtfG(SxfG(T|fG(UfG(VfH(Wf3H(XfIH(YfjH(ZfH([fH(\fH(]fH(^fH(`fH&cPdI&{$dNI(flI(f~I&aI(fI&aI( fI(!fI(#fI&%|a J&cc/J&pc^J(fpJ&haJ(5fJ(fJ(fJ(fJ&saK& aK&eJK&epK&@eK& eK&eK&?bK&|dL ?L\LyLLLLLM$MAM^M{MMMMMN-NJNfNd\C_0[ `}L.>M^o{+7DRd{'?Nc )6F4#C.D)7H?<>Q'F@/IE O;%$K&="1L9A8!6(NB32MP*GR+5J,0-:__dyld_func_lookupdyld_stub_binding_helper__mh_bundle_header___i686.get_pc_thunk.bx___pyx_type_9_speedups_metamethod_init_speedups_PyArg_ParseTupleAndKeywords_PyBaseObject_Type_PyClass_Type_PyCode_New_PyDict_New_PyErr_Clear_PyErr_ExceptionMatches_PyErr_Fetch_PyErr_NormalizeException_PyErr_Occurred_PyErr_Restore_PyErr_SetObject_PyErr_SetString_PyErr_Warn_PyExc_AttributeError_PyExc_DeprecationWarning_PyExc_NameError_PyExc_TypeError_PyFrame_New_PyImport_AddModule_PyInstance_Type_PyInt_FromLong_PyIter_Next_PyList_Append_PyList_New_PyList_Type_PyMethod_New_PyModule_GetDict_PyObject_CallFunction_PyObject_CallObject_PyObject_GC_Del_PyObject_GetAttr_PyObject_GetAttrString_PyObject_GetItem_PyObject_GetIter_PyObject_IsInstance_PyObject_IsTrue_PyObject_SetAttr_PyObject_SetAttrString_PyObject_Type_PyString_FromString_PyString_FromStringAndSize_PyString_InternFromString_PyString_Type_PyThreadState_Get_PyTraceBack_Here_PyTraceBack_Type_PyTuple_New_PyTuple_Size_PyTuple_Type_PyType_IsSubtype_PyType_Ready_PyType_Type_Py_InitModule4__Py_NoneStruct{standard input}int:t1=r1;-2147483648;2147483647;char:t2=r2;0;127;void:t3=3/SourceCache/Csu/Csu-58/bundle1.s/SourceCache/Csu/Csu-58///SourceCache/Csu/Csu-58/bundle1.s/SourceCache/Csu/Csu-58/bundle1.sdyld_stub_binding_helper:F3dyld__mh_bundle_headerdyld_lazy_symbol_binding_entry_point__dyld_func_lookup:F3dyld_func_lookup_pointer/Users/alberto/src/python/checkouts/PyProtocols/src/protocols/_speedups.cgcc2_compiled.___pyx_tp_dealloc_9_speedups_metamethod___pyx_tp_as_number_metamethod___pyx_tp_as_sequence_metamethod___pyx_tp_as_mapping_metamethod___pyx_tp_as_buffer_metamethod___pyx_tp_traverse_9_speedups_metamethod___pyx_tp_clear_9_speedups_metamethod___pyx_methods_9_speedups_metamethod___pyx_tp_descr_get_9_speedups_metamethod___pyx_tp_descr_set_9_speedups_metamethod___pyx_f_9_speedups_10metamethod___init_____pyx_tp_new_9_speedups_metamethod___pyx_k18___pyx_k17___pyx_k16___pyx_k15___pyx_ptype_9_speedups_metamethod___pyx_string_tab___pyx_k11p___pyx_k11___pyx_k26p___pyx_k26___pyx_k27p___pyx_k27___pyx_k28p___pyx_k28___pyx_k29p___pyx_k29___pyx_intern_tab___pyx_n_AdaptationFailure___pyx_n_AttributeError___pyx_n_DOES_NOT_SUPPORT___pyx_n_ExtensionClass___pyx_n_False___pyx_n_ImportError___pyx_n_NO_ADAPTER_NEEDED___pyx_n_Protocol__adapt_____pyx_n_Protocol__call_____pyx_n_TypeError___pyx_n__Protocol__adapters___pyx_n___all_____pyx_n___bases_____pyx_n___class___pyx_n___mro_____pyx_n_adapt___pyx_n_classicMRO___pyx_n_exc_info___pyx_n_extClassMRO___pyx_n_get___pyx_n_getMRO___pyx_n_metamethod___pyx_n_object___pyx_n_sys___pyx_n_tb_next___pyx_mdoc___pyx_methods___pyx_f_9_speedups_NO_ADAPTER_NEEDED___pyx_doc_9_speedups_NO_ADAPTER_NEEDED___pyx_f_9_speedups_DOES_NOT_SUPPORT___pyx_doc_9_speedups_DOES_NOT_SUPPORT___pyx_f_9_speedups_adapt___pyx_doc_9_speedups_adapt___pyx_f_9_speedups_Protocol__call_____pyx_doc_9_speedups_Protocol__call_____pyx_f_9_speedups_classicMRO___pyx_f_9_speedups_extClassMRO___pyx_f_9_speedups_getMRO___pyx_f_9_speedups_Protocol__adapt_____pyx_filenames___pyx_argnames.7041___pyx_k19__pyx_f_9_speedups_NO_ADAPTER_NEEDED:f(0,1)__pyx_self:p(0,1)__pyx_args:p(0,1)__pyx_kwds:p(0,1)__pyx_v_obj:(0,1)__pyx_v_protocol:(0,1)__pyx_r:r(0,1)__pyx_argnames:V(0,2)void:t(0,3)=(0,3):t(0,1)=*(0,4):t(0,2)=ar(0,5);0;2;(0,6)PyObject:t(0,4)=(0,7)long unsigned int:t(0,5)=r(0,5);0;037777777777;:t(0,6)=*(0,8)_object:T(0,7)=s8ob_refcnt:(0,9),0,32;ob_type:(0,10),32,32;;char:t(0,8)=r(0,8);0;127;int:t(0,9)=r(0,9);-2147483648;2147483647;:t(0,10)=*(0,11)_typeobject:T(0,11)=s192ob_refcnt:(0,9),0,32;ob_type:(0,10),32,32;ob_size:(0,9),64,32;tp_name:(0,6),96,32;tp_basicsize:(0,9),128,32;tp_itemsize:(0,9),160,32;tp_dealloc:(0,12),192,32;tp_print:(0,14),224,32;tp_getattr:(0,16),256,32;tp_setattr:(0,18),288,32;tp_compare:(0,20),320,32;tp_repr:(0,22),352,32;tp_as_number:(0,24),384,32;tp_as_sequence:(0,25),416,32;tp_as_mapping:(0,26),448,32;tp_hash:(0,27),480,32;tp_call:(0,29),512,32;tp_str:(0,22),544,32;tp_getattro:(0,31),576,32;tp_setattro:(0,33),608,32;tp_as_buffer:(0,35),640,32;tp_flags:(0,36),672,32;tp_doc:(0,6),704,32;tp_traverse:(0,37),736,32;tp_clear:(0,39),768,32;tp_richcompare:(0,41),800,32;tp_weaklistoffset:(0,36),832,32;tp_iter:(0,43),864,32;tp_iternext:(0,44),896,32;tp_methods:(0,45),928,32;tp_members:(0,46),960,32;tp_getset:(0,47),992,32;tp_base:(0,10),1024,32;tp_dict:(0,1),1056,32;tp_descr_get:(0,48),1088,32;tp_descr_set:(0,49),1120,32;tp_dictoffset:(0,36),1152,32;tp_init:(0,50),1184,32;tp_alloc:(0,51),1216,32;tp_new:(0,53),1248,32;tp_free:(0,55),1280,32;tp_is_gc:(0,39),1312,32;tp_bases:(0,1),1344,32;tp_mro:(0,1),1376,32;tp_cache:(0,1),1408,32;tp_subclasses:(0,1),1440,32;tp_weaklist:(0,1),1472,32;tp_del:(0,12),1504,32;;:t(0,13)=*(0,57)destructor:t(0,12)=(0,13):t(0,15)=*(0,58)printfunc:t(0,14)=(0,15):t(0,17)=*(0,59)getattrfunc:t(0,16)=(0,17):t(0,19)=*(0,60)setattrfunc:t(0,18)=(0,19):t(0,21)=*(0,61)cmpfunc:t(0,20)=(0,21):t(0,23)=*(0,62)reprfunc:t(0,22)=(0,23):t(0,24)=*(0,63):t(0,25)=*(0,64):t(0,26)=*(0,65):t(0,28)=*(0,66)hashfunc:t(0,27)=(0,28):t(0,30)=*(0,67)ternaryfunc:t(0,29)=(0,30):t(0,32)=*(0,68)getattrofunc:t(0,31)=(0,32):t(0,34)=*(0,69)setattrofunc:t(0,33)=(0,34):t(0,35)=*(0,70)long int:t(0,36)=r(0,36);-2147483648;2147483647;:t(0,38)=*(0,71)traverseproc:t(0,37)=(0,38):t(0,40)=*(0,72)inquiry:t(0,39)=(0,40):t(0,42)=*(0,73)richcmpfunc:t(0,41)=(0,42)getiterfunc:t(0,43)=(0,23)iternextfunc:t(0,44)=(0,23):t(0,45)=*(0,74):t(0,46)=*(0,75):t(0,47)=*(0,76)descrgetfunc:t(0,48)=(0,30)descrsetfunc:t(0,49)=(0,34)initproc:t(0,50)=(0,34):t(0,52)=*(0,77)allocfunc:t(0,51)=(0,52):t(0,54)=*(0,78)newfunc:t(0,53)=(0,54):t(0,56)=*(0,79)freefunc:t(0,55)=(0,56):t(0,57)=f(0,3):t(0,58)=f(0,9):t(0,59)=f(0,1):t(0,60)=f(0,9):t(0,61)=f(0,9):t(0,62)=f(0,1)PyNumberMethods:t(0,63)=(0,80)PySequenceMethods:t(0,64)=(0,81)PyMappingMethods:t(0,65)=(0,82):t(0,66)=f(0,36):t(0,67)=f(0,1):t(0,68)=f(0,1):t(0,69)=f(0,9)PyBufferProcs:t(0,70)=(0,83):t(0,71)=f(0,9):t(0,72)=f(0,9):t(0,73)=f(0,1)PyMethodDef:T(0,74)=s16ml_name:(0,6),0,32;ml_meth:(0,84),32,32;ml_flags:(0,9),64,32;ml_doc:(0,6),96,32;;PyMemberDef:T(0,75)=s20name:(0,6),0,32;type:(0,9),32,32;offset:(0,9),64,32;flags:(0,9),96,32;doc:(0,6),128,32;;PyGetSetDef:T(0,76)=s20name:(0,6),0,32;get:(0,85),32,32;set:(0,87),64,32;doc:(0,6),96,32;closure:(0,89),128,32;;:t(0,77)=f(0,1):t(0,78)=f(0,1):t(0,79)=f(0,3):T(0,80)=s152nb_add:(0,90),0,32;nb_subtract:(0,90),32,32;nb_multiply:(0,90),64,32;nb_divide:(0,90),96,32;nb_remainder:(0,90),128,32;nb_divmod:(0,90),160,32;nb_power:(0,29),192,32;nb_negative:(0,91),224,32;nb_positive:(0,91),256,32;nb_absolute:(0,91),288,32;nb_nonzero:(0,39),320,32;nb_invert:(0,91),352,32;nb_lshift:(0,90),384,32;nb_rshift:(0,90),416,32;nb_and:(0,90),448,32;nb_xor:(0,90),480,32;nb_or:(0,90),512,32;nb_coerce:(0,92),544,32;nb_int:(0,91),576,32;nb_long:(0,91),608,32;nb_float:(0,91),640,32;nb_oct:(0,91),672,32;nb_hex:(0,91),704,32;nb_inplace_add:(0,90),736,32;nb_inplace_subtract:(0,90),768,32;nb_inplace_multiply:(0,90),800,32;nb_inplace_divide:(0,90),832,32;nb_inplace_remainder:(0,90),864,32;nb_inplace_power:(0,29),896,32;nb_inplace_lshift:(0,90),928,32;nb_inplace_rshift:(0,90),960,32;nb_inplace_and:(0,90),992,32;nb_inplace_xor:(0,90),1024,32;nb_inplace_or:(0,90),1056,32;nb_floor_divide:(0,90),1088,32;nb_true_divide:(0,90),1120,32;nb_inplace_floor_divide:(0,90),1152,32;nb_inplace_true_divide:(0,90),1184,32;;:T(0,81)=s40sq_length:(0,39),0,32;sq_concat:(0,90),32,32;sq_repeat:(0,94),64,32;sq_item:(0,94),96,32;sq_slice:(0,96),128,32;sq_ass_item:(0,98),160,32;sq_ass_slice:(0,100),192,32;sq_contains:(0,102),224,32;sq_inplace_concat:(0,90),256,32;sq_inplace_repeat:(0,94),288,32;;:T(0,82)=s12mp_length:(0,39),0,32;mp_subscript:(0,90),32,32;mp_ass_subscript:(0,103),64,32;;:T(0,83)=s16bf_getreadbuffer:(0,104),0,32;bf_getwritebuffer:(0,106),32,32;bf_getsegcount:(0,107),64,32;bf_getcharbuffer:(0,109),96,32;;PyCFunction:t(0,84)=(0,32):t(0,86)=*(0,111)getter:t(0,85)=(0,86):t(0,88)=*(0,112)setter:t(0,87)=(0,88):t(0,89)=*(0,3)binaryfunc:t(0,90)=(0,32)unaryfunc:t(0,91)=(0,23):t(0,93)=*(0,113)coercion:t(0,92)=(0,93):t(0,95)=*(0,114)intargfunc:t(0,94)=(0,95):t(0,97)=*(0,115)intintargfunc:t(0,96)=(0,97):t(0,99)=*(0,116)intobjargproc:t(0,98)=(0,99):t(0,101)=*(0,117)intintobjargproc:t(0,100)=(0,101)objobjproc:t(0,102)=(0,21)objobjargproc:t(0,103)=(0,34):t(0,105)=*(0,118)getreadbufferproc:t(0,104)=(0,105)getwritebufferproc:t(0,106)=(0,105):t(0,108)=*(0,119)getsegcountproc:t(0,107)=(0,108):t(0,110)=*(0,120)getcharbufferproc:t(0,109)=(0,110):t(0,111)=f(0,1):t(0,112)=f(0,9):t(0,113)=f(0,9):t(0,114)=f(0,1):t(0,115)=f(0,1):t(0,116)=f(0,9):t(0,117)=f(0,9):t(0,118)=f(0,9):t(0,119)=f(0,9):t(0,120)=f(0,9)__pyx_args:r(0,1)__pyx_kwds:r(0,1)___pyx_argnames.7073___pyx_k20__pyx_f_9_speedups_DOES_NOT_SUPPORT:f(0,1)__pyx_self:p(0,1)__pyx_args:p(0,1)__pyx_kwds:p(0,1)__pyx_v_obj:(0,1)__pyx_v_protocol:(0,1)__pyx_r:r(0,1)__pyx_argnames:V(0,121):t(0,121)=ar(0,5);0;2;(0,6)__pyx_args:r(0,1)__pyx_kwds:r(0,1)___pyx_argnames.7103__pyx_f_9_speedups_10metamethod___init__:f(0,9)__pyx_v_self:p(0,1)__pyx_args:p(0,1)__pyx_kwds:p(0,1)__pyx_v_func:(0,1)__pyx_r:r(0,9)int:t(0,9)__pyx_argnames:V(0,122)__pyx_v_self:r(0,1)__pyx_args:r(0,1)__pyx_kwds:r(0,1):t(0,122)=ar(0,5);0;1;(0,6)__pyx_tp_new_9_speedups_metamethod:f(0,1)t:p(0,123)a:p(0,1)k:p(0,1)o:r(0,1)t:r(0,123):t(0,123)=*(0,124)PyTypeObject:t(0,124)=(0,11)__pyx_tp_dealloc_9_speedups_metamethod:f(0,3)o:p(0,1)__pyx_obj_9_speedups_metamethod:T(0,125)=s12ob_refcnt:(0,9),0,32;ob_type:(0,10),32,32;func:(0,1),64,32;;o:r(0,1)__pyx_tp_traverse_9_speedups_metamethod:f(0,9)o:p(0,1)v:p(0,126)a:p(0,89)e:r(0,9):t(0,127)=*(0,128)visitproc:t(0,126)=(0,127):t(0,128)=f(0,9)o:r(0,1)__pyx_tp_clear_9_speedups_metamethod:f(0,9)o:p(0,1)o:r(0,1)___Pyx_Import___pyx_b___pyx_m__Pyx_Import:f(0,1)name:p(0,1)from_list:P(0,1)__import__:r(0,1)empty_list:(0,1)module:r(0,1)global_dict:r(0,1)empty_dict:(0,1)list:(0,1)___Pyx_GetExcValue__Pyx_GetExcValue:f(0,1)type:(0,1)value:(0,1)tb:(0,1)result:r(0,1)tstate:(0,129):t(0,129)=*(0,130)PyThreadState:t(0,130)=(0,131)_ts:T(0,131)=s84next:(0,132),0,32;interp:(0,133),32,32;frame:(0,134),64,32;recursion_depth:(0,9),96,32;tracing:(0,9),128,32;use_tracing:(0,9),160,32;c_profilefunc:(0,135),192,32;c_tracefunc:(0,135),224,32;c_profileobj:(0,1),256,32;c_traceobj:(0,1),288,32;curexc_type:(0,1),320,32;curexc_value:(0,1),352,32;curexc_traceback:(0,1),384,32;exc_type:(0,1),416,32;exc_value:(0,1),448,32;exc_traceback:(0,1),480,32;dict:(0,1),512,32;tick_counter:(0,9),544,32;gilstate_counter:(0,9),576,32;async_exc:(0,1),608,32;thread_id:(0,36),640,32;;:t(0,132)=*(0,131):t(0,133)=*(0,137):t(0,134)=*(0,138):t(0,136)=*(0,139)Py_tracefunc:t(0,135)=(0,136)PyInterpreterState:t(0,137)=(0,140)_frame:T(0,138)=s336ob_refcnt:(0,9),0,32;ob_type:(0,10),32,32;ob_size:(0,9),64,32;f_back:(0,134),96,32;f_code:(0,141),128,32;f_builtins:(0,1),160,32;f_globals:(0,1),192,32;f_locals:(0,1),224,32;f_valuestack:(0,142),256,32;f_stacktop:(0,142),288,32;f_trace:(0,1),320,32;f_exc_type:(0,1),352,32;f_exc_value:(0,1),384,32;f_exc_traceback:(0,1),416,32;f_tstate:(0,129),448,32;f_lasti:(0,9),480,32;f_lineno:(0,9),512,32;f_restricted:(0,9),544,32;f_iblock:(0,9),576,32;f_blockstack:(0,143),608,1920;f_nlocals:(0,9),2528,32;f_ncells:(0,9),2560,32;f_nfreevars:(0,9),2592,32;f_stacksize:(0,9),2624,32;f_localsplus:(0,144),2656,32;;:t(0,139)=f(0,9)_is:T(0,140)=s36next:(0,145),0,32;tstate_head:(0,132),32,32;modules:(0,1),64,32;sysdict:(0,1),96,32;builtins:(0,1),128,32;codec_search_path:(0,1),160,32;codec_search_cache:(0,1),192,32;codec_error_registry:(0,1),224,32;dlopenflags:(0,9),256,32;;:t(0,141)=*(0,146):t(0,142)=*(0,1):t(0,143)=ar(0,5);0;19;(0,147):t(0,144)=ar(0,5);0;0;(0,1):t(0,145)=*(0,140)PyCodeObject:t(0,146)=(0,148)PyTryBlock:t(0,147)=(0,149):T(0,148)=s64ob_refcnt:(0,9),0,32;ob_type:(0,10),32,32;co_argcount:(0,9),64,32;co_nlocals:(0,9),96,32;co_stacksize:(0,9),128,32;co_flags:(0,9),160,32;co_code:(0,1),192,32;co_consts:(0,1),224,32;co_names:(0,1),256,32;co_varnames:(0,1),288,32;co_freevars:(0,1),320,32;co_cellvars:(0,1),352,32;co_filename:(0,1),384,32;co_name:(0,1),416,32;co_firstlineno:(0,9),448,32;co_lnotab:(0,1),480,32;;:T(0,149)=s12b_type:(0,9),0,32;b_handler:(0,9),32,32;b_level:(0,9),64,32;;___Pyx_Raise__Pyx_Raise:f(0,3)type:P(0,1)value:p(0,1)tb:p(0,1)___Pyx_AddTraceback___pyx_filename___pyx_lineno__Pyx_AddTraceback:f(0,3)funcname:P(0,6)py_srcfile:(0,1)py_funcname:r(0,1)py_globals:(0,1)empty_tuple:r(0,1)empty_string:(0,1)py_code:(0,141)py_frame:(0,150):t(0,150)=*(0,151)PyFrameObject:t(0,151)=(0,138)___pyx_f__pyx_tp_descr_get_9_speedups_metamethod:f(0,1)o:p(0,1)i:p(0,1)c:p(0,1)r:(0,1)i:r(0,1)c:r(0,1)___pyx_f_9_speedups_buildClassicMRO__pyx_f_9_speedups_buildClassicMRO:f(0,1)__pyx_v_cls:P(0,152)__pyx_v_list:p(0,153)__pyx_v_i:(0,9):t(0,152)=*(0,154):t(0,153)=*(0,155)PyClassObject:t(0,154)=(0,156)PyListObject:t(0,155)=(0,157):T(0,156)=s32ob_refcnt:(0,9),0,32;ob_type:(0,10),32,32;cl_bases:(0,1),64,32;cl_dict:(0,1),96,32;cl_name:(0,1),128,32;cl_getattr:(0,1),160,32;cl_setattr:(0,1),192,32;cl_delattr:(0,1),224,32;;:T(0,157)=s16ob_refcnt:(0,9),0,32;ob_type:(0,10),32,32;ob_size:(0,9),64,32;ob_item:(0,142),96,32;;__pyx_v_tmp:r(0,1)__pyx_r:r(0,1)__pyx_2:r(0,9)___pyx_f_9_speedups_buildECMRO__pyx_f_9_speedups_buildECMRO:f(0,1)__pyx_v_cls:p(0,1)__pyx_v_list:p(0,153)__pyx_v_i:r(0,1)__pyx_r:r(0,1)__pyx_1:r(0,9)__pyx_2:r(0,1)__pyx_3:(0,1)___pyx_argnames.7684___pyx_k24__pyx_f_9_speedups_extClassMRO:f(0,1)__pyx_self:p(0,1)__pyx_args:p(0,1)__pyx_kwds:p(0,1)__pyx_v_ob:(0,1)__pyx_v_extendedClassic:(0,1)__pyx_v_mro:r(0,1)__pyx_r:r(0,1)__pyx_1:r(0,1)__pyx_2:r(0,9)__pyx_argnames:V(0,158):t(0,158)=ar(0,5);0;2;(0,6)__pyx_args:r(0,1)__pyx_kwds:r(0,1)___pyx_f_9_speedups__adapt___pyx_v_9_speedups___conform___pyx_v_9_speedups___adapt___pyx_v_9_speedups__marker__pyx_f_9_speedups__adapt:f(0,1)__pyx_v_obj:p(0,1)__pyx_v_protocol:p(0,1)__pyx_v_default:p(0,1)__pyx_v_meth:r(0,1)__pyx_v_result:(0,1)__pyx_v_err:(0,1)__pyx_r:r(0,1)__pyx_1:r(0,9)__pyx_2:r(0,1)__pyx_3:(0,1)__pyx_4:(0,1)name:r(0,1)name:r(0,1)name:r(0,1)name:r(0,1)name:r(0,1)name:r(0,1)name:r(0,1)name:(0,1)name:r(0,1)name:(0,1)___pyx_argnames.7479___pyx_k22__pyx_f_9_speedups_Protocol__call__:f(0,1)__pyx_self:p(0,1)__pyx_args:p(0,1)__pyx_kwds:p(0,1)__pyx_v_self:(0,1)__pyx_v_ob:(0,1)__pyx_v_default:(0,1)__pyx_r:r(0,1)__pyx_1:r(0,1)__pyx_argnames:V(0,159):t(0,159)=ar(0,5);0;3;(0,6)__pyx_args:r(0,1)__pyx_kwds:r(0,1)___pyx_argnames.7431___pyx_k21__pyx_f_9_speedups_adapt:f(0,1)__pyx_self:p(0,1)__pyx_args:p(0,1)__pyx_kwds:p(0,1)__pyx_v_obj:(0,1)__pyx_v_protocol:(0,1)__pyx_v_default:(0,1)__pyx_r:r(0,1)__pyx_1:r(0,1)__pyx_argnames:V(0,160):t(0,160)=ar(0,5);0;3;(0,6)__pyx_args:r(0,1)__pyx_kwds:r(0,1)___pyx_argnames.7567___pyx_k23__pyx_f_9_speedups_classicMRO:f(0,1)__pyx_self:p(0,1)__pyx_args:p(0,1)__pyx_kwds:p(0,1)__pyx_v_ob:(0,1)__pyx_v_extendedClassic:(0,1)__pyx_v_mro:r(0,1)__pyx_r:r(0,1)__pyx_1:r(0,9)__pyx_2:r(0,1)__pyx_3:(0,1)__pyx_4:r(0,1)__pyx_argnames:V(0,161):t(0,161)=ar(0,5);0;2;(0,6)__pyx_args:r(0,1)__pyx_kwds:r(0,1)name:r(0,1)name:r(0,1)___pyx_argnames.7740___pyx_k25___pyx_v_9_speedups___ECType__pyx_f_9_speedups_getMRO:f(0,1)__pyx_self:p(0,1)__pyx_args:p(0,1)__pyx_kwds:p(0,1)__pyx_v_ob:(0,1)__pyx_v_extendedClassic:(0,1)__pyx_r:r(0,1)__pyx_2:(0,1)__pyx_3:r(0,1)__pyx_4:r(0,1)__pyx_argnames:V(0,162):t(0,162)=ar(0,5);0;2;(0,6)__pyx_args:r(0,1)__pyx_kwds:r(0,1)name:r(0,1)name:r(0,1)name:r(0,1)name:r(0,1)___pyx_argnames.7828___pyx_v_9_speedups___mro__pyx_f_9_speedups_Protocol__adapt__:f(0,1)__pyx_self:p(0,1)__pyx_args:p(0,1)__pyx_kwds:p(0,1)__pyx_v_self:(0,1)__pyx_v_obj:(0,1)__pyx_v_i:(0,9)__pyx_v_cls:(0,1)__pyx_v_err:r(0,1)__pyx_v_mro:(0,1)__pyx_v_get:(0,1)__pyx_v_factory:(0,1)__pyx_r:r(0,1)__pyx_1:(0,9)__pyx_2:(0,1)__pyx_3:(0,1)__pyx_4:(0,1)__pyx_6:(0,1)__pyx_argnames:V(0,163):t(0,163)=ar(0,5);0;2;(0,6)__pyx_args:r(0,1)__pyx_kwds:r(0,1)name:r(0,1)name:r(0,1)name:r(0,1)name:r(0,1)init_speedups:F(0,3)__pyx_1:r(0,1)__pyx_2:r(0,1)__pyx_3:r(0,9)__pyx_4:r(0,1)t:r(0,164)t:r(0,165)t:r(0,165)name:r(0,1)name:r(0,1)name:r(0,1)name:r(0,1)name:r(0,1)name:r(0,1)name:r(0,1)name:r(0,1)name:r(0,1)name:r(0,1)name:r(0,1)name:r(0,1)name:r(0,1)name:r(0,1):t(0,164)=*(0,166):t(0,165)=*(0,167)__Pyx_InternTabEntry:t(0,166)=(0,168)__Pyx_StringTabEntry:t(0,167)=(0,169):T(0,168)=s8p:(0,142),0,32;s:(0,6),32,32;;:T(0,169)=s12p:(0,142),0,32;s:(0,6),32,32;n:(0,36),64,32;;__pyx_tp_descr_set_9_speedups_metamethod:f(0,9)o:p(0,1)i:p(0,1)v:p(0,1)__pyx_1:r(0,1)__pyx_2:r(0,1)__pyx_3:(0,1)name:r(0,1)__pyx_1:r(0,1)__pyx_2:r(0,1)__pyx_3:(0,1)__pyx_1:r(0,1)__pyx_2:r(0,1)__pyx_3:(0,1)__pyx_1:r(0,1)__pyx_2:r(0,1)__pyx_3:(0,1)name:r(0,1)__pyx_1:r(0,1)__pyx_2:r(0,1)__pyx_3:(0,1)__pyx_1:r(0,1)__pyx_2:r(0,1)__pyx_3:(0,1)__pyx_1:r(0,1)__pyx_2:r(0,1)__pyx_3:(0,1)name:r(0,1)__pyx_1:r(0,1)__pyx_2:r(0,1)__pyx_3:(0,1)name:r(0,1)__pyx_m:S(0,1)__pyx_b:S(0,1)__pyx_lineno:S(0,9)__pyx_filename:S(0,6)char:t(0,8)__pyx_f:S(0,170):t(0,170)=*(0,6)__pyx_mdoc:S(0,171)__pyx_ptype_9_speedups_metamethod:S(0,123)__pyx_v_9_speedups__marker:S(0,1)__pyx_v_9_speedups___conform:S(0,1)__pyx_v_9_speedups___adapt:S(0,1)__pyx_v_9_speedups___mro:S(0,1)__pyx_v_9_speedups___ECType:S(0,1)__pyx_k19:S(0,1)__pyx_k20:S(0,1)__pyx_k21:S(0,1)__pyx_k22:S(0,1)__pyx_k23:S(0,1)__pyx_k24:S(0,1)__pyx_k25:S(0,1)__pyx_k11:S(0,172)__pyx_k15:S(0,173)__pyx_k16:S(0,174)__pyx_k17:S(0,175)__pyx_k18:S(0,176)__pyx_n___all__:S(0,1)__pyx_n_exc_info:S(0,1)__pyx_n_AdaptationFailure:S(0,1)__pyx_n_ExtensionClass:S(0,1)__pyx_n___class:S(0,1)__pyx_n_NO_ADAPTER_NEEDED:S(0,1)__pyx_n_DOES_NOT_SUPPORT:S(0,1)__pyx_n_adapt:S(0,1)__pyx_n_Protocol__call__:S(0,1)__pyx_n_classicMRO:S(0,1)__pyx_n_extClassMRO:S(0,1)__pyx_n_getMRO:S(0,1)__pyx_n_Protocol__adapt__:S(0,1)__pyx_n_metamethod:S(0,1)__pyx_n_sys:S(0,1)__pyx_n_ImportError:S(0,1)__pyx_n_object:S(0,1)__pyx_n_False:S(0,1)__pyx_k11p:S(0,1)__pyx_doc_9_speedups_NO_ADAPTER_NEEDED:S(0,177)__pyx_doc_9_speedups_DOES_NOT_SUPPORT:S(0,178)__pyx_n_AttributeError:S(0,1)__pyx_k26p:S(0,1)__pyx_k26:S(0,179)__pyx_k27p:S(0,1)__pyx_k27:S(0,180)__pyx_n_TypeError:S(0,1)__pyx_n_tb_next:S(0,1)__pyx_k28p:S(0,1)__pyx_k28:S(0,181)__pyx_doc_9_speedups_adapt:S(0,182)__pyx_doc_9_speedups_Protocol__call__:S(0,183)__pyx_k29p:S(0,1)__pyx_k29:S(0,184)__pyx_n___bases__:S(0,1)__pyx_n___mro__:S(0,1)__pyx_n__Protocol__adapters:S(0,1)__pyx_n_get:S(0,1)__pyx_intern_tab:S(0,185)__pyx_string_tab:S(0,186)__pyx_methods_9_speedups_metamethod:S(0,187)__pyx_tp_as_number_metamethod:S(0,63)__pyx_tp_as_sequence_metamethod:S(0,64)__pyx_tp_as_mapping_metamethod:S(0,65)__pyx_tp_as_buffer_metamethod:S(0,70)__pyx_methods:S(0,188)__pyx_filenames:S(0,189)__pyx_type_9_speedups_metamethod:G(0,124):t(0,171)=ar(0,5);0;39;(0,8):t(0,172)=ar(0,5);0;18;(0,8):t(0,173)=ar(0,5);0;11;(0,8):t(0,174)=ar(0,5);0;9;(0,8):t(0,175)=ar(0,5);0;9;(0,8):t(0,176)=ar(0,5);0;7;(0,8):t(0,177)=ar(0,5);0;43;(0,8):t(0,178)=ar(0,5);0;40;(0,8):t(0,179)=ar(0,5);0;19;(0,8):t(0,180)=ar(0,5);0;19;(0,8):t(0,181)=ar(0,5);0;11;(0,8):t(0,182)=ar(0,5);0;155;(0,8):t(0,183)=ar(0,5);0;22;(0,8):t(0,184)=ar(0,5);0;19;(0,8):t(0,185)=ar(0,5);0;25;(0,166):t(0,186)=ar(0,5);0;5;(0,167):t(0,187)=ar(0,5);0;0;(0,74):t(0,188)=ar(0,5);0;8;(0,74):t(0,189)=ar(0,5);0;0;(0,6)PK˃95-\OOprotocols/adapters.py"""Basic Adapters and Adapter Operations""" __all__ = [ 'NO_ADAPTER_NEEDED','DOES_NOT_SUPPORT', 'Adapter', 'minimumAdapter', 'composeAdapters', 'updateWithSimplestAdapter', 'StickyAdapter', 'AdaptationFailure', 'bindAdapter', ] from types import FunctionType,ClassType,MethodType try: PendingDeprecationWarning except NameError: class PendingDeprecationWarning(Warning): 'Base class for warnings about features which will be deprecated in the future.' class AdaptationFailure(NotImplementedError,TypeError): """A suitable implementation/adapter could not be found""" # Fundamental Adapters def NO_ADAPTER_NEEDED(obj, protocol=None): """Assume 'obj' implements 'protocol' directly""" return obj def DOES_NOT_SUPPORT(obj, protocol=None): """Prevent 'obj' from supporting 'protocol'""" return None try: from _speedups import NO_ADAPTER_NEEDED, DOES_NOT_SUPPORT except ImportError: pass class Adapter(object): """Convenient base class for adapters""" def __init__(self, ob): self.subject = ob class StickyAdapter(object): """Adapter that attaches itself to its subject for repeated use""" attachForProtocols = () def __init__(self, ob): self.subject = ob # Declare this instance as a per-instance adaptation for the # given protocols provides = list(self.attachForProtocols) from protocols.api import declareAdapter declareAdapter(lambda s: self, provides, forObjects=[ob]) # Adapter "arithmetic" def minimumAdapter(a1,a2,d1=0,d2=0): """Shortest route to implementation, 'a1' @ depth 'd1', or 'a2' @ 'd2'? Assuming both a1 and a2 are interchangeable adapters (i.e. have the same source and destination protocols), return the one which is preferable; that is, the one with the shortest implication depth, or, if the depths are equal, then the adapter that is composed of the fewest chained adapters. If both are the same, then prefer 'NO_ADAPTER_NEEDED', followed by anything but 'DOES_NOT_SUPPORT', with 'DOES_NOT_SUPPORT' being least preferable. If there is no unambiguous choice, and 'not a1 is a2', TypeError is raised. """ if d1=maxargs: newAdapter = lambda ob: adapter(ob,proto) newAdapter.__adapterCount__ = getattr( adapter,'__adapterCount__',1 ) newAdapter.__unbound_adapter__ = adapter from warnings import warn warn("Adapter %r to protocol %r needs multiple arguments" % (adapter,proto), PendingDeprecationWarning, 6) return newAdapter return adapter def updateWithSimplestAdapter(mapping, key, adapter, depth): """Replace 'mapping[key]' w/'adapter' @ 'depth', return true if changed""" new = adapter old = mapping.get(key) if old is not None: old, oldDepth = old new = minimumAdapter(old,adapter,oldDepth,depth) if old is new and depth>=oldDepth: return False mapping[key] = new, depth return True PK86jR\protocols/adapters.pyc; Ec @s,dZddddddddd g Zd klZlZlZyeWn)ej od efd YZnXde e fd YZ e dZ e dZydkl Z lZWnej onXdefdYZdefdYZdddZdZdZdZdS(s%Basic Adapters and Adapter OperationssNO_ADAPTER_NEEDEDsDOES_NOT_SUPPORTsAdaptersminimumAdapterscomposeAdapterssupdateWithSimplestAdapters StickyAdaptersAdaptationFailures bindAdapter(s FunctionTypes ClassTypes MethodTypesPendingDeprecationWarningcBstZdZRS(sNBase class for warnings about features which will be deprecated in the future.(s__name__s __module__s__doc__(((s7build/bdist.darwin-8.9.1-i386/egg/protocols/adapters.pysPendingDeprecationWarnings cBstZdZRS(s4A suitable implementation/adapter could not be found(s__name__s __module__s__doc__(((s7build/bdist.darwin-8.9.1-i386/egg/protocols/adapters.pysAdaptationFailures cCs|SdS(s+Assume 'obj' implements 'protocol' directlyN(sobj(sobjsprotocol((s7build/bdist.darwin-8.9.1-i386/egg/protocols/adapters.pysNO_ADAPTER_NEEDEDscCstSdS(s(Prevent 'obj' from supporting 'protocol'N(sNone(sobjsprotocol((s7build/bdist.darwin-8.9.1-i386/egg/protocols/adapters.pysDOES_NOT_SUPPORTs(sNO_ADAPTER_NEEDEDsDOES_NOT_SUPPORTcBstZdZdZRS(s"Convenient base class for adapterscCs ||_dS(N(sobsselfssubject(sselfsob((s7build/bdist.darwin-8.9.1-i386/egg/protocols/adapters.pys__init__.s(s__name__s __module__s__doc__s__init__(((s7build/bdist.darwin-8.9.1-i386/egg/protocols/adapters.pysAdapter*s cBstZdZfZdZRS(s<Adapter that attaches itself to its subject for repeated usecsE|_ti}dkl}|d|d|gdS(N(sdeclareAdaptercsS(N(sself(ss(sself(s7build/bdist.darwin-8.9.1-i386/egg/protocols/adapters.pysBss forObjects(sobsselfssubjectslistsattachForProtocolssprovidess protocols.apisdeclareAdapter(sselfsobsdeclareAdaptersprovides((sselfs7build/bdist.darwin-8.9.1-i386/egg/protocols/adapters.pys__init__8s  (s__name__s __module__s__doc__sattachForProtocolss__init__(((s7build/bdist.darwin-8.9.1-i386/egg/protocols/adapters.pys StickyAdapter2s icCs||jo|Sn||jo|Snt|d|t|d|jo|Snt|dd}t|dd}||jo|Sn||jo|Sn|tjp |tjo|Sn|tjp |tjo|Snt d||||dS(spShortest route to implementation, 'a1' @ depth 'd1', or 'a2' @ 'd2'? Assuming both a1 and a2 are interchangeable adapters (i.e. have the same source and destination protocols), return the one which is preferable; that is, the one with the shortest implication depth, or, if the depths are equal, then the adapter that is composed of the fewest chained adapters. If both are the same, then prefer 'NO_ADAPTER_NEEDED', followed by anything but 'DOES_NOT_SUPPORT', with 'DOES_NOT_SUPPORT' being least preferable. If there is no unambiguous choice, and 'not a1 is a2', TypeError is raised. s__unbound_adapter__s__adapterCount__isAmbiguous adapter choiceN( sd1sd2sa1sa2sgetattrsa1ctsa2ctsNO_ADAPTER_NEEDEDsDOES_NOT_SUPPORTs TypeError(sa1sa2sd1sd2sa2ctsa1ct((s7build/bdist.darwin-8.9.1-i386/egg/protocols/adapters.pysminimumAdapterUs$   %  cstjp tjotSntjoSntjoSnd}tddtdd|_|SdS(s:Return the composition of 'baseAdapter'+'extendingAdapter'cs+|}|tj o|SndS(N(s baseAdaptersobsNonesextendingAdapter(sob(sextendingAdapters baseAdapter(s7build/bdist.darwin-8.9.1-i386/egg/protocols/adapters.pys newAdapters  s__adapterCount__iN(s baseAdaptersDOES_NOT_SUPPORTsextendingAdaptersNO_ADAPTER_NEEDEDs newAdaptersgetattrs__adapterCount__(s baseAdapters baseProtocolsextendingAdapters newAdapter((s baseAdaptersextendingAdapters7build/bdist.darwin-8.9.1-i386/egg/protocols/adapters.pyscomposeAdapters|s  %c s~d} }d}xt|t o|ot|to&| |itj 7} |i }d}qt|t t fo!| d7} |i }|d8}q|i }|d8}qWt|todkl}||\}} }}|o|t| }nt|| jo\d} tdd| _| _dkl}|dftd | SqvnSd S( sEBackward compatibility: wrap 'adapter' to support old 2-arg signatureii i(s getargspeccs |S(N(sadaptersobsproto(sob(sadaptersproto(s7build/bdist.darwin-8.9.1-i386/egg/protocols/adapters.pysss__adapterCount__(swarns2Adapter %r to protocol %r needs multiple argumentsiN(smaxargssadaptersfstriess isinstances FunctionTypes MethodTypesim_selfsNonesim_funcs ClassTypestypes__init__s__call__sinspects getargspecsargssvarargssvarkwsdefaultsslens newAdaptersgetattrs__adapterCount__s__unbound_adapter__swarningsswarnsprotosPendingDeprecationWarning( sadaptersprotos getargspecsdefaultssargssfswarnstriessvarkws newAdaptersvarargssmaxargs((sadaptersprotos7build/bdist.darwin-8.9.1-i386/egg/protocols/adapters.pys bindAdapters8          cCs|}|i|}|tj oG|\}}t||||}||jo ||jot Sqin||f||UsN(sproperty(sfunc((sfuncs5build/bdist.darwin-8.9.1-i386/egg/protocols/advice.pys metamethodSs(sExtensionClassccsg}|i}|i}|d|xF|o>|}|Vt|}x|iD]}|||qRWq(W|o t Vt VndS(Ni( sstacksinsertspushspopsobsclsslensps __bases__sbsextendedClassics InstanceTypesobject(sobsextendedClassicsbspopspspushsstackscls((s5build/bdist.darwin-8.9.1-i386/egg/protocols/advice.pys classicMRO^s      cCsGt|tot||Snt|to |iSn|fSdS(N(s isinstancesobs ClassicTypess classicMROsextendedClassicstypes__mro__(sobsextendedClassic((s5build/bdist.darwin-8.9.1-i386/egg/protocols/advice.pysgetMROls  (s metamethodsgetMROs classicMROcst}|ijo}|intx\D]B}|jo/gi}D]}||i qi~PqHqHWt d|tdt fdY}|SdS(NsNot sub/supertypes:stheSupercstZdZRS(Ncstx]D]U}||joB||}y |i}Wntj o |Sq\X|SqqWti ||SdS(N( smrosdsnamesdescrs__get__sAttributeErrorsobstypsobjects__getattribute__sself(sselfsnamesdescrsd(stypsobsmro(s5build/bdist.darwin-8.9.1-i386/egg/protocols/advice.pys__getattribute__s    (s__name__s __module__s__getattribute__((sobsmrostyp(s5build/bdist.darwin-8.9.1-i386/egg/protocols/advice.pystheSupers(stypesobs starttypes__mro__smrostypsitersclssappends_[1]s__dict__s TypeErrorsobjectstheSuper(stypsobstheSupers_[1]smros starttypescls((stypsobsmros5build/bdist.darwin-8.9.1-i386/egg/protocols/advice.pys supermeta~s      *  cCsdkl}|dtdgi}|D]!}|tj o||q+q+~}g}xl|D]d}x[|D](}t ||o ||j oPqoqoW||jo|i |n|i|qbW|SdS(s DEPRECATED(swarnsAprotocols.advice.minimalBases is deprecated; please do not use itiN( swarningsswarnsDeprecationWarningsappends_[1]sclassesscs ClassTypes candidatessmsns issubclasssremove(sclassess_[1]scsmsnswarns candidates((s5build/bdist.darwin-8.9.1-i386/egg/protocols/advice.pys minimalBasess   8  (srefcBsAtZdZdZdZdZdZdZdZRS(s/Like a weakref, but for non-weakrefable objectssreferentcCs ||_dS(N(sreferentsself(sselfsreferent((s5build/bdist.darwin-8.9.1-i386/egg/protocols/advice.pys__init__scCs |iSdS(N(sselfsreferent(sself((s5build/bdist.darwin-8.9.1-i386/egg/protocols/advice.pys__call__scCst|iSdS(N(shashsselfsreferent(sself((s5build/bdist.darwin-8.9.1-i386/egg/protocols/advice.pys__hash__scCs|i|jSdS(N(sselfsreferentsother(sselfsother((s5build/bdist.darwin-8.9.1-i386/egg/protocols/advice.pys__eq__scCsd|iSdS(Ns StrongRef(%r)(sselfsreferent(sself((s5build/bdist.darwin-8.9.1-i386/egg/protocols/advice.pys__repr__s( s__name__s __module__s__doc__s __slots__s__init__s__call__s__hash__s__eq__s__repr__(((s5build/bdist.darwin-8.9.1-i386/egg/protocols/advice.pys StrongRefs     cGs5yt||SWntj ot|SnXdS(swReturn either a weakref or a StrongRef for 'ob' Note that extra args are forwarded to weakref.ref() if applicable.N(srefsobsargss TypeErrors StrongRef(sobsargs((s5build/bdist.darwin-8.9.1-i386/egg/protocols/advice.pysmkRefs (!s __future__s generatorssnewsinstancemethodstypess ClassTypes FunctionTypes InstanceTypessyss__all__s peak.utils decoratorssNonesaddClassAdvisorsadd_assignment_advisors getFrameInfosdetermineMetaclasssisClassAdvisors metamethodsExtensionClasss ImportErrors ClassicTypessFalses classicMROsgetMROs _speedupss supermetas minimalBasessweakrefsrefsobjects StrongRefsmkRef(s minimalBasessisClassAdvisors__all__s metamethods StrongRefs generatorssaddClassAdvisorsgetMROs decoratorss InstanceTypes getFrameInfosdetermineMetaclassssyssmkRefs ClassicTypessrefs classicMROsadd_assignment_advisorsinstancemethodsExtensionClasss ClassTypes supermetas FunctionType((s5build/bdist.darwin-8.9.1-i386/egg/protocols/advice.pys?s6   *&         ' ) PKOk6%$zcprotocols/api.py"""Adapter and Declaration API""" __all__ = [ 'adapt', 'declareAdapterForType', 'declareAdapterForProtocol', 'declareAdapterForObject', 'advise', 'declareImplementation', 'declareAdapter', 'adviseObject', ] _marker = object() from sys import _getframe, exc_info, modules from types import ClassType ClassTypes = ClassType, type from adapters import NO_ADAPTER_NEEDED, DOES_NOT_SUPPORT, AdaptationFailure from adapters import bindAdapter from peak.util.decorators import decorate_class, frameinfo from interfaces import IOpenProtocol, IOpenProvider, IOpenImplementor from interfaces import Protocol, InterfaceClass def adapt(obj, protocol, default=_marker): """PEP 246-alike: Adapt 'obj' to 'protocol', return 'default' If 'default' is not supplied and no implementation is found, the result of 'factory(obj,protocol)' is returned. If 'factory' is also not supplied, 'NotImplementedError' is then raised.""" if isinstance(protocol,ClassTypes) and isinstance(obj,protocol): return obj try: _conform = obj.__conform__ except AttributeError: pass else: try: result = _conform(protocol) if result is not None: return result except TypeError: if exc_info()[2].tb_next is not None: raise try: _adapt = protocol.__adapt__ except AttributeError: pass else: try: result = _adapt(obj) if result is not None: return result except TypeError: if exc_info()[2].tb_next is not None: raise if default is _marker: raise AdaptationFailure("Can't adapt", obj, protocol) return default try: from _speedups import adapt except ImportError: pass # Fundamental, explicit interface/adapter declaration API: # All declarations should end up passing through these three routines. def declareAdapterForType(protocol, adapter, typ, depth=1): """Declare that 'adapter' adapts instances of 'typ' to 'protocol'""" adapter = bindAdapter(adapter,protocol) adapter = adapt(protocol, IOpenProtocol).registerImplementation( typ, adapter, depth ) oi = adapt(typ, IOpenImplementor, None) if oi is not None: oi.declareClassImplements(protocol,adapter,depth) def declareAdapterForProtocol(protocol, adapter, proto, depth=1): """Declare that 'adapter' adapts 'proto' to 'protocol'""" adapt(protocol, IOpenProtocol) # src and dest must support IOpenProtocol adapt(proto, IOpenProtocol).addImpliedProtocol(protocol, bindAdapter(adapter,protocol), depth) def declareAdapterForObject(protocol, adapter, ob, depth=1): """Declare that 'adapter' adapts 'ob' to 'protocol'""" adapt(protocol,IOpenProtocol).registerObject(ob,bindAdapter(adapter,protocol),depth) # Bootstrap APIs to work with Protocol and InterfaceClass, without needing to # give Protocol a '__conform__' method that's hardwired to IOpenProtocol. # Note that InterfaceClass has to be registered first, so that when the # registration propagates to IAdaptingProtocol and IProtocol, InterfaceClass # will already be recognized as an IOpenProtocol, preventing infinite regress. IOpenProtocol.registerImplementation(InterfaceClass) # VERY BAD!! IOpenProtocol.registerImplementation(Protocol) # NEVER DO THIS!! # From this line forward, the declaration APIs can work. Use them instead! # Interface and adapter declarations - convenience forms, explicit targets def declareAdapter(factory, provides, forTypes=(), forProtocols=(), forObjects=() ): """'factory' is an IAdapterFactory providing 'provides' protocols""" for protocol in provides: for typ in forTypes: declareAdapterForType(protocol, factory, typ) for proto in forProtocols: declareAdapterForProtocol(protocol, factory, proto) for ob in forObjects: declareAdapterForObject(protocol, factory, ob) def declareImplementation(typ, instancesProvide=(), instancesDoNotProvide=()): """Declare information about a class, type, or 'IOpenImplementor'""" for proto in instancesProvide: declareAdapterForType(proto, NO_ADAPTER_NEEDED, typ) for proto in instancesDoNotProvide: declareAdapterForType(proto, DOES_NOT_SUPPORT, typ) def adviseObject(ob, provides=(), doesNotProvide=()): """Tell an object what it does or doesn't provide""" for proto in provides: declareAdapterForObject(proto, NO_ADAPTER_NEEDED, ob) for proto in doesNotProvide: declareAdapterForObject(proto, DOES_NOT_SUPPORT, ob) # And now for the magic function... def advise(**kw): kw = kw.copy() frame = _getframe(1) kind, module, caller_locals, caller_globals = frameinfo(frame) if kind=="module": moduleProvides = kw.setdefault('moduleProvides',()) del kw['moduleProvides'] for k in kw: raise TypeError( "Invalid keyword argument for advising modules: %s" % k ) adviseObject(module, provides=moduleProvides ) return elif kind != "class": raise SyntaxError( "protocols.advise() must be called directly in a class or" " module body, not in a function or exec." ) classProvides = kw.setdefault('classProvides',()) classDoesNotProvide = kw.setdefault('classDoesNotProvide',()) instancesProvide = kw.setdefault('instancesProvide',()) instancesDoNotProvide = kw.setdefault('instancesDoNotProvide',()) asAdapterForTypes = kw.setdefault('asAdapterForTypes',()) asAdapterForProtocols = kw.setdefault('asAdapterForProtocols',()) protocolExtends = kw.setdefault('protocolExtends',()) protocolIsSubsetOf = kw.setdefault('protocolIsSubsetOf',()) factoryMethod = kw.setdefault('factoryMethod',None) equivalentProtocols = kw.setdefault('equivalentProtocols',()) map(kw.__delitem__,"classProvides classDoesNotProvide instancesProvide" " instancesDoNotProvide asAdapterForTypes asAdapterForProtocols" " protocolExtends protocolIsSubsetOf factoryMethod equivalentProtocols" .split()) for k in kw: raise TypeError( "Invalid keyword argument for advising classes: %s" % k ) def callback(klass): if classProvides or classDoesNotProvide: adviseObject(klass, provides=classProvides, doesNotProvide=classDoesNotProvide ) if instancesProvide or instancesDoNotProvide: declareImplementation(klass, instancesProvide=instancesProvide, instancesDoNotProvide=instancesDoNotProvide ) if asAdapterForTypes or asAdapterForProtocols: if not instancesProvide: raise TypeError( "When declaring an adapter, you must specify what" " its instances will provide." ) if factoryMethod: factory = getattr(klass,factoryMethod) else: factory = klass declareAdapter(factory, instancesProvide, forTypes=asAdapterForTypes, forProtocols=asAdapterForProtocols ) elif factoryMethod: raise TypeError( "'factoryMethod' is only used when declaring an adapter type" ) if protocolExtends: declareAdapter(NO_ADAPTER_NEEDED, protocolExtends, forProtocols=[klass] ) if protocolIsSubsetOf: declareAdapter(NO_ADAPTER_NEEDED, [klass], forProtocols=protocolIsSubsetOf ) if equivalentProtocols: declareAdapter( NO_ADAPTER_NEEDED, equivalentProtocols, forProtocols=[klass] ) declareAdapter( NO_ADAPTER_NEEDED, [klass], forProtocols=equivalentProtocols ) return klass decorate_class(callback) PK86v_i&&protocols/api.pyc; (Ec@srdZddddddddgZeZd klZlZlZd kl Z e e fZ d k l Z lZlZd k lZd klZlZdklZlZlZdklZlZedZydklZWnej onXddZddZddZei eei efffdZ!ffdZ"ffdZ#dZ$dS(sAdapter and Declaration APIsadaptsdeclareAdapterForTypesdeclareAdapterForProtocolsdeclareAdapterForObjectsadvisesdeclareImplementationsdeclareAdapters adviseObject(s _getframesexc_infosmodules(s ClassType(sNO_ADAPTER_NEEDEDsDOES_NOT_SUPPORTsAdaptationFailure(s bindAdapter(sdecorate_classs frameinfo(s IOpenProtocols IOpenProvidersIOpenImplementor(sProtocolsInterfaceClasscCsKt|to t||o|Sny |i}Wntj on[Xy%||}|tj o|SnWn1t j o%t di tj oqnXy |i }Wntj on[Xy%||}|tj o|SnWn1t j o%t di tj oq nX|tjotd||n|SdS(sPEP 246-alike: Adapt 'obj' to 'protocol', return 'default' If 'default' is not supplied and no implementation is found, the result of 'factory(obj,protocol)' is returned. If 'factory' is also not supplied, 'NotImplementedError' is then raised.is Can't adaptN(s isinstancesprotocols ClassTypessobjs __conform__s_conformsAttributeErrorsresultsNones TypeErrorsexc_infostb_nexts __adapt__s_adaptsdefaults_markersAdaptationFailure(sobjsprotocolsdefaults_conformsresults_adapt((s2build/bdist.darwin-8.9.1-i386/egg/protocols/api.pysadapt*s8            (sadapticCsgt||}t|ti|||}t|tt }|t j o|i |||ndS(s>Declare that 'adapter' adapts instances of 'typ' to 'protocol'N( s bindAdaptersadaptersprotocolsadapts IOpenProtocolsregisterImplementationstypsdepthsIOpenImplementorsNonesoisdeclareClassImplements(sprotocolsadapterstypsdepthsoi((s2build/bdist.darwin-8.9.1-i386/egg/protocols/api.pysdeclareAdapterForType[s  cCs6t|tt|ti|t|||dS(s3Declare that 'adapter' adapts 'proto' to 'protocol'N(sadaptsprotocols IOpenProtocolsprotosaddImpliedProtocols bindAdaptersadaptersdepth(sprotocolsadaptersprotosdepth((s2build/bdist.darwin-8.9.1-i386/egg/protocols/api.pysdeclareAdapterForProtocolhs cCs)t|ti|t|||dS(s0Declare that 'adapter' adapts 'ob' to 'protocol'N(sadaptsprotocols IOpenProtocolsregisterObjectsobs bindAdaptersadaptersdepth(sprotocolsadaptersobsdepth((s2build/bdist.darwin-8.9.1-i386/egg/protocols/api.pysdeclareAdapterForObjectnsc Csxxq|D]i}x|D]}t|||qWx|D]}t|||q5Wx|D]}t |||qVWqWdS(s>'factory' is an IAdapterFactory providing 'provides' protocolsN( sprovidessprotocolsforTypesstypsdeclareAdapterForTypesfactorys forProtocolssprotosdeclareAdapterForProtocols forObjectssobsdeclareAdapterForObject( sfactorysprovidessforTypess forProtocolss forObjectssobsprotocolsprotostyp((s2build/bdist.darwin-8.9.1-i386/egg/protocols/api.pysdeclareAdapter~scCsFx|D]}t|t|qWx|D]}t|t|q(WdS(s>Declare information about a class, type, or 'IOpenImplementor'N(sinstancesProvidesprotosdeclareAdapterForTypesNO_ADAPTER_NEEDEDstypsinstancesDoNotProvidesDOES_NOT_SUPPORT(stypsinstancesProvidesinstancesDoNotProvidesproto((s2build/bdist.darwin-8.9.1-i386/egg/protocols/api.pysdeclareImplementationscCsFx|D]}t|t|qWx|D]}t|t|q(WdS(s.Tell an object what it does or doesn't provideN(sprovidessprotosdeclareAdapterForObjectsNO_ADAPTER_NEEDEDsobsdoesNotProvidesDOES_NOT_SUPPORT(sobsprovidessdoesNotProvidesproto((s2build/bdist.darwin-8.9.1-i386/egg/protocols/api.pys adviseObjectsc s|i}td}t|\} }}}| djoR|i df} |d=x|D]}t d|q]Wt |d| dSn| djotdn|i df|i d f|i d f|i d f|i d f|i d f|i df|i df |i dt|i dft|idix|D]}t d|q}W d}t|dS(NismodulesmoduleProvidess1Invalid keyword argument for advising modules: %ssprovidessclasss`protocols.advise() must be called directly in a class or module body, not in a function or exec.s classProvidessclassDoesNotProvidesinstancesProvidesinstancesDoNotProvidesasAdapterForTypessasAdapterForProtocolssprotocolExtendssprotocolIsSubsetOfs factoryMethodsequivalentProtocolssclassProvides classDoesNotProvide instancesProvide instancesDoNotProvide asAdapterForTypes asAdapterForProtocols protocolExtends protocolIsSubsetOf factoryMethod equivalentProtocolss1Invalid keyword argument for advising classes: %scsKp ot|dd npot|ddnpoU ot dnot |}n|}t |ddnot dnot td|gnot t|gdno0t td|gt t|gdn|SdS( NsprovidessdoesNotProvidesinstancesProvidesinstancesDoNotProvidesLWhen declaring an adapter, you must specify what its instances will provide.sforTypess forProtocolss;'factoryMethod' is only used when declaring an adapter type(s classProvidessclassDoesNotProvides adviseObjectsklasssinstancesProvidesinstancesDoNotProvidesdeclareImplementationsasAdapterForTypessasAdapterForProtocolss TypeErrors factoryMethodsgetattrsfactorysdeclareAdaptersprotocolExtendssNO_ADAPTER_NEEDEDsprotocolIsSubsetOfsequivalentProtocols(sklasssfactory( sasAdapterForTypessprotocolExtendssasAdapterForProtocolssequivalentProtocolssinstancesProvides factoryMethodsinstancesDoNotProvides classProvidessprotocolIsSubsetOfsclassDoesNotProvide(s2build/bdist.darwin-8.9.1-i386/egg/protocols/api.pyscallbacks6   (skwscopys _getframesframes frameinfoskindsmodules caller_localsscaller_globalss setdefaultsmoduleProvidessks TypeErrors adviseObjects SyntaxErrors classProvidessclassDoesNotProvidesinstancesProvidesinstancesDoNotProvidesasAdapterForTypessasAdapterForProtocolssprotocolExtendssprotocolIsSubsetOfsNones factoryMethodsequivalentProtocolssmaps __delitem__ssplitscallbacksdecorate_class(skwsframesmodules classProvidessclassDoesNotProvidesasAdapterForTypesscaller_globalss caller_localssinstancesDoNotProvidesasAdapterForProtocolssmoduleProvidessprotocolExtendsskindsequivalentProtocolssinstancesProvidesks factoryMethodscallbacksprotocolIsSubsetOf(( s classProvidessclassDoesNotProvidesasAdapterForTypessinstancesDoNotProvidesasAdapterForProtocolssprotocolExtendssequivalentProtocolssinstancesProvides factoryMethodsprotocolIsSubsetOfs2build/bdist.darwin-8.9.1-i386/egg/protocols/api.pysadvises<     '3N(%s__doc__s__all__sobjects_markerssyss _getframesexc_infosmodulesstypess ClassTypestypes ClassTypessadapterssNO_ADAPTER_NEEDEDsDOES_NOT_SUPPORTsAdaptationFailures bindAdapterspeak.util.decoratorssdecorate_classs frameinfos interfacess IOpenProtocols IOpenProvidersIOpenImplementorsProtocolsInterfaceClasssadapts _speedupss ImportErrorsdeclareAdapterForTypesdeclareAdapterForProtocolsdeclareAdapterForObjectsregisterImplementationsdeclareAdaptersdeclareImplementations adviseObjectsadvise(sdeclareAdapterForTypesdeclareAdapterForObjectsDOES_NOT_SUPPORTsdeclareImplementationsdeclareAdapters IOpenProvidersAdaptationFailures frameinfosdeclareAdapterForProtocolsdecorate_classsadaptsInterfaceClasssadvisesNO_ADAPTER_NEEDEDs_markers bindAdapters ClassTypess adviseObjectsProtocols__all__sIOpenImplementors ClassTypesmoduless _getframesexc_infos IOpenProtocol((s2build/bdist.darwin-8.9.1-i386/egg/protocols/api.pys?s0     )     PK˃95 Kprotocols/classic.py"""Declaration support for Python built-in types""" __all__ = ['ProviderMixin'] from types import FunctionType, ModuleType, InstanceType, ClassType from adapters import * from api import declareImplementation, advise, declareAdapterForObject, adapt from interfaces import * from new import instancemethod from advice import getMRO, metamethod, mkRef class ProviderMixin: """Mixin to support per-instance declarations""" advise( instancesProvide=[IOpenProvider, IImplicationListener] ) def declareProvides(self,protocol,adapter=NO_ADAPTER_NEEDED,depth=1): registry = self.__dict__.get('__protocols_provided__') if registry is None: self.__protocols_provided__ = registry = {} if updateWithSimplestAdapter(registry,protocol,adapter,depth): adapt(protocol,IOpenProtocol).addImplicationListener(self) return True declareProvides = metamethod(declareProvides) def newProtocolImplied(self, srcProto, destProto, adapter, depth): registry = self.__dict__.get('__protocols_provided__',()) if srcProto not in registry: return baseAdapter, d = registry[srcProto] adapter = composeAdapters(baseAdapter,srcProto,adapter) declareAdapterForObject( destProto, adapter, self, depth+d ) newProtocolImplied = metamethod(newProtocolImplied) def __conform__(self,protocol): for cls in getMRO(self): conf = cls.__dict__.get('__protocols_provided__',()) if protocol in conf: return conf[protocol][0](self) __conform__ = metamethod(__conform__) class conformsRegistry(dict): """Helper type for objects and classes that need registration support""" def __call__(self, protocol): # This only gets called for non-class objects if protocol in self: subject = self.subject() if subject is not None: return self[protocol][0](subject) def findImplementation(self, subject, protocol, checkSelf=True): for cls in getMRO(subject): conf = cls.__dict__.get('__conform__') if conf is None: continue if not isinstance(conf,conformsRegistry): raise TypeError( "Incompatible __conform__ in base class", conf, cls ) if protocol in conf: return conf[protocol][0](subject) def newProtocolImplied(self, srcProto, destProto, adapter, depth): subject = self.subject() if subject is None or srcProto not in self: return baseAdapter, d = self[srcProto] adapter = composeAdapters(baseAdapter,srcProto,adapter) declareAdapterForObject( destProto, adapter, subject, depth+d ) def __hash__(self): # Need this because dictionaries aren't hashable, but we need to # be referenceable by a weak-key dictionary return id(self) def __get__(self,ob,typ=None): if ob is not None: raise AttributeError( "__conform__ registry does not pass to instances" ) # Return a bound method that adds the retrieved-from class to the return instancemethod(self.findImplementation, typ, type(typ)) def __getstate__(self): return self.subject(), self.items() def __setstate__(self,(subject,items)): self.clear() self.update(dict(items)) self.subject = mkRef(subject) class MiscObjectsAsOpenProvider(object): """Supply __conform__ registry for funcs, modules, & classic instances""" advise( instancesProvide=[IOpenProvider], asAdapterForTypes=[ FunctionType, ModuleType, InstanceType, ClassType, type, object ] ) def __init__(self,ob): obs = list(getMRO(ob)) for item in obs: try: reg = item.__dict__.get('__conform__') if reg is None and obs==[ob]: # Make sure we don't obscure a method from the class! reg = getattr(item,'__conform__',None) except AttributeError: raise TypeError( "Only objects with dictionaries can use this adapter", ob ) if reg is not None and not isinstance(reg,conformsRegistry): raise TypeError( "Incompatible __conform__ on adapted object", ob, reg ) reg = ob.__dict__.get('__conform__') if reg is None: reg = ob.__conform__ = self.newRegistry(ob) self.ob = ob self.reg = reg def declareProvides(self, protocol, adapter=NO_ADAPTER_NEEDED, depth=1): if updateWithSimplestAdapter(self.reg, protocol, adapter, depth): adapt(protocol,IOpenProtocol).addImplicationListener(self.reg) return True def newRegistry(self,subject): # Create a registry that's also set up for inheriting declarations reg = conformsRegistry() reg.subject = mkRef(subject) return reg PK86IȦ protocols/classic.pyc; Ec@sdZdgZdklZlZlZlZdkTdkl Z l Z l Z l Z dk TdklZdklZlZlZdfdYZdefd YZd efd YZd S( s-Declaration support for Python built-in typess ProviderMixin(s FunctionTypes ModuleTypes InstanceTypes ClassType(s*(sdeclareImplementationsadvisesdeclareAdapterForObjectsadapt(sinstancemethod(sgetMROs metamethodsmkRefcBsftZdZedeegeddZeeZdZ ee Z dZ ee Z RS(s*Mixin to support per-instance declarationssinstancesProvideicCsh|iid}|tjoh|_}nt||||ot |t i |t SndS(Ns__protocols_provided__(sselfs__dict__sgetsregistrysNones__protocols_provided__supdateWithSimplestAdaptersprotocolsadaptersdepthsadapts IOpenProtocolsaddImplicationListenersTrue(sselfsprotocolsadaptersdepthsregistry((s6build/bdist.darwin-8.9.1-i386/egg/protocols/classic.pysdeclareProvides2s  cCsg|iidf}||jodSn||\}}t|||}t |||||dS(Ns__protocols_provided__( sselfs__dict__sgetsregistryssrcProtos baseAdaptersdscomposeAdapterssadaptersdeclareAdapterForObjects destProtosdepth(sselfssrcProtos destProtosadaptersdepthsds baseAdaptersregistry((s6build/bdist.darwin-8.9.1-i386/egg/protocols/classic.pysnewProtocolImplied<s  cCsSxLt|D]>}|iidf}||jo||d|Sq q WdS(Ns__protocols_provided__i(sgetMROsselfsclss__dict__sgetsconfsprotocol(sselfsprotocolsconfscls((s6build/bdist.darwin-8.9.1-i386/egg/protocols/classic.pys __conform__Js   ( s__name__s __module__s__doc__sadvises IOpenProvidersIImplicationListenersNO_ADAPTER_NEEDEDsdeclareProvidess metamethodsnewProtocolImplieds __conform__(((s6build/bdist.darwin-8.9.1-i386/egg/protocols/classic.pys ProviderMixin*s    sconformsRegistrycBsStZdZdZedZdZdZedZ dZ dZ RS(sBHelper type for objects and classes that need registration supportcCsD||jo3|i}|tj o||d|Sq@ndS(Ni(sprotocolsselfssubjectsNone(sselfsprotocolssubject((s6build/bdist.darwin-8.9.1-i386/egg/protocols/classic.pys__call__Ws   cCsxt|D]v}|iid}|tjoq nt|t ot d||n||jo||d|Sq q WdS(Ns __conform__s&Incompatible __conform__ in base classi( sgetMROssubjectsclss__dict__sgetsconfsNones isinstancesconformsRegistrys TypeErrorsprotocol(sselfssubjectsprotocols checkSelfsconfscls((s6build/bdist.darwin-8.9.1-i386/egg/protocols/classic.pysfindImplementationcs   cCsk|i}|tjp ||jodSn||\}}t|||}t|||||dS(N( sselfssubjectsNonessrcProtos baseAdaptersdscomposeAdapterssadaptersdeclareAdapterForObjects destProtosdepth(sselfssrcProtos destProtosadaptersdepthsds baseAdapterssubject((s6build/bdist.darwin-8.9.1-i386/egg/protocols/classic.pysnewProtocolImplied|s  cCst|SdS(N(sidsself(sself((s6build/bdist.darwin-8.9.1-i386/egg/protocols/classic.pys__hash__scCs:|tj otdnt|i|t|SdS(Ns/__conform__ registry does not pass to instances(sobsNonesAttributeErrorsinstancemethodsselfsfindImplementationstypstype(sselfsobstyp((s6build/bdist.darwin-8.9.1-i386/egg/protocols/classic.pys__get__s cCs|i|ifSdS(N(sselfssubjectsitems(sself((s6build/bdist.darwin-8.9.1-i386/egg/protocols/classic.pys __getstate__scCs<|\}}|i|it|t||_dS(N(ssubjectsitemssselfsclearsupdatesdictsmkRef(sselfs.2ssubjectsitems((s6build/bdist.darwin-8.9.1-i386/egg/protocols/classic.pys __setstate__s  ( s__name__s __module__s__doc__s__call__sTruesfindImplementationsnewProtocolImplieds__hash__sNones__get__s __getstate__s __setstate__(((s6build/bdist.darwin-8.9.1-i386/egg/protocols/classic.pysconformsRegistrySs      sMiscObjectsAsOpenProviderc BsWtZdZedegdeeeee e gdZ e ddZ dZRS(sCSupply __conform__ registry for funcs, modules, & classic instancessinstancesProvidesasAdapterForTypescCstt|}x|D]}yI|iid}|tjo ||gjot |dt}nWn"t j ot d|nX|tj ot |t  ot d||qqW|iid}|tjo|i|}|_n||_||_dS(Ns __conform__s3Only objects with dictionaries can use this adapters*Incompatible __conform__ on adapted object(slistsgetMROsobsobssitems__dict__sgetsregsNonesgetattrsAttributeErrors TypeErrors isinstancesconformsRegistrysselfs newRegistrys __conform__(sselfsobsregsitemsobs((s6build/bdist.darwin-8.9.1-i386/egg/protocols/classic.pys__init__s"  icCs>t|i|||o!t|ti|it SndS(N( supdateWithSimplestAdaptersselfsregsprotocolsadaptersdepthsadapts IOpenProtocolsaddImplicationListenersTrue(sselfsprotocolsadaptersdepth((s6build/bdist.darwin-8.9.1-i386/egg/protocols/classic.pysdeclareProvidesscCs t}t||_|SdS(N(sconformsRegistrysregsmkRefssubject(sselfssubjectsreg((s6build/bdist.darwin-8.9.1-i386/egg/protocols/classic.pys newRegistrys (s__name__s __module__s__doc__sadvises IOpenProviders FunctionTypes ModuleTypes InstanceTypes ClassTypestypesobjects__init__sNO_ADAPTER_NEEDEDsdeclareProvidess newRegistry(((s6build/bdist.darwin-8.9.1-i386/egg/protocols/classic.pysMiscObjectsAsOpenProviders   N(s__doc__s__all__stypess FunctionTypes ModuleTypes InstanceTypes ClassTypesadapterssapisdeclareImplementationsadvisesdeclareAdapterForObjectsadapts interfacessnewsinstancemethodsadvicesgetMROs metamethodsmkRefs ProviderMixinsdictsconformsRegistrysobjectsMiscObjectsAsOpenProvider(sdeclareAdapterForObjects__all__s ClassTypes metamethodsconformsRegistrysinstancemethodsgetMROsMiscObjectsAsOpenProviders ProviderMixinsadaptsmkRefsdeclareImplementations ModuleTypes FunctionTypes InstanceTypesadvise((s6build/bdist.darwin-8.9.1-i386/egg/protocols/classic.pys?s  )RPK˃958protocols/generate.py"""Autogenerated protocols from type+method names, URI, sequence, etc.""" from interfaces import Protocol, allocate_lock, Interface from advice import metamethod, supermeta from api import declareAdapterForProtocol, declareAdapterForType from api import declareAdapter, adapt from adapters import NO_ADAPTER_NEEDED __all__ = [ 'protocolForType', 'protocolForURI', 'sequenceOf', 'IBasicSequence', 'URIProtocol', 'TypeSubset', 'WeakSubset', 'ADAPT_SEQUENCE', 'SequenceProtocol' ] class URIProtocol(Protocol): """Protocol representing a URI, UUID, or other unique textual identifier""" def __init__(self,uri): self.URI = uri Protocol.__init__(self) def __repr__(self): return "URIProtocol(%r)" % self.URI def __reduce__(self): return protocolForURI, (self.URI,) class TypeSubset(Protocol): """Protocol representing some set of a type's methods""" def __init__(self,baseType,methods): self.baseType = baseType self.methods = methods Protocol.__init__(self) def __repr__(self): return "TypeSubset(%r,%r)" % (self.baseType,self.methods) def __reduce__(self): return protocolForType, (self.baseType, self.methods, False) class WeakSubset(TypeSubset,object): """TypeSubset that accepts any object with the right attributes""" __metaclass__ = type # new-style so we can use super() def __adapt__(self,ob): result = supermeta(TypeSubset,self).__adapt__(ob) if result is not None: return result for name in self.methods: if not hasattr(ob,name): return None else: return ob __adapt__ = metamethod(__adapt__) def __repr__(self): return "WeakSubset(%r,%r)" % (self.baseType,self.methods) def __reduce__(self): return protocolForType, (self.baseType, self.methods, True) class SequenceProtocol(Protocol): """Protocol representing a "sequence of" some base protocol""" def __init__(self,baseProtocol): self.baseProtocol = baseProtocol Protocol.__init__(self) def __repr__(self): return "sequenceOf(%r)" % self.baseProtocol def __reduce__(self): return sequenceOf, (self.baseProtocol,) class IBasicSequence(Interface): """Non-string, iterable object sequence""" def __iter__(): """Return an iterator over the sequence""" declareAdapter( NO_ADAPTER_NEEDED, provides=[IBasicSequence], forTypes=[list,tuple] ) def ADAPT_SEQUENCE(ob, proto): """Convert iterable 'ob' into list of objects implementing 'proto'""" marker = object() out = [] proto = proto.baseProtocol # get the protocol to adapt to for item in ob: item = adapt(item,proto, marker) if item is marker: return None # can't adapt unless all members adapt out.append(item) return out __registryLock = allocate_lock() registry = {} def protocolForURI(uri): """Return a unique protocol object representing the supplied URI/UUID""" __registryLock.acquire() try: try: return registry[uri] except KeyError: proto = registry[uri] = URIProtocol(uri) return proto finally: __registryLock.release() def protocolForType(baseType, methods=(), implicit=False): """Return a protocol representing a subset of methods of a specific type""" # Normalize 'methods' to a sorted tuple w/no duplicate names methods = dict([(k,k) for k in methods]).keys() methods.sort() methods = tuple(methods) key = baseType, methods, (not not implicit) # ensure implicit is true/false return __protocolForType(key) def sequenceOf(baseProtocol): """Return a protocol representing an sequence of a given base protocol""" key = (sequenceOf, baseProtocol) __registryLock.acquire() try: try: return registry[key] except KeyError: proto = registry[key] = SequenceProtocol(baseProtocol) declareAdapterForProtocol( proto, lambda o: ADAPT_SEQUENCE(o,proto), IBasicSequence ) return proto finally: __registryLock.release() def __protocolForType(key): """Recursive implementation of protocolForType; assumes standardized key""" __registryLock.acquire() try: try: return registry[key] except KeyError: baseType, methods, implicit = key if implicit: proto = WeakSubset(baseType,methods) else: proto = TypeSubset(baseType,methods) registry[key] = proto finally: __registryLock.release() # declare that proto implies all subset-method protocols if len(methods)>1: for method in methods: subset = tuple([m for m in methods if m!=method]) implied = __protocolForType((baseType, subset, implicit)) declareAdapterForProtocol(implied, NO_ADAPTER_NEEDED, proto) # declare that explicit form implies implicit form if implicit: impliedBy = __protocolForType((baseType, methods, False)) declareAdapterForProtocol(proto, NO_ADAPTER_NEEDED, impliedBy) # declare that baseType implements this protocol declareAdapterForType(proto, NO_ADAPTER_NEEDED, baseType) return proto PK86U{qh&h&protocols/generate.pyc; Ec @s\dZdklZlZlZdklZlZdkl Z l Z dkl Z l Z dk lZdddd d d d d dg Zd efdYZd efdYZd eefdYZdefdYZd efdYZe edegdeegdZeZhZdZfedZdZdZdS(sCAutogenerated protocols from type+method names, URI, sequence, etc.(sProtocols allocate_locks Interface(s metamethods supermeta(sdeclareAdapterForProtocolsdeclareAdapterForType(sdeclareAdaptersadapt(sNO_ADAPTER_NEEDEDsprotocolForTypesprotocolForURIs sequenceOfsIBasicSequences URIProtocols TypeSubsets WeakSubsetsADAPT_SEQUENCEsSequenceProtocolcBs)tZdZdZdZdZRS(sEProtocol representing a URI, UUID, or other unique textual identifiercCs||_ti|dS(N(surisselfsURIsProtocols__init__(sselfsuri((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pys__init__s cCsd|iSdS(NsURIProtocol(%r)(sselfsURI(sself((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pys__repr__scCst|iffSdS(N(sprotocolForURIsselfsURI(sself((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pys __reduce__s(s__name__s __module__s__doc__s__init__s__repr__s __reduce__(((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pys URIProtocols   cBs)tZdZdZdZdZRS(s2Protocol representing some set of a type's methodscCs#||_||_ti|dS(N(sbaseTypesselfsmethodssProtocols__init__(sselfsbaseTypesmethods((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pys__init__.s  cCsd|i|ifSdS(NsTypeSubset(%r,%r)(sselfsbaseTypesmethods(sself((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pys__repr__3scCst|i|itffSdS(N(sprotocolForTypesselfsbaseTypesmethodssFalse(sself((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pys __reduce__6s(s__name__s __module__s__doc__s__init__s__repr__s __reduce__(((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pys TypeSubset*s   cBs;tZdZeZdZeeZdZdZRS(s<TypeSubset that accepts any object with the right attributescCsbtt|i|}|tj o|Snx.|iD]}t || otSq7q7W|SdS(N( s supermetas TypeSubsetsselfs __adapt__sobsresultsNonesmethodssnameshasattr(sselfsobsnamesresult((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pys __adapt__Ys   cCsd|i|ifSdS(NsWeakSubset(%r,%r)(sselfsbaseTypesmethods(sself((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pys__repr__iscCst|i|itffSdS(N(sprotocolForTypesselfsbaseTypesmethodssTrue(sself((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pys __reduce__ls( s__name__s __module__s__doc__stypes __metaclass__s __adapt__s metamethods__repr__s __reduce__(((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pys WeakSubsetSs   cBs)tZdZdZdZdZRS(s8Protocol representing a "sequence of" some base protocolcCs||_ti|dS(N(s baseProtocolsselfsProtocols__init__(sselfs baseProtocol((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pys__init__s cCsd|iSdS(NssequenceOf(%r)(sselfs baseProtocol(sself((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pys__repr__scCst|iffSdS(N(s sequenceOfsselfs baseProtocol(sself((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pys __reduce__s(s__name__s __module__s__doc__s__init__s__repr__s __reduce__(((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pysSequenceProtocol|s   cBstZdZdZRS(s$Non-string, iterable object sequencecCsdS(s$Return an iterator over the sequenceN((((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pys__iter__s(s__name__s __module__s__doc__s__iter__(((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pysIBasicSequences sprovidessforTypescCset}g}|i}xB|D]:}t|||}||jotSn|i |qW|SdS(s?Convert iterable 'ob' into list of objects implementing 'proto'N( sobjectsmarkersoutsprotos baseProtocolsobsitemsadaptsNonesappend(sobsprotositemsmarkersout((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pysADAPT_SEQUENCEs   cCsZtiz>y t|SWn+tj ot|}t|<|SnXWdtiXdS(sBReturn a unique protocol object representing the supplied URI/UUIDN(s__registryLocksacquiresregistrysurisKeyErrors URIProtocolsprotosrelease(surisproto((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pysprotocolForURIs   cCsntgi}|D]}|||fq~i}|it|}||| f}t |SdS(sEReturn a protocol representing a subset of methods of a specific typeN( sdictsappends_[1]smethodsskskeysssortstuplesbaseTypesimplicitskeys__protocolForType(sbaseTypesmethodssimplicitsks_[1]skey((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pysprotocolForTypes 9  cs|t|f}tizTy t|SWnAtj o5t|t|sN( s sequenceOfs baseProtocolskeys__registryLocksacquiresregistrysKeyErrorsSequenceProtocolsprotosdeclareAdapterForProtocolsIBasicSequencesrelease(s baseProtocolsprotoskey((sprotos7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pys sequenceOfs    c CsStizhy t|SWnUtj oI|\}}}|ot||}nt ||}|t|N( s__doc__s interfacessProtocols allocate_locks Interfacesadvices metamethods supermetasapisdeclareAdapterForProtocolsdeclareAdapterForTypesdeclareAdaptersadaptsadapterssNO_ADAPTER_NEEDEDs__all__s URIProtocols TypeSubsetsobjects WeakSubsetsSequenceProtocolsIBasicSequencesliststuplesADAPT_SEQUENCEs__registryLocksregistrysprotocolForURIsFalsesprotocolForTypes sequenceOfs__protocolForType(sdeclareAdapterForTypes__registryLocks sequenceOfs__all__s metamethodsdeclareAdapterForProtocolsprotocolForTypes TypeSubsetsadapts InterfacesADAPT_SEQUENCEsSequenceProtocolsIBasicSequences WeakSubsetsprotocolForURIsdeclareAdaptersregistrys__protocolForTypesProtocols allocate_locksNO_ADAPTER_NEEDEDs supermetas URIProtocol((s7build/bdist.darwin-8.9.1-i386/egg/protocols/generate.pys?s* !))  )   )PK˃95)//protocols/interfaces.py"""Implement Interfaces and define the interfaces used by the package""" from __future__ import generators __all__ = [ 'Protocol', 'InterfaceClass', 'Interface', 'AbstractBase', 'AbstractBaseMeta', 'IAdapterFactory', 'IProtocol', 'IAdaptingProtocol', 'IOpenProtocol', 'IOpenProvider', 'IOpenImplementor', 'IImplicationListener', 'Attribute', 'Variation' ] import api from advice import metamethod, classicMRO, mkRef from adapters import composeAdapters, updateWithSimplestAdapter from adapters import NO_ADAPTER_NEEDED, DOES_NOT_SUPPORT from types import InstanceType # Thread locking support try: from thread import allocate_lock except ImportError: try: from dummy_thread import allocate_lock except ImportError: class allocate_lock(object): __slots__ = () def acquire(*args): pass def release(*args): pass # Trivial interface implementation class Protocol: """Generic protocol w/type-based adapter registry""" def __init__(self): self.__adapters = {} self.__implies = {} self.__listeners = None self.__lock = allocate_lock() def getImpliedProtocols(self): # This is messy so it can clean out weakrefs, but this method is only # called for declaration activities and is thus not at all # speed-critical. It's more important that we support weak refs to # implied protocols, so that dynamically created subset protocols can # be garbage collected. out = [] add = out.append self.__lock.acquire() # we might clean out dead weakrefs try: for k,v in self.__implies.items(): proto = k() if proto is None: del self.__implies[k] else: add((proto,v)) return out finally: self.__lock.release() def addImpliedProtocol(self,proto,adapter=NO_ADAPTER_NEEDED,depth=1): self.__lock.acquire() try: key = mkRef(proto) if not updateWithSimplestAdapter( self.__implies, key, adapter, depth ): return self.__implies[key][0] finally: self.__lock.release() # Always register implied protocol with classes, because they should # know if we break the implication link between two protocols for klass,(baseAdapter,d) in self.__adapters.items(): api.declareAdapterForType( proto,composeAdapters(baseAdapter,self,adapter),klass,depth+d ) if self.__listeners: for listener in self.__listeners.keys(): # Must use keys()! listener.newProtocolImplied(self, proto, adapter, depth) return adapter addImpliedProtocol = metamethod(addImpliedProtocol) def registerImplementation(self,klass,adapter=NO_ADAPTER_NEEDED,depth=1): self.__lock.acquire() try: if not updateWithSimplestAdapter( self.__adapters,klass,adapter,depth ): return self.__adapters[klass][0] finally: self.__lock.release() if adapter is DOES_NOT_SUPPORT: # Don't register non-support with implied protocols, because # "X implies Y" and "not X" doesn't imply "not Y". In effect, # explicitly registering DOES_NOT_SUPPORT for a type is just a # way to "disinherit" a superclass' claim to support something. return adapter for proto, (extender,d) in self.getImpliedProtocols(): api.declareAdapterForType( proto, composeAdapters(adapter,self,extender), klass, depth+d ) return adapter registerImplementation = metamethod(registerImplementation) def registerObject(self, ob, adapter=NO_ADAPTER_NEEDED,depth=1): # Object needs to be able to handle registration if api.adapt(ob,IOpenProvider).declareProvides(self,adapter,depth): if adapter is DOES_NOT_SUPPORT: return # non-support doesn't imply non-support of implied # Handle implied protocols for proto, (extender,d) in self.getImpliedProtocols(): api.declareAdapterForObject( proto, composeAdapters(adapter,self,extender), ob, depth+d ) registerObject = metamethod(registerObject) def __adapt__(self, obj): get = self.__adapters.get try: typ = obj.__class__ except AttributeError: typ = type(obj) try: mro = typ.__mro__ except AttributeError: # Note: this adds 'InstanceType' and 'object' to end of MRO mro = classicMRO(typ,extendedClassic=True) for klass in mro: factory=get(klass) if factory is not None: return factory[0](obj) try: from _speedups import Protocol__adapt__ as __adapt__ except ImportError: pass __adapt__ = metamethod(__adapt__) def addImplicationListener(self, listener): self.__lock.acquire() try: if self.__listeners is None: from weakref import WeakKeyDictionary self.__listeners = WeakKeyDictionary() self.__listeners[listener] = 1 finally: self.__lock.release() addImplicationListener = metamethod(addImplicationListener) def __call__(self, ob, default=api._marker): """Adapt to this protocol""" return api.adapt(ob,self,default) # Use faster __call__ method, if possible # XXX it could be even faster if the __call__ were in the tp_call slot # XXX directly, but Pyrex doesn't have a way to do that AFAIK. try: from _speedups import Protocol__call__ except ImportError: pass else: from new import instancemethod Protocol.__call__ = instancemethod(Protocol__call__, None, Protocol) class AbstractBaseMeta(Protocol, type): """Metaclass for 'AbstractBase' - a protocol that's also a class (Note that this should not be used as an explicit metaclass - always subclass from 'AbstractBase' or 'Interface' instead.) """ def __init__(self, __name__, __bases__, __dict__): type.__init__(self, __name__, __bases__, __dict__) Protocol.__init__(self) for b in __bases__: if isinstance(b,AbstractBaseMeta) and b.__bases__<>(object,): self.addImpliedProtocol(b) def __setattr__(self,attr,val): # We could probably support changing __bases__, as long as we checked # that no bases are *removed*. But it'd be a pain, since we'd # have to do callbacks, remove entries from our __implies registry, # etc. So just punt for now. if attr=='__bases__': raise TypeError( "Can't change interface __bases__", self ) type.__setattr__(self,attr,val) __call__ = type.__call__ class AbstractBase(object): """Base class for a protocol that's a class""" __metaclass__ = AbstractBaseMeta class InterfaceClass(AbstractBaseMeta): """Metaclass for 'Interface' - a non-instantiable protocol (Note that this should not be used as an explicit metaclass - always subclass from 'AbstractBase' or 'Interface' instead.) """ def __call__(self, *__args, **__kw): if self.__init__ is Interface.__init__: return Protocol.__call__(self,*__args, **__kw) else: return type.__call__(self,*__args, **__kw) def getBases(self): return [ b for b in self.__bases__ if isinstance(b,AbstractBaseMeta) and b.__bases__<>(object,) ] class Interface(object): __metaclass__ = InterfaceClass class Variation(Protocol): """A variation of a base protocol - "inherits" the base's adapters See the 'LocalProtocol' example in the reference manual for more info. """ def __init__(self, baseProtocol, context = None): self.baseProtocol = baseProtocol self.context = context # Note: Protocol is a ``classic'' class, so we don't use super() Protocol.__init__(self) api.declareAdapterForProtocol(self,NO_ADAPTER_NEEDED,baseProtocol) def __repr__(self): if self.context is None: return "Variation(%r)" % self.baseProtocol return "Variation(%r,%r)" % (self.baseProtocol, self.context) # Semi-backward compatible 'interface.Attribute' class Attribute(object): """Attribute declaration; should we get rid of this?""" def __init__(self,doc,name=None,value=None): self.__doc__ = doc self.name = name self.value = value def __get__(self,ob,typ=None): if ob is None: return self if not self.name: raise NotImplementedError("Abstract attribute") try: return ob.__dict__[self.name] except KeyError: return self.value def __set__(self,ob,val): if not self.name: raise NotImplementedError("Abstract attribute") ob.__dict__[self.name] = val def __delete__(self,ob): if not self.name: raise NotImplementedError("Abstract attribute") del ob.__dict__[self.name] def __repr__(self): return "Attribute: %s" % self.__doc__ # Interfaces and adapters for declaring protocol/type/object relationships class IAdapterFactory(Interface): """Callable that can adapt an object to a protocol""" def __call__(ob): """Return an implementation of protocol for 'ob'""" class IProtocol(Interface): """Object usable as a protocol by 'adapt()'""" def __hash__(): """Protocols must be usable as dictionary keys""" def __eq__(other): """Protocols must be comparable with == and !=""" def __ne__(other): """Protocols must be comparable with == and !=""" class IAdaptingProtocol(IProtocol): """A protocol that potentially knows how to adapt some object to itself""" def __adapt__(ob): """Return 'ob' adapted to protocol, or 'None'""" class IConformingObject(Interface): """An object that potentially knows how to adapt to a protocol""" def __conform__(protocol): """Return an implementation of 'protocol' for self, or 'None'""" class IOpenProvider(Interface): """An object that can be told how to adapt to protocols""" def declareProvides(protocol, adapter=NO_ADAPTER_NEEDED, depth=1): """Register 'adapter' as providing 'protocol' for this object Return a true value if the provided adapter is the "shortest path" to 'protocol' for the object, or false if a shorter path already existed. """ class IOpenImplementor(Interface): """Object/type that can be told how its instances adapt to protocols""" def declareClassImplements(protocol, adapter=NO_ADAPTER_NEEDED, depth=1): """Register 'adapter' as implementing 'protocol' for instances""" class IOpenProtocol(IAdaptingProtocol): """A protocol that be told what it implies, and what supports it Note that these methods are for the use of the declaration APIs only, and you should NEVER call them directly.""" def addImpliedProtocol(proto, adapter=NO_ADAPTER_NEEDED, depth=1): """'adapter' provides conversion from this protocol to 'proto'""" def registerImplementation(klass, adapter=NO_ADAPTER_NEEDED, depth=1): """'adapter' provides protocol for instances of klass""" def registerObject(ob, adapter=NO_ADAPTER_NEEDED, depth=1): """'adapter' provides protocol for 'ob' directly""" def addImplicationListener(listener): """Notify 'listener' whenever protocol has new implied protocol""" class IImplicationListener(Interface): def newProtocolImplied(srcProto, destProto, adapter, depth): """'srcProto' now implies 'destProto' via 'adapter' at 'depth'""" PK86n޿LLprotocols/interfaces.pyc; Ec@sdZdklZdddddddd d d d d ddgZdkZdklZlZlZdk l Z l Z dk l Z l Z dklZydklZWnPej oDydklZWqej odefdYZqXnXdfdYZydklZWnej on$XdklZeeeee_deefdYZdefdYZdefdYZdefdYZ defdYZ!defd YZ"de fd!YZ#de fd"YZ$d e$fd#YZ%d$e fd%YZ&d e fd&YZ'd e fd'YZ(d e%fd(YZ)d e fd)YZ*dS(*sBImplement Interfaces and define the interfaces used by the package(s generatorssProtocolsInterfaceClasss Interfaces AbstractBasesAbstractBaseMetasIAdapterFactorys IProtocolsIAdaptingProtocols IOpenProtocols IOpenProvidersIOpenImplementorsIImplicationListeners Attributes VariationN(s metamethods classicMROsmkRef(scomposeAdapterssupdateWithSimplestAdapter(sNO_ADAPTER_NEEDEDsDOES_NOT_SUPPORT(s InstanceType(s allocate_locks allocate_lockcBs tZfZdZdZRS(NcGsdS(N((sargs((s9build/bdist.darwin-8.9.1-i386/egg/protocols/interfaces.pysacquire!scGsdS(N((sargs((s9build/bdist.darwin-8.9.1-i386/egg/protocols/interfaces.pysrelease"s(s__name__s __module__s __slots__sacquiresrelease(((s9build/bdist.darwin-8.9.1-i386/egg/protocols/interfaces.pys allocate_locks cBstZdZdZdZeddZeeZeddZeeZeddZ ee Z dZ ydk l Z Wne j onXee Z d ZeeZeid ZRS( s.Generic protocol w/type-based adapter registrycCs+h|_h|_t|_t|_dS(N(sselfs_Protocol__adapterss_Protocol__impliessNones_Protocol__listenerss allocate_locks_Protocol__lock(sself((s9build/bdist.darwin-8.9.1-i386/egg/protocols/interfaces.pys__init__0s   cCsg}|i}|iiz\xQ|iiD]@\}}|}|t jo|i|=q/|||fq/W|SWd|ii XdS(N( soutsappendsaddsselfs_Protocol__locksacquires_Protocol__impliessitemssksvsprotosNonesrelease(sselfsprotosksaddsvsout((s9build/bdist.darwin-8.9.1-i386/egg/protocols/interfaces.pysgetImpliedProtocols7s     ic Cs|iiz=t|}t|i||| o|i|dSnWd|ii XxI|i i D]8\}\}}ti|t||||||qkW|io4x1|iiD]}|i||||qWn|SdS(Ni(sselfs_Protocol__locksacquiresmkRefsprotoskeysupdateWithSimplestAdapters_Protocol__impliessadaptersdepthsreleases_Protocol__adapterssitemssklasss baseAdaptersdsapisdeclareAdapterForTypescomposeAdapterss_Protocol__listenersskeysslistenersnewProtocolImplied( sselfsprotosadaptersdepthskeys baseAdapterslistenersklasssd((s9build/bdist.darwin-8.9.1-i386/egg/protocols/interfaces.pysaddImpliedProtocolSs  * cCs|iiz1t|i||| o|i|dSnWd|iiX|t jo|SnxF|i D]8\}\}}ti|t||||||qqW|SdS(Ni(sselfs_Protocol__locksacquiresupdateWithSimplestAdapters_Protocol__adapterssklasssadaptersdepthsreleasesDOES_NOT_SUPPORTsgetImpliedProtocolssprotosextendersdsapisdeclareAdapterForTypescomposeAdapters(sselfsklasssadaptersdepthsdsprotosextender((s9build/bdist.darwin-8.9.1-i386/egg/protocols/interfaces.pysregisterImplementation|s   *cCsti|ti|||ob|tjodSnxJ|i D]8\}\}}ti |t||||||qDWndS(N(sapisadaptsobs IOpenProvidersdeclareProvidessselfsadaptersdepthsDOES_NOT_SUPPORTsgetImpliedProtocolssprotosextendersdsdeclareAdapterForObjectscomposeAdapters(sselfsobsadaptersdepthsdsprotosextender((s9build/bdist.darwin-8.9.1-i386/egg/protocols/interfaces.pysregisterObjects "  cCs|ii}y |i}Wntj ot|}nXy |i}Wn%tj ot |dt }nXx9|D]1}||}|tj o|d|SqwqwWdS(NsextendedClassici(sselfs_Protocol__adapterssgetsobjs __class__stypsAttributeErrorstypes__mro__smros classicMROsTruesklasssfactorysNone(sselfsobjsgetsfactorysmrosklassstyp((s9build/bdist.darwin-8.9.1-i386/egg/protocols/interfaces.pys __adapt__s     (sProtocol__adapt__cCs`|iiz>|itjodkl}||_nd|i|build/bdist.darwin-8.9.1-i386/egg/protocols/twisted_support.pys__init__5scCs/t||io|Sn|i|tSdS(N(sTwistedImplementssobjsselfsifacesNone(sselfsobj((s>build/bdist.darwin-8.9.1-i386/egg/protocols/twisted_support.pys__call__9scCs;|iiid}|tjo|Sn|||SdS(Ns __adapt__(sselfsifaces__dict__sgetsmethsNonesdefaultsob(sselfsobsdefaultsmeth((s>build/bdist.darwin-8.9.1-i386/egg/protocols/twisted_support.pysim_funcEs (s__name__s __module__s__doc__s __slots__s__init__s__call__sim_func(((s>build/bdist.darwin-8.9.1-i386/egg/protocols/twisted_support.pysTwistedAdaptMethod.s   (s implementss MetaInterfaces getInterfacescCs t|S(N(sTwistedAdaptMethodss(ss((s>build/bdist.darwin-8.9.1-i386/egg/protocols/twisted_support.pys`ssTwistedInterfaceAsProtocolcBsltZdZedegdedZdZeddZ eddZ edd Z d Z RS( NsifacesinstancesProvidesasAdapterForTypescCs ||_dS(N(sifacesself(sselfsiface((s>build/bdist.darwin-8.9.1-i386/egg/protocols/twisted_support.pys__init__scCs|ii|SdS(N(sselfsifaces __adapt__sobj(sselfsobj((s>build/bdist.darwin-8.9.1-i386/egg/protocols/twisted_support.pys __adapt__sicCst|}|tjo|it|f|_n]|t jo7|i|jo#|i |it||_qnt d|i||dS(Ns9Twisted interfaces can only declare support, not adapters( sTwistedGetInterfacessklasss oldImplementssadaptersNO_ADAPTER_NEEDEDsselfsifacestuples__implements__sDOES_NOT_SUPPORTsremoves TypeError(sselfsklasssadaptersdepths oldImplements((s>build/bdist.darwin-8.9.1-i386/egg/protocols/twisted_support.pysregisterImplementations   csk|i|iid|iidh}x*|iD]}|i |||qGWdS(Ncs |S(N(sadaptersosiface(so(sadaptersiface(s>build/bdist.darwin-8.9.1-i386/egg/protocols/twisted_support.pysss_Protocol__listeners( sselfsifaces adaptWithsprotos__dict__sgets listenersskeysslistenersnewProtocolImpliedsadaptersdepth(sselfsprotosadaptersdepthsifaceslisteners listeners((sadaptersifaces>build/bdist.darwin-8.9.1-i386/egg/protocols/twisted_support.pysaddImpliedProtocols   cCst|}|tjo|it|f|_n]|t jo7|i|jo#|i |it||_qnt d|i||dS(Ns9Twisted interfaces can only declare support, not adapters( sTwistedGetInterfacessobs oldImplementssadaptersNO_ADAPTER_NEEDEDsselfsifacestuples__implements__sDOES_NOT_SUPPORTsremoves TypeError(sselfsobsadaptersdepths oldImplements((s>build/bdist.darwin-8.9.1-i386/egg/protocols/twisted_support.pysregisterObjects   cCs)|iiidt}t||build/bdist.darwin-8.9.1-i386/egg/protocols/twisted_support.pysaddImplicationListeners( s__name__s __module__s __slots__sadvises IOpenProtocolsTwistedInterfaceTypess__init__s __adapt__sNO_ADAPTER_NEEDEDsregisterImplementationsaddImpliedProtocolsregisterObjectsaddImplicationListener(((s>build/bdist.darwin-8.9.1-i386/egg/protocols/twisted_support.pysTwistedInterfaceAsProtocol|s    N(s__doc__s__all__sadapterssapisadvises interfacess IOpenProtocolsweakrefsWeakKeyDictionarysobjectsTwistedAdaptMethodstwisted.python.componentss implementssTwistedImplementss MetaInterfacesTwistedInterfaceClasss getInterfacessTwistedGetInterfacess ImportErrorsTwistedInterfaceTypesspropertys __adapt__sTwistedInterfaceAsProtocol( sTwistedInterfaceClasssTwistedInterfaceTypessWeakKeyDictionarysTwistedInterfaceAsProtocols__all__sTwistedAdaptMethodsTwistedGetInterfacessadvises IOpenProtocolsTwistedImplements((s>build/bdist.darwin-8.9.1-i386/egg/protocols/twisted_support.pys?s   &'  PKmy6.w protocols/zope_support.py"""Declaration support for Zope Interfaces""" __all__ = [] from types import ClassType from adapters import * from api import declareImplementation, advise, adapt from interfaces import IOpenProtocol, Protocol from advice import metamethod, supermeta # Monkeypatch Zope Interfaces try: import zope.interface as zi except ImportError: ZopeInterfaceTypes = [] zi = None else: def __adapt__(self, obj): return adapt(self,IOpenProtocol).__adapt__(obj) try: from zope.interface import adapter_hooks except ImportError: try: from zope.interface.interface import adapter_hooks except ImportError: zi.Interface.__class__.__adapt__ = __adapt__ adapter_hooks = [] adapter_hooks.append(__adapt__) ZopeInterfaceTypes = [zi.Interface.__class__] del __adapt__, adapter_hooks # Adapter for Zope X3 Interfaces class ZopeInterfaceAsProtocol(StickyAdapter, Protocol): advise( instancesProvide=[IOpenProtocol], asAdapterForTypes=ZopeInterfaceTypes, ) attachForProtocols = IOpenProtocol, def __init__(self, ob): StickyAdapter.__init__(self,ob) Protocol.__init__(self) if ZopeInterfaceTypes and hasattr(ZopeInterfaceTypes[0],'providedBy'): def __adapt__(self, obj): if self.subject.providedBy(obj): return obj return supermeta(ZopeInterfaceAsProtocol,self).__adapt__(obj) else: def __adapt__(self, obj): if self.subject.isImplementedBy(obj): return obj return supermeta(ZopeInterfaceAsProtocol,self).__adapt__(obj) def registerImplementation(self,klass,adapter=NO_ADAPTER_NEEDED,depth=1): if adapter is NO_ADAPTER_NEEDED: zi.classImplements(klass, self.subject) elif adapter is DOES_NOT_SUPPORT: ifaces = zi.Declaration( [i.__iro__ for i in zi.implementedBy(klass)] ) - self.subject zi.classImplementsOnly(klass, ifaces) return supermeta(ZopeInterfaceAsProtocol,self).registerImplementation( klass,adapter,depth ) registerImplementation = metamethod(registerImplementation) def registerObject(self, ob, adapter=NO_ADAPTER_NEEDED, depth=1): if adapter is NO_ADAPTER_NEEDED: zi.directlyProvides(ob,self.subject) elif adapter is DOES_NOT_SUPPORT: zi.directlyProvides(ob, zi.directlyProvidedBy(ob)-self.subject) return supermeta(ZopeInterfaceAsProtocol,self).registerObject( ob, adapter, depth ) registerObject = metamethod(registerObject) def getImpliedProtocols(self): protos = super(ZopeInterfaceAsProtocol,self).getImpliedProtocols() return list(protos) + [ (i,(NO_ADAPTER_NEEDED,1)) for i in self.subject.__bases__ if i is not zi.Interface ] def __getstate__(self): state = self.__dict__.copy() del state['_Protocol__lock'] # locks can't be pickled del state['_Protocol__listeners'] # and neither can weakref dict return state def __hash__(self): return hash(self.subject) def __cmp__(self,other): return cmp(self.subject, other) PK86]{protocols/zope_support.pyc; ~ *Fc@s<dZgZdklZdkTdklZlZlZdk l Z l Z dk l Z lZydkiZWnej ogZeZnXdZydklZWnOej oCydklZWqej oeeii_gZqXnXeieeiigZ[[d ee fd YZdS( s'Declaration support for Zope Interfaces(s ClassType(s*(sdeclareImplementationsadvisesadapt(s IOpenProtocolsProtocol(s metamethods supermetaNcCst|ti|SdS(N(sadaptsselfs IOpenProtocols __adapt__sobj(sselfsobj((s;build/bdist.darwin-8.9.1-i386/egg/protocols/zope_support.pys __adapt__s(s adapter_hookssZopeInterfaceAsProtocolcBstZedegdeefZdZeoeeddo dZn dZe dd Z e e Z e dd Z e e Z d Z d Zd ZdZRS(NsinstancesProvidesasAdapterForTypescCs!ti||ti|dS(N(s StickyAdapters__init__sselfsobsProtocol(sselfsob((s;build/bdist.darwin-8.9.1-i386/egg/protocols/zope_support.pys__init__3sis providedBycCs5|ii|o|Sntt|i|SdS(N(sselfssubjects providedBysobjs supermetasZopeInterfaceAsProtocols __adapt__(sselfsobj((s;build/bdist.darwin-8.9.1-i386/egg/protocols/zope_support.pys __adapt__8scCs5|ii|o|Sntt|i|SdS(N(sselfssubjectsisImplementedBysobjs supermetasZopeInterfaceAsProtocols __adapt__(sselfsobj((s;build/bdist.darwin-8.9.1-i386/egg/protocols/zope_support.pys __adapt__=sicCs|tjoti||ine|tjoWtigi }ti |D]}||i qN~|i}ti||ntt|i|||SdS(N(sadaptersNO_ADAPTER_NEEDEDszisclassImplementssklasssselfssubjectsDOES_NOT_SUPPORTs Declarationsappends_[1]s implementedBysis__iro__sifacessclassImplementsOnlys supermetasZopeInterfaceAsProtocolsregisterImplementationsdepth(sselfsklasssadaptersdepthsifacessis_[1]((s;build/bdist.darwin-8.9.1-i386/egg/protocols/zope_support.pysregisterImplementationBs   CcCsu|tjoti||in2|tjo$ti|ti||int t |i |||SdS(N( sadaptersNO_ADAPTER_NEEDEDszisdirectlyProvidessobsselfssubjectsDOES_NOT_SUPPORTsdirectlyProvidedBys supermetasZopeInterfaceAsProtocolsregisterObjectsdepth(sselfsobsadaptersdepth((s;build/bdist.darwin-8.9.1-i386/egg/protocols/zope_support.pysregisterObjectSs   $cCsntt|i}t|gi}|ii D]0}|t i j o||t dffq2q2~SdS(Ni(ssupersZopeInterfaceAsProtocolsselfsgetImpliedProtocolssprotosslistsappends_[1]ssubjects __bases__siszis InterfacesNO_ADAPTER_NEEDED(sselfsis_[1]sprotos((s;build/bdist.darwin-8.9.1-i386/egg/protocols/zope_support.pysgetImpliedProtocolsbscCs%|ii}|d=|d=|SdS(Ns_Protocol__locks_Protocol__listeners(sselfs__dict__scopysstate(sselfsstate((s;build/bdist.darwin-8.9.1-i386/egg/protocols/zope_support.pys __getstate__jscCst|iSdS(N(shashsselfssubject(sself((s;build/bdist.darwin-8.9.1-i386/egg/protocols/zope_support.pys__hash__pscCst|i|SdS(N(scmpsselfssubjectsother(sselfsother((s;build/bdist.darwin-8.9.1-i386/egg/protocols/zope_support.pys__cmp__ss(s__name__s __module__sadvises IOpenProtocolsZopeInterfaceTypessattachForProtocolss__init__shasattrs __adapt__sNO_ADAPTER_NEEDEDsregisterImplementations metamethodsregisterObjectsgetImpliedProtocolss __getstate__s__hash__s__cmp__(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/zope_support.pysZopeInterfaceAsProtocol,s           (s__doc__s__all__stypess ClassTypesadapterssapisdeclareImplementationsadvisesadapts interfacess IOpenProtocolsProtocolsadvices metamethods supermetaszope.interfaces interfaceszis ImportErrorsZopeInterfaceTypessNones __adapt__s adapter_hooksszope.interface.interfaces Interfaces __class__sappends StickyAdaptersZopeInterfaceAsProtocol(sProtocolszis__all__s ClassTypes metamethodsZopeInterfaceTypess __adapt__sadapts adapter_hookssdeclareImplementationsadvises supermetas IOpenProtocolsZopeInterfaceAsProtocol((s;build/bdist.darwin-8.9.1-i386/egg/protocols/zope_support.pys?s0    PKmy6 "ttprotocols/tests/__init__.pyfrom unittest import TestSuite, TestCase, makeSuite from protocols import adapt, advise, Interface, Attribute, declareAdapter from protocols import AbstractBase, AdaptationFailure class APITests(TestCase): def checkAdaptTrapsTypeErrorsOnConform(self): class Conformer: def __conform__(self,ob): return [] assert adapt(Conformer,list,None) is None assert adapt(Conformer(),list,None) == [] def checkAdaptHandlesIsInstance(self): assert adapt([1,2,3],list,None) == [1,2,3] assert adapt('foo',str,None) == 'foo' assert adapt('foo',list,None) is None def checkAdviseFailsInCallContext(self): try: advise() except SyntaxError: pass else: raise AssertionError( "Should've got SyntaxError for advise() in function" ) def checkAdviseClassKeywordsValidated(self): try: class X: advise(moduleProvides=list) except TypeError,v: assert v.args==( "Invalid keyword argument for advising classes: moduleProvides", ) else: raise AssertionError("Should've caught invalid keyword") def checkAdviseClassKeywordsValidated(self): try: class X: advise(moduleProvides=list) except TypeError,v: assert v.args==( "Invalid keyword argument for advising classes: moduleProvides", ) else: raise AssertionError("Should've caught invalid keyword") def checkAdviseModuleKeywordsValidated(self): try: exec "advise(instancesProvide=[IProtocol1])" in globals(),globals() except TypeError,v: assert v.args==( "Invalid keyword argument for advising modules: instancesProvide", ) else: raise AssertionError("Should've caught invalid keyword") def checkAdviseInClassExec(self): d = {'advise':advise,'IProtocol1':IProtocol1} exec "class Foo: advise(instancesProvide=[IProtocol1])" in d def checkSimpleAdaptation(self): class Conformer: def __conform__(self,protocol): if protocol==42: return "hitchhiker",self class AdaptingProtocol: def __adapt__(klass,ob): return "adapted", ob __adapt__ = classmethod(__adapt__) c = Conformer() assert adapt(c,42,None) == ("hitchhiker",c) assert adapt(c,AdaptingProtocol,None) == ("adapted",c) assert adapt(42,AdaptingProtocol,None) == ("adapted",42) assert adapt(42,42,None) is None def checkAdaptFiltersTypeErrors(self): class Nonconformist: def __conform__(self,ob): raise TypeError("You got me!") class Unadaptive: def __adapt__(self,ob): raise TypeError("You got me!") # These will get a type errors calling __conform__/__adapt__ # but should be ignored since the error is at calling level assert adapt(None, Unadaptive, None) is None assert adapt(Nonconformist, None, None) is None # These will get type errors internally, and the error should # bleed through to the caller self.assertTypeErrorPassed(None, Unadaptive(), None) self.assertTypeErrorPassed(Nonconformist(), None, None) self.assertRaises(AdaptationFailure, adapt, None, None) def assertTypeErrorPassed(self, *args): try: # This should raise TypeError internally, and be caught adapt(*args) except TypeError,v: assert v.args==("You got me!",) else: raise AssertionError("Should've passed TypeError through") def checkImplicationBug(self): class I1(Interface): pass class I2(I1): pass declareAdapter(lambda o: o, provides=[I1],forProtocols=[I2]) def checkAttribute(self): for i in range(10)+[None]: class Abstract(AbstractBase): value = Attribute("testing", "value", i) ob = Abstract() assert ob.value == i for j in range(10): ob.value = j assert ob.value==j def checkStickyAdapter(self): class T: pass t = T() class I(Interface): pass from protocols.adapters import StickyAdapter class A(StickyAdapter): attachForProtocols = I, advise(instancesProvide=[I], asAdapterForTypes=[T]) a = I(t) assert adapt(t, I) is a assert a.subject is t n = T() a2 = I(n) assert a2 is not a assert a2.subject is n assert adapt(n, I) is a2 from protocols import protocolForType, protocolForURI, sequenceOf, advise from protocols import declareImplementation, Variation from UserDict import UserDict IGetSetMapping = protocolForType(dict,['__getitem__','__setitem__']) IGetMapping = protocolForType(dict,['__getitem__']) ISimpleReadFile = protocolForType(file,['read']) IImplicitRead = protocolForType(file,['read'], implicit=True) IProtocol1 = protocolForURI("http://peak.telecommunity.com/PyProtocols") multimap = sequenceOf(IGetMapping) declareImplementation(UserDict,[IGetSetMapping]) IMyUnusualMapping = Variation(IGetSetMapping) class MyUserMapping(object): pass declareImplementation(MyUserMapping,[IMyUnusualMapping]) class GenerationTests(TestCase): def checkTypeSubset(self): d = {} assert IGetSetMapping(d,None) is d assert IGetMapping(d,None) is d def checkImplications(self): d = UserDict() assert IGetMapping(d,None) is d assert IImplicitRead(d,None) is None def checkWeak(self): from cStringIO import StringIO s = StringIO("foo") assert ISimpleReadFile(s,None) is None assert IImplicitRead(s,None) is s def checkURI(self): p = protocolForURI("http://www.python.org/") assert p is not IProtocol1 p = protocolForURI("http://peak.telecommunity.com/PyProtocols") assert p is IProtocol1 def checkSequence(self): d1,d2 = {},{} seq = multimap([d1,d2]) assert seq == [d1,d2] assert seq[0] is d1 and seq[1] is d2 class ISequenceLike(Interface): advise(protocolIsSubsetOf=[multimap]) ISequenceLike([d1,d2]) def checkVariation(self): d = {} assert IMyUnusualMapping(d,None) is d # GetSet implies variation d = MyUserMapping(); assert IMyUnusualMapping(d,None) is d assert IGetSetMapping(d,None) is None # but not the other way self.assertEqual(repr(IMyUnusualMapping), "Variation(TypeSubset(,('__getitem__', '__setitem__')))") self.assertEqual(repr(Variation(Interface,42)), "Variation(,42)") def test_suite(): from protocols.tests import test_advice, test_direct, test_classes tests = [ test_advice.test_suite(), test_classes.test_suite(), test_direct.test_suite(), makeSuite(APITests,'check'), makeSuite(GenerationTests,'check'), ] try: import zope.interface except ImportError: pass else: from protocols.tests import test_zope tests.append( test_zope.test_suite() ) try: from twisted.python.components import Interface except (ImportError, SystemError): pass else: from protocols.tests import test_twisted tests.append( test_twisted.test_suite() ) return TestSuite( tests ) PK86lZPN=N=protocols/tests/__init__.pyc; ~ *Fc@stdklZlZlZdklZlZlZlZl Z dkl Z l Z defdYZ dkl Z lZlZlZdklZlZdklZe edd gZe edgZe ed gZe ed gd eZed ZeeZeeegeeZd efdYZeeegdefdYZdZ dS((s TestSuitesTestCases makeSuite(sadaptsadvises Interfaces AttributesdeclareAdapter(s AbstractBasesAdaptationFailuresAPITestscBs}tZdZdZdZdZdZdZdZdZdZ d Z d Z d Z d Z RS( NcCsZdfdY}t|tttjptt|ttgjptdS(Ns ConformercBstZdZRS(NcCsgSdS(N((sselfsob((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pys __conform__ s(s__name__s __module__s __conform__(((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pys Conformers(s ConformersadaptslistsNonesAssertionError(sselfs Conformer((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pys"checkAdaptTrapsTypeErrorsOnConforms cCsvtdddgttdddgjpttdttdjpttdtttjptdS(Niiisfoo(sadaptslistsNonesAssertionErrorsstr(sself((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pyscheckAdaptHandlesIsInstances2 cCs1y tWntj onXtddS(Ns2Should've got SyntaxError for advise() in function(sadvises SyntaxErrorsAssertionError(sself((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pyscheckAdviseFailsInCallContexts  cCsYydfdY}Wn/tj o#}|idfjptnXtddS(NsXcBstZedeRS(NsmoduleProvides(s__name__s __module__sadviseslist(((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pysX!ss=Invalid keyword argument for advising classes: moduleProvidess Should've caught invalid keyword(sXs TypeErrorsvsargssAssertionError(sselfsXsv((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pys!checkAdviseClassKeywordsValidateds cBsVydeeUWn/ej o#}|idfjptnXeddS(Ns%advise(instancesProvide=[IProtocol1])s?Invalid keyword argument for advising modules: instancesProvides Should've caught invalid keyword(sglobalss TypeErrorsvsargssAssertionError(sselfsv((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pys"checkAdviseModuleKeywordsValidated5s cBs$hde<de<}d|UdS(Nsadvises IProtocol1s0class Foo: advise(instancesProvide=[IProtocol1])(sadvises IProtocol1sd(sselfsd((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pyscheckAdviseInClassExec?scCsdfdY}dfdY}|}t|dtd|fjptt||td|fjpttd|tddfjpttddttjptdS(Ns ConformercBstZdZRS(NcCs|djod|fSndS(Ni*s hitchhiker(sprotocolsself(sselfsprotocol((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pys __conform__Es (s__name__s __module__s __conform__(((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pys ConformerDssAdaptingProtocolcBstZdZeeZRS(NcCsd|fSdS(Nsadapted(sob(sklasssob((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pys __adapt__Is(s__name__s __module__s __adapt__s classmethod(((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pysAdaptingProtocolHs i*s hitchhikersadapted(s ConformersAdaptingProtocolscsadaptsNonesAssertionError(sselfsAdaptingProtocolscs Conformer((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pyscheckSimpleAdaptationCs &&&cCsdfdY}dfdY}tt|ttjptt|tttjpt|it|t|i|tt|ittttdS(Ns NonconformistcBstZdZRS(NcCstddS(Ns You got me!(s TypeError(sselfsob((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pys __conform__Vs(s__name__s __module__s __conform__(((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pys NonconformistUss UnadaptivecBstZdZRS(NcCstddS(Ns You got me!(s TypeError(sselfsob((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pys __adapt__Zs(s__name__s __module__s __adapt__(((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pys UnadaptiveYs( s Nonconformists UnadaptivesadaptsNonesAssertionErrorsselfsassertTypeErrorPasseds assertRaisessAdaptationFailure(sselfs Unadaptives Nonconformist((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pyscheckAdaptFiltersTypeErrorsSs  cGsPyt|Wn/tj o#}|idfjptnXtddS(Ns You got me!s"Should've passed TypeError through(sadaptsargss TypeErrorsvsAssertionError(sselfsargssv((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pysassertTypeErrorPassedis cCsOdtfdY}d|fdY}tdd|gd|gdS(NsI1cBstZRS(N(s__name__s __module__(((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pysI1sssI2cBstZRS(N(s__name__s __module__(((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pysI2tscCs|S(N(so(so((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pysussprovidess forProtocols(s InterfacesI1sI2sdeclareAdapter(sselfsI1sI2((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pyscheckImplicationBugrscsxtdtgD]vdtfdY}|}|ijptx4tdD]&}||_|i|jptq`WqWdS(Ni sAbstractcstZeddZRS(Nstestingsvalue(s__name__s __module__s Attributesisvalue((si(s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pysAbstracts( srangesNonesis AbstractBasesAbstractsobsvaluesAssertionErrorsj(sselfsisAbstractsjsob((sis=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pyscheckAttribute|s   c sdfdY}dtfdYdkl}d|fdY}|}t||jpt |i |jpt }|}||j pt |i |jpt t||jpt dS(NsTcBstZRS(N(s__name__s __module__(((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pysTssIcBstZRS(N(s__name__s __module__(((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pysIs(s StickyAdaptersAcs*tZfZedgdgRS(NsinstancesProvidesasAdapterForTypes(s__name__s __module__sIsattachForProtocolssadvisesT((sIsT(s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pysAs ( sTsts InterfacesIsprotocols.adapterss StickyAdaptersAsasadaptsAssertionErrorssubjectsnsa2( sselfsAsasIs StickyAdaptersnsa2sTst((sIsTs=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pyscheckStickyAdapters     (s__name__s __module__s"checkAdaptTrapsTypeErrorsOnConformscheckAdaptHandlesIsInstancescheckAdviseFailsInCallContexts!checkAdviseClassKeywordsValidateds"checkAdviseModuleKeywordsValidatedscheckAdviseInClassExecscheckSimpleAdaptationscheckAdaptFiltersTypeErrorssassertTypeErrorPassedscheckImplicationBugscheckAttributescheckStickyAdapter(((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pysAPITestss      (sprotocolForTypesprotocolForURIs sequenceOfsadvise(sdeclareImplementations Variation(sUserDicts __getitem__s __setitem__sreadsimplicits)http://peak.telecommunity.com/PyProtocolss MyUserMappingcBstZRS(N(s__name__s __module__(((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pys MyUserMappingssGenerationTestscBs>tZdZdZdZdZdZdZRS(NcCsDh}t|t|jptt|t|jptdS(N(sdsIGetSetMappingsNonesAssertionErrors IGetMapping(sselfsd((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pyscheckTypeSubsetscCsGt}t|t|jptt|ttjptdS(N(sUserDictsds IGetMappingsNonesAssertionErrors IImplicitRead(sselfsd((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pyscheckImplicationss cCsWdkl}|d}t|ttjptt|t|jptdS(N(sStringIOsfoo(s cStringIOsStringIOsssISimpleReadFilesNonesAssertionErrors IImplicitRead(sselfsStringIOss((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pys checkWeaks  cCsDtd}|tj pttd}|tjptdS(Nshttp://www.python.org/s)http://peak.telecommunity.com/PyProtocols(sprotocolForURIsps IProtocol1sAssertionError(sselfsp((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pyscheckURIs  cCshhf\}}t||g}|||gjpt|d|jo|d|jptdtfdY}|||gdS(Niis ISequenceLikecBstZedegRS(NsprotocolIsSubsetOf(s__name__s __module__sadvisesmultimap(((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pys ISequenceLikes(sd1sd2smultimapsseqsAssertionErrors Interfaces ISequenceLike(sselfsseqs ISequenceLikesd2sd1((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pys checkSequences )cCsh}t|t|jptt}t|t|jptt|ttjpt|ittd|itt t dddS(NsCVariation(TypeSubset(,('__getitem__', '__setitem__')))i*s6Variation(,42)( sdsIMyUnusualMappingsNonesAssertionErrors MyUserMappingsIGetSetMappingsselfs assertEqualsreprs Variations Interface(sselfsd((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pyscheckVariations&(s__name__s __module__scheckTypeSubsetscheckImplicationss checkWeakscheckURIs checkSequencescheckVariation(((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pysGenerationTestss      cCsdkl}l}l}|i|i|ittdttdg}y dk }Wnt j on"Xdkl }|i |iydkl}Wnt tfj on"Xdkl}|i |it|SdS(N(s test_advices test_directs test_classesscheck(s test_zope(s Interface(s test_twisted(sprotocols.testss test_advices test_directs test_classess test_suites makeSuitesAPITestssGenerationTestsstestsszope.interfaceszopes ImportErrors test_zopesappendstwisted.python.componentss Interfaces SystemErrors test_twisteds TestSuite(stestss test_twisteds test_advices Interfaces test_zopes test_classesszopes test_direct((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pys test_suites9   N(!sunittests TestSuitesTestCases makeSuites protocolssadaptsadvises Interfaces AttributesdeclareAdapters AbstractBasesAdaptationFailuresAPITestssprotocolForTypesprotocolForURIs sequenceOfsdeclareImplementations VariationsUserDictsdictsIGetSetMappings IGetMappingsfilesISimpleReadFilesTrues IImplicitReads IProtocol1smultimapsIMyUnusualMappingsobjects MyUserMappingsGenerationTestss test_suite(s sequenceOfsIMyUnusualMappings Variations TestSuitesAdaptationFailuresISimpleReadFilesprotocolForTypesTestCasesadapts IImplicitReads InterfacesadvisesAPITestssmultimapsUserDicts makeSuitesGenerationTestssprotocolForURIsdeclareAdaptersIGetSetMappingsdeclareImplementations MyUserMappings Attributes IGetMappings test_suites IProtocol1s AbstractBase((s=build/bdist.darwin-8.9.1-i386/egg/protocols/tests/__init__.pys?s$%    )PKmy6dov1v1protocols/tests/checks.py"""Basic test setups""" __all__ = [ 'TestBase', 'ImplementationChecks', 'ProviderChecks', 'InstanceImplementationChecks', 'makeClassTests', 'ClassProvidesChecks', 'AdaptiveChecks', 'SimpleAdaptiveChecks', 'makeMetaClassProvidesTests', 'BasicClassProvidesChecks', ] from unittest import TestCase, makeSuite, TestSuite from protocols import * # Dummy interfaces and adapters used in tests def a1(ob): return 'a1',ob def a2(ob): return 'a2',ob class TestBase(TestCase): """Non-adapter instance tests""" a1 = staticmethod(a1) a2 = staticmethod(a2) def assertObProvidesOnlyA(self): assert self.IA(self.ob, None) is self.ob assert self.IB(self.ob, None) is None assert self.IA(None, None) is None assert adapt(self.IB, None, None) is None assert adapt(self.ob, None, None) is None def assertObProvidesAandB(self): assert self.IA(self.ob, None) is self.ob assert self.IB(self.ob, None) is self.ob assert adapt(self.IA, None, None) is None assert adapt(self.IB, None, None) is None assert adapt(self.ob, None, None) is None def assertAmbiguous(self, a1, a2, d1, d2, ifaces): try: self.declareObAdapts(a2,ifaces) except TypeError,v: assert v.args == ("Ambiguous adapter choice", a1, a2, d1, d2) def make(self,klass): # This is overridden by tests where 'klass' is a metaclass return klass() def assertObProvidesSubsetOfA(self): # Assert that self.ob provides a new subset of self.IA # (Caller must ensure that self.ob provides self.IA) class IC(self.Interface): advise(protocolIsSubsetOf=[self.IA]) if 'self' in locals(): del locals()['self'] # how the heck??? assert IC(self.ob, None) is self.ob def setupBases(self,base): class M1(base): pass class M2(base): pass return M1, M2 def assertM1ProvidesOnlyAandM2ProvidesB(self,M1,M2): assert self.IA(M1,None) is M1 assert self.IB(M1,None) is None assert self.IB(M2,None) is M2 def assertChangingBasesChangesInterface(self,M1,M2,m1,m2): try: M1.__bases__ = M2, except TypeError: # XXX 2.2 doesn't let newstyle __bases__ change pass else: assert self.IA(m1,None) is m1 assert self.IB(m1,None) is m1 def assertObProvidesABCD(self,IC,ID): assert self.IA(self.ob, None) is self.ob assert self.IB(self.ob, None) is self.ob assert IC(self.ob, None) is self.ob assert ID(self.ob, None) is self.ob def assertObProvidesCandDnotAorB(self,IC,ID): assert self.IA(self.ob, None) is None assert self.IB(self.ob, None) is None assert IC(self.ob, None) is self.ob assert ID(self.ob, None) is self.ob class ProviderChecks(TestBase): """Non-adapter specific-object-provides checks""" def declareObImplements(self,ifaces): adviseObject(self.ob, provides=ifaces) def declareObAdapts(self,factory,ifaces): declareAdapter(factory,provides=ifaces,forObjects=[self.ob]) def checkSimpleRegister(self): self.declareObImplements([self.IA]) self.assertObProvidesOnlyA() def checkImpliedRegister(self): self.declareObImplements([self.IB]) self.assertObProvidesAandB() class SimpleAdaptiveChecks: """Simple adapter-oriented checks that Twisted can handle (Well, it handles them as long as all the interfaces are Twisted)""" def checkDelayedImplication(self): self.declareObImplements([self.IA]) self.assertObProvidesSubsetOfA() def checkIndirectImplication(self): # Zope fails this because it does not support adding after-the-fact # implication. # IB->IA + ID->IC + IC->IB = ID->IA class IC(self.Interface): pass class ID(IC): pass self.declareObImplements([ID]) self.assertObProvidesCandDnotAorB(IC,ID) declareAdapter( NO_ADAPTER_NEEDED, provides=[self.IB], forProtocols=[IC] ) self.assertObProvidesABCD(IC,ID) class AdaptiveChecks(SimpleAdaptiveChecks): """General adapter/protocol implication checks Twisted can't handle these.""" def checkAmbiguity(self): self.declareObAdapts(self.a1,[self.IA]) self.assertAmbiguous(self.a1,self.a2,1,1,[self.IA]) def checkOverrideDepth(self): self.declareObAdapts(self.a1,[self.IB]) self.assertEquals(self.IA(self.ob,None), ('a1',self.ob)) self.declareObAdapts(self.a2,[self.IA]) self.assertEquals(self.IA(self.ob,None), ('a2',self.ob)) def checkComposed(self): class IC(self.Interface): pass declareAdapter(self.a2,provides=[IC],forProtocols=[self.IA]) self.declareObAdapts(self.a1,[self.IA]) self.assertEqual(IC(self.ob,None), ('a2',('a1',self.ob))) def checkLateDefinition(self): # Zope fails this because it has different override semantics self.declareObAdapts(DOES_NOT_SUPPORT, [self.IA]) assert self.IA(self.ob,None) is None self.declareObImplements([self.IA]) assert self.IA(self.ob,None) is self.ob # NO_ADAPTER_NEEDED at same depth should override DOES_NOT_SUPPORT self.declareObAdapts(DOES_NOT_SUPPORT, [self.IA]) assert self.IA(self.ob,None) is self.ob class InstanceImplementationChecks(TestBase): """Non-adapter class-instances-provide checks""" # Everybody can handle these def declareObImplements(self,ifaces): declareImplementation(self.klass, ifaces) def declareObAdapts(self,factory,ifaces): declareAdapter(factory,provides=ifaces,forTypes=[self.klass]) def checkSimpleRegister(self): self.declareObImplements([self.IA]) self.assertObProvidesOnlyA() def checkImpliedRegister(self): self.declareObImplements([self.IB]) self.assertObProvidesAandB() class ImplementationChecks(InstanceImplementationChecks): """Non-adapter class-instances vs. class-provide checks""" # Twisted fails these tests because it has no way to distinguish the # interfaces an object provides from the interfaces its class provides def checkNoClassPassThru(self): self.declareObImplements([self.IA]) assert self.IA(self.klass, None) is None def checkInheritedDeclaration(self): self.declareObImplements([self.IB]) class Sub(self.klass): pass inst = self.make(Sub) assert self.IB(inst,None) is inst assert self.IA(inst,None) is inst assert self.IA(Sub,None) is None # check not passed up to class assert self.IB(Sub,None) is None def checkRejectInheritanceAndReplace(self): self.declareObImplements([self.IB]) class Sub(self.klass): advise(instancesDoNotProvide=[self.IB]) inst = self.make(Sub) assert self.IA(inst,None) is inst assert self.IB(inst,None) is None declareImplementation(Sub, instancesProvide=[self.IB]) assert self.IB(inst,None) is inst class BasicClassProvidesChecks: """Object-provides checks for classes and types""" # Twisted doesn't support these because it makes no object/type distinction def checkNoInstancePassThru(self): inst = self.ob() adviseObject(self.ob, provides=[self.IA]) assert self.IA(inst, None) is None def checkChangingBases(self): M1, M2 = self.setupBases(self.ob) adviseObject(M1, provides=[self.IA]) adviseObject(M2, provides=[self.IB]) self.assertM1ProvidesOnlyAandM2ProvidesB(M1,M2) self.assertChangingBasesChangesInterface(M1,M2,M1,M2) class ClassProvidesChecks(BasicClassProvidesChecks): # Twisted doesn't support these because it makes no object/type distinction def checkInheritedDeclaration(self): class Sub(self.ob): pass adviseObject(self.ob, provides=[self.IB]) assert self.IB(Sub, None) is Sub assert self.IA(Sub, None) is Sub def checkRejectInheritanceAndReplace(self): adviseObject(self.ob, provides=[self.IB]) class Sub(self.ob): advise(classDoesNotProvide=[self.IB]) assert self.IA(Sub,None) is Sub assert self.IB(Sub,None) is None adviseObject(Sub,provides=[self.IB]) assert self.IB(Sub,None) is Sub def makeInstanceTests(base,Picklable,NewStyle): """Generate a set of instance-oriented test classes using 'base'""" class AdviseFunction(base): __module__ = base.__module__ def setUp(self): def aFunc(foo,bar): pass self.ob = aFunc AdviseFunction.__name__ = base.__name__+'.AdviseFunction' class AdviseModule(base): __module__ = base.__module__ def setUp(self): from types import ModuleType self.ob = ModuleType('x') AdviseModule.__name__ = base.__name__+'.AdviseModule' class AdviseInstance(base): __module__ = base.__module__ def setUp(self): self.ob = Picklable() def checkPickling(self): from cPickle import loads,dumps # pickle has a bug! adviseObject(self.ob, provides=[self.IPure]) newOb = loads(dumps(self.ob)) assert self.IPure(newOb,None) is newOb AdviseInstance.__name__ = base.__name__+'.AdviseInstance' class AdviseNewInstance(AdviseInstance): __module__ = base.__module__ def setUp(self): self.ob = NewStyle() AdviseNewInstance.__name__ = base.__name__+'.AdviseNewInstance' return AdviseFunction, AdviseModule, AdviseInstance, AdviseNewInstance def makeClassProvidesTests(base): """Generate a set of class-provides-oriented test classes using 'base'""" class AdviseClass(base): def setUp(self): class Classic: pass self.ob = Classic class AdviseType(AdviseClass): def setUp(self): class Class(object): pass self.ob = Class return AdviseClass, AdviseType def makeMetaClassProvidesTests(base): """Generate a set of class-provides-oriented test classes using 'base'""" # Notice that we don't test the *metaclass* of the next two configurations; # it would fail because the metaclass itself can't be adapted to an open # provider, because it has a __conform__ method (from ProviderMixin). For # that to work, there'd have to be *another* metalevel. class AdviseMixinClass(base): def setUp(self): class Meta(ProviderMixin, type): pass class Test(object): __metaclass__ = Meta self.ob = Test class AdviseMixinMultiMeta2(base): def setUp(self): class Meta(ProviderMixin, type): pass class Test(ProviderMixin,object): __metaclass__ = Meta self.ob = Test return AdviseMixinClass, AdviseMixinMultiMeta2 def makeClassTests(base): """Generate a set of class-oriented test classes using 'base'""" class TestClassic(base): __module__ = base.__module__ def setUp(self): class Classic: pass self.klass = Classic self.ob = Classic() TestClassic.__name__ = base.__name__+'.TestClassic' class TestBuiltin(base): __module__ = base.__module__ def setUp(self): # Note: We need a type with a no-arguments constructor class Newstyle(list): __slots__ = () self.klass = Newstyle self.ob = Newstyle() TestBuiltin.__name__ = base.__name__+'.TestBuiltin' class TestMetaclass(base): __module__ = base.__module__ def setUp(self): class Meta(type): pass self.klass = Meta class Base(object): __metaclass__ = Meta self.ob = Base def make(self,klass): return klass('Dummy',(object,),{}) TestMetaclass.__name__ = base.__name__+'.TestMetaclass' class TestMetaInstance(base): __module__ = base.__module__ def setUp(self): class Meta(type): pass class Base(object): __metaclass__ = Meta self.klass = Base self.ob = Base() TestMetaInstance.__name__ = base.__name__+'.TestMetaInstance' return TestClassic, TestBuiltin, TestMetaclass, TestMetaInstance PK86Prrprotocols/tests/checks.pyc; ~ *Fc @s.dZddddddddd d g Zd klZlZlZd kTd ZdZdefdYZ de fdYZ dfdYZ de fdYZ de fdYZ de fdYZd fdYZdefdYZdZdZdZdZdS(sBasic test setupssTestBasesImplementationCheckssProviderCheckssInstanceImplementationCheckssmakeClassTestssClassProvidesCheckssAdaptiveCheckssSimpleAdaptiveCheckssmakeMetaClassProvidesTestssBasicClassProvidesChecks(sTestCases makeSuites TestSuite(s*cCsd|fSdS(Nsa1(sob(sob((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysa1scCsd|fSdS(Nsa2(sob(sob((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysa2scBstZdZeeZeeZdZdZdZdZ dZ dZ dZ dZ d Zd ZRS( sNon-adapter instance testscCs|i|it|ijpt|i|ittjpt|itttjptt|itttjptt|itttjptdS(N(sselfsIAsobsNonesAssertionErrorsIBsadapt(sself((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysassertObProvidesOnlyA1s &# #cCs|i|it|ijpt|i|it|ijptt|itttjptt|itttjptt|itttjptdS(N(sselfsIAsobsNonesAssertionErrorsIBsadapt(sself((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysassertObProvidesAandB8s &&##cCsVy|i||Wn;tj o/}|id||||fjpt nXdS(NsAmbiguous adapter choice( sselfsdeclareObAdaptssa2sifacess TypeErrorsvsargssa1sd1sd2sAssertionError(sselfsa1sa2sd1sd2sifacessv((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysassertAmbiguous?scCs |SdS(N(sklass(sselfsklass((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysmakeEscsCdifdY}|itijptdS(NsICcs9tZedigdejoed=nRS(NsprotocolIsSubsetOfsself(s__name__s __module__sadvisesselfsIAslocals((sself(s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysICLs(sselfs InterfacesICsobsNonesAssertionError(sselfsIC((sselfs;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysassertObProvidesSubsetOfAIscCs:d|fdY}d|fdY}||fSdS(NsM1cBstZRS(N(s__name__s __module__(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysM1TssM2cBstZRS(N(s__name__s __module__(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysM2Us(sbasesM1sM2(sselfsbasesM1sM2((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pys setupBasesSscCsd|i|t|jpt|i|ttjpt|i|t|jptdS(N(sselfsIAsM1sNonesAssertionErrorsIBsM2(sselfsM1sM2((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pys#assertM1ProvidesOnlyAandM2ProvidesBYs  cCsjy|f|_Wntj onBX|i|t|jpt|i |t|jptdS(N( sM2sM1s __bases__s TypeErrorsselfsIAsm1sNonesAssertionErrorsIB(sselfsM1sM2sm1sm2((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pys#assertChangingBasesChangesInterface_s  cCs|i|it|ijpt|i|it|ijpt||it|ijpt||it|ijptdS(N(sselfsIAsobsNonesAssertionErrorsIBsICsID(sselfsICsID((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysassertObProvidesABCDhs&&#cCs|i|ittjpt|i|ittjpt||it|ijpt||it|ijptdS(N(sselfsIAsobsNonesAssertionErrorsIBsICsID(sselfsICsID((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysassertObProvidesCandDnotAorBns###(s__name__s __module__s__doc__s staticmethodsa1sa2sassertObProvidesOnlyAsassertObProvidesAandBsassertAmbiguoussmakesassertObProvidesSubsetOfAs setupBasess#assertM1ProvidesOnlyAandM2ProvidesBs#assertChangingBasesChangesInterfacesassertObProvidesABCDsassertObProvidesCandDnotAorB(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysTestBase*s          cBs2tZdZdZdZdZdZRS(s+Non-adapter specific-object-provides checkscCst|id|dS(Nsprovides(s adviseObjectsselfsobsifaces(sselfsifaces((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysdeclareObImplementsscCs t|d|d|igdS(Nsprovidess forObjects(sdeclareAdaptersfactorysifacessselfsob(sselfsfactorysifaces((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysdeclareObAdaptsscCs!|i|ig|idS(N(sselfsdeclareObImplementssIAsassertObProvidesOnlyA(sself((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyscheckSimpleRegisterscCs!|i|ig|idS(N(sselfsdeclareObImplementssIBsassertObProvidesAandB(sself((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyscheckImpliedRegisters(s__name__s __module__s__doc__sdeclareObImplementssdeclareObAdaptsscheckSimpleRegisterscheckImpliedRegister(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysProviderChecks|s    cBs tZdZdZdZRS(s}Simple adapter-oriented checks that Twisted can handle (Well, it handles them as long as all the interfaces are Twisted)cCs!|i|ig|idS(N(sselfsdeclareObImplementssIAsassertObProvidesSubsetOfA(sself((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyscheckDelayedImplicationscCsd|ifdY}d|fdY}|i|g|i||ttd|igd|g|i ||dS(NsICcBstZRS(N(s__name__s __module__(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysICssIDcBstZRS(N(s__name__s __module__(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysIDssprovidess forProtocols( sselfs InterfacesICsIDsdeclareObImplementssassertObProvidesCandDnotAorBsdeclareAdaptersNO_ADAPTER_NEEDEDsIBsassertObProvidesABCD(sselfsICsID((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyscheckIndirectImplications (s__name__s __module__s__doc__scheckDelayedImplicationscheckIndirectImplication(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysSimpleAdaptiveCheckss  cBs2tZdZdZdZdZdZRS(sLGeneral adapter/protocol implication checks Twisted can't handle these.cCsB|i|i|ig|i|i|idd|igdS(Ni(sselfsdeclareObAdaptssa1sIAsassertAmbiguoussa2(sself((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyscheckAmbiguityscCs|i|i|ig|i|i|itd|if|i|i|ig|i|i|itd|ifdS(Nsa1sa2( sselfsdeclareObAdaptssa1sIBs assertEqualssIAsobsNonesa2(sself((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyscheckOverrideDepths(cCsd|ifdY}t|id|gd|ig|i|i|ig|i||i t dd|i ffdS(NsICcBstZRS(N(s__name__s __module__(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysICssprovidess forProtocolssa2sa1( sselfs InterfacesICsdeclareAdaptersa2sIAsdeclareObAdaptssa1s assertEqualsobsNone(sselfsIC((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pys checkComposeds"cCs|it|ig|i|ittjpt|i|ig|i|it|ijpt|it|ig|i|it|ijptdS(N(sselfsdeclareObAdaptssDOES_NOT_SUPPORTsIAsobsNonesAssertionErrorsdeclareObImplements(sself((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyscheckLateDefinitions #&(s__name__s __module__s__doc__scheckAmbiguityscheckOverrideDepths checkComposedscheckLateDefinition(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysAdaptiveCheckss    cBs2tZdZdZdZdZdZRS(s*Non-adapter class-instances-provide checkscCst|i|dS(N(sdeclareImplementationsselfsklasssifaces(sselfsifaces((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysdeclareObImplementsscCs t|d|d|igdS(NsprovidessforTypes(sdeclareAdaptersfactorysifacessselfsklass(sselfsfactorysifaces((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysdeclareObAdaptsscCs!|i|ig|idS(N(sselfsdeclareObImplementssIAsassertObProvidesOnlyA(sself((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyscheckSimpleRegisterscCs!|i|ig|idS(N(sselfsdeclareObImplementssIBsassertObProvidesAandB(sself((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyscheckImpliedRegisters(s__name__s __module__s__doc__sdeclareObImplementssdeclareObAdaptsscheckSimpleRegisterscheckImpliedRegister(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysInstanceImplementationCheckss    cBs)tZdZdZdZdZRS(s4Non-adapter class-instances vs. class-provide checkscCs:|i|ig|i|ittjptdS(N(sselfsdeclareObImplementssIAsklasssNonesAssertionError(sself((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyscheckNoClassPassThruscCs|i|igd|ifdY}|i|}|i|t|jpt|i |t|jpt|i |ttjpt|i|ttjptdS(NsSubcBstZRS(N(s__name__s __module__(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysSubs( sselfsdeclareObImplementssIBsklasssSubsmakesinstsNonesAssertionErrorsIA(sselfsinstsSub((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyscheckInheritedDeclarations   csiigdifdY}i|}i|t|jpt i|ttjpt t |digi|t|jpt dS(NsSubcstZedigRS(NsinstancesDoNotProvide(s__name__s __module__sadvisesselfsIB((sself(s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysSub#ssinstancesProvide( sselfsdeclareObImplementssIBsklasssSubsmakesinstsIAsNonesAssertionErrorsdeclareImplementation(sselfsinstsSub((sselfs;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pys checkRejectInheritanceAndReplace s  (s__name__s __module__s__doc__scheckNoClassPassThruscheckInheritedDeclarations checkRejectInheritanceAndReplace(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysImplementationChecks s   cBs tZdZdZdZRS(s,Object-provides checks for classes and typescCsI|i}t|id|ig|i|ttjptdS(Nsprovides(sselfsobsinsts adviseObjectsIAsNonesAssertionError(sselfsinst((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyscheckNoInstancePassThruOs cCsn|i|i\}}t|d|igt|d|ig|i|||i ||||dS(Nsprovides( sselfs setupBasessobsM1sM2s adviseObjectsIAsIBs#assertM1ProvidesOnlyAandM2ProvidesBs#assertChangingBasesChangesInterface(sselfsM1sM2((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyscheckChangingBasesTs (s__name__s __module__s__doc__scheckNoInstancePassThruscheckChangingBases(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysBasicClassProvidesChecksIs  cBstZdZdZRS(NcCsvd|ifdY}t|id|ig|i|t|jpt|i|t|jptdS(NsSubcBstZRS(N(s__name__s __module__(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysSubassprovides(sselfsobsSubs adviseObjectsIBsNonesAssertionErrorsIA(sselfsSub((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyscheckInheritedDeclaration`s cstidigdifdY}i|t|jpti|ttjptt|digi|t|jptdS(NsprovidessSubcstZedigRS(NsclassDoesNotProvide(s__name__s __module__sadvisesselfsIB((sself(s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysSubjs(s adviseObjectsselfsobsIBsSubsIAsNonesAssertionError(sselfsSub((sselfs;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pys checkRejectInheritanceAndReplacegs   (s__name__s __module__scheckInheritedDeclarations checkRejectInheritanceAndReplace(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysClassProvidesChecks\s csdfdY}id|_dfdY}id|_dfdY}id |_d |fd Y}id |_||||fSd S(s=Generate a set of instance-oriented test classes using 'base'sAdviseFunctioncstZiZdZRS(NcCsd}||_dS(NcCsdS(N((sfoosbar((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysaFuncys(saFuncsselfsob(sselfsaFunc((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyssetUpxs (s__name__s __module__sbasessetUp((sbase(s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysAdviseFunctionvs s.AdviseFunctions AdviseModulecstZiZdZRS(NcCs dkl}|d|_dS(N(s ModuleTypesx(stypess ModuleTypesselfsob(sselfs ModuleType((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyssetUps (s__name__s __module__sbasessetUp((sbase(s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pys AdviseModule~s s .AdviseModulesAdviseInstancecs&tZiZdZdZRS(Ncs|_dS(N(s Picklablesselfsob(sself(s Picklable(s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyssetUpscCsedkl}l}t|id|ig|||i}|i|t|jpt dS(N(sloadssdumpssprovides( scPicklesloadssdumpss adviseObjectsselfsobsIPuresnewObsNonesAssertionError(sselfsnewObsdumpssloads((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pys checkPicklings(s__name__s __module__sbasessetUps checkPickling((s Picklablesbase(s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysAdviseInstances  s.AdviseInstancesAdviseNewInstancecstZiZdZRS(Ncs|_dS(N(sNewStylesselfsob(sself(sNewStyle(s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyssetUps(s__name__s __module__sbasessetUp((sNewStylesbase(s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysAdviseNewInstances s.AdviseNewInstanceN(sbasesAdviseFunctions__name__s AdviseModulesAdviseInstancesAdviseNewInstance(sbases PicklablesNewStyles AdviseModulesAdviseFunctionsAdviseInstancesAdviseNewInstance((sbases PicklablesNewStyles;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysmakeInstanceTestsrs cCs:d|fdY}d|fdY}||fSdS(sCGenerate a set of class-provides-oriented test classes using 'base's AdviseClasscBstZdZRS(NcCs dfdY}||_dS(NsClassiccBstZRS(N(s__name__s __module__(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysClassics(sClassicsselfsob(sselfsClassic((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyssetUps(s__name__s __module__ssetUp(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pys AdviseClassss AdviseTypecBstZdZRS(NcCs#dtfdY}||_dS(NsClasscBstZRS(N(s__name__s __module__(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysClasss(sobjectsClasssselfsob(sselfsClass((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyssetUps(s__name__s __module__ssetUp(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pys AdviseTypesN(sbases AdviseClasss AdviseType(sbases AdviseTypes AdviseClass((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysmakeClassProvidesTestsscCs:d|fdY}d|fdY}||fSdS(sCGenerate a set of class-provides-oriented test classes using 'base'sAdviseMixinClasscBstZdZRS(Ncs?dttfdYdtfdY}||_dS(NsMetacBstZRS(N(s__name__s __module__(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysMetassTestcstZZRS(N(s__name__s __module__sMetas __metaclass__((sMeta(s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysTests(s ProviderMixinstypesMetasobjectsTestsselfsob(sselfsMetasTest((sMetas;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyssetUps(s__name__s __module__ssetUp(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysAdviseMixinClassssAdviseMixinMultiMeta2cBstZdZRS(NcsBdttfdYdttfdY}||_dS(NsMetacBstZRS(N(s__name__s __module__(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysMetassTestcstZZRS(N(s__name__s __module__sMetas __metaclass__((sMeta(s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysTests(s ProviderMixinstypesMetasobjectsTestsselfsob(sselfsMetasTest((sMetas;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyssetUps(s__name__s __module__ssetUp(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysAdviseMixinMultiMeta2sN(sbasesAdviseMixinClasssAdviseMixinMultiMeta2(sbasesAdviseMixinMultiMeta2sAdviseMixinClass((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysmakeMetaClassProvidesTestsscsdfdY}id|_dfdY}id|_dfdY}id |_d fd Y}id |_||||fSd S(s:Generate a set of class-oriented test classes using 'base's TestClassiccstZiZdZRS(NcCs,dfdY}||_||_dS(NsClassiccBstZRS(N(s__name__s __module__(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysClassics(sClassicsselfsklasssob(sselfsClassic((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyssetUps (s__name__s __module__sbasessetUp((sbase(s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pys TestClassics s .TestClassics TestBuiltincstZiZdZRS(NcCs/dtfdY}||_||_dS(NsNewstylecBstZfZRS(N(s__name__s __module__s __slots__(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysNewstyles(slistsNewstylesselfsklasssob(sselfsNewstyle((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyssetUps (s__name__s __module__sbasessetUp((sbase(s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pys TestBuiltins s .TestBuiltins TestMetaclasscs#tZiZdZdZRS(NcsEdtfdY|_dtfdY}||_dS(NsMetacBstZRS(N(s__name__s __module__(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysMetassBasecstZZRS(N(s__name__s __module__sMetas __metaclass__((sMeta(s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysBases(stypesMetasselfsklasssobjectsBasesob(sselfsBasesMeta((sMetas;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyssetUps cCs|dtfhSdS(NsDummy(sklasssobject(sselfsklass((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysmakes(s__name__s __module__sbasessetUpsmake((sbase(s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pys TestMetaclasss  s.TestMetaclasssTestMetaInstancecstZiZdZRS(NcsHdtfdYdtfdY}||_||_dS(NsMetacBstZRS(N(s__name__s __module__(((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysMetassBasecstZZRS(N(s__name__s __module__sMetas __metaclass__((sMeta(s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysBases(stypesMetasobjectsBasesselfsklasssob(sselfsBasesMeta((sMetas;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pyssetUps (s__name__s __module__sbasessetUp((sbase(s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysTestMetaInstances s.TestMetaInstanceN(sbases TestClassics__name__s TestBuiltins TestMetaclasssTestMetaInstance(sbases TestBuiltins TestMetaclasssTestMetaInstances TestClassic((sbases;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pysmakeClassTestss N(s__doc__s__all__sunittestsTestCases makeSuites TestSuites protocolssa1sa2sTestBasesProviderCheckssSimpleAdaptiveCheckssAdaptiveCheckssInstanceImplementationCheckssImplementationCheckssBasicClassProvidesCheckssClassProvidesCheckssmakeInstanceTestssmakeClassProvidesTestssmakeMetaClassProvidesTestssmakeClassTests(s TestSuitesTestBasesa1sImplementationCheckss__all__smakeClassTestssmakeClassProvidesTestss makeSuitesClassProvidesCheckssTestCasesProviderCheckssa2sAdaptiveCheckssmakeInstanceTestssInstanceImplementationCheckssSimpleAdaptiveCheckssmakeMetaClassProvidesTestssBasicClassProvidesChecks((s;build/bdist.darwin-8.9.1-i386/egg/protocols/tests/checks.pys?s"$  R)))= )  PKOk6fv protocols/tests/doctest.py# Module doctest. # Released to the public domain 16-Jan-2001, by Tim Peters (tim@python.org). # Major enhancements and refactoring by: # Jim Fulton # Edward Loper # Provided as-is; use at your own risk; no warranty; no promises; enjoy! try: basestring except NameError: basestring = str,unicode try: enumerate except NameError: def enumerate(seq): return zip(range(len(seq)),seq) r"""Module doctest -- a framework for running examples in docstrings. In simplest use, end each module M to be tested with: def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test() Then running the module as a script will cause the examples in the docstrings to get executed and verified: python M.py This won't display anything unless an example fails, in which case the failing example(s) and the cause(s) of the failure(s) are printed to stdout (why not stderr? because stderr is a lame hack <0.2 wink>), and the final line of output is "Test failed.". Run it with the -v switch instead: python M.py -v and a detailed report of all examples tried is printed to stdout, along with assorted summaries at the end. You can force verbose mode by passing "verbose=True" to testmod, or prohibit it by passing "verbose=False". In either of those cases, sys.argv is not examined by testmod. There are a variety of other ways to run doctests, including integration with the unittest framework, and support for running non-Python text files containing doctests. There are also many ways to override parts of doctest's default behaviors. See the Library Reference Manual for details. """ __docformat__ = 'reStructuredText en' __all__ = [ # 0, Option Flags 'register_optionflag', 'DONT_ACCEPT_TRUE_FOR_1', 'DONT_ACCEPT_BLANKLINE', 'NORMALIZE_WHITESPACE', 'ELLIPSIS', 'IGNORE_EXCEPTION_DETAIL', 'COMPARISON_FLAGS', 'REPORT_UDIFF', 'REPORT_CDIFF', 'REPORT_NDIFF', 'REPORT_ONLY_FIRST_FAILURE', 'REPORTING_FLAGS', # 1. Utility Functions 'is_private', # 2. Example & DocTest 'Example', 'DocTest', # 3. Doctest Parser 'DocTestParser', # 4. Doctest Finder 'DocTestFinder', # 5. Doctest Runner 'DocTestRunner', 'OutputChecker', 'DocTestFailure', 'UnexpectedException', 'DebugRunner', # 6. Test Functions 'testmod', 'testfile', 'run_docstring_examples', # 7. Tester 'Tester', # 8. Unittest Support 'DocTestSuite', 'DocFileSuite', 'set_unittest_reportflags', # 9. Debugging Support 'script_from_examples', 'testsource', 'debug_src', 'debug', ] import __future__ import sys, traceback, inspect, linecache, os, re, types import unittest, difflib, pdb, tempfile import warnings from StringIO import StringIO # Don't whine about the deprecated is_private function in this # module's tests. warnings.filterwarnings("ignore", "is_private", DeprecationWarning, __name__, 0) # There are 4 basic classes: # - Example: a pair, plus an intra-docstring line number. # - DocTest: a collection of examples, parsed from a docstring, plus # info about where the docstring came from (name, filename, lineno). # - DocTestFinder: extracts DocTests from a given object's docstring and # its contained objects' docstrings. # - DocTestRunner: runs DocTest cases, and accumulates statistics. # # So the basic picture is: # # list of: # +------+ +---------+ +-------+ # |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results| # +------+ +---------+ +-------+ # | Example | # | ... | # | Example | # +---------+ # Option constants. OPTIONFLAGS_BY_NAME = {} def register_optionflag(name): flag = 1 << len(OPTIONFLAGS_BY_NAME) OPTIONFLAGS_BY_NAME[name] = flag return flag DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1') DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE') NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE') ELLIPSIS = register_optionflag('ELLIPSIS') IGNORE_EXCEPTION_DETAIL = register_optionflag('IGNORE_EXCEPTION_DETAIL') COMPARISON_FLAGS = (DONT_ACCEPT_TRUE_FOR_1 | DONT_ACCEPT_BLANKLINE | NORMALIZE_WHITESPACE | ELLIPSIS | IGNORE_EXCEPTION_DETAIL) REPORT_UDIFF = register_optionflag('REPORT_UDIFF') REPORT_CDIFF = register_optionflag('REPORT_CDIFF') REPORT_NDIFF = register_optionflag('REPORT_NDIFF') REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE') REPORTING_FLAGS = (REPORT_UDIFF | REPORT_CDIFF | REPORT_NDIFF | REPORT_ONLY_FIRST_FAILURE) # Special string markers for use in `want` strings: BLANKLINE_MARKER = '' ELLIPSIS_MARKER = '...' ###################################################################### ## Table of Contents ###################################################################### # 1. Utility Functions # 2. Example & DocTest -- store test cases # 3. DocTest Parser -- extracts examples from strings # 4. DocTest Finder -- extracts test cases from objects # 5. DocTest Runner -- runs test cases # 6. Test Functions -- convenient wrappers for testing # 7. Tester Class -- for backwards compatibility # 8. Unittest Support # 9. Debugging Support # 10. Example Usage ###################################################################### ## 1. Utility Functions ###################################################################### def is_private(prefix, base): """prefix, base -> true iff name prefix + "." + base is "private". Prefix may be an empty string, and base does not contain a period. Prefix is ignored (although functions you write conforming to this protocol may make use of it). Return true iff base begins with an (at least one) underscore, but does not both begin and end with (at least) two underscores. >>> is_private("a.b", "my_func") False >>> is_private("____", "_my_func") True >>> is_private("someclass", "__init__") False >>> is_private("sometypo", "__init_") True >>> is_private("x.y.z", "_") True >>> is_private("_x.y.z", "__") False >>> is_private("", "") # senseless but consistent False """ warnings.warn("is_private is deprecated; it wasn't useful; " "examine DocTestFinder.find() lists instead", DeprecationWarning, stacklevel=2) return base[:1] == "_" and not base[:2] == "__" == base[-2:] def _extract_future_flags(globs): """ Return the compiler-flags associated with the future features that have been imported into the given namespace (globs). """ flags = 0 for fname in __future__.all_feature_names: feature = globs.get(fname, None) if feature is getattr(__future__, fname): flags |= feature.compiler_flag return flags def _normalize_module(module, depth=2): """ Return the module specified by `module`. In particular: - If `module` is a module, then return module. - If `module` is a string, then import and return the module with that name. - If `module` is None, then return the calling module. The calling module is assumed to be the module of the stack frame at the given depth in the call stack. """ if inspect.ismodule(module): return module elif isinstance(module, (str, unicode)): return __import__(module, globals(), locals(), ["*"]) elif module is None: return sys.modules[sys._getframe(depth).f_globals['__name__']] else: raise TypeError("Expected a module, string, or None") def _indent(s, indent=4): """ Add the given number of space characters to the beginning every non-blank line in `s`, and return the result. """ # This regexp matches the start of non-blank lines: return re.sub('(?m)^(?!$)', indent*' ', s) def _exception_traceback(exc_info): """ Return a string containing a traceback message for the given exc_info tuple (as returned by sys.exc_info()). """ # Get a traceback message. excout = StringIO() exc_type, exc_val, exc_tb = exc_info traceback.print_exception(exc_type, exc_val, exc_tb, file=excout) return excout.getvalue() # Override some StringIO methods. class _SpoofOut(StringIO): def getvalue(self): result = StringIO.getvalue(self) # If anything at all was written, make sure there's a trailing # newline. There's no way for the expected output to indicate # that a trailing newline is missing. if result and not result.endswith("\n"): result += "\n" # Prevent softspace from screwing up the next test case, in # case they used print with a trailing comma in an example. if hasattr(self, "softspace"): del self.softspace return result def truncate(self, size=None): StringIO.truncate(self, size) if hasattr(self, "softspace"): del self.softspace # Worst-case linear-time ellipsis matching. def _ellipsis_match(want, got): """ Essentially the only subtle case: >>> _ellipsis_match('aa...aa', 'aaa') False """ if want.find(ELLIPSIS_MARKER)==-1: return want == got # Find "the real" strings. ws = want.split(ELLIPSIS_MARKER) assert len(ws) >= 2 # Deal with exact matches possibly needed at one or both ends. startpos, endpos = 0, len(got) w = ws[0] if w: # starts with exact match if got.startswith(w): startpos = len(w) del ws[0] else: return False w = ws[-1] if w: # ends with exact match if got.endswith(w): endpos -= len(w) del ws[-1] else: return False if startpos > endpos: # Exact end matches required more characters than we have, as in # _ellipsis_match('aa...aa', 'aaa') return False # For the rest, we only need to find the leftmost non-overlapping # match for each piece. If there's no overall match that way alone, # there's no overall match period. for w in ws: # w may be '' at times, if there are consecutive ellipses, or # due to an ellipsis at the start or end of `want`. That's OK. # Search for an empty string succeeds, and doesn't change startpos. startpos = got.find(w, startpos, endpos) if startpos < 0: return False startpos += len(w) return True def _comment_line(line): "Return a commented form of the given line" line = line.rstrip() if line: return '# '+line else: return '#' class _OutputRedirectingPdb(pdb.Pdb): """ A specialized version of the python debugger that redirects stdout to a given stream when interacting with the user. Stdout is *not* redirected when traced code is executed. """ def __init__(self, out): self.__out = out pdb.Pdb.__init__(self) def trace_dispatch(self, *args): # Redirect stdout to the given stream. save_stdout = sys.stdout sys.stdout = self.__out # Call Pdb's trace dispatch method. try: return pdb.Pdb.trace_dispatch(self, *args) finally: sys.stdout = save_stdout # [XX] Normalize with respect to os.path.pardir? def _module_relative_path(module, path): if not inspect.ismodule(module): raise TypeError, 'Expected a module: %r' % module if path.startswith('/'): raise ValueError, 'Module-relative files may not have absolute paths' # Find the base directory for the path. if hasattr(module, '__file__'): # A normal module/package basedir = os.path.split(module.__file__)[0] elif module.__name__ == '__main__': # An interactive session. if len(sys.argv)>0 and sys.argv[0] != '': basedir = os.path.split(sys.argv[0])[0] else: basedir = os.curdir else: # A module w/o __file__ (this includes builtins) raise ValueError("Can't resolve paths relative to the module " + module + " (it has no __file__)") # Combine the base directory and the path. return os.path.join(basedir, *(path.split('/'))) ###################################################################### ## 2. Example & DocTest ###################################################################### ## - An "example" is a pair, where "source" is a ## fragment of source code, and "want" is the expected output for ## "source." The Example class also includes information about ## where the example was extracted from. ## ## - A "doctest" is a collection of examples, typically extracted from ## a string (such as an object's docstring). The DocTest class also ## includes information about where the string was extracted from. class Example: """ A single doctest example, consisting of source code and expected output. `Example` defines the following attributes: - source: A single Python statement, always ending with a newline. The constructor adds a newline if needed. - want: The expected output from running the source code (either from stdout, or a traceback in case of exception). `want` ends with a newline unless it's empty, in which case it's an empty string. The constructor adds a newline if needed. - exc_msg: The exception message generated by the example, if the example is expected to generate an exception; or `None` if it is not expected to generate an exception. This exception message is compared against the return value of `traceback.format_exception_only()`. `exc_msg` ends with a newline unless it's `None`. The constructor adds a newline if needed. - lineno: The line number within the DocTest string containing this Example where the Example begins. This line number is zero-based, with respect to the beginning of the DocTest. - indent: The example's indentation in the DocTest string. I.e., the number of space characters that preceed the example's first prompt. - options: A dictionary mapping from option flags to True or False, which is used to override default options for this example. Any option flags not contained in this dictionary are left at their default value (as specified by the DocTestRunner's optionflags). By default, no options are set. """ def __init__(self, source, want, exc_msg=None, lineno=0, indent=0, options=None): # Normalize inputs. if not source.endswith('\n'): source += '\n' if want and not want.endswith('\n'): want += '\n' if exc_msg is not None and not exc_msg.endswith('\n'): exc_msg += '\n' # Store properties. self.source = source self.want = want self.lineno = lineno self.indent = indent if options is None: options = {} self.options = options self.exc_msg = exc_msg class DocTest: """ A collection of doctest examples that should be run in a single namespace. Each `DocTest` defines the following attributes: - examples: the list of examples. - globs: The namespace (aka globals) that the examples should be run in. - name: A name identifying the DocTest (typically, the name of the object whose docstring this DocTest was extracted from). - filename: The name of the file that this DocTest was extracted from, or `None` if the filename is unknown. - lineno: The line number within filename where this DocTest begins, or `None` if the line number is unavailable. This line number is zero-based, with respect to the beginning of the file. - docstring: The string that the examples were extracted from, or `None` if the string is unavailable. """ def __init__(self, examples, globs, name, filename, lineno, docstring): """ Create a new DocTest containing the given examples. The DocTest's globals are initialized with a copy of `globs`. """ assert not isinstance(examples, basestring), \ "DocTest no longer accepts str; use DocTestParser instead" self.examples = examples self.docstring = docstring self.globs = globs.copy() self.name = name self.filename = filename self.lineno = lineno def __repr__(self): if len(self.examples) == 0: examples = 'no examples' elif len(self.examples) == 1: examples = '1 example' else: examples = '%d examples' % len(self.examples) return ('' % (self.name, self.filename, self.lineno, examples)) # This lets us sort tests by name: def __cmp__(self, other): if not isinstance(other, DocTest): return -1 return cmp((self.name, self.filename, self.lineno, id(self)), (other.name, other.filename, other.lineno, id(other))) ###################################################################### ## 3. DocTestParser ###################################################################### class DocTestParser: """ A class used to parse strings containing doctest examples. """ # This regular expression is used to find doctest examples in a # string. It defines three groups: `source` is the source code # (including leading indentation and prompts); `indent` is the # indentation of the first (PS1) line of the source code; and # `want` is the expected output (including leading indentation). _EXAMPLE_RE = re.compile(r''' # Source consists of a PS1 line followed by zero or more PS2 lines. (?P (?:^(?P [ ]*) >>> .*) # PS1 line (?:\n [ ]* \.\.\. .*)*) # PS2 lines \n? # Want consists of any non-blank lines that do not start with PS1. (?P (?:(?![ ]*$) # Not a blank line (?![ ]*>>>) # Not a line starting with PS1 .*$\n? # But any other line )*) ''', re.MULTILINE | re.VERBOSE) # A regular expression for handling `want` strings that contain # expected exceptions. It divides `want` into three pieces: # - the traceback header line (`hdr`) # - the traceback stack (`stack`) # - the exception message (`msg`), as generated by # traceback.format_exception_only() # `msg` may have multiple lines. We assume/require that the # exception message is the first non-indented line starting with a word # character following the traceback header line. _EXCEPTION_RE = re.compile(r""" # Grab the traceback header. Different versions of Python have # said different things on the first traceback line. ^(?P Traceback\ \( (?: most\ recent\ call\ last | innermost\ last ) \) : ) \s* $ # toss trailing whitespace on the header. (?P .*?) # don't blink: absorb stuff until... ^ (?P \w+ .*) # a line *starts* with alphanum. """, re.VERBOSE | re.MULTILINE | re.DOTALL) # A callable returning a true value iff its argument is a blank line # or contains a single comment. _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match def parse(self, string, name=''): """ Divide the given string into examples and intervening text, and return them as a list of alternating Examples and strings. Line numbers for the Examples are 0-based. The optional argument `name` is a name identifying this string, and is only used for error messages. """ string = string.expandtabs() # If all lines begin with the same indentation, then strip it. min_indent = self._min_indent(string) if min_indent > 0: string = '\n'.join([l[min_indent:] for l in string.split('\n')]) output = [] charno, lineno = 0, 0 # Find all doctest examples in the string: for m in self._EXAMPLE_RE.finditer(string): # Add the pre-example text to `output`. output.append(string[charno:m.start()]) # Update lineno (lines before this example) lineno += string.count('\n', charno, m.start()) # Extract info from the regexp match. (source, options, want, exc_msg) = \ self._parse_example(m, name, lineno) # Create an Example, and add it to the list. if not self._IS_BLANK_OR_COMMENT(source): output.append( Example(source, want, exc_msg, lineno=lineno, indent=min_indent+len(m.group('indent')), options=options) ) # Update lineno (lines inside this example) lineno += string.count('\n', m.start(), m.end()) # Update charno. charno = m.end() # Add any remaining post-example text to `output`. output.append(string[charno:]) return output def get_doctest(self, string, globs, name, filename, lineno): """ Extract all doctest examples from the given string, and collect them into a `DocTest` object. `globs`, `name`, `filename`, and `lineno` are attributes for the new `DocTest` object. See the documentation for `DocTest` for more information. """ return DocTest(self.get_examples(string, name), globs, name, filename, lineno, string) def get_examples(self, string, name=''): """ Extract all doctest examples from the given string, and return them as a list of `Example` objects. Line numbers are 0-based, because it's most common in doctests that nothing interesting appears on the same line as opening triple-quote, and so the first interesting line is called \"line 1\" then. The optional argument `name` is a name identifying this string, and is only used for error messages. """ return [x for x in self.parse(string, name) if isinstance(x, Example)] def _parse_example(self, m, name, lineno): """ Given a regular expression match from `_EXAMPLE_RE` (`m`), return a pair `(source, want)`, where `source` is the matched example's source code (with prompts and indentation stripped); and `want` is the example's expected output (with indentation stripped). `name` is the string's name, and `lineno` is the line number where the example starts; both are used for error messages. """ # Get the example's indentation level. indent = len(m.group('indent')) # Divide source into lines; check that they're properly # indented; and then strip their indentation & prompts. source_lines = m.group('source').split('\n') self._check_prompt_blank(source_lines, indent, name, lineno) self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno) source = '\n'.join([sl[indent+4:] for sl in source_lines]) # Divide want into lines; check that it's properly indented; and # then strip the indentation. Spaces before the last newline should # be preserved, so plain rstrip() isn't good enough. want = m.group('want') want_lines = want.split('\n') if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]): del want_lines[-1] # forget final newline & spaces after it self._check_prefix(want_lines, ' '*indent, name, lineno + len(source_lines)) want = '\n'.join([wl[indent:] for wl in want_lines]) # If `want` contains a traceback message, then extract it. m = self._EXCEPTION_RE.match(want) if m: exc_msg = m.group('msg') else: exc_msg = None # Extract options from the source. options = self._find_options(source, name, lineno) return source, options, want, exc_msg # This regular expression looks for option directives in the # source code of an example. Option directives are comments # starting with "doctest:". Warning: this may give false # positives for string-literals that contain the string # "#doctest:". Eliminating these false positives would require # actually parsing the string; but we limit them by ignoring any # line containing "#doctest:" that is *followed* by a quote mark. _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$', re.MULTILINE) def _find_options(self, source, name, lineno): """ Return a dictionary containing option overrides extracted from option directives in the given source string. `name` is the string's name, and `lineno` is the line number where the example starts; both are used for error messages. """ options = {} # (note: with the current regexp, this will match at most once:) for m in self._OPTION_DIRECTIVE_RE.finditer(source): option_strings = m.group(1).replace(',', ' ').split() for option in option_strings: if (option[0] not in '+-' or option[1:] not in OPTIONFLAGS_BY_NAME): raise ValueError('line %r of the doctest for %s ' 'has an invalid option: %r' % (lineno+1, name, option)) flag = OPTIONFLAGS_BY_NAME[option[1:]] options[flag] = (option[0] == '+') if options and self._IS_BLANK_OR_COMMENT(source): raise ValueError('line %r of the doctest for %s has an option ' 'directive on a line with no example: %r' % (lineno, name, source)) return options # This regular expression finds the indentation of every non-blank # line in a string. _INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE) def _min_indent(self, s): "Return the minimum indentation of any non-blank line in `s`" indents = [len(indent) for indent in self._INDENT_RE.findall(s)] if len(indents) > 0: return min(indents) else: return 0 def _check_prompt_blank(self, lines, indent, name, lineno): """ Given the lines of a source string (including prompts and leading indentation), check to make sure that every prompt is followed by a space character. If any line is not followed by a space character, then raise ValueError. """ for i, line in enumerate(lines): if len(line) >= indent+4 and line[indent+3] != ' ': raise ValueError('line %r of the docstring for %s ' 'lacks blank after %s: %r' % (lineno+i+1, name, line[indent:indent+3], line)) def _check_prefix(self, lines, prefix, name, lineno): """ Check that every line in the given list starts with the given prefix; if any line does not, then raise a ValueError. """ for i, line in enumerate(lines): if line and not line.startswith(prefix): raise ValueError('line %r of the docstring for %s has ' 'inconsistent leading whitespace: %r' % (lineno+i+1, name, line)) ###################################################################### ## 4. DocTest Finder ###################################################################### class DocTestFinder: """ A class used to extract the DocTests that are relevant to a given object, from its docstring and the docstrings of its contained objects. Doctests can currently be extracted from the following object types: modules, functions, classes, methods, staticmethods, classmethods, and properties. """ def __init__(self, verbose=False, parser=DocTestParser(), recurse=True, _namefilter=None, exclude_empty=True): """ Create a new doctest finder. The optional argument `parser` specifies a class or function that should be used to create new DocTest objects (or objects that implement the same interface as DocTest). The signature for this factory function should match the signature of the DocTest constructor. If the optional argument `recurse` is false, then `find` will only examine the given object, and not any contained objects. If the optional argument `exclude_empty` is false, then `find` will include tests for objects with empty docstrings. """ self._parser = parser self._verbose = verbose self._recurse = recurse self._exclude_empty = exclude_empty # _namefilter is undocumented, and exists only for temporary backward- # compatibility support of testmod's deprecated isprivate mess. self._namefilter = _namefilter def find(self, obj, name=None, module=None, globs=None, extraglobs=None): """ Return a list of the DocTests that are defined by the given object's docstring, or by any of its contained objects' docstrings. The optional parameter `module` is the module that contains the given object. If the module is not specified or is None, then the test finder will attempt to automatically determine the correct module. The object's module is used: - As a default namespace, if `globs` is not specified. - To prevent the DocTestFinder from extracting DocTests from objects that are imported from other modules. - To find the name of the file containing the object. - To help find the line number of the object within its file. Contained objects whose module does not match `module` are ignored. If `module` is False, no attempt to find the module will be made. This is obscure, of use mostly in tests: if `module` is False, or is None but cannot be found automatically, then all objects are considered to belong to the (non-existent) module, so all contained objects will (recursively) be searched for doctests. The globals for each DocTest is formed by combining `globs` and `extraglobs` (bindings in `extraglobs` override bindings in `globs`). A new copy of the globals dictionary is created for each DocTest. If `globs` is not specified, then it defaults to the module's `__dict__`, if specified, or {} otherwise. If `extraglobs` is not specified, then it defaults to {}. """ # If name was not specified, then extract it from the object. if name is None: name = getattr(obj, '__name__', None) if name is None: raise ValueError("DocTestFinder.find: name must be given " "when obj.__name__ doesn't exist: %r" % (type(obj),)) # Find the module that contains the given object (if obj is # a module, then module=obj.). Note: this may fail, in which # case module will be None. if module is False: module = None elif module is None: module = inspect.getmodule(obj) # Read the module's source code. This is used by # DocTestFinder._find_lineno to find the line number for a # given object's docstring. try: file = inspect.getsourcefile(obj) or inspect.getfile(obj) source_lines = linecache.getlines(file) if not source_lines: source_lines = None except TypeError: source_lines = None # Initialize globals, and merge in extraglobs. if globs is None: if module is None: globs = {} else: globs = module.__dict__.copy() else: globs = globs.copy() if extraglobs is not None: globs.update(extraglobs) # Recursively expore `obj`, extracting DocTests. tests = [] self._find(tests, obj, name, module, source_lines, globs, {}) return tests def _filter(self, obj, prefix, base): """ Return true if the given object should not be examined. """ return (self._namefilter is not None and self._namefilter(prefix, base)) def _from_module(self, module, object): """ Return true if the given object is defined in the given module. """ if module is None: return True elif inspect.isfunction(object): return module.__dict__ is object.func_globals elif inspect.isclass(object): return module.__name__ == object.__module__ elif inspect.getmodule(object) is not None: return module is inspect.getmodule(object) elif hasattr(object, '__module__'): return module.__name__ == object.__module__ elif isinstance(object, property): return True # [XX] no way not be sure. else: raise ValueError("object must be a class or function") def _find(self, tests, obj, name, module, source_lines, globs, seen): """ Find tests for the given object and any contained objects, and add them to `tests`. """ if self._verbose: print 'Finding tests in %s' % name # If we've already processed this object, then ignore it. if id(obj) in seen: return seen[id(obj)] = 1 # Find a test for this object, and add it to the list of tests. test = self._get_test(obj, name, module, globs, source_lines) if test is not None: tests.append(test) # Look for tests in a module's contained objects. if inspect.ismodule(obj) and self._recurse: for valname, val in obj.__dict__.items(): # Check if this contained object should be ignored. if self._filter(val, name, valname): continue valname = '%s.%s' % (name, valname) # Recurse to functions & classes. if ((inspect.isfunction(val) or inspect.isclass(val)) and self._from_module(module, val)): self._find(tests, val, valname, module, source_lines, globs, seen) # Look for tests in a module's __test__ dictionary. if inspect.ismodule(obj) and self._recurse: for valname, val in getattr(obj, '__test__', {}).items(): if not isinstance(valname, basestring): raise ValueError("DocTestFinder.find: __test__ keys " "must be strings: %r" % (type(valname),)) if not (inspect.isfunction(val) or inspect.isclass(val) or inspect.ismethod(val) or inspect.ismodule(val) or isinstance(val, basestring)): raise ValueError("DocTestFinder.find: __test__ values " "must be strings, functions, methods, " "classes, or modules: %r" % (type(val),)) valname = '%s.__test__.%s' % (name, valname) self._find(tests, val, valname, module, source_lines, globs, seen) # Look for tests in a class's contained objects. if inspect.isclass(obj) and self._recurse: for valname, val in obj.__dict__.items(): # Check if this contained object should be ignored. if self._filter(val, name, valname): continue # Special handling for staticmethod/classmethod. if isinstance(val, staticmethod): val = getattr(obj, valname) if isinstance(val, classmethod): val = getattr(obj, valname).im_func # Recurse to methods, properties, and nested classes. if ((inspect.isfunction(val) or inspect.isclass(val) or isinstance(val, property)) and self._from_module(module, val)): valname = '%s.%s' % (name, valname) self._find(tests, val, valname, module, source_lines, globs, seen) def _get_test(self, obj, name, module, globs, source_lines): """ Return a DocTest for the given object, if it defines a docstring; otherwise, return None. """ # Extract the object's docstring. If it doesn't have one, # then return None (no test for this object). if isinstance(obj, basestring): docstring = obj else: try: if obj.__doc__ is None: docstring = '' else: docstring = obj.__doc__ if not isinstance(docstring, basestring): docstring = str(docstring) except (TypeError, AttributeError): docstring = '' # Find the docstring's location in the file. lineno = self._find_lineno(obj, source_lines) # Don't bother if the docstring is empty. if self._exclude_empty and not docstring: return None # Return a DocTest for this object. if module is None: filename = None else: filename = getattr(module, '__file__', module.__name__) if filename[-4:] in (".pyc", ".pyo"): filename = filename[:-1] return self._parser.get_doctest(docstring, globs, name, filename, lineno) def _find_lineno(self, obj, source_lines): """ Return a line number of the given object's docstring. Note: this method assumes that the object has a docstring. """ lineno = None # Find the line number for modules. if inspect.ismodule(obj): lineno = 0 # Find the line number for classes. # Note: this could be fooled if a class is defined multiple # times in a single file. if inspect.isclass(obj): if source_lines is None: return None pat = re.compile(r'^\s*class\s*%s\b' % getattr(obj, '__name__', '-')) for i, line in enumerate(source_lines): if pat.match(line): lineno = i break # Find the line number for functions & methods. if inspect.ismethod(obj): obj = obj.im_func if inspect.isfunction(obj): obj = obj.func_code if inspect.istraceback(obj): obj = obj.tb_frame if inspect.isframe(obj): obj = obj.f_code if inspect.iscode(obj): lineno = getattr(obj, 'co_firstlineno', None)-1 # Find the line number where the docstring starts. Assume # that it's the first line that begins with a quote mark. # Note: this could be fooled by a multiline function # signature, where a continuation line begins with a quote # mark. if lineno is not None: if source_lines is None: return lineno+1 pat = re.compile('(^|.*:)\s*\w*("|\')') for lineno in range(lineno, len(source_lines)): if pat.match(source_lines[lineno]): return lineno # We couldn't find the line number. return None ###################################################################### ## 5. DocTest Runner ###################################################################### class DocTestRunner: """ A class used to run DocTest test cases, and accumulate statistics. The `run` method is used to process a single DocTest case. It returns a tuple `(f, t)`, where `t` is the number of test cases tried, and `f` is the number of test cases that failed. >>> tests = DocTestFinder().find(_TestClass) >>> runner = DocTestRunner(verbose=False) >>> for test in tests: ... print runner.run(test) (0, 2) (0, 1) (0, 2) (0, 2) The `summarize` method prints a summary of all the test cases that have been run by the runner, and returns an aggregated `(f, t)` tuple: >>> runner.summarize(verbose=1) 4 items passed all tests: 2 tests in _TestClass 2 tests in _TestClass.__init__ 2 tests in _TestClass.get 1 tests in _TestClass.square 7 tests in 4 items. 7 passed and 0 failed. Test passed. (0, 7) The aggregated number of tried examples and failed examples is also available via the `tries` and `failures` attributes: >>> runner.tries 7 >>> runner.failures 0 The comparison between expected outputs and actual outputs is done by an `OutputChecker`. This comparison may be customized with a number of option flags; see the documentation for `testmod` for more information. If the option flags are insufficient, then the comparison may also be customized by passing a subclass of `OutputChecker` to the constructor. The test runner's display output can be controlled in two ways. First, an output function (`out) can be passed to `TestRunner.run`; this function will be called with strings that should be displayed. It defaults to `sys.stdout.write`. If capturing the output is not sufficient, then the display output can be also customized by subclassing DocTestRunner, and overriding the methods `report_start`, `report_success`, `report_unexpected_exception`, and `report_failure`. """ # This divider string is used to separate failure messages, and to # separate sections of the summary. DIVIDER = "*" * 70 def __init__(self, checker=None, verbose=None, optionflags=0): """ Create a new test runner. Optional keyword arg `checker` is the `OutputChecker` that should be used to compare the expected outputs and actual outputs of doctest examples. Optional keyword arg 'verbose' prints lots of stuff if true, only failures if false; by default, it's true iff '-v' is in sys.argv. Optional argument `optionflags` can be used to control how the test runner compares expected output to actual output, and how it displays failures. See the documentation for `testmod` for more information. """ self._checker = checker or OutputChecker() if verbose is None: verbose = '-v' in sys.argv self._verbose = verbose self.optionflags = optionflags self.original_optionflags = optionflags # Keep track of the examples we've run. self.tries = 0 self.failures = 0 self._name2ft = {} # Create a fake output target for capturing doctest output. self._fakeout = _SpoofOut() #///////////////////////////////////////////////////////////////// # Reporting methods #///////////////////////////////////////////////////////////////// def report_start(self, out, test, example): """ Report that the test runner is about to process the given example. (Only displays a message if verbose=True) """ if self._verbose: if example.want: out('Trying:\n' + _indent(example.source) + 'Expecting:\n' + _indent(example.want)) else: out('Trying:\n' + _indent(example.source) + 'Expecting nothing\n') def report_success(self, out, test, example, got): """ Report that the given example ran successfully. (Only displays a message if verbose=True) """ if self._verbose: out("ok\n") def report_failure(self, out, test, example, got): """ Report that the given example failed. """ out(self._failure_header(test, example) + self._checker.output_difference(example, got, self.optionflags)) def report_unexpected_exception(self, out, test, example, exc_info): """ Report that the given example raised an unexpected exception. """ out(self._failure_header(test, example) + 'Exception raised:\n' + _indent(_exception_traceback(exc_info))) def _failure_header(self, test, example): out = [self.DIVIDER] if test.filename: if test.lineno is not None and example.lineno is not None: lineno = test.lineno + example.lineno + 1 else: lineno = '?' out.append('File "%s", line %s, in %s' % (test.filename, lineno, test.name)) else: out.append('Line %s, in %s' % (example.lineno+1, test.name)) out.append('Failed example:') source = example.source out.append(_indent(source)) return '\n'.join(out) #///////////////////////////////////////////////////////////////// # DocTest Running #///////////////////////////////////////////////////////////////// def __run(self, test, compileflags, out): """ Run the examples in `test`. Write the outcome of each example with one of the `DocTestRunner.report_*` methods, using the writer function `out`. `compileflags` is the set of compiler flags that should be used to execute examples. Return a tuple `(f, t)`, where `t` is the number of examples tried, and `f` is the number of examples that failed. The examples are run in the namespace `test.globs`. """ # Keep track of the number of failures and tries. failures = tries = 0 # Save the option flags (since option directives can be used # to modify them). original_optionflags = self.optionflags SUCCESS, FAILURE, BOOM = range(3) # `outcome` state check = self._checker.check_output # Process each example. for examplenum, example in enumerate(test.examples): # If REPORT_ONLY_FIRST_FAILURE is set, then supress # reporting after the first failure. quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and failures > 0) # Merge in the example's options. self.optionflags = original_optionflags if example.options: for (optionflag, val) in example.options.items(): if val: self.optionflags |= optionflag else: self.optionflags &= ~optionflag # Record that we started this example. tries += 1 if not quiet: self.report_start(out, test, example) # Use a special filename for compile(), so we can retrieve # the source code during interactive debugging (see # __patched_linecache_getlines). filename = '' % (test.name, examplenum) # Run the example in the given context (globs), and record # any exception that gets raised. (But don't intercept # keyboard interrupts.) try: # Don't blink! This is where the user's code gets run. exec compile(example.source, filename, "single", compileflags, 1) in test.globs self.debugger.set_continue() # ==== Example Finished ==== exception = None except KeyboardInterrupt: raise except: exception = sys.exc_info() self.debugger.set_continue() # ==== Example Finished ==== got = self._fakeout.getvalue() # the actual output self._fakeout.truncate(0) outcome = FAILURE # guilty until proved innocent or insane # If the example executed without raising any exceptions, # verify its output. if exception is None: if check(example.want, got, self.optionflags): outcome = SUCCESS # The example raised an exception: check if it was expected. else: exc_info = sys.exc_info() exc_msg = traceback.format_exception_only(*exc_info[:2])[-1] if not quiet: got += _exception_traceback(exc_info) # If `example.exc_msg` is None, then we weren't expecting # an exception. if example.exc_msg is None: outcome = BOOM # We expected an exception: see whether it matches. elif check(example.exc_msg, exc_msg, self.optionflags): outcome = SUCCESS # Another chance if they didn't care about the detail. elif self.optionflags & IGNORE_EXCEPTION_DETAIL: m1 = re.match(r'[^:]*:', example.exc_msg) m2 = re.match(r'[^:]*:', exc_msg) if m1 and m2 and check(m1.group(0), m2.group(0), self.optionflags): outcome = SUCCESS # Report the outcome. if outcome is SUCCESS: if not quiet: self.report_success(out, test, example, got) elif outcome is FAILURE: if not quiet: self.report_failure(out, test, example, got) failures += 1 elif outcome is BOOM: if not quiet: self.report_unexpected_exception(out, test, example, exc_info) failures += 1 else: assert False, ("unknown outcome", outcome) # Restore the option flags (in case they were modified) self.optionflags = original_optionflags # Record and return the number of failures and tries. self.__record_outcome(test, failures, tries) return failures, tries def __record_outcome(self, test, f, t): """ Record the fact that the given DocTest (`test`) generated `f` failures out of `t` tried examples. """ f2, t2 = self._name2ft.get(test.name, (0,0)) self._name2ft[test.name] = (f+f2, t+t2) self.failures += f self.tries += t __LINECACHE_FILENAME_RE = re.compile(r'[\w\.]+)' r'\[(?P\d+)\]>$') def __patched_linecache_getlines(self, filename, module_globals=None): m = self.__LINECACHE_FILENAME_RE.match(filename) if m and m.group('name') == self.test.name: example = self.test.examples[int(m.group('examplenum'))] return example.source.splitlines(True) elif self.save_linecache_getlines.func_code.co_argcount>1: return self.save_linecache_getlines(filename, module_globals) else: return self.save_linecache_getlines(filename) def run(self, test, compileflags=None, out=None, clear_globs=True): """ Run the examples in `test`, and display the results using the writer function `out`. The examples are run in the namespace `test.globs`. If `clear_globs` is true (the default), then this namespace will be cleared after the test runs, to help with garbage collection. If you would like to examine the namespace after the test completes, then use `clear_globs=False`. `compileflags` gives the set of flags that should be used by the Python compiler when running the examples. If not specified, then it will default to the set of future-import flags that apply to `globs`. The output of each example is checked using `DocTestRunner.check_output`, and the results are formatted by the `DocTestRunner.report_*` methods. """ self.test = test if compileflags is None: compileflags = _extract_future_flags(test.globs) save_stdout = sys.stdout if out is None: out = save_stdout.write sys.stdout = self._fakeout # Patch pdb.set_trace to restore sys.stdout during interactive # debugging (so it's not still redirected to self._fakeout). # Note that the interactive output will go to *our* # save_stdout, even if that's not the real sys.stdout; this # allows us to write test cases for the set_trace behavior. save_set_trace = pdb.set_trace self.debugger = _OutputRedirectingPdb(save_stdout) self.debugger.reset() pdb.set_trace = self.debugger.set_trace # Patch linecache.getlines, so we can see the example's source # when we're inside the debugger. self.save_linecache_getlines = linecache.getlines linecache.getlines = self.__patched_linecache_getlines try: return self.__run(test, compileflags, out) finally: sys.stdout = save_stdout pdb.set_trace = save_set_trace linecache.getlines = self.save_linecache_getlines if clear_globs: test.globs.clear() #///////////////////////////////////////////////////////////////// # Summarization #///////////////////////////////////////////////////////////////// def summarize(self, verbose=None): """ Print a summary of all the test cases that have been run by this DocTestRunner, and return a tuple `(f, t)`, where `f` is the total number of failed examples, and `t` is the total number of tried examples. The optional `verbose` argument controls how detailed the summary is. If the verbosity is not specified, then the DocTestRunner's verbosity is used. """ if verbose is None: verbose = self._verbose notests = [] passed = [] failed = [] totalt = totalf = 0 for x in self._name2ft.items(): name, (f, t) = x assert f <= t totalt += t totalf += f if t == 0: notests.append(name) elif f == 0: passed.append( (name, t) ) else: failed.append(x) if verbose: if notests: print len(notests), "items had no tests:" notests.sort() for thing in notests: print " ", thing if passed: print len(passed), "items passed all tests:" passed.sort() for thing, count in passed: print " %3d tests in %s" % (count, thing) if failed: print self.DIVIDER print len(failed), "items had failures:" failed.sort() for thing, (f, t) in failed: print " %3d of %3d in %s" % (f, t, thing) if verbose: print totalt, "tests in", len(self._name2ft), "items." print totalt - totalf, "passed and", totalf, "failed." if totalf: print "***Test Failed***", totalf, "failures." elif verbose: print "Test passed." return totalf, totalt #///////////////////////////////////////////////////////////////// # Backward compatibility cruft to maintain doctest.master. #///////////////////////////////////////////////////////////////// def merge(self, other): d = self._name2ft for name, (f, t) in other._name2ft.items(): if name in d: print "*** DocTestRunner.merge: '" + name + "' in both" \ " testers; summing outcomes." f2, t2 = d[name] f = f + f2 t = t + t2 d[name] = f, t class OutputChecker: """ A class used to check the whether the actual output from a doctest example matches the expected output. `OutputChecker` defines two methods: `check_output`, which compares a given pair of outputs, and returns true if they match; and `output_difference`, which returns a string describing the differences between two outputs. """ def check_output(self, want, got, optionflags): """ Return True iff the actual output from an example (`got`) matches the expected output (`want`). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, several non-exact match types are also possible. See the documentation for `TestRunner` for more information about option flags. """ # Handle the common case first, for efficiency: # if they're string-identical, always return true. if got == want: return True # The values True and False replaced 1 and 0 as the return # value for boolean comparisons in Python 2.3. if not (optionflags & DONT_ACCEPT_TRUE_FOR_1): if (got,want) == ("True\n", "1\n"): return True if (got,want) == ("False\n", "0\n"): return True # can be used as a special sequence to signify a # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used. if not (optionflags & DONT_ACCEPT_BLANKLINE): # Replace in want with a blank line. want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER), '', want) # If a line in got contains only spaces, then remove the # spaces. got = re.sub('(?m)^\s*?$', '', got) if got == want: return True # This flag causes doctest to ignore any differences in the # contents of whitespace strings. Note that this can be used # in conjunction with the ELLIPSIS flag. if optionflags & NORMALIZE_WHITESPACE: got = ' '.join(got.split()) want = ' '.join(want.split()) if got == want: return True # The ELLIPSIS flag says to let the sequence "..." in `want` # match any substring in `got`. if optionflags & ELLIPSIS: if _ellipsis_match(want, got): return True # We didn't find any match; return false. return False # Should we do a fancy diff? def _do_a_fancy_diff(self, want, got, optionflags): # Not unless they asked for a fancy diff. if not optionflags & (REPORT_UDIFF | REPORT_CDIFF | REPORT_NDIFF): return False # If expected output uses ellipsis, a meaningful fancy diff is # too hard ... or maybe not. In two real-life failures Tim saw, # a diff was a major help anyway, so this is commented out. # [todo] _ellipsis_match() knows which pieces do and don't match, # and could be the basis for a kick-ass diff in this case. ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want: ## return False # ndiff does intraline difference marking, so can be useful even # for 1-line differences. if optionflags & REPORT_NDIFF: return True # The other diff types need at least a few lines to be helpful. return want.count('\n') > 2 and got.count('\n') > 2 def output_difference(self, example, got, optionflags): """ Return a string describing the differences between the expected output for a given example (`example`) and the actual output (`got`). `optionflags` is the set of option flags used to compare `want` and `got`. """ want = example.want # If s are being used, then replace blank lines # with in the actual output string. if not (optionflags & DONT_ACCEPT_BLANKLINE): got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got) # Check if we should use diff. if self._do_a_fancy_diff(want, got, optionflags): # Split want & got into lines. want_lines = want.splitlines(True) # True == keep line ends got_lines = got.splitlines(True) # Use difflib to find their differences. if optionflags & REPORT_UDIFF: diff = difflib.unified_diff(want_lines, got_lines, n=2) diff = list(diff)[2:] # strip the diff header kind = 'unified diff with -expected +actual' elif optionflags & REPORT_CDIFF: diff = difflib.context_diff(want_lines, got_lines, n=2) diff = list(diff)[2:] # strip the diff header kind = 'context diff with expected followed by actual' elif optionflags & REPORT_NDIFF: engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK) diff = list(engine.compare(want_lines, got_lines)) kind = 'ndiff with -expected +actual' else: assert 0, 'Bad diff option' # Remove trailing whitespace on diff output. diff = [line.rstrip() + '\n' for line in diff] return 'Differences (%s):\n' % kind + _indent(''.join(diff)) # If we're not using diff, then simply list the expected # output followed by the actual output. if want and got: return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got)) elif want: return 'Expected:\n%sGot nothing\n' % _indent(want) elif got: return 'Expected nothing\nGot:\n%s' % _indent(got) else: return 'Expected nothing\nGot nothing\n' class DocTestFailure(Exception): """A DocTest example has failed in debugging mode. The exception instance has variables: - test: the DocTest object being run - excample: the Example object that failed - got: the actual output """ def __init__(self, test, example, got): self.test = test self.example = example self.got = got def __str__(self): return str(self.test) class UnexpectedException(Exception): """A DocTest example has encountered an unexpected exception The exception instance has variables: - test: the DocTest object being run - excample: the Example object that failed - exc_info: the exception info """ def __init__(self, test, example, exc_info): self.test = test self.example = example self.exc_info = exc_info def __str__(self): return str(self.test) class DebugRunner(DocTestRunner): r"""Run doc tests but raise an exception as soon as there is a failure. If an unexpected exception occurs, an UnexpectedException is raised. It contains the test, the example, and the original exception: >>> runner = DebugRunner(verbose=False) >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42', ... {}, 'foo', 'foo.py', 0) >>> try: ... runner.run(test) ... except UnexpectedException, failure: ... pass >>> failure.test is test True >>> failure.example.want '42\n' >>> exc_info = failure.exc_info >>> raise exc_info[0], exc_info[1], exc_info[2] Traceback (most recent call last): ... KeyError We wrap the original exception to give the calling application access to the test and example information. If the output doesn't match, then a DocTestFailure is raised: >>> test = DocTestParser().get_doctest(''' ... >>> x = 1 ... >>> x ... 2 ... ''', {}, 'foo', 'foo.py', 0) >>> try: ... runner.run(test) ... except DocTestFailure, failure: ... pass DocTestFailure objects provide access to the test: >>> failure.test is test True As well as to the example: >>> failure.example.want '2\n' and the actual output: >>> failure.got '1\n' If a failure or error occurs, the globals are left intact: >>> del test.globs['__builtins__'] >>> test.globs {'x': 1} >>> test = DocTestParser().get_doctest(''' ... >>> x = 2 ... >>> raise KeyError ... ''', {}, 'foo', 'foo.py', 0) >>> runner.run(test) Traceback (most recent call last): ... UnexpectedException: >>> del test.globs['__builtins__'] >>> test.globs {'x': 2} But the globals are cleared if there is no error: >>> test = DocTestParser().get_doctest(''' ... >>> x = 2 ... ''', {}, 'foo', 'foo.py', 0) >>> runner.run(test) (0, 1) >>> test.globs {} """ def run(self, test, compileflags=None, out=None, clear_globs=True): r = DocTestRunner.run(self, test, compileflags, out, False) if clear_globs: test.globs.clear() return r def report_unexpected_exception(self, out, test, example, exc_info): raise UnexpectedException(test, example, exc_info) def report_failure(self, out, test, example, got): raise DocTestFailure(test, example, got) ###################################################################### ## 6. Test Functions ###################################################################### # These should be backwards compatible. # For backward compatibility, a global instance of a DocTestRunner # class, updated by testmod. master = None def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, exclude_empty=False): """m=None, name=None, globs=None, verbose=None, isprivate=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, exclude_empty=False Test examples in docstrings in functions and classes reachable from module m (or the current module if m is not supplied), starting with m.__doc__. Unless isprivate is specified, private names are not skipped. Also test examples reachable from dict m.__test__ if it exists and is not None. m.__test__ maps names to functions, classes and strings; function and class docstrings are tested even if the name is private; strings are tested directly, as if they were docstrings. Return (#failures, #tests). See doctest.__doc__ for an overview. Optional keyword arg "name" gives the name of the module; by default use m.__name__. Optional keyword arg "globs" gives a dict to be used as the globals when executing examples; by default, use m.__dict__. A copy of this dict is actually used for each docstring, so that each docstring's examples start with a clean slate. Optional keyword arg "extraglobs" gives a dictionary that should be merged into the globals that are used to execute examples. By default, no extra globals are used. This is new in 2.4. Optional keyword arg "verbose" prints lots of stuff if true, prints only failures if false; by default, it's true iff "-v" is in sys.argv. Optional keyword arg "report" prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else very brief (in fact, empty if all tests passed). Optional keyword arg "optionflags" or's together module constants, and defaults to 0. This is new in 2.3. Possible values (see the docs for details): DONT_ACCEPT_TRUE_FOR_1 DONT_ACCEPT_BLANKLINE NORMALIZE_WHITESPACE ELLIPSIS IGNORE_EXCEPTION_DETAIL REPORT_UDIFF REPORT_CDIFF REPORT_NDIFF REPORT_ONLY_FIRST_FAILURE Optional keyword arg "raise_on_error" raises an exception on the first unexpected exception or failure. This allows failures to be post-mortem debugged. Deprecated in Python 2.4: Optional keyword arg "isprivate" specifies a function used to determine whether a name is private. The default function is treat all functions as public. Optionally, "isprivate" can be set to doctest.is_private to skip over functions marked as private using the underscore naming convention; see its docs for details. Advanced tomfoolery: testmod runs methods of a local instance of class doctest.Tester, then merges the results into (or creates) global Tester instance doctest.master. Methods of doctest.master can be called directly too, if you want to do something unusual. Passing report=0 to testmod is especially useful then, to delay displaying a summary. Invoke doctest.master.summarize(verbose) when you're done fiddling. """ global master if isprivate is not None: warnings.warn("the isprivate argument is deprecated; " "examine DocTestFinder.find() lists instead", DeprecationWarning) # If no module was given, then use __main__. if m is None: # DWA - m will still be None if this wasn't invoked from the command # line, in which case the following TypeError is about as good an error # as we should expect m = sys.modules.get('__main__') # Check that we were actually given a module. if not inspect.ismodule(m): raise TypeError("testmod: module required; %r" % (m,)) # If no name was given, then use the module's name. if name is None: name = m.__name__ # Find, parse, and run all tests in the given module. finder = DocTestFinder(_namefilter=isprivate, exclude_empty=exclude_empty) if raise_on_error: runner = DebugRunner(verbose=verbose, optionflags=optionflags) else: runner = DocTestRunner(verbose=verbose, optionflags=optionflags) for test in finder.find(m, name, globs=globs, extraglobs=extraglobs): runner.run(test) if report: runner.summarize() if master is None: master = runner else: master.merge(runner) return runner.failures, runner.tries def testfile(filename, module_relative=True, name=None, package=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, parser=DocTestParser()): """ Test examples in the given file. Return (#failures, #tests). Optional keyword arg "module_relative" specifies how filenames should be interpreted: - If "module_relative" is True (the default), then "filename" specifies a module-relative path. By default, this path is relative to the calling module's directory; but if the "package" argument is specified, then it is relative to that package. To ensure os-independence, "filename" should use "/" characters to separate path segments, and should not be an absolute path (i.e., it may not begin with "/"). - If "module_relative" is False, then "filename" specifies an os-specific path. The path may be absolute or relative (to the current working directory). Optional keyword arg "name" gives the name of the test; by default use the file's basename. Optional keyword argument "package" is a Python package or the name of a Python package whose directory should be used as the base directory for a module relative filename. If no package is specified, then the calling module's directory is used as the base directory for module relative filenames. It is an error to specify "package" if "module_relative" is False. Optional keyword arg "globs" gives a dict to be used as the globals when executing examples; by default, use {}. A copy of this dict is actually used for each docstring, so that each docstring's examples start with a clean slate. Optional keyword arg "extraglobs" gives a dictionary that should be merged into the globals that are used to execute examples. By default, no extra globals are used. Optional keyword arg "verbose" prints lots of stuff if true, prints only failures if false; by default, it's true iff "-v" is in sys.argv. Optional keyword arg "report" prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else very brief (in fact, empty if all tests passed). Optional keyword arg "optionflags" or's together module constants, and defaults to 0. Possible values (see the docs for details): DONT_ACCEPT_TRUE_FOR_1 DONT_ACCEPT_BLANKLINE NORMALIZE_WHITESPACE ELLIPSIS IGNORE_EXCEPTION_DETAIL REPORT_UDIFF REPORT_CDIFF REPORT_NDIFF REPORT_ONLY_FIRST_FAILURE Optional keyword arg "raise_on_error" raises an exception on the first unexpected exception or failure. This allows failures to be post-mortem debugged. Optional keyword arg "parser" specifies a DocTestParser (or subclass) that should be used to extract tests from the files. Advanced tomfoolery: testmod runs methods of a local instance of class doctest.Tester, then merges the results into (or creates) global Tester instance doctest.master. Methods of doctest.master can be called directly too, if you want to do something unusual. Passing report=0 to testmod is especially useful then, to delay displaying a summary. Invoke doctest.master.summarize(verbose) when you're done fiddling. """ global master if package and not module_relative: raise ValueError("Package may only be specified for module-" "relative paths.") # Relativize the path if module_relative: package = _normalize_module(package) filename = _module_relative_path(package, filename) # If no name was given, then use the file's name. if name is None: name = os.path.basename(filename) # Assemble the globals. if globs is None: globs = {} else: globs = globs.copy() if extraglobs is not None: globs.update(extraglobs) if raise_on_error: runner = DebugRunner(verbose=verbose, optionflags=optionflags) else: runner = DocTestRunner(verbose=verbose, optionflags=optionflags) # Read the file, convert it to a test, and run it. s = open(filename).read() test = parser.get_doctest(s, globs, name, filename, 0) runner.run(test) if report: runner.summarize() if master is None: master = runner else: master.merge(runner) return runner.failures, runner.tries def run_docstring_examples(f, globs, verbose=False, name="NoName", compileflags=None, optionflags=0): """ Test examples in the given object's docstring (`f`), using `globs` as globals. Optional argument `name` is used in failure messages. If the optional argument `verbose` is true, then generate output even if there are no failures. `compileflags` gives the set of flags that should be used by the Python compiler when running the examples. If not specified, then it will default to the set of future-import flags that apply to `globs`. Optional keyword arg `optionflags` specifies options for the testing and output. See the documentation for `testmod` for more information. """ # Find, parse, and run all tests in the given module. finder = DocTestFinder(verbose=verbose, recurse=False) runner = DocTestRunner(verbose=verbose, optionflags=optionflags) for test in finder.find(f, name, globs=globs): runner.run(test, compileflags=compileflags) ###################################################################### ## 7. Tester ###################################################################### # This is provided only for backwards compatibility. It's not # actually used in any way. class Tester: def __init__(self, mod=None, globs=None, verbose=None, isprivate=None, optionflags=0): warnings.warn("class Tester is deprecated; " "use class doctest.DocTestRunner instead", DeprecationWarning, stacklevel=2) if mod is None and globs is None: raise TypeError("Tester.__init__: must specify mod or globs") if mod is not None and not inspect.ismodule(mod): raise TypeError("Tester.__init__: mod must be a module; %r" % (mod,)) if globs is None: globs = mod.__dict__ self.globs = globs self.verbose = verbose self.isprivate = isprivate self.optionflags = optionflags self.testfinder = DocTestFinder(_namefilter=isprivate) self.testrunner = DocTestRunner(verbose=verbose, optionflags=optionflags) def runstring(self, s, name): test = DocTestParser().get_doctest(s, self.globs, name, None, None) if self.verbose: print "Running string", name (f,t) = self.testrunner.run(test) if self.verbose: print f, "of", t, "examples failed in string", name return (f,t) def rundoc(self, object, name=None, module=None): f = t = 0 tests = self.testfinder.find(object, name, module=module, globs=self.globs) for test in tests: (f2, t2) = self.testrunner.run(test) (f,t) = (f+f2, t+t2) return (f,t) def rundict(self, d, name, module=None): import new m = new.module(name) m.__dict__.update(d) if module is None: module = False return self.rundoc(m, name, module) def run__test__(self, d, name): import new m = new.module(name) m.__test__ = d return self.rundoc(m, name) def summarize(self, verbose=None): return self.testrunner.summarize(verbose) def merge(self, other): self.testrunner.merge(other.testrunner) ###################################################################### ## 8. Unittest Support ###################################################################### _unittest_reportflags = 0 def set_unittest_reportflags(flags): """Sets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: >>> old = _unittest_reportflags >>> set_unittest_reportflags(REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) == old True >>> import doctest >>> doctest._unittest_reportflags == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True Only reporting flags can be set: >>> set_unittest_reportflags(ELLIPSIS) Traceback (most recent call last): ... ValueError: ('Only reporting flags allowed', 8) >>> set_unittest_reportflags(old) == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True """ global _unittest_reportflags if (flags & REPORTING_FLAGS) != flags: raise ValueError("Only reporting flags allowed", flags) old = _unittest_reportflags _unittest_reportflags = flags return old class DocTestCase(unittest.TestCase): def __init__(self, test, optionflags=0, setUp=None, tearDown=None, checker=None): unittest.TestCase.__init__(self) self._dt_optionflags = optionflags self._dt_checker = checker self._dt_test = test self._dt_setUp = setUp self._dt_tearDown = tearDown def setUp(self): test = self._dt_test if self._dt_setUp is not None: self._dt_setUp(test) def tearDown(self): test = self._dt_test if self._dt_tearDown is not None: self._dt_tearDown(test) test.globs.clear() def runTest(self): test = self._dt_test old = sys.stdout new = StringIO() optionflags = self._dt_optionflags if not (optionflags & REPORTING_FLAGS): # The option flags don't include any reporting flags, # so add the default reporting flags optionflags |= _unittest_reportflags runner = DocTestRunner(optionflags=optionflags, checker=self._dt_checker, verbose=False) try: runner.DIVIDER = "-"*70 failures, tries = runner.run( test, out=new.write, clear_globs=False) finally: sys.stdout = old if failures: raise self.failureException(self.format_failure(new.getvalue())) def format_failure(self, err): test = self._dt_test if test.lineno is None: lineno = 'unknown line number' else: lineno = '%s' % test.lineno lname = '.'.join(test.name.split('.')[-1:]) return ('Failed doctest test for %s\n' ' File "%s", line %s, in %s\n\n%s' % (test.name, test.filename, lineno, lname, err) ) def debug(self): r"""Run the test case without results and without catching exceptions The unit test framework includes a debug method on test cases and test suites to support post-mortem debugging. The test code is run in such a way that errors are not caught. This way a caller can catch the errors and initiate post-mortem debugging. The DocTestCase provides a debug method that raises UnexpectedException errors if there is an unexepcted exception: >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42', ... {}, 'foo', 'foo.py', 0) >>> case = DocTestCase(test) >>> try: ... case.debug() ... except UnexpectedException, failure: ... pass The UnexpectedException contains the test, the example, and the original exception: >>> failure.test is test True >>> failure.example.want '42\n' >>> exc_info = failure.exc_info >>> raise exc_info[0], exc_info[1], exc_info[2] Traceback (most recent call last): ... KeyError If the output doesn't match, then a DocTestFailure is raised: >>> test = DocTestParser().get_doctest(''' ... >>> x = 1 ... >>> x ... 2 ... ''', {}, 'foo', 'foo.py', 0) >>> case = DocTestCase(test) >>> try: ... case.debug() ... except DocTestFailure, failure: ... pass DocTestFailure objects provide access to the test: >>> failure.test is test True As well as to the example: >>> failure.example.want '2\n' and the actual output: >>> failure.got '1\n' """ self.setUp() runner = DebugRunner(optionflags=self._dt_optionflags, checker=self._dt_checker, verbose=False) runner.run(self._dt_test) self.tearDown() def id(self): return self._dt_test.name def __repr__(self): name = self._dt_test.name.split('.') return "%s (%s)" % (name[-1], '.'.join(name[:-1])) __str__ = __repr__ def shortDescription(self): return "Doctest: " + self._dt_test.name def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None, **options): """ Convert doctest tests for a module to a unittest test suite. This converts each documentation string in a module that contains doctest tests to a unittest test case. If any of the tests in a doc string fail, then the test case fails. An exception is raised showing the name of the file containing the test and a (sometimes approximate) line number. The `module` argument provides the module to be tested. The argument can be either a module or a module name. If no argument is given, the calling module is used. A number of options may be provided as keyword arguments: setUp A set-up function. This is called before running the tests in each file. The setUp function will be passed a DocTest object. The setUp function can access the test globals as the globs attribute of the test passed. tearDown A tear-down function. This is called after running the tests in each file. The tearDown function will be passed a DocTest object. The tearDown function can access the test globals as the globs attribute of the test passed. globs A dictionary containing initial global variables for the tests. optionflags A set of doctest option flags expressed as an integer. """ if test_finder is None: test_finder = DocTestFinder() module = _normalize_module(module) tests = test_finder.find(module, globs=globs, extraglobs=extraglobs) if globs is None: globs = module.__dict__ if not tests: # Why do we want to do this? Because it reveals a bug that might # otherwise be hidden. raise ValueError(module, "has no tests") tests.sort() suite = unittest.TestSuite() for test in tests: if len(test.examples) == 0: continue if not test.filename: filename = module.__file__ if filename[-4:] in (".pyc", ".pyo"): filename = filename[:-1] test.filename = filename suite.addTest(DocTestCase(test, **options)) return suite class DocFileCase(DocTestCase): def id(self): return '_'.join(self._dt_test.name.split('.')) def __repr__(self): return self._dt_test.filename __str__ = __repr__ def format_failure(self, err): return ('Failed doctest test for %s\n File "%s", line 0\n\n%s' % (self._dt_test.name, self._dt_test.filename, err) ) def DocFileTest(path, module_relative=True, package=None, globs=None, parser=DocTestParser(), **options): if globs is None: globs = {} if package and not module_relative: raise ValueError("Package may only be specified for module-" "relative paths.") # Relativize the path. if module_relative: package = _normalize_module(package) path = _module_relative_path(package, path) # Find the file and read it. name = os.path.basename(path) doc = open(path).read() # Convert it to a test, and wrap it in a DocFileCase. test = parser.get_doctest(doc, globs, name, path, 0) return DocFileCase(test, **options) def DocFileSuite(*paths, **kw): """A unittest suite for one or more doctest files. The path to each doctest file is given as a string; the interpretation of that string depends on the keyword argument "module_relative". A number of options may be provided as keyword arguments: module_relative If "module_relative" is True, then the given file paths are interpreted as os-independent module-relative paths. By default, these paths are relative to the calling module's directory; but if the "package" argument is specified, then they are relative to that package. To ensure os-independence, "filename" should use "/" characters to separate path segments, and may not be an absolute path (i.e., it may not begin with "/"). If "module_relative" is False, then the given file paths are interpreted as os-specific paths. These paths may be absolute or relative (to the current working directory). package A Python package or the name of a Python package whose directory should be used as the base directory for module relative paths. If "package" is not specified, then the calling module's directory is used as the base directory for module relative filenames. It is an error to specify "package" if "module_relative" is False. setUp A set-up function. This is called before running the tests in each file. The setUp function will be passed a DocTest object. The setUp function can access the test globals as the globs attribute of the test passed. tearDown A tear-down function. This is called after running the tests in each file. The tearDown function will be passed a DocTest object. The tearDown function can access the test globals as the globs attribute of the test passed. globs A dictionary containing initial global variables for the tests. optionflags A set of doctest option flags expressed as an integer. parser A DocTestParser (or subclass) that should be used to extract tests from the files. """ suite = unittest.TestSuite() # We do this here so that _normalize_module is called at the right # level. If it were called in DocFileTest, then this function # would be the caller and we might guess the package incorrectly. if kw.get('module_relative', True): kw['package'] = _normalize_module(kw.get('package')) for path in paths: suite.addTest(DocFileTest(path, **kw)) return suite ###################################################################### ## 9. Debugging Support ###################################################################### def script_from_examples(s): r"""Extract script from text with examples. Converts text with examples to a Python script. Example input is converted to regular code. Example output and all other words are converted to comments: >>> text = ''' ... Here are examples of simple math. ... ... Python has super accurate integer addition ... ... >>> 2 + 2 ... 5 ... ... And very friendly error messages: ... ... >>> 1/0 ... To Infinity ... And ... Beyond ... ... You can use logic if you want: ... ... >>> if 0: ... ... blah ... ... blah ... ... ... ... Ho hum ... ''' >>> print script_from_examples(text) # Here are examples of simple math. # # Python has super accurate integer addition # 2 + 2 # Expected: ## 5 # # And very friendly error messages: # 1/0 # Expected: ## To Infinity ## And ## Beyond # # You can use logic if you want: # if 0: blah blah # # Ho hum """ output = [] for piece in DocTestParser().parse(s): if isinstance(piece, Example): # Add the example's source code (strip trailing NL) output.append(piece.source[:-1]) # Add the expected output: want = piece.want if want: output.append('# Expected:') output += ['## '+l for l in want.split('\n')[:-1]] else: # Add non-example text. output += [_comment_line(l) for l in piece.split('\n')[:-1]] # Trim junk on both ends. while output and output[-1] == '#': output.pop() while output and output[0] == '#': output.pop(0) # Combine the output, and return it. return '\n'.join(output) def testsource(module, name): """Extract the test sources from a doctest docstring as a script. Provide the module (or dotted name of the module) containing the test to be debugged and the name (within the module) of the object with the doc string with tests to be debugged. """ module = _normalize_module(module) tests = DocTestFinder().find(module) test = [t for t in tests if t.name == name] if not test: raise ValueError(name, "not found in tests") test = test[0] testsrc = script_from_examples(test.docstring) return testsrc def debug_src(src, pm=False, globs=None): """Debug a single doctest docstring, in argument `src`'""" testsrc = script_from_examples(src) debug_script(testsrc, pm, globs) def debug_script(src, pm=False, globs=None): "Debug a test script. `src` is the script, as a string." import pdb # Note that tempfile.NameTemporaryFile() cannot be used. As the # docs say, a file so created cannot be opened by name a second time # on modern Windows boxes, and execfile() needs to open it. srcfilename = tempfile.mktemp(".py", "doctestdebug") f = open(srcfilename, 'w') f.write(src) f.close() try: if globs: globs = globs.copy() else: globs = {} if pm: try: execfile(srcfilename, globs, globs) except: print sys.exc_info()[1] pdb.post_mortem(sys.exc_info()[2]) else: # Note that %r is vital here. '%s' instead can, e.g., cause # backslashes to get treated as metacharacters on Windows. pdb.run("execfile(%r)" % srcfilename, globs, globs) finally: os.remove(srcfilename) def debug(module, name, pm=False): """Debug a single doctest docstring. Provide the module (or dotted name of the module) containing the test to be debugged and the name (within the module) of the object with the docstring with tests to be debugged. """ module = _normalize_module(module) testsrc = testsource(module, name) debug_script(testsrc, pm, module.__dict__) ###################################################################### ## 10. Example Usage ###################################################################### class _TestClass: """ A pointless class, for sanity-checking of docstring testing. Methods: square() get() >>> _TestClass(13).get() + _TestClass(-12).get() 1 >>> hex(_TestClass(13).square().get()) '0xa9' """ def __init__(self, val): """val -> _TestClass object with associated value val. >>> t = _TestClass(123) >>> print t.get() 123 """ self.val = val def square(self): """square() -> square TestClass's associated value >>> _TestClass(13).square().get() 169 """ self.val = self.val ** 2 return self def get(self): """get() -> return TestClass's associated value. >>> x = _TestClass(-42) >>> print x.get() -42 """ return self.val __test__ = {"_TestClass": _TestClass, "string": r""" Example of a string object, searched as-is. >>> x = 1; y = 2 >>> x + y, x * y (3, 2) """, "bool-int equivalence": r""" In 2.2, boolean expressions displayed 0 or 1. By default, we still accept them. This can be disabled by passing DONT_ACCEPT_TRUE_FOR_1 to the new optionflags argument. >>> 4 == 4 1 >>> 4 == 4 True >>> 4 > 4 0 >>> 4 > 4 False """, "blank lines": r""" Blank lines can be marked with : >>> print 'foo\n\nbar\n' foo bar """, "ellipsis": r""" If the ellipsis flag is used, then '...' can be used to elide substrings in the desired output: >>> print range(1000) #doctest: +ELLIPSIS [0, 1, 2, ..., 999] """, "whitespace normalization": r""" If the whitespace normalization flag is used, then differences in whitespace are ignored. >>> print range(30) #doctest: +NORMALIZE_WHITESPACE [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29] """, } def _test(): r = unittest.TextTestRunner() r.run(DocTestSuite()) if __name__ == "__main__": _test() PK86MU { {protocols/tests/doctest.pyc; (Ec!@syeWnej oeefZnXyeWnej odZnXdZdddddddd d d d d ddddddddddddddddddd d!d"g!Zd#kZd#kZd#k Z d#k Z d#k Z d#k Z d#k Z d#kZd#kZd#kZd#kZd#kZd#kZd$klZeid%deed&hZd'ZedZedZedZedZedZeeBeBeBeBZed Z ed Z!ed Z"ed Z#e e!Be"Be#BZ$d(Z%d)Z&d*Z'd+Z(d,d-Z)d.d/Z*d0Z+d1efd2YZ,d3Z-d4Z.d5ei/fd6YZ0d7Z1dfd8YZ2dfd9YZ3dfd:YZ4dfd;YZ5dfd<YZ6dfd=YZ7de8fd>YZ9de8fd?YZ:de6fd@YZ;e<a=e<e<e<e<e<e>d&e<e?e?dA Z@e>e<e<e<e<e>d&e<e?e4dB ZAe?dCe<d&dDZBdfdEYZCd&aDdFZEdGeiFfdHYZGe<e<e<e<dIZHdJeGfdKYZIe>e<e<e4dLZJdMZKdNZLdOZMe?e<dPZNe?e<dQZOe?dRZPdSfdTYZQhdSeQ<dUdV<dWdX<dYdZ<d[d\<d]d^}|t|<|SdS(Ni(slensOPTIONFLAGS_BY_NAMEsflagsname(snamesflag((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysregister_optionflags s s...cCsOtidtdd|d djo$|d djo|djn SdS( sprefix, base -> true iff name prefix + "." + base is "private". Prefix may be an empty string, and base does not contain a period. Prefix is ignored (although functions you write conforming to this protocol may make use of it). Return true iff base begins with an (at least one) underscore, but does not both begin and end with (at least) two underscores. >>> is_private("a.b", "my_func") False >>> is_private("____", "_my_func") True >>> is_private("someclass", "__init__") False >>> is_private("sometypo", "__init_") True >>> is_private("x.y.z", "_") True >>> is_private("_x.y.z", "__") False >>> is_private("", "") # senseless but consistent False sVis_private is deprecated; it wasn't useful; examine DocTestFinder.find() lists insteads stackleveliis_s__iN(swarningsswarnsDeprecationWarningsbase(sprefixsbase((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys is_privates  cCs[d}xJtiD]?}|i|t}|tt|jo||i O}qqW|SdS(s Return the compiler-flags associated with the future features that have been imported into the given namespace (globs). iN( sflagss __future__sall_feature_namessfnamesglobssgetsNonesfeaturesgetattrs compiler_flag(sglobssfeaturesflagssfname((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys_extract_future_flagss icCsti|o|Snot|ttfo t|ttdgSn9|t jot i t i |idSn tddS(s Return the module specified by `module`. In particular: - If `module` is a module, then return module. - If `module` is a string, then import and return the module with that name. - If `module` is None, then return the calling module. The calling module is assumed to be the module of the stack frame at the given depth in the call stack. s*s__name__s"Expected a module, string, or NoneN(sinspectsismodulesmodules isinstancesstrsunicodes __import__sglobalsslocalssNonessyssmoduless _getframesdepths f_globalss TypeError(smodulesdepth((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys_normalize_modules   icCstid|d|SdS(s{ Add the given number of space characters to the beginning every non-blank line in `s`, and return the result. s (?m)^(?!$)s N(sressubsindentss(sssindent((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys_indentscCs?t}|\}}}ti|||d||iSdS(sz Return a string containing a traceback message for the given exc_info tuple (as returned by sys.exc_info()). sfileN( sStringIOsexcoutsexc_infosexc_typesexc_valsexc_tbs tracebacksprint_exceptionsgetvalue(sexc_infosexc_valsexc_typesexcoutsexc_tb((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys_exception_tracebacks  s _SpoofOutcBstZdZedZRS(NcCsWti|}|o|id o|d7}nt|do |`n|SdS(Ns s softspace(sStringIOsgetvaluesselfsresultsendswithshasattrs softspace(sselfsresult((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysgetvalues  cCs.ti||t|do |`ndS(Ns softspace(sStringIOstruncatesselfssizeshasattrs softspace(sselfssize((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pystruncates(s__name__s __module__sgetvaluesNonestruncate(((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys _SpoofOuts cCsQ|itdjo||jSn|it}t|djptdt|f\}}|d}|o/|i |ot|}|d=qt Sn|d}|o3|i |o|t|8}|d=qt Sn||jot SnxH|D]@}|i|||}|djot Sn|t|7}qWtSdS(s_ Essentially the only subtle case: >>> _ellipsis_match('aa...aa', 'aaa') False iiiN(swantsfindsELLIPSIS_MARKERsgotssplitswsslensAssertionErrorsstartpossendpossws startswithsFalsesendswithsTrue(swantsgotswswssstartpossendpos((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys_ellipsis_match"s6       cCs'|i}|o d|SndSdS(s)Return a commented form of the given lines# s#N(slinesrstrip(sline((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys _comment_lineSs   s_OutputRedirectingPdbcBs tZdZdZdZRS(s A specialized version of the python debugger that redirects stdout to a given stream when interacting with the user. Stdout is *not* redirected when traced code is executed. cCs||_tii|dS(N(soutsselfs_OutputRedirectingPdb__outspdbsPdbs__init__(sselfsout((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys__init__as cGs=ti}|it_ztii||SWd|t_XdS(N( ssyssstdouts save_stdoutsselfs_OutputRedirectingPdb__outspdbsPdbstrace_dispatchsargs(sselfsargss save_stdout((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pystrace_dispatches   (s__name__s __module__s__doc__s__init__strace_dispatch(((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys_OutputRedirectingPdb[s  cCsti| otd|n|ido tdnt|dotii |i d}n}|i djoXt tidjotiddjo!tii tidd}qti}ntd|d tii||i dSdS( NsExpected a module: %rs/s1Module-relative files may not have absolute pathss__file__is__main__ss+Can't resolve paths relative to the module s (it has no __file__)(sinspectsismodulesmodules TypeErrorspaths startswiths ValueErrorshasattrsosssplits__file__sbasedirs__name__slenssyssargvscurdirsjoin(smodulespathsbasedir((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys_module_relative_pathps *! cBs#tZdZeddedZRS(sn A single doctest example, consisting of source code and expected output. `Example` defines the following attributes: - source: A single Python statement, always ending with a newline. The constructor adds a newline if needed. - want: The expected output from running the source code (either from stdout, or a traceback in case of exception). `want` ends with a newline unless it's empty, in which case it's an empty string. The constructor adds a newline if needed. - exc_msg: The exception message generated by the example, if the example is expected to generate an exception; or `None` if it is not expected to generate an exception. This exception message is compared against the return value of `traceback.format_exception_only()`. `exc_msg` ends with a newline unless it's `None`. The constructor adds a newline if needed. - lineno: The line number within the DocTest string containing this Example where the Example begins. This line number is zero-based, with respect to the beginning of the DocTest. - indent: The example's indentation in the DocTest string. I.e., the number of space characters that preceed the example's first prompt. - options: A dictionary mapping from option flags to True or False, which is used to override default options for this example. Any option flags not contained in this dictionary are left at their default value (as specified by the DocTestRunner's optionflags). By default, no options are set. icCs|id o|d7}n|o|id o|d7}n|tj o|id o|d7}n||_||_||_||_|tjo h}n||_||_dS(Ns ( ssourcesendswithswantsexc_msgsNonesselfslinenosindentsoptions(sselfssourceswantsexc_msgslinenosindentsoptions((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys__init__s      (s__name__s __module__s__doc__sNones__init__(((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysExamples "cBs)tZdZdZdZdZRS(se A collection of doctest examples that should be run in a single namespace. Each `DocTest` defines the following attributes: - examples: the list of examples. - globs: The namespace (aka globals) that the examples should be run in. - name: A name identifying the DocTest (typically, the name of the object whose docstring this DocTest was extracted from). - filename: The name of the file that this DocTest was extracted from, or `None` if the filename is unknown. - lineno: The line number within filename where this DocTest begins, or `None` if the line number is unavailable. This line number is zero-based, with respect to the beginning of the file. - docstring: The string that the examples were extracted from, or `None` if the string is unavailable. cCs[t|t p td||_||_|i|_||_||_ ||_ dS(s Create a new DocTest containing the given examples. The DocTest's globals are initialized with a copy of `globs`. s8DocTest no longer accepts str; use DocTestParser insteadN( s isinstancesexampless basestringsAssertionErrorsselfs docstringsglobsscopysnamesfilenameslineno(sselfsexamplessglobssnamesfilenameslinenos docstring((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys__init__s    cCstt|idjo d}n4t|idjo d}ndt|i}d|i|i|i|fSdS(Nis no examplesis 1 examples %d exampless(slensselfsexamplessnamesfilenameslineno(sselfsexamples((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys__repr__s   cCs`t|t odSnt|i|i|it|f|i|i|it|fSdS(Ni( s isinstancesothersDocTestscmpsselfsnamesfilenameslinenosid(sselfsother((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys__cmp__s!(s__name__s __module__s__doc__s__init__s__repr__s__cmp__(((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysDocTests   cBstZdZeideieiBZeideieiBeiBZ eidi Z ddZ dZ ddZdZeid eiZd Zeid eiZd Zd ZdZRS(sD A class used to parse strings containing doctest examples. s # Source consists of a PS1 line followed by zero or more PS2 lines. (?P (?:^(?P [ ]*) >>> .*) # PS1 line (?:\n [ ]* \.\.\. .*)*) # PS2 lines \n? # Want consists of any non-blank lines that do not start with PS1. (?P (?:(?![ ]*$) # Not a blank line (?![ ]*>>>) # Not a line starting with PS1 .*$\n? # But any other line )*) s # Grab the traceback header. Different versions of Python have # said different things on the first traceback line. ^(?P Traceback\ \( (?: most\ recent\ call\ last | innermost\ last ) \) : ) \s* $ # toss trailing whitespace on the header. (?P .*?) # don't blink: absorb stuff until... ^ (?P \w+ .*) # a line *starts* with alphanum. s ^[ ]*(#.*)?$sc Cs|i}|i|}|djoAdigi}|idD]}|||qE~}ng} ddf\} } x|i i|D]}| i|| |i!| |id| |i7} |i||| \}} } }|i| oB| it|| |d| d|t|idd| n| |id|i|i7} |i} qW| i|| | SdS(s= Divide the given string into examples and intervening text, and return them as a list of alternating Examples and strings. Line numbers for the Examples are 0-based. The optional argument `name` is a name identifying this string, and is only used for error messages. is slinenosindentsoptionsN(sstrings expandtabssselfs _min_indents min_indentsjoinsappends_[1]ssplitslsoutputscharnoslinenos _EXAMPLE_REsfinditersmsstartscounts_parse_examplesnamessourcesoptionsswantsexc_msgs_IS_BLANK_OR_COMMENTsExampleslensgroupsend(sselfsstringsnames min_indentsexc_msgsmsls_[1]ssourceslinenoswantsoutputscharnosoptions((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysparse5s*  A!%cCs)t|i|||||||SdS(s" Extract all doctest examples from the given string, and collect them into a `DocTest` object. `globs`, `name`, `filename`, and `lineno` are attributes for the new `DocTest` object. See the documentation for `DocTest` for more information. N(sDocTestsselfs get_examplessstringsnamesglobssfilenameslineno(sselfsstringsglobssnamesfilenameslineno((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys get_doctest\scCsIgi}|i||D]$}t|to||qq~SdS(s Extract all doctest examples from the given string, and return them as a list of `Example` objects. Line numbers are 0-based, because it's most common in doctests that nothing interesting appears on the same line as opening triple-quote, and so the first interesting line is called "line 1" then. The optional argument `name` is a name identifying this string, and is only used for error messages. N( sappends_[1]sselfsparsesstringsnamesxs isinstancesExample(sselfsstringsnames_[1]sx((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys get_exampleshs cCst|id}|idid} |i| ||||i | dd|d||di gi }| D]} || |dqy~} |id} | id}t|djotid |d o |d =n|i |d|||t| di gi }|D]}|||q(~} |ii| }|o|id }nt}|i| ||} | | | |fSd S( s Given a regular expression match from `_EXAMPLE_RE` (`m`), return a pair `(source, want)`, where `source` is the matched example's source code (with prompts and indentation stripped); and `want` is the example's expected output (with indentation stripped). `name` is the string's name, and `lineno` is the line number where the example starts; both are used for error messages. sindentssources is s.iswants *$ismsgN(slensmsgroupsindentssplits source_linessselfs_check_prompt_blanksnameslinenos _check_prefixsjoinsappends_[1]sslssourceswants want_linessresmatchswls _EXCEPTION_REsexc_msgsNones _find_optionssoptions(sselfsmsnameslinenosindents want_linessexc_msgswls_[1]ssourceswantssls source_linessoptions((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys_parse_examplevs& "8* 4s#\s*doctest:\s*([^\n\'"]*)$c Csh}x|ii|D]}|ididdi}xs|D]k}|ddjp|dt jo!t d|d||fnt |d}|ddj||>> tests = DocTestFinder().find(_TestClass) >>> runner = DocTestRunner(verbose=False) >>> for test in tests: ... print runner.run(test) (0, 2) (0, 1) (0, 2) (0, 2) The `summarize` method prints a summary of all the test cases that have been run by the runner, and returns an aggregated `(f, t)` tuple: >>> runner.summarize(verbose=1) 4 items passed all tests: 2 tests in _TestClass 2 tests in _TestClass.__init__ 2 tests in _TestClass.get 1 tests in _TestClass.square 7 tests in 4 items. 7 passed and 0 failed. Test passed. (0, 7) The aggregated number of tried examples and failed examples is also available via the `tries` and `failures` attributes: >>> runner.tries 7 >>> runner.failures 0 The comparison between expected outputs and actual outputs is done by an `OutputChecker`. This comparison may be customized with a number of option flags; see the documentation for `testmod` for more information. If the option flags are insufficient, then the comparison may also be customized by passing a subclass of `OutputChecker` to the constructor. The test runner's display output can be controlled in two ways. First, an output function (`out) can be passed to `TestRunner.run`; this function will be called with strings that should be displayed. It defaults to `sys.stdout.write`. If capturing the output is not sufficient, then the display output can be also customized by subclassing DocTestRunner, and overriding the methods `report_start`, `report_success`, `report_unexpected_exception`, and `report_failure`. s*iFicCsy|pt|_|tjodtij}n||_||_ ||_ d|_ d|_ h|_ t|_dS(sc Create a new test runner. Optional keyword arg `checker` is the `OutputChecker` that should be used to compare the expected outputs and actual outputs of doctest examples. Optional keyword arg 'verbose' prints lots of stuff if true, only failures if false; by default, it's true iff '-v' is in sys.argv. Optional argument `optionflags` can be used to control how the test runner compares expected output to actual output, and how it displays failures. See the documentation for `testmod` for more information. s-viN(scheckers OutputCheckersselfs_checkersverbosesNonessyssargvs_verboses optionflagssoriginal_optionflagsstriessfailuress_name2fts _SpoofOuts_fakeout(sselfscheckersverboses optionflags((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys__init__Us       cCsc|ioU|io,|dt|idt|iq_|dt|idndS(s Report that the test runner is about to process the given example. (Only displays a message if verbose=True) sTrying: s Expecting: sExpecting nothing N(sselfs_verbosesexampleswantsouts_indentssource(sselfsoutstestsexample((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys report_startys   ,cCs|io|dndS(st Report that the given example ran successfully. (Only displays a message if verbose=True) sok N(sselfs_verbosesout(sselfsoutstestsexamplesgot((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysreport_successs cCs3||i|||ii|||idS(s7 Report that the given example failed. N( soutsselfs_failure_headerstestsexamples_checkersoutput_differencesgots optionflags(sselfsoutstestsexamplesgot((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysreport_failurescCs.||i||dtt|dS(sO Report that the given example raised an unexpected exception. sException raised: N(soutsselfs_failure_headerstestsexamples_indents_exception_tracebacksexc_info(sselfsoutstestsexamplesexc_info((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysreport_unexpected_exceptionscCs|ig}|iob|itj o |itj o|i|id}nd}|id|i||i fn"|id|id|i f|id|i }|it |di |SdS(Nis?sFile "%s", line %s, in %ssLine %s, in %ssFailed example:s ( sselfsDIVIDERsoutstestsfilenameslinenosNonesexamplesappendsnamessources_indentsjoin(sselfstestsexamplessourceslinenosout((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys_failure_headers   $!  cBsd}} |i} ed\} }}|i i }xUe |iD]D\}}|ie@o |dj}| |_|ioNxK|iiD]6\}}|o|i|O_q|i|M_qWn| d7} | o|i|||nd|i|f}y7e|i|d|d|iU|ii e!}Wn5e#j o n!e$i%}|ii nX|i&i'} |i&i)d|}|e!jo'||i+| |io | }qne$i%}e,i-|d d} | o| e/|7} n|i.e!jo |}n||i.| |io | }nz|ie0@oke1i2d|i.}e1i2d| }|o,|o%||i5d|i5d|io | }qn|| jo&| o|i6|||| qqD||jo0| o|i7|||| n|d7}qD||jo0| o|i8||||n|d7}qDe9pt:d |fqDW| |_|i;||| || fSd S( s Run the examples in `test`. Write the outcome of each example with one of the `DocTestRunner.report_*` methods, using the writer function `out`. `compileflags` is the set of compiler flags that should be used to execute examples. Return a tuple `(f, t)`, where `t` is the number of examples tried, and `f` is the number of examples that failed. The examples are run in the namespace `test.globs`. iiisssingleiis[^:]*:sunknown outcomeN(<sfailuresstriessselfs optionflagssoriginal_optionflagssrangesSUCCESSsFAILUREsBOOMs_checkers check_outputschecks enumeratestestsexampless examplenumsexamplesREPORT_ONLY_FIRST_FAILUREsquietsoptionssitemss optionflagsvals report_startsoutsnamesfilenamescompilessources compileflagssglobssdebuggers set_continuesNones exceptionsKeyboardInterruptssyssexc_infos_fakeoutsgetvaluesgotstruncatesoutcomeswants tracebacksformat_exception_onlysexc_msgs_exception_tracebacksIGNORE_EXCEPTION_DETAILsresmatchsm1sm2sgroupsreport_successsreport_failuresreport_unexpected_exceptionsFalsesAssertionErrors_DocTestRunner__record_outcome(sselfstests compileflagssoutschecksvalsfilenamesm1sm2sgotsoriginal_optionflagssSUCCESSsexc_msgstriessexc_infos exceptions optionflagsquietsFAILUREsBOOMs examplenumsfailuressoutcomesexample((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys__runs                )      cCsd|ii|iddf\}}||||f|i|i<|i |7_ |i |7_ dS(s{ Record the fact that the given DocTest (`test`) generated `f` failures out of `t` tried examples. iN( sselfs_name2ftsgetstestsnamesf2st2sfstsfailuresstries(sselfstestsfstsf2st2((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys__record_outcome(s $s3[\w\.]+)\[(?P\d+)\]>$cCs|ii|}|o|id|iijo3|iit |id}|i i t Sn8|iiidjo|i||Sn|i|SdS(Nsnames examplenumi(sselfs%_DocTestRunner__LINECACHE_FILENAME_REsmatchsfilenamesmsgroupstestsnamesexamplessintsexamplessources splitlinessTruessave_linecache_getliness func_codes co_argcountsmodule_globals(sselfsfilenamesmodule_globalssmsexample((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys__patched_linecache_getlines5s#cCs||_|tjot|i}nti}|tjo |i }n|i t_t i }t||_|ii|ii t _ ti|_|it_z|i|||SWd|t_|t _ |it_|o|iinXdS(sJ Run the examples in `test`, and display the results using the writer function `out`. The examples are run in the namespace `test.globs`. If `clear_globs` is true (the default), then this namespace will be cleared after the test runs, to help with garbage collection. If you would like to examine the namespace after the test completes, then use `clear_globs=False`. `compileflags` gives the set of flags that should be used by the Python compiler when running the examples. If not specified, then it will default to the set of future-import flags that apply to `globs`. The output of each example is checked using `DocTestRunner.check_output`, and the results are formatted by the `DocTestRunner.report_*` methods. N(stestsselfs compileflagssNones_extract_future_flagssglobsssyssstdouts save_stdoutsoutswrites_fakeoutspdbs set_tracessave_set_traces_OutputRedirectingPdbsdebuggersresets linecachesgetlinesssave_linecache_getliness*_DocTestRunner__patched_linecache_getliness_DocTestRunner__runs clear_globssclear(sselfstests compileflagssouts clear_globss save_stdoutssave_set_trace((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysrun?s,             c Cs7|tjo |i}ng} g}g}d}} x|i i D]} | \}\}}||jpt||7}| |7} |djo| i|qF|djo|i||fqF|i| qFW|o| o7t| GdGH| ix| D]} dG| GHqWn|oCt|GdGH|ix'|D]\} }d|| fGHqEWqln|oT|iGHt|GdGH|ix0|D]$\} \}}d||| fGHqWn|o3|GdGt|i Gd GH|| Gd G| Gd GHn| od G| Gd GHn|o dGHn| |fSdS(s Print a summary of all the test cases that have been run by this DocTestRunner, and return a tuple `(f, t)`, where `f` is the total number of failed examples, and `t` is the total number of tried examples. The optional `verbose` argument controls how detailed the summary is. If the verbosity is not specified, then the DocTestRunner's verbosity is used. isitems had no tests:s sitems passed all tests:s %3d tests in %ssitems had failures:s %3d of %3d in %sstests insitems.s passed andsfailed.s***Test Failed***s failures.s Test passed.N(sverbosesNonesselfs_verbosesnotestsspassedsfailedstotaltstotalfs_name2ftsitemssxsnamesfstsAssertionErrorsappendslenssortsthingscountsDIVIDER( sselfsverbosescountsfstotaltsnamesfailedstspassedsxstotalfsthingsnotests((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys summarizexs\             cCs|i}xu|iiD]d\}\}}||jo5d|dGH||\}}||}||}n||f||>> runner = DebugRunner(verbose=False) >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42', ... {}, 'foo', 'foo.py', 0) >>> try: ... runner.run(test) ... except UnexpectedException, failure: ... pass >>> failure.test is test True >>> failure.example.want '42\n' >>> exc_info = failure.exc_info >>> raise exc_info[0], exc_info[1], exc_info[2] Traceback (most recent call last): ... KeyError We wrap the original exception to give the calling application access to the test and example information. If the output doesn't match, then a DocTestFailure is raised: >>> test = DocTestParser().get_doctest(''' ... >>> x = 1 ... >>> x ... 2 ... ''', {}, 'foo', 'foo.py', 0) >>> try: ... runner.run(test) ... except DocTestFailure, failure: ... pass DocTestFailure objects provide access to the test: >>> failure.test is test True As well as to the example: >>> failure.example.want '2\n' and the actual output: >>> failure.got '1\n' If a failure or error occurs, the globals are left intact: >>> del test.globs['__builtins__'] >>> test.globs {'x': 1} >>> test = DocTestParser().get_doctest(''' ... >>> x = 2 ... >>> raise KeyError ... ''', {}, 'foo', 'foo.py', 0) >>> runner.run(test) Traceback (most recent call last): ... UnexpectedException: >>> del test.globs['__builtins__'] >>> test.globs {'x': 2} But the globals are cleared if there is no error: >>> test = DocTestParser().get_doctest(''' ... >>> x = 2 ... ''', {}, 'foo', 'foo.py', 0) >>> runner.run(test) (0, 1) >>> test.globs {} cCs;ti||||t}|o|i i n|SdS(N( s DocTestRunnersrunsselfstests compileflagssoutsFalsesrs clear_globssglobssclear(sselfstests compileflagssouts clear_globssr((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysrunscCst|||dS(N(sUnexpectedExceptionstestsexamplesexc_info(sselfsoutstestsexamplesexc_info((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysreport_unexpected_exceptionscCst|||dS(N(sDocTestFailurestestsexamplesgot(sselfsoutstestsexamplesgot((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysreport_failures(s__name__s __module__s__doc__sNonesTruesrunsreport_unexpected_exceptionsreport_failure(((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys DebugRunnergs Y c CsS|tj otidtn|tjotiid}nt i | ot d|fn|tjo |i }ntd|d| } |otd|d|} ntd|d|} x3| i||d|d |D]} | i| qW|o| inttjo | anti| | i | i!fSd S( s m=None, name=None, globs=None, verbose=None, isprivate=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, exclude_empty=False Test examples in docstrings in functions and classes reachable from module m (or the current module if m is not supplied), starting with m.__doc__. Unless isprivate is specified, private names are not skipped. Also test examples reachable from dict m.__test__ if it exists and is not None. m.__test__ maps names to functions, classes and strings; function and class docstrings are tested even if the name is private; strings are tested directly, as if they were docstrings. Return (#failures, #tests). See doctest.__doc__ for an overview. Optional keyword arg "name" gives the name of the module; by default use m.__name__. Optional keyword arg "globs" gives a dict to be used as the globals when executing examples; by default, use m.__dict__. A copy of this dict is actually used for each docstring, so that each docstring's examples start with a clean slate. Optional keyword arg "extraglobs" gives a dictionary that should be merged into the globals that are used to execute examples. By default, no extra globals are used. This is new in 2.4. Optional keyword arg "verbose" prints lots of stuff if true, prints only failures if false; by default, it's true iff "-v" is in sys.argv. Optional keyword arg "report" prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else very brief (in fact, empty if all tests passed). Optional keyword arg "optionflags" or's together module constants, and defaults to 0. This is new in 2.3. Possible values (see the docs for details): DONT_ACCEPT_TRUE_FOR_1 DONT_ACCEPT_BLANKLINE NORMALIZE_WHITESPACE ELLIPSIS IGNORE_EXCEPTION_DETAIL REPORT_UDIFF REPORT_CDIFF REPORT_NDIFF REPORT_ONLY_FIRST_FAILURE Optional keyword arg "raise_on_error" raises an exception on the first unexpected exception or failure. This allows failures to be post-mortem debugged. Deprecated in Python 2.4: Optional keyword arg "isprivate" specifies a function used to determine whether a name is private. The default function is treat all functions as public. Optionally, "isprivate" can be set to doctest.is_private to skip over functions marked as private using the underscore naming convention; see its docs for details. Advanced tomfoolery: testmod runs methods of a local instance of class doctest.Tester, then merges the results into (or creates) global Tester instance doctest.master. Methods of doctest.master can be called directly too, if you want to do something unusual. Passing report=0 to testmod is especially useful then, to delay displaying a summary. Invoke doctest.master.summarize(verbose) when you're done fiddling. sPthe isprivate argument is deprecated; examine DocTestFinder.find() lists insteads__main__stestmod: module required; %rs _namefilters exclude_emptysverboses optionflagssglobss extraglobsN("s isprivatesNoneswarningsswarnsDeprecationWarningsmssyssmodulessgetsinspectsismodules TypeErrorsnames__name__s DocTestFinders exclude_emptysfindersraise_on_errors DebugRunnersverboses optionflagssrunners DocTestRunnersfindsglobss extraglobsstestsrunsreports summarizesmastersmergesfailuresstries( smsnamesglobssverboses isprivatesreports optionflagss extraglobssraise_on_errors exclude_emptysrunnerstestsfinder((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pystestmods0H         c Cse|o| otdn|ot|}t||}n|tjoti i |}n|tjo h}n |i }|tj o|i|n| otd|d|} ntd|d|} t|i} | i| |||d} | i| |o| inttjo | anti| | i | i!fSdS(s Test examples in the given file. Return (#failures, #tests). Optional keyword arg "module_relative" specifies how filenames should be interpreted: - If "module_relative" is True (the default), then "filename" specifies a module-relative path. By default, this path is relative to the calling module's directory; but if the "package" argument is specified, then it is relative to that package. To ensure os-independence, "filename" should use "/" characters to separate path segments, and should not be an absolute path (i.e., it may not begin with "/"). - If "module_relative" is False, then "filename" specifies an os-specific path. The path may be absolute or relative (to the current working directory). Optional keyword arg "name" gives the name of the test; by default use the file's basename. Optional keyword argument "package" is a Python package or the name of a Python package whose directory should be used as the base directory for a module relative filename. If no package is specified, then the calling module's directory is used as the base directory for module relative filenames. It is an error to specify "package" if "module_relative" is False. Optional keyword arg "globs" gives a dict to be used as the globals when executing examples; by default, use {}. A copy of this dict is actually used for each docstring, so that each docstring's examples start with a clean slate. Optional keyword arg "extraglobs" gives a dictionary that should be merged into the globals that are used to execute examples. By default, no extra globals are used. Optional keyword arg "verbose" prints lots of stuff if true, prints only failures if false; by default, it's true iff "-v" is in sys.argv. Optional keyword arg "report" prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else very brief (in fact, empty if all tests passed). Optional keyword arg "optionflags" or's together module constants, and defaults to 0. Possible values (see the docs for details): DONT_ACCEPT_TRUE_FOR_1 DONT_ACCEPT_BLANKLINE NORMALIZE_WHITESPACE ELLIPSIS IGNORE_EXCEPTION_DETAIL REPORT_UDIFF REPORT_CDIFF REPORT_NDIFF REPORT_ONLY_FIRST_FAILURE Optional keyword arg "raise_on_error" raises an exception on the first unexpected exception or failure. This allows failures to be post-mortem debugged. Optional keyword arg "parser" specifies a DocTestParser (or subclass) that should be used to extract tests from the files. Advanced tomfoolery: testmod runs methods of a local instance of class doctest.Tester, then merges the results into (or creates) global Tester instance doctest.master. Methods of doctest.master can be called directly too, if you want to do something unusual. Passing report=0 to testmod is especially useful then, to delay displaying a summary. Invoke doctest.master.summarize(verbose) when you're done fiddling. s8Package may only be specified for module-relative paths.sverboses optionflagsiN("spackagesmodule_relatives ValueErrors_normalize_modules_module_relative_pathsfilenamesnamesNonesosspathsbasenamesglobsscopys extraglobssupdatesraise_on_errors DebugRunnersverboses optionflagssrunners DocTestRunnersopensreadsssparsers get_docteststestsrunsreports summarizesmastersmergesfailuresstries(sfilenamesmodule_relativesnamespackagesglobssverbosesreports optionflagss extraglobssraise_on_errorsparsersrunnerstestss((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pystestfileKs4J          sNoNamec Csdtd|dt}td|d|}x3|i||d|D]}|i |d|qCWdS(sr Test examples in the given object's docstring (`f`), using `globs` as globals. Optional argument `name` is used in failure messages. If the optional argument `verbose` is true, then generate output even if there are no failures. `compileflags` gives the set of flags that should be used by the Python compiler when running the examples. If not specified, then it will default to the set of future-import flags that apply to `globs`. Optional keyword arg `optionflags` specifies options for the testing and output. See the documentation for `testmod` for more information. sverbosesrecurses optionflagssglobss compileflagsN(s DocTestFindersverbosesFalsesfinders DocTestRunners optionflagssrunnersfindsfsnamesglobsstestsruns compileflags( sfsglobssverbosesnames compileflagss optionflagssrunnerstestsfinder((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysrun_docstring_exampless cBsbtZeeeeddZdZeedZedZdZedZdZ RS( NicCstidtdd|tjo |tjotdn|tj oti| otd|fn|tjo |i }n||_||_ ||_ ||_ td||_td|d||_dS( NsCclass Tester is deprecated; use class doctest.DocTestRunner insteads stacklevelis*Tester.__init__: must specify mod or globss)Tester.__init__: mod must be a module; %rs _namefiltersverboses optionflags(swarningsswarnsDeprecationWarningsmodsNonesglobss TypeErrorsinspectsismodules__dict__sselfsverboses isprivates optionflagss DocTestFinders testfinders DocTestRunners testrunner(sselfsmodsglobssverboses isprivates optionflags((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys__init__s         cCsti||i|tt}|io dG|GHn|i i |\}}|io|GdG|GdG|GHn||fSdS(NsRunning stringsofsexamples failed in string( s DocTestParsers get_doctestsssselfsglobssnamesNonestestsverboses testrunnersrunsfst(sselfsssnamesfststest((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys runstrings!   c Csd}}|ii||d|d|i}x@|D]8} |i i | \}}||||f\}}q5W||fSdS(Nismodulesglobs(sfstsselfs testfindersfindsobjectsnamesmodulesglobsstestsstests testrunnersrunsf2st2( sselfsobjectsnamesmodulestestssfst2sf2ststest((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysrundocs cCsVdk}|i|}|ii||tjo t}n|i |||SdS(N( snewsmodulesnamesms__dict__supdatesdsNonesFalsesselfsrundoc(sselfsdsnamesmodulesmsnew((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysrundicts    cCs5dk}|i|}||_|i||SdS(N(snewsmodulesnamesmsds__test__sselfsrundoc(sselfsdsnamesnewsm((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys run__test__s  cCs|ii|SdS(N(sselfs testrunners summarizesverbose(sselfsverbose((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys summarizescCs|ii|idS(N(sselfs testrunnersmergesother(sselfsother((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysmerges( s__name__s __module__sNones__init__s runstringsrundocsrundicts run__test__s summarizesmerge(((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysTesters    cCs8|t@|jotd|nt}|a|SdS(sSets the unittest option flags. The old flag is returned so that a runner could restore the old value if it wished to: >>> old = _unittest_reportflags >>> set_unittest_reportflags(REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) == old True >>> import doctest >>> doctest._unittest_reportflags == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True Only reporting flags can be set: >>> set_unittest_reportflags(ELLIPSIS) Traceback (most recent call last): ... ValueError: ('Only reporting flags allowed', 8) >>> set_unittest_reportflags(old) == (REPORT_NDIFF | ... REPORT_ONLY_FIRST_FAILURE) True sOnly reporting flags allowedN(sflagssREPORTING_FLAGSs ValueErrors_unittest_reportflagssold(sflagssold((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysset_unittest_reportflags!ss DocTestCasecBsktZdeeedZdZdZdZdZdZdZ d Z e Z d Z RS( NicCsAtii|||_||_||_ ||_ ||_ dS(N(sunittestsTestCases__init__sselfs optionflagss_dt_optionflagsscheckers _dt_checkerstests_dt_testssetUps _dt_setUpstearDowns _dt_tearDown(sselfstests optionflagsssetUpstearDownschecker((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys__init__Gs     cCs.|i}|itj o|i|ndS(N(sselfs_dt_teststests _dt_setUpsNone(sselfstest((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pyssetUpQs cCs;|i}|itj o|i|n|iidS(N(sselfs_dt_teststests _dt_tearDownsNonesglobssclear(sselfstest((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pystearDownWs cCs|i}ti}t}|i}|t @ o|t O}nt d|d|i dt}z5dd|_|i|d|idt\}}Wd|t_X|o"|i|i|indS(Ns optionflagsscheckersverboses-iFsouts clear_globs(sselfs_dt_teststestssyssstdoutsoldsStringIOsnews_dt_optionflagss optionflagssREPORTING_FLAGSs_unittest_reportflagss DocTestRunners _dt_checkersFalsesrunnersDIVIDERsrunswritesfailuresstriessfailureExceptionsformat_failuresgetvalue(sselfsoldsrunnerstriessfailuresstestsnews optionflags((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysrunTest_s       ( cCsp|i}|itjo d}nd|i}di|iidd}d|i|i |||fSdS(Nsunknown line numbers%ss.is:Failed doctest test for %s File "%s", line %s, in %s %s( sselfs_dt_teststestslinenosNonesjoinsnamessplitslnamesfilenameserr(sselfserrslnameslinenostest((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysformat_failurews    cCsI|itd|id|idt}|i|i|i dS(sRun the test case without results and without catching exceptions The unit test framework includes a debug method on test cases and test suites to support post-mortem debugging. The test code is run in such a way that errors are not caught. This way a caller can catch the errors and initiate post-mortem debugging. The DocTestCase provides a debug method that raises UnexpectedException errors if there is an unexepcted exception: >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42', ... {}, 'foo', 'foo.py', 0) >>> case = DocTestCase(test) >>> try: ... case.debug() ... except UnexpectedException, failure: ... pass The UnexpectedException contains the test, the example, and the original exception: >>> failure.test is test True >>> failure.example.want '42\n' >>> exc_info = failure.exc_info >>> raise exc_info[0], exc_info[1], exc_info[2] Traceback (most recent call last): ... KeyError If the output doesn't match, then a DocTestFailure is raised: >>> test = DocTestParser().get_doctest(''' ... >>> x = 1 ... >>> x ... 2 ... ''', {}, 'foo', 'foo.py', 0) >>> case = DocTestCase(test) >>> try: ... case.debug() ... except DocTestFailure, failure: ... pass DocTestFailure objects provide access to the test: >>> failure.test is test True As well as to the example: >>> failure.example.want '2\n' and the actual output: >>> failure.got '1\n' s optionflagsscheckersverboseN( sselfssetUps DebugRunners_dt_optionflagss _dt_checkersFalsesrunnersruns_dt_teststearDown(sselfsrunner((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysdebugs @  cCs|iiSdS(N(sselfs_dt_testsname(sself((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysidscCs8|iiid}d|ddi|d fSdS(Ns.s%s (%s)i(sselfs_dt_testsnamessplitsjoin(sselfsname((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys__repr__scCsd|iiSdS(Ns Doctest: (sselfs_dt_testsname(sself((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysshortDescriptions( s__name__s __module__sNones__init__ssetUpstearDownsrunTestsformat_failuresdebugsids__repr__s__str__sshortDescription(((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys DocTestCaseEs    H  c Ks|tjo t}nt|}|i|d|d|}|tjo |i }n| ot |dn|i t i }x|D]}t|idjoqn|i o;|i}|dddfjo|d }n||_n|it||qW|Sd S( s Convert doctest tests for a module to a unittest test suite. This converts each documentation string in a module that contains doctest tests to a unittest test case. If any of the tests in a doc string fail, then the test case fails. An exception is raised showing the name of the file containing the test and a (sometimes approximate) line number. The `module` argument provides the module to be tested. The argument can be either a module or a module name. If no argument is given, the calling module is used. A number of options may be provided as keyword arguments: setUp A set-up function. This is called before running the tests in each file. The setUp function will be passed a DocTest object. The setUp function can access the test globals as the globs attribute of the test passed. tearDown A tear-down function. This is called after running the tests in each file. The tearDown function will be passed a DocTest object. The tearDown function can access the test globals as the globs attribute of the test passed. globs A dictionary containing initial global variables for the tests. optionflags A set of doctest option flags expressed as an integer. sglobss extraglobss has no testsiis.pycs.pyoiN(s test_findersNones DocTestFinders_normalize_modulesmodulesfindsglobss extraglobsstestss__dict__s ValueErrorssortsunittests TestSuitessuitestestslensexamplessfilenames__file__saddTests DocTestCasesoptions( smodulesglobss extraglobss test_findersoptionsstestsstestssuitesfilename((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys DocTestSuites,#          s DocFileCasecBs)tZdZdZeZdZRS(NcCs di|iiidSdS(Ns_s.(sjoinsselfs_dt_testsnamessplit(sself((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysid scCs|iiSdS(N(sselfs_dt_testsfilename(sself((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys__repr__ scCs!d|ii|ii|fSdS(Ns2Failed doctest test for %s File "%s", line 0 %s(sselfs_dt_testsnamesfilenameserr(sselfserr((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysformat_failure s(s__name__s __module__sids__repr__s__str__sformat_failure(((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys DocFileCase s  c Ks|tjo h}n|o| otdn|ot|}t||}ntii |}t |i }|i||||d}t||SdS(Ns8Package may only be specified for module-relative paths.i(sglobssNonespackagesmodule_relatives ValueErrors_normalize_modules_module_relative_pathspathsossbasenamesnamesopensreadsdocsparsers get_docteststests DocFileCasesoptions( spathsmodule_relativespackagesglobssparsersoptionssnamesdocstest((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys DocFileTest$ s   cOskti}|idtot|id|dA unittest suite for one or more doctest files. The path to each doctest file is given as a string; the interpretation of that string depends on the keyword argument "module_relative". A number of options may be provided as keyword arguments: module_relative If "module_relative" is True, then the given file paths are interpreted as os-independent module-relative paths. By default, these paths are relative to the calling module's directory; but if the "package" argument is specified, then they are relative to that package. To ensure os-independence, "filename" should use "/" characters to separate path segments, and may not be an absolute path (i.e., it may not begin with "/"). If "module_relative" is False, then the given file paths are interpreted as os-specific paths. These paths may be absolute or relative (to the current working directory). package A Python package or the name of a Python package whose directory should be used as the base directory for module relative paths. If "package" is not specified, then the calling module's directory is used as the base directory for module relative filenames. It is an error to specify "package" if "module_relative" is False. setUp A set-up function. This is called before running the tests in each file. The setUp function will be passed a DocTest object. The setUp function can access the test globals as the globs attribute of the test passed. tearDown A tear-down function. This is called after running the tests in each file. The tearDown function will be passed a DocTest object. The tearDown function can access the test globals as the globs attribute of the test passed. globs A dictionary containing initial global variables for the tests. optionflags A set of doctest option flags expressed as an integer. parser A DocTestParser (or subclass) that should be used to extract tests from the files. smodule_relativespackageN( sunittests TestSuitessuiteskwsgetsTrues_normalize_modulespathsspathsaddTests DocFileTest(spathsskwspathssuite((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys DocFileSuite: s4 cCsNg}xti|D]}t|tou|i|id |i }|oM|id|gi}|i dd D]}|d|q~~7}qq|gi}|i dd D]}|t |q~7}qWx'|o|ddjo|iqWx*|o|ddjo|idqWdi|SdS(scExtract script from text with examples. Converts text with examples to a Python script. Example input is converted to regular code. Example output and all other words are converted to comments: >>> text = ''' ... Here are examples of simple math. ... ... Python has super accurate integer addition ... ... >>> 2 + 2 ... 5 ... ... And very friendly error messages: ... ... >>> 1/0 ... To Infinity ... And ... Beyond ... ... You can use logic if you want: ... ... >>> if 0: ... ... blah ... ... blah ... ... ... ... Ho hum ... ''' >>> print script_from_examples(text) # Here are examples of simple math. # # Python has super accurate integer addition # 2 + 2 # Expected: ## 5 # # And very friendly error messages: # 1/0 # Expected: ## To Infinity ## And ## Beyond # # You can use logic if you want: # if 0: blah blah # # Ho hum is # Expected:s s## s#iN(soutputs DocTestParsersparsessspieces isinstancesExamplesappendssourceswants_[1]ssplitsls _comment_linespopsjoin(ssspiecesls_[1]swantsoutput((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysscript_from_examples s$8  DBcCst|}ti|}gi}|D]$}|i|jo||q,q,~}| ot |dn|d}t |i }|SdS(sExtract the test sources from a doctest docstring as a script. Provide the module (or dotted name of the module) containing the test to be debugged and the name (within the module) of the object with the doc string with tests to be debugged. snot found in testsiN(s_normalize_modulesmodules DocTestFindersfindstestssappends_[1]stsnamestests ValueErrorsscript_from_exampless docstringstestsrc(smodulesnamestestss_[1]stestsrcststest((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys testsource s ; cCs t|}t|||dS(s4Debug a single doctest docstring, in argument `src`'N(sscript_from_examplesssrcstestsrcs debug_scriptspmsglobs(ssrcspmsglobsstestsrc((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys debug_src s cCsdk}tidd}t|d}|i||iz|o|i }nh}|oHyt |||Wqt idGH|it idqXn|id|||Wdti|XdS(s7Debug a test script. `src` is the script, as a string.Ns.pys doctestdebugswiis execfile(%r)(spdbstempfilesmktemps srcfilenamesopensfswritessrcsclosesglobsscopyspmsexecfilessyssexc_infos post_mortemsrunsossremove(ssrcspmsglobssfs srcfilenamespdb((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys debug_script s&   cCs2t|}t||}t|||idS(sDebug a single doctest docstring. Provide the module (or dotted name of the module) containing the test to be debugged and the name (within the module) of the object with the docstring with tests to be debugged. N(s_normalize_modulesmodules testsourcesnamestestsrcs debug_scriptspms__dict__(smodulesnamespmstestsrc((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysdebug s s _TestClasscBs)tZdZdZdZdZRS(s A pointless class, for sanity-checking of docstring testing. Methods: square() get() >>> _TestClass(13).get() + _TestClass(-12).get() 1 >>> hex(_TestClass(13).square().get()) '0xa9' cCs ||_dS(sval -> _TestClass object with associated value val. >>> t = _TestClass(123) >>> print t.get() 123 N(svalsself(sselfsval((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys__init__! scCs|id|_|SdS(sosquare() -> square TestClass's associated value >>> _TestClass(13).square().get() 169 iN(sselfsval(sself((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pyssquare+ scCs |iSdS(s}get() -> return TestClass's associated value. >>> x = _TestClass(-42) >>> print x.get() -42 N(sselfsval(sself((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pysget5 s(s__name__s __module__s__doc__s__init__ssquaresget(((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys _TestClass s  sstrings Example of a string object, searched as-is. >>> x = 1; y = 2 >>> x + y, x * y (3, 2) sbool-int equivalences In 2.2, boolean expressions displayed 0 or 1. By default, we still accept them. This can be disabled by passing DONT_ACCEPT_TRUE_FOR_1 to the new optionflags argument. >>> 4 == 4 1 >>> 4 == 4 True >>> 4 > 4 0 >>> 4 > 4 False s blank liness Blank lines can be marked with : >>> print 'foo\n\nbar\n' foo bar sellipsiss If the ellipsis flag is used, then '...' can be used to elide substrings in the desired output: >>> print range(1000) #doctest: +ELLIPSIS [0, 1, 2, ..., 999] swhitespace normalizations| If the whitespace normalization flag is used, then differences in whitespace are ignored. >>> print range(30) #doctest: +NORMALIZE_WHITESPACE [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29] cCs ti}|itdS(N(sunittestsTextTestRunnersrsruns DocTestSuite(sr((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys_testq s s__main__(Ts basestrings NameErrorsstrsunicodes enumerates __docformat__s__all__s __future__ssyss tracebacksinspects linecachesossrestypessunittestsdifflibspdbstempfileswarningssStringIOsfilterwarningssDeprecationWarnings__name__sOPTIONFLAGS_BY_NAMEsregister_optionflagsDONT_ACCEPT_TRUE_FOR_1sDONT_ACCEPT_BLANKLINEsNORMALIZE_WHITESPACEsELLIPSISsIGNORE_EXCEPTION_DETAILsCOMPARISON_FLAGSs REPORT_UDIFFs REPORT_CDIFFs REPORT_NDIFFsREPORT_ONLY_FIRST_FAILUREsREPORTING_FLAGSsBLANKLINE_MARKERsELLIPSIS_MARKERs is_privates_extract_future_flagss_normalize_modules_indents_exception_tracebacks _SpoofOuts_ellipsis_matchs _comment_linesPdbs_OutputRedirectingPdbs_module_relative_pathsExamplesDocTests DocTestParsers DocTestFinders DocTestRunners OutputCheckers ExceptionsDocTestFailuresUnexpectedExceptions DebugRunnersNonesmastersTruesFalsestestmodstestfilesrun_docstring_examplessTesters_unittest_reportflagssset_unittest_reportflagssTestCases DocTestCases DocTestSuites DocFileCases DocFileTests DocFileSuitesscript_from_exampless testsources debug_srcs debug_scriptsdebugs _TestClasss__test__s_test(Fs_module_relative_paths __future__s OutputCheckersBLANKLINE_MARKERsunittestsNORMALIZE_WHITESPACEs __docformat__stestmods_normalize_modules REPORT_UDIFFsDONT_ACCEPT_TRUE_FOR_1s enumerates_OutputRedirectingPdbs_ellipsis_matchs basestringsIGNORE_EXCEPTION_DETAILs__all__sTesterstempfiles DocFileCases DocTestRunners DocFileTestsres is_privatesDocTestFailures DocTestCasesELLIPSISs_tests _comment_lines REPORT_CDIFFs testsourcesDocTestsDONT_ACCEPT_BLANKLINEs _SpoofOutswarningss DocFileSuitesrun_docstring_examplessREPORT_ONLY_FIRST_FAILUREsinspects _TestClasss debug_scriptssyssdebugsscript_from_exampless debug_srcs__test__s_extract_future_flagss_indentsExamplestypess DocTestSuitesregister_optionflagsOPTIONFLAGS_BY_NAMEs DocTestParsersStringIOsset_unittest_reportflagss REPORT_NDIFFs tracebacksdifflibs linecaches DocTestFinders DebugRunnersELLIPSIS_MARKERsREPORTING_FLAGSsCOMPARISON_FLAGSsUnexpectedExceptionsosspdbstestfiles_exception_traceback((s<build/bdist.darwin-8.9.1-i386/egg/protocols/tests/doctest.pys? s(i. ?$                  1  $5<+n't*vA $? F P  ,<2  PKOk6<#protocols/tests/test_advice.py"""Tests for advice""" from unittest import TestCase, makeSuite, TestSuite from protocols.advice import * import sys from types import InstanceType class SuperTest(TestCase): def checkMetaSuper(self): class Meta(type): def foo(self,arg): return arg foo = metamethod(foo) class Class(object): __metaclass__ = Meta def foo(self,arg): return arg*2 # Verify that ob.foo() and ob.__class__.foo() are different assert Class.foo(1)==1 assert Class().foo(1)==2 # Verify that supermeta() works for such methods class SubMeta(Meta): def foo(self,arg): return -supermeta(SubMeta,self).foo(arg) foo = metamethod(foo) class ClassOfSubMeta(Class): __metaclass__ = SubMeta assert ClassOfSubMeta.foo(1)==-1 assert ClassOfSubMeta().foo(1)==2 def checkPropSuper(self): class Base(object): __slots__ = 'foo' class Sub(Base): def getFoo(self): return supermeta(Sub,self).foo * 2 def setFoo(self,val): Base.foo.__set__(self,val) foo = property(getFoo, setFoo) ob = Sub() ob.foo = 1 assert ob.foo == 2 def checkSuperNotFound(self): class Base(object): pass b = Base() try: supermeta(Base,b).foo except AttributeError: pass else: raise AssertionError("Shouldn't have returned a value") class MROTests(TestCase): def checkStdMRO(self): class foo(object): pass class bar(foo): pass class baz(foo): pass class spam(bar,baz): pass assert getMRO(spam) is spam.__mro__ def checkClassicMRO(self): class foo: pass class bar(foo): pass class baz(foo): pass class spam(bar,baz): pass basicMRO = [spam,bar,foo,baz,foo] assert list(getMRO(spam)) == basicMRO assert list(getMRO(spam,True)) == basicMRO+[InstanceType,object] TestClasses = SuperTest, MROTests def test_suite(): return TestSuite([makeSuite(t,'check') for t in TestClasses]) PK86yprotocols/tests/test_advice.pyc; (Ec@sdZdklZlZlZdkTdkZdklZdefdYZ defdYZ e e fZ d Z dS( sTests for advice(sTestCases makeSuites TestSuite(s*N(s InstanceTypes SuperTestcBs#tZdZdZdZRS(NcsdtfdYdtfdY}|iddjpt|iddjptdfdYd |fd Y}|idd jpt|iddjptdS( NsMetacBstZdZeeZRS(NcCs|SdS(N(sarg(sselfsarg((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pysfoo s(s__name__s __module__sfoos metamethod(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pysMeta s sClasscstZZdZRS(NcCs |dSdS(Ni(sarg(sselfsarg((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pysfoos(s__name__s __module__sMetas __metaclass__sfoo((sMeta(s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pysClasssiisSubMetacs tZdZeeZRS(Ncst|i| SdS(N(s supermetasSubMetasselfsfoosarg(sselfsarg(sSubMeta(s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pysfoos(s__name__s __module__sfoos metamethod((sSubMeta(s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pysSubMetas sClassOfSubMetacstZZRS(N(s__name__s __module__sSubMetas __metaclass__((sSubMeta(s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pysClassOfSubMeta#si(stypesMetasobjectsClasssfoosAssertionErrorsSubMetasClassOfSubMeta(sselfsClassOfSubMetasSubMetasMetasClass((sSubMetasMetas@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pyscheckMetaSuper s cs_dtfdYdfdY}d|_|idjptdS(NsBasecBstZdZRS(Nsfoo(s__name__s __module__s __slots__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pysBase,ssSubcs/tZdZdZeeeZRS(Ncst|idSdS(Ni(s supermetasSubsselfsfoo(sself(sSub(s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pysgetFoo1scsii||dS(N(sBasesfoos__set__sselfsval(sselfsval(sBase(s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pyssetFoo4s(s__name__s __module__sgetFoossetFoospropertysfoo((sSubsBase(s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pysSub/s  ii(sobjectsBasesSubsobsfoosAssertionError(sselfsBasesSubsob((sBasesSubs@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pyscheckPropSuper*s   cCsYdtfdY}|}yt||iWntj onXtddS(NsBasecBstZRS(N(s__name__s __module__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pysBase?ssShouldn't have returned a value(sobjectsBasesbs supermetasfoosAttributeErrorsAssertionError(sselfsbsBase((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pyscheckSuperNotFound>s (s__name__s __module__scheckMetaSuperscheckPropSuperscheckSuperNotFound(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pys SuperTests sMROTestscBstZdZdZRS(NcCs|dtfdY}d|fdY}d|fdY}d||fdY}t||ijptdS( NsfoocBstZRS(N(s__name__s __module__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pysfooVssbarcBstZRS(N(s__name__s __module__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pysbarWssbazcBstZRS(N(s__name__s __module__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pysbazXssspamcBstZRS(N(s__name__s __module__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pysspamYs(sobjectsfoosbarsbazsspamsgetMROs__mro__sAssertionError(sselfsbarsspamsbazsfoo((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pys checkStdMROUs cCsdfdY}d|fdY}d|fdY}d||fdY}|||||g}tt||jpttt|t|t t gjptdS( NsfoocBstZRS(N(s__name__s __module__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pysfoo]ssbarcBstZRS(N(s__name__s __module__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pysbar^ssbazcBstZRS(N(s__name__s __module__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pysbaz_ssspamcBstZRS(N(s__name__s __module__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pysspam`s( sfoosbarsbazsspamsbasicMROslistsgetMROsAssertionErrorsTrues InstanceTypesobject(sselfsbarsspamsbazsbasicMROsfoo((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pyscheckClassicMRO\s (s__name__s __module__s checkStdMROscheckClassicMRO(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pysMROTestsSs cCs8tgi}tD]}|t|dq~SdS(Nscheck(s TestSuitesappends_[1]s TestClassessts makeSuite(s_[1]st((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pys test_suiteis( s__doc__sunittestsTestCases makeSuites TestSuitesprotocols.advicessysstypess InstanceTypes SuperTestsMROTestss TestClassess test_suite( s TestSuites TestClassess makeSuites SuperTestsTestCases test_suitessyss InstanceTypesMROTests((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_advice.pys?s  K PKʃ95ԥ$$protocols/tests/test_classes.py"""Tests for implementor declarations (i.e. instancesProvides)""" from unittest import TestCase, makeSuite, TestSuite from protocols import * from checks import ImplementationChecks, AdaptiveChecks, makeClassTests class IA(Interface): pass class IB(IA): pass class IPure(Interface): # We use this for pickle/copy tests because the other protocols # imply various dynamically created interfaces, and so any object # registered with them won't be picklable pass class BasicChecks(AdaptiveChecks, ImplementationChecks): """PyProtocols-only class-instances-provide checks""" IA = IA IB = IB Interface = Interface IPure = IPure def checkChangingBases(self): # Zope and Twisted fail this because they rely on the first-found # __implements__ attribute and ignore a class' MRO/__bases__ M1, M2 = self.setupBases(self.klass) m1 = self.make(M1) m2 = self.make(M2) declareImplementation(M1, instancesProvide=[self.IA]) declareImplementation(M2, instancesProvide=[self.IB]) self.assertM1ProvidesOnlyAandM2ProvidesB(m1,m2) self.assertChangingBasesChangesInterface(M1,M2,m1,m2) TestClasses = makeClassTests(BasicChecks) def test_suite(): return TestSuite([makeSuite(t,'check') for t in TestClasses]) PK86& protocols/tests/test_classes.pyc; Ec@sdZdklZlZlZdkTdklZlZl Z de fdYZ de fdYZ de fd YZ d eefd YZe eZd Zd S(s;Tests for implementor declarations (i.e. instancesProvides)(sTestCases makeSuites TestSuite(s*(sImplementationCheckssAdaptiveCheckssmakeClassTestssIAcBstZRS(N(s__name__s __module__(((sAbuild/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_classes.pysIAssIBcBstZRS(N(s__name__s __module__(((sAbuild/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_classes.pysIBssIPurecBstZRS(N(s__name__s __module__(((sAbuild/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_classes.pysIPure ss BasicCheckscBs/tZdZeZeZeZeZdZRS(s/PyProtocols-only class-instances-provide checkscCs|i|i\}}|i|}|i|}t|d|i gt|d|i g|i |||i ||||dS(NsinstancesProvide( sselfs setupBasessklasssM1sM2smakesm1sm2sdeclareImplementationsIAsIBs#assertM1ProvidesOnlyAandM2ProvidesBs#assertChangingBasesChangesInterface(sselfsM2sm1sm2sM1((sAbuild/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_classes.pyscheckChangingBasess(s__name__s __module__s__doc__sIAsIBs InterfacesIPurescheckChangingBases(((sAbuild/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_classes.pys BasicCheckss cCs8tgi}tD]}|t|dq~SdS(Nscheck(s TestSuitesappends_[1]s TestClassessts makeSuite(s_[1]st((sAbuild/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_classes.pys test_suite'sN(s__doc__sunittestsTestCases makeSuites TestSuites protocolsscheckssImplementationCheckssAdaptiveCheckssmakeClassTestss InterfacesIAsIBsIPures BasicCheckss TestClassess test_suite( s TestSuitesIBsImplementationCheckssmakeClassTestssIPures makeSuitesTestCases TestClassess test_suitesIAsAdaptiveCheckss BasicChecks((sAbuild/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_classes.pys?s PKʃ95" protocols/tests/test_direct.py"""Tests for default IOpenProvider (etc.) adapters TODO: - Test Zope interface registrations """ from unittest import TestCase, makeSuite, TestSuite from protocols import * from checks import ProviderChecks, AdaptiveChecks, ClassProvidesChecks from checks import makeClassProvidesTests, makeInstanceTests from checks import makeMetaClassProvidesTests class IA(Interface): pass class IB(IA): pass class IPure(Interface): # We use this for pickle/copy tests because the other protocols # imply various dynamically created interfaces, and so any object # registered with them won't be picklable pass class BasicChecks(AdaptiveChecks, ProviderChecks): """Checks to be done on every object""" IA = IA IB = IB Interface = Interface IPure = IPure def checkCircularRegister(self): P1 = Protocol() P2 = Protocol() declareAdapter(NO_ADAPTER_NEEDED,provides=[P2],forProtocols=[P1]) declareAdapter(NO_ADAPTER_NEEDED,provides=[P1],forProtocols=[P2]) self.declareObImplements([P1]) # implies P1->P2->P1 class ClassChecks(ClassProvidesChecks, BasicChecks): """Checks to be done on classes and types""" class InstanceConformChecks: """Things to check on adapted instances""" def checkBadConform(self): def __conform__(proto): pass self.ob.__conform__ = __conform__ self.assertBadConform(self.ob, [self.IA], __conform__) def assertBadConform(self, ob, protocols, conform): try: adviseObject(ob, provides=protocols) except TypeError,v: assert v.args==( "Incompatible __conform__ on adapted object", ob, conform ), v.args else: raise AssertionError("Should've detected invalid __conform__") class ClassConformChecks(InstanceConformChecks): """Things to check on adapted classes""" def checkInheritedConform(self): class Base(self.ob): def __conform__(self,protocol): pass class Sub(Base): pass self.assertBadConform(Sub, [self.IA], Base.__conform__.im_func) def checkInstanceConform(self): class Base(self.ob): def __conform__(self,protocol): pass b = Base() self.assertBadConform(b, [self.IA], b.__conform__) class AdviseMixinInstance(BasicChecks): def setUp(self): self.ob = ProviderMixin() # Notice that we don't test the *metaclass* of the next three configurations; # it would fail because the metaclass itself can't be adapted to an open # provider, because it has a __conform__ method (from ProviderMixin). For # that to work, there'd have to be *another* metalevel. class AdviseMixinMultiMeta1(BasicChecks): def setUp(self): class Meta(ProviderMixin, type): pass class Test(ProviderMixin,object): __metaclass__ = Meta self.ob = Test() class InstanceTestsBase(BasicChecks, InstanceConformChecks): pass class ClassTestsBase(ClassChecks, ClassConformChecks): pass class Picklable: # Pickling needs classes in top-level namespace pass class NewStyle(object): pass TestClasses = ( AdviseMixinInstance, AdviseMixinMultiMeta1, ) TestClasses += makeMetaClassProvidesTests(ClassChecks) TestClasses += makeClassProvidesTests(ClassTestsBase) TestClasses += makeInstanceTests(InstanceTestsBase,Picklable,NewStyle) def test_suite(): return TestSuite([makeSuite(t,'check') for t in TestClasses]) PK86?*B##protocols/tests/test_direct.pyc; Ec@sdZdklZlZlZdkTdklZlZl Z dkl Z l Z dkl Z de fdYZdefd YZd e fd YZd eefd YZde efdYZdfdYZdefdYZdefdYZdefdYZdeefdYZdeefdYZdfdYZdefdYZeefZee e7Zee e7Zee eee7Zd Zd!S("scTests for default IOpenProvider (etc.) adapters TODO: - Test Zope interface registrations (sTestCases makeSuites TestSuite(s*(sProviderCheckssAdaptiveCheckssClassProvidesChecks(smakeClassProvidesTestssmakeInstanceTests(smakeMetaClassProvidesTestssIAcBstZRS(N(s__name__s __module__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pysIAssIBcBstZRS(N(s__name__s __module__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pysIBssIPurecBstZRS(N(s__name__s __module__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pysIPuress BasicCheckscBs/tZdZeZeZeZeZdZRS(s!Checks to be done on every objectcCs^t}t}ttd|gd|gttd|gd|g|i|gdS(Nsprovidess forProtocols(sProtocolsP1sP2sdeclareAdaptersNO_ADAPTER_NEEDEDsselfsdeclareObImplements(sselfsP2sP1((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pyscheckCircularRegister s   (s__name__s __module__s__doc__sIAsIBs InterfacesIPurescheckCircularRegister(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pys BasicCheckss s ClassCheckscBstZdZRS(s&Checks to be done on classes and types(s__name__s __module__s__doc__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pys ClassChecks's sInstanceConformCheckscBs tZdZdZdZRS(s$Things to check on adapted instancescCs5d}||i_|i|i|ig|dS(NcCsdS(N((sproto((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pys __conform__.s(s __conform__sselfsobsassertBadConformsIA(sselfs __conform__((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pyscheckBadConform-s  cCsbyt|d|Wn;tj o/}|id||fjp t|inXtddS(Nsprovidess*Incompatible __conform__ on adapted objects&Should've detected invalid __conform__(s adviseObjectsobs protocolss TypeErrorsvsargssconformsAssertionError(sselfsobs protocolssconformsv((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pysassertBadConform4s +(s__name__s __module__s__doc__scheckBadConformsassertBadConform(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pysInstanceConformChecks*s  sClassConformCheckscBs tZdZdZdZRS(s"Things to check on adapted classescCsRd|ifdY}d|fdY}|i||ig|iidS(NsBasecBstZdZRS(NcCsdS(N((sselfsprotocol((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pys __conform__Ds(s__name__s __module__s __conform__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pysBaseCssSubcBstZRS(N(s__name__s __module__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pysSubFs(sselfsobsBasesSubsassertBadConformsIAs __conform__sim_func(sselfsBasesSub((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pyscheckInheritedConformBscCsBd|ifdY}|}|i||ig|idS(NsBasecBstZdZRS(NcCsdS(N((sselfsprotocol((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pys __conform__Ms(s__name__s __module__s __conform__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pysBaseLs(sselfsobsBasesbsassertBadConformsIAs __conform__(sselfsBasesb((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pyscheckInstanceConformJs (s__name__s __module__s__doc__scheckInheritedConformscheckInstanceConform(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pysClassConformChecks?s  sAdviseMixinInstancecBstZdZRS(NcCst|_dS(N(s ProviderMixinsselfsob(sself((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pyssetUpUs(s__name__s __module__ssetUp(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pysAdviseMixinInstanceSssAdviseMixinMultiMeta1cBstZdZRS(NcsEdttfdYdttfdY}||_dS(NsMetacBstZRS(N(s__name__s __module__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pysMetaassTestcstZZRS(N(s__name__s __module__sMetas __metaclass__((sMeta(s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pysTestbs(s ProviderMixinstypesMetasobjectsTestsselfsob(sselfsMetasTest((sMetas@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pyssetUp`s(s__name__s __module__ssetUp(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pysAdviseMixinMultiMeta1^ssInstanceTestsBasecBstZRS(N(s__name__s __module__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pysInstanceTestsBasefssClassTestsBasecBstZRS(N(s__name__s __module__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pysClassTestsBaseiss PicklablecBstZRS(N(s__name__s __module__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pys PicklablelssNewStylecBstZRS(N(s__name__s __module__(((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pysNewStylepscCs8tgi}tD]}|t|dq~SdS(Nscheck(s TestSuitesappends_[1]s TestClassessts makeSuite(s_[1]st((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pys test_suite|sN(s__doc__sunittestsTestCases makeSuites TestSuites protocolsscheckssProviderCheckssAdaptiveCheckssClassProvidesCheckssmakeClassProvidesTestssmakeInstanceTestssmakeMetaClassProvidesTestss InterfacesIAsIBsIPures BasicCheckss ClassCheckssInstanceConformCheckssClassConformCheckssAdviseMixinInstancesAdviseMixinMultiMeta1sInstanceTestsBasesClassTestsBases PicklablesobjectsNewStyles TestClassess test_suite(s TestClassessAdviseMixinInstancesmakeInstanceTestssClassConformCheckssInstanceConformCheckss TestSuitesClassTestsBasesTestCasesmakeClassProvidesTestssInstanceTestsBasesAdaptiveCheckss BasicCheckss makeSuitesIPuresAdviseMixinMultiMeta1sClassProvidesCheckssIAsIBsmakeMetaClassProvidesTestss PicklablesProviderCheckss test_suites ClassCheckssNewStyle((s@build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_direct.pys?s.   PKʃ95CSSprotocols/tests/test_twisted.py"""Twisted Interface tests""" from unittest import TestCase, makeSuite, TestSuite from protocols import * import protocols.twisted_support from twisted.python.components import Interface # Dummy interfaces and adapters used in tests class IA(Interface): pass class IB(IA): pass class IPure(Interface): # We use this for pickle/copy tests because the other protocols # imply various dynamically created interfaces, and so any object # registered with them won't be picklable pass from checks import InstanceImplementationChecks, makeClassTests, ProviderChecks from checks import makeInstanceTests, SimpleAdaptiveChecks class Picklable: # Pickling needs classes in top-level namespace pass class NewStyle(object): pass class BasicChecks(SimpleAdaptiveChecks, InstanceImplementationChecks): IA = IA IB = IB Interface = Interface IPure = IPure class InstanceChecks(ProviderChecks): IA = IA IB = IB Interface = Interface IPure = IPure TestClasses = makeClassTests(BasicChecks) TestClasses += makeInstanceTests(InstanceChecks,Picklable,NewStyle) class IB(protocols.Interface): advise(protocolExtends = [IA]) class BasicChecks(InstanceImplementationChecks): IA = IA IB = IB Interface = Interface IPure = IPure class InstanceChecks(ProviderChecks): IA = IA IB = IB Interface = Interface IPure = IPure TestClasses += makeClassTests(BasicChecks) TestClasses += makeInstanceTests(InstanceChecks,Picklable,NewStyle) def test_suite(): return TestSuite([makeSuite(t,'check') for t in TestClasses]) PK86y protocols/tests/test_twisted.pyc; Ec@sdZdklZlZlZdkTdkZdklZdefdYZ de fdYZ d efd YZ d k l Z lZlZd k lZlZd fdYZdefdYZdee fdYZdefdYZeeZeeeee7ZdeifdYZ de fdYZdefdYZeee7Zeeeee7ZdZdS(sTwisted Interface tests(sTestCases makeSuites TestSuite(s*N(s InterfacesIAcBstZRS(N(s__name__s __module__(((sAbuild/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_twisted.pysIA ssIBcBstZRS(N(s__name__s __module__(((sAbuild/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_twisted.pysIB ssIPurecBstZRS(N(s__name__s __module__(((sAbuild/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_twisted.pysIPures(sInstanceImplementationCheckssmakeClassTestssProviderChecks(smakeInstanceTestssSimpleAdaptiveCheckss PicklablecBstZRS(N(s__name__s __module__(((sAbuild/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_twisted.pys PicklablessNewStylecBstZRS(N(s__name__s __module__(((sAbuild/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_twisted.pysNewStyless BasicCheckscBs tZeZeZeZeZRS(N(s__name__s __module__sIAsIBs InterfacesIPure(((sAbuild/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_twisted.pys BasicChecksssInstanceCheckscBs tZeZeZeZeZRS(N(s__name__s __module__sIAsIBs InterfacesIPure(((sAbuild/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_twisted.pysInstanceChecks$scBstZedegRS(NsprotocolExtends(s__name__s __module__sadvisesIA(((sAbuild/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_twisted.pysIB-scCs8tgi}tD]}|t|dq~SdS(Nscheck(s TestSuitesappends_[1]s TestClassessts makeSuite(s_[1]st((sAbuild/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_twisted.pys test_suite?s(s__doc__sunittestsTestCases makeSuites TestSuites protocolssprotocols.twisted_supportstwisted.python.componentss InterfacesIAsIBsIPurescheckssInstanceImplementationCheckssmakeClassTestssProviderCheckssmakeInstanceTestssSimpleAdaptiveCheckss PicklablesobjectsNewStyles BasicCheckssInstanceCheckss TestClassess test_suite(s Picklables TestSuitesSimpleAdaptiveCheckssInstanceImplementationCheckssmakeClassTestssIPures makeSuitesTestCases InterfacesProviderCheckss TestClassess BasicCheckssInstanceCheckssmakeInstanceTestssIAsNewStylesIBs test_suites protocols((sAbuild/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_twisted.pys?s*   PKmy6Xprotocols/tests/test_zope.py"""Zope Interface tests""" from unittest import TestCase, makeSuite, TestSuite from protocols import * import protocols.zope_support from zope.interface import Interface # Dummy interfaces and adapters used in tests class IA(Interface): pass class IB(IA): pass class IPure(Interface): # We use this for pickle/copy tests because the other protocols # imply various dynamically created interfaces, and so any object # registered with them won't be picklable pass class Picklable: # Pickling needs classes in top-level namespace pass class NewStyle(object): pass from checks import ImplementationChecks, makeClassTests, makeInstanceTests from checks import ProviderChecks, BasicClassProvidesChecks from checks import makeMetaClassProvidesTests, AdaptiveChecks class BasicChecks(AdaptiveChecks, ImplementationChecks): IA = IA IB = IB Interface = Interface IPure = IPure class InstanceChecks(AdaptiveChecks, ProviderChecks): IA = IA IB = IB Interface = Interface IPure = IPure class ClassChecks(BasicClassProvidesChecks, ProviderChecks): IA = IA IB = IB Interface = Interface IPure = IPure TestClasses = makeClassTests(BasicChecks) TestClasses += makeMetaClassProvidesTests(ClassChecks) TestClasses += makeInstanceTests(InstanceChecks,Picklable,NewStyle) class IB(protocols.Interface): advise(protocolExtends = [IA]) class BasicChecks2(AdaptiveChecks, ImplementationChecks): IA = IA IB = IB Interface = Interface IPure = IPure class InstanceChecks2(AdaptiveChecks, ProviderChecks): IA = IA IB = IB Interface = Interface IPure = IPure class ClassChecks2(AdaptiveChecks, BasicClassProvidesChecks, ProviderChecks): IA = IA IB = IB Interface = Interface IPure = IPure TestClasses += makeClassTests(BasicChecks2) TestClasses += makeMetaClassProvidesTests(ClassChecks2) TestClasses += makeInstanceTests(InstanceChecks2,Picklable,NewStyle) def test_suite(): return TestSuite([makeSuite(t,'check') for t in TestClasses]) PK86}QQprotocols/tests/test_zope.pyc; ~ *Fc@s dZdklZlZlZdkTdkZdklZdefdYZ de fdYZ d efd YZ d fd YZ d e fdYZdklZlZlZdklZlZdklZlZdeefdYZdeefdYZdeefdYZeeZeee7Zeeee e7ZdeifdYZ deefdYZdeefdYZdeeefdYZeee7Zeee7Zeeee e7ZdZdS( sZope Interface tests(sTestCases makeSuites TestSuite(s*N(s InterfacesIAcBstZRS(N(s__name__s __module__(((s>build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_zope.pysIA ssIBcBstZRS(N(s__name__s __module__(((s>build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_zope.pysIB ssIPurecBstZRS(N(s__name__s __module__(((s>build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_zope.pysIPure ss PicklablecBstZRS(N(s__name__s __module__(((s>build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_zope.pys PicklablessNewStylecBstZRS(N(s__name__s __module__(((s>build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_zope.pysNewStyles(sImplementationCheckssmakeClassTestssmakeInstanceTests(sProviderCheckssBasicClassProvidesChecks(smakeMetaClassProvidesTestssAdaptiveCheckss BasicCheckscBs tZeZeZeZeZRS(N(s__name__s __module__sIAsIBs InterfacesIPure(((s>build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_zope.pys BasicChecksssInstanceCheckscBs tZeZeZeZeZRS(N(s__name__s __module__sIAsIBs InterfacesIPure(((s>build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_zope.pysInstanceChecks$ss ClassCheckscBs tZeZeZeZeZRS(N(s__name__s __module__sIAsIBs InterfacesIPure(((s>build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_zope.pys ClassChecks*scBstZedegRS(NsprotocolExtends(s__name__s __module__sadvisesIA(((s>build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_zope.pysIB4ss BasicChecks2cBs tZeZeZeZeZRS(N(s__name__s __module__sIAsIBs InterfacesIPure(((s>build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_zope.pys BasicChecks27ssInstanceChecks2cBs tZeZeZeZeZRS(N(s__name__s __module__sIAsIBs InterfacesIPure(((s>build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_zope.pysInstanceChecks2=ss ClassChecks2cBs tZeZeZeZeZRS(N(s__name__s __module__sIAsIBs InterfacesIPure(((s>build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_zope.pys ClassChecks2CscCs8tgi}tD]}|t|dq~SdS(Nscheck(s TestSuitesappends_[1]s TestClassessts makeSuite(s_[1]st((s>build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_zope.pys test_suiteMs(s__doc__sunittestsTestCases makeSuites TestSuites protocolssprotocols.zope_supportszope.interfaces InterfacesIAsIBsIPures PicklablesobjectsNewStylescheckssImplementationCheckssmakeClassTestssmakeInstanceTestssProviderCheckssBasicClassProvidesCheckssmakeMetaClassProvidesTestssAdaptiveCheckss BasicCheckssInstanceCheckss ClassCheckss TestClassess BasicChecks2sInstanceChecks2s ClassChecks2s test_suite(s TestClassessmakeInstanceTestss TestSuites ClassChecks2sTestCases protocolss InterfacesAdaptiveCheckss BasicCheckssInstanceCheckss makeSuitesmakeClassTestssIPuresIAsIBsmakeMetaClassProvidesTestss Picklables BasicChecks2sBasicClassProvidesCheckssImplementationCheckssProviderCheckss test_suitesInstanceChecks2s ClassCheckssNewStyle((s>build/bdist.darwin-8.9.1-i386/egg/protocols/tests/test_zope.pys?s4   PK76^RI))EGG-INFO/PKG-INFOPK76ɑXEGG-INFO/SOURCES.txtPK762EGG-INFO/dependency_links.txtPK863ntEGG-INFO/native_libs.txtPK76. EGG-INFO/requires.txtPK76; _EGG-INFO/top_level.txtPK952EGG-INFO/zip-safePK˃95d)yyprotocols/__init__.pyPK86LkUEEyprotocols/__init__.pycPK86" protocols/_speedups.pyPK86i<<*protocols/_speedups.pycPK8666protocols/_speedups.soPK˃95-\OOGprotocols/adapters.pyPK86jR\\protocols/adapters.pycPKOk6|gss{protocols/advice.pyPK86mJj##wprotocols/advice.pycPKOk6%$zcKprotocols/api.pyPK86v_i&&\protocols/api.pycPK˃95 Kprotocols/classic.pyPK86IȦ protocols/classic.pycPK˃95810protocols/generate.pyPK86U{qh&h&#Fprotocols/generate.pycPK˃95)//lprotocols/interfaces.pyPK86n޿LLprotocols/interfaces.pycPK˃95l)[[protocols/twisted_support.pyPK86C+?protocols/twisted_support.pycPKmy6.w ]protocols/zope_support.pyPK86]{protocols/zope_support.pycPKmy6 "tt3protocols/tests/__init__.pyPK86lZPN=N=mRprotocols/tests/__init__.pycPKmy6dov1v1protocols/tests/checks.pyPK86Prrprotocols/tests/checks.pycPKOk6fv 4protocols/tests/doctest.pyPK86MU { {protocols/tests/doctest.pycPKOk6<#5protocols/tests/test_advice.pyPK86y>protocols/tests/test_advice.pycPKʃ95ԥ$$%^protocols/tests/test_classes.pyPK86& cprotocols/tests/test_classes.pycPKʃ95" Rnprotocols/tests/test_direct.pyPK86?*B##\|protocols/tests/test_direct.pycPKʃ95CSSprotocols/tests/test_twisted.pyPK86y protocols/tests/test_twisted.pycPKmy6Xprotocols/tests/test_zope.pyPK86}QQ^protocols/tests/test_zope.pycPK,,