ClientTest.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  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
  180. ->expects($this->once())
  181. ->method('__invoke')
  182. ->with($this->isInstanceOf('Predis\Configuration\OptionsInterface'))
  183. ->will($this->returnValue($connection));
  184. $client = new Client($callable);
  185. $this->assertSame($connection, $client->getConnection());
  186. }
  187. /**
  188. * @group disconnected
  189. * @expectedException \InvalidArgumentException
  190. * @expectedExceptionMessage Callable parameters must return a valid connection
  191. */
  192. public function testConstructorWithCallableConnectionInitializerThrowsExceptionOnInvalidReturnType()
  193. {
  194. $wrongType = $this->getMock('stdClass');
  195. $callable = $this->getMock('stdClass', array('__invoke'));
  196. $callable
  197. ->expects($this->once())
  198. ->method('__invoke')
  199. ->with($this->isInstanceOf('Predis\Configuration\OptionsInterface'))
  200. ->will($this->returnValue($wrongType));
  201. new Client($callable);
  202. }
  203. /**
  204. * @group disconnected
  205. */
  206. public function testConstructorWithNullAndArrayArgument()
  207. {
  208. $connections = $this->getMock('Predis\Connection\FactoryInterface');
  209. $arg2 = array('prefix' => 'prefix:', 'connections' => $connections);
  210. $client = new Client(null, $arg2);
  211. $this->assertInstanceOf('Predis\Command\FactoryInterface', $commands = $client->getCommandFactory());
  212. $this->assertInstanceOf('Predis\Command\Processor\KeyPrefixProcessor', $commands->getProcessor());
  213. $this->assertSame('prefix:', $commands->getProcessor()->getPrefix());
  214. }
  215. /**
  216. * @group disconnected
  217. */
  218. public function testConstructorWithArrayAndOptionReplication()
  219. {
  220. $arg1 = array('tcp://127.0.0.1:6379?role=master', 'tcp://127.0.0.1:6380?role=slave');
  221. $arg2 = array('replication' => 'predis');
  222. $client = new Client($arg1, $arg2);
  223. $this->assertInstanceOf('Predis\Connection\Replication\ReplicationInterface', $connection = $client->getConnection());
  224. $this->assertSame('127.0.0.1:6379', (string) $connection->getConnectionByRole('master'));
  225. $this->assertSame('127.0.0.1:6380', (string) $connection->getConnectionByRole('slave'));
  226. }
  227. /**
  228. * @group disconnected
  229. */
  230. public function testClusterOptionHasPrecedenceOverReplicationOptionAndAggregateOption()
  231. {
  232. $arg1 = array('tcp://host1', 'tcp://host2');
  233. $connection = $this->getMock('Predis\Connection\AggregateConnectionInterface');
  234. $fncluster = $this->getMock('stdClass', array('__invoke'));
  235. $fncluster
  236. ->expects($this->once())
  237. ->method('__invoke')
  238. ->with($this->isInstanceOf('Predis\Configuration\OptionsInterface'), $arg1)
  239. ->will($this->returnValue($connection));
  240. $fnreplication = $this->getMock('stdClass', array('__invoke'));
  241. $fnreplication
  242. ->expects($this->never())
  243. ->method('__invoke');
  244. $fnaggregate = $this->getMock('stdClass', array('__invoke'));
  245. $fnaggregate
  246. ->expects($this->never())
  247. ->method('__invoke');
  248. $arg2 = array(
  249. 'cluster' => $fncluster,
  250. 'replication' => $fnreplication,
  251. 'aggregate' => $fnaggregate,
  252. );
  253. $client = new Client($arg1, $arg2);
  254. $this->assertSame($connection, $client->getConnection());
  255. }
  256. /**
  257. * @group disconnected
  258. */
  259. public function testReplicationOptionHasPrecedenceOverAggregateOption()
  260. {
  261. $arg1 = array('tcp://host1', 'tcp://host2');
  262. $connection = $this->getMock('Predis\Connection\AggregateConnectionInterface');
  263. $fnreplication = $this->getMock('stdClass', array('__invoke'));
  264. $fnreplication
  265. ->expects($this->once())
  266. ->method('__invoke')
  267. ->with($this->isInstanceOf('Predis\Configuration\OptionsInterface'), $arg1)
  268. ->will($this->returnValue($connection));
  269. $fnaggregate = $this->getMock('stdClass', array('__invoke'));
  270. $fnaggregate->expects($this->never())->method('__invoke');
  271. $arg2 = array(
  272. 'replication' => $fnreplication,
  273. 'aggregate' => $fnaggregate,
  274. );
  275. $client = new Client($arg1, $arg2);
  276. $this->assertSame($connection, $client->getConnection());
  277. }
  278. /**
  279. * @group disconnected
  280. */
  281. public function testAggregateOptionDoesNotTriggerAggregationInClient()
  282. {
  283. $arg1 = array('tcp://host1', 'tcp://host2');
  284. $connection = $this->getMock('Predis\Connection\AggregateConnectionInterface');
  285. $fnaggregate = $this->getMock('stdClass', array('__invoke'));
  286. $fnaggregate
  287. ->expects($this->once())
  288. ->method('__invoke')
  289. ->with($this->isInstanceOf('Predis\Configuration\OptionsInterface'), $arg1)
  290. ->will($this->returnValue($connection));
  291. $connections = $this->getMock('Predis\Connection\FactoryInterface');
  292. $connections
  293. ->expects($this->never())
  294. ->method('aggregate');
  295. $arg2 = array('aggregate' => $fnaggregate, 'connections' => $connections);
  296. $client = new Client($arg1, $arg2);
  297. $this->assertSame($connection, $client->getConnection());
  298. }
  299. /**
  300. * @group disconnected
  301. * @expectedException \InvalidArgumentException
  302. * @expectedExceptionMessage Invalid type for connection parameters
  303. */
  304. public function testConstructorWithInvalidArgumentType()
  305. {
  306. $client = new Client(new \stdClass());
  307. }
  308. /**
  309. * @group disconnected
  310. * @expectedException \InvalidArgumentException
  311. * @expectedExceptionMessage Invalid type for client options
  312. */
  313. public function testConstructorWithInvalidOptionType()
  314. {
  315. $client = new Client('tcp://host1', new \stdClass());
  316. }
  317. /**
  318. * @group disconnected
  319. */
  320. public function testConnectAndDisconnect()
  321. {
  322. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  323. $connection
  324. ->expects($this->once())
  325. ->method('connect');
  326. $connection
  327. ->expects($this->once())
  328. ->method('disconnect');
  329. $client = new Client($connection);
  330. $client->connect();
  331. $client->disconnect();
  332. }
  333. /**
  334. * @group disconnected
  335. */
  336. public function testIsConnectedChecksConnectionState()
  337. {
  338. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  339. $connection
  340. ->expects($this->once())
  341. ->method('isConnected');
  342. $client = new Client($connection);
  343. $client->isConnected();
  344. }
  345. /**
  346. * @group disconnected
  347. */
  348. public function testQuitIsAliasForDisconnect()
  349. {
  350. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  351. $connection
  352. ->expects($this->once())
  353. ->method('disconnect');
  354. $client = new Client($connection);
  355. $client->quit();
  356. }
  357. /**
  358. * @group disconnected
  359. */
  360. public function testCreatesNewCommandUsingSpecifiedCommandFactory()
  361. {
  362. $ping = $this->getCommandFactory()->createCommand('ping', array());
  363. $commands = $this->getMock('Predis\Command\FactoryInterface');
  364. $commands
  365. ->expects($this->once())
  366. ->method('createCommand')
  367. ->with('ping', array())
  368. ->will($this->returnValue($ping));
  369. $client = new Client(null, array('commands' => $commands));
  370. $this->assertSame($ping, $client->createCommand('ping', array()));
  371. }
  372. /**
  373. * @group disconnected
  374. */
  375. public function testExecuteCommandReturnsParsedResponses()
  376. {
  377. $commands = $this->getCommandFactory();
  378. $ping = $commands->createCommand('ping', array());
  379. $hgetall = $commands->createCommand('hgetall', array('metavars', 'foo', 'hoge'));
  380. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  381. $connection
  382. ->expects($this->at(0))
  383. ->method('executeCommand')
  384. ->with($ping)
  385. ->will($this->returnValue(new Response\Status('PONG')));
  386. $connection
  387. ->expects($this->at(1))
  388. ->method('executeCommand')
  389. ->with($hgetall)
  390. ->will($this->returnValue(array('foo', 'bar', 'hoge', 'piyo')));
  391. $client = new Client($connection);
  392. $this->assertEquals('PONG', $client->executeCommand($ping));
  393. $this->assertSame(array('foo' => 'bar', 'hoge' => 'piyo'), $client->executeCommand($hgetall));
  394. }
  395. /**
  396. * @group disconnected
  397. * @expectedException \Predis\Response\ServerException
  398. * @expectedExceptionMessage Operation against a key holding the wrong kind of value
  399. */
  400. public function testExecuteCommandThrowsExceptionOnRedisError()
  401. {
  402. $ping = $this->getCommandFactory()->createCommand('ping', array());
  403. $expectedResponse = new Response\Error('ERR Operation against a key holding the wrong kind of value');
  404. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  405. $connection
  406. ->expects($this->once())
  407. ->method('executeCommand')
  408. ->will($this->returnValue($expectedResponse));
  409. $client = new Client($connection);
  410. $client->executeCommand($ping);
  411. }
  412. /**
  413. * @group disconnected
  414. */
  415. public function testExecuteCommandReturnsErrorResponseOnRedisError()
  416. {
  417. $ping = $this->getCommandFactory()->createCommand('ping', array());
  418. $expectedResponse = new Response\Error('ERR Operation against a key holding the wrong kind of value');
  419. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  420. $connection
  421. ->expects($this->once())
  422. ->method('executeCommand')
  423. ->will($this->returnValue($expectedResponse));
  424. $client = new Client($connection, array('exceptions' => false));
  425. $response = $client->executeCommand($ping);
  426. $this->assertSame($response, $expectedResponse);
  427. }
  428. /**
  429. * @group disconnected
  430. */
  431. public function testCallingRedisCommandExecutesInstanceOfCommand()
  432. {
  433. $ping = $this->getCommandFactory()->createCommand('ping', array());
  434. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  435. $connection
  436. ->expects($this->once())
  437. ->method('executeCommand')
  438. ->with($this->isInstanceOf('Predis\Command\Redis\PING'))
  439. ->will($this->returnValue('PONG'));
  440. $commands = $this->getMock('Predis\Command\FactoryInterface');
  441. $commands
  442. ->expects($this->once())
  443. ->method('createCommand')
  444. ->with('ping', array())
  445. ->will($this->returnValue($ping));
  446. $options = array('commands' => $commands);
  447. $client = $this->getMock('Predis\Client', null, array($connection, $options));
  448. $this->assertEquals('PONG', $client->ping());
  449. }
  450. /**
  451. * @group disconnected
  452. * @expectedException \Predis\Response\ServerException
  453. * @expectedExceptionMessage Operation against a key holding the wrong kind of value
  454. */
  455. public function testCallingRedisCommandThrowsExceptionOnServerError()
  456. {
  457. $expectedResponse = new Response\Error('ERR Operation against a key holding the wrong kind of value');
  458. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  459. $connection
  460. ->expects($this->once())
  461. ->method('executeCommand')
  462. ->with($this->isRedisCommand('PING'))
  463. ->will($this->returnValue($expectedResponse));
  464. $client = new Client($connection);
  465. $client->ping();
  466. }
  467. /**
  468. * @group disconnected
  469. */
  470. public function testCallingRedisCommandReturnsErrorResponseOnRedisError()
  471. {
  472. $expectedResponse = new Response\Error('ERR Operation against a key holding the wrong kind of value');
  473. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  474. $connection
  475. ->expects($this->once())
  476. ->method('executeCommand')
  477. ->with($this->isRedisCommand('PING'))
  478. ->will($this->returnValue($expectedResponse));
  479. $client = new Client($connection, array('exceptions' => false));
  480. $response = $client->ping();
  481. $this->assertSame($response, $expectedResponse);
  482. }
  483. /**
  484. * @group disconnected
  485. */
  486. public function testRawCommand()
  487. {
  488. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  489. $connection
  490. ->expects($this->at(0))
  491. ->method('executeCommand')
  492. ->with($this->isRedisCommand('SET', array('foo', 'bar')))
  493. ->will($this->returnValue(new Response\Status('OK')));
  494. $connection
  495. ->expects($this->at(1))
  496. ->method('executeCommand')
  497. ->with($this->isRedisCommand('GET', array('foo')))
  498. ->will($this->returnValue('bar'));
  499. $connection
  500. ->expects($this->at(2))
  501. ->method('executeCommand')
  502. ->with($this->isRedisCommand('PING'))
  503. ->will($this->returnValue('PONG'));
  504. $client = new Client($connection);
  505. $this->assertSame('OK', $client->executeRaw(array('SET', 'foo', 'bar')));
  506. $this->assertSame('bar', $client->executeRaw(array('GET', 'foo')));
  507. $error = true; // $error is always populated by reference.
  508. $this->assertSame('PONG', $client->executeRaw(array('PING'), $error));
  509. $this->assertFalse($error);
  510. }
  511. /**
  512. * @group disconnected
  513. */
  514. public function testRawCommandNeverAppliesPrefix()
  515. {
  516. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  517. $connection
  518. ->expects($this->at(0))
  519. ->method('executeCommand')
  520. ->with($this->isRedisCommand('SET', array('foo', 'bar')))
  521. ->will($this->returnValue(new Response\Status('OK')));
  522. $connection
  523. ->expects($this->at(1))
  524. ->method('executeCommand')
  525. ->with($this->isRedisCommand('GET', array('foo')))
  526. ->will($this->returnValue('bar'));
  527. $client = new Client($connection, array('prefix' => 'predis:'));
  528. $this->assertSame('OK', $client->executeRaw(array('SET', 'foo', 'bar')));
  529. $this->assertSame('bar', $client->executeRaw(array('GET', 'foo')));
  530. }
  531. /**
  532. * @group disconnected
  533. */
  534. public function testRawCommandNeverThrowsExceptions()
  535. {
  536. $message = 'ERR Mock error response';
  537. $response = new Response\Error($message);
  538. $connection = $this->getMock('Predis\Connection\ConnectionInterface');
  539. $connection
  540. ->expects($this->once())
  541. ->method('executeCommand')
  542. ->with($this->isRedisCommand('PING'))
  543. ->will($this->returnValue($response));
  544. $client = new Client($connection, array('exceptions' => true));
  545. $this->assertSame($message, $client->executeRaw(array('PING'), $error));
  546. $this->assertTrue($error);
  547. }
  548. /**
  549. * @group disconnected
  550. * @expectedException \Predis\ClientException
  551. * @expectedExceptionMessage Command 'INVALIDCOMMAND' is not a registered Redis command.
  552. */
  553. public function testThrowsExceptionOnNonRegisteredRedisCommand()
  554. {
  555. $client = new Client();
  556. $client->invalidCommand();
  557. }
  558. /**
  559. * @group disconnected
  560. */
  561. public function testGetClientByMethodReturnsInstanceOfSubclass()
  562. {
  563. $nodes = array('tcp://host1?alias=node01', 'tcp://host2?alias=node02');
  564. $client = $this->getMock('Predis\Client', array('dummy'), array($nodes, array('cluster' => 'predis')), 'SubclassedClient');
  565. $this->assertInstanceOf('SubclassedClient', $client->getClientBy('alias', 'node02'));
  566. }
  567. /**
  568. * @group disconnected
  569. */
  570. public function testGetClientByMethodInvokesCallableInSecondArgumentAndReturnsItsReturnValue()
  571. {
  572. $test = $this;
  573. $client = new Client(array('tcp://host1?alias=node01', 'tcp://host2?alias=node02'), array('cluster' => 'predis'));
  574. $callable = $this->getMock('stdClass', array('__invoke'));
  575. $callable
  576. ->expects($this->once())
  577. ->method('__invoke')
  578. ->with($this->callback(function ($clientNode) use ($test, $client) {
  579. $test->isInstanceOf('Predis\ClientInterface', $clientNode);
  580. $test->assertNotSame($client, $clientNode);
  581. $test->assertInstanceOf('Predis\Connection\NodeConnectionInterface', $connection = $clientNode->getConnection());
  582. $test->assertSame('node02', $connection->getParameters()->alias);
  583. return true;
  584. }))
  585. ->will($this->returnValue('value'));
  586. $this->assertSame('value', $client->getClientBy('alias', 'node02', $callable));
  587. }
  588. /**
  589. * @group disconnected
  590. */
  591. public function testGetClientByMethodSupportsSelectingConnectionById()
  592. {
  593. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  594. $aggregate = $this->getMockBuilder('Predis\Connection\AggregateConnectionInterface')
  595. ->setMethods(array('getConnectionById'))
  596. ->getMockForAbstractClass();
  597. $aggregate
  598. ->expects($this->once())
  599. ->method('getConnectionById')
  600. ->with('127.0.0.1:6379')
  601. ->will($this->returnValue($connection));
  602. $client = new Client($aggregate);
  603. $nodeClient = $client->getClientBy('id', '127.0.0.1:6379');
  604. $this->assertSame($connection, $nodeClient->getConnection());
  605. $this->assertSame($client->getOptions(), $nodeClient->getOptions());
  606. }
  607. /**
  608. * @group disconnected
  609. * @expectedException \InvalidArgumentException
  610. * @expectedExceptionMessage Cannot find a connection by id matching `127.0.0.1:7000`
  611. */
  612. public function testGetClientByMethodThrowsExceptionSelectingConnectionByUnknownId()
  613. {
  614. $aggregate = $this->getMock('Predis\Connection\AggregateConnectionInterface');
  615. $aggregate
  616. ->expects($this->once())
  617. ->method('getConnectionById')
  618. ->with('127.0.0.1:7000')
  619. ->will($this->returnValue(null));
  620. $client = new Client($aggregate);
  621. $client->getClientBy('id', '127.0.0.1:7000');
  622. }
  623. /**
  624. * @group disconnected
  625. */
  626. public function testGetClientByMethodSupportsSelectingConnectionByAlias()
  627. {
  628. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  629. $aggregate = $this->getMockBuilder('Predis\Connection\AggregateConnectionInterface')
  630. ->setMethods(array('getConnectionByAlias'))
  631. ->getMockForAbstractClass();
  632. $aggregate
  633. ->expects($this->once())
  634. ->method('getConnectionByAlias')
  635. ->with('myalias')
  636. ->will($this->returnValue($connection));
  637. $client = new Client($aggregate);
  638. $nodeClient = $client->getClientBy('alias', 'myalias');
  639. $this->assertSame($connection, $nodeClient->getConnection());
  640. $this->assertSame($client->getOptions(), $nodeClient->getOptions());
  641. }
  642. /**
  643. * @group disconnected
  644. */
  645. public function testGetClientByMethodSupportsSelectingConnectionByKey()
  646. {
  647. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  648. $aggregate = $this->getMockBuilder('Predis\Connection\AggregateConnectionInterface')
  649. ->setMethods(array('getConnectionByKey'))
  650. ->getMockForAbstractClass();
  651. $aggregate
  652. ->expects($this->once())
  653. ->method('getConnectionByKey')
  654. ->with('key:1')
  655. ->will($this->returnValue($connection));
  656. $client = new Client($aggregate);
  657. $nodeClient = $client->getClientBy('key', 'key:1');
  658. $this->assertSame($connection, $nodeClient->getConnection());
  659. $this->assertSame($client->getOptions(), $nodeClient->getOptions());
  660. }
  661. /**
  662. * @group disconnected
  663. */
  664. public function testGetClientByMethodSupportsSelectingConnectionBySlot()
  665. {
  666. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  667. $aggregate = $this->getMockBuilder('Predis\Connection\AggregateConnectionInterface')
  668. ->setMethods(array('getConnectionBySlot'))
  669. ->getMockForAbstractClass();
  670. $aggregate
  671. ->expects($this->once())
  672. ->method('getConnectionBySlot')
  673. ->with(5460)
  674. ->will($this->returnValue($connection));
  675. $client = new Client($aggregate);
  676. $nodeClient = $client->getClientBy('slot', 5460);
  677. $this->assertSame($connection, $nodeClient->getConnection());
  678. $this->assertSame($client->getOptions(), $nodeClient->getOptions());
  679. }
  680. /**
  681. * @group disconnected
  682. */
  683. public function testGetClientByMethodSupportsSelectingConnectionByRole()
  684. {
  685. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  686. $aggregate = $this->getMockBuilder('Predis\Connection\AggregateConnectionInterface')
  687. ->setMethods(array('getConnectionByRole'))
  688. ->getMockForAbstractClass();
  689. $aggregate
  690. ->expects($this->once())
  691. ->method('getConnectionByRole')
  692. ->with('master')
  693. ->will($this->returnValue($connection));
  694. $client = new Client($aggregate);
  695. $nodeClient = $client->getClientBy('role', 'master');
  696. $this->assertSame($connection, $nodeClient->getConnection());
  697. $this->assertSame($client->getOptions(), $nodeClient->getOptions());
  698. }
  699. /**
  700. * @group disconnected
  701. */
  702. public function testGetClientByMethodSupportsSelectingConnectionByCommand()
  703. {
  704. $command = \Predis\Command\RawCommand::create('GET', 'key');
  705. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  706. $aggregate = $this->getMockBuilder('Predis\Connection\AggregateConnectionInterface')
  707. ->setMethods(array('getConnectionByCommand'))
  708. ->getMockForAbstractClass();
  709. $aggregate
  710. ->expects($this->once())
  711. ->method('getConnectionByCommand')
  712. ->with($command)
  713. ->will($this->returnValue($connection));
  714. $client = new Client($aggregate);
  715. $nodeClient = $client->getClientBy('command', $command);
  716. $this->assertSame($connection, $nodeClient->getConnection());
  717. $this->assertSame($client->getOptions(), $nodeClient->getOptions());
  718. }
  719. /**
  720. * @group disconnected
  721. * @expectedException \InvalidArgumentException
  722. * @expectedExceptionMessage Invalid selector type: `unknown`
  723. */
  724. public function testGetClientByMethodThrowsExceptionWhenSelectingConnectionByUnknownType()
  725. {
  726. $client = new Client('tcp://127.0.0.1?alias=node01');
  727. $client->getClientBy('unknown', 'test');
  728. }
  729. /**
  730. * @group disconnected
  731. * @expectedException \InvalidArgumentException
  732. * @expectedExceptionMessage Selecting connection by id is not supported by Predis\Connection\StreamConnection
  733. */
  734. public function testGetClientByMethodThrowsExceptionWhenConnectionDoesNotSupportSelectorType()
  735. {
  736. $client = new Client('tcp://127.0.0.1?alias=node01');
  737. $client->getClientBy('id', 'node01');
  738. }
  739. /**
  740. * @group disconnected
  741. */
  742. public function testPipelineWithoutArgumentsReturnsPipeline()
  743. {
  744. $client = new Client();
  745. $this->assertInstanceOf('Predis\Pipeline\Pipeline', $client->pipeline());
  746. }
  747. /**
  748. * @group disconnected
  749. */
  750. public function testPipelineWithArrayReturnsPipeline()
  751. {
  752. $client = new Client();
  753. $this->assertInstanceOf('Predis\Pipeline\Pipeline', $client->pipeline(array()));
  754. $this->assertInstanceOf('Predis\Pipeline\Atomic', $client->pipeline(array('atomic' => true)));
  755. $this->assertInstanceOf('Predis\Pipeline\FireAndForget', $client->pipeline(array('fire-and-forget' => true)));
  756. }
  757. /**
  758. * @group disconnected
  759. */
  760. public function testPipelineWithCallableExecutesPipeline()
  761. {
  762. $callable = $this->getMock('stdClass', array('__invoke'));
  763. $callable
  764. ->expects($this->once())
  765. ->method('__invoke')
  766. ->with($this->isInstanceOf('Predis\Pipeline\Pipeline'));
  767. $client = new Client();
  768. $client->pipeline($callable);
  769. }
  770. /**
  771. * @group disconnected
  772. */
  773. public function testPubSubLoopWithoutArgumentsReturnsPubSubConsumer()
  774. {
  775. $client = new Client();
  776. $this->assertInstanceOf('Predis\PubSub\Consumer', $client->pubSubLoop());
  777. }
  778. /**
  779. * @group disconnected
  780. */
  781. public function testPubSubLoopWithArrayReturnsPubSubConsumerWithOptions()
  782. {
  783. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  784. $options = array('subscribe' => 'channel');
  785. $client = new Client($connection);
  786. $this->assertInstanceOf('Predis\PubSub\Consumer', $pubsub = $client->pubSubLoop($options));
  787. $reflection = new \ReflectionProperty($pubsub, 'options');
  788. $reflection->setAccessible(true);
  789. $this->assertSame($options, $reflection->getValue($pubsub));
  790. }
  791. /**
  792. * @group disconnected
  793. */
  794. public function testPubSubLoopWithArrayAndCallableExecutesPubSub()
  795. {
  796. // NOTE: we use a subscribe count of 0 in the message payload to trick
  797. // the context and forcing it to be closed since there are no more
  798. // active subscriptions.
  799. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  800. $connection
  801. ->expects($this->once())
  802. ->method('read')
  803. ->will($this->returnValue(array('subscribe', 'channel', 0)));
  804. $callable = $this->getMock('stdClass', array('__invoke'));
  805. $callable
  806. ->expects($this->once())
  807. ->method('__invoke');
  808. $client = new Client($connection);
  809. $this->assertNull($client->pubSubLoop(array('subscribe' => 'channel'), $callable));
  810. }
  811. /**
  812. * @group disconnected
  813. */
  814. public function testPubSubLoopWithCallableReturningFalseStopsPubSubConsumer()
  815. {
  816. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  817. $connection
  818. ->expects($this->at(1))
  819. ->method('read')
  820. ->will($this->returnValue(array('subscribe', 'channel', 1)));
  821. $connection
  822. ->expects($this->at(2))
  823. ->method('writeRequest')
  824. ->with($this->isRedisCommand('UNSUBSCRIBE'));
  825. $connection
  826. ->expects($this->at(3))
  827. ->method('read')
  828. ->will($this->returnValue(array('unsubscribe', 'channel', 0)));
  829. $callable = $this->getMock('stdClass', array('__invoke'));
  830. $callable
  831. ->expects($this->at(0))
  832. ->method('__invoke')
  833. ->will($this->returnValue(false));
  834. $client = new Client($connection);
  835. $this->assertNull($client->pubSubLoop(array('subscribe' => 'channel'), $callable));
  836. }
  837. /**
  838. * @group disconnected
  839. */
  840. public function testTransactionWithoutArgumentsReturnsMultiExec()
  841. {
  842. $client = new Client();
  843. $this->assertInstanceOf('Predis\Transaction\MultiExec', $client->transaction());
  844. }
  845. /**
  846. * @group disconnected
  847. */
  848. public function testTransactionWithArrayReturnsMultiExecTransactionWithOptions()
  849. {
  850. $options = array('cas' => true, 'retry' => 3);
  851. $client = new Client();
  852. $this->assertInstanceOf('Predis\Transaction\MultiExec', $tx = $client->transaction($options));
  853. // I hate this part but reflection is the easiest way in this case.
  854. $property = new \ReflectionProperty($tx, 'modeCAS');
  855. $property->setAccessible(true);
  856. $this->assertSame($options['cas'], $property->getValue($tx));
  857. $property = new \ReflectionProperty($tx, 'attempts');
  858. $property->setAccessible(true);
  859. $this->assertSame($options['retry'], $property->getValue($tx));
  860. }
  861. /**
  862. * @group disconnected
  863. */
  864. public function testTransactionWithArrayAndCallableExecutesMultiExec()
  865. {
  866. // We use CAS here as we don't care about the actual MULTI/EXEC context.
  867. $options = array('cas' => true, 'retry' => 3);
  868. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  869. $connection
  870. ->expects($this->once())
  871. ->method('executeCommand')
  872. ->will($this->returnValue(new Response\Status('QUEUED')));
  873. $callable = $this->getMock('stdClass', array('__invoke'));
  874. $callable
  875. ->expects($this->once())
  876. ->method('__invoke')
  877. ->will($this->returnCallback(function ($tx) { $tx->ping(); }));
  878. $client = new Client($connection);
  879. $client->transaction($options, $callable);
  880. }
  881. /**
  882. * @group disconnected
  883. */
  884. public function testMonitorReturnsMonitorConsumer()
  885. {
  886. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  887. $client = new Client($connection);
  888. $this->assertInstanceOf('Predis\Monitor\Consumer', $monitor = $client->monitor());
  889. }
  890. /**
  891. * @group disconnected
  892. */
  893. public function testClientResendScriptCommandUsingEvalOnNoScriptErrors()
  894. {
  895. $command = $this->getMockForAbstractClass('Predis\Command\ScriptCommand', array(), '', true, true, true, array('parseResponse'));
  896. $command
  897. ->expects($this->once())
  898. ->method('getScript')
  899. ->will($this->returnValue('return redis.call(\'exists\', KEYS[1])'));
  900. $command
  901. ->expects($this->once())
  902. ->method('parseResponse')
  903. ->with('OK')
  904. ->will($this->returnValue(true));
  905. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  906. $connection
  907. ->expects($this->at(0))
  908. ->method('executeCommand')
  909. ->with($command)
  910. ->will($this->returnValue(new Response\Error('NOSCRIPT')));
  911. $connection
  912. ->expects($this->at(1))
  913. ->method('executeCommand')
  914. ->with($this->isRedisCommand('EVAL'))
  915. ->will($this->returnValue('OK'));
  916. $client = new Client($connection);
  917. $this->assertTrue($client->executeCommand($command));
  918. }
  919. /**
  920. * @group disconnected
  921. */
  922. public function testGetIteratorWithTraversableConnections()
  923. {
  924. $connection1 = $this->getMockConnection('tcp://127.0.0.1:6381');
  925. $connection2 = $this->getMockConnection('tcp://127.0.0.1:6382');
  926. $connection3 = $this->getMockConnection('tcp://127.0.0.1:6383');
  927. $aggregate = new \Predis\Connection\Cluster\PredisCluster();
  928. $aggregate->add($connection1);
  929. $aggregate->add($connection2);
  930. $aggregate->add($connection3);
  931. $client = new Client($aggregate);
  932. $iterator = $client->getIterator();
  933. $this->assertInstanceOf('\Predis\Client', $nodeClient = $iterator->current());
  934. $this->assertSame($connection1, $nodeClient->getConnection());
  935. $this->assertSame('127.0.0.1:6381', $iterator->key());
  936. $iterator->next();
  937. $this->assertInstanceOf('\Predis\Client', $nodeClient = $iterator->current());
  938. $this->assertSame($connection2, $nodeClient->getConnection());
  939. $this->assertSame('127.0.0.1:6382', $iterator->key());
  940. $iterator->next();
  941. $this->assertInstanceOf('\Predis\Client', $nodeClient = $iterator->current());
  942. $this->assertSame($connection3, $nodeClient->getConnection());
  943. $this->assertSame('127.0.0.1:6383', $iterator->key());
  944. }
  945. /**
  946. * @group disconnected
  947. * @expectedException \Predis\ClientException
  948. * @expectedExceptionMessage The underlying connection is not traversable
  949. */
  950. public function testGetIteratorWithNonTraversableConnectionThrowsException()
  951. {
  952. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  953. $client = new Client($connection);
  954. $client->getIterator();
  955. }
  956. // ******************************************************************** //
  957. // ---- HELPER METHODS ------------------------------------------------ //
  958. // ******************************************************************** //
  959. /**
  960. * Returns an URI string representation of the specified connection parameters.
  961. *
  962. * @param array $parameters Array of connection parameters.
  963. *
  964. * @return string URI string.
  965. */
  966. protected function getParametersString(array $parameters)
  967. {
  968. $defaults = $this->getDefaultParametersArray();
  969. $scheme = isset($parameters['scheme']) ? $parameters['scheme'] : $defaults['scheme'];
  970. $host = isset($parameters['host']) ? $parameters['host'] : $defaults['host'];
  971. $port = isset($parameters['port']) ? $parameters['port'] : $defaults['port'];
  972. unset($parameters['scheme'], $parameters['host'], $parameters['port']);
  973. $uriString = "$scheme://$host:$port/?";
  974. foreach ($parameters as $k => $v) {
  975. $uriString .= "$k=$v&";
  976. }
  977. return $uriString;
  978. }
  979. /**
  980. * Returns a mock callable simulating an aggregate connection initializer.
  981. *
  982. * @param mixed $parameters Expected connection parameters
  983. *
  984. * @return callable
  985. */
  986. protected function getAggregateInitializer($parameters)
  987. {
  988. $connection = $this->getMock('Predis\Connection\AggregateConnectionInterface');
  989. $callable = $this->getMock('stdClass', array('__invoke'));
  990. $callable
  991. ->expects($this->once())
  992. ->method('__invoke')
  993. ->with($this->isInstanceOf('Predis\Configuration\OptionsInterface'), $parameters)
  994. ->will($this->returnValue($connection));
  995. return $callable;
  996. }
  997. }