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 18KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. from __future__ import division, absolute_import
  4. import contextlib
  5. import errno
  6. import os
  7. import stat
  8. import time
  9. from twisted.trial import unittest
  10. from twisted.python import logfile, runtime
  11. class LogFileTests(unittest.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)) as log:
  56. # test automatic rotation
  57. log.write("123")
  58. log.write("4567890")
  59. log.write("1" * 11)
  60. self.assertTrue(os.path.exists("{0}.1".format(self.path)))
  61. self.assertFalse(os.path.exists("{0}.2".format(self.path)))
  62. log.write('')
  63. self.assertTrue(os.path.exists("{0}.1".format(self.path)))
  64. self.assertTrue(os.path.exists("{0}.2".format(self.path)))
  65. self.assertFalse(os.path.exists("{0}.3".format(self.path)))
  66. log.write("3")
  67. self.assertFalse(os.path.exists("{0}.3".format(self.path)))
  68. # test manual rotation
  69. log.rotate()
  70. self.assertTrue(os.path.exists("{0}.3".format(self.path)))
  71. self.assertFalse(os.path.exists("{0}.4".format(self.path)))
  72. self.assertEqual(log.listLogs(), [1, 2, 3])
  73. def test_append(self):
  74. """
  75. Log files can be written to, closed. Their size is the number of
  76. bytes written to them. Everything that was written to them can
  77. be read, even if the writing happened on separate occasions,
  78. and even if the log file was closed in between.
  79. """
  80. with contextlib.closing(logfile.LogFile(self.name, self.dir)) as log:
  81. log.write("0123456789")
  82. log = logfile.LogFile(self.name, self.dir)
  83. self.addCleanup(log.close)
  84. self.assertEqual(log.size, 10)
  85. self.assertEqual(log._file.tell(), log.size)
  86. log.write("abc")
  87. self.assertEqual(log.size, 13)
  88. self.assertEqual(log._file.tell(), log.size)
  89. f = log._file
  90. f.seek(0, 0)
  91. self.assertEqual(f.read(), b"0123456789abc")
  92. def test_logReader(self):
  93. """
  94. Various tests for log readers.
  95. First of all, log readers can get logs by number and read what
  96. was written to those log files. Getting nonexistent log files
  97. raises C{ValueError}. Using anything other than an integer
  98. index raises C{TypeError}. As logs get older, their log
  99. numbers increase.
  100. """
  101. log = logfile.LogFile(self.name, self.dir)
  102. self.addCleanup(log.close)
  103. log.write("abc\n")
  104. log.write("def\n")
  105. log.rotate()
  106. log.write("ghi\n")
  107. log.flush()
  108. # check reading logs
  109. self.assertEqual(log.listLogs(), [1])
  110. with contextlib.closing(log.getCurrentLog()) as reader:
  111. reader._file.seek(0)
  112. self.assertEqual(reader.readLines(), ["ghi\n"])
  113. self.assertEqual(reader.readLines(), [])
  114. with contextlib.closing(log.getLog(1)) as reader:
  115. self.assertEqual(reader.readLines(), ["abc\n", "def\n"])
  116. self.assertEqual(reader.readLines(), [])
  117. # check getting illegal log readers
  118. self.assertRaises(ValueError, log.getLog, 2)
  119. self.assertRaises(TypeError, log.getLog, "1")
  120. # check that log numbers are higher for older logs
  121. log.rotate()
  122. self.assertEqual(log.listLogs(), [1, 2])
  123. with contextlib.closing(log.getLog(1)) as reader:
  124. reader._file.seek(0)
  125. self.assertEqual(reader.readLines(), ["ghi\n"])
  126. self.assertEqual(reader.readLines(), [])
  127. with contextlib.closing(log.getLog(2)) as reader:
  128. self.assertEqual(reader.readLines(), ["abc\n", "def\n"])
  129. self.assertEqual(reader.readLines(), [])
  130. def test_LogReaderReadsZeroLine(self):
  131. """
  132. L{LogReader.readLines} supports reading no line.
  133. """
  134. # We don't need any content, just a file path that can be opened.
  135. with open(self.path, "w"):
  136. pass
  137. reader = logfile.LogReader(self.path)
  138. self.addCleanup(reader.close)
  139. self.assertEqual([], reader.readLines(0))
  140. def test_modePreservation(self):
  141. """
  142. Check rotated files have same permissions as original.
  143. """
  144. open(self.path, "w").close()
  145. os.chmod(self.path, 0o707)
  146. mode = os.stat(self.path)[stat.ST_MODE]
  147. log = logfile.LogFile(self.name, self.dir)
  148. self.addCleanup(log.close)
  149. log.write("abc")
  150. log.rotate()
  151. self.assertEqual(mode, os.stat(self.path)[stat.ST_MODE])
  152. def test_noPermission(self):
  153. """
  154. Check it keeps working when permission on dir changes.
  155. """
  156. log = logfile.LogFile(self.name, self.dir)
  157. self.addCleanup(log.close)
  158. log.write("abc")
  159. # change permissions so rotation would fail
  160. os.chmod(self.dir, 0o555)
  161. # if this succeeds, chmod doesn't restrict us, so we can't
  162. # do the test
  163. try:
  164. f = open(os.path.join(self.dir,"xxx"), "w")
  165. except (OSError, IOError):
  166. pass
  167. else:
  168. f.close()
  169. return
  170. log.rotate() # this should not fail
  171. log.write("def")
  172. log.flush()
  173. f = log._file
  174. self.assertEqual(f.tell(), 6)
  175. f.seek(0, 0)
  176. self.assertEqual(f.read(), b"abcdef")
  177. def test_maxNumberOfLog(self):
  178. """
  179. Test it respect the limit on the number of files when maxRotatedFiles
  180. is not None.
  181. """
  182. log = logfile.LogFile(self.name, self.dir, rotateLength=10,
  183. maxRotatedFiles=3)
  184. self.addCleanup(log.close)
  185. log.write("1" * 11)
  186. log.write("2" * 11)
  187. self.assertTrue(os.path.exists("{0}.1".format(self.path)))
  188. log.write("3" * 11)
  189. self.assertTrue(os.path.exists("{0}.2".format(self.path)))
  190. log.write("4" * 11)
  191. self.assertTrue(os.path.exists("{0}.3".format(self.path)))
  192. with open("{0}.3".format(self.path)) as fp:
  193. self.assertEqual(fp.read(), "1" * 11)
  194. log.write("5" * 11)
  195. with open("{0}.3".format(self.path)) as fp:
  196. self.assertEqual(fp.read(), "2" * 11)
  197. self.assertFalse(os.path.exists("{0}.4".format(self.path)))
  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]),
  220. currentMode)
  221. self.addCleanup(log1.close)
  222. def test_specifiedPermissions(self):
  223. """
  224. Test specifying the permissions used on the log file.
  225. """
  226. log1 = logfile.LogFile(self.name, self.dir, defaultMode=0o066)
  227. self.addCleanup(log1.close)
  228. mode = stat.S_IMODE(os.stat(self.path)[stat.ST_MODE])
  229. if runtime.platform.isWindows():
  230. # The only thing we can get here is global read-only
  231. self.assertEqual(mode, 0o444)
  232. else:
  233. self.assertEqual(mode, 0o066)
  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. if runtime.platform.isWindows():
  250. test_reopen.skip = "Can't test reopen on Windows"
  251. def test_nonExistentDir(self):
  252. """
  253. Specifying an invalid directory to L{LogFile} raises C{IOError}.
  254. """
  255. e = self.assertRaises(
  256. IOError, logfile.LogFile, self.name, 'this_dir_does_not_exist')
  257. self.assertEqual(e.errno, errno.ENOENT)
  258. def test_cantChangeFileMode(self):
  259. """
  260. Opening a L{LogFile} which can be read and write but whose mode can't
  261. be changed doesn't trigger an error.
  262. """
  263. if runtime.platform.isWindows():
  264. name, directory = "NUL", ""
  265. expectedPath = "NUL"
  266. else:
  267. name, directory = "null", "/dev"
  268. expectedPath = "/dev/null"
  269. log = logfile.LogFile(name, directory, defaultMode=0o555)
  270. self.addCleanup(log.close)
  271. self.assertEqual(log.path, expectedPath)
  272. self.assertEqual(log.defaultMode, 0o555)
  273. def test_listLogsWithBadlyNamedFiles(self):
  274. """
  275. L{LogFile.listLogs} doesn't choke if it encounters a file with an
  276. unexpected name.
  277. """
  278. log = logfile.LogFile(self.name, self.dir)
  279. self.addCleanup(log.close)
  280. with open("{0}.1".format(log.path), "w") as fp:
  281. fp.write("123")
  282. with open("{0}.bad-file".format(log.path), "w") as fp:
  283. fp.write("123")
  284. self.assertEqual([1], log.listLogs())
  285. def test_listLogsIgnoresZeroSuffixedFiles(self):
  286. """
  287. L{LogFile.listLogs} ignores log files which rotated suffix is 0.
  288. """
  289. log = logfile.LogFile(self.name, self.dir)
  290. self.addCleanup(log.close)
  291. for i in range(0, 3):
  292. with open("{0}.{1}".format(log.path, i), "w") as fp:
  293. fp.write("123")
  294. self.assertEqual([1, 2], log.listLogs())
  295. class RiggedDailyLogFile(logfile.DailyLogFile):
  296. _clock = 0.0
  297. def _openFile(self):
  298. logfile.DailyLogFile._openFile(self)
  299. # rig the date to match _clock, not mtime
  300. self.lastDate = self.toDate()
  301. def toDate(self, *args):
  302. if args:
  303. return time.gmtime(*args)[:3]
  304. return time.gmtime(self._clock)[:3]
  305. class DailyLogFileTests(unittest.TestCase):
  306. """
  307. Test rotating log file.
  308. """
  309. def setUp(self):
  310. self.dir = self.mktemp()
  311. os.makedirs(self.dir)
  312. self.name = "testdaily.log"
  313. self.path = os.path.join(self.dir, self.name)
  314. def test_writing(self):
  315. """
  316. A daily log file can be written to like an ordinary log file.
  317. """
  318. with contextlib.closing(RiggedDailyLogFile(self.name, self.dir)) as log:
  319. log.write("123")
  320. log.write("456")
  321. log.flush()
  322. log.write("7890")
  323. with open(self.path) as f:
  324. self.assertEqual(f.read(), "1234567890")
  325. def test_rotation(self):
  326. """
  327. Daily log files rotate daily.
  328. """
  329. log = RiggedDailyLogFile(self.name, self.dir)
  330. self.addCleanup(log.close)
  331. days = [(self.path + '.' + log.suffix(day * 86400)) for day in range(3)]
  332. # test automatic rotation
  333. log._clock = 0.0 # 1970/01/01 00:00.00
  334. log.write("123")
  335. log._clock = 43200 # 1970/01/01 12:00.00
  336. log.write("4567890")
  337. log._clock = 86400 # 1970/01/02 00:00.00
  338. log.write("1" * 11)
  339. self.assertTrue(os.path.exists(days[0]))
  340. self.assertFalse(os.path.exists(days[1]))
  341. log._clock = 172800 # 1970/01/03 00:00.00
  342. log.write('')
  343. self.assertTrue(os.path.exists(days[0]))
  344. self.assertTrue(os.path.exists(days[1]))
  345. self.assertFalse(os.path.exists(days[2]))
  346. log._clock = 259199 # 1970/01/03 23:59.59
  347. log.write("3")
  348. self.assertFalse(os.path.exists(days[2]))
  349. def test_getLog(self):
  350. """
  351. Test retrieving log files with L{DailyLogFile.getLog}.
  352. """
  353. data = ["1\n", "2\n", "3\n"]
  354. log = RiggedDailyLogFile(self.name, self.dir)
  355. self.addCleanup(log.close)
  356. for d in data:
  357. log.write(d)
  358. log.flush()
  359. # This returns the current log file.
  360. r = log.getLog(0.0)
  361. self.addCleanup(r.close)
  362. self.assertEqual(data, r.readLines())
  363. # We can't get this log, it doesn't exist yet.
  364. self.assertRaises(ValueError, log.getLog, 86400)
  365. log._clock = 86401 # New day
  366. r.close()
  367. log.rotate()
  368. r = log.getLog(0) # We get the previous log
  369. self.addCleanup(r.close)
  370. self.assertEqual(data, r.readLines())
  371. def test_rotateAlreadyExists(self):
  372. """
  373. L{DailyLogFile.rotate} doesn't do anything if they new log file already
  374. exists on the disk.
  375. """
  376. log = RiggedDailyLogFile(self.name, self.dir)
  377. self.addCleanup(log.close)
  378. # Build a new file with the same name as the file which would be created
  379. # if the log file is to be rotated.
  380. newFilePath = "{0}.{1}".format(log.path, log.suffix(log.lastDate))
  381. with open(newFilePath, "w") as fp:
  382. fp.write("123")
  383. previousFile = log._file
  384. log.rotate()
  385. self.assertEqual(previousFile, log._file)
  386. def test_rotatePermissionDirectoryNotOk(self):
  387. """
  388. L{DailyLogFile.rotate} doesn't do anything if the directory containing
  389. the log files can't be written to.
  390. """
  391. log = logfile.DailyLogFile(self.name, self.dir)
  392. self.addCleanup(log.close)
  393. os.chmod(log.directory, 0o444)
  394. # Restore permissions so tests can be cleaned up.
  395. self.addCleanup(os.chmod, log.directory, 0o755)
  396. previousFile = log._file
  397. log.rotate()
  398. self.assertEqual(previousFile, log._file)
  399. if runtime.platform.isWindows():
  400. test_rotatePermissionDirectoryNotOk.skip = (
  401. "Making read-only directories on Windows is too complex for this "
  402. "test to reasonably do.")
  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)