ÿØÿà JFIF    ÿÛ „  ( %"1!%)+...383,7(-.+  -+++--++++---+-+-----+---------------+---+-++7-----ÿÀ  ß â" ÿÄ     ÿÄ H    !1AQaq"‘¡2B±ÁÑð#R“Ò Tbr‚²á3csƒ’ÂñDS¢³$CÿÄ   ÿÄ %  !1AQa"23‘ÿÚ   ? ôÿ ¨pŸªáÿ —åYõõ\?àÒü©ŠÄï¨pŸªáÿ —åYõõ\?àÓü©ŠÄá 0Ÿªáÿ Ÿå[úƒ ú®ði~TÁbqÐ8OÕpÿ ƒOò¤Oè`–RÂáœá™êi€ßÉ< FtŸI“öÌ8úDf´°å}“¾œ6  öFá°y¥jñÇh†ˆ¢ã/ÃÐ:ªcÈ "Y¡ðÑl>ÿ ”ÏËte:qž\oäŠe÷󲍷˜HT4&ÿ ÓÐü6ö®¿øþßèô Ÿ•7Ñi’•j|“ñì>b…þS?*Óôÿ ÓÐü*h¥£ír¶ü UãS炟[AÐaè[ûª•õ&õj?†Éö+EzP—WeÒírJFt ‘BŒ†Ï‡%#tE Øz ¥OÛ«!1›üä±Í™%ºÍãö]°î(–:@<‹ŒÊö×òÆt¦ãº+‡¦%ÌÁ²h´OƒJŒtMÜ>ÀÜÊw3Y´•牋4ǍýʏTì>œú=Íwhyë,¾Ôò×õ¿ßÊa»«þˆѪQ|%6ž™A õ%:øj<>É—ÿ Å_ˆCbõ¥š±ý¯Ýƒï…¶|RëócÍf溪“t.СøTÿ *Ä¿-{†çàczůŽ_–^XþŒ±miB[X±d 1,é”zEù»& î9gœf™9Ð'.;—™i}!ôšåîqêÛ٤ёý£½ÆA–àôe"A$˝Úsäÿ ÷Û #°xŸëí(l »ý3—¥5m! rt`†0~'j2(]S¦¦kv,ÚÇ l¦øJA£Šƒ J3E8ÙiŽ:cÉžúeZ°€¯\®kÖ(79«Ž:¯X”¾³Š&¡* ….‰Ž(ÜíŸ2¥ª‡×Hi²TF¤ò[¨íÈRëÉ䢍mgÑ.Ÿ<öäS0í„ǹÁU´f#Vß;Õ–…P@3ío<ä-±»Ž.L|kªÀê›fÂ6@»eu‚|ÓaÞÆŸ…¨ááå>åŠ?cKü6ùTÍÆ”†sĤÚ;H2RÚ†õ\Ö·Ÿn'¾ ñ#ºI¤Å´%çÁ­‚â7›‹qT3Iï¨ÖÚ5I7Ë!ÅOóŸ¶øÝñØôת¦$Tcö‘[«Ö³šÒ';Aþ ¸èíg A2Z"i¸vdÄ÷.iõ®§)¿]¤À†–‡É&ä{V¶iŽ”.Ó×Õÿ û?h¬Mt–íª[ÿ Ñÿ ÌV(í}=ibÔ¡›¥¢±b Lô¥‡piη_Z<‡z§èŒ)iÖwiÇ 2hÙ3·=’d÷8éŽ1¦¸c¤µ€7›7Ø ð\á)} ¹fËí›pAÃL%âc2 í§æQz¿;T8sæ°qø)QFMð‰XŒÂ±N¢aF¨…8¯!U  Z©RÊ ÖPVÄÀÍin™Ì-GˆªÅËŠ›•zË}º±ŽÍFò¹}Uw×#ä5B¤{î}Ð<ÙD é©¤&‡ïDbàÁôMÁ." ¤‡ú*õ'VŽ|¼´Úgllº¼klz[Æüï÷Aób‡Eÿ dÑ»Xx9ÃÜ£ÁT/`¼¸vI±Ýµ·Ë‚“G³þ*Ÿû´r|*}<¨îºœ @¦mÄ’M¹”.œ«Y–|6ÏU¤jç¥ÕÞqO ˜kDÆÁ¨5ÿ š;ÐЦ¦€GÙk \ –Þ=â¼=SͧµªS°ÚÍpÜãQűÀõ¬?ÃÁ1Ñ•õZà?hóœ€ L¦l{Y*K˜Ù›zc˜–ˆâ ø+¾ ­-Ök¥%ùEÜA'}ˆ><ÊIè“bpÍ/qÞâvoX€w,\úªò6Z[XdÒæ­@Ö—€$òJí#é>'°Ú ôª˜<)4ryÙ£|óAÅn5žêŸyÒäMÝ2{"}‰–¤l÷ûWX\l¾Á¸góÉOÔ /óñB¤f¸çñ[.P˜ZsÊË*ßT܈§QN¢’¡¨§V¼(Üù*eÕ“”5T¨‹Âê¥FŒã½Dü[8'Ò¥a…Ú¶k7a *•›¼'Ò·\8¨ª\@\õ¢¦íq+DÙrmÎ…_ªæ»ŠÓœ¡¯’Ré9MÅ×D™lælffc+ŒÑ,ý™ÿ ¯þǤ=Å’Á7µ÷ÚÛ/“Ü€ñýã¼àí¾ÕÑ+ƒ,uµMâÀÄbm:ÒÎPæ{˜Gz[ƒ¯«® KHà`ߨŠéí¯P8Aq.C‰ à€kòpj´kN¶qô€…Õ,ÜNŠª-­{Zö’æû44‰sŽè‰îVíRœÕm" 6?³D9¡ÇTíÅꋇ`4«¸ÝÁô ï’ýorqКÇZ«x4Žâéþuïf¹µö[P ,Q£éaX±`PÉÍZ ¸äYúg üAx ’6Lê‚xÝÓ*äQ  Ï’¨hÍ =²,6ï#rÃ<¯–£»ƒ‹,–ê•€ aÛsñ'%Æ"®ÛüìBᝠHÚ3ß°©$“XnœÖ’î2ËTeûìxîß ¦å¿çÉ ðK§þ{‘t‚Ϋ¬jéîZ[ ”š7L¥4VÚCE×]m¤Øy”ä4-dz£œ§¸x.*ãÊÊ b÷•h:©‡¦s`BTÁRû¾g⻩‹jø sF¢àJøFl‘È•Xᓁà~*j¯ +(ÚÕ6-£¯÷GŠØy‚<Ç’.F‹Hœw(+)ÜÜâÈzÄäT§FߘãÏ;DmVœ3Àu@mÚüXÝü•3B¨òÌÁÛ<·ÃÜ z,Ì@õÅ·d2]ü8s÷IôÞ¯^Ç9¢u„~ëAŸï4«M? K]­ÅàPl@s_ p:°¬ZR”´›JC[CS.h‹ƒïËœ«Æ]–÷ó‚wR×k7X‰k›‘´ù¦=¡«‰¨¨Â')—71ó’c‡Ðúµ `é.{§p¹ój\Ž{1h{o±Ý=áUÊïGÖŒõ–-BÄm+AZX¶¡ ïHðæ¥JmÙ;…䡟ˆ¦ ° äšiÉg«$üMk5¤L“’çÊvïâï ,=f“"íἊ5ô¬x6{ɏžID0e¸vçmi'︧ºð9$ò¹÷*£’9ÿ ²TÔ…×>JV¥}Œ}$p[bÔ®*[jzS*8 ”·T›Í–ñUîƒwo$áè=LT™ç—~ô·¤ÈÚ$榍q‰„+´kFm)ž‹©i–ËqÞŠ‰à¶ü( ‚•§ •°ò·‡#5ª•µÊ﯅¡X¨šÁ*F#TXJÊ ušJVÍ&=iÄs1‚3•'fý§5Ñ<=[íÞ­ PÚ;ѱÌ_~Ä££8rÞ ²w;’hDT°>ÈG¬8Á²ÚzŽ®ò®qZcqJêäÞ-ö[ܘbň±çb“ж31²n×iƒðÕ;1¶þÉ ªX‰,ßqÏ$>•î íZ¥Z 1{ç൵+ƒÕµ¥°T$§K]á»Ûï*·¤tMI’ÂZbŽÕiÒ˜}bÓ0£ª5›¨ [5Ž^ÝœWøÂÝh° ¢OWun£¤5 a2Z.G2³YL]jåtì”ä ÁÓ‘%"©<Ôúʰsº UZvä‡ÄiÆÒM .÷V·™ø#kèýiíÌ–ª)µT[)BˆõÑ xB¾B€ÖT¨.¥~ð@VĶr#¸ü*åZNDŽH;âi ],©£öØpù(šºãö¼T.uCê•4@ÿ GÕÛ)Cx›®0ø#:ÏðFÒbR\(€€Ä®fã4Þ‰Fä¯HXƒÅ,†öEÑÔÜ]Öv²?tLÃvBY£ú6Êu5ÅAQ³1‘’¬x–HŒÐ‡ ^ ¸KwJôÖŽ5×CÚ¨vÜ«/B0$×k°=ðbÇ(Ï)w±A†Á† 11Í=èQšµ626ŒÜ/`G«µ<}—-Ö7KEHÈÉðóȤmݱû±·ø«Snmá=“䫚mݱŸ¡¶~ó·“äUóJæúòB|E LêŽy´jDÔ$G¢þÐñ7óR8ýÒ…Ç› WVe#·Ÿ p·Fx~•ݤF÷0Èÿ K¯æS<6’¡WШ; ´ÿ ¥Êø\Òuî†åÝ–VNœkÒ7oòX¨Á­Ø÷FÎÑä±g÷ÿ M~Çî=p,X´ ÝÌÚÅ‹’ÃjÖ.ØöÏñ qïQ¤ÓZE†° =6·]܈ s¸>v•Ž^Ý\wq9r‰Î\¸¡kURÒ$­*‹Nq?Þª*!sŠÆ:TU_u±T+øX¡ ®¹¡,ÄâÃBTsÜ$Ø›4m椴zÜK]’’›Pƒ @€#â˜`é¹=I‡fiV•Ôî“nRm+µFPOhÍ0B£ €+¬5c v•:P'ÒyÎ ‰V~‚Ó†ÖuókDoh$å\*ö%Ю=£«…aȼ½÷Û.-½VŒŠ¼'lyî±1¬3ó#ÞE¿ÔS¤gV£m›=§\û"—WU¤ÚǼÿ ÂnÁGŒÃ ‚õN D³õNÚíŒÕ;HôyÄÈ©P¹Ä{:?R‘Ô¨âF÷ø£bÅó® JS|‚R÷ivýáâ€Æé¡è³´IئÑT!§˜•ت‚¬â@q€wnïCWÄ@JU€ê¯m6]Ï:£âx'+ÒðXvÓ¦Úm=–´7œ $ì“B£~p%ÕŸUþ« N@¼üï~w˜ñø5®—'Ôe»¤5ã//€ž~‰Tþ›Å7•#¤× Íö pÄ$ùeåì*«ÓŠEØWEÈsßg ¦ûvžSsLpºÊW–âµEWöˬH; ™!CYõZ ÃÄf æ#1W. \uWâ\,\Çf j’<qTbên›Î[vxx£ë 'ö¨1›˜ÀM¼Pÿ H)ƒêêŒA7s,|F“ 꺸k³9Ìö*ç®;Ö!Ö$Eiž•¹ÒÚ†ýóéÝû¾ÕS®ó$’NÝäŸz¤5r¦ãÄÃD÷Üø!°ø‡Ô&@m™Ì^Ãä­d q5Lnÿ N;.6½·N|#ä"1Nƒx“ã<3('&ñßt  ~ªu”1Tb㫨9ê–›–bìd$ߣ=#ÕãÒmU¯eí$EFù5ýYô櫨æì™Ç—±ssM]·á¿0ÕåJRÓªîiƒ+O58ÖñªŠÒx" \µâá¨i’¤i —Ö ” M+M¤ë9‚‰A¦°Qõ¾ßøK~¼Ã‘g…Ö´~÷Ï[3GUœÒ½#…kàÔ®Ò”‰³·dWV‰IP‰Ú8u¹”E ÖqLj¾êÕCBš{A^Âß;–¨`¯¬ìö ˼ ×tìø.tƐm*n¨y4o&Àx¥n¦×î‡aupáÛj8¿m›è¶ã!o½;ß0y^ý×^EÑ¿ÒjzŒ­)vÚÑnÄL …^ªô× ‡—‚3k Îý­hï]içå–îÏ*÷ñþ»Ô CÒjøjÍznˆ´ ¹#b'Fô‹ ‰v¥'’à'T´ƒHýÍ%M‰ ƒ&ÆÇŒï1 ‘ –Þ ‰i¬s žR-Ÿ kЬá¬7:þ 0ŒÅÒÕ/aÙ¬ÃÝ#Úøœ ©aiVc‰. ¹¦ãµ” ›Yg¦›ÆÎýº°f³7ƒhá·¸­}&D9¡ÂsÉÙÞèŠõØàC™¨ñbFC|´Ü(ŸƒÚÒ-%»'a Ì¿)ËÇn¿úÿ ÞŽX…4ÊÅH^ôΑí@ù¹Eh¶“L8Çjù ¼ÎåVªóR©Ï5uà V4lZß®=€xÖŸ–ÑÈ ÷”¨°¾__yM1tÉ?uÆþIkÄgæ@þ[¢†°XÃJ£j·:nkÅ¢u ‘}âGzö­/IµèЬ¼48q¦F°ŽR¼=ûì{´¯RýicS ÕÛ íNtÍÙï£,w4rêì®»~x(©Uñ§#Ñ&œÕ¤>ÎåÍÓ9’Ö{9eV­[Öjâ²ãu]˜å2›qÑšÕJç0€sÄ|Êëè0튔bÁ>“{×_F`Ø©ºê:µä,v¤ðfc1±"«ÔÍän1#=· Âøv~H½ÐßA¾¿Ü€Óš]Õ; I¾÷ç‚Qi†î¹9ywÔKG˜áñ zQY—§ÃÕZ07§X‚ Áh;ÁM)iÌCH-¯T‘ë|A0{Ò½LÚ–TâÖkÜ’dÀ“rmm»”جPF³ÖcbE§T€ÒxKºû’Ó®7±²(\4ŽÃ¸Uu@j™yĵ;³µ!Á¢b.W¤=mõ´êµK k ¸K^ÜÛ#p*Ü14qkZç5ïë †°5Ï%ÍÛ<Õ¤×Ô¥ê†C Õ´¼ú$ƒÖ“”]Ù¬qÞÚ[4©ý!ûÏ—Áb쳐XµA¬â~`›Çr¸8ìùÝ䫦<>ä÷«?xs´ÇÑ /á;¹øüÊÈÙà{"@Žïzâ¬[âß‚ U_<ÇŸ½4èN˜ú61®qŠu ¦þF£»äJ_ˆÙÎ~ ÞAã–݄ϗrŠD;xTž‘ô`É«…suãO`?³à™ô Lý#Íc5öoæØ‚y´´÷«ZR§<&JÇ+éâô´€i!Àˆ0æAoàðLèÖ-2ŸõW.’t^–(KÁmHµV@xÜÇy®Ñø­â^:Ú3w· 7½¹°ñ¸â¹®:',«Mœ—n­Á+Ãbš LÈ‘ÄnRÓÅœ%¦²‰¨ùQ:¤f‚ "PÕtô¸…cæl…&˜Ú˜Ôkv‹ž+vŠ,=¢v­6—Xy*¥t£«<™:“aîϲ=¦6rO]XI¿Œ÷¤zÚ­›¶ 6÷”w\d ü~v®ˆÌk«^m<ÿ ¢‰Õ\)ùºŽ;… lîÙÅEŠ®cѾ@vnMÏ,¼“ñ•ŽBxðÃzãÇç%3ˆ"}Ù•Åî> BÉú;Ò]V+P˜F_´ßé> Øše|ï‡ÄOmFæÇ ãqÞ$/xÐx­z`ï9"œÜij‚!7.\Td…9M‡•iŽ‹¾‘50ÞŽn¥ß4ÉôO ¹*í^QêËÜÇÌ8=ާs‰'ÂëÙ«á%Pú[O †ÅP¯Vsް.‰,kc¶ ¬A9n˜XÎ-ÞšN["¹QÕ‰ƒMýÁߺXJæÍaLj¾×Ãmã¾ãÚ uñÒþåQô¦¥ /ÄUx:‚ÍÜ’ Đ©ØÝ3V¨‰ÕnÐ6ó*óúK­«…c ¯U òhsý­jóÔj#,ímŒRµ«lbïUTŒÑ8†Ä0œÏr`ð¡¬É Ї ë"À² ™ 6¥ f¶ ¢ÚoܱԷ-<Àî)†a¶ž'Ú»¨TXqØæ¶÷YÄHy˜9ÈIW­YÀuMFë ºÏ’AqÌ4·/Ú †ô'i$øä­=Ä Ý|öK×40è|È6p‘0§)o¥ctî§H+CA-“ xØ|ÐXАç l8íºð3Ø:³¤¬KX¯UÿÙ # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for twisted.python.modules, abstract access to imported or importable objects. """ from __future__ import division, absolute_import import sys import itertools import compileall import zipfile import twisted from twisted.python import modules from twisted.python.compat import networkString from twisted.python.filepath import FilePath from twisted.python.reflect import namedAny from twisted.trial.unittest import TestCase from twisted.python.test.modules_helpers import TwistedModulesMixin from twisted.python.test.test_zippath import zipit class TwistedModulesTestCase(TwistedModulesMixin, TestCase): """ Base class for L{modules} test cases. """ def findByIteration(self, modname, where=modules, importPackages=False): """ You don't ever actually want to do this, so it's not in the public API, but sometimes we want to compare the result of an iterative call with a lookup call and make sure they're the same for test purposes. """ for modinfo in where.walkModules(importPackages=importPackages): if modinfo.name == modname: return modinfo self.fail("Unable to find module %r through iteration." % (modname,)) class BasicTests(TwistedModulesTestCase): def test_namespacedPackages(self): """ Duplicate packages are not yielded when iterating over namespace packages. """ # Force pkgutil to be loaded already, since the probe package being # created depends on it, and the replaceSysPath call below will make # pretty much everything unimportable. __import__('pkgutil') namespaceBoilerplate = ( b'import pkgutil; ' b'__path__ = pkgutil.extend_path(__path__, __name__)') # Create two temporary directories with packages: # # entry: # test_package/ # __init__.py # nested_package/ # __init__.py # module.py # # anotherEntry: # test_package/ # __init__.py # nested_package/ # __init__.py # module2.py # # test_package and test_package.nested_package are namespace packages, # and when both of these are in sys.path, test_package.nested_package # should become a virtual package containing both "module" and # "module2" entry = self.pathEntryWithOnePackage() testPackagePath = entry.child('test_package') testPackagePath.child('__init__.py').setContent(namespaceBoilerplate) nestedEntry = testPackagePath.child('nested_package') nestedEntry.makedirs() nestedEntry.child('__init__.py').setContent(namespaceBoilerplate) nestedEntry.child('module.py').setContent(b'') anotherEntry = self.pathEntryWithOnePackage() anotherPackagePath = anotherEntry.child('test_package') anotherPackagePath.child('__init__.py').setContent(namespaceBoilerplate) anotherNestedEntry = anotherPackagePath.child('nested_package') anotherNestedEntry.makedirs() anotherNestedEntry.child('__init__.py').setContent(namespaceBoilerplate) anotherNestedEntry.child('module2.py').setContent(b'') self.replaceSysPath([entry.path, anotherEntry.path]) module = modules.getModule('test_package') # We have to use importPackages=True in order to resolve the namespace # packages, so we remove the imported packages from sys.modules after # walking try: walkedNames = [ mod.name for mod in module.walkModules(importPackages=True)] finally: for module in list(sys.modules.keys()): if module.startswith('test_package'): del sys.modules[module] expected = [ 'test_package', 'test_package.nested_package', 'test_package.nested_package.module', 'test_package.nested_package.module2', ] self.assertEqual(walkedNames, expected) def test_unimportablePackageGetItem(self): """ If a package has been explicitly forbidden from importing by setting a L{None} key in sys.modules under its name, L{modules.PythonPath.__getitem__} should still be able to retrieve an unloaded L{modules.PythonModule} for that package. """ shouldNotLoad = [] path = modules.PythonPath(sysPath=[self.pathEntryWithOnePackage().path], moduleLoader=shouldNotLoad.append, importerCache={}, sysPathHooks={}, moduleDict={'test_package': None}) self.assertEqual(shouldNotLoad, []) self.assertFalse(path['test_package'].isLoaded()) def test_unimportablePackageWalkModules(self): """ If a package has been explicitly forbidden from importing by setting a L{None} key in sys.modules under its name, L{modules.walkModules} should still be able to retrieve an unloaded L{modules.PythonModule} for that package. """ existentPath = self.pathEntryWithOnePackage() self.replaceSysPath([existentPath.path]) self.replaceSysModules({"test_package": None}) walked = list(modules.walkModules()) self.assertEqual([m.name for m in walked], ["test_package"]) self.assertFalse(walked[0].isLoaded()) def test_nonexistentPaths(self): """ Verify that L{modules.walkModules} ignores entries in sys.path which do not exist in the filesystem. """ existentPath = self.pathEntryWithOnePackage() nonexistentPath = FilePath(self.mktemp()) self.assertFalse(nonexistentPath.exists()) self.replaceSysPath([existentPath.path]) expected = [modules.getModule("test_package")] beforeModules = list(modules.walkModules()) sys.path.append(nonexistentPath.path) afterModules = list(modules.walkModules()) self.assertEqual(beforeModules, expected) self.assertEqual(afterModules, expected) def test_nonDirectoryPaths(self): """ Verify that L{modules.walkModules} ignores entries in sys.path which refer to regular files in the filesystem. """ existentPath = self.pathEntryWithOnePackage() nonDirectoryPath = FilePath(self.mktemp()) self.assertFalse(nonDirectoryPath.exists()) nonDirectoryPath.setContent(b"zip file or whatever\n") self.replaceSysPath([existentPath.path]) beforeModules = list(modules.walkModules()) sys.path.append(nonDirectoryPath.path) afterModules = list(modules.walkModules()) self.assertEqual(beforeModules, afterModules) def test_twistedShowsUp(self): """ Scrounge around in the top-level module namespace and make sure that Twisted shows up, and that the module thusly obtained is the same as the module that we find when we look for it explicitly by name. """ self.assertEqual(modules.getModule('twisted'), self.findByIteration("twisted")) def test_dottedNames(self): """ Verify that the walkModules APIs will give us back subpackages, not just subpackages. """ self.assertEqual( modules.getModule('twisted.python'), self.findByIteration("twisted.python", where=modules.getModule('twisted'))) def test_onlyTopModules(self): """ Verify that the iterModules API will only return top-level modules and packages, not submodules or subpackages. """ for module in modules.iterModules(): self.assertFalse( '.' in module.name, "no nested modules should be returned from iterModules: %r" % (module.filePath)) def test_loadPackagesAndModules(self): """ Verify that we can locate and load packages, modules, submodules, and subpackages. """ for n in ['os', 'twisted', 'twisted.python', 'twisted.python.reflect']: m = namedAny(n) self.failUnlessIdentical( modules.getModule(n).load(), m) self.failUnlessIdentical( self.findByIteration(n).load(), m) def test_pathEntriesOnPath(self): """ Verify that path entries discovered via module loading are, in fact, on sys.path somewhere. """ for n in ['os', 'twisted', 'twisted.python', 'twisted.python.reflect']: self.failUnlessIn( modules.getModule(n).pathEntry.filePath.path, sys.path) def test_alwaysPreferPy(self): """ Verify that .py files will always be preferred to .pyc files, regardless of directory listing order. """ mypath = FilePath(self.mktemp()) mypath.createDirectory() pp = modules.PythonPath(sysPath=[mypath.path]) originalSmartPath = pp._smartPath def _evilSmartPath(pathName): o = originalSmartPath(pathName) originalChildren = o.children def evilChildren(): # normally this order is random; let's make sure it always # comes up .pyc-first. x = list(originalChildren()) x.sort() x.reverse() return x o.children = evilChildren return o mypath.child("abcd.py").setContent(b'\n') compileall.compile_dir(mypath.path, quiet=True) # sanity check self.assertEqual(len(list(mypath.children())), 2) pp._smartPath = _evilSmartPath self.assertEqual(pp['abcd'].filePath, mypath.child('abcd.py')) def test_packageMissingPath(self): """ A package can delete its __path__ for some reasons, C{modules.PythonPath} should be able to deal with it. """ mypath = FilePath(self.mktemp()) mypath.createDirectory() pp = modules.PythonPath(sysPath=[mypath.path]) subpath = mypath.child("abcd") subpath.createDirectory() subpath.child("__init__.py").setContent(b'del __path__\n') sys.path.append(mypath.path) __import__("abcd") try: l = list(pp.walkModules()) self.assertEqual(len(l), 1) self.assertEqual(l[0].name, 'abcd') finally: del sys.modules['abcd'] sys.path.remove(mypath.path) class PathModificationTests(TwistedModulesTestCase): """ These tests share setup/cleanup behavior of creating a dummy package and stuffing some code in it. """ _serialnum = itertools.count() # used to generate serial numbers for # package names. def setUp(self): self.pathExtensionName = self.mktemp() self.pathExtension = FilePath(self.pathExtensionName) self.pathExtension.createDirectory() self.packageName = "pyspacetests%d" % (next(self._serialnum),) self.packagePath = self.pathExtension.child(self.packageName) self.packagePath.createDirectory() self.packagePath.child("__init__.py").setContent(b"") self.packagePath.child("a.py").setContent(b"") self.packagePath.child("b.py").setContent(b"") self.packagePath.child("c__init__.py").setContent(b"") self.pathSetUp = False def _setupSysPath(self): assert not self.pathSetUp self.pathSetUp = True sys.path.append(self.pathExtensionName) def _underUnderPathTest(self, doImport=True): moddir2 = self.mktemp() fpmd = FilePath(moddir2) fpmd.createDirectory() fpmd.child("foozle.py").setContent(b"x = 123\n") self.packagePath.child("__init__.py").setContent( networkString("__path__.append({0})\n".format(repr(moddir2)))) # Cut here self._setupSysPath() modinfo = modules.getModule(self.packageName) self.assertEqual( self.findByIteration(self.packageName+".foozle", modinfo, importPackages=doImport), modinfo['foozle']) self.assertEqual(modinfo['foozle'].load().x, 123) def test_underUnderPathAlreadyImported(self): """ Verify that iterModules will honor the __path__ of already-loaded packages. """ self._underUnderPathTest() def _listModules(self): pkginfo = modules.getModule(self.packageName) nfni = [modinfo.name.split(".")[-1] for modinfo in pkginfo.iterModules()] nfni.sort() self.assertEqual(nfni, ['a', 'b', 'c__init__']) def test_listingModules(self): """ Make sure the module list comes back as we expect from iterModules on a package, whether zipped or not. """ self._setupSysPath() self._listModules() def test_listingModulesAlreadyImported(self): """ Make sure the module list comes back as we expect from iterModules on a package, whether zipped or not, even if the package has already been imported. """ self._setupSysPath() namedAny(self.packageName) self._listModules() def tearDown(self): # Intentionally using 'assert' here, this is not a test assertion, this # is just an "oh fuck what is going ON" assertion. -glyph if self.pathSetUp: HORK = "path cleanup failed: don't be surprised if other tests break" assert sys.path.pop() is self.pathExtensionName, HORK+", 1" assert self.pathExtensionName not in sys.path, HORK+", 2" class RebindingTests(PathModificationTests): """ These tests verify that the default path interrogation API works properly even when sys.path has been rebound to a different object. """ def _setupSysPath(self): assert not self.pathSetUp self.pathSetUp = True self.savedSysPath = sys.path sys.path = sys.path[:] sys.path.append(self.pathExtensionName) def tearDown(self): """ Clean up sys.path by re-binding our original object. """ if self.pathSetUp: sys.path = self.savedSysPath class ZipPathModificationTests(PathModificationTests): def _setupSysPath(self): assert not self.pathSetUp zipit(self.pathExtensionName, self.pathExtensionName+'.zip') self.pathExtensionName += '.zip' assert zipfile.is_zipfile(self.pathExtensionName) PathModificationTests._setupSysPath(self) class PythonPathTests(TestCase): """ Tests for the class which provides the implementation for all of the public API of L{twisted.python.modules}, L{PythonPath}. """ def test_unhandledImporter(self): """ Make sure that the behavior when encountering an unknown importer type is not catastrophic failure. """ class SecretImporter(object): pass def hook(name): return SecretImporter() syspath = ['example/path'] sysmodules = {} syshooks = [hook] syscache = {} def sysloader(name): return None space = modules.PythonPath( syspath, sysmodules, syshooks, syscache, sysloader) entries = list(space.iterEntries()) self.assertEqual(len(entries), 1) self.assertRaises(KeyError, lambda: entries[0]['module']) def test_inconsistentImporterCache(self): """ If the path a module loaded with L{PythonPath.__getitem__} is not present in the path importer cache, a warning is emitted, but the L{PythonModule} is returned as usual. """ space = modules.PythonPath([], sys.modules, [], {}) thisModule = space[__name__] warnings = self.flushWarnings([self.test_inconsistentImporterCache]) self.assertEqual(warnings[0]['category'], UserWarning) self.assertEqual( warnings[0]['message'], FilePath(twisted.__file__).parent().dirname() + " (for module " + __name__ + ") not in path importer cache " "(PEP 302 violation - check your local configuration).") self.assertEqual(len(warnings), 1) self.assertEqual(thisModule.name, __name__) def test_containsModule(self): """ L{PythonPath} implements the C{in} operator so that when it is the right-hand argument and the name of a module which exists on that L{PythonPath} is the left-hand argument, the result is C{True}. """ thePath = modules.PythonPath() self.assertIn('os', thePath) def test_doesntContainModule(self): """ L{PythonPath} implements the C{in} operator so that when it is the right-hand argument and the name of a module which does not exist on that L{PythonPath} is the left-hand argument, the result is C{False}. """ thePath = modules.PythonPath() self.assertNotIn('bogusModule', thePath) __all__ = ["BasicTests", "PathModificationTests", "RebindingTests", "ZipPathModificationTests", "PythonPathTests"]