TcpServerTest.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. <?php
  2. namespace React\Tests\Socket;
  3. use React\EventLoop\Loop;
  4. use React\Socket\TcpServer;
  5. use React\Stream\DuplexResourceStream;
  6. use React\Promise\Promise;
  7. class TcpServerTest extends TestCase
  8. {
  9. const TIMEOUT = 5.0;
  10. private $server;
  11. private $port;
  12. /**
  13. * @before
  14. * @covers React\Socket\TcpServer::__construct
  15. * @covers React\Socket\TcpServer::getAddress
  16. */
  17. public function setUpServer()
  18. {
  19. $this->server = new TcpServer(0);
  20. $this->port = parse_url($this->server->getAddress(), PHP_URL_PORT);
  21. }
  22. public function testCtorThrowsForInvalidLoop()
  23. {
  24. $this->setExpectedException('InvalidArgumentException', 'Argument #2 ($loop) expected null|React\EventLoop\LoopInterface');
  25. new TcpServer(0, 'loop');
  26. }
  27. public function testConstructWithoutLoopAssignsLoopAutomatically()
  28. {
  29. $server = new TcpServer(0);
  30. $ref = new \ReflectionProperty($server, 'loop');
  31. $ref->setAccessible(true);
  32. $loop = $ref->getValue($server);
  33. $this->assertInstanceOf('React\EventLoop\LoopInterface', $loop);
  34. $server->close();
  35. }
  36. /**
  37. * @covers React\Socket\TcpServer::handleConnection
  38. */
  39. public function testServerEmitsConnectionEventForNewConnection()
  40. {
  41. $client = stream_socket_client('tcp://localhost:'.$this->port);
  42. assert($client !== false);
  43. $server = $this->server;
  44. $promise = new Promise(function ($resolve) use ($server) {
  45. $server->on('connection', $resolve);
  46. });
  47. $connection = \React\Async\await(\React\Promise\Timer\timeout($promise, self::TIMEOUT));
  48. $this->assertInstanceOf('React\Socket\ConnectionInterface', $connection);
  49. }
  50. /**
  51. * @covers React\Socket\TcpServer::handleConnection
  52. */
  53. public function testConnectionWithManyClients()
  54. {
  55. $client1 = stream_socket_client('tcp://localhost:'.$this->port);
  56. $client2 = stream_socket_client('tcp://localhost:'.$this->port);
  57. $client3 = stream_socket_client('tcp://localhost:'.$this->port);
  58. assert($client1 !== false && $client2 !== false && $client3 !== false);
  59. $this->server->on('connection', $this->expectCallableExactly(3));
  60. $this->tick();
  61. $this->tick();
  62. $this->tick();
  63. $this->tick();
  64. }
  65. public function testDataEventWillNotBeEmittedWhenClientSendsNoData()
  66. {
  67. $client = stream_socket_client('tcp://localhost:'.$this->port);
  68. assert($client !== false);
  69. $mock = $this->expectCallableNever();
  70. $this->server->on('connection', function ($conn) use ($mock) {
  71. $conn->on('data', $mock);
  72. });
  73. $this->tick();
  74. $this->tick();
  75. }
  76. public function testDataWillBeEmittedWithDataClientSends()
  77. {
  78. $client = stream_socket_client('tcp://localhost:'.$this->port);
  79. fwrite($client, "foo\n");
  80. $mock = $this->expectCallableOnceWith("foo\n");
  81. $this->server->on('connection', function ($conn) use ($mock) {
  82. $conn->on('data', $mock);
  83. });
  84. $this->tick();
  85. $this->tick();
  86. }
  87. public function testDataWillBeEmittedEvenWhenClientShutsDownAfterSending()
  88. {
  89. $client = stream_socket_client('tcp://localhost:' . $this->port);
  90. fwrite($client, "foo\n");
  91. stream_socket_shutdown($client, STREAM_SHUT_WR);
  92. $mock = $this->expectCallableOnceWith("foo\n");
  93. $this->server->on('connection', function ($conn) use ($mock) {
  94. $conn->on('data', $mock);
  95. });
  96. $this->tick();
  97. $this->tick();
  98. }
  99. public function testLoopWillEndWhenServerIsClosed()
  100. {
  101. // explicitly unset server because we already call close()
  102. $this->server->close();
  103. $this->server = null;
  104. Loop::run();
  105. // if we reach this, then everything is good
  106. $this->assertNull(null);
  107. }
  108. public function testCloseTwiceIsNoOp()
  109. {
  110. $this->server->close();
  111. $this->server->close();
  112. // if we reach this, then everything is good
  113. $this->assertNull(null);
  114. }
  115. public function testGetAddressAfterCloseReturnsNull()
  116. {
  117. $this->server->close();
  118. $this->assertNull($this->server->getAddress());
  119. }
  120. public function testLoopWillEndWhenServerIsClosedAfterSingleConnection()
  121. {
  122. $client = stream_socket_client('tcp://localhost:' . $this->port);
  123. assert($client !== false);
  124. // explicitly unset server because we only accept a single connection
  125. // and then already call close()
  126. $server = $this->server;
  127. $this->server = null;
  128. $server->on('connection', function ($conn) use ($server) {
  129. $conn->close();
  130. $server->close();
  131. });
  132. Loop::run();
  133. // if we reach this, then everything is good
  134. $this->assertNull(null);
  135. }
  136. public function testDataWillBeEmittedInMultipleChunksWhenClientSendsExcessiveAmounts()
  137. {
  138. $client = stream_socket_client('tcp://localhost:' . $this->port);
  139. $stream = new DuplexResourceStream($client);
  140. $bytes = 1024 * 1024;
  141. $stream->end(str_repeat('*', $bytes));
  142. $mock = $this->expectCallableOnce();
  143. // explicitly unset server because we only accept a single connection
  144. // and then already call close()
  145. $server = $this->server;
  146. $this->server = null;
  147. $received = 0;
  148. $server->on('connection', function ($conn) use ($mock, &$received, $server) {
  149. // count number of bytes received
  150. $conn->on('data', function ($data) use (&$received) {
  151. $received += strlen($data);
  152. });
  153. $conn->on('end', $mock);
  154. // do not await any further connections in order to let the loop terminate
  155. $server->close();
  156. });
  157. Loop::run();
  158. $this->assertEquals($bytes, $received);
  159. }
  160. public function testConnectionDoesNotEndWhenClientDoesNotClose()
  161. {
  162. $client = stream_socket_client('tcp://localhost:'.$this->port);
  163. assert($client !== false);
  164. $mock = $this->expectCallableNever();
  165. $this->server->on('connection', function ($conn) use ($mock) {
  166. $conn->on('end', $mock);
  167. });
  168. $this->tick();
  169. $this->tick();
  170. }
  171. /**
  172. * @covers React\Socket\Connection::end
  173. */
  174. public function testConnectionDoesEndWhenClientCloses()
  175. {
  176. $client = stream_socket_client('tcp://localhost:'.$this->port);
  177. fclose($client);
  178. $mock = $this->expectCallableOnce();
  179. $this->server->on('connection', function ($conn) use ($mock) {
  180. $conn->on('end', $mock);
  181. });
  182. $this->tick();
  183. $this->tick();
  184. }
  185. public function testCtorAddsResourceToLoop()
  186. {
  187. $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
  188. $loop->expects($this->once())->method('addReadStream');
  189. new TcpServer(0, $loop);
  190. }
  191. public function testResumeWithoutPauseIsNoOp()
  192. {
  193. $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
  194. $loop->expects($this->once())->method('addReadStream');
  195. $server = new TcpServer(0, $loop);
  196. $server->resume();
  197. }
  198. public function testPauseRemovesResourceFromLoop()
  199. {
  200. $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
  201. $loop->expects($this->once())->method('removeReadStream');
  202. $server = new TcpServer(0, $loop);
  203. $server->pause();
  204. }
  205. public function testPauseAfterPauseIsNoOp()
  206. {
  207. $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
  208. $loop->expects($this->once())->method('removeReadStream');
  209. $server = new TcpServer(0, $loop);
  210. $server->pause();
  211. $server->pause();
  212. }
  213. public function testCloseRemovesResourceFromLoop()
  214. {
  215. $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
  216. $loop->expects($this->once())->method('removeReadStream');
  217. $server = new TcpServer(0, $loop);
  218. $server->close();
  219. }
  220. public function testEmitsErrorWhenAcceptListenerFailsWithoutCallingCustomErrorHandler()
  221. {
  222. $listener = null;
  223. $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
  224. $loop->expects($this->once())->method('addReadStream')->with($this->anything(), $this->callback(function ($cb) use (&$listener) {
  225. $listener = $cb;
  226. return true;
  227. }));
  228. $server = new TcpServer(0, $loop);
  229. $exception = null;
  230. $server->on('error', function ($e) use (&$exception) {
  231. $exception = $e;
  232. });
  233. $this->assertNotNull($listener);
  234. $socket = stream_socket_server('tcp://127.0.0.1:0');
  235. $error = null;
  236. set_error_handler(function ($_, $errstr) use (&$error) {
  237. $error = $errstr;
  238. });
  239. $time = microtime(true);
  240. $listener($socket);
  241. $time = microtime(true) - $time;
  242. restore_error_handler();
  243. $this->assertNull($error);
  244. $this->assertLessThan(1, $time);
  245. $this->assertInstanceOf('RuntimeException', $exception);
  246. assert($exception instanceof \RuntimeException);
  247. $this->assertStringStartsWith('Unable to accept new connection: ', $exception->getMessage());
  248. return $exception;
  249. }
  250. /**
  251. * @param \RuntimeException $e
  252. * @requires extension sockets
  253. * @depends testEmitsErrorWhenAcceptListenerFailsWithoutCallingCustomErrorHandler
  254. */
  255. public function testEmitsTimeoutErrorWhenAcceptListenerFails(\RuntimeException $exception)
  256. {
  257. if (defined('HHVM_VERSION')) {
  258. $this->markTestSkipped('Not supported on HHVM');
  259. }
  260. $this->assertEquals('Unable to accept new connection: ' . socket_strerror(SOCKET_ETIMEDOUT) . ' (ETIMEDOUT)', $exception->getMessage());
  261. $this->assertEquals(SOCKET_ETIMEDOUT, $exception->getCode());
  262. }
  263. public function testListenOnBusyPortThrows()
  264. {
  265. if (DIRECTORY_SEPARATOR === '\\') {
  266. $this->markTestSkipped('Windows supports listening on same port multiple times');
  267. }
  268. if (defined('HHVM_VERSION')) {
  269. $this->markTestSkipped('Not supported on HHVM');
  270. }
  271. $this->setExpectedException(
  272. 'RuntimeException',
  273. 'Failed to listen on "tcp://127.0.0.1:' . $this->port . '": ' . (function_exists('socket_strerror') ? socket_strerror(SOCKET_EADDRINUSE) . ' (EADDRINUSE)' : 'Address already in use'),
  274. defined('SOCKET_EADDRINUSE') ? SOCKET_EADDRINUSE : 0
  275. );
  276. new TcpServer($this->port);
  277. }
  278. /**
  279. * @after
  280. * @covers React\Socket\TcpServer::close
  281. */
  282. public function tearDownServer()
  283. {
  284. if ($this->server) {
  285. $this->server->close();
  286. }
  287. }
  288. /**
  289. * This methods runs the loop for "one tick"
  290. *
  291. * This is prone to race conditions and as such somewhat unreliable across
  292. * different operating systems. Running the loop until the expected events
  293. * fire is the preferred alternative.
  294. *
  295. * @deprecated
  296. */
  297. private function tick()
  298. {
  299. if (DIRECTORY_SEPARATOR === '\\') {
  300. $this->markTestSkipped('Not supported on Windows');
  301. }
  302. \React\Async\await(\React\Promise\Timer\sleep(0.0));
  303. }
  304. }