ClientTest.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.com>
  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 Predis;
  11. use PredisTestCase;
  12. /**
  13. *
  14. */
  15. class ClientTest extends PredisTestCase
  16. {
  17. /**
  18. * @group disconnected
  19. */
  20. public function testConstructorWithoutArguments()
  21. {
  22. $client = new Client();
  23. $connection = $client->getConnection();
  24. $this->assertInstanceOf('Predis\Connection\NodeConnectionInterface', $connection);
  25. $parameters = $connection->getParameters();
  26. $this->assertSame($parameters->host, '127.0.0.1');
  27. $this->assertSame($parameters->port, 6379);
  28. $options = $client->getOptions();
  29. $this->assertSame($options->commands, $client->getCommandFactory());
  30. $this->assertFalse($client->isConnected());
  31. }
  32. /**
  33. * @group disconnected
  34. */
  35. public function testConstructorWithNullArgument()
  36. {
  37. $client = new Client(null);
  38. $connection = $client->getConnection();
  39. $this->assertInstanceOf('Predis\Connection\NodeConnectionInterface', $connection);
  40. $parameters = $connection->getParameters();
  41. $this->assertSame($parameters->host, '127.0.0.1');
  42. $this->assertSame($parameters->port, 6379);
  43. $options = $client->getOptions();
  44. $this->assertSame($options->commands, $client->getCommandFactory());
  45. $this->assertFalse($client->isConnected());
  46. }
  47. /**
  48. * @group disconnected
  49. */
  50. public function testConstructorWithNullAndNullArguments()
  51. {
  52. $client = new Client(null, null);
  53. $connection = $client->getConnection();
  54. $this->assertInstanceOf('Predis\Connection\NodeConnectionInterface', $connection);
  55. $parameters = $connection->getParameters();
  56. $this->assertSame($parameters->host, '127.0.0.1');
  57. $this->assertSame($parameters->port, 6379);
  58. $options = $client->getOptions();
  59. $this->assertSame($options->commands, $client->getCommandFactory());
  60. $this->assertFalse($client->isConnected());
  61. }
  62. /**
  63. * @group disconnected
  64. */
  65. public function testConstructorWithArrayArgument()
  66. {
  67. $client = new Client($arg1 = array('host' => 'localhost', 'port' => 7000));
  68. $parameters = $client->getConnection()->getParameters();
  69. $this->assertSame($parameters->host, $arg1['host']);
  70. $this->assertSame($parameters->port, $arg1['port']);
  71. }
  72. /**
  73. * @group disconnected
  74. * @expectedException \InvalidArgumentException
  75. * @expectedExceptionMessage Array of connection parameters requires `cluster`, `replication` or `aggregate` client option
  76. */
  77. public function testConstructorThrowsExceptionWithArrayOfParametersArgumentAndMissingOption()
  78. {
  79. $arg1 = array(
  80. array('host' => 'localhost', 'port' => 7000),
  81. array('host' => 'localhost', 'port' => 7001),
  82. );
  83. $client = new Client($arg1);
  84. }
  85. /**
  86. * @group disconnected
  87. */
  88. public function testConstructorWithArrayOfArrayArgumentAndClusterOption()
  89. {
  90. $arg1 = array(
  91. array('host' => 'localhost', 'port' => 7000),
  92. array('host' => 'localhost', 'port' => 7001),
  93. );
  94. $client = new Client($arg1, array(
  95. 'aggregate' => $this->getAggregateInitializer($arg1),
  96. ));
  97. $this->assertInstanceOf('Predis\Connection\AggregateConnectionInterface', $client->getConnection());
  98. }
  99. /**
  100. * @group disconnected
  101. */
  102. public function testConstructorWithStringArgument()
  103. {
  104. $client = new Client('tcp://localhost:7000');
  105. $parameters = $client->getConnection()->getParameters();
  106. $this->assertSame($parameters->host, 'localhost');
  107. $this->assertSame($parameters->port, 7000);
  108. }
  109. /**
  110. * @group disconnected
  111. */
  112. public function testConstructorWithArrayOfStringArgument()
  113. {
  114. $arg1 = array('tcp://localhost:7000', 'tcp://localhost:7001');
  115. $client = new Client($arg1, array(
  116. 'aggregate' => $this->getAggregateInitializer($arg1),
  117. ));
  118. $this->assertInstanceOf('Predis\Connection\AggregateConnectionInterface', $client->getConnection());
  119. }
  120. /**
  121. * @group disconnected
  122. */
  123. public function testConstructorWithArrayOfConnectionsArgument()
  124. {
  125. $arg1 = array(
  126. $this->getMock('Predis\Connection\NodeConnectionInterface'),
  127. $this->getMock('Predis\Connection\NodeConnectionInterface'),
  128. );
  129. $client = new Client($arg1, array(
  130. 'aggregate' => $this->getAggregateInitializer($arg1),
  131. ));
  132. $this->assertInstanceOf('Predis\Connection\AggregateConnectionInterface', $client->getConnection());
  133. }
  134. /**
  135. * @group disconnected
  136. */
  137. public function testConstructorWithConnectionArgument()
  138. {
  139. $factory = new Connection\Factory();
  140. $connection = $factory->create('tcp://localhost:7000');
  141. $client = new Client($connection);
  142. $this->assertInstanceOf('Predis\Connection\NodeConnectionInterface', $client->getConnection());
  143. $this->assertSame($connection, $client->getConnection());
  144. $parameters = $client->getConnection()->getParameters();
  145. $this->assertSame($parameters->host, 'localhost');
  146. $this->assertSame($parameters->port, 7000);
  147. }
  148. /**
  149. * @group disconnected
  150. */
  151. public function testConstructorWithClusterArgument()
  152. {
  153. $cluster = new Connection\Cluster\PredisCluster();
  154. $factory = new Connection\Factory();
  155. $factory->aggregate($cluster, array('tcp://localhost:7000', 'tcp://localhost:7001'));
  156. $client = new Client($cluster);
  157. $this->assertInstanceOf('Predis\Connection\Cluster\ClusterInterface', $client->getConnection());
  158. $this->assertSame($cluster, $client->getConnection());
  159. }
  160. /**
  161. * @group disconnected
  162. */
  163. public function testConstructorWithReplicationArgument()
  164. {
  165. $replication = new Connection\Replication\MasterSlaveReplication();
  166. $factory = new Connection\Factory();
  167. $factory->aggregate($replication, array('tcp://host1?alias=master', 'tcp://host2?alias=slave'));
  168. $client = new Client($replication);
  169. $this->assertInstanceOf('Predis\Connection\Replication\ReplicationInterface', $client->getConnection());
  170. $this->assertSame($replication, $client->getConnection());
  171. }
  172. /**
  173. * @group disconnected
  174. */
  175. public function testConstructorWithCallableArgument()
  176. {
  177. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  178. $callable = $this->getMock('stdClass', array('__invoke'));
  179. $callable->expects($this->once())
  180. ->method('__invoke')
  181. ->with($this->isInstanceOf('Predis\Configuration\OptionsInterface'))
  182. ->will($this->returnValue($connection));
  183. $client = new Client($callable);
  184. $this->assertSame($connection, $client->getConnection());
  185. }
  186. /**
  187. * @group disconnected
  188. * @expectedException \InvalidArgumentException
  189. * @expectedExceptionMessage Callable parameters must return a valid connection
  190. */
  191. public function testConstructorWithCallableConnectionInitializerThrowsExceptionOnInvalidReturnType()
  192. {
  193. $wrongType = $this->getMock('stdClass');
  194. $callable = $this->getMock('stdClass', array('__invoke'));
  195. $callable->expects($this->once())
  196. ->method('__invoke')
  197. ->with($this->isInstanceOf('Predis\Configuration\OptionsInterface'))
  198. ->will($this->returnValue($wrongType));
  199. new Client($callable);
  200. }
  201. /**
  202. * @group disconnected
  203. */
  204. public function testConstructorWithNullAndArrayArgument()
  205. {
  206. $connections = $this->getMock('Predis\Connection\FactoryInterface');
  207. $arg2 = array('prefix' => 'prefix:', 'connections' => $connections);
  208. $client = new Client(null, $arg2);
  209. $this->assertInstanceOf('Predis\Command\FactoryInterface', $commands = $client->getCommandFactory());
  210. $this->assertInstanceOf('Predis\Command\Processor\KeyPrefixProcessor', $commands->getProcessor());
  211. $this->assertSame('prefix:', $commands->getProcessor()->getPrefix());
  212. }
  213. /**
  214. * @group disconnected
  215. */
  216. public function testConstructorWithArrayAndOptionReplication()
  217. {
  218. $arg1 = array('tcp://host1?alias=master', 'tcp://host2?alias=slave');
  219. $arg2 = array('replication' => 'predis');
  220. $client = new Client($arg1, $arg2);
  221. $this->assertInstanceOf('Predis\Connection\Replication\ReplicationInterface', $connection = $client->getConnection());
  222. $this->assertSame('host1', $connection->getConnectionById('master')->getParameters()->host);
  223. $this->assertSame('host2', $connection->getConnectionById('slave')->getParameters()->host);
  224. }
  225. /**
  226. * @group disconnected
  227. */
  228. public function testClusterOptionHasPrecedenceOverReplicationOptionAndAggregateOption()
  229. {
  230. $arg1 = array('tcp://host1', 'tcp://host2');
  231. $connection = $this->getMock('Predis\Connection\AggregateConnectionInterface');
  232. $fncluster = $this->getMock('stdClass', array('__invoke'));
  233. $fncluster->expects($this->once())
  234. ->method('__invoke')
  235. ->with($this->isInstanceOf('Predis\Configuration\OptionsInterface'), $arg1)
  236. ->will($this->returnValue($connection));
  237. $fnreplication = $this->getMock('stdClass', array('__invoke'));
  238. $fnreplication->expects($this->never())->method('__invoke');
  239. $fnaggregate = $this->getMock('stdClass', array('__invoke'));
  240. $fnaggregate->expects($this->never())->method('__invoke');
  241. $arg2 = array(
  242. 'cluster' => $fncluster,
  243. 'replication' => $fnreplication,
  244. 'aggregate' => $fnaggregate,
  245. );
  246. $client = new Client($arg1, $arg2);
  247. $this->assertSame($connection, $client->getConnection());
  248. }
  249. /**
  250. * @group disconnected
  251. */
  252. public function testReplicationOptionHasPrecedenceOverAggregateOption()
  253. {
  254. $arg1 = array('tcp://host1', 'tcp://host2');
  255. $connection = $this->getMock('Predis\Connection\AggregateConnectionInterface');
  256. $fnreplication = $this->getMock('stdClass', array('__invoke'));
  257. $fnreplication->expects($this->once())
  258. ->method('__invoke')
  259. ->with($this->isInstanceOf('Predis\Configuration\OptionsInterface'), $arg1)
  260. ->will($this->returnValue($connection));
  261. $fnaggregate = $this->getMock('stdClass', array('__invoke'));
  262. $fnaggregate->expects($this->never())->method('__invoke');
  263. $arg2 = array(
  264. 'replication' => $fnreplication,
  265. 'aggregate' => $fnaggregate,
  266. );
  267. $client = new Client($arg1, $arg2);
  268. $this->assertSame($connection, $client->getConnection());
  269. }
  270. /**
  271. * @group disconnected
  272. */
  273. public function testAggregateOptionDoesNotTriggerAggregationInClient()
  274. {
  275. $arg1 = array('tcp://host1', 'tcp://host2');
  276. $connection = $this->getMock('Predis\Connection\AggregateConnectionInterface');
  277. $fnaggregate = $this->getMock('stdClass', array('__invoke'));
  278. $fnaggregate->expects($this->once())
  279. ->method('__invoke')
  280. ->with($this->isInstanceOf('Predis\Configuration\OptionsInterface'), $arg1)
  281. ->will($this->returnValue($connection));
  282. $connections = $this->getMock('Predis\Connection\FactoryInterface');
  283. $connections->expects($this->never())
  284. ->method('aggregate');
  285. $arg2 = array('aggregate' => $fnaggregate, 'connections' => $connections);
  286. $client = new Client($arg1, $arg2);
  287. $this->assertSame($connection, $client->getConnection());
  288. }
  289. /**
  290. * @group disconnected
  291. * @expectedException \InvalidArgumentException
  292. * @expectedExceptionMessage Invalid type for connection parameters
  293. */
  294. public function testConstructorWithInvalidArgumentType()
  295. {
  296. $client = new Client(new \stdClass);
  297. }
  298. /**
  299. * @group disconnected
  300. * @expectedException \InvalidArgumentException
  301. * @expectedExceptionMessage Invalid type for client options
  302. */
  303. public function testConstructorWithInvalidOptionType()
  304. {
  305. $client = new Client('tcp://host1', new \stdClass);
  306. }
  307. /**
  308. * @group disconnected
  309. */
  310. public function testConnectAndDisconnect()
  311. {
  312. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  313. $connection->expects($this->once())->method('connect');
  314. $connection->expects($this->once())->method('disconnect');
  315. $client = new Client($connection);
  316. $client->connect();
  317. $client->disconnect();
  318. }
  319. /**
  320. * @group disconnected
  321. */
  322. public function testIsConnectedChecksConnectionState()
  323. {
  324. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  325. $connection->expects($this->once())->method('isConnected');
  326. $client = new Client($connection);
  327. $client->isConnected();
  328. }
  329. /**
  330. * @group disconnected
  331. */
  332. public function testQuitIsAliasForDisconnect()
  333. {
  334. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  335. $connection->expects($this->once())->method('disconnect');
  336. $client = new Client($connection);
  337. $client->quit();
  338. }
  339. /**
  340. * @group disconnected
  341. */
  342. public function testCreatesNewCommandUsingSpecifiedCommandFactory()
  343. {
  344. $ping = $this->getCommandFactory()->createCommand('ping', array());
  345. $commands = $this->getMock('Predis\Command\FactoryInterface');
  346. $commands->expects($this->once())
  347. ->method('createCommand')
  348. ->with('ping', array())
  349. ->will($this->returnValue($ping));
  350. $client = new Client(null, array('commands' => $commands));
  351. $this->assertSame($ping, $client->createCommand('ping', array()));
  352. }
  353. /**
  354. * @group disconnected
  355. */
  356. public function testExecuteCommandReturnsParsedResponses()
  357. {
  358. $commands = $this->getCommandFactory();
  359. $ping = $commands->createCommand('ping', array());
  360. $hgetall = $commands->createCommand('hgetall', array('metavars', 'foo', 'hoge'));
  361. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  362. $connection->expects($this->at(0))
  363. ->method('executeCommand')
  364. ->with($ping)
  365. ->will($this->returnValue(new Response\Status('PONG')));
  366. $connection->expects($this->at(1))
  367. ->method('executeCommand')
  368. ->with($hgetall)
  369. ->will($this->returnValue(array('foo', 'bar', 'hoge', 'piyo')));
  370. $client = new Client($connection);
  371. $this->assertEquals('PONG', $client->executeCommand($ping));
  372. $this->assertSame(array('foo' => 'bar', 'hoge' => 'piyo'), $client->executeCommand($hgetall));
  373. }
  374. /**
  375. * @group disconnected
  376. * @expectedException \Predis\Response\ServerException
  377. * @expectedExceptionMessage Operation against a key holding the wrong kind of value
  378. */
  379. public function testExecuteCommandThrowsExceptionOnRedisError()
  380. {
  381. $ping = $this->getCommandFactory()->createCommand('ping', array());
  382. $expectedResponse = new Response\Error('ERR Operation against a key holding the wrong kind of value');
  383. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  384. $connection->expects($this->once())
  385. ->method('executeCommand')
  386. ->will($this->returnValue($expectedResponse));
  387. $client = new Client($connection);
  388. $client->executeCommand($ping);
  389. }
  390. /**
  391. * @group disconnected
  392. */
  393. public function testExecuteCommandReturnsErrorResponseOnRedisError()
  394. {
  395. $ping = $this->getCommandFactory()->createCommand('ping', array());
  396. $expectedResponse = new Response\Error('ERR Operation against a key holding the wrong kind of value');
  397. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  398. $connection->expects($this->once())
  399. ->method('executeCommand')
  400. ->will($this->returnValue($expectedResponse));
  401. $client = new Client($connection, array('exceptions' => false));
  402. $response = $client->executeCommand($ping);
  403. $this->assertSame($response, $expectedResponse);
  404. }
  405. /**
  406. * @group disconnected
  407. */
  408. public function testCallingRedisCommandExecutesInstanceOfCommand()
  409. {
  410. $ping = $this->getCommandFactory()->createCommand('ping', array());
  411. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  412. $connection->expects($this->once())
  413. ->method('executeCommand')
  414. ->with($this->isInstanceOf('Predis\Command\Redis\PING'))
  415. ->will($this->returnValue('PONG'));
  416. $commands = $this->getMock('Predis\Command\FactoryInterface');
  417. $commands->expects($this->once())
  418. ->method('createCommand')
  419. ->with('ping', array())
  420. ->will($this->returnValue($ping));
  421. $options = array('commands' => $commands);
  422. $client = $this->getMock('Predis\Client', null, array($connection, $options));
  423. $this->assertEquals('PONG', $client->ping());
  424. }
  425. /**
  426. * @group disconnected
  427. * @expectedException \Predis\Response\ServerException
  428. * @expectedExceptionMessage Operation against a key holding the wrong kind of value
  429. */
  430. public function testCallingRedisCommandThrowsExceptionOnServerError()
  431. {
  432. $expectedResponse = new Response\Error('ERR Operation against a key holding the wrong kind of value');
  433. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  434. $connection->expects($this->once())
  435. ->method('executeCommand')
  436. ->with($this->isRedisCommand('PING'))
  437. ->will($this->returnValue($expectedResponse));
  438. $client = new Client($connection);
  439. $client->ping();
  440. }
  441. /**
  442. * @group disconnected
  443. */
  444. public function testCallingRedisCommandReturnsErrorResponseOnRedisError()
  445. {
  446. $expectedResponse = new Response\Error('ERR Operation against a key holding the wrong kind of value');
  447. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  448. $connection->expects($this->once())
  449. ->method('executeCommand')
  450. ->with($this->isRedisCommand('PING'))
  451. ->will($this->returnValue($expectedResponse));
  452. $client = new Client($connection, array('exceptions' => false));
  453. $response = $client->ping();
  454. $this->assertSame($response, $expectedResponse);
  455. }
  456. /**
  457. * @group disconnected
  458. */
  459. public function testRawCommand()
  460. {
  461. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  462. $connection->expects($this->at(0))
  463. ->method('executeCommand')
  464. ->with($this->isRedisCommand('SET', array('foo', 'bar')))
  465. ->will($this->returnValue(new Response\Status('OK')));
  466. $connection->expects($this->at(1))
  467. ->method('executeCommand')
  468. ->with($this->isRedisCommand('GET', array('foo')))
  469. ->will($this->returnValue('bar'));
  470. $connection->expects($this->at(2))
  471. ->method('executeCommand')
  472. ->with($this->isRedisCommand('PING'))
  473. ->will($this->returnValue('PONG'));
  474. $client = new Client($connection);
  475. $this->assertSame('OK', $client->executeRaw(array('SET', 'foo', 'bar')));
  476. $this->assertSame('bar', $client->executeRaw(array('GET', 'foo')));
  477. $error = true; // $error is always populated by reference.
  478. $this->assertSame('PONG', $client->executeRaw(array('PING'), $error));
  479. $this->assertFalse($error);
  480. }
  481. /**
  482. * @group disconnected
  483. */
  484. public function testRawCommandNeverAppliesPrefix()
  485. {
  486. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  487. $connection->expects($this->at(0))
  488. ->method('executeCommand')
  489. ->with($this->isRedisCommand('SET', array('foo', 'bar')))
  490. ->will($this->returnValue(new Response\Status('OK')));
  491. $connection->expects($this->at(1))
  492. ->method('executeCommand')
  493. ->with($this->isRedisCommand('GET', array('foo')))
  494. ->will($this->returnValue('bar'));
  495. $client = new Client($connection, array('prefix' => 'predis:'));
  496. $this->assertSame('OK', $client->executeRaw(array('SET', 'foo', 'bar')));
  497. $this->assertSame('bar', $client->executeRaw(array('GET', 'foo')));
  498. }
  499. /**
  500. * @group disconnected
  501. */
  502. public function testRawCommandNeverThrowsExceptions()
  503. {
  504. $message = 'ERR Mock error response';
  505. $response = new Response\Error($message);
  506. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  507. $connection->expects($this->once())
  508. ->method('executeCommand')
  509. ->with($this->isRedisCommand('PING'))
  510. ->will($this->returnValue($response));
  511. $client = new Client($connection, array('exceptions' => true));
  512. $this->assertSame($message, $client->executeRaw(array('PING'), $error));
  513. $this->assertTrue($error);
  514. }
  515. /**
  516. * @group disconnected
  517. * @expectedException \Predis\ClientException
  518. * @expectedExceptionMessage Command 'INVALIDCOMMAND' is not a registered Redis command.
  519. */
  520. public function testThrowsExceptionOnNonRegisteredRedisCommand()
  521. {
  522. $client = new Client();
  523. $client->invalidCommand();
  524. }
  525. /**
  526. * @group disconnected
  527. */
  528. public function testGetConnectionFromAggregateConnectionWithAlias()
  529. {
  530. $client = new Client(array('tcp://host1?alias=node01', 'tcp://host2?alias=node02'), array('cluster' => 'predis'));
  531. $this->assertInstanceOf('Predis\Connection\Cluster\ClusterInterface', $cluster = $client->getConnection());
  532. $this->assertInstanceOf('Predis\Connection\NodeConnectionInterface', $node01 = $client->getConnectionById('node01'));
  533. $this->assertInstanceOf('Predis\Connection\NodeConnectionInterface', $node02 = $client->getConnectionById('node02'));
  534. $this->assertSame('host1', $node01->getParameters()->host);
  535. $this->assertSame('host2', $node02->getParameters()->host);
  536. }
  537. /**
  538. * @group disconnected
  539. * @expectedException \Predis\NotSupportedException
  540. * @expectedExceptionMessage Retrieving connections by ID is supported only by aggregate connections.
  541. */
  542. public function testGetConnectionByIdWorksOnlyWithAggregateConnections()
  543. {
  544. $client = new Client();
  545. $client->getConnectionById('node01');
  546. }
  547. /**
  548. * @group disconnected
  549. */
  550. public function testOnMethodCreatesClientWithConnectionFromAggregateConnection()
  551. {
  552. $client = new Client(array('tcp://host1?alias=node01', 'tcp://host2?alias=node02'), array('prefix' => 'pfx:', 'cluster' => 'predis'));
  553. $this->assertInstanceOf('Predis\Connection\Cluster\ClusterInterface', $cluster = $client->getConnection());
  554. $this->assertInstanceOf('Predis\Connection\NodeConnectionInterface', $node01 = $client->getConnectionById('node01'));
  555. $this->assertInstanceOf('Predis\Connection\NodeConnectionInterface', $node02 = $client->getConnectionById('node02'));
  556. $clientNode02 = $client->on('node02');
  557. $this->assertInstanceOf('Predis\Client', $clientNode02);
  558. $this->assertSame($node02, $clientNode02->getConnection());
  559. $this->assertSame($client->getOptions(), $clientNode02->getOptions());
  560. }
  561. /**
  562. * @group disconnected
  563. */
  564. public function testOnMethodReturnsInstanceOfSubclass()
  565. {
  566. $nodes = array('tcp://host1?alias=node01', 'tcp://host2?alias=node02');
  567. $client = $this->getMock('Predis\Client', array('dummy'), array($nodes, array('cluster' => 'predis')), 'SubclassedClient');
  568. $this->assertInstanceOf('SubclassedClient', $client->on('node02'));
  569. }
  570. /**
  571. * @group disconnected
  572. */
  573. public function testOnMethodInvokesCallableInSecondArgumentAndReturnsItsReturnValue()
  574. {
  575. $test = $this;
  576. $client = new Client(array('tcp://host1?alias=node01', 'tcp://host2?alias=node02'), array('cluster' => 'predis'));
  577. $callable = $this->getMock('stdClass', array('__invoke'));
  578. $callable->expects($this->once())
  579. ->method('__invoke')
  580. ->with($this->callback(function ($clientNode) use ($test, $client) {
  581. $test->isInstanceOf('Predis\ClientInterface', $clientNode);
  582. $test->assertNotSame($client, $clientNode);
  583. $test->assertInstanceOf('Predis\Connection\NodeConnectionInterface', $connection = $clientNode->getConnection());
  584. $test->assertSame('node02', $connection->getParameters()->alias);
  585. return true;
  586. }))
  587. ->will($this->returnValue('value'));
  588. $this->assertSame('value', $client->on('node02', $callable));
  589. }
  590. /**
  591. * @group disconnected
  592. * @expectedException \Predis\NotSupportedException
  593. * @expectedExceptionMessage Retrieving connections by ID is supported only by aggregate connections
  594. */
  595. public function testOnMethodThrowsExceptionWithNodeConnection()
  596. {
  597. $client = new Client('tcp://127.0.0.1?alias=node01');
  598. $client->on('node01');
  599. }
  600. /**
  601. * @group disconnected
  602. * @expectedException \InvalidArgumentException
  603. * @expectedExceptionMessage Invalid connection ID: `nodeXX`
  604. */
  605. public function testOnMethodThrowsExceptionWithUnknownConnectionID()
  606. {
  607. $client = new Client(array('tcp://host1?alias=node01', 'tcp://host2?alias=node02'), array('cluster' => 'predis'));
  608. $client->on('nodeXX');
  609. }
  610. /**
  611. * @group disconnected
  612. */
  613. public function testPipelineWithoutArgumentsReturnsPipeline()
  614. {
  615. $client = new Client();
  616. $this->assertInstanceOf('Predis\Pipeline\Pipeline', $client->pipeline());
  617. }
  618. /**
  619. * @group disconnected
  620. */
  621. public function testPipelineWithArrayReturnsPipeline()
  622. {
  623. $client = new Client();
  624. $this->assertInstanceOf('Predis\Pipeline\Pipeline', $client->pipeline(array()));
  625. $this->assertInstanceOf('Predis\Pipeline\Atomic', $client->pipeline(array('atomic' => true)));
  626. $this->assertInstanceOf('Predis\Pipeline\FireAndForget', $client->pipeline(array('fire-and-forget' => true)));
  627. }
  628. /**
  629. * @group disconnected
  630. */
  631. public function testPipelineWithCallableExecutesPipeline()
  632. {
  633. $callable = $this->getMock('stdClass', array('__invoke'));
  634. $callable->expects($this->once())
  635. ->method('__invoke')
  636. ->with($this->isInstanceOf('Predis\Pipeline\Pipeline'));
  637. $client = new Client();
  638. $client->pipeline($callable);
  639. }
  640. /**
  641. * @group disconnected
  642. */
  643. public function testPubSubLoopWithoutArgumentsReturnsPubSubConsumer()
  644. {
  645. $client = new Client();
  646. $this->assertInstanceOf('Predis\PubSub\Consumer', $client->pubSubLoop());
  647. }
  648. /**
  649. * @group disconnected
  650. */
  651. public function testPubSubLoopWithArrayReturnsPubSubConsumerWithOptions()
  652. {
  653. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  654. $options = array('subscribe' => 'channel');
  655. $client = new Client($connection);
  656. $this->assertInstanceOf('Predis\PubSub\Consumer', $pubsub = $client->pubSubLoop($options));
  657. $reflection = new \ReflectionProperty($pubsub, 'options');
  658. $reflection->setAccessible(true);
  659. $this->assertSame($options, $reflection->getValue($pubsub));
  660. }
  661. /**
  662. * @group disconnected
  663. */
  664. public function testPubSubLoopWithArrayAndCallableExecutesPubSub()
  665. {
  666. // NOTE: we use a subscribe count of 0 in the message payload to trick
  667. // the context and forcing it to be closed since there are no more
  668. // active subscriptions.
  669. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  670. $connection->expects($this->once())
  671. ->method('read')
  672. ->will($this->returnValue(array('subscribe', 'channel', 0)));
  673. $callable = $this->getMock('stdClass', array('__invoke'));
  674. $callable->expects($this->once())
  675. ->method('__invoke');
  676. $client = new Client($connection);
  677. $this->assertNull($client->pubSubLoop(array('subscribe' => 'channel'), $callable));
  678. }
  679. /**
  680. * @group disconnected
  681. */
  682. public function testPubSubLoopWithCallableReturningFalseStopsPubSubConsumer()
  683. {
  684. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  685. $connection->expects($this->at(1))
  686. ->method('read')
  687. ->will($this->returnValue(array('subscribe', 'channel', 1)));
  688. $connection->expects($this->at(2))
  689. ->method('writeRequest')
  690. ->with($this->isRedisCommand('UNSUBSCRIBE'));
  691. $connection->expects($this->at(3))
  692. ->method('read')
  693. ->will($this->returnValue(array('unsubscribe', 'channel', 0)));
  694. $callable = $this->getMock('stdClass', array('__invoke'));
  695. $callable->expects($this->at(0))
  696. ->method('__invoke')
  697. ->will($this->returnValue(false));
  698. $client = new Client($connection);
  699. $this->assertNull($client->pubSubLoop(array('subscribe' => 'channel'), $callable));
  700. }
  701. /**
  702. * @group disconnected
  703. */
  704. public function testTransactionWithoutArgumentsReturnsMultiExec()
  705. {
  706. $client = new Client();
  707. $this->assertInstanceOf('Predis\Transaction\MultiExec', $client->transaction());
  708. }
  709. /**
  710. * @group disconnected
  711. */
  712. public function testTransactionWithArrayReturnsMultiExecTransactionWithOptions()
  713. {
  714. $options = array('cas' => true, 'retry' => 3);
  715. $client = new Client();
  716. $this->assertInstanceOf('Predis\Transaction\MultiExec', $tx = $client->transaction($options));
  717. // I hate this part but reflection is the easiest way in this case.
  718. $property = new \ReflectionProperty($tx, 'modeCAS');
  719. $property->setAccessible(true);
  720. $this->assertSame($options['cas'], $property->getValue($tx));
  721. $property = new \ReflectionProperty($tx, 'attempts');
  722. $property->setAccessible(true);
  723. $this->assertSame($options['retry'], $property->getValue($tx));
  724. }
  725. /**
  726. * @group disconnected
  727. */
  728. public function testTransactionWithArrayAndCallableExecutesMultiExec()
  729. {
  730. // We use CAS here as we don't care about the actual MULTI/EXEC context.
  731. $options = array('cas' => true, 'retry' => 3);
  732. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  733. $connection->expects($this->once())
  734. ->method('executeCommand')
  735. ->will($this->returnValue(new Response\Status('QUEUED')));
  736. $txCallback = function ($tx) {
  737. $tx->ping();
  738. };
  739. $callable = $this->getMock('stdClass', array('__invoke'));
  740. $callable->expects($this->once())
  741. ->method('__invoke')
  742. ->will($this->returnCallback($txCallback));
  743. $client = new Client($connection);
  744. $client->transaction($options, $callable);
  745. }
  746. /**
  747. * @group disconnected
  748. */
  749. public function testMonitorReturnsMonitorConsumer()
  750. {
  751. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  752. $client = new Client($connection);
  753. $this->assertInstanceOf('Predis\Monitor\Consumer', $monitor = $client->monitor());
  754. }
  755. /**
  756. * @group disconnected
  757. */
  758. public function testClientResendScriptCommandUsingEvalOnNoScriptErrors()
  759. {
  760. $command = $this->getMockForAbstractClass('Predis\Command\ScriptCommand', array(), '', true, true, true, array('parseResponse'));
  761. $command->expects($this->once())
  762. ->method('getScript')
  763. ->will($this->returnValue('return redis.call(\'exists\', KEYS[1])'));
  764. $command->expects($this->once())
  765. ->method('parseResponse')
  766. ->with('OK')
  767. ->will($this->returnValue(true));
  768. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  769. $connection->expects($this->at(0))
  770. ->method('executeCommand')
  771. ->with($command)
  772. ->will($this->returnValue(new Response\Error('NOSCRIPT')));
  773. $connection->expects($this->at(1))
  774. ->method('executeCommand')
  775. ->with($this->isRedisCommand('EVAL'))
  776. ->will($this->returnValue('OK'));
  777. $client = new Client($connection);
  778. $this->assertTrue($client->executeCommand($command));
  779. }
  780. /**
  781. * @group disconnected
  782. */
  783. public function testGetIteratorWithTraversableConnections()
  784. {
  785. $connection1 = $this->getMockConnection('tcp://127.0.0.1:6381');
  786. $connection2 = $this->getMockConnection('tcp://127.0.0.1:6382');
  787. $connection3 = $this->getMockConnection('tcp://127.0.0.1:6383');
  788. $aggregate = new \Predis\Connection\Cluster\PredisCluster();
  789. $aggregate->add($connection1);
  790. $aggregate->add($connection2);
  791. $aggregate->add($connection3);
  792. $client = new Client($aggregate);
  793. $iterator = $client->getIterator();
  794. $this->assertInstanceOf('\Predis\Client', $nodeClient = $iterator->current());
  795. $this->assertSame($connection1, $nodeClient->getConnection());
  796. $this->assertSame('127.0.0.1:6381', $iterator->key());
  797. $iterator->next();
  798. $this->assertInstanceOf('\Predis\Client', $nodeClient = $iterator->current());
  799. $this->assertSame($connection2, $nodeClient->getConnection());
  800. $this->assertSame('127.0.0.1:6382', $iterator->key());
  801. $iterator->next();
  802. $this->assertInstanceOf('\Predis\Client', $nodeClient = $iterator->current());
  803. $this->assertSame($connection3, $nodeClient->getConnection());
  804. $this->assertSame('127.0.0.1:6383', $iterator->key());
  805. }
  806. /**
  807. * @group disconnected
  808. * @expectedException \Predis\ClientException
  809. * @expectedExceptionMessage The underlying connection is not traversable
  810. */
  811. public function testGetIteratorWithNonTraversableConnectionThrowsException()
  812. {
  813. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  814. $client = new Client($connection);
  815. $client->getIterator();
  816. }
  817. // ******************************************************************** //
  818. // ---- HELPER METHODS ------------------------------------------------ //
  819. // ******************************************************************** //
  820. /**
  821. * Returns an URI string representation of the specified connection parameters.
  822. *
  823. * @param array $parameters Array of connection parameters.
  824. *
  825. * @return string URI string.
  826. */
  827. protected function getParametersString(array $parameters)
  828. {
  829. $defaults = $this->getDefaultParametersArray();
  830. $scheme = isset($parameters['scheme']) ? $parameters['scheme'] : $defaults['scheme'];
  831. $host = isset($parameters['host']) ? $parameters['host'] : $defaults['host'];
  832. $port = isset($parameters['port']) ? $parameters['port'] : $defaults['port'];
  833. unset($parameters['scheme'], $parameters['host'], $parameters['port']);
  834. $uriString = "$scheme://$host:$port/?";
  835. foreach ($parameters as $k => $v) {
  836. $uriString .= "$k=$v&";
  837. }
  838. return $uriString;
  839. }
  840. /**
  841. * Returns a mock callable simulating an aggregate connection initializer.
  842. *
  843. * @param mixed $parameters Expected connection parameters
  844. *
  845. * @return callable
  846. */
  847. protected function getAggregateInitializer($parameters)
  848. {
  849. $connection = $this->getMock('Predis\Connection\AggregateConnectionInterface');
  850. $callable = $this->getMock('stdClass', array('__invoke'));
  851. $callable->expects($this->once())
  852. ->method('__invoke')
  853. ->with($this->isInstanceOf('Predis\Configuration\OptionsInterface'), $parameters)
  854. ->will($this->returnValue($connection));
  855. return $callable;
  856. }
  857. }