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_logfile.py 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. import contextlib
  4. import errno
  5. import os
  6. import stat
  7. import time
  8. from unittest import skipIf
  9. from twisted.python import logfile, runtime
  10. from twisted.trial.unittest import TestCase
  11. class LogFileTests(TestCase):
  12. """
  13. Test the rotating log file.
  14. """
  15. def setUp(self):
  16. self.dir = self.mktemp()
  17. os.makedirs(self.dir)
  18. self.name = "test.log"
  19. self.path = os.path.join(self.dir, self.name)
  20. def tearDown(self):
  21. """
  22. Restore back write rights on created paths: if tests modified the
  23. rights, that will allow the paths to be removed easily afterwards.
  24. """
  25. os.chmod(self.dir, 0o777)
  26. if os.path.exists(self.path):
  27. os.chmod(self.path, 0o777)
  28. def test_abstractShouldRotate(self):
  29. """
  30. L{BaseLogFile.shouldRotate} is abstract and must be implemented by
  31. subclass.
  32. """
  33. log = logfile.BaseLogFile(self.name, self.dir)
  34. self.addCleanup(log.close)
  35. self.assertRaises(NotImplementedError, log.shouldRotate)
  36. def test_writing(self):
  37. """
  38. Log files can be written to, flushed and closed. Closing a log file
  39. also flushes it.
  40. """
  41. with contextlib.closing(logfile.LogFile(self.name, self.dir)) as log:
  42. log.write("123")
  43. log.write("456")
  44. log.flush()
  45. log.write("7890")
  46. with open(self.path) as f:
  47. self.assertEqual(f.read(), "1234567890")
  48. def test_rotation(self):
  49. """
  50. Rotating log files autorotate after a period of time, and can also be
  51. manually rotated.
  52. """
  53. # this logfile should rotate every 10 bytes
  54. with contextlib.closing(
  55. logfile.LogFile(self.name, self.dir, rotateLength=10)
  56. ) as log:
  57. # test automatic rotation
  58. log.write("123")
  59. log.write("4567890")
  60. log.write("1" * 11)
  61. self.assertTrue(os.path.exists(f"{self.path}.1"))
  62. self.assertFalse(os.path.exists(f"{self.path}.2"))
  63. log.write("")
  64. self.assertTrue(os.path.exists(f"{self.path}.1"))
  65. self.assertTrue(os.path.exists(f"{self.path}.2"))
  66. self.assertFalse(os.path.exists(f"{self.path}.3"))
  67. log.write("3")
  68. self.assertFalse(os.path.exists(f"{self.path}.3"))
  69. # test manual rotation
  70. log.rotate()
  71. self.assertTrue(os.path.exists(f"{self.path}.3"))
  72. self.assertFalse(os.path.exists(f"{self.path}.4"))
  73. self.assertEqual(log.listLogs(), [1, 2, 3])
  74. def test_append(self):
  75. """
  76. Log files can be written to, closed. Their size is the number of
  77. bytes written to them. Everything that was written to them can
  78. be read, even if the writing happened on separate occasions,
  79. and even if the log file was closed in between.
  80. """
  81. with contextlib.closing(logfile.LogFile(self.name, self.dir)) as log:
  82. log.write("0123456789")
  83. log = logfile.LogFile(self.name, self.dir)
  84. self.addCleanup(log.close)
  85. self.assertEqual(log.size, 10)
  86. self.assertEqual(log._file.tell(), log.size)
  87. log.write("abc")
  88. self.assertEqual(log.size, 13)
  89. self.assertEqual(log._file.tell(), log.size)
  90. f = log._file
  91. f.seek(0, 0)
  92. self.assertEqual(f.read(), b"0123456789abc")
  93. def test_logReader(self):
  94. """
  95. Various tests for log readers.
  96. First of all, log readers can get logs by number and read what
  97. was written to those log files. Getting nonexistent log files
  98. raises C{ValueError}. Using anything other than an integer
  99. index raises C{TypeError}. As logs get older, their log
  100. numbers increase.
  101. """
  102. log = logfile.LogFile(self.name, self.dir)
  103. self.addCleanup(log.close)
  104. log.write("abc\n")
  105. log.write("def\n")
  106. log.rotate()
  107. log.write("ghi\n")
  108. log.flush()
  109. # check reading logs
  110. self.assertEqual(log.listLogs(), [1])
  111. with contextlib.closing(log.getCurrentLog()) as reader:
  112. reader._file.seek(0)
  113. self.assertEqual(reader.readLines(), ["ghi\n"])
  114. self.assertEqual(reader.readLines(), [])
  115. with contextlib.closing(log.getLog(1)) as reader:
  116. self.assertEqual(reader.readLines(), ["abc\n", "def\n"])
  117. self.assertEqual(reader.readLines(), [])
  118. # check getting illegal log readers
  119. self.assertRaises(ValueError, log.getLog, 2)
  120. self.assertRaises(TypeError, log.getLog, "1")
  121. # check that log numbers are higher for older logs
  122. log.rotate()
  123. self.assertEqual(log.listLogs(), [1, 2])
  124. with contextlib.closing(log.getLog(1)) as reader:
  125. reader._file.seek(0)
  126. self.assertEqual(reader.readLines(), ["ghi\n"])
  127. self.assertEqual(reader.readLines(), [])
  128. with contextlib.closing(log.getLog(2)) as reader:
  129. self.assertEqual(reader.readLines(), ["abc\n", "def\n"])
  130. self.assertEqual(reader.readLines(), [])
  131. def test_LogReaderReadsZeroLine(self):
  132. """
  133. L{LogReader.readLines} supports reading no line.
  134. """
  135. # We don't need any content, just a file path that can be opened.
  136. with open(self.path, "w"):
  137. pass
  138. reader = logfile.LogReader(self.path)
  139. self.addCleanup(reader.close)
  140. self.assertEqual([], reader.readLines(0))
  141. def test_modePreservation(self):
  142. """
  143. Check rotated files have same permissions as original.
  144. """
  145. open(self.path, "w").close()
  146. os.chmod(self.path, 0o707)
  147. mode = os.stat(self.path)[stat.ST_MODE]
  148. log = logfile.LogFile(self.name, self.dir)
  149. self.addCleanup(log.close)
  150. log.write("abc")
  151. log.rotate()
  152. self.assertEqual(mode, os.stat(self.path)[stat.ST_MODE])
  153. def test_noPermission(self):
  154. """
  155. Check it keeps working when permission on dir changes.
  156. """
  157. log = logfile.LogFile(self.name, self.dir)
  158. self.addCleanup(log.close)
  159. log.write("abc")
  160. # change permissions so rotation would fail
  161. os.chmod(self.dir, 0o555)
  162. # if this succeeds, chmod doesn't restrict us, so we can't
  163. # do the test
  164. try:
  165. f = open(os.path.join(self.dir, "xxx"), "w")
  166. except OSError:
  167. pass
  168. else:
  169. f.close()
  170. return
  171. log.rotate() # this should not fail
  172. log.write("def")
  173. log.flush()
  174. f = log._file
  175. self.assertEqual(f.tell(), 6)
  176. f.seek(0, 0)
  177. self.assertEqual(f.read(), b"abcdef")
  178. def test_maxNumberOfLog(self):
  179. """
  180. Test it respect the limit on the number of files when maxRotatedFiles
  181. is not None.
  182. """
  183. log = logfile.LogFile(self.name, self.dir, rotateLength=10, maxRotatedFiles=3)
  184. self.addCleanup(log.close)
  185. log.write("1" * 11)
  186. log.write("2" * 11)
  187. self.assertTrue(os.path.exists(f"{self.path}.1"))
  188. log.write("3" * 11)
  189. self.assertTrue(os.path.exists(f"{self.path}.2"))
  190. log.write("4" * 11)
  191. self.assertTrue(os.path.exists(f"{self.path}.3"))
  192. with open(f"{self.path}.3") as fp:
  193. self.assertEqual(fp.read(), "1" * 11)
  194. log.write("5" * 11)
  195. with open(f"{self.path}.3") as fp:
  196. self.assertEqual(fp.read(), "2" * 11)
  197. self.assertFalse(os.path.exists(f"{self.path}.4"))
  198. def test_fromFullPath(self):
  199. """
  200. Test the fromFullPath method.
  201. """
  202. log1 = logfile.LogFile(self.name, self.dir, 10, defaultMode=0o777)
  203. self.addCleanup(log1.close)
  204. log2 = logfile.LogFile.fromFullPath(self.path, 10, defaultMode=0o777)
  205. self.addCleanup(log2.close)
  206. self.assertEqual(log1.name, log2.name)
  207. self.assertEqual(os.path.abspath(log1.path), log2.path)
  208. self.assertEqual(log1.rotateLength, log2.rotateLength)
  209. self.assertEqual(log1.defaultMode, log2.defaultMode)
  210. def test_defaultPermissions(self):
  211. """
  212. Test the default permission of the log file: if the file exist, it
  213. should keep the permission.
  214. """
  215. with open(self.path, "wb"):
  216. os.chmod(self.path, 0o707)
  217. currentMode = stat.S_IMODE(os.stat(self.path)[stat.ST_MODE])
  218. log1 = logfile.LogFile(self.name, self.dir)
  219. self.assertEqual(stat.S_IMODE(os.stat(self.path)[stat.ST_MODE]), currentMode)
  220. self.addCleanup(log1.close)
  221. def test_specifiedPermissions(self):
  222. """
  223. Test specifying the permissions used on the log file.
  224. """
  225. log1 = logfile.LogFile(self.name, self.dir, defaultMode=0o066)
  226. self.addCleanup(log1.close)
  227. mode = stat.S_IMODE(os.stat(self.path)[stat.ST_MODE])
  228. if runtime.platform.isWindows():
  229. # The only thing we can get here is global read-only
  230. self.assertEqual(mode, 0o444)
  231. else:
  232. self.assertEqual(mode, 0o066)
  233. @skipIf(runtime.platform.isWindows(), "Can't test reopen on Windows")
  234. def test_reopen(self):
  235. """
  236. L{logfile.LogFile.reopen} allows to rename the currently used file and
  237. make L{logfile.LogFile} create a new file.
  238. """
  239. with contextlib.closing(logfile.LogFile(self.name, self.dir)) as log1:
  240. log1.write("hello1")
  241. savePath = os.path.join(self.dir, "save.log")
  242. os.rename(self.path, savePath)
  243. log1.reopen()
  244. log1.write("hello2")
  245. with open(self.path) as f:
  246. self.assertEqual(f.read(), "hello2")
  247. with open(savePath) as f:
  248. self.assertEqual(f.read(), "hello1")
  249. def test_nonExistentDir(self):
  250. """
  251. Specifying an invalid directory to L{LogFile} raises C{IOError}.
  252. """
  253. e = self.assertRaises(
  254. IOError, logfile.LogFile, self.name, "this_dir_does_not_exist"
  255. )
  256. self.assertEqual(e.errno, errno.ENOENT)
  257. def test_cantChangeFileMode(self):
  258. """
  259. Opening a L{LogFile} which can be read and write but whose mode can't
  260. be changed doesn't trigger an error.
  261. """
  262. if runtime.platform.isWindows():
  263. name, directory = "NUL", ""
  264. expectedPath = "NUL"
  265. else:
  266. name, directory = "null", "/dev"
  267. expectedPath = "/dev/null"
  268. log = logfile.LogFile(name, directory, defaultMode=0o555)
  269. self.addCleanup(log.close)
  270. self.assertEqual(log.path, expectedPath)
  271. self.assertEqual(log.defaultMode, 0o555)
  272. def test_listLogsWithBadlyNamedFiles(self):
  273. """
  274. L{LogFile.listLogs} doesn't choke if it encounters a file with an
  275. unexpected name.
  276. """
  277. log = logfile.LogFile(self.name, self.dir)
  278. self.addCleanup(log.close)
  279. with open(f"{log.path}.1", "w") as fp:
  280. fp.write("123")
  281. with open(f"{log.path}.bad-file", "w") as fp:
  282. fp.write("123")
  283. self.assertEqual([1], log.listLogs())
  284. def test_listLogsIgnoresZeroSuffixedFiles(self):
  285. """
  286. L{LogFile.listLogs} ignores log files which rotated suffix is 0.
  287. """
  288. log = logfile.LogFile(self.name, self.dir)
  289. self.addCleanup(log.close)
  290. for i in range(0, 3):
  291. with open(f"{log.path}.{i}", "w") as fp:
  292. fp.write("123")
  293. self.assertEqual([1, 2], log.listLogs())
  294. class RiggedDailyLogFile(logfile.DailyLogFile):
  295. _clock = 0.0
  296. def _openFile(self):
  297. logfile.DailyLogFile._openFile(self)
  298. # rig the date to match _clock, not mtime
  299. self.lastDate = self.toDate()
  300. def toDate(self, *args):
  301. if args:
  302. return time.gmtime(*args)[:3]
  303. return time.gmtime(self._clock)[:3]
  304. class DailyLogFileTests(TestCase):
  305. """
  306. Test rotating log file.
  307. """
  308. def setUp(self):
  309. self.dir = self.mktemp()
  310. os.makedirs(self.dir)
  311. self.name = "testdaily.log"
  312. self.path = os.path.join(self.dir, self.name)
  313. def test_writing(self):
  314. """
  315. A daily log file can be written to like an ordinary log file.
  316. """
  317. with contextlib.closing(RiggedDailyLogFile(self.name, self.dir)) as log:
  318. log.write("123")
  319. log.write("456")
  320. log.flush()
  321. log.write("7890")
  322. with open(self.path) as f:
  323. self.assertEqual(f.read(), "1234567890")
  324. def test_rotation(self):
  325. """
  326. Daily log files rotate daily.
  327. """
  328. log = RiggedDailyLogFile(self.name, self.dir)
  329. self.addCleanup(log.close)
  330. days = [(self.path + "." + log.suffix(day * 86400)) for day in range(3)]
  331. # test automatic rotation
  332. log._clock = 0.0 # 1970/01/01 00:00.00
  333. log.write("123")
  334. log._clock = 43200 # 1970/01/01 12:00.00
  335. log.write("4567890")
  336. log._clock = 86400 # 1970/01/02 00:00.00
  337. log.write("1" * 11)
  338. self.assertTrue(os.path.exists(days[0]))
  339. self.assertFalse(os.path.exists(days[1]))
  340. log._clock = 172800 # 1970/01/03 00:00.00
  341. log.write("")
  342. self.assertTrue(os.path.exists(days[0]))
  343. self.assertTrue(os.path.exists(days[1]))
  344. self.assertFalse(os.path.exists(days[2]))
  345. log._clock = 259199 # 1970/01/03 23:59.59
  346. log.write("3")
  347. self.assertFalse(os.path.exists(days[2]))
  348. def test_getLog(self):
  349. """
  350. Test retrieving log files with L{DailyLogFile.getLog}.
  351. """
  352. data = ["1\n", "2\n", "3\n"]
  353. log = RiggedDailyLogFile(self.name, self.dir)
  354. self.addCleanup(log.close)
  355. for d in data:
  356. log.write(d)
  357. log.flush()
  358. # This returns the current log file.
  359. r = log.getLog(0.0)
  360. self.addCleanup(r.close)
  361. self.assertEqual(data, r.readLines())
  362. # We can't get this log, it doesn't exist yet.
  363. self.assertRaises(ValueError, log.getLog, 86400)
  364. log._clock = 86401 # New day
  365. r.close()
  366. log.rotate()
  367. r = log.getLog(0) # We get the previous log
  368. self.addCleanup(r.close)
  369. self.assertEqual(data, r.readLines())
  370. def test_rotateAlreadyExists(self):
  371. """
  372. L{DailyLogFile.rotate} doesn't do anything if they new log file already
  373. exists on the disk.
  374. """
  375. log = RiggedDailyLogFile(self.name, self.dir)
  376. self.addCleanup(log.close)
  377. # Build a new file with the same name as the file which would be created
  378. # if the log file is to be rotated.
  379. newFilePath = f"{log.path}.{log.suffix(log.lastDate)}"
  380. with open(newFilePath, "w") as fp:
  381. fp.write("123")
  382. previousFile = log._file
  383. log.rotate()
  384. self.assertEqual(previousFile, log._file)
  385. @skipIf(
  386. runtime.platform.isWindows(),
  387. "Making read-only directories on Windows is too complex for this "
  388. "test to reasonably do.",
  389. )
  390. def test_rotatePermissionDirectoryNotOk(self):
  391. """
  392. L{DailyLogFile.rotate} doesn't do anything if the directory containing
  393. the log files can't be written to.
  394. """
  395. log = logfile.DailyLogFile(self.name, self.dir)
  396. self.addCleanup(log.close)
  397. os.chmod(log.directory, 0o444)
  398. # Restore permissions so tests can be cleaned up.
  399. self.addCleanup(os.chmod, log.directory, 0o755)
  400. previousFile = log._file
  401. log.rotate()
  402. self.assertEqual(previousFile, log._file)
  403. def test_rotatePermissionFileNotOk(self):
  404. """
  405. L{DailyLogFile.rotate} doesn't do anything if the log file can't be
  406. written to.
  407. """
  408. log = logfile.DailyLogFile(self.name, self.dir)
  409. self.addCleanup(log.close)
  410. os.chmod(log.path, 0o444)
  411. previousFile = log._file
  412. log.rotate()
  413. self.assertEqual(previousFile, log._file)
  414. def test_toDate(self):
  415. """
  416. Test that L{DailyLogFile.toDate} converts its timestamp argument to a
  417. time tuple (year, month, day).
  418. """
  419. log = logfile.DailyLogFile(self.name, self.dir)
  420. self.addCleanup(log.close)
  421. timestamp = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, 0))
  422. self.assertEqual((2000, 1, 1), log.toDate(timestamp))
  423. def test_toDateDefaultToday(self):
  424. """
  425. Test that L{DailyLogFile.toDate} returns today's date by default.
  426. By mocking L{time.localtime}, we ensure that L{DailyLogFile.toDate}
  427. returns the first 3 values of L{time.localtime} which is the current
  428. date.
  429. Note that we don't compare the *real* result of L{DailyLogFile.toDate}
  430. to the *real* current date, as there's a slight possibility that the
  431. date changes between the 2 function calls.
  432. """
  433. def mock_localtime(*args):
  434. self.assertEqual((), args)
  435. return list(range(0, 9))
  436. log = logfile.DailyLogFile(self.name, self.dir)
  437. self.addCleanup(log.close)
  438. self.patch(time, "localtime", mock_localtime)
  439. logDate = log.toDate()
  440. self.assertEqual([0, 1, 2], logDate)
  441. def test_toDateUsesArgumentsToMakeADate(self):
  442. """
  443. Test that L{DailyLogFile.toDate} uses its arguments to create a new
  444. date.
  445. """
  446. log = logfile.DailyLogFile(self.name, self.dir)
  447. self.addCleanup(log.close)
  448. date = (2014, 10, 22)
  449. seconds = time.mktime(date + (0,) * 6)
  450. logDate = log.toDate(seconds)
  451. self.assertEqual(date, logDate)