RotatingFileHandlerTest.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Handler;
  11. use InvalidArgumentException;
  12. use Monolog\Test\TestCase;
  13. /**
  14. * @covers Monolog\Handler\RotatingFileHandler
  15. */
  16. class RotatingFileHandlerTest extends TestCase
  17. {
  18. private array|null $lastError = null;
  19. public function setUp(): void
  20. {
  21. $dir = __DIR__.'/Fixtures';
  22. chmod($dir, 0777);
  23. if (!is_writable($dir)) {
  24. $this->markTestSkipped($dir.' must be writable to test the RotatingFileHandler.');
  25. }
  26. $this->lastError = null;
  27. set_error_handler(function ($code, $message) {
  28. $this->lastError = [
  29. 'code' => $code,
  30. 'message' => $message,
  31. ];
  32. return true;
  33. });
  34. }
  35. private function assertErrorWasTriggered($code, $message)
  36. {
  37. if (empty($this->lastError)) {
  38. $this->fail(
  39. sprintf(
  40. 'Failed asserting that error with code `%d` and message `%s` was triggered',
  41. $code,
  42. $message
  43. )
  44. );
  45. }
  46. $this->assertEquals($code, $this->lastError['code'], sprintf('Expected an error with code %d to be triggered, got `%s` instead', $code, $this->lastError['code']));
  47. $this->assertEquals($message, $this->lastError['message'], sprintf('Expected an error with message `%d` to be triggered, got `%s` instead', $message, $this->lastError['message']));
  48. }
  49. public function testRotationCreatesNewFile()
  50. {
  51. touch(__DIR__.'/Fixtures/foo-'.date('Y-m-d', time() - 86400).'.rot');
  52. $handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot');
  53. $handler->setFormatter($this->getIdentityFormatter());
  54. $handler->handle($this->getRecord());
  55. $log = __DIR__.'/Fixtures/foo-'.date('Y-m-d').'.rot';
  56. $this->assertTrue(file_exists($log));
  57. $this->assertEquals('test', file_get_contents($log));
  58. }
  59. /**
  60. * @dataProvider rotationTests
  61. */
  62. public function testRotation($createFile, $dateFormat, $timeCallback)
  63. {
  64. touch($old1 = __DIR__.'/Fixtures/foo-'.date($dateFormat, $timeCallback(-1)).'.rot');
  65. touch($old2 = __DIR__.'/Fixtures/foo-'.date($dateFormat, $timeCallback(-2)).'.rot');
  66. touch($old3 = __DIR__.'/Fixtures/foo-'.date($dateFormat, $timeCallback(-3)).'.rot');
  67. touch($old4 = __DIR__.'/Fixtures/foo-'.date($dateFormat, $timeCallback(-4)).'.rot');
  68. $log = __DIR__.'/Fixtures/foo-'.date($dateFormat).'.rot';
  69. if ($createFile) {
  70. touch($log);
  71. }
  72. $handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2);
  73. $handler->setFormatter($this->getIdentityFormatter());
  74. $handler->setFilenameFormat('{filename}-{date}', $dateFormat);
  75. $handler->handle($this->getRecord());
  76. $handler->close();
  77. $this->assertTrue(file_exists($log));
  78. $this->assertTrue(file_exists($old1));
  79. $this->assertEquals($createFile, file_exists($old2));
  80. $this->assertEquals($createFile, file_exists($old3));
  81. $this->assertEquals($createFile, file_exists($old4));
  82. $this->assertEquals('test', file_get_contents($log));
  83. }
  84. public function rotationTests()
  85. {
  86. $now = time();
  87. $dayCallback = function ($ago) use ($now) {
  88. return $now + 86400 * $ago;
  89. };
  90. $monthCallback = function ($ago) {
  91. return gmmktime(0, 0, 0, (int) (date('n') + $ago), 1, (int) date('Y'));
  92. };
  93. $yearCallback = function ($ago) {
  94. return gmmktime(0, 0, 0, 1, 1, (int) (date('Y') + $ago));
  95. };
  96. return [
  97. 'Rotation is triggered when the file of the current day is not present'
  98. => [true, RotatingFileHandler::FILE_PER_DAY, $dayCallback],
  99. 'Rotation is not triggered when the file of the current day is already present'
  100. => [false, RotatingFileHandler::FILE_PER_DAY, $dayCallback],
  101. 'Rotation is triggered when the file of the current month is not present'
  102. => [true, RotatingFileHandler::FILE_PER_MONTH, $monthCallback],
  103. 'Rotation is not triggered when the file of the current month is already present'
  104. => [false, RotatingFileHandler::FILE_PER_MONTH, $monthCallback],
  105. 'Rotation is triggered when the file of the current year is not present'
  106. => [true, RotatingFileHandler::FILE_PER_YEAR, $yearCallback],
  107. 'Rotation is not triggered when the file of the current year is already present'
  108. => [false, RotatingFileHandler::FILE_PER_YEAR, $yearCallback],
  109. ];
  110. }
  111. /**
  112. * @dataProvider dateFormatProvider
  113. */
  114. public function testAllowOnlyFixedDefinedDateFormats($dateFormat, $valid)
  115. {
  116. $handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2);
  117. if (!$valid) {
  118. $this->expectException(InvalidArgumentException::class);
  119. $this->expectExceptionMessageMatches('~^Invalid date format~');
  120. }
  121. $handler->setFilenameFormat('{filename}-{date}', $dateFormat);
  122. $this->assertTrue(true);
  123. }
  124. public function dateFormatProvider()
  125. {
  126. return [
  127. [RotatingFileHandler::FILE_PER_DAY, true],
  128. [RotatingFileHandler::FILE_PER_MONTH, true],
  129. [RotatingFileHandler::FILE_PER_YEAR, true],
  130. ['Y/m/d', true],
  131. ['Y.m.d', true],
  132. ['Y_m_d', true],
  133. ['Ymd', true],
  134. ['Ym/d', true],
  135. ['Y/m', true],
  136. ['Ym', true],
  137. ['Y.m', true],
  138. ['Y_m', true],
  139. ['Y/md', true],
  140. ['', false],
  141. ['m-d-Y', false],
  142. ['Y-m-d-h-i', false],
  143. ['Y-', false],
  144. ['Y-m-', false],
  145. ['Y--', false],
  146. ['m-d', false],
  147. ['Y-d', false],
  148. ];
  149. }
  150. /**
  151. * @dataProvider filenameFormatProvider
  152. */
  153. public function testDisallowFilenameFormatsWithoutDate($filenameFormat, $valid)
  154. {
  155. $handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2);
  156. if (!$valid) {
  157. $this->expectException(InvalidArgumentException::class);
  158. $this->expectExceptionMessageMatches('~^Invalid filename format~');
  159. }
  160. $handler->setFilenameFormat($filenameFormat, RotatingFileHandler::FILE_PER_DAY);
  161. }
  162. public function filenameFormatProvider()
  163. {
  164. return [
  165. ['{filename}', false],
  166. ['{filename}-{date}', true],
  167. ['{date}', true],
  168. ['foobar-{date}', true],
  169. ['foo-{date}-bar', true],
  170. ['{date}-foobar', true],
  171. ['foobar', false],
  172. ];
  173. }
  174. /**
  175. * @dataProvider rotationWhenSimilarFilesExistTests
  176. */
  177. public function testRotationWhenSimilarFileNamesExist($dateFormat)
  178. {
  179. touch($old1 = __DIR__.'/Fixtures/foo-foo-'.date($dateFormat).'.rot');
  180. touch($old2 = __DIR__.'/Fixtures/foo-bar-'.date($dateFormat).'.rot');
  181. $log = __DIR__.'/Fixtures/foo-'.date($dateFormat).'.rot';
  182. $handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2);
  183. $handler->setFormatter($this->getIdentityFormatter());
  184. $handler->setFilenameFormat('{filename}-{date}', $dateFormat);
  185. $handler->handle($this->getRecord());
  186. $handler->close();
  187. $this->assertTrue(file_exists($log));
  188. }
  189. public function rotationWhenSimilarFilesExistTests()
  190. {
  191. return [
  192. 'Rotation is triggered when the file of the current day is not present but similar exists'
  193. => [RotatingFileHandler::FILE_PER_DAY],
  194. 'Rotation is triggered when the file of the current month is not present but similar exists'
  195. => [RotatingFileHandler::FILE_PER_MONTH],
  196. 'Rotation is triggered when the file of the current year is not present but similar exists'
  197. => [RotatingFileHandler::FILE_PER_YEAR],
  198. ];
  199. }
  200. public function testReuseCurrentFile()
  201. {
  202. $log = __DIR__.'/Fixtures/foo-'.date('Y-m-d').'.rot';
  203. file_put_contents($log, "foo");
  204. $handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot');
  205. $handler->setFormatter($this->getIdentityFormatter());
  206. $handler->handle($this->getRecord());
  207. $this->assertEquals('footest', file_get_contents($log));
  208. }
  209. public function tearDown(): void
  210. {
  211. foreach (glob(__DIR__.'/Fixtures/*.rot') as $file) {
  212. unlink($file);
  213. }
  214. restore_error_handler();
  215. }
  216. }