UdpSocketTest.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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\Handler\SyslogUdp\UdpSocket;
  13. /**
  14. * @requires extension sockets
  15. */
  16. class UdpSocketTest extends TestCase
  17. {
  18. public function testWeDoNotTruncateShortMessages()
  19. {
  20. $this->initSocket();
  21. $socket = new UdpSocket('127.0.0.1', 51984);
  22. $socket->write("The quick brown fox jumps over the lazy dog", "HEADER: ");
  23. $this->closeSocket();
  24. $this->assertEquals('HEADER: The quick brown fox jumps over the lazy dog', $this->socket->getOutput());
  25. }
  26. public function testLongMessagesAreTruncated()
  27. {
  28. $this->initSocket();
  29. $socket = new UdpSocket('127.0.0.1', 51984);
  30. $longString = str_repeat("derp", 20000);
  31. $socket->write($longString, "HEADER");
  32. $truncatedString = str_repeat("derp", 16254).'d';
  33. $this->closeSocket();
  34. $this->assertEquals('HEADER'.$truncatedString, $this->socket->getOutput());
  35. }
  36. public function testDoubleCloseDoesNotError()
  37. {
  38. $socket = new UdpSocket('127.0.0.1', 514);
  39. $socket->close();
  40. $socket->close();
  41. }
  42. /**
  43. * @expectedException LogicException
  44. */
  45. public function testWriteAfterCloseErrors()
  46. {
  47. $socket = new UdpSocket('127.0.0.1', 514);
  48. $socket->close();
  49. $socket->write('foo', "HEADER");
  50. }
  51. private function initSocket()
  52. {
  53. $tmpFile = sys_get_temp_dir().'/monolog-test-socket.php';
  54. file_put_contents($tmpFile, <<<'SCRIPT'
  55. <?php
  56. $sock = socket_create(AF_INET, SOCK_DGRAM, getprotobyname('udp'));
  57. socket_bind($sock, '127.0.0.1', 51984);
  58. echo 'INIT';
  59. while (true) {
  60. socket_recvfrom($sock, $read, 100*1024, 0, $ip, $port);
  61. echo $read;
  62. }
  63. SCRIPT
  64. );
  65. $this->socket = new \Symfony\Component\Process\Process(escapeshellarg(PHP_BINARY).' '.escapeshellarg($tmpFile));
  66. $this->socket->start();
  67. while (true) {
  68. if ($this->socket->getOutput() === 'INIT') {
  69. $this->socket->clearOutput();
  70. break;
  71. }
  72. usleep(100);
  73. }
  74. }
  75. private function closeSocket()
  76. {
  77. usleep(100);
  78. $this->socket->stop();
  79. }
  80. public function tearDown()
  81. {
  82. if (isset($this->socket)) {
  83. $this->closeSocket();
  84. unset($this->socket);
  85. }
  86. }
  87. }