MultiExecTest.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  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\Transaction;
  11. use Predis\Client;
  12. use Predis\Command\CommandInterface;
  13. use Predis\Response;
  14. use PredisTestCase;
  15. /**
  16. * @group realm-transaction
  17. */
  18. class MultiExecTest extends PredisTestCase
  19. {
  20. /**
  21. * @group disconnected
  22. * @expectedException \Predis\NotSupportedException
  23. * @expectedExceptionMessage MULTI, EXEC and DISCARD are not supported by the current command factory.
  24. */
  25. public function testThrowsExceptionOnUnsupportedMultiExecInCommandFactory()
  26. {
  27. $commands = $this->getMock('Predis\Command\FactoryInterface');
  28. $commands
  29. ->expects($this->once())
  30. ->method('supportsCommands')
  31. ->with(array('MULTI', 'EXEC', 'DISCARD'))
  32. ->will($this->returnValue(false));
  33. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  34. $client = new Client($connection, array('commands' => $commands));
  35. new MultiExec($client);
  36. }
  37. /**
  38. * @group disconnected
  39. * @expectedException \Predis\NotSupportedException
  40. * @expectedExceptionMessage WATCH is not supported by the current command factory.
  41. */
  42. public function testThrowsExceptionOnUnsupportedWatchInCommandFactory()
  43. {
  44. $commands = $this->getMock('Predis\Command\FactoryInterface');
  45. $commands
  46. ->expects($this->once())
  47. ->method('supportsCommands')
  48. ->with(array('MULTI', 'EXEC', 'DISCARD'))
  49. ->will($this->returnValue(true));
  50. $commands
  51. ->expects($this->once())
  52. ->method('supportsCommand')
  53. ->with('WATCH')
  54. ->will($this->returnValue(false));
  55. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  56. $client = new Client($connection, array('commands' => $commands));
  57. $tx = new MultiExec($client, array('options' => 'cas'));
  58. $tx->watch('foo');
  59. }
  60. /**
  61. * @group disconnected
  62. * @expectedException \Predis\NotSupportedException
  63. * @expectedExceptionMessage UNWATCH is not supported by the current command factory.
  64. */
  65. public function testThrowsExceptionOnUnsupportedUnwatchInCommandFactory()
  66. {
  67. $commands = $this->getMock('Predis\Command\FactoryInterface');
  68. $commands
  69. ->expects($this->once())
  70. ->method('supportsCommands')
  71. ->with(array('MULTI', 'EXEC', 'DISCARD'))
  72. ->will($this->returnValue(true));
  73. $commands
  74. ->expects($this->once())
  75. ->method('supportsCommand')
  76. ->with('UNWATCH')
  77. ->will($this->returnValue(false));
  78. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  79. $client = new Client($connection, array('commands' => $commands));
  80. $tx = new MultiExec($client, array('options' => 'cas'));
  81. $tx->unwatch('foo');
  82. }
  83. /**
  84. * @group disconnected
  85. */
  86. public function testExecutionWithFluentInterface()
  87. {
  88. $commands = array();
  89. $expected = array('one', 'two', 'three');
  90. $callback = $this->getExecuteCallback($expected, $commands);
  91. $tx = $this->getMockedTransaction($callback);
  92. $this->assertSame($expected, $tx->echo('one')->echo('two')->echo('three')->execute());
  93. $this->assertSame(array('MULTI', 'ECHO', 'ECHO', 'ECHO', 'EXEC'), self::commandsToIDs($commands));
  94. }
  95. /**
  96. * @group disconnected
  97. */
  98. public function testExecutionWithCallable()
  99. {
  100. $commands = array();
  101. $expected = array('one', 'two', 'three');
  102. $callback = $this->getExecuteCallback($expected, $commands);
  103. $tx = $this->getMockedTransaction($callback);
  104. $responses = $tx->execute(function ($tx) {
  105. $tx->echo('one');
  106. $tx->echo('two');
  107. $tx->echo('three');
  108. });
  109. $this->assertSame($expected, $responses);
  110. $this->assertSame(array('MULTI', 'ECHO', 'ECHO', 'ECHO', 'EXEC'), self::commandsToIDs($commands));
  111. }
  112. /**
  113. * @group disconnected
  114. */
  115. public function testCannotMixExecutionWithFluentInterfaceAndCallable()
  116. {
  117. $commands = array();
  118. $callback = $this->getExecuteCallback(null, $commands);
  119. $tx = $this->getMockedTransaction($callback);
  120. $exception = null;
  121. try {
  122. $tx->echo('foo')->execute(function ($tx) {
  123. $tx->echo('bar');
  124. });
  125. } catch (\Exception $ex) {
  126. $exception = $ex;
  127. }
  128. $this->assertInstanceOf('Predis\ClientException', $exception);
  129. $this->assertSame(array('MULTI', 'ECHO', 'DISCARD'), self::commandsToIDs($commands));
  130. }
  131. /**
  132. * @group disconnected
  133. */
  134. public function testEmptyTransactionDoesNotSendMultiExecCommands()
  135. {
  136. $commands = array();
  137. $callback = $this->getExecuteCallback(null, $commands);
  138. $tx = $this->getMockedTransaction($callback);
  139. $responses = $tx->execute(function ($tx) {
  140. // NOOP
  141. });
  142. $this->assertNull($responses);
  143. $this->assertSame(array(), self::commandsToIDs($commands));
  144. }
  145. /**
  146. * @group disconnected
  147. * @expectedException \Predis\ClientException
  148. * @expectedExceptionMessage Cannot invoke "execute" or "exec" inside an active transaction context.
  149. */
  150. public function testThrowsExceptionOnExecInsideTransactionBlock()
  151. {
  152. $commands = array();
  153. $callback = $this->getExecuteCallback(null, $commands);
  154. $tx = $this->getMockedTransaction($callback);
  155. $responses = $tx->execute(function ($tx) {
  156. $tx->exec();
  157. });
  158. $this->assertNull($responses);
  159. $this->assertSame(array(), self::commandsToIDs($commands));
  160. }
  161. /**
  162. * @group disconnected
  163. */
  164. public function testEmptyTransactionIgnoresDiscard()
  165. {
  166. $commands = array();
  167. $callback = $this->getExecuteCallback(null, $commands);
  168. $tx = $this->getMockedTransaction($callback);
  169. $responses = $tx->execute(function ($tx) {
  170. $tx->discard();
  171. });
  172. $this->assertNull($responses);
  173. $this->assertSame(array(), self::commandsToIDs($commands));
  174. }
  175. /**
  176. * @group disconnected
  177. */
  178. public function testTransactionWithCommandsSendsDiscard()
  179. {
  180. $commands = array();
  181. $callback = $this->getExecuteCallback(null, $commands);
  182. $tx = $this->getMockedTransaction($callback);
  183. $responses = $tx->execute(function ($tx) {
  184. $tx->set('foo', 'bar');
  185. $tx->get('foo');
  186. $tx->discard();
  187. });
  188. $this->assertNull($responses);
  189. $this->assertSame(array('MULTI', 'SET', 'GET', 'DISCARD'), self::commandsToIDs($commands));
  190. }
  191. /**
  192. * @group disconnected
  193. */
  194. public function testSendMultiOnCommandsFollowingDiscard()
  195. {
  196. $commands = array();
  197. $expected = array('after DISCARD');
  198. $callback = $this->getExecuteCallback($expected, $commands);
  199. $tx = $this->getMockedTransaction($callback);
  200. $responses = $tx->execute(function ($tx) {
  201. $tx->echo('before DISCARD');
  202. $tx->discard();
  203. $tx->echo('after DISCARD');
  204. });
  205. $this->assertSame($responses, $expected);
  206. $this->assertSame(array('MULTI', 'ECHO', 'DISCARD', 'MULTI', 'ECHO', 'EXEC'), self::commandsToIDs($commands));
  207. }
  208. /**
  209. * @group disconnected
  210. * @expectedException \Predis\ClientException
  211. */
  212. public function testThrowsExceptionOnWatchInsideMulti()
  213. {
  214. $callback = $this->getExecuteCallback();
  215. $tx = $this->getMockedTransaction($callback);
  216. $tx->echo('foobar')->watch('foo')->execute();
  217. }
  218. /**
  219. * @group disconnected
  220. */
  221. public function testUnwatchInsideMulti()
  222. {
  223. $commands = array();
  224. $expected = array('foobar', true);
  225. $callback = $this->getExecuteCallback($expected, $commands);
  226. $tx = $this->getMockedTransaction($callback);
  227. $responses = $tx->echo('foobar')->unwatch('foo')->execute();
  228. $this->assertSame($responses, $expected);
  229. $this->assertSame(array('MULTI', 'ECHO', 'UNWATCH', 'EXEC'), self::commandsToIDs($commands));
  230. }
  231. /**
  232. * @group disconnected
  233. */
  234. public function testAutomaticWatchInOptions()
  235. {
  236. $txCommands = $casCommands = array();
  237. $expected = array('bar', 'piyo');
  238. $options = array('watch' => array('foo', 'hoge'));
  239. $callback = $this->getExecuteCallback($expected, $txCommands, $casCommands);
  240. $tx = $this->getMockedTransaction($callback, $options);
  241. $responses = $tx->execute(function ($tx) {
  242. $tx->get('foo');
  243. $tx->get('hoge');
  244. });
  245. $this->assertSame($responses, $expected);
  246. $this->assertSame(array('WATCH'), self::commandsToIDs($casCommands));
  247. $this->assertSame(array('foo', 'hoge'), $casCommands[0]->getArguments());
  248. $this->assertSame(array('MULTI', 'GET', 'GET', 'EXEC'), self::commandsToIDs($txCommands));
  249. }
  250. /**
  251. * @group disconnected
  252. */
  253. public function testCheckAndSetWithFluentInterface()
  254. {
  255. $txCommands = $casCommands = array();
  256. $expected = array('bar', 'piyo');
  257. $options = array('cas' => true, 'watch' => array('foo', 'hoge'));
  258. $callback = $this->getExecuteCallback($expected, $txCommands, $casCommands);
  259. $tx = $this->getMockedTransaction($callback, $options);
  260. $tx->watch('foobar');
  261. $this->assertSame('DUMMY_RESPONSE', $tx->get('foo'));
  262. $this->assertSame('DUMMY_RESPONSE', $tx->get('hoge'));
  263. $responses = $tx
  264. ->multi()
  265. ->get('foo')
  266. ->get('hoge')
  267. ->execute();
  268. $this->assertSame($responses, $expected);
  269. $this->assertSame(array('WATCH', 'WATCH', 'GET', 'GET'), self::commandsToIDs($casCommands));
  270. $this->assertSame(array('MULTI', 'GET', 'GET', 'EXEC'), self::commandsToIDs($txCommands));
  271. }
  272. /**
  273. * @group disconnected
  274. */
  275. public function testCheckAndSetWithBlock()
  276. {
  277. $txCommands = $casCommands = array();
  278. $expected = array('bar', 'piyo');
  279. $options = array('cas' => true, 'watch' => array('foo', 'hoge'));
  280. $callback = $this->getExecuteCallback($expected, $txCommands, $casCommands);
  281. $tx = $this->getMockedTransaction($callback, $options);
  282. $test = $this;
  283. $responses = $tx->execute(function ($tx) use ($test) {
  284. $tx->watch('foobar');
  285. $response1 = $tx->get('foo');
  286. $response2 = $tx->get('hoge');
  287. $test->assertSame('DUMMY_RESPONSE', $response1);
  288. $test->assertSame('DUMMY_RESPONSE', $response2);
  289. $tx->multi();
  290. $tx->get('foo');
  291. $tx->get('hoge');
  292. });
  293. $this->assertSame($responses, $expected);
  294. $this->assertSame(array('WATCH', 'WATCH', 'GET', 'GET'), self::commandsToIDs($casCommands));
  295. $this->assertSame(array('MULTI', 'GET', 'GET', 'EXEC'), self::commandsToIDs($txCommands));
  296. }
  297. /**
  298. * @group disconnected
  299. */
  300. public function testCheckAndSetWithEmptyBlock()
  301. {
  302. $txCommands = $casCommands = array();
  303. $options = array('cas' => true);
  304. $callback = $this->getExecuteCallback(array(), $txCommands, $casCommands);
  305. $tx = $this->getMockedTransaction($callback, $options);
  306. $tx->execute(function ($tx) {
  307. $tx->multi();
  308. });
  309. $this->assertSame(array(), self::commandsToIDs($casCommands));
  310. $this->assertSame(array(), self::commandsToIDs($txCommands));
  311. }
  312. /**
  313. * @group disconnected
  314. */
  315. public function testCheckAndSetWithoutExec()
  316. {
  317. $txCommands = $casCommands = array();
  318. $options = array('cas' => true);
  319. $callback = $this->getExecuteCallback(array(), $txCommands, $casCommands);
  320. $tx = $this->getMockedTransaction($callback, $options);
  321. $tx->execute(function ($tx) {
  322. $tx->get('foo');
  323. $tx->set('hoge', 'piyo');
  324. });
  325. $this->assertSame(array('GET', 'SET'), self::commandsToIDs($casCommands));
  326. $this->assertSame(array(), self::commandsToIDs($txCommands));
  327. }
  328. /**
  329. * @group disconnected
  330. * @expectedException \Predis\ClientException
  331. * @expectedExceptionMessage Automatic retries are supported only when a callable block is provided.
  332. */
  333. public function testThrowsExceptionOnAutomaticRetriesWithFluentInterface()
  334. {
  335. $options = array('retry' => 1);
  336. $callback = $this->getExecuteCallback();
  337. $tx = $this->getMockedTransaction($callback, $options);
  338. $tx->echo('message')->execute();
  339. }
  340. /**
  341. * @group disconnected
  342. */
  343. public function testAutomaticRetryOnServerSideTransactionAbort()
  344. {
  345. $casCommands = $txCommands = array();
  346. $expected = array('bar');
  347. $options = array('watch' => array('foo', 'bar'), 'retry' => ($attempts = 2) + 1);
  348. $sentinel = $this->getMock('stdClass', array('signal'));
  349. $sentinel->expects($this->exactly($attempts))->method('signal');
  350. $callback = $this->getExecuteCallback($expected, $txCommands, $casCommands);
  351. $tx = $this->getMockedTransaction($callback, $options);
  352. $responses = $tx->execute(function ($tx) use ($sentinel, &$attempts) {
  353. $tx->get('foo');
  354. if ($attempts > 0) {
  355. $attempts -= 1;
  356. $sentinel->signal();
  357. $tx->echo('!!ABORT!!');
  358. }
  359. });
  360. $this->assertSame($responses, $expected);
  361. $this->assertSame(array('WATCH'), self::commandsToIDs($casCommands));
  362. $this->assertSame(array('foo', 'bar'), $casCommands[0]->getArguments());
  363. $this->assertSame(array('MULTI', 'GET', 'EXEC'), self::commandsToIDs($txCommands));
  364. }
  365. /**
  366. * @group disconnected
  367. * @expectedException \Predis\Transaction\AbortedMultiExecException
  368. */
  369. public function testThrowsExceptionOnServerSideTransactionAbort()
  370. {
  371. $callback = $this->getExecuteCallback();
  372. $tx = $this->getMockedTransaction($callback);
  373. $tx->execute(function ($tx) {
  374. $tx->echo('!!ABORT!!');
  375. });
  376. }
  377. /**
  378. * @group disconnected
  379. */
  380. public function testHandlesStandardExceptionsInBlock()
  381. {
  382. $commands = array();
  383. $expected = array('foobar', true);
  384. $callback = $this->getExecuteCallback($expected, $commands);
  385. $tx = $this->getMockedTransaction($callback);
  386. $responses = null;
  387. try {
  388. $responses = $tx->execute(function ($tx) {
  389. $tx->set('foo', 'bar');
  390. $tx->get('foo');
  391. throw new \RuntimeException('TEST');
  392. });
  393. } catch (\Exception $ex) {
  394. // NOOP
  395. }
  396. $this->assertNull($responses, $expected);
  397. $this->assertSame(array('MULTI', 'SET', 'GET', 'DISCARD'), self::commandsToIDs($commands));
  398. }
  399. /**
  400. * @group disconnected
  401. */
  402. public function testHandlesServerExceptionsInBlock()
  403. {
  404. $commands = array();
  405. $expected = array('foobar', true);
  406. $callback = $this->getExecuteCallback($expected, $commands);
  407. $tx = $this->getMockedTransaction($callback);
  408. $responses = null;
  409. try {
  410. $responses = $tx->execute(function ($tx) {
  411. $tx->set('foo', 'bar');
  412. $tx->echo('ERR Invalid operation');
  413. $tx->get('foo');
  414. });
  415. } catch (Response\ServerException $ex) {
  416. $tx->discard();
  417. }
  418. $this->assertNull($responses);
  419. $this->assertSame(array('MULTI', 'SET', 'ECHO', 'DISCARD'), self::commandsToIDs($commands));
  420. }
  421. /**
  422. * @group disconnected
  423. */
  424. public function testProperlyDiscardsTransactionAfterServerExceptionInBlock()
  425. {
  426. $connection = $this->getMockedConnection(function (CommandInterface $command) {
  427. switch ($command->getId()) {
  428. case 'MULTI':
  429. return true;
  430. case 'ECHO':
  431. return new Response\Error('ERR simulated failure on ECHO');
  432. case 'EXEC':
  433. return new Response\Error('EXECABORT Transaction discarded because of previous errors.');
  434. default:
  435. return new Response\Status('QUEUED');
  436. }
  437. });
  438. $client = new Client($connection);
  439. // First attempt
  440. $tx = new MultiExec($client);
  441. try {
  442. $tx->multi()->set('foo', 'bar')->echo('simulated failure')->exec();
  443. } catch (\Exception $exception) {
  444. $this->assertInstanceOf('Predis\Transaction\AbortedMultiExecException', $exception);
  445. $this->assertSame('ERR simulated failure on ECHO', $exception->getMessage());
  446. }
  447. // Second attempt
  448. $tx = new MultiExec($client);
  449. try {
  450. $tx->multi()->set('foo', 'bar')->echo('simulated failure')->exec();
  451. } catch (\Exception $exception) {
  452. $this->assertInstanceOf('Predis\Transaction\AbortedMultiExecException', $exception);
  453. $this->assertSame('ERR simulated failure on ECHO', $exception->getMessage());
  454. }
  455. }
  456. /**
  457. * @group disconnected
  458. */
  459. public function testExceptionsOptionTakesPrecedenceOverClientOptionsWhenFalse()
  460. {
  461. $expected = array('before', new Response\Error('ERR simulated error'), 'after');
  462. $connection = $this->getMockedConnection(function (CommandInterface $command) use ($expected) {
  463. switch ($command->getId()) {
  464. case 'MULTI':
  465. return true;
  466. case 'EXEC':
  467. return $expected;
  468. default:
  469. return new Response\Status('QUEUED');
  470. }
  471. });
  472. $client = new Client($connection, array('exceptions' => true));
  473. $tx = new MultiExec($client, array('exceptions' => false));
  474. $result = $tx
  475. ->multi()
  476. ->echo('before')
  477. ->echo('ERROR PLEASE!')
  478. ->echo('after')
  479. ->exec();
  480. $this->assertSame($expected, $result);
  481. }
  482. /**
  483. * @group disconnected
  484. * @expectedException \Predis\Response\ServerException
  485. * @expectedExceptionMessage ERR simulated error
  486. */
  487. public function testExceptionsOptionTakesPrecedenceOverClientOptionsWhenTrue()
  488. {
  489. $expected = array('before', new Response\Error('ERR simulated error'), 'after');
  490. $connection = $this->getMockedConnection(function (CommandInterface $command) use ($expected) {
  491. switch ($command->getId()) {
  492. case 'MULTI':
  493. return true;
  494. case 'EXEC':
  495. return $expected;
  496. default:
  497. return new Response\Status('QUEUED');
  498. }
  499. });
  500. $client = new Client($connection, array('exceptions' => false));
  501. $tx = new MultiExec($client, array('exceptions' => true));
  502. $tx->multi()->echo('before')->echo('ERROR PLEASE!')->echo('after')->exec();
  503. }
  504. /**
  505. * @group disconnected
  506. * @expectedException \Predis\Response\ServerException
  507. * @expectedExceptionMessage ERR simulated failure on EXEC
  508. */
  509. public function testExceptionsOptionDoesNotAffectTransactionControlCommands()
  510. {
  511. $connection = $this->getMockedConnection(function (CommandInterface $command) {
  512. switch ($command->getId()) {
  513. case 'MULTI':
  514. return true;
  515. case 'EXEC':
  516. return new Response\Error('ERR simulated failure on EXEC');
  517. default:
  518. return new Response\Status('QUEUED');
  519. }
  520. });
  521. $client = new Client($connection, array('exceptions' => false));
  522. $tx = new MultiExec($client);
  523. $tx->multi()->echo('test')->exec();
  524. }
  525. // ******************************************************************** //
  526. // ---- INTEGRATION TESTS --------------------------------------------- //
  527. // ******************************************************************** //
  528. /**
  529. * @group connected
  530. */
  531. public function testIntegrationHandlesStandardExceptionsInBlock()
  532. {
  533. $client = $this->getClient();
  534. $exception = null;
  535. try {
  536. $client->transaction(function ($tx) {
  537. $tx->set('foo', 'bar');
  538. throw new \RuntimeException('TEST');
  539. });
  540. } catch (\Exception $ex) {
  541. $exception = $ex;
  542. }
  543. $this->assertInstanceOf('RuntimeException', $exception);
  544. $this->assertSame(0, $client->exists('foo'));
  545. }
  546. /**
  547. * @group connected
  548. */
  549. public function testIntegrationThrowsExceptionOnRedisErrorInBlock()
  550. {
  551. $client = $this->getClient();
  552. $exception = null;
  553. $value = (string) rand();
  554. try {
  555. $client->transaction(function ($tx) use ($value) {
  556. $tx->set('foo', 'bar');
  557. $tx->lpush('foo', 'bar');
  558. $tx->set('foo', $value);
  559. });
  560. } catch (Response\ServerException $ex) {
  561. $exception = $ex;
  562. }
  563. $this->assertInstanceOf('Predis\Response\ErrorInterface', $exception);
  564. $this->assertSame($value, $client->get('foo'));
  565. }
  566. /**
  567. * @group connected
  568. */
  569. public function testIntegrationReturnsErrorObjectOnRedisErrorInBlock()
  570. {
  571. $client = $this->getClient(array(), array('exceptions' => false));
  572. $responses = $client->transaction(function ($tx) {
  573. $tx->set('foo', 'bar');
  574. $tx->lpush('foo', 'bar');
  575. $tx->echo('foobar');
  576. });
  577. $this->assertInstanceOf('Predis\Response\Status', $responses[0]);
  578. $this->assertInstanceOf('Predis\Response\Error', $responses[1]);
  579. $this->assertSame('foobar', $responses[2]);
  580. }
  581. /**
  582. * @group connected
  583. * @requiresRedisVersion >= 2.0.0
  584. */
  585. public function testIntegrationSendMultiOnCommandsAfterDiscard()
  586. {
  587. $client = $this->getClient();
  588. $responses = $client->transaction(function ($tx) {
  589. $tx->set('foo', 'bar');
  590. $tx->discard();
  591. $tx->set('hoge', 'piyo');
  592. });
  593. $this->assertSame(1, count($responses));
  594. $this->assertSame(0, $client->exists('foo'));
  595. $this->assertSame(1, $client->exists('hoge'));
  596. }
  597. /**
  598. * @group connected
  599. * @requiresRedisVersion >= 2.2.0
  600. */
  601. public function testIntegrationWritesOnWatchedKeysAbortTransaction()
  602. {
  603. $exception = null;
  604. $client1 = $this->getClient();
  605. $client2 = $this->getClient();
  606. try {
  607. $client1->transaction(array('watch' => 'sentinel'), function ($tx) use ($client2) {
  608. $tx->set('sentinel', 'client1');
  609. $tx->get('sentinel');
  610. $client2->set('sentinel', 'client2');
  611. });
  612. } catch (AbortedMultiExecException $ex) {
  613. $exception = $ex;
  614. }
  615. $this->assertInstanceOf('Predis\Transaction\AbortedMultiExecException', $exception);
  616. $this->assertSame('client2', $client1->get('sentinel'));
  617. }
  618. /**
  619. * @group connected
  620. * @requiresRedisVersion >= 2.2.0
  621. */
  622. public function testIntegrationCheckAndSetWithDiscardAndRetry()
  623. {
  624. $client = $this->getClient();
  625. $client->set('foo', 'bar');
  626. $options = array('watch' => 'foo', 'cas' => true);
  627. $responses = $client->transaction($options, function ($tx) {
  628. $tx->watch('foobar');
  629. $foo = $tx->get('foo');
  630. $tx->multi();
  631. $tx->set('foobar', $foo);
  632. $tx->discard();
  633. $tx->mget('foo', 'foobar');
  634. });
  635. $this->assertInternalType('array', $responses);
  636. $this->assertSame(array(array('bar', null)), $responses);
  637. $hijack = true;
  638. $client2 = $this->getClient();
  639. $client->set('foo', 'bar');
  640. $options = array('watch' => 'foo', 'cas' => true, 'retry' => 1);
  641. $responses = $client->transaction($options, function ($tx) use ($client2, &$hijack) {
  642. $foo = $tx->get('foo');
  643. $tx->multi();
  644. $tx->set('foobar', $foo);
  645. $tx->discard();
  646. if ($hijack) {
  647. $hijack = false;
  648. $client2->set('foo', 'hijacked!');
  649. }
  650. $tx->mget('foo', 'foobar');
  651. });
  652. $this->assertInternalType('array', $responses);
  653. $this->assertSame(array(array('hijacked!', null)), $responses);
  654. }
  655. // ******************************************************************** //
  656. // ---- HELPER METHODS ------------------------------------------------ //
  657. // ******************************************************************** //
  658. /**
  659. * Returns a mocked instance of Predis\Connection\NodeConnectionInterface
  660. * using the specified callback to return values from executeCommand().
  661. *
  662. * @param \Closure $executeCallback
  663. *
  664. * @return \Predis\Connection\NodeConnectionInterface
  665. */
  666. protected function getMockedConnection($executeCallback)
  667. {
  668. $connection = $this->getMock('Predis\Connection\NodeConnectionInterface');
  669. $connection
  670. ->expects($this->any())
  671. ->method('executeCommand')
  672. ->will($this->returnCallback($executeCallback));
  673. return $connection;
  674. }
  675. /**
  676. * Returns a mocked instance of Predis\Transaction\MultiExec using
  677. * the specified callback to return values from the executeCommand method
  678. * of the underlying connection.
  679. *
  680. * @param \Closure $executeCallback
  681. * @param array $txOpts
  682. * @param array $clientOpts
  683. *
  684. * @return MultiExec
  685. */
  686. protected function getMockedTransaction($executeCallback, $txOpts = null, $clientOpts = null)
  687. {
  688. $connection = $this->getMockedConnection($executeCallback);
  689. $client = new Client($connection, $clientOpts ?: array());
  690. $transaction = new MultiExec($client, $txOpts ?: array());
  691. return $transaction;
  692. }
  693. /**
  694. * Returns a callback that emulates a server-side MULTI/EXEC transaction context.
  695. *
  696. * @param array $expected Expected responses.
  697. * @param array $commands Reference to an array storing the whole flow of commands.
  698. * @param array $cas Check and set operations performed by the transaction.
  699. *
  700. * @return \Closure
  701. */
  702. protected function getExecuteCallback($expected = array(), &$commands = array(), &$cas = array())
  703. {
  704. $multi = $watch = $abort = false;
  705. return function (CommandInterface $command) use (&$expected, &$commands, &$cas, &$multi, &$watch, &$abort) {
  706. $cmd = $command->getId();
  707. if ($multi || $cmd === 'MULTI') {
  708. $commands[] = $command;
  709. } else {
  710. $cas[] = $command;
  711. }
  712. switch ($cmd) {
  713. case 'WATCH':
  714. if ($multi) {
  715. return new Response\Error("ERR $cmd inside MULTI is not allowed");
  716. }
  717. return $watch = true;
  718. case 'MULTI':
  719. if ($multi) {
  720. return new Response\Error('ERR MULTI calls can not be nested');
  721. }
  722. return $multi = true;
  723. case 'EXEC':
  724. if (!$multi) {
  725. return new Response\Error("ERR $cmd without MULTI");
  726. }
  727. $watch = $multi = false;
  728. if ($abort) {
  729. $commands = $cas = array();
  730. $abort = false;
  731. return;
  732. }
  733. return $expected;
  734. case 'DISCARD':
  735. if (!$multi) {
  736. return new Response\Error("ERR $cmd without MULTI");
  737. }
  738. $watch = $multi = false;
  739. return true;
  740. case 'ECHO':
  741. @list($trigger) = $command->getArguments();
  742. if (strpos($trigger, 'ERR ') === 0) {
  743. throw new Response\ServerException($trigger);
  744. }
  745. if ($trigger === '!!ABORT!!' && $multi) {
  746. $abort = true;
  747. }
  748. return new Response\Status('QUEUED');
  749. case 'UNWATCH':
  750. $watch = false;
  751. // no break
  752. default:
  753. return $multi ? new Response\Status('QUEUED') : 'DUMMY_RESPONSE';
  754. }
  755. };
  756. }
  757. /**
  758. * Converts an array of instances of Predis\Command\CommandInterface and
  759. * returns an array containing their IDs.
  760. *
  761. * @param array $commands List of commands instances.
  762. *
  763. * @return array
  764. */
  765. protected static function commandsToIDs($commands)
  766. {
  767. return array_map(function ($cmd) { return $cmd->getId(); }, $commands);
  768. }
  769. /**
  770. * Returns a client instance connected to the specified Redis
  771. * server instance to perform integration tests.
  772. *
  773. * @param array $parameters Additional connection parameters.
  774. * @param array $options Additional client options.
  775. *
  776. * @return Client
  777. */
  778. protected function getClient(array $parameters = array(), array $options = array())
  779. {
  780. return $this->createClient($parameters, $options);
  781. }
  782. }