StreamHandlerTest.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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 Monolog\Test\TestCase;
  12. use Monolog\Level;
  13. use PHPUnit\Framework\Attributes\DataProvider;
  14. class StreamHandlerTest extends TestCase
  15. {
  16. /**
  17. * @covers Monolog\Handler\StreamHandler::__construct
  18. * @covers Monolog\Handler\StreamHandler::write
  19. */
  20. public function testWrite()
  21. {
  22. $handle = fopen('php://memory', 'a+');
  23. $handler = new StreamHandler($handle);
  24. $handler->setFormatter($this->getIdentityFormatter());
  25. $handler->handle($this->getRecord(Level::Warning, 'test'));
  26. $handler->handle($this->getRecord(Level::Warning, 'test2'));
  27. $handler->handle($this->getRecord(Level::Warning, 'test3'));
  28. fseek($handle, 0);
  29. $this->assertEquals('testtest2test3', fread($handle, 100));
  30. }
  31. /**
  32. * @covers Monolog\Handler\StreamHandler::close
  33. */
  34. public function testCloseKeepsExternalHandlersOpen()
  35. {
  36. $handle = fopen('php://memory', 'a+');
  37. $handler = new StreamHandler($handle);
  38. $this->assertTrue(\is_resource($handle));
  39. $handler->close();
  40. $this->assertTrue(\is_resource($handle));
  41. }
  42. /**
  43. * @covers Monolog\Handler\StreamHandler::close
  44. */
  45. public function testClose()
  46. {
  47. $handler = new StreamHandler('php://memory');
  48. $handler->handle($this->getRecord(Level::Warning, 'test'));
  49. $stream = $handler->getStream();
  50. $this->assertTrue(\is_resource($stream));
  51. $handler->close();
  52. $this->assertFalse(\is_resource($stream));
  53. }
  54. /**
  55. * @covers Monolog\Handler\StreamHandler::close
  56. * @covers Monolog\Handler\Handler::__sleep
  57. */
  58. public function testSerialization()
  59. {
  60. $handler = new StreamHandler('php://memory');
  61. $handler->handle($this->getRecord(Level::Warning, 'testfoo'));
  62. $stream = $handler->getStream();
  63. $this->assertTrue(\is_resource($stream));
  64. fseek($stream, 0);
  65. $this->assertStringContainsString('testfoo', stream_get_contents($stream));
  66. $serialized = serialize($handler);
  67. $this->assertFalse(\is_resource($stream));
  68. $handler = unserialize($serialized);
  69. $handler->handle($this->getRecord(Level::Warning, 'testbar'));
  70. $stream = $handler->getStream();
  71. $this->assertTrue(\is_resource($stream));
  72. fseek($stream, 0);
  73. $contents = stream_get_contents($stream);
  74. $this->assertStringNotContainsString('testfoo', $contents);
  75. $this->assertStringContainsString('testbar', $contents);
  76. }
  77. /**
  78. * @covers Monolog\Handler\StreamHandler::write
  79. */
  80. public function testWriteCreatesTheStreamResource()
  81. {
  82. $handler = new StreamHandler('php://memory');
  83. $handler->handle($this->getRecord());
  84. }
  85. /**
  86. * @covers Monolog\Handler\StreamHandler::__construct
  87. * @covers Monolog\Handler\StreamHandler::write
  88. */
  89. public function testWriteLocking()
  90. {
  91. $temp = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'monolog_locked_log';
  92. $handler = new StreamHandler($temp, Level::Debug, true, null, true);
  93. $handler->handle($this->getRecord());
  94. }
  95. /**
  96. * @covers Monolog\Handler\StreamHandler::__construct
  97. * @covers Monolog\Handler\StreamHandler::write
  98. */
  99. public function testWriteMissingResource()
  100. {
  101. $this->expectException(\LogicException::class);
  102. $handler = new StreamHandler(null);
  103. $handler->handle($this->getRecord());
  104. }
  105. public static function invalidArgumentProvider()
  106. {
  107. return [
  108. [1],
  109. [[]],
  110. [['bogus://url']],
  111. ];
  112. }
  113. /**
  114. * @covers Monolog\Handler\StreamHandler::__construct
  115. */
  116. #[DataProvider('invalidArgumentProvider')]
  117. public function testWriteInvalidArgument($invalidArgument)
  118. {
  119. $this->expectException(\InvalidArgumentException::class);
  120. $handler = new StreamHandler($invalidArgument);
  121. }
  122. /**
  123. * @covers Monolog\Handler\StreamHandler::__construct
  124. * @covers Monolog\Handler\StreamHandler::write
  125. */
  126. public function testWriteInvalidResource()
  127. {
  128. $this->expectException(\UnexpectedValueException::class);
  129. $php7xMessage = <<<STRING
  130. The stream or file "bogus://url" could not be opened in append mode: failed to open stream: No such file or directory
  131. The exception occurred while attempting to log: test
  132. Context: {"foo":"bar"}
  133. Extra: [1,2,3]
  134. STRING;
  135. $php8xMessage = <<<STRING
  136. The stream or file "bogus://url" could not be opened in append mode: Failed to open stream: No such file or directory
  137. The exception occurred while attempting to log: test
  138. Context: {"foo":"bar"}
  139. Extra: [1,2,3]
  140. STRING;
  141. $phpVersionString = phpversion();
  142. $phpVersionComponents = explode('.', $phpVersionString);
  143. $majorVersion = (int) $phpVersionComponents[0];
  144. $this->expectExceptionMessage(($majorVersion >= 8) ? $php8xMessage : $php7xMessage);
  145. $handler = new StreamHandler('bogus://url');
  146. $record = $this->getRecord(
  147. context: ['foo' => 'bar'],
  148. extra: [1, 2, 3],
  149. );
  150. $handler->handle($record);
  151. }
  152. /**
  153. * @covers Monolog\Handler\StreamHandler::__construct
  154. * @covers Monolog\Handler\StreamHandler::write
  155. */
  156. public function testWriteNonExistingResource()
  157. {
  158. $this->expectException(\UnexpectedValueException::class);
  159. $handler = new StreamHandler('ftp://foo/bar/baz/'.rand(0, 10000));
  160. $handler->handle($this->getRecord());
  161. }
  162. /**
  163. * @covers Monolog\Handler\StreamHandler::__construct
  164. * @covers Monolog\Handler\StreamHandler::write
  165. */
  166. public function testWriteNonExistingPath()
  167. {
  168. $handler = new StreamHandler(sys_get_temp_dir().'/bar/'.rand(0, 10000).DIRECTORY_SEPARATOR.rand(0, 10000));
  169. $handler->handle($this->getRecord());
  170. }
  171. /**
  172. * @covers Monolog\Handler\StreamHandler::__construct
  173. * @covers Monolog\Handler\StreamHandler::write
  174. */
  175. public function testWriteNonExistingFileResource()
  176. {
  177. $handler = new StreamHandler('file://'.sys_get_temp_dir().'/bar/'.rand(0, 10000).DIRECTORY_SEPARATOR.rand(0, 10000));
  178. $handler->handle($this->getRecord());
  179. }
  180. /**
  181. * @covers Monolog\Handler\StreamHandler::__construct
  182. * @covers Monolog\Handler\StreamHandler::write
  183. */
  184. #[DataProvider('provideNonExistingAndNotCreatablePath')]
  185. public function testWriteNonExistingAndNotCreatablePath($nonExistingAndNotCreatablePath)
  186. {
  187. if (\defined('PHP_WINDOWS_VERSION_BUILD')) {
  188. $this->markTestSkipped('Permissions checks can not run on windows');
  189. }
  190. $handler = null;
  191. try {
  192. $handler = new StreamHandler($nonExistingAndNotCreatablePath);
  193. } catch (\Exception $fail) {
  194. $this->fail(
  195. 'A non-existing and not creatable path should throw an Exception earliest on first write.
  196. Not during instantiation.'
  197. );
  198. }
  199. $this->expectException(\UnexpectedValueException::class);
  200. $this->expectExceptionMessage('There is no existing directory at');
  201. $handler->handle($this->getRecord());
  202. }
  203. public static function provideNonExistingAndNotCreatablePath()
  204. {
  205. return [
  206. '/foo/bar/…' => [
  207. '/foo/bar/'.rand(0, 10000).DIRECTORY_SEPARATOR.rand(0, 10000),
  208. ],
  209. 'file:///foo/bar/…' => [
  210. 'file:///foo/bar/'.rand(0, 10000).DIRECTORY_SEPARATOR.rand(0, 10000),
  211. ],
  212. ];
  213. }
  214. public static function provideMemoryValues()
  215. {
  216. return [
  217. ['1M', (int) (1024*1024/10)],
  218. ['10M', (int) (1024*1024)],
  219. ['1024M', (int) (1024*1024*1024/10)],
  220. ['1G', (int) (1024*1024*1024/10)],
  221. ['2000M', (int) (2000*1024*1024/10)],
  222. ['2050M', (int) (2050*1024*1024/10)],
  223. ['2048M', (int) (2048*1024*1024/10)],
  224. ['3G', (int) (3*1024*1024*1024/10)],
  225. ['2560M', (int) (2560*1024*1024/10)],
  226. ];
  227. }
  228. #[DataProvider('provideMemoryValues')]
  229. public function testPreventOOMError($phpMemory, $expectedChunkSize): void
  230. {
  231. $previousValue = @ini_set('memory_limit', $phpMemory);
  232. if ($previousValue === false) {
  233. $this->markTestSkipped('We could not set a memory limit that would trigger the error.');
  234. }
  235. try {
  236. $stream = tmpfile();
  237. if ($stream === false) {
  238. $this->markTestSkipped('We could not create a temp file to be use as a stream.');
  239. }
  240. $handler = new StreamHandler($stream);
  241. stream_get_contents($stream, 1024);
  242. $this->assertEquals($expectedChunkSize, $handler->getStreamChunkSize());
  243. } finally {
  244. ini_set('memory_limit', $previousValue);
  245. }
  246. }
  247. public function testSimpleOOMPrevention(): void
  248. {
  249. $previousValue = ini_set('memory_limit', '2048M');
  250. if ($previousValue === false) {
  251. $this->markTestSkipped('We could not set a memory limit that would trigger the error.');
  252. }
  253. try {
  254. $stream = tmpfile();
  255. new StreamHandler($stream);
  256. stream_get_contents($stream);
  257. $this->assertTrue(true);
  258. } finally {
  259. ini_set('memory_limit', $previousValue);
  260. }
  261. }
  262. }