UnixServerTest.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. <?php
  2. namespace React\Tests\Socket;
  3. use React\EventLoop\Loop;
  4. use React\Socket\UnixServer;
  5. use React\Stream\DuplexResourceStream;
  6. class UnixServerTest extends TestCase
  7. {
  8. /** @var ?UnixServer */
  9. private $server;
  10. /** @var ?string */
  11. private $uds;
  12. /**
  13. * @before
  14. * @covers React\Socket\UnixServer::__construct
  15. * @covers React\Socket\UnixServer::getAddress
  16. */
  17. public function setUpServer()
  18. {
  19. if (!in_array('unix', stream_get_transports())) {
  20. $this->markTestSkipped('Unix domain sockets (UDS) not supported on your platform (Windows?)');
  21. }
  22. $this->uds = $this->getRandomSocketUri();
  23. $this->server = new UnixServer($this->uds);
  24. }
  25. public function testConstructWithoutLoopAssignsLoopAutomatically()
  26. {
  27. unlink(str_replace('unix://', '', $this->uds));
  28. $this->uds = $this->getRandomSocketUri();
  29. $server = new UnixServer($this->uds);
  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\UnixServer::handleConnection
  38. */
  39. public function testConnection()
  40. {
  41. $client = stream_socket_client($this->uds);
  42. assert(is_resource($client));
  43. $this->server->on('connection', $this->expectCallableOnce());
  44. $this->tick();
  45. $this->tick();
  46. }
  47. /**
  48. * @covers React\Socket\UnixServer::handleConnection
  49. */
  50. public function testConnectionWithManyClients()
  51. {
  52. $client1 = stream_socket_client($this->uds);
  53. assert(is_resource($client1));
  54. $client2 = stream_socket_client($this->uds);
  55. assert(is_resource($client2));
  56. $client3 = stream_socket_client($this->uds);
  57. assert(is_resource($client3));
  58. $this->server->on('connection', $this->expectCallableExactly(3));
  59. $this->tick();
  60. $this->tick();
  61. $this->tick();
  62. }
  63. public function testDataEventWillNotBeEmittedWhenClientSendsNoData()
  64. {
  65. $client = stream_socket_client($this->uds);
  66. assert(is_resource($client));
  67. $mock = $this->expectCallableNever();
  68. $this->server->on('connection', function ($conn) use ($mock) {
  69. $conn->on('data', $mock);
  70. });
  71. $this->tick();
  72. $this->tick();
  73. }
  74. public function testDataWillBeEmittedWithDataClientSends()
  75. {
  76. $client = stream_socket_client($this->uds);
  77. assert(is_resource($client));
  78. fwrite($client, "foo\n");
  79. $mock = $this->expectCallableOnceWith("foo\n");
  80. $this->server->on('connection', function ($conn) use ($mock) {
  81. $conn->on('data', $mock);
  82. });
  83. $this->tick();
  84. $this->tick();
  85. }
  86. public function testDataWillBeEmittedEvenWhenClientShutsDownAfterSending()
  87. {
  88. $client = stream_socket_client($this->uds);
  89. fwrite($client, "foo\n");
  90. stream_socket_shutdown($client, STREAM_SHUT_WR);
  91. $mock = $this->expectCallableOnceWith("foo\n");
  92. $this->server->on('connection', function ($conn) use ($mock) {
  93. $conn->on('data', $mock);
  94. });
  95. $this->tick();
  96. $this->tick();
  97. }
  98. public function testLoopWillEndWhenServerIsClosed()
  99. {
  100. // explicitly unset server because we already call close()
  101. $this->server->close();
  102. $this->server = null;
  103. Loop::run();
  104. // if we reach this, then everything is good
  105. $this->assertNull(null);
  106. }
  107. public function testCloseTwiceIsNoOp()
  108. {
  109. $this->server->close();
  110. $this->server->close();
  111. // if we reach this, then everything is good
  112. $this->assertNull(null);
  113. }
  114. public function testGetAddressAfterCloseReturnsNull()
  115. {
  116. $this->server->close();
  117. $this->assertNull($this->server->getAddress());
  118. }
  119. public function testLoopWillEndWhenServerIsClosedAfterSingleConnection()
  120. {
  121. $client = stream_socket_client($this->uds);
  122. assert(is_resource($client));
  123. // explicitly unset server because we only accept a single connection
  124. // and then already call close()
  125. $server = $this->server;
  126. $this->server = null;
  127. $server->on('connection', function ($conn) use ($server) {
  128. $conn->close();
  129. $server->close();
  130. });
  131. Loop::run();
  132. // if we reach this, then everything is good
  133. $this->assertNull(null);
  134. }
  135. public function testDataWillBeEmittedInMultipleChunksWhenClientSendsExcessiveAmounts()
  136. {
  137. $client = stream_socket_client($this->uds);
  138. $stream = new DuplexResourceStream($client);
  139. $bytes = 1024 * 1024;
  140. $stream->end(str_repeat('*', $bytes));
  141. $mock = $this->expectCallableOnce();
  142. // explicitly unset server because we only accept a single connection
  143. // and then already call close()
  144. $server = $this->server;
  145. $this->server = null;
  146. $received = 0;
  147. $server->on('connection', function ($conn) use ($mock, &$received, $server) {
  148. // count number of bytes received
  149. $conn->on('data', function ($data) use (&$received) {
  150. $received += strlen($data);
  151. });
  152. $conn->on('end', $mock);
  153. // do not await any further connections in order to let the loop terminate
  154. $server->close();
  155. });
  156. Loop::run();
  157. $this->assertEquals($bytes, $received);
  158. }
  159. public function testConnectionDoesNotEndWhenClientDoesNotClose()
  160. {
  161. $client = stream_socket_client($this->uds);
  162. assert(is_resource($client));
  163. $mock = $this->expectCallableNever();
  164. $this->server->on('connection', function ($conn) use ($mock) {
  165. $conn->on('end', $mock);
  166. });
  167. $this->tick();
  168. $this->tick();
  169. }
  170. /**
  171. * @covers React\Socket\Connection::end
  172. */
  173. public function testConnectionDoesEndWhenClientCloses()
  174. {
  175. $client = stream_socket_client($this->uds);
  176. fclose($client);
  177. $mock = $this->expectCallableOnce();
  178. $this->server->on('connection', function ($conn) use ($mock) {
  179. $conn->on('end', $mock);
  180. });
  181. $this->tick();
  182. $this->tick();
  183. }
  184. public function testCtorAddsResourceToLoop()
  185. {
  186. unlink(str_replace('unix://', '', $this->uds));
  187. $this->uds = $this->getRandomSocketUri();
  188. $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
  189. $loop->expects($this->once())->method('addReadStream');
  190. new UnixServer($this->uds, $loop);
  191. }
  192. public function testCtorThrowsForInvalidAddressScheme()
  193. {
  194. $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
  195. $this->setExpectedException(
  196. 'InvalidArgumentException',
  197. 'Given URI "tcp://localhost:0" is invalid (EINVAL)',
  198. defined('SOCKET_EINVAL') ? SOCKET_EINVAL : (defined('PCNTL_EINVAL') ? PCNTL_EINVAL : 22)
  199. );
  200. new UnixServer('tcp://localhost:0', $loop);
  201. }
  202. public function testCtorThrowsWhenPathIsNotWritableWithoutCallingCustomErrorHandler()
  203. {
  204. $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
  205. $error = null;
  206. set_error_handler(function ($_, $errstr) use (&$error) {
  207. $error = $errstr;
  208. });
  209. $this->setExpectedException('RuntimeException');
  210. try {
  211. new UnixServer('/dev/null', $loop);
  212. restore_error_handler();
  213. } catch (\Exception $e) {
  214. restore_error_handler();
  215. $this->assertNull($error);
  216. throw $e;
  217. }
  218. }
  219. public function testResumeWithoutPauseIsNoOp()
  220. {
  221. unlink(str_replace('unix://', '', $this->uds));
  222. $this->uds = $this->getRandomSocketUri();
  223. $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
  224. $loop->expects($this->once())->method('addReadStream');
  225. $server = new UnixServer($this->uds, $loop);
  226. $server->resume();
  227. }
  228. public function testPauseRemovesResourceFromLoop()
  229. {
  230. unlink(str_replace('unix://', '', $this->uds));
  231. $this->uds = $this->getRandomSocketUri();
  232. $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
  233. $loop->expects($this->once())->method('removeReadStream');
  234. $server = new UnixServer($this->uds, $loop);
  235. $server->pause();
  236. }
  237. public function testPauseAfterPauseIsNoOp()
  238. {
  239. unlink(str_replace('unix://', '', $this->uds));
  240. $this->uds = $this->getRandomSocketUri();
  241. $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
  242. $loop->expects($this->once())->method('removeReadStream');
  243. $server = new UnixServer($this->uds, $loop);
  244. $server->pause();
  245. $server->pause();
  246. }
  247. public function testCloseRemovesResourceFromLoop()
  248. {
  249. unlink(str_replace('unix://', '', $this->uds));
  250. $this->uds = $this->getRandomSocketUri();
  251. $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
  252. $loop->expects($this->once())->method('removeReadStream');
  253. $server = new UnixServer($this->uds, $loop);
  254. $server->close();
  255. }
  256. public function testEmitsErrorWhenAcceptListenerFailsWithoutCallingCustomErrorHandler()
  257. {
  258. unlink(str_replace('unix://', '', $this->uds));
  259. $this->uds = $this->getRandomSocketUri();
  260. $listener = null;
  261. $loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
  262. $loop->expects($this->once())->method('addReadStream')->with($this->anything(), $this->callback(function ($cb) use (&$listener) {
  263. $listener = $cb;
  264. return true;
  265. }));
  266. $server = new UnixServer($this->uds, $loop);
  267. $exception = null;
  268. $server->on('error', function ($e) use (&$exception) {
  269. $exception = $e;
  270. });
  271. $this->assertNotNull($listener);
  272. $socket = stream_socket_server('tcp://127.0.0.1:0');
  273. $error = null;
  274. set_error_handler(function ($_, $errstr) use (&$error) {
  275. $error = $errstr;
  276. });
  277. $time = microtime(true);
  278. $listener($socket);
  279. $time = microtime(true) - $time;
  280. restore_error_handler();
  281. $this->assertNull($error);
  282. $this->assertLessThan(1, $time);
  283. $this->assertInstanceOf('RuntimeException', $exception);
  284. assert($exception instanceof \RuntimeException);
  285. $this->assertStringStartsWith('Unable to accept new connection: ', $exception->getMessage());
  286. return $exception;
  287. }
  288. /**
  289. * @param \RuntimeException $e
  290. * @requires extension sockets
  291. * @depends testEmitsErrorWhenAcceptListenerFailsWithoutCallingCustomErrorHandler
  292. */
  293. public function testEmitsTimeoutErrorWhenAcceptListenerFails(\RuntimeException $exception)
  294. {
  295. if (defined('HHVM_VERSION')) {
  296. $this->markTestSkipped('not supported on HHVM');
  297. }
  298. $this->assertEquals('Unable to accept new connection: ' . socket_strerror(SOCKET_ETIMEDOUT) . ' (ETIMEDOUT)', $exception->getMessage());
  299. $this->assertEquals(SOCKET_ETIMEDOUT, $exception->getCode());
  300. }
  301. public function testListenOnBusyPortThrows()
  302. {
  303. if (DIRECTORY_SEPARATOR === '\\') {
  304. $this->markTestSkipped('Windows supports listening on same port multiple times');
  305. }
  306. $this->setExpectedException('RuntimeException');
  307. new UnixServer($this->uds);
  308. }
  309. /**
  310. * @after
  311. * @covers React\Socket\UnixServer::close
  312. */
  313. public function tearDownServer()
  314. {
  315. if ($this->server) {
  316. $this->server->close();
  317. $this->server = null;
  318. }
  319. assert(is_string($this->uds));
  320. unlink(str_replace('unix://', '', $this->uds));
  321. }
  322. private function getRandomSocketUri()
  323. {
  324. return "unix://" . sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid(rand(), true) . '.sock';
  325. }
  326. private function tick()
  327. {
  328. \React\Async\await(\React\Promise\Timer\sleep(0.0));
  329. }
  330. }