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_twistd.py 72KB

1 year ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for L{twisted.application.app} and L{twisted.scripts.twistd}.
  5. """
  6. import errno
  7. import inspect
  8. import os
  9. import pickle
  10. import signal
  11. import sys
  12. try:
  13. import grp as _grp
  14. import pwd as _pwd
  15. except ImportError:
  16. pwd = None
  17. grp = None
  18. else:
  19. pwd = _pwd
  20. grp = _grp
  21. from io import StringIO
  22. from unittest import skipIf
  23. from zope.interface import implementer
  24. from zope.interface.verify import verifyObject
  25. from twisted import internet, logger, plugin
  26. from twisted.application import app, reactors, service
  27. from twisted.application.service import IServiceMaker
  28. from twisted.internet.base import ReactorBase
  29. from twisted.internet.defer import Deferred
  30. from twisted.internet.interfaces import IReactorDaemonize, _ISupportsExitSignalCapturing
  31. from twisted.internet.test.modulehelpers import AlternateReactor
  32. from twisted.logger import ILogObserver, globalLogBeginner, globalLogPublisher
  33. from twisted.python import util
  34. from twisted.python.components import Componentized
  35. from twisted.python.fakepwd import UserDatabase
  36. from twisted.python.log import ILogObserver as LegacyILogObserver, textFromEventDict
  37. from twisted.python.reflect import requireModule
  38. from twisted.python.runtime import platformType
  39. from twisted.python.usage import UsageError
  40. from twisted.scripts import twistd
  41. from twisted.test.proto_helpers import MemoryReactor
  42. from twisted.test.test_process import MockOS
  43. from twisted.trial.unittest import TestCase
  44. _twistd_unix = requireModule("twisted.scripts._twistd_unix")
  45. if _twistd_unix:
  46. from twisted.scripts._twistd_unix import (
  47. UnixApplicationRunner,
  48. UnixAppLogger,
  49. checkPID,
  50. )
  51. syslog = requireModule("twisted.python.syslog")
  52. profile = requireModule("profile")
  53. pstats = requireModule("pstats")
  54. cProfile = requireModule("cProfile")
  55. def patchUserDatabase(patch, user, uid, group, gid):
  56. """
  57. Patch L{pwd.getpwnam} so that it behaves as though only one user exists
  58. and patch L{grp.getgrnam} so that it behaves as though only one group
  59. exists.
  60. @param patch: A function like L{TestCase.patch} which will be used to
  61. install the fake implementations.
  62. @type user: C{str}
  63. @param user: The name of the single user which will exist.
  64. @type uid: C{int}
  65. @param uid: The UID of the single user which will exist.
  66. @type group: C{str}
  67. @param group: The name of the single user which will exist.
  68. @type gid: C{int}
  69. @param gid: The GID of the single group which will exist.
  70. """
  71. # Try not to be an unverified fake, but try not to depend on quirks of
  72. # the system either (eg, run as a process with a uid and gid which
  73. # equal each other, and so doesn't reliably test that uid is used where
  74. # uid should be used and gid is used where gid should be used). -exarkun
  75. pwent = pwd.getpwuid(os.getuid())
  76. grent = grp.getgrgid(os.getgid())
  77. database = UserDatabase()
  78. database.addUser(
  79. user, pwent.pw_passwd, uid, gid, pwent.pw_gecos, pwent.pw_dir, pwent.pw_shell
  80. )
  81. def getgrnam(name):
  82. result = list(grent)
  83. result[result.index(grent.gr_name)] = group
  84. result[result.index(grent.gr_gid)] = gid
  85. result = tuple(result)
  86. return {group: result}[name]
  87. patch(pwd, "getpwnam", database.getpwnam)
  88. patch(grp, "getgrnam", getgrnam)
  89. patch(pwd, "getpwuid", database.getpwuid)
  90. class MockServiceMaker:
  91. """
  92. A non-implementation of L{twisted.application.service.IServiceMaker}.
  93. """
  94. tapname = "ueoa"
  95. def makeService(self, options):
  96. """
  97. Take a L{usage.Options} instance and return a
  98. L{service.IService} provider.
  99. """
  100. self.options = options
  101. self.service = service.Service()
  102. return self.service
  103. class CrippledAppLogger(app.AppLogger):
  104. """
  105. @see: CrippledApplicationRunner.
  106. """
  107. def start(self, application):
  108. pass
  109. class CrippledApplicationRunner(twistd._SomeApplicationRunner):
  110. """
  111. An application runner that cripples the platform-specific runner and
  112. nasty side-effect-having code so that we can use it without actually
  113. running any environment-affecting code.
  114. """
  115. loggerFactory = CrippledAppLogger
  116. def preApplication(self):
  117. pass
  118. def postApplication(self):
  119. pass
  120. class ServerOptionsTests(TestCase):
  121. """
  122. Non-platform-specific tests for the platform-specific ServerOptions class.
  123. """
  124. def test_subCommands(self):
  125. """
  126. subCommands is built from IServiceMaker plugins, and is sorted
  127. alphabetically.
  128. """
  129. class FakePlugin:
  130. def __init__(self, name):
  131. self.tapname = name
  132. self._options = "options for " + name
  133. self.description = "description of " + name
  134. def options(self):
  135. return self._options
  136. apple = FakePlugin("apple")
  137. banana = FakePlugin("banana")
  138. coconut = FakePlugin("coconut")
  139. donut = FakePlugin("donut")
  140. def getPlugins(interface):
  141. self.assertEqual(interface, IServiceMaker)
  142. yield coconut
  143. yield banana
  144. yield donut
  145. yield apple
  146. config = twistd.ServerOptions()
  147. self.assertEqual(config._getPlugins, plugin.getPlugins)
  148. config._getPlugins = getPlugins
  149. # "subCommands is a list of 4-tuples of (command name, command
  150. # shortcut, parser class, documentation)."
  151. subCommands = config.subCommands
  152. expectedOrder = [apple, banana, coconut, donut]
  153. for subCommand, expectedCommand in zip(subCommands, expectedOrder):
  154. name, shortcut, parserClass, documentation = subCommand
  155. self.assertEqual(name, expectedCommand.tapname)
  156. self.assertIsNone(shortcut)
  157. self.assertEqual(parserClass(), expectedCommand._options),
  158. self.assertEqual(documentation, expectedCommand.description)
  159. def test_sortedReactorHelp(self):
  160. """
  161. Reactor names are listed alphabetically by I{--help-reactors}.
  162. """
  163. class FakeReactorInstaller:
  164. def __init__(self, name):
  165. self.shortName = "name of " + name
  166. self.description = "description of " + name
  167. self.moduleName = "twisted.internet.default"
  168. apple = FakeReactorInstaller("apple")
  169. banana = FakeReactorInstaller("banana")
  170. coconut = FakeReactorInstaller("coconut")
  171. donut = FakeReactorInstaller("donut")
  172. def getReactorTypes():
  173. yield coconut
  174. yield banana
  175. yield donut
  176. yield apple
  177. config = twistd.ServerOptions()
  178. self.assertEqual(config._getReactorTypes, reactors.getReactorTypes)
  179. config._getReactorTypes = getReactorTypes
  180. config.messageOutput = StringIO()
  181. self.assertRaises(SystemExit, config.parseOptions, ["--help-reactors"])
  182. helpOutput = config.messageOutput.getvalue()
  183. indexes = []
  184. for reactor in apple, banana, coconut, donut:
  185. def getIndex(s):
  186. self.assertIn(s, helpOutput)
  187. indexes.append(helpOutput.index(s))
  188. getIndex(reactor.shortName)
  189. getIndex(reactor.description)
  190. self.assertEqual(
  191. indexes,
  192. sorted(indexes),
  193. "reactor descriptions were not in alphabetical order: {!r}".format(
  194. helpOutput
  195. ),
  196. )
  197. def test_postOptionsSubCommandCausesNoSave(self):
  198. """
  199. postOptions should set no_save to True when a subcommand is used.
  200. """
  201. config = twistd.ServerOptions()
  202. config.subCommand = "ueoa"
  203. config.postOptions()
  204. self.assertTrue(config["no_save"])
  205. def test_postOptionsNoSubCommandSavesAsUsual(self):
  206. """
  207. If no sub command is used, postOptions should not touch no_save.
  208. """
  209. config = twistd.ServerOptions()
  210. config.postOptions()
  211. self.assertFalse(config["no_save"])
  212. def test_listAllProfilers(self):
  213. """
  214. All the profilers that can be used in L{app.AppProfiler} are listed in
  215. the help output.
  216. """
  217. config = twistd.ServerOptions()
  218. helpOutput = str(config)
  219. for profiler in app.AppProfiler.profilers:
  220. self.assertIn(profiler, helpOutput)
  221. @skipIf(not _twistd_unix, "twistd unix not available")
  222. def test_defaultUmask(self):
  223. """
  224. The default value for the C{umask} option is L{None}.
  225. """
  226. config = twistd.ServerOptions()
  227. self.assertIsNone(config["umask"])
  228. @skipIf(not _twistd_unix, "twistd unix not available")
  229. def test_umask(self):
  230. """
  231. The value given for the C{umask} option is parsed as an octal integer
  232. literal.
  233. """
  234. config = twistd.ServerOptions()
  235. config.parseOptions(["--umask", "123"])
  236. self.assertEqual(config["umask"], 83)
  237. config.parseOptions(["--umask", "0123"])
  238. self.assertEqual(config["umask"], 83)
  239. @skipIf(not _twistd_unix, "twistd unix not available")
  240. def test_invalidUmask(self):
  241. """
  242. If a value is given for the C{umask} option which cannot be parsed as
  243. an integer, L{UsageError} is raised by L{ServerOptions.parseOptions}.
  244. """
  245. config = twistd.ServerOptions()
  246. self.assertRaises(UsageError, config.parseOptions, ["--umask", "abcdef"])
  247. def test_unimportableConfiguredLogObserver(self):
  248. """
  249. C{--logger} with an unimportable module raises a L{UsageError}.
  250. """
  251. config = twistd.ServerOptions()
  252. e = self.assertRaises(
  253. UsageError, config.parseOptions, ["--logger", "no.such.module.I.hope"]
  254. )
  255. self.assertTrue(
  256. e.args[0].startswith(
  257. "Logger 'no.such.module.I.hope' could not be imported: "
  258. "'no.such.module.I.hope' does not name an object"
  259. )
  260. )
  261. self.assertNotIn("\n", e.args[0])
  262. def test_badAttributeWithConfiguredLogObserver(self):
  263. """
  264. C{--logger} with a non-existent object raises a L{UsageError}.
  265. """
  266. config = twistd.ServerOptions()
  267. e = self.assertRaises(
  268. UsageError,
  269. config.parseOptions,
  270. ["--logger", "twisted.test.test_twistd.FOOBAR"],
  271. )
  272. self.assertTrue(
  273. e.args[0].startswith(
  274. "Logger 'twisted.test.test_twistd.FOOBAR' could not be "
  275. "imported: module 'twisted.test.test_twistd' "
  276. "has no attribute 'FOOBAR'"
  277. )
  278. )
  279. self.assertNotIn("\n", e.args[0])
  280. def test_version(self):
  281. """
  282. C{--version} prints the version.
  283. """
  284. from twisted import copyright
  285. if platformType == "win32":
  286. name = "(the Twisted Windows runner)"
  287. else:
  288. name = "(the Twisted daemon)"
  289. expectedOutput = "twistd {} {}\n{}\n".format(
  290. name, copyright.version, copyright.copyright
  291. )
  292. stdout = StringIO()
  293. config = twistd.ServerOptions(stdout=stdout)
  294. e = self.assertRaises(SystemExit, config.parseOptions, ["--version"])
  295. self.assertIs(e.code, None)
  296. self.assertEqual(stdout.getvalue(), expectedOutput)
  297. def test_printSubCommandForUsageError(self):
  298. """
  299. Command is printed when an invalid option is requested.
  300. """
  301. stdout = StringIO()
  302. config = twistd.ServerOptions(stdout=stdout)
  303. self.assertRaises(UsageError, config.parseOptions, ["web --foo"])
  304. @skipIf(not _twistd_unix, "twistd unix not available")
  305. class CheckPIDTests(TestCase):
  306. """
  307. Tests for L{checkPID}.
  308. """
  309. def test_notExists(self):
  310. """
  311. Nonexistent PID file is not an error.
  312. """
  313. self.patch(os.path, "exists", lambda _: False)
  314. checkPID("non-existent PID file")
  315. def test_nonNumeric(self):
  316. """
  317. Non-numeric content in a PID file causes a system exit.
  318. """
  319. pidfile = self.mktemp()
  320. with open(pidfile, "w") as f:
  321. f.write("non-numeric")
  322. e = self.assertRaises(SystemExit, checkPID, pidfile)
  323. self.assertIn("non-numeric value", e.code)
  324. def test_anotherRunning(self):
  325. """
  326. Another running twistd server causes a system exit.
  327. """
  328. pidfile = self.mktemp()
  329. with open(pidfile, "w") as f:
  330. f.write("42")
  331. def kill(pid, sig):
  332. pass
  333. self.patch(os, "kill", kill)
  334. e = self.assertRaises(SystemExit, checkPID, pidfile)
  335. self.assertIn("Another twistd server", e.code)
  336. def test_stale(self):
  337. """
  338. Stale PID file is removed without causing a system exit.
  339. """
  340. pidfile = self.mktemp()
  341. with open(pidfile, "w") as f:
  342. f.write(str(os.getpid() + 1))
  343. def kill(pid, sig):
  344. raise OSError(errno.ESRCH, "fake")
  345. self.patch(os, "kill", kill)
  346. checkPID(pidfile)
  347. self.assertFalse(os.path.exists(pidfile))
  348. def test_unexpectedOSError(self):
  349. """
  350. An unexpected L{OSError} when checking the validity of a
  351. PID in a C{pidfile} terminates the process via L{SystemExit}.
  352. """
  353. pidfile = self.mktemp()
  354. with open(pidfile, "w") as f:
  355. f.write("3581")
  356. def kill(pid, sig):
  357. raise OSError(errno.EBADF, "fake")
  358. self.patch(os, "kill", kill)
  359. e = self.assertRaises(SystemExit, checkPID, pidfile)
  360. self.assertIsNot(e.code, None)
  361. self.assertTrue(e.args[0].startswith("Can't check status of PID"))
  362. class TapFileTests(TestCase):
  363. """
  364. Test twistd-related functionality that requires a tap file on disk.
  365. """
  366. def setUp(self):
  367. """
  368. Create a trivial Application and put it in a tap file on disk.
  369. """
  370. self.tapfile = self.mktemp()
  371. with open(self.tapfile, "wb") as f:
  372. pickle.dump(service.Application("Hi!"), f)
  373. def test_createOrGetApplicationWithTapFile(self):
  374. """
  375. Ensure that the createOrGetApplication call that 'twistd -f foo.tap'
  376. makes will load the Application out of foo.tap.
  377. """
  378. config = twistd.ServerOptions()
  379. config.parseOptions(["-f", self.tapfile])
  380. application = CrippledApplicationRunner(config).createOrGetApplication()
  381. self.assertEqual(service.IService(application).name, "Hi!")
  382. class TestLoggerFactory:
  383. """
  384. A logger factory for L{TestApplicationRunner}.
  385. """
  386. def __init__(self, runner):
  387. self.runner = runner
  388. def start(self, application):
  389. """
  390. Save the logging start on the C{runner} instance.
  391. """
  392. self.runner.order.append("log")
  393. self.runner.hadApplicationLogObserver = hasattr(self.runner, "application")
  394. def stop(self):
  395. """
  396. Don't log anything.
  397. """
  398. class TestApplicationRunner(app.ApplicationRunner):
  399. """
  400. An ApplicationRunner which tracks the environment in which its methods are
  401. called.
  402. """
  403. def __init__(self, options):
  404. app.ApplicationRunner.__init__(self, options)
  405. self.order = []
  406. self.logger = TestLoggerFactory(self)
  407. def preApplication(self):
  408. self.order.append("pre")
  409. self.hadApplicationPreApplication = hasattr(self, "application")
  410. def postApplication(self):
  411. self.order.append("post")
  412. self.hadApplicationPostApplication = hasattr(self, "application")
  413. class ApplicationRunnerTests(TestCase):
  414. """
  415. Non-platform-specific tests for the platform-specific ApplicationRunner.
  416. """
  417. def setUp(self):
  418. config = twistd.ServerOptions()
  419. self.serviceMaker = MockServiceMaker()
  420. # Set up a config object like it's been parsed with a subcommand
  421. config.loadedPlugins = {"test_command": self.serviceMaker}
  422. config.subOptions = object()
  423. config.subCommand = "test_command"
  424. self.config = config
  425. def test_applicationRunnerGetsCorrectApplication(self):
  426. """
  427. Ensure that a twistd plugin gets used in appropriate ways: it
  428. is passed its Options instance, and the service it returns is
  429. added to the application.
  430. """
  431. arunner = CrippledApplicationRunner(self.config)
  432. arunner.run()
  433. self.assertIs(
  434. self.serviceMaker.options,
  435. self.config.subOptions,
  436. "ServiceMaker.makeService needs to be passed the correct "
  437. "sub Command object.",
  438. )
  439. self.assertIs(
  440. self.serviceMaker.service,
  441. service.IService(arunner.application).services[0],
  442. "ServiceMaker.makeService's result needs to be set as a child "
  443. "of the Application.",
  444. )
  445. def test_preAndPostApplication(self):
  446. """
  447. Test thet preApplication and postApplication methods are
  448. called by ApplicationRunner.run() when appropriate.
  449. """
  450. s = TestApplicationRunner(self.config)
  451. s.run()
  452. self.assertFalse(s.hadApplicationPreApplication)
  453. self.assertTrue(s.hadApplicationPostApplication)
  454. self.assertTrue(s.hadApplicationLogObserver)
  455. self.assertEqual(s.order, ["pre", "log", "post"])
  456. def _applicationStartsWithConfiguredID(self, argv, uid, gid):
  457. """
  458. Assert that given a particular command line, an application is started
  459. as a particular UID/GID.
  460. @param argv: A list of strings giving the options to parse.
  461. @param uid: An integer giving the expected UID.
  462. @param gid: An integer giving the expected GID.
  463. """
  464. self.config.parseOptions(argv)
  465. events = []
  466. class FakeUnixApplicationRunner(twistd._SomeApplicationRunner):
  467. def setupEnvironment(self, chroot, rundir, nodaemon, umask, pidfile):
  468. events.append("environment")
  469. def shedPrivileges(self, euid, uid, gid):
  470. events.append(("privileges", euid, uid, gid))
  471. def startReactor(self, reactor, oldstdout, oldstderr):
  472. events.append("reactor")
  473. def removePID(self, pidfile):
  474. pass
  475. @implementer(service.IService, service.IProcess)
  476. class FakeService:
  477. parent = None
  478. running = None
  479. name = None
  480. processName = None
  481. uid = None
  482. gid = None
  483. def setName(self, name):
  484. pass
  485. def setServiceParent(self, parent):
  486. pass
  487. def disownServiceParent(self):
  488. pass
  489. def privilegedStartService(self):
  490. events.append("privilegedStartService")
  491. def startService(self):
  492. events.append("startService")
  493. def stopService(self):
  494. pass
  495. application = FakeService()
  496. verifyObject(service.IService, application)
  497. verifyObject(service.IProcess, application)
  498. runner = FakeUnixApplicationRunner(self.config)
  499. runner.preApplication()
  500. runner.application = application
  501. runner.postApplication()
  502. self.assertEqual(
  503. events,
  504. [
  505. "environment",
  506. "privilegedStartService",
  507. ("privileges", False, uid, gid),
  508. "startService",
  509. "reactor",
  510. ],
  511. )
  512. @skipIf(
  513. not getattr(os, "setuid", None),
  514. "Platform does not support --uid/--gid twistd options.",
  515. )
  516. def test_applicationStartsWithConfiguredNumericIDs(self):
  517. """
  518. L{postApplication} should change the UID and GID to the values
  519. specified as numeric strings by the configuration after running
  520. L{service.IService.privilegedStartService} and before running
  521. L{service.IService.startService}.
  522. """
  523. uid = 1234
  524. gid = 4321
  525. self._applicationStartsWithConfiguredID(
  526. ["--uid", str(uid), "--gid", str(gid)], uid, gid
  527. )
  528. @skipIf(
  529. not getattr(os, "setuid", None),
  530. "Platform does not support --uid/--gid twistd options.",
  531. )
  532. def test_applicationStartsWithConfiguredNameIDs(self):
  533. """
  534. L{postApplication} should change the UID and GID to the values
  535. specified as user and group names by the configuration after running
  536. L{service.IService.privilegedStartService} and before running
  537. L{service.IService.startService}.
  538. """
  539. user = "foo"
  540. uid = 1234
  541. group = "bar"
  542. gid = 4321
  543. patchUserDatabase(self.patch, user, uid, group, gid)
  544. self._applicationStartsWithConfiguredID(
  545. ["--uid", user, "--gid", group], uid, gid
  546. )
  547. def test_startReactorRunsTheReactor(self):
  548. """
  549. L{startReactor} calls L{reactor.run}.
  550. """
  551. reactor = DummyReactor()
  552. runner = app.ApplicationRunner(
  553. {"profile": False, "profiler": "profile", "debug": False}
  554. )
  555. runner.startReactor(reactor, None, None)
  556. self.assertTrue(reactor.called, "startReactor did not call reactor.run()")
  557. def test_applicationRunnerChoosesReactorIfNone(self):
  558. """
  559. L{ApplicationRunner} chooses a reactor if none is specified.
  560. """
  561. reactor = DummyReactor()
  562. self.patch(internet, "reactor", reactor)
  563. runner = app.ApplicationRunner(
  564. {"profile": False, "profiler": "profile", "debug": False}
  565. )
  566. runner.startReactor(None, None, None)
  567. self.assertTrue(reactor.called)
  568. def test_applicationRunnerCapturesSignal(self):
  569. """
  570. If the reactor exits with a signal, the application runner caches
  571. the signal.
  572. """
  573. class DummyReactorWithSignal(ReactorBase):
  574. """
  575. A dummy reactor, providing a C{run} method, and setting the
  576. _exitSignal attribute to a nonzero value.
  577. """
  578. def installWaker(self):
  579. """
  580. Dummy method, does nothing.
  581. """
  582. def run(self):
  583. """
  584. A fake run method setting _exitSignal to a nonzero value
  585. """
  586. self._exitSignal = 2
  587. reactor = DummyReactorWithSignal()
  588. runner = app.ApplicationRunner(
  589. {"profile": False, "profiler": "profile", "debug": False}
  590. )
  591. runner.startReactor(reactor, None, None)
  592. self.assertEquals(2, runner._exitSignal)
  593. def test_applicationRunnerIgnoresNoSignal(self):
  594. """
  595. The runner sets its _exitSignal instance attribute to None if
  596. the reactor does not implement L{_ISupportsExitSignalCapturing}.
  597. """
  598. class DummyReactorWithExitSignalAttribute:
  599. """
  600. A dummy reactor, providing a C{run} method, and setting the
  601. _exitSignal attribute to a nonzero value.
  602. """
  603. def installWaker(self):
  604. """
  605. Dummy method, does nothing.
  606. """
  607. def run(self):
  608. """
  609. A fake run method setting _exitSignal to a nonzero value
  610. that should be ignored.
  611. """
  612. self._exitSignal = 2
  613. reactor = DummyReactorWithExitSignalAttribute()
  614. runner = app.ApplicationRunner(
  615. {"profile": False, "profiler": "profile", "debug": False}
  616. )
  617. runner.startReactor(reactor, None, None)
  618. self.assertEquals(None, runner._exitSignal)
  619. @skipIf(not _twistd_unix, "twistd unix not available")
  620. class UnixApplicationRunnerSetupEnvironmentTests(TestCase):
  621. """
  622. Tests for L{UnixApplicationRunner.setupEnvironment}.
  623. @ivar root: The root of the filesystem, or C{unset} if none has been
  624. specified with a call to L{os.chroot} (patched for this TestCase with
  625. L{UnixApplicationRunnerSetupEnvironmentTests.chroot}).
  626. @ivar cwd: The current working directory of the process, or C{unset} if
  627. none has been specified with a call to L{os.chdir} (patched for this
  628. TestCase with L{UnixApplicationRunnerSetupEnvironmentTests.chdir}).
  629. @ivar mask: The current file creation mask of the process, or C{unset} if
  630. none has been specified with a call to L{os.umask} (patched for this
  631. TestCase with L{UnixApplicationRunnerSetupEnvironmentTests.umask}).
  632. @ivar daemon: A boolean indicating whether daemonization has been performed
  633. by a call to L{_twistd_unix.daemonize} (patched for this TestCase with
  634. L{UnixApplicationRunnerSetupEnvironmentTests}.
  635. """
  636. unset = object()
  637. def setUp(self):
  638. self.root = self.unset
  639. self.cwd = self.unset
  640. self.mask = self.unset
  641. self.daemon = False
  642. self.pid = os.getpid()
  643. self.patch(os, "chroot", lambda path: setattr(self, "root", path))
  644. self.patch(os, "chdir", lambda path: setattr(self, "cwd", path))
  645. self.patch(os, "umask", lambda mask: setattr(self, "mask", mask))
  646. self.runner = UnixApplicationRunner(twistd.ServerOptions())
  647. self.runner.daemonize = self.daemonize
  648. def daemonize(self, reactor):
  649. """
  650. Indicate that daemonization has happened and change the PID so that the
  651. value written to the pidfile can be tested in the daemonization case.
  652. """
  653. self.daemon = True
  654. self.patch(os, "getpid", lambda: self.pid + 1)
  655. def test_chroot(self):
  656. """
  657. L{UnixApplicationRunner.setupEnvironment} changes the root of the
  658. filesystem if passed a non-L{None} value for the C{chroot} parameter.
  659. """
  660. self.runner.setupEnvironment("/foo/bar", ".", True, None, None)
  661. self.assertEqual(self.root, "/foo/bar")
  662. def test_noChroot(self):
  663. """
  664. L{UnixApplicationRunner.setupEnvironment} does not change the root of
  665. the filesystem if passed L{None} for the C{chroot} parameter.
  666. """
  667. self.runner.setupEnvironment(None, ".", True, None, None)
  668. self.assertIs(self.root, self.unset)
  669. def test_changeWorkingDirectory(self):
  670. """
  671. L{UnixApplicationRunner.setupEnvironment} changes the working directory
  672. of the process to the path given for the C{rundir} parameter.
  673. """
  674. self.runner.setupEnvironment(None, "/foo/bar", True, None, None)
  675. self.assertEqual(self.cwd, "/foo/bar")
  676. def test_daemonize(self):
  677. """
  678. L{UnixApplicationRunner.setupEnvironment} daemonizes the process if
  679. C{False} is passed for the C{nodaemon} parameter.
  680. """
  681. with AlternateReactor(FakeDaemonizingReactor()):
  682. self.runner.setupEnvironment(None, ".", False, None, None)
  683. self.assertTrue(self.daemon)
  684. def test_noDaemonize(self):
  685. """
  686. L{UnixApplicationRunner.setupEnvironment} does not daemonize the
  687. process if C{True} is passed for the C{nodaemon} parameter.
  688. """
  689. self.runner.setupEnvironment(None, ".", True, None, None)
  690. self.assertFalse(self.daemon)
  691. def test_nonDaemonPIDFile(self):
  692. """
  693. L{UnixApplicationRunner.setupEnvironment} writes the process's PID to
  694. the file specified by the C{pidfile} parameter.
  695. """
  696. pidfile = self.mktemp()
  697. self.runner.setupEnvironment(None, ".", True, None, pidfile)
  698. with open(pidfile, "rb") as f:
  699. pid = int(f.read())
  700. self.assertEqual(pid, self.pid)
  701. def test_daemonPIDFile(self):
  702. """
  703. L{UnixApplicationRunner.setupEnvironment} writes the daemonized
  704. process's PID to the file specified by the C{pidfile} parameter if
  705. C{nodaemon} is C{False}.
  706. """
  707. pidfile = self.mktemp()
  708. with AlternateReactor(FakeDaemonizingReactor()):
  709. self.runner.setupEnvironment(None, ".", False, None, pidfile)
  710. with open(pidfile, "rb") as f:
  711. pid = int(f.read())
  712. self.assertEqual(pid, self.pid + 1)
  713. def test_umask(self):
  714. """
  715. L{UnixApplicationRunner.setupEnvironment} changes the process umask to
  716. the value specified by the C{umask} parameter.
  717. """
  718. with AlternateReactor(FakeDaemonizingReactor()):
  719. self.runner.setupEnvironment(None, ".", False, 123, None)
  720. self.assertEqual(self.mask, 123)
  721. def test_noDaemonizeNoUmask(self):
  722. """
  723. L{UnixApplicationRunner.setupEnvironment} doesn't change the process
  724. umask if L{None} is passed for the C{umask} parameter and C{True} is
  725. passed for the C{nodaemon} parameter.
  726. """
  727. self.runner.setupEnvironment(None, ".", True, None, None)
  728. self.assertIs(self.mask, self.unset)
  729. def test_daemonizedNoUmask(self):
  730. """
  731. L{UnixApplicationRunner.setupEnvironment} changes the process umask to
  732. C{0077} if L{None} is passed for the C{umask} parameter and C{False} is
  733. passed for the C{nodaemon} parameter.
  734. """
  735. with AlternateReactor(FakeDaemonizingReactor()):
  736. self.runner.setupEnvironment(None, ".", False, None, None)
  737. self.assertEqual(self.mask, 0o077)
  738. @skipIf(not _twistd_unix, "twistd unix not available")
  739. class UnixApplicationRunnerStartApplicationTests(TestCase):
  740. """
  741. Tests for L{UnixApplicationRunner.startApplication}.
  742. """
  743. def test_setupEnvironment(self):
  744. """
  745. L{UnixApplicationRunner.startApplication} calls
  746. L{UnixApplicationRunner.setupEnvironment} with the chroot, rundir,
  747. nodaemon, umask, and pidfile parameters from the configuration it is
  748. constructed with.
  749. """
  750. options = twistd.ServerOptions()
  751. options.parseOptions(
  752. [
  753. "--nodaemon",
  754. "--umask",
  755. "0070",
  756. "--chroot",
  757. "/foo/chroot",
  758. "--rundir",
  759. "/foo/rundir",
  760. "--pidfile",
  761. "/foo/pidfile",
  762. ]
  763. )
  764. application = service.Application("test_setupEnvironment")
  765. self.runner = UnixApplicationRunner(options)
  766. args = []
  767. def fakeSetupEnvironment(self, chroot, rundir, nodaemon, umask, pidfile):
  768. args.extend((chroot, rundir, nodaemon, umask, pidfile))
  769. # Sanity check
  770. setupEnvironmentParameters = inspect.signature(
  771. self.runner.setupEnvironment
  772. ).parameters
  773. fakeSetupEnvironmentParameters = inspect.signature(
  774. fakeSetupEnvironment
  775. ).parameters
  776. # inspect.signature() does not return "self" in the signature of
  777. # a class method, so we need to omit it when comparing the
  778. # the signature of a plain method
  779. fakeSetupEnvironmentParameters = fakeSetupEnvironmentParameters.copy()
  780. fakeSetupEnvironmentParameters.pop("self")
  781. self.assertEqual(setupEnvironmentParameters, fakeSetupEnvironmentParameters)
  782. self.patch(UnixApplicationRunner, "setupEnvironment", fakeSetupEnvironment)
  783. self.patch(UnixApplicationRunner, "shedPrivileges", lambda *a, **kw: None)
  784. self.patch(app, "startApplication", lambda *a, **kw: None)
  785. self.runner.startApplication(application)
  786. self.assertEqual(args, ["/foo/chroot", "/foo/rundir", True, 56, "/foo/pidfile"])
  787. def test_shedPrivileges(self):
  788. """
  789. L{UnixApplicationRunner.shedPrivileges} switches the user ID
  790. of the process.
  791. """
  792. def switchUIDPass(uid, gid, euid):
  793. self.assertEqual(uid, 200)
  794. self.assertEqual(gid, 54)
  795. self.assertEqual(euid, 35)
  796. self.patch(_twistd_unix, "switchUID", switchUIDPass)
  797. runner = UnixApplicationRunner({})
  798. runner.shedPrivileges(35, 200, 54)
  799. def test_shedPrivilegesError(self):
  800. """
  801. An unexpected L{OSError} when calling
  802. L{twisted.scripts._twistd_unix.shedPrivileges}
  803. terminates the process via L{SystemExit}.
  804. """
  805. def switchUIDFail(uid, gid, euid):
  806. raise OSError(errno.EBADF, "fake")
  807. runner = UnixApplicationRunner({})
  808. self.patch(_twistd_unix, "switchUID", switchUIDFail)
  809. exc = self.assertRaises(SystemExit, runner.shedPrivileges, 35, 200, None)
  810. self.assertEqual(exc.code, 1)
  811. def _setUID(self, wantedUser, wantedUid, wantedGroup, wantedGid):
  812. """
  813. Common code for tests which try to pass the the UID to
  814. L{UnixApplicationRunner}.
  815. """
  816. patchUserDatabase(self.patch, wantedUser, wantedUid, wantedGroup, wantedGid)
  817. def initgroups(uid, gid):
  818. self.assertEqual(uid, wantedUid)
  819. self.assertEqual(gid, wantedGid)
  820. def setuid(uid):
  821. self.assertEqual(uid, wantedUid)
  822. def setgid(gid):
  823. self.assertEqual(gid, wantedGid)
  824. self.patch(util, "initgroups", initgroups)
  825. self.patch(os, "setuid", setuid)
  826. self.patch(os, "setgid", setgid)
  827. options = twistd.ServerOptions()
  828. options.parseOptions(["--nodaemon", "--uid", str(wantedUid)])
  829. application = service.Application("test_setupEnvironment")
  830. self.runner = UnixApplicationRunner(options)
  831. runner = UnixApplicationRunner(options)
  832. runner.startApplication(application)
  833. def test_setUidWithoutGid(self):
  834. """
  835. Starting an application with L{UnixApplicationRunner} configured
  836. with a UID and no GUID will result in the GUID being
  837. set to the default GUID for that UID.
  838. """
  839. self._setUID("foo", 5151, "bar", 4242)
  840. def test_setUidSameAsCurrentUid(self):
  841. """
  842. If the specified UID is the same as the current UID of the process,
  843. then a warning is displayed.
  844. """
  845. currentUid = os.getuid()
  846. self._setUID("morefoo", currentUid, "morebar", 4343)
  847. warningsShown = self.flushWarnings()
  848. self.assertEqual(1, len(warningsShown))
  849. expectedWarning = (
  850. "tried to drop privileges and setuid {} but uid is already {}; "
  851. "should we be root? Continuing.".format(currentUid, currentUid)
  852. )
  853. self.assertEqual(expectedWarning, warningsShown[0]["message"])
  854. @skipIf(not _twistd_unix, "twistd unix not available")
  855. class UnixApplicationRunnerRemovePIDTests(TestCase):
  856. """
  857. Tests for L{UnixApplicationRunner.removePID}.
  858. """
  859. def test_removePID(self):
  860. """
  861. L{UnixApplicationRunner.removePID} deletes the file the name of
  862. which is passed to it.
  863. """
  864. runner = UnixApplicationRunner({})
  865. path = self.mktemp()
  866. os.makedirs(path)
  867. pidfile = os.path.join(path, "foo.pid")
  868. open(pidfile, "w").close()
  869. runner.removePID(pidfile)
  870. self.assertFalse(os.path.exists(pidfile))
  871. def test_removePIDErrors(self):
  872. """
  873. Calling L{UnixApplicationRunner.removePID} with a non-existent filename
  874. logs an OSError.
  875. """
  876. runner = UnixApplicationRunner({})
  877. runner.removePID("fakepid")
  878. errors = self.flushLoggedErrors(OSError)
  879. self.assertEqual(len(errors), 1)
  880. self.assertEqual(errors[0].value.errno, errno.ENOENT)
  881. class FakeNonDaemonizingReactor:
  882. """
  883. A dummy reactor, providing C{beforeDaemonize} and C{afterDaemonize}
  884. methods, but not announcing this, and logging whether the methods have been
  885. called.
  886. @ivar _beforeDaemonizeCalled: if C{beforeDaemonize} has been called or not.
  887. @type _beforeDaemonizeCalled: C{bool}
  888. @ivar _afterDaemonizeCalled: if C{afterDaemonize} has been called or not.
  889. @type _afterDaemonizeCalled: C{bool}
  890. """
  891. def __init__(self):
  892. self._beforeDaemonizeCalled = False
  893. self._afterDaemonizeCalled = False
  894. def beforeDaemonize(self):
  895. self._beforeDaemonizeCalled = True
  896. def afterDaemonize(self):
  897. self._afterDaemonizeCalled = True
  898. def addSystemEventTrigger(self, *args, **kw):
  899. """
  900. Skip event registration.
  901. """
  902. @implementer(IReactorDaemonize)
  903. class FakeDaemonizingReactor(FakeNonDaemonizingReactor):
  904. """
  905. A dummy reactor, providing C{beforeDaemonize} and C{afterDaemonize}
  906. methods, announcing this, and logging whether the methods have been called.
  907. """
  908. class DummyReactor:
  909. """
  910. A dummy reactor, only providing a C{run} method and checking that it
  911. has been called.
  912. @ivar called: if C{run} has been called or not.
  913. @type called: C{bool}
  914. """
  915. called = False
  916. def run(self):
  917. """
  918. A fake run method, checking that it's been called one and only time.
  919. """
  920. if self.called:
  921. raise RuntimeError("Already called")
  922. self.called = True
  923. class AppProfilingTests(TestCase):
  924. """
  925. Tests for L{app.AppProfiler}.
  926. """
  927. @skipIf(not profile, "profile module not available")
  928. def test_profile(self):
  929. """
  930. L{app.ProfileRunner.run} should call the C{run} method of the reactor
  931. and save profile data in the specified file.
  932. """
  933. config = twistd.ServerOptions()
  934. config["profile"] = self.mktemp()
  935. config["profiler"] = "profile"
  936. profiler = app.AppProfiler(config)
  937. reactor = DummyReactor()
  938. profiler.run(reactor)
  939. self.assertTrue(reactor.called)
  940. with open(config["profile"]) as f:
  941. data = f.read()
  942. self.assertIn("DummyReactor.run", data)
  943. self.assertIn("function calls", data)
  944. def _testStats(self, statsClass, profile):
  945. out = StringIO()
  946. # Patch before creating the pstats, because pstats binds self.stream to
  947. # sys.stdout early in 2.5 and newer.
  948. stdout = self.patch(sys, "stdout", out)
  949. # If pstats.Stats can load the data and then reformat it, then the
  950. # right thing probably happened.
  951. stats = statsClass(profile)
  952. stats.print_stats()
  953. stdout.restore()
  954. data = out.getvalue()
  955. self.assertIn("function calls", data)
  956. self.assertIn("(run)", data)
  957. @skipIf(not profile, "profile module not available")
  958. def test_profileSaveStats(self):
  959. """
  960. With the C{savestats} option specified, L{app.ProfileRunner.run}
  961. should save the raw stats object instead of a summary output.
  962. """
  963. config = twistd.ServerOptions()
  964. config["profile"] = self.mktemp()
  965. config["profiler"] = "profile"
  966. config["savestats"] = True
  967. profiler = app.AppProfiler(config)
  968. reactor = DummyReactor()
  969. profiler.run(reactor)
  970. self.assertTrue(reactor.called)
  971. self._testStats(pstats.Stats, config["profile"])
  972. def test_withoutProfile(self):
  973. """
  974. When the C{profile} module is not present, L{app.ProfilerRunner.run}
  975. should raise a C{SystemExit} exception.
  976. """
  977. savedModules = sys.modules.copy()
  978. config = twistd.ServerOptions()
  979. config["profiler"] = "profile"
  980. profiler = app.AppProfiler(config)
  981. sys.modules["profile"] = None
  982. try:
  983. self.assertRaises(SystemExit, profiler.run, None)
  984. finally:
  985. sys.modules.clear()
  986. sys.modules.update(savedModules)
  987. @skipIf(not profile, "profile module not available")
  988. def test_profilePrintStatsError(self):
  989. """
  990. When an error happens during the print of the stats, C{sys.stdout}
  991. should be restored to its initial value.
  992. """
  993. class ErroneousProfile(profile.Profile):
  994. def print_stats(self):
  995. raise RuntimeError("Boom")
  996. self.patch(profile, "Profile", ErroneousProfile)
  997. config = twistd.ServerOptions()
  998. config["profile"] = self.mktemp()
  999. config["profiler"] = "profile"
  1000. profiler = app.AppProfiler(config)
  1001. reactor = DummyReactor()
  1002. oldStdout = sys.stdout
  1003. self.assertRaises(RuntimeError, profiler.run, reactor)
  1004. self.assertIs(sys.stdout, oldStdout)
  1005. @skipIf(not cProfile, "cProfile module not available")
  1006. def test_cProfile(self):
  1007. """
  1008. L{app.CProfileRunner.run} should call the C{run} method of the
  1009. reactor and save profile data in the specified file.
  1010. """
  1011. config = twistd.ServerOptions()
  1012. config["profile"] = self.mktemp()
  1013. config["profiler"] = "cProfile"
  1014. profiler = app.AppProfiler(config)
  1015. reactor = DummyReactor()
  1016. profiler.run(reactor)
  1017. self.assertTrue(reactor.called)
  1018. with open(config["profile"]) as f:
  1019. data = f.read()
  1020. self.assertIn("run", data)
  1021. self.assertIn("function calls", data)
  1022. @skipIf(not cProfile, "cProfile module not available")
  1023. def test_cProfileSaveStats(self):
  1024. """
  1025. With the C{savestats} option specified,
  1026. L{app.CProfileRunner.run} should save the raw stats object
  1027. instead of a summary output.
  1028. """
  1029. config = twistd.ServerOptions()
  1030. config["profile"] = self.mktemp()
  1031. config["profiler"] = "cProfile"
  1032. config["savestats"] = True
  1033. profiler = app.AppProfiler(config)
  1034. reactor = DummyReactor()
  1035. profiler.run(reactor)
  1036. self.assertTrue(reactor.called)
  1037. self._testStats(pstats.Stats, config["profile"])
  1038. def test_withoutCProfile(self):
  1039. """
  1040. When the C{cProfile} module is not present,
  1041. L{app.CProfileRunner.run} should raise a C{SystemExit}
  1042. exception and log the C{ImportError}.
  1043. """
  1044. savedModules = sys.modules.copy()
  1045. sys.modules["cProfile"] = None
  1046. config = twistd.ServerOptions()
  1047. config["profiler"] = "cProfile"
  1048. profiler = app.AppProfiler(config)
  1049. try:
  1050. self.assertRaises(SystemExit, profiler.run, None)
  1051. finally:
  1052. sys.modules.clear()
  1053. sys.modules.update(savedModules)
  1054. def test_unknownProfiler(self):
  1055. """
  1056. Check that L{app.AppProfiler} raises L{SystemExit} when given an
  1057. unknown profiler name.
  1058. """
  1059. config = twistd.ServerOptions()
  1060. config["profile"] = self.mktemp()
  1061. config["profiler"] = "foobar"
  1062. error = self.assertRaises(SystemExit, app.AppProfiler, config)
  1063. self.assertEqual(str(error), "Unsupported profiler name: foobar")
  1064. def test_defaultProfiler(self):
  1065. """
  1066. L{app.Profiler} defaults to the cprofile profiler if not specified.
  1067. """
  1068. profiler = app.AppProfiler({})
  1069. self.assertEqual(profiler.profiler, "cprofile")
  1070. def test_profilerNameCaseInsentive(self):
  1071. """
  1072. The case of the profiler name passed to L{app.AppProfiler} is not
  1073. relevant.
  1074. """
  1075. profiler = app.AppProfiler({"profiler": "CprOfile"})
  1076. self.assertEqual(profiler.profiler, "cprofile")
  1077. def _patchTextFileLogObserver(patch):
  1078. """
  1079. Patch L{logger.textFileLogObserver} to record every call and keep a
  1080. reference to the passed log file for tests.
  1081. @param patch: a callback for patching (usually L{TestCase.patch}).
  1082. @return: the list that keeps track of the log files.
  1083. @rtype: C{list}
  1084. """
  1085. logFiles = []
  1086. oldFileLogObserver = logger.textFileLogObserver
  1087. def observer(logFile, *args, **kwargs):
  1088. logFiles.append(logFile)
  1089. return oldFileLogObserver(logFile, *args, **kwargs)
  1090. patch(logger, "textFileLogObserver", observer)
  1091. return logFiles
  1092. def _setupSyslog(testCase):
  1093. """
  1094. Make fake syslog, and return list to which prefix and then log
  1095. messages will be appended if it is used.
  1096. """
  1097. logMessages = []
  1098. class fakesyslogobserver:
  1099. def __init__(self, prefix):
  1100. logMessages.append(prefix)
  1101. def emit(self, eventDict):
  1102. logMessages.append(eventDict)
  1103. testCase.patch(syslog, "SyslogObserver", fakesyslogobserver)
  1104. return logMessages
  1105. class AppLoggerTests(TestCase):
  1106. """
  1107. Tests for L{app.AppLogger}.
  1108. @ivar observers: list of observers installed during the tests.
  1109. @type observers: C{list}
  1110. """
  1111. def setUp(self):
  1112. """
  1113. Override L{globaLogBeginner.beginLoggingTo} so that we can trace the
  1114. observers installed in C{self.observers}.
  1115. """
  1116. self.observers = []
  1117. def beginLoggingTo(observers):
  1118. for observer in observers:
  1119. self.observers.append(observer)
  1120. globalLogPublisher.addObserver(observer)
  1121. self.patch(globalLogBeginner, "beginLoggingTo", beginLoggingTo)
  1122. def tearDown(self):
  1123. """
  1124. Remove all installed observers.
  1125. """
  1126. for observer in self.observers:
  1127. globalLogPublisher.removeObserver(observer)
  1128. def _makeObserver(self):
  1129. """
  1130. Make a new observer which captures all logs sent to it.
  1131. @return: An observer that stores all logs sent to it.
  1132. @rtype: Callable that implements L{ILogObserver}.
  1133. """
  1134. @implementer(ILogObserver)
  1135. class TestObserver:
  1136. _logs = []
  1137. def __call__(self, event):
  1138. self._logs.append(event)
  1139. return TestObserver()
  1140. def _checkObserver(self, observer):
  1141. """
  1142. Ensure that initial C{twistd} logs are written to logs.
  1143. @param observer: The observer made by L{self._makeObserver).
  1144. """
  1145. self.assertEqual(self.observers, [observer])
  1146. self.assertIn("starting up", observer._logs[0]["log_format"])
  1147. self.assertIn("reactor class", observer._logs[1]["log_format"])
  1148. def test_start(self):
  1149. """
  1150. L{app.AppLogger.start} calls L{globalLogBeginner.addObserver}, and then
  1151. writes some messages about twistd and the reactor.
  1152. """
  1153. logger = app.AppLogger({})
  1154. observer = self._makeObserver()
  1155. logger._getLogObserver = lambda: observer
  1156. logger.start(Componentized())
  1157. self._checkObserver(observer)
  1158. def test_startUsesApplicationLogObserver(self):
  1159. """
  1160. When the L{ILogObserver} component is available on the application,
  1161. that object will be used as the log observer instead of constructing a
  1162. new one.
  1163. """
  1164. application = Componentized()
  1165. observer = self._makeObserver()
  1166. application.setComponent(ILogObserver, observer)
  1167. logger = app.AppLogger({})
  1168. logger.start(application)
  1169. self._checkObserver(observer)
  1170. def _setupConfiguredLogger(
  1171. self, application, extraLogArgs={}, appLogger=app.AppLogger
  1172. ):
  1173. """
  1174. Set up an AppLogger which exercises the C{logger} configuration option.
  1175. @type application: L{Componentized}
  1176. @param application: The L{Application} object to pass to
  1177. L{app.AppLogger.start}.
  1178. @type extraLogArgs: C{dict}
  1179. @param extraLogArgs: extra values to pass to AppLogger.
  1180. @type appLogger: L{AppLogger} class, or a subclass
  1181. @param appLogger: factory for L{AppLogger} instances.
  1182. @rtype: C{list}
  1183. @return: The logs accumulated by the log observer.
  1184. """
  1185. observer = self._makeObserver()
  1186. logArgs = {"logger": lambda: observer}
  1187. logArgs.update(extraLogArgs)
  1188. logger = appLogger(logArgs)
  1189. logger.start(application)
  1190. return observer
  1191. def test_startUsesConfiguredLogObserver(self):
  1192. """
  1193. When the C{logger} key is specified in the configuration dictionary
  1194. (i.e., when C{--logger} is passed to twistd), the initial log observer
  1195. will be the log observer returned from the callable which the value
  1196. refers to in FQPN form.
  1197. """
  1198. application = Componentized()
  1199. self._checkObserver(self._setupConfiguredLogger(application))
  1200. def test_configuredLogObserverBeatsComponent(self):
  1201. """
  1202. C{--logger} takes precedence over a L{ILogObserver} component set on
  1203. Application.
  1204. """
  1205. observer = self._makeObserver()
  1206. application = Componentized()
  1207. application.setComponent(ILogObserver, observer)
  1208. self._checkObserver(self._setupConfiguredLogger(application))
  1209. self.assertEqual(observer._logs, [])
  1210. def test_configuredLogObserverBeatsLegacyComponent(self):
  1211. """
  1212. C{--logger} takes precedence over a L{LegacyILogObserver} component
  1213. set on Application.
  1214. """
  1215. nonlogs = []
  1216. application = Componentized()
  1217. application.setComponent(LegacyILogObserver, nonlogs.append)
  1218. self._checkObserver(self._setupConfiguredLogger(application))
  1219. self.assertEqual(nonlogs, [])
  1220. def test_loggerComponentBeatsLegacyLoggerComponent(self):
  1221. """
  1222. A L{ILogObserver} takes precedence over a L{LegacyILogObserver}
  1223. component set on Application.
  1224. """
  1225. nonlogs = []
  1226. observer = self._makeObserver()
  1227. application = Componentized()
  1228. application.setComponent(ILogObserver, observer)
  1229. application.setComponent(LegacyILogObserver, nonlogs.append)
  1230. logger = app.AppLogger({})
  1231. logger.start(application)
  1232. self._checkObserver(observer)
  1233. self.assertEqual(nonlogs, [])
  1234. @skipIf(not _twistd_unix, "twistd unix not available")
  1235. @skipIf(not syslog, "syslog not available")
  1236. def test_configuredLogObserverBeatsSyslog(self):
  1237. """
  1238. C{--logger} takes precedence over a C{--syslog} command line
  1239. argument.
  1240. """
  1241. logs = _setupSyslog(self)
  1242. application = Componentized()
  1243. self._checkObserver(
  1244. self._setupConfiguredLogger(application, {"syslog": True}, UnixAppLogger)
  1245. )
  1246. self.assertEqual(logs, [])
  1247. def test_configuredLogObserverBeatsLogfile(self):
  1248. """
  1249. C{--logger} takes precedence over a C{--logfile} command line
  1250. argument.
  1251. """
  1252. application = Componentized()
  1253. path = self.mktemp()
  1254. self._checkObserver(
  1255. self._setupConfiguredLogger(application, {"logfile": "path"})
  1256. )
  1257. self.assertFalse(os.path.exists(path))
  1258. def test_getLogObserverStdout(self):
  1259. """
  1260. When logfile is empty or set to C{-}, L{app.AppLogger._getLogObserver}
  1261. returns a log observer pointing at C{sys.stdout}.
  1262. """
  1263. logger = app.AppLogger({"logfile": "-"})
  1264. logFiles = _patchTextFileLogObserver(self.patch)
  1265. logger._getLogObserver()
  1266. self.assertEqual(len(logFiles), 1)
  1267. self.assertIs(logFiles[0], sys.stdout)
  1268. logger = app.AppLogger({"logfile": ""})
  1269. logger._getLogObserver()
  1270. self.assertEqual(len(logFiles), 2)
  1271. self.assertIs(logFiles[1], sys.stdout)
  1272. def test_getLogObserverFile(self):
  1273. """
  1274. When passing the C{logfile} option, L{app.AppLogger._getLogObserver}
  1275. returns a log observer pointing at the specified path.
  1276. """
  1277. logFiles = _patchTextFileLogObserver(self.patch)
  1278. filename = self.mktemp()
  1279. sut = app.AppLogger({"logfile": filename})
  1280. observer = sut._getLogObserver()
  1281. self.addCleanup(observer._outFile.close)
  1282. self.assertEqual(len(logFiles), 1)
  1283. self.assertEqual(logFiles[0].path, os.path.abspath(filename))
  1284. def test_stop(self):
  1285. """
  1286. L{app.AppLogger.stop} removes the observer created in C{start}, and
  1287. reinitialize its C{_observer} so that if C{stop} is called several
  1288. times it doesn't break.
  1289. """
  1290. removed = []
  1291. observer = object()
  1292. def remove(observer):
  1293. removed.append(observer)
  1294. self.patch(globalLogPublisher, "removeObserver", remove)
  1295. logger = app.AppLogger({})
  1296. logger._observer = observer
  1297. logger.stop()
  1298. self.assertEqual(removed, [observer])
  1299. logger.stop()
  1300. self.assertEqual(removed, [observer])
  1301. self.assertIsNone(logger._observer)
  1302. def test_legacyObservers(self):
  1303. """
  1304. L{app.AppLogger} using a legacy logger observer still works, wrapping
  1305. it in a compat shim.
  1306. """
  1307. logs = []
  1308. logger = app.AppLogger({})
  1309. @implementer(LegacyILogObserver)
  1310. class LoggerObserver:
  1311. """
  1312. An observer which implements the legacy L{LegacyILogObserver}.
  1313. """
  1314. def __call__(self, x):
  1315. """
  1316. Add C{x} to the logs list.
  1317. """
  1318. logs.append(x)
  1319. logger._observerFactory = lambda: LoggerObserver()
  1320. logger.start(Componentized())
  1321. self.assertIn("starting up", textFromEventDict(logs[0]))
  1322. warnings = self.flushWarnings([self.test_legacyObservers])
  1323. self.assertEqual(len(warnings), 0, warnings)
  1324. def test_unmarkedObserversDeprecated(self):
  1325. """
  1326. L{app.AppLogger} using a logger observer which does not implement
  1327. L{ILogObserver} or L{LegacyILogObserver} will be wrapped in a compat
  1328. shim and raise a L{DeprecationWarning}.
  1329. """
  1330. logs = []
  1331. logger = app.AppLogger({})
  1332. logger._getLogObserver = lambda: logs.append
  1333. logger.start(Componentized())
  1334. self.assertIn("starting up", textFromEventDict(logs[0]))
  1335. warnings = self.flushWarnings([self.test_unmarkedObserversDeprecated])
  1336. self.assertEqual(len(warnings), 1, warnings)
  1337. self.assertEqual(
  1338. warnings[0]["message"],
  1339. (
  1340. "Passing a logger factory which makes log observers "
  1341. "which do not implement twisted.logger.ILogObserver "
  1342. "or twisted.python.log.ILogObserver to "
  1343. "twisted.application.app.AppLogger was deprecated "
  1344. "in Twisted 16.2. Please use a factory that "
  1345. "produces twisted.logger.ILogObserver (or the "
  1346. "legacy twisted.python.log.ILogObserver) "
  1347. "implementing objects instead."
  1348. ),
  1349. )
  1350. @skipIf(not _twistd_unix, "twistd unix not available")
  1351. class UnixAppLoggerTests(TestCase):
  1352. """
  1353. Tests for L{UnixAppLogger}.
  1354. @ivar signals: list of signal handlers installed.
  1355. @type signals: C{list}
  1356. """
  1357. def setUp(self):
  1358. """
  1359. Fake C{signal.signal} for not installing the handlers but saving them
  1360. in C{self.signals}.
  1361. """
  1362. self.signals = []
  1363. def fakeSignal(sig, f):
  1364. self.signals.append((sig, f))
  1365. self.patch(signal, "signal", fakeSignal)
  1366. def test_getLogObserverStdout(self):
  1367. """
  1368. When non-daemonized and C{logfile} is empty or set to C{-},
  1369. L{UnixAppLogger._getLogObserver} returns a log observer pointing at
  1370. C{sys.stdout}.
  1371. """
  1372. logFiles = _patchTextFileLogObserver(self.patch)
  1373. logger = UnixAppLogger({"logfile": "-", "nodaemon": True})
  1374. logger._getLogObserver()
  1375. self.assertEqual(len(logFiles), 1)
  1376. self.assertIs(logFiles[0], sys.stdout)
  1377. logger = UnixAppLogger({"logfile": "", "nodaemon": True})
  1378. logger._getLogObserver()
  1379. self.assertEqual(len(logFiles), 2)
  1380. self.assertIs(logFiles[1], sys.stdout)
  1381. def test_getLogObserverStdoutDaemon(self):
  1382. """
  1383. When daemonized and C{logfile} is set to C{-},
  1384. L{UnixAppLogger._getLogObserver} raises C{SystemExit}.
  1385. """
  1386. logger = UnixAppLogger({"logfile": "-", "nodaemon": False})
  1387. error = self.assertRaises(SystemExit, logger._getLogObserver)
  1388. self.assertEqual(str(error), "Daemons cannot log to stdout, exiting!")
  1389. def test_getLogObserverFile(self):
  1390. """
  1391. When C{logfile} contains a file name, L{app.AppLogger._getLogObserver}
  1392. returns a log observer pointing at the specified path, and a signal
  1393. handler rotating the log is installed.
  1394. """
  1395. logFiles = _patchTextFileLogObserver(self.patch)
  1396. filename = self.mktemp()
  1397. sut = UnixAppLogger({"logfile": filename})
  1398. observer = sut._getLogObserver()
  1399. self.addCleanup(observer._outFile.close)
  1400. self.assertEqual(len(logFiles), 1)
  1401. self.assertEqual(logFiles[0].path, os.path.abspath(filename))
  1402. self.assertEqual(len(self.signals), 1)
  1403. self.assertEqual(self.signals[0][0], signal.SIGUSR1)
  1404. d = Deferred()
  1405. def rotate():
  1406. d.callback(None)
  1407. logFiles[0].rotate = rotate
  1408. rotateLog = self.signals[0][1]
  1409. rotateLog(None, None)
  1410. return d
  1411. def test_getLogObserverDontOverrideSignalHandler(self):
  1412. """
  1413. If a signal handler is already installed,
  1414. L{UnixAppLogger._getLogObserver} doesn't override it.
  1415. """
  1416. def fakeGetSignal(sig):
  1417. self.assertEqual(sig, signal.SIGUSR1)
  1418. return object()
  1419. self.patch(signal, "getsignal", fakeGetSignal)
  1420. filename = self.mktemp()
  1421. sut = UnixAppLogger({"logfile": filename})
  1422. observer = sut._getLogObserver()
  1423. self.addCleanup(observer._outFile.close)
  1424. self.assertEqual(self.signals, [])
  1425. def test_getLogObserverDefaultFile(self):
  1426. """
  1427. When daemonized and C{logfile} is empty, the observer returned by
  1428. L{UnixAppLogger._getLogObserver} points at C{twistd.log} in the current
  1429. directory.
  1430. """
  1431. logFiles = _patchTextFileLogObserver(self.patch)
  1432. logger = UnixAppLogger({"logfile": "", "nodaemon": False})
  1433. logger._getLogObserver()
  1434. self.assertEqual(len(logFiles), 1)
  1435. self.assertEqual(logFiles[0].path, os.path.abspath("twistd.log"))
  1436. @skipIf(not _twistd_unix, "twistd unix not available")
  1437. def test_getLogObserverSyslog(self):
  1438. """
  1439. If C{syslog} is set to C{True}, L{UnixAppLogger._getLogObserver} starts
  1440. a L{syslog.SyslogObserver} with given C{prefix}.
  1441. """
  1442. logs = _setupSyslog(self)
  1443. logger = UnixAppLogger({"syslog": True, "prefix": "test-prefix"})
  1444. observer = logger._getLogObserver()
  1445. self.assertEqual(logs, ["test-prefix"])
  1446. observer({"a": "b"})
  1447. self.assertEqual(logs, ["test-prefix", {"a": "b"}])
  1448. @skipIf(not _twistd_unix, "twistd unix support not available")
  1449. class DaemonizeTests(TestCase):
  1450. """
  1451. Tests for L{_twistd_unix.UnixApplicationRunner} daemonization.
  1452. """
  1453. def setUp(self):
  1454. self.mockos = MockOS()
  1455. self.config = twistd.ServerOptions()
  1456. self.patch(_twistd_unix, "os", self.mockos)
  1457. self.runner = _twistd_unix.UnixApplicationRunner(self.config)
  1458. self.runner.application = service.Application("Hi!")
  1459. self.runner.oldstdout = sys.stdout
  1460. self.runner.oldstderr = sys.stderr
  1461. self.runner.startReactor = lambda *args: None
  1462. def test_success(self):
  1463. """
  1464. When double fork succeeded in C{daemonize}, the child process writes
  1465. B{0} to the status pipe.
  1466. """
  1467. with AlternateReactor(FakeDaemonizingReactor()):
  1468. self.runner.postApplication()
  1469. self.assertEqual(
  1470. self.mockos.actions,
  1471. [
  1472. ("chdir", "."),
  1473. ("umask", 0o077),
  1474. ("fork", True),
  1475. "setsid",
  1476. ("fork", True),
  1477. ("write", -2, b"0"),
  1478. ("unlink", "twistd.pid"),
  1479. ],
  1480. )
  1481. self.assertEqual(self.mockos.closed, [-3, -2])
  1482. def test_successInParent(self):
  1483. """
  1484. The parent process initiating the C{daemonize} call reads data from the
  1485. status pipe and then exit the process.
  1486. """
  1487. self.mockos.child = False
  1488. self.mockos.readData = b"0"
  1489. with AlternateReactor(FakeDaemonizingReactor()):
  1490. self.assertRaises(SystemError, self.runner.postApplication)
  1491. self.assertEqual(
  1492. self.mockos.actions,
  1493. [
  1494. ("chdir", "."),
  1495. ("umask", 0o077),
  1496. ("fork", True),
  1497. ("read", -1, 100),
  1498. ("exit", 0),
  1499. ("unlink", "twistd.pid"),
  1500. ],
  1501. )
  1502. self.assertEqual(self.mockos.closed, [-1])
  1503. def test_successEINTR(self):
  1504. """
  1505. If the C{os.write} call to the status pipe raises an B{EINTR} error,
  1506. the process child retries to write.
  1507. """
  1508. written = []
  1509. def raisingWrite(fd, data):
  1510. written.append((fd, data))
  1511. if len(written) == 1:
  1512. raise OSError(errno.EINTR)
  1513. self.mockos.write = raisingWrite
  1514. with AlternateReactor(FakeDaemonizingReactor()):
  1515. self.runner.postApplication()
  1516. self.assertEqual(
  1517. self.mockos.actions,
  1518. [
  1519. ("chdir", "."),
  1520. ("umask", 0o077),
  1521. ("fork", True),
  1522. "setsid",
  1523. ("fork", True),
  1524. ("unlink", "twistd.pid"),
  1525. ],
  1526. )
  1527. self.assertEqual(self.mockos.closed, [-3, -2])
  1528. self.assertEqual([(-2, b"0"), (-2, b"0")], written)
  1529. def test_successInParentEINTR(self):
  1530. """
  1531. If the C{os.read} call on the status pipe raises an B{EINTR} error, the
  1532. parent child retries to read.
  1533. """
  1534. read = []
  1535. def raisingRead(fd, size):
  1536. read.append((fd, size))
  1537. if len(read) == 1:
  1538. raise OSError(errno.EINTR)
  1539. return b"0"
  1540. self.mockos.read = raisingRead
  1541. self.mockos.child = False
  1542. with AlternateReactor(FakeDaemonizingReactor()):
  1543. self.assertRaises(SystemError, self.runner.postApplication)
  1544. self.assertEqual(
  1545. self.mockos.actions,
  1546. [
  1547. ("chdir", "."),
  1548. ("umask", 0o077),
  1549. ("fork", True),
  1550. ("exit", 0),
  1551. ("unlink", "twistd.pid"),
  1552. ],
  1553. )
  1554. self.assertEqual(self.mockos.closed, [-1])
  1555. self.assertEqual([(-1, 100), (-1, 100)], read)
  1556. def assertErrorWritten(self, raised, reported):
  1557. """
  1558. Assert L{UnixApplicationRunner.postApplication} writes
  1559. C{reported} to its status pipe if the service raises an
  1560. exception whose message is C{raised}.
  1561. """
  1562. class FakeService(service.Service):
  1563. def startService(self):
  1564. raise RuntimeError(raised)
  1565. errorService = FakeService()
  1566. errorService.setServiceParent(self.runner.application)
  1567. with AlternateReactor(FakeDaemonizingReactor()):
  1568. self.assertRaises(RuntimeError, self.runner.postApplication)
  1569. self.assertEqual(
  1570. self.mockos.actions,
  1571. [
  1572. ("chdir", "."),
  1573. ("umask", 0o077),
  1574. ("fork", True),
  1575. "setsid",
  1576. ("fork", True),
  1577. ("write", -2, reported),
  1578. ("unlink", "twistd.pid"),
  1579. ],
  1580. )
  1581. self.assertEqual(self.mockos.closed, [-3, -2])
  1582. def test_error(self):
  1583. """
  1584. If an error happens during daemonization, the child process writes the
  1585. exception error to the status pipe.
  1586. """
  1587. self.assertErrorWritten(
  1588. raised="Something is wrong", reported=b"1 RuntimeError: Something is wrong"
  1589. )
  1590. def test_unicodeError(self):
  1591. """
  1592. If an error happens during daemonization, and that error's
  1593. message is Unicode, the child encodes the message as ascii
  1594. with backslash Unicode code points.
  1595. """
  1596. self.assertErrorWritten(raised="\u2022", reported=b"1 RuntimeError: \\u2022")
  1597. def assertErrorInParentBehavior(self, readData, errorMessage, mockOSActions):
  1598. """
  1599. Make L{os.read} appear to return C{readData}, and assert that
  1600. L{UnixApplicationRunner.postApplication} writes
  1601. C{errorMessage} to standard error and executes the calls
  1602. against L{os} functions specified in C{mockOSActions}.
  1603. """
  1604. self.mockos.child = False
  1605. self.mockos.readData = readData
  1606. errorIO = StringIO()
  1607. self.patch(sys, "__stderr__", errorIO)
  1608. with AlternateReactor(FakeDaemonizingReactor()):
  1609. self.assertRaises(SystemError, self.runner.postApplication)
  1610. self.assertEqual(errorIO.getvalue(), errorMessage)
  1611. self.assertEqual(self.mockos.actions, mockOSActions)
  1612. self.assertEqual(self.mockos.closed, [-1])
  1613. def test_errorInParent(self):
  1614. """
  1615. When the child writes an error message to the status pipe
  1616. during daemonization, the parent writes the repr of the
  1617. message to C{stderr} and exits with non-zero status code.
  1618. """
  1619. self.assertErrorInParentBehavior(
  1620. readData=b"1 Exception: An identified error",
  1621. errorMessage=(
  1622. "An error has occurred: b'Exception: An identified error'\n"
  1623. "Please look at log file for more information.\n"
  1624. ),
  1625. mockOSActions=[
  1626. ("chdir", "."),
  1627. ("umask", 0o077),
  1628. ("fork", True),
  1629. ("read", -1, 100),
  1630. ("exit", 1),
  1631. ("unlink", "twistd.pid"),
  1632. ],
  1633. )
  1634. def test_nonASCIIErrorInParent(self):
  1635. """
  1636. When the child writes a non-ASCII error message to the status
  1637. pipe during daemonization, the parent writes the repr of the
  1638. message to C{stderr} and exits with a non-zero status code.
  1639. """
  1640. self.assertErrorInParentBehavior(
  1641. readData=b"1 Exception: \xff",
  1642. errorMessage=(
  1643. "An error has occurred: b'Exception: \\xff'\n"
  1644. "Please look at log file for more information.\n"
  1645. ),
  1646. mockOSActions=[
  1647. ("chdir", "."),
  1648. ("umask", 0o077),
  1649. ("fork", True),
  1650. ("read", -1, 100),
  1651. ("exit", 1),
  1652. ("unlink", "twistd.pid"),
  1653. ],
  1654. )
  1655. def test_errorInParentWithTruncatedUnicode(self):
  1656. """
  1657. When the child writes a non-ASCII error message to the status
  1658. pipe during daemonization, and that message is too longer, the
  1659. parent writes the repr of the truncated message to C{stderr}
  1660. and exits with a non-zero status code.
  1661. """
  1662. truncatedMessage = b"1 RuntimeError: " + b"\\u2022" * 14
  1663. # the escape sequence will appear to be escaped twice, because
  1664. # we're getting the repr
  1665. reportedMessage = "b'RuntimeError: {}'".format(r"\\u2022" * 14)
  1666. self.assertErrorInParentBehavior(
  1667. readData=truncatedMessage,
  1668. errorMessage=(
  1669. "An error has occurred: {}\n"
  1670. "Please look at log file for more information.\n".format(
  1671. reportedMessage
  1672. )
  1673. ),
  1674. mockOSActions=[
  1675. ("chdir", "."),
  1676. ("umask", 0o077),
  1677. ("fork", True),
  1678. ("read", -1, 100),
  1679. ("exit", 1),
  1680. ("unlink", "twistd.pid"),
  1681. ],
  1682. )
  1683. def test_errorMessageTruncated(self):
  1684. """
  1685. If an error occurs during daemonization and its message is too
  1686. long, it's truncated by the child.
  1687. """
  1688. self.assertErrorWritten(
  1689. raised="x" * 200, reported=b"1 RuntimeError: " + b"x" * 84
  1690. )
  1691. def test_unicodeErrorMessageTruncated(self):
  1692. """
  1693. If an error occurs during daemonization and its message is
  1694. unicode and too long, it's truncated by the child, even if
  1695. this splits a unicode escape sequence.
  1696. """
  1697. self.assertErrorWritten(
  1698. raised="\u2022" * 30,
  1699. reported=b"1 RuntimeError: " + b"\\u2022" * 14,
  1700. )
  1701. def test_hooksCalled(self):
  1702. """
  1703. C{daemonize} indeed calls L{IReactorDaemonize.beforeDaemonize} and
  1704. L{IReactorDaemonize.afterDaemonize} if the reactor implements
  1705. L{IReactorDaemonize}.
  1706. """
  1707. reactor = FakeDaemonizingReactor()
  1708. self.runner.daemonize(reactor)
  1709. self.assertTrue(reactor._beforeDaemonizeCalled)
  1710. self.assertTrue(reactor._afterDaemonizeCalled)
  1711. def test_hooksNotCalled(self):
  1712. """
  1713. C{daemonize} does NOT call L{IReactorDaemonize.beforeDaemonize} or
  1714. L{IReactorDaemonize.afterDaemonize} if the reactor does NOT implement
  1715. L{IReactorDaemonize}.
  1716. """
  1717. reactor = FakeNonDaemonizingReactor()
  1718. self.runner.daemonize(reactor)
  1719. self.assertFalse(reactor._beforeDaemonizeCalled)
  1720. self.assertFalse(reactor._afterDaemonizeCalled)
  1721. @implementer(_ISupportsExitSignalCapturing)
  1722. class SignalCapturingMemoryReactor(MemoryReactor):
  1723. """
  1724. MemoryReactor that implements the _ISupportsExitSignalCapturing interface,
  1725. all other operations identical to MemoryReactor.
  1726. """
  1727. @property
  1728. def _exitSignal(self):
  1729. return self._val
  1730. @_exitSignal.setter
  1731. def _exitSignal(self, val):
  1732. self._val = val
  1733. class StubApplicationRunnerWithSignal(twistd._SomeApplicationRunner):
  1734. """
  1735. An application runner that uses a SignalCapturingMemoryReactor and
  1736. has a _signalValue attribute that it will set in the reactor.
  1737. @ivar _signalValue: The signal value to set on the reactor's _exitSignal
  1738. attribute.
  1739. """
  1740. loggerFactory = CrippledAppLogger
  1741. def __init__(self, config):
  1742. super().__init__(config)
  1743. self._signalValue = None
  1744. def preApplication(self):
  1745. """
  1746. Does nothing.
  1747. """
  1748. def postApplication(self):
  1749. """
  1750. Instantiate a SignalCapturingMemoryReactor and start it
  1751. in the runner.
  1752. """
  1753. reactor = SignalCapturingMemoryReactor()
  1754. reactor._exitSignal = self._signalValue
  1755. self.startReactor(reactor, sys.stdout, sys.stderr)
  1756. def stubApplicationRunnerFactoryCreator(signum):
  1757. """
  1758. Create a factory function to instantiate a
  1759. StubApplicationRunnerWithSignal that will report signum as the captured
  1760. signal..
  1761. @param signum: The integer signal number or None
  1762. @type signum: C{int} or C{None}
  1763. @return: A factory function to create stub runners.
  1764. @rtype: stubApplicationRunnerFactory
  1765. """
  1766. def stubApplicationRunnerFactory(config):
  1767. """
  1768. Create a StubApplicationRunnerWithSignal using a reactor that
  1769. implements _ISupportsExitSignalCapturing and whose _exitSignal
  1770. attribute is set to signum.
  1771. @param config: The runner configuration, platform dependent.
  1772. @type config: L{twisted.scripts.twistd.ServerOptions}
  1773. @return: A runner to use for the test.
  1774. @rtype: twisted.test.test_twistd.StubApplicationRunnerWithSignal
  1775. """
  1776. runner = StubApplicationRunnerWithSignal(config)
  1777. runner._signalValue = signum
  1778. return runner
  1779. return stubApplicationRunnerFactory
  1780. class ExitWithSignalTests(TestCase):
  1781. """
  1782. Tests for L{twisted.application.app._exitWithSignal}.
  1783. """
  1784. def setUp(self):
  1785. """
  1786. Set up the server options and a fake for use by test cases.
  1787. """
  1788. self.config = twistd.ServerOptions()
  1789. self.config.loadedPlugins = {"test_command": MockServiceMaker()}
  1790. self.config.subOptions = object()
  1791. self.config.subCommand = "test_command"
  1792. self.fakeKillArgs = [None, None]
  1793. def fakeKill(pid, sig):
  1794. """
  1795. Fake method to capture arguments passed to os.kill.
  1796. @param pid: The pid of the process being killed.
  1797. @param sig: The signal sent to the process.
  1798. """
  1799. self.fakeKillArgs[0] = pid
  1800. self.fakeKillArgs[1] = sig
  1801. self.patch(os, "kill", fakeKill)
  1802. def test_exitWithSignal(self):
  1803. """
  1804. exitWithSignal replaces the existing signal handler with the default
  1805. handler and sends the replaced signal to the current process.
  1806. """
  1807. fakeSignalArgs = [None, None]
  1808. def fake_signal(sig, handler):
  1809. fakeSignalArgs[0] = sig
  1810. fakeSignalArgs[1] = handler
  1811. self.patch(signal, "signal", fake_signal)
  1812. app._exitWithSignal(signal.SIGINT)
  1813. self.assertEquals(fakeSignalArgs[0], signal.SIGINT)
  1814. self.assertEquals(fakeSignalArgs[1], signal.SIG_DFL)
  1815. self.assertEquals(self.fakeKillArgs[0], os.getpid())
  1816. self.assertEquals(self.fakeKillArgs[1], signal.SIGINT)
  1817. def test_normalExit(self):
  1818. """
  1819. _exitWithSignal is not called if the runner does not exit with a
  1820. signal.
  1821. """
  1822. self.patch(
  1823. twistd, "_SomeApplicationRunner", stubApplicationRunnerFactoryCreator(None)
  1824. )
  1825. twistd.runApp(self.config)
  1826. self.assertIsNone(self.fakeKillArgs[0])
  1827. self.assertIsNone(self.fakeKillArgs[1])
  1828. def test_runnerExitsWithSignal(self):
  1829. """
  1830. _exitWithSignal is called when the runner exits with a signal.
  1831. """
  1832. self.patch(
  1833. twistd,
  1834. "_SomeApplicationRunner",
  1835. stubApplicationRunnerFactoryCreator(signal.SIGINT),
  1836. )
  1837. twistd.runApp(self.config)
  1838. self.assertEquals(self.fakeKillArgs[0], os.getpid())
  1839. self.assertEquals(self.fakeKillArgs[1], signal.SIGINT)