UnixServerTest.php 12 KB

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