Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_application.py 33KB

1 year ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for L{twisted.application} and its interaction with
  5. L{twisted.persisted.sob}.
  6. """
  7. import copy
  8. import os
  9. import pickle
  10. from io import StringIO
  11. try:
  12. import asyncio
  13. except ImportError:
  14. asyncio = None # type: ignore[assignment]
  15. from unittest import skipIf
  16. from twisted.application import app, internet, reactors, service
  17. from twisted.application.internet import backoffPolicy
  18. from twisted.internet import defer, interfaces, protocol, reactor
  19. from twisted.persisted import sob
  20. from twisted.plugins import twisted_reactors
  21. from twisted.protocols import basic, wire
  22. from twisted.python import usage
  23. from twisted.python.runtime import platformType
  24. from twisted.python.test.modules_helpers import TwistedModulesMixin
  25. from twisted.test.proto_helpers import MemoryReactor
  26. from twisted.trial.unittest import SkipTest, TestCase
  27. class Dummy:
  28. processName = None
  29. class ServiceTests(TestCase):
  30. def testName(self):
  31. s = service.Service()
  32. s.setName("hello")
  33. self.assertEqual(s.name, "hello")
  34. def testParent(self):
  35. s = service.Service()
  36. p = service.MultiService()
  37. s.setServiceParent(p)
  38. self.assertEqual(list(p), [s])
  39. self.assertEqual(s.parent, p)
  40. def testApplicationAsParent(self):
  41. s = service.Service()
  42. p = service.Application("")
  43. s.setServiceParent(p)
  44. self.assertEqual(list(service.IServiceCollection(p)), [s])
  45. self.assertEqual(s.parent, service.IServiceCollection(p))
  46. def testNamedChild(self):
  47. s = service.Service()
  48. p = service.MultiService()
  49. s.setName("hello")
  50. s.setServiceParent(p)
  51. self.assertEqual(list(p), [s])
  52. self.assertEqual(s.parent, p)
  53. self.assertEqual(p.getServiceNamed("hello"), s)
  54. def testDoublyNamedChild(self):
  55. s = service.Service()
  56. p = service.MultiService()
  57. s.setName("hello")
  58. s.setServiceParent(p)
  59. self.assertRaises(RuntimeError, s.setName, "lala")
  60. def testDuplicateNamedChild(self):
  61. s = service.Service()
  62. p = service.MultiService()
  63. s.setName("hello")
  64. s.setServiceParent(p)
  65. s = service.Service()
  66. s.setName("hello")
  67. self.assertRaises(RuntimeError, s.setServiceParent, p)
  68. def testDisowning(self):
  69. s = service.Service()
  70. p = service.MultiService()
  71. s.setServiceParent(p)
  72. self.assertEqual(list(p), [s])
  73. self.assertEqual(s.parent, p)
  74. s.disownServiceParent()
  75. self.assertEqual(list(p), [])
  76. self.assertIsNone(s.parent)
  77. def testRunning(self):
  78. s = service.Service()
  79. self.assertFalse(s.running)
  80. s.startService()
  81. self.assertTrue(s.running)
  82. s.stopService()
  83. self.assertFalse(s.running)
  84. def testRunningChildren1(self):
  85. s = service.Service()
  86. p = service.MultiService()
  87. s.setServiceParent(p)
  88. self.assertFalse(s.running)
  89. self.assertFalse(p.running)
  90. p.startService()
  91. self.assertTrue(s.running)
  92. self.assertTrue(p.running)
  93. p.stopService()
  94. self.assertFalse(s.running)
  95. self.assertFalse(p.running)
  96. def testRunningChildren2(self):
  97. s = service.Service()
  98. def checkRunning():
  99. self.assertTrue(s.running)
  100. t = service.Service()
  101. t.stopService = checkRunning
  102. t.startService = checkRunning
  103. p = service.MultiService()
  104. s.setServiceParent(p)
  105. t.setServiceParent(p)
  106. p.startService()
  107. p.stopService()
  108. def testAddingIntoRunning(self):
  109. p = service.MultiService()
  110. p.startService()
  111. s = service.Service()
  112. self.assertFalse(s.running)
  113. s.setServiceParent(p)
  114. self.assertTrue(s.running)
  115. s.disownServiceParent()
  116. self.assertFalse(s.running)
  117. def testPrivileged(self):
  118. s = service.Service()
  119. def pss():
  120. s.privilegedStarted = 1
  121. s.privilegedStartService = pss
  122. s1 = service.Service()
  123. p = service.MultiService()
  124. s.setServiceParent(p)
  125. s1.setServiceParent(p)
  126. p.privilegedStartService()
  127. self.assertTrue(s.privilegedStarted)
  128. def testCopying(self):
  129. s = service.Service()
  130. s.startService()
  131. s1 = copy.copy(s)
  132. self.assertFalse(s1.running)
  133. self.assertTrue(s.running)
  134. if hasattr(os, "getuid"):
  135. curuid = os.getuid()
  136. curgid = os.getgid()
  137. else:
  138. curuid = curgid = 0
  139. class ProcessTests(TestCase):
  140. def testID(self):
  141. p = service.Process(5, 6)
  142. self.assertEqual(p.uid, 5)
  143. self.assertEqual(p.gid, 6)
  144. def testDefaults(self):
  145. p = service.Process(5)
  146. self.assertEqual(p.uid, 5)
  147. self.assertIsNone(p.gid)
  148. p = service.Process(gid=5)
  149. self.assertIsNone(p.uid)
  150. self.assertEqual(p.gid, 5)
  151. p = service.Process()
  152. self.assertIsNone(p.uid)
  153. self.assertIsNone(p.gid)
  154. def testProcessName(self):
  155. p = service.Process()
  156. self.assertIsNone(p.processName)
  157. p.processName = "hello"
  158. self.assertEqual(p.processName, "hello")
  159. class InterfacesTests(TestCase):
  160. def testService(self):
  161. self.assertTrue(service.IService.providedBy(service.Service()))
  162. def testMultiService(self):
  163. self.assertTrue(service.IService.providedBy(service.MultiService()))
  164. self.assertTrue(service.IServiceCollection.providedBy(service.MultiService()))
  165. def testProcess(self):
  166. self.assertTrue(service.IProcess.providedBy(service.Process()))
  167. class ApplicationTests(TestCase):
  168. def testConstructor(self):
  169. service.Application("hello")
  170. service.Application("hello", 5)
  171. service.Application("hello", 5, 6)
  172. def testProcessComponent(self):
  173. a = service.Application("hello")
  174. self.assertIsNone(service.IProcess(a).uid)
  175. self.assertIsNone(service.IProcess(a).gid)
  176. a = service.Application("hello", 5)
  177. self.assertEqual(service.IProcess(a).uid, 5)
  178. self.assertIsNone(service.IProcess(a).gid)
  179. a = service.Application("hello", 5, 6)
  180. self.assertEqual(service.IProcess(a).uid, 5)
  181. self.assertEqual(service.IProcess(a).gid, 6)
  182. def testServiceComponent(self):
  183. a = service.Application("hello")
  184. self.assertIs(service.IService(a), service.IServiceCollection(a))
  185. self.assertEqual(service.IService(a).name, "hello")
  186. self.assertIsNone(service.IService(a).parent)
  187. def testPersistableComponent(self):
  188. a = service.Application("hello")
  189. p = sob.IPersistable(a)
  190. self.assertEqual(p.style, "pickle")
  191. self.assertEqual(p.name, "hello")
  192. self.assertIs(p.original, a)
  193. class LoadingTests(TestCase):
  194. def test_simpleStoreAndLoad(self):
  195. a = service.Application("hello")
  196. p = sob.IPersistable(a)
  197. for style in "source pickle".split():
  198. p.setStyle(style)
  199. p.save()
  200. a1 = service.loadApplication("hello.ta" + style[0], style)
  201. self.assertEqual(service.IService(a1).name, "hello")
  202. with open("hello.tac", "w") as f:
  203. f.writelines(
  204. [
  205. "from twisted.application import service\n",
  206. "application = service.Application('hello')\n",
  207. ]
  208. )
  209. a1 = service.loadApplication("hello.tac", "python")
  210. self.assertEqual(service.IService(a1).name, "hello")
  211. class AppSupportTests(TestCase):
  212. def testPassphrase(self):
  213. self.assertIsNone(app.getPassphrase(0))
  214. def testLoadApplication(self):
  215. """
  216. Test loading an application file in different dump format.
  217. """
  218. a = service.Application("hello")
  219. baseconfig = {"file": None, "source": None, "python": None}
  220. for style in "source pickle".split():
  221. config = baseconfig.copy()
  222. config[{"pickle": "file"}.get(style, style)] = "helloapplication"
  223. sob.IPersistable(a).setStyle(style)
  224. sob.IPersistable(a).save(filename="helloapplication")
  225. a1 = app.getApplication(config, None)
  226. self.assertEqual(service.IService(a1).name, "hello")
  227. config = baseconfig.copy()
  228. config["python"] = "helloapplication"
  229. with open("helloapplication", "w") as f:
  230. f.writelines(
  231. [
  232. "from twisted.application import service\n",
  233. "application = service.Application('hello')\n",
  234. ]
  235. )
  236. a1 = app.getApplication(config, None)
  237. self.assertEqual(service.IService(a1).name, "hello")
  238. def test_convertStyle(self):
  239. appl = service.Application("lala")
  240. for instyle in "source pickle".split():
  241. for outstyle in "source pickle".split():
  242. sob.IPersistable(appl).setStyle(instyle)
  243. sob.IPersistable(appl).save(filename="converttest")
  244. app.convertStyle(
  245. "converttest", instyle, None, "converttest.out", outstyle, 0
  246. )
  247. appl2 = service.loadApplication("converttest.out", outstyle)
  248. self.assertEqual(service.IService(appl2).name, "lala")
  249. def test_startApplication(self):
  250. appl = service.Application("lala")
  251. app.startApplication(appl, 0)
  252. self.assertTrue(service.IService(appl).running)
  253. class Foo(basic.LineReceiver):
  254. def connectionMade(self):
  255. self.transport.write(b"lalala\r\n")
  256. def lineReceived(self, line):
  257. self.factory.line = line
  258. self.transport.loseConnection()
  259. def connectionLost(self, reason):
  260. self.factory.d.callback(self.factory.line)
  261. class DummyApp:
  262. processName = None
  263. def addService(self, service):
  264. self.services[service.name] = service
  265. def removeService(self, service):
  266. del self.services[service.name]
  267. class TimerTarget:
  268. def __init__(self):
  269. self.l = []
  270. def append(self, what):
  271. self.l.append(what)
  272. class TestEcho(wire.Echo):
  273. def connectionLost(self, reason):
  274. self.d.callback(True)
  275. class InternetTests(TestCase):
  276. def testTCP(self):
  277. s = service.MultiService()
  278. s.startService()
  279. factory = protocol.ServerFactory()
  280. factory.protocol = TestEcho
  281. TestEcho.d = defer.Deferred()
  282. t = internet.TCPServer(0, factory)
  283. t.setServiceParent(s)
  284. num = t._port.getHost().port
  285. factory = protocol.ClientFactory()
  286. factory.d = defer.Deferred()
  287. factory.protocol = Foo
  288. factory.line = None
  289. internet.TCPClient("127.0.0.1", num, factory).setServiceParent(s)
  290. factory.d.addCallback(self.assertEqual, b"lalala")
  291. factory.d.addCallback(lambda x: s.stopService())
  292. factory.d.addCallback(lambda x: TestEcho.d)
  293. return factory.d
  294. def test_UDP(self):
  295. """
  296. Test L{internet.UDPServer} with a random port: starting the service
  297. should give it valid port, and stopService should free it so that we
  298. can start a server on the same port again.
  299. """
  300. if not interfaces.IReactorUDP(reactor, None):
  301. raise SkipTest("This reactor does not support UDP sockets")
  302. p = protocol.DatagramProtocol()
  303. t = internet.UDPServer(0, p)
  304. t.startService()
  305. num = t._port.getHost().port
  306. self.assertNotEqual(num, 0)
  307. def onStop(ignored):
  308. t = internet.UDPServer(num, p)
  309. t.startService()
  310. return t.stopService()
  311. return defer.maybeDeferred(t.stopService).addCallback(onStop)
  312. def testPrivileged(self):
  313. factory = protocol.ServerFactory()
  314. factory.protocol = TestEcho
  315. TestEcho.d = defer.Deferred()
  316. t = internet.TCPServer(0, factory)
  317. t.privileged = 1
  318. t.privilegedStartService()
  319. num = t._port.getHost().port
  320. factory = protocol.ClientFactory()
  321. factory.d = defer.Deferred()
  322. factory.protocol = Foo
  323. factory.line = None
  324. c = internet.TCPClient("127.0.0.1", num, factory)
  325. c.startService()
  326. factory.d.addCallback(self.assertEqual, b"lalala")
  327. factory.d.addCallback(lambda x: c.stopService())
  328. factory.d.addCallback(lambda x: t.stopService())
  329. factory.d.addCallback(lambda x: TestEcho.d)
  330. return factory.d
  331. def testConnectionGettingRefused(self):
  332. factory = protocol.ServerFactory()
  333. factory.protocol = wire.Echo
  334. t = internet.TCPServer(0, factory)
  335. t.startService()
  336. num = t._port.getHost().port
  337. t.stopService()
  338. d = defer.Deferred()
  339. factory = protocol.ClientFactory()
  340. factory.clientConnectionFailed = lambda *args: d.callback(None)
  341. c = internet.TCPClient("127.0.0.1", num, factory)
  342. c.startService()
  343. return d
  344. @skipIf(
  345. not interfaces.IReactorUNIX(reactor, None),
  346. "This reactor does not support UNIX domain sockets",
  347. )
  348. def testUNIX(self):
  349. # FIXME: This test is far too dense. It needs comments.
  350. # -- spiv, 2004-11-07
  351. s = service.MultiService()
  352. s.startService()
  353. factory = protocol.ServerFactory()
  354. factory.protocol = TestEcho
  355. TestEcho.d = defer.Deferred()
  356. t = internet.UNIXServer("echo.skt", factory)
  357. t.setServiceParent(s)
  358. factory = protocol.ClientFactory()
  359. factory.protocol = Foo
  360. factory.d = defer.Deferred()
  361. factory.line = None
  362. internet.UNIXClient("echo.skt", factory).setServiceParent(s)
  363. factory.d.addCallback(self.assertEqual, b"lalala")
  364. factory.d.addCallback(lambda x: s.stopService())
  365. factory.d.addCallback(lambda x: TestEcho.d)
  366. factory.d.addCallback(self._cbTestUnix, factory, s)
  367. return factory.d
  368. def _cbTestUnix(self, ignored, factory, s):
  369. TestEcho.d = defer.Deferred()
  370. factory.line = None
  371. factory.d = defer.Deferred()
  372. s.startService()
  373. factory.d.addCallback(self.assertEqual, b"lalala")
  374. factory.d.addCallback(lambda x: s.stopService())
  375. factory.d.addCallback(lambda x: TestEcho.d)
  376. return factory.d
  377. @skipIf(
  378. not interfaces.IReactorUNIX(reactor, None),
  379. "This reactor does not support UNIX domain sockets",
  380. )
  381. def testVolatile(self):
  382. factory = protocol.ServerFactory()
  383. factory.protocol = wire.Echo
  384. t = internet.UNIXServer("echo.skt", factory)
  385. t.startService()
  386. self.failIfIdentical(t._port, None)
  387. t1 = copy.copy(t)
  388. self.assertIsNone(t1._port)
  389. t.stopService()
  390. self.assertIsNone(t._port)
  391. self.assertFalse(t.running)
  392. factory = protocol.ClientFactory()
  393. factory.protocol = wire.Echo
  394. t = internet.UNIXClient("echo.skt", factory)
  395. t.startService()
  396. self.failIfIdentical(t._connection, None)
  397. t1 = copy.copy(t)
  398. self.assertIsNone(t1._connection)
  399. t.stopService()
  400. self.assertIsNone(t._connection)
  401. self.assertFalse(t.running)
  402. @skipIf(
  403. not interfaces.IReactorUNIX(reactor, None),
  404. "This reactor does not support UNIX domain sockets",
  405. )
  406. def testStoppingServer(self):
  407. factory = protocol.ServerFactory()
  408. factory.protocol = wire.Echo
  409. t = internet.UNIXServer("echo.skt", factory)
  410. t.startService()
  411. t.stopService()
  412. self.assertFalse(t.running)
  413. factory = protocol.ClientFactory()
  414. d = defer.Deferred()
  415. factory.clientConnectionFailed = lambda *args: d.callback(None)
  416. reactor.connectUNIX("echo.skt", factory)
  417. return d
  418. def testPickledTimer(self):
  419. target = TimerTarget()
  420. t0 = internet.TimerService(1, target.append, "hello")
  421. t0.startService()
  422. s = pickle.dumps(t0)
  423. t0.stopService()
  424. t = pickle.loads(s)
  425. self.assertFalse(t.running)
  426. def testBrokenTimer(self):
  427. d = defer.Deferred()
  428. t = internet.TimerService(1, lambda: 1 // 0)
  429. oldFailed = t._failed
  430. def _failed(why):
  431. oldFailed(why)
  432. d.callback(None)
  433. t._failed = _failed
  434. t.startService()
  435. d.addCallback(lambda x: t.stopService)
  436. d.addCallback(
  437. lambda x: self.assertEqual(
  438. [ZeroDivisionError],
  439. [o.value.__class__ for o in self.flushLoggedErrors(ZeroDivisionError)],
  440. )
  441. )
  442. return d
  443. def test_everythingThere(self):
  444. """
  445. L{twisted.application.internet} dynamically defines a set of
  446. L{service.Service} subclasses that in general have corresponding
  447. reactor.listenXXX or reactor.connectXXX calls.
  448. """
  449. trans = ["TCP", "UNIX", "SSL", "UDP", "UNIXDatagram", "Multicast"]
  450. for tran in trans[:]:
  451. if not getattr(interfaces, "IReactor" + tran)(reactor, None):
  452. trans.remove(tran)
  453. for tran in trans:
  454. for side in ["Server", "Client"]:
  455. if tran == "Multicast" and side == "Client":
  456. continue
  457. if tran == "UDP" and side == "Client":
  458. continue
  459. self.assertTrue(hasattr(internet, tran + side))
  460. method = getattr(internet, tran + side).method
  461. prefix = {"Server": "listen", "Client": "connect"}[side]
  462. self.assertTrue(
  463. hasattr(reactor, prefix + method)
  464. or (prefix == "connect" and method == "UDP")
  465. )
  466. o = getattr(internet, tran + side)()
  467. self.assertEqual(service.IService(o), o)
  468. def test_importAll(self):
  469. """
  470. L{twisted.application.internet} dynamically defines L{service.Service}
  471. subclasses. This test ensures that the subclasses exposed by C{__all__}
  472. are valid attributes of the module.
  473. """
  474. for cls in internet.__all__:
  475. self.assertTrue(
  476. hasattr(internet, cls),
  477. f"{cls} not importable from twisted.application.internet",
  478. )
  479. def test_reactorParametrizationInServer(self):
  480. """
  481. L{internet._AbstractServer} supports a C{reactor} keyword argument
  482. that can be used to parametrize the reactor used to listen for
  483. connections.
  484. """
  485. reactor = MemoryReactor()
  486. factory = object()
  487. t = internet.TCPServer(1234, factory, reactor=reactor)
  488. t.startService()
  489. self.assertEqual(reactor.tcpServers.pop()[:2], (1234, factory))
  490. def test_reactorParametrizationInClient(self):
  491. """
  492. L{internet._AbstractClient} supports a C{reactor} keyword arguments
  493. that can be used to parametrize the reactor used to create new client
  494. connections.
  495. """
  496. reactor = MemoryReactor()
  497. factory = protocol.ClientFactory()
  498. t = internet.TCPClient("127.0.0.1", 1234, factory, reactor=reactor)
  499. t.startService()
  500. self.assertEqual(reactor.tcpClients.pop()[:3], ("127.0.0.1", 1234, factory))
  501. def test_reactorParametrizationInServerMultipleStart(self):
  502. """
  503. Like L{test_reactorParametrizationInServer}, but stop and restart the
  504. service and check that the given reactor is still used.
  505. """
  506. reactor = MemoryReactor()
  507. factory = protocol.Factory()
  508. t = internet.TCPServer(1234, factory, reactor=reactor)
  509. t.startService()
  510. self.assertEqual(reactor.tcpServers.pop()[:2], (1234, factory))
  511. t.stopService()
  512. t.startService()
  513. self.assertEqual(reactor.tcpServers.pop()[:2], (1234, factory))
  514. def test_reactorParametrizationInClientMultipleStart(self):
  515. """
  516. Like L{test_reactorParametrizationInClient}, but stop and restart the
  517. service and check that the given reactor is still used.
  518. """
  519. reactor = MemoryReactor()
  520. factory = protocol.ClientFactory()
  521. t = internet.TCPClient("127.0.0.1", 1234, factory, reactor=reactor)
  522. t.startService()
  523. self.assertEqual(reactor.tcpClients.pop()[:3], ("127.0.0.1", 1234, factory))
  524. t.stopService()
  525. t.startService()
  526. self.assertEqual(reactor.tcpClients.pop()[:3], ("127.0.0.1", 1234, factory))
  527. class TimerBasicTests(TestCase):
  528. def testTimerRuns(self):
  529. d = defer.Deferred()
  530. self.t = internet.TimerService(1, d.callback, "hello")
  531. self.t.startService()
  532. d.addCallback(self.assertEqual, "hello")
  533. d.addCallback(lambda x: self.t.stopService())
  534. d.addCallback(lambda x: self.assertFalse(self.t.running))
  535. return d
  536. def tearDown(self):
  537. return self.t.stopService()
  538. def testTimerRestart(self):
  539. # restart the same TimerService
  540. d1 = defer.Deferred()
  541. d2 = defer.Deferred()
  542. work = [(d2, "bar"), (d1, "foo")]
  543. def trigger():
  544. d, arg = work.pop()
  545. d.callback(arg)
  546. self.t = internet.TimerService(1, trigger)
  547. self.t.startService()
  548. def onFirstResult(result):
  549. self.assertEqual(result, "foo")
  550. return self.t.stopService()
  551. def onFirstStop(ignored):
  552. self.assertFalse(self.t.running)
  553. self.t.startService()
  554. return d2
  555. def onSecondResult(result):
  556. self.assertEqual(result, "bar")
  557. self.t.stopService()
  558. d1.addCallback(onFirstResult)
  559. d1.addCallback(onFirstStop)
  560. d1.addCallback(onSecondResult)
  561. return d1
  562. def testTimerLoops(self):
  563. l = []
  564. def trigger(data, number, d):
  565. l.append(data)
  566. if len(l) == number:
  567. d.callback(l)
  568. d = defer.Deferred()
  569. self.t = internet.TimerService(0.01, trigger, "hello", 10, d)
  570. self.t.startService()
  571. d.addCallback(self.assertEqual, ["hello"] * 10)
  572. d.addCallback(lambda x: self.t.stopService())
  573. return d
  574. class FakeReactor(reactors.Reactor):
  575. """
  576. A fake reactor with a hooked install method.
  577. """
  578. def __init__(self, install, *args, **kwargs):
  579. """
  580. @param install: any callable that will be used as install method.
  581. @type install: C{callable}
  582. """
  583. reactors.Reactor.__init__(self, *args, **kwargs)
  584. self.install = install
  585. class PluggableReactorTests(TwistedModulesMixin, TestCase):
  586. """
  587. Tests for the reactor discovery/inspection APIs.
  588. """
  589. def setUp(self):
  590. """
  591. Override the L{reactors.getPlugins} function, normally bound to
  592. L{twisted.plugin.getPlugins}, in order to control which
  593. L{IReactorInstaller} plugins are seen as available.
  594. C{self.pluginResults} can be customized and will be used as the
  595. result of calls to C{reactors.getPlugins}.
  596. """
  597. self.pluginCalls = []
  598. self.pluginResults = []
  599. self.originalFunction = reactors.getPlugins
  600. reactors.getPlugins = self._getPlugins
  601. def tearDown(self):
  602. """
  603. Restore the original L{reactors.getPlugins}.
  604. """
  605. reactors.getPlugins = self.originalFunction
  606. def _getPlugins(self, interface, package=None):
  607. """
  608. Stand-in for the real getPlugins method which records its arguments
  609. and returns a fixed result.
  610. """
  611. self.pluginCalls.append((interface, package))
  612. return list(self.pluginResults)
  613. def test_getPluginReactorTypes(self):
  614. """
  615. Test that reactor plugins are returned from L{getReactorTypes}
  616. """
  617. name = "fakereactortest"
  618. package = __name__ + ".fakereactor"
  619. description = "description"
  620. self.pluginResults = [reactors.Reactor(name, package, description)]
  621. reactorTypes = reactors.getReactorTypes()
  622. self.assertEqual(self.pluginCalls, [(reactors.IReactorInstaller, None)])
  623. for r in reactorTypes:
  624. if r.shortName == name:
  625. self.assertEqual(r.description, description)
  626. break
  627. else:
  628. self.fail("Reactor plugin not present in getReactorTypes() result")
  629. def test_reactorInstallation(self):
  630. """
  631. Test that L{reactors.Reactor.install} loads the correct module and
  632. calls its install attribute.
  633. """
  634. installed = []
  635. def install():
  636. installed.append(True)
  637. fakeReactor = FakeReactor(install, "fakereactortest", __name__, "described")
  638. modules = {"fakereactortest": fakeReactor}
  639. self.replaceSysModules(modules)
  640. installer = reactors.Reactor("fakereactor", "fakereactortest", "described")
  641. installer.install()
  642. self.assertEqual(installed, [True])
  643. def test_installReactor(self):
  644. """
  645. Test that the L{reactors.installReactor} function correctly installs
  646. the specified reactor.
  647. """
  648. installed = []
  649. def install():
  650. installed.append(True)
  651. name = "fakereactortest"
  652. package = __name__
  653. description = "description"
  654. self.pluginResults = [FakeReactor(install, name, package, description)]
  655. reactors.installReactor(name)
  656. self.assertEqual(installed, [True])
  657. def test_installReactorReturnsReactor(self):
  658. """
  659. Test that the L{reactors.installReactor} function correctly returns
  660. the installed reactor.
  661. """
  662. reactor = object()
  663. def install():
  664. from twisted import internet
  665. self.patch(internet, "reactor", reactor)
  666. name = "fakereactortest"
  667. package = __name__
  668. description = "description"
  669. self.pluginResults = [FakeReactor(install, name, package, description)]
  670. installed = reactors.installReactor(name)
  671. self.assertIs(installed, reactor)
  672. def test_installReactorMultiplePlugins(self):
  673. """
  674. Test that the L{reactors.installReactor} function correctly installs
  675. the specified reactor when there are multiple reactor plugins.
  676. """
  677. installed = []
  678. def install():
  679. installed.append(True)
  680. name = "fakereactortest"
  681. package = __name__
  682. description = "description"
  683. fakeReactor = FakeReactor(install, name, package, description)
  684. otherReactor = FakeReactor(lambda: None, "otherreactor", package, description)
  685. self.pluginResults = [otherReactor, fakeReactor]
  686. reactors.installReactor(name)
  687. self.assertEqual(installed, [True])
  688. def test_installNonExistentReactor(self):
  689. """
  690. Test that L{reactors.installReactor} raises L{reactors.NoSuchReactor}
  691. when asked to install a reactor which it cannot find.
  692. """
  693. self.pluginResults = []
  694. self.assertRaises(
  695. reactors.NoSuchReactor, reactors.installReactor, "somereactor"
  696. )
  697. def test_installNotAvailableReactor(self):
  698. """
  699. Test that L{reactors.installReactor} raises an exception when asked to
  700. install a reactor which doesn't work in this environment.
  701. """
  702. def install():
  703. raise ImportError("Missing foo bar")
  704. name = "fakereactortest"
  705. package = __name__
  706. description = "description"
  707. self.pluginResults = [FakeReactor(install, name, package, description)]
  708. self.assertRaises(ImportError, reactors.installReactor, name)
  709. def test_reactorSelectionMixin(self):
  710. """
  711. Test that the reactor selected is installed as soon as possible, ie
  712. when the option is parsed.
  713. """
  714. executed = []
  715. INSTALL_EVENT = "reactor installed"
  716. SUBCOMMAND_EVENT = "subcommands loaded"
  717. class ReactorSelectionOptions(usage.Options, app.ReactorSelectionMixin):
  718. @property
  719. def subCommands(self):
  720. executed.append(SUBCOMMAND_EVENT)
  721. return [("subcommand", None, lambda: self, "test subcommand")]
  722. def install():
  723. executed.append(INSTALL_EVENT)
  724. self.pluginResults = [
  725. FakeReactor(install, "fakereactortest", __name__, "described")
  726. ]
  727. options = ReactorSelectionOptions()
  728. options.parseOptions(["--reactor", "fakereactortest", "subcommand"])
  729. self.assertEqual(executed[0], INSTALL_EVENT)
  730. self.assertEqual(executed.count(INSTALL_EVENT), 1)
  731. self.assertEqual(options["reactor"], "fakereactortest")
  732. def test_reactorSelectionMixinNonExistent(self):
  733. """
  734. Test that the usage mixin exits when trying to use a non existent
  735. reactor (the name not matching to any reactor), giving an error
  736. message.
  737. """
  738. class ReactorSelectionOptions(usage.Options, app.ReactorSelectionMixin):
  739. pass
  740. self.pluginResults = []
  741. options = ReactorSelectionOptions()
  742. options.messageOutput = StringIO()
  743. e = self.assertRaises(
  744. usage.UsageError,
  745. options.parseOptions,
  746. ["--reactor", "fakereactortest", "subcommand"],
  747. )
  748. self.assertIn("fakereactortest", e.args[0])
  749. self.assertIn("help-reactors", e.args[0])
  750. def test_reactorSelectionMixinNotAvailable(self):
  751. """
  752. Test that the usage mixin exits when trying to use a reactor not
  753. available (the reactor raises an error at installation), giving an
  754. error message.
  755. """
  756. class ReactorSelectionOptions(usage.Options, app.ReactorSelectionMixin):
  757. pass
  758. message = "Missing foo bar"
  759. def install():
  760. raise ImportError(message)
  761. name = "fakereactortest"
  762. package = __name__
  763. description = "description"
  764. self.pluginResults = [FakeReactor(install, name, package, description)]
  765. options = ReactorSelectionOptions()
  766. options.messageOutput = StringIO()
  767. e = self.assertRaises(
  768. usage.UsageError,
  769. options.parseOptions,
  770. ["--reactor", "fakereactortest", "subcommand"],
  771. )
  772. self.assertIn(message, e.args[0])
  773. self.assertIn("help-reactors", e.args[0])
  774. class HelpReactorsTests(TestCase):
  775. """
  776. --help-reactors lists the available reactors
  777. """
  778. def setUp(self):
  779. """
  780. Get the text from --help-reactors
  781. """
  782. self.options = app.ReactorSelectionMixin()
  783. self.options.messageOutput = StringIO()
  784. self.assertRaises(SystemExit, self.options.opt_help_reactors)
  785. self.message = self.options.messageOutput.getvalue()
  786. @skipIf(asyncio, "Not applicable, asyncio is available")
  787. def test_lacksAsyncIO(self):
  788. """
  789. --help-reactors should NOT display the asyncio reactor on Python < 3.4
  790. """
  791. self.assertIn(twisted_reactors.asyncio.description, self.message)
  792. self.assertIn("!" + twisted_reactors.asyncio.shortName, self.message)
  793. @skipIf(not asyncio, "asyncio library not available")
  794. def test_hasAsyncIO(self):
  795. """
  796. --help-reactors should display the asyncio reactor on Python >= 3.4
  797. """
  798. self.assertIn(twisted_reactors.asyncio.description, self.message)
  799. self.assertNotIn("!" + twisted_reactors.asyncio.shortName, self.message)
  800. @skipIf(platformType != "win32", "Test only applicable on Windows")
  801. def test_iocpWin32(self):
  802. """
  803. --help-reactors should display the iocp reactor on Windows
  804. """
  805. self.assertIn(twisted_reactors.iocp.description, self.message)
  806. self.assertNotIn("!" + twisted_reactors.iocp.shortName, self.message)
  807. @skipIf(platformType == "win32", "Test not applicable on Windows")
  808. def test_iocpNotWin32(self):
  809. """
  810. --help-reactors should NOT display the iocp reactor on Windows
  811. """
  812. self.assertIn(twisted_reactors.iocp.description, self.message)
  813. self.assertIn("!" + twisted_reactors.iocp.shortName, self.message)
  814. def test_onlySupportedReactors(self):
  815. """
  816. --help-reactors with only supported reactors
  817. """
  818. def getReactorTypes():
  819. yield twisted_reactors.default
  820. options = app.ReactorSelectionMixin()
  821. options._getReactorTypes = getReactorTypes
  822. options.messageOutput = StringIO()
  823. self.assertRaises(SystemExit, options.opt_help_reactors)
  824. message = options.messageOutput.getvalue()
  825. self.assertNotIn("reactors not available", message)
  826. class BackoffPolicyTests(TestCase):
  827. """
  828. Tests of L{twisted.application.internet.backoffPolicy}
  829. """
  830. def test_calculates_correct_values(self):
  831. """
  832. Test that L{backoffPolicy()} calculates expected values
  833. """
  834. pol = backoffPolicy(1.0, 60.0, 1.5, jitter=lambda: 1)
  835. self.assertAlmostEqual(pol(0), 2)
  836. self.assertAlmostEqual(pol(1), 2.5)
  837. self.assertAlmostEqual(pol(10), 58.6650390625)
  838. self.assertEqual(pol(20), 61)
  839. self.assertEqual(pol(100), 61)
  840. def test_does_not_overflow_on_high_attempts(self):
  841. """
  842. L{backoffPolicy()} does not fail for large values of the attempt
  843. parameter. In previous versions, this test failed when attempt was
  844. larger than 1750.
  845. See https://twistedmatrix.com/trac/ticket/9476
  846. """
  847. pol = backoffPolicy(1.0, 60.0, 1.5, jitter=lambda: 1)
  848. self.assertEqual(pol(1751), 61)
  849. self.assertEqual(pol(1000000), 61)
  850. def test_does_not_overflow_with_large_factor_value(self):
  851. """
  852. Even with unusual parameters, any L{OverflowError} within
  853. L{backoffPolicy()} will be caught and L{maxDelay} will be returned
  854. instead
  855. """
  856. pol = backoffPolicy(1.0, 60.0, 1e10, jitter=lambda: 1)
  857. self.assertEqual(pol(1751), 61)