菜谱项目

PdoSessionHandlerTest.php 12KB

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