No Description

PdoSessionHandlerTest.php 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.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 Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler;
  11. use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler;
  12. /**
  13. * @requires extension pdo_sqlite
  14. * @group time-sensitive
  15. */
  16. class PdoSessionHandlerTest extends \PHPUnit_Framework_TestCase
  17. {
  18. private $dbFile;
  19. protected function tearDown()
  20. {
  21. // make sure the temporary database file is deleted when it has been created (even when a test fails)
  22. if ($this->dbFile) {
  23. @unlink($this->dbFile);
  24. }
  25. parent::tearDown();
  26. }
  27. protected function getPersistentSqliteDsn()
  28. {
  29. $this->dbFile = tempnam(sys_get_temp_dir(), 'sf2_sqlite_sessions');
  30. return 'sqlite:'.$this->dbFile;
  31. }
  32. protected function getMemorySqlitePdo()
  33. {
  34. $pdo = new \PDO('sqlite::memory:');
  35. $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
  36. $storage = new PdoSessionHandler($pdo);
  37. $storage->createTable();
  38. return $pdo;
  39. }
  40. /**
  41. * @expectedException \InvalidArgumentException
  42. */
  43. public function testWrongPdoErrMode()
  44. {
  45. $pdo = $this->getMemorySqlitePdo();
  46. $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_SILENT);
  47. $storage = new PdoSessionHandler($pdo);
  48. }
  49. /**
  50. * @expectedException \RuntimeException
  51. */
  52. public function testInexistentTable()
  53. {
  54. $storage = new PdoSessionHandler($this->getMemorySqlitePdo(), array('db_table' => 'inexistent_table'));
  55. $storage->open('', 'sid');
  56. $storage->read('id');
  57. $storage->write('id', 'data');
  58. $storage->close();
  59. }
  60. /**
  61. * @expectedException \RuntimeException
  62. */
  63. public function testCreateTableTwice()
  64. {
  65. $storage = new PdoSessionHandler($this->getMemorySqlitePdo());
  66. $storage->createTable();
  67. }
  68. public function testWithLazyDsnConnection()
  69. {
  70. $dsn = $this->getPersistentSqliteDsn();
  71. $storage = new PdoSessionHandler($dsn);
  72. $storage->createTable();
  73. $storage->open('', 'sid');
  74. $data = $storage->read('id');
  75. $storage->write('id', 'data');
  76. $storage->close();
  77. $this->assertSame('', $data, 'New session returns empty string data');
  78. $storage->open('', 'sid');
  79. $data = $storage->read('id');
  80. $storage->close();
  81. $this->assertSame('data', $data, 'Written value can be read back correctly');
  82. }
  83. public function testWithLazySavePathConnection()
  84. {
  85. $dsn = $this->getPersistentSqliteDsn();
  86. // Open is called with what ini_set('session.save_path', $dsn) would mean
  87. $storage = new PdoSessionHandler(null);
  88. $storage->open($dsn, 'sid');
  89. $storage->createTable();
  90. $data = $storage->read('id');
  91. $storage->write('id', 'data');
  92. $storage->close();
  93. $this->assertSame('', $data, 'New session returns empty string data');
  94. $storage->open($dsn, 'sid');
  95. $data = $storage->read('id');
  96. $storage->close();
  97. $this->assertSame('data', $data, 'Written value can be read back correctly');
  98. }
  99. public function testReadWriteReadWithNullByte()
  100. {
  101. $sessionData = 'da'."\0".'ta';
  102. $storage = new PdoSessionHandler($this->getMemorySqlitePdo());
  103. $storage->open('', 'sid');
  104. $readData = $storage->read('id');
  105. $storage->write('id', $sessionData);
  106. $storage->close();
  107. $this->assertSame('', $readData, 'New session returns empty string data');
  108. $storage->open('', 'sid');
  109. $readData = $storage->read('id');
  110. $storage->close();
  111. $this->assertSame($sessionData, $readData, 'Written value can be read back correctly');
  112. }
  113. public function testReadConvertsStreamToString()
  114. {
  115. if (defined('HHVM_VERSION')) {
  116. $this->markTestSkipped('PHPUnit_MockObject cannot mock the PDOStatement class on HHVM. See https://github.com/sebastianbergmann/phpunit-mock-objects/pull/289');
  117. }
  118. $pdo = new MockPdo('pgsql');
  119. $pdo->prepareResult = $this->getMockBuilder('PDOStatement')->getMock();
  120. $content = 'foobar';
  121. $stream = $this->createStream($content);
  122. $pdo->prepareResult->expects($this->once())->method('fetchAll')
  123. ->will($this->returnValue(array(array($stream, 42, time()))));
  124. $storage = new PdoSessionHandler($pdo);
  125. $result = $storage->read('foo');
  126. $this->assertSame($content, $result);
  127. }
  128. public function testReadLockedConvertsStreamToString()
  129. {
  130. if (defined('HHVM_VERSION')) {
  131. $this->markTestSkipped('PHPUnit_MockObject cannot mock the PDOStatement class on HHVM. See https://github.com/sebastianbergmann/phpunit-mock-objects/pull/289');
  132. }
  133. $pdo = new MockPdo('pgsql');
  134. $selectStmt = $this->getMockBuilder('PDOStatement')->getMock();
  135. $insertStmt = $this->getMockBuilder('PDOStatement')->getMock();
  136. $pdo->prepareResult = function ($statement) use ($selectStmt, $insertStmt) {
  137. return 0 === strpos($statement, 'INSERT') ? $insertStmt : $selectStmt;
  138. };
  139. $content = 'foobar';
  140. $stream = $this->createStream($content);
  141. $exception = null;
  142. $selectStmt->expects($this->atLeast(2))->method('fetchAll')
  143. ->will($this->returnCallback(function () use (&$exception, $stream) {
  144. return $exception ? array(array($stream, 42, time())) : array();
  145. }));
  146. $insertStmt->expects($this->once())->method('execute')
  147. ->will($this->returnCallback(function () use (&$exception) {
  148. throw $exception = new \PDOException('', '23');
  149. }));
  150. $storage = new PdoSessionHandler($pdo);
  151. $result = $storage->read('foo');
  152. $this->assertSame($content, $result);
  153. }
  154. public function testReadingRequiresExactlySameId()
  155. {
  156. $storage = new PdoSessionHandler($this->getMemorySqlitePdo());
  157. $storage->open('', 'sid');
  158. $storage->write('id', 'data');
  159. $storage->write('test', 'data');
  160. $storage->write('space ', 'data');
  161. $storage->close();
  162. $storage->open('', 'sid');
  163. $readDataCaseSensitive = $storage->read('ID');
  164. $readDataNoCharFolding = $storage->read('tést');
  165. $readDataKeepSpace = $storage->read('space ');
  166. $readDataExtraSpace = $storage->read('space ');
  167. $storage->close();
  168. $this->assertSame('', $readDataCaseSensitive, 'Retrieval by ID should be case-sensitive (collation setting)');
  169. $this->assertSame('', $readDataNoCharFolding, 'Retrieval by ID should not do character folding (collation setting)');
  170. $this->assertSame('data', $readDataKeepSpace, 'Retrieval by ID requires spaces as-is');
  171. $this->assertSame('', $readDataExtraSpace, 'Retrieval by ID requires spaces as-is');
  172. }
  173. /**
  174. * Simulates session_regenerate_id(true) which will require an INSERT or UPDATE (replace).
  175. */
  176. public function testWriteDifferentSessionIdThanRead()
  177. {
  178. $storage = new PdoSessionHandler($this->getMemorySqlitePdo());
  179. $storage->open('', 'sid');
  180. $storage->read('id');
  181. $storage->destroy('id');
  182. $storage->write('new_id', 'data_of_new_session_id');
  183. $storage->close();
  184. $storage->open('', 'sid');
  185. $data = $storage->read('new_id');
  186. $storage->close();
  187. $this->assertSame('data_of_new_session_id', $data, 'Data of regenerated session id is available');
  188. }
  189. public function testWrongUsageStillWorks()
  190. {
  191. // wrong method sequence that should no happen, but still works
  192. $storage = new PdoSessionHandler($this->getMemorySqlitePdo());
  193. $storage->write('id', 'data');
  194. $storage->write('other_id', 'other_data');
  195. $storage->destroy('inexistent');
  196. $storage->open('', 'sid');
  197. $data = $storage->read('id');
  198. $otherData = $storage->read('other_id');
  199. $storage->close();
  200. $this->assertSame('data', $data);
  201. $this->assertSame('other_data', $otherData);
  202. }
  203. public function testSessionDestroy()
  204. {
  205. $pdo = $this->getMemorySqlitePdo();
  206. $storage = new PdoSessionHandler($pdo);
  207. $storage->open('', 'sid');
  208. $storage->read('id');
  209. $storage->write('id', 'data');
  210. $storage->close();
  211. $this->assertEquals(1, $pdo->query('SELECT COUNT(*) FROM sessions')->fetchColumn());
  212. $storage->open('', 'sid');
  213. $storage->read('id');
  214. $storage->destroy('id');
  215. $storage->close();
  216. $this->assertEquals(0, $pdo->query('SELECT COUNT(*) FROM sessions')->fetchColumn());
  217. $storage->open('', 'sid');
  218. $data = $storage->read('id');
  219. $storage->close();
  220. $this->assertSame('', $data, 'Destroyed session returns empty string');
  221. }
  222. public function testSessionGC()
  223. {
  224. $previousLifeTime = ini_set('session.gc_maxlifetime', 1000);
  225. $pdo = $this->getMemorySqlitePdo();
  226. $storage = new PdoSessionHandler($pdo);
  227. $storage->open('', 'sid');
  228. $storage->read('id');
  229. $storage->write('id', 'data');
  230. $storage->close();
  231. $storage->open('', 'sid');
  232. $storage->read('gc_id');
  233. ini_set('session.gc_maxlifetime', -1); // test that you can set lifetime of a session after it has been read
  234. $storage->write('gc_id', 'data');
  235. $storage->close();
  236. $this->assertEquals(2, $pdo->query('SELECT COUNT(*) FROM sessions')->fetchColumn(), 'No session pruned because gc not called');
  237. $storage->open('', 'sid');
  238. $data = $storage->read('gc_id');
  239. $storage->gc(-1);
  240. $storage->close();
  241. ini_set('session.gc_maxlifetime', $previousLifeTime);
  242. $this->assertSame('', $data, 'Session already considered garbage, so not returning data even if it is not pruned yet');
  243. $this->assertEquals(1, $pdo->query('SELECT COUNT(*) FROM sessions')->fetchColumn(), 'Expired session is pruned');
  244. }
  245. public function testGetConnection()
  246. {
  247. $storage = new PdoSessionHandler($this->getMemorySqlitePdo());
  248. $method = new \ReflectionMethod($storage, 'getConnection');
  249. $method->setAccessible(true);
  250. $this->assertInstanceOf('\PDO', $method->invoke($storage));
  251. }
  252. public function testGetConnectionConnectsIfNeeded()
  253. {
  254. $storage = new PdoSessionHandler('sqlite::memory:');
  255. $method = new \ReflectionMethod($storage, 'getConnection');
  256. $method->setAccessible(true);
  257. $this->assertInstanceOf('\PDO', $method->invoke($storage));
  258. }
  259. private function createStream($content)
  260. {
  261. $stream = tmpfile();
  262. fwrite($stream, $content);
  263. fseek($stream, 0);
  264. return $stream;
  265. }
  266. }
  267. class MockPdo extends \PDO
  268. {
  269. public $prepareResult;
  270. private $driverName;
  271. private $errorMode;
  272. public function __construct($driverName = null, $errorMode = null)
  273. {
  274. $this->driverName = $driverName;
  275. $this->errorMode = null !== $errorMode ?: \PDO::ERRMODE_EXCEPTION;
  276. }
  277. public function getAttribute($attribute)
  278. {
  279. if (\PDO::ATTR_ERRMODE === $attribute) {
  280. return $this->errorMode;
  281. }
  282. if (\PDO::ATTR_DRIVER_NAME === $attribute) {
  283. return $this->driverName;
  284. }
  285. return parent::getAttribute($attribute);
  286. }
  287. public function prepare($statement, $driverOptions = array())
  288. {
  289. return is_callable($this->prepareResult)
  290. ? call_user_func($this->prepareResult, $statement, $driverOptions)
  291. : $this->prepareResult;
  292. }
  293. public function beginTransaction()
  294. {
  295. }
  296. public function rollBack()
  297. {
  298. }
  299. }