PageRenderTime 43ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/tests/Zend/Session/SessionManagerTest.php

https://github.com/mridgway/zf2
PHP | 575 lines | 427 code | 53 blank | 95 comment | 26 complexity | 2470452f4bb008b512f306a1a6911953 MD5 | raw file
  1. <?php
  2. namespace ZendTest\Session;
  3. use Zend\Session\SessionManager,
  4. Zend\Session,
  5. Zend\Registry;
  6. class SessionManagerTest extends \PHPUnit_Framework_TestCase
  7. {
  8. public $error;
  9. public $cookieDateFormat = 'D, d-M-y H:i:s e';
  10. public function setUp()
  11. {
  12. $this->forceAutoloader();
  13. $this->error = false;
  14. $this->manager = new SessionManager();
  15. Registry::_unsetInstance();
  16. }
  17. protected function forceAutoloader()
  18. {
  19. $splAutoloadFunctions = spl_autoload_functions();
  20. if (!$splAutoloadFunctions || !in_array('ZendTest_Autoloader', $splAutoloadFunctions)) {
  21. include __DIR__ . '/../../_autoload.php';
  22. }
  23. }
  24. /**
  25. * Hack to allow running tests in separate processes
  26. *
  27. * @see http://matthewturland.com/2010/08/19/process-isolation-in-phpunit/
  28. * @param PHPUnit_Framework_TestResult $result
  29. * @return void
  30. */
  31. public function run(\PHPUnit_Framework_TestResult $result = NULL)
  32. {
  33. $this->setPreserveGlobalState(false);
  34. return parent::run($result);
  35. }
  36. public function handleErrors($errno, $errstr)
  37. {
  38. $this->error = $errstr;
  39. }
  40. public function getTimestampFromCookie($cookie)
  41. {
  42. if (preg_match('/expires=([^;]+)/', $cookie, $matches)) {
  43. $ts = new \DateTime($matches[1]);
  44. return $ts;
  45. }
  46. return false;
  47. }
  48. public function testManagerUsesSessionConfigurationByDefault()
  49. {
  50. $config = $this->manager->getConfig();
  51. $this->assertTrue($config instanceof Session\Configuration\SessionConfiguration);
  52. }
  53. public function testCanPassConfigurationToConstructor()
  54. {
  55. $config = new Session\Configuration\StandardConfiguration();
  56. $manager = new SessionManager($config);
  57. $this->assertSame($config, $manager->getConfig());
  58. }
  59. public function testPassingUnknownStringClassForConfigurationRaisesException()
  60. {
  61. $this->setExpectedException('Zend\\Session\\Exception', 'invalid');
  62. $manager = new SessionManager('foobarbazbat');
  63. }
  64. public function testPassingInvalidStringClassForConfigurationRaisesException()
  65. {
  66. $this->setExpectedException('Zend\\Session\\Exception', 'invalid');
  67. $manager = new SessionManager('Zend\\Session\\Storage\\ArrayStorage');
  68. }
  69. public function testPassingValidStringClassForConfigurationInstantiatesThatConfiguration()
  70. {
  71. $manager = new SessionManager('Zend\\Session\\Configuration\\StandardConfiguration');
  72. $config = $manager->getConfig();
  73. $this->assertTrue($config instanceof Session\Configuration\StandardConfiguration);
  74. }
  75. public function testPassingValidStringClassInClassKeyOfArrayConfigurationInstantiatesThatConfiguration()
  76. {
  77. $manager = new SessionManager(array('class' => 'Zend\\Session\\Configuration\\StandardConfiguration'));
  78. $config = $manager->getConfig();
  79. $this->assertTrue($config instanceof Session\Configuration\StandardConfiguration);
  80. }
  81. public function testPassingInvalidStringClassInClassKeyOfArrayConfigurationRaisesException()
  82. {
  83. $this->setExpectedException('Zend\\Session\\Exception', 'invalid');
  84. $manager = new SessionManager(array('class' => 'foobarbaz'));
  85. }
  86. public function testPassingValidStringClassInClassKeyOfArrayConfigurationInstantiatesThatConfigurationWithOptionsProvided()
  87. {
  88. $manager = new SessionManager(array(
  89. 'class' => 'Zend\\Session\\Configuration\\StandardConfiguration',
  90. 'save_path' => __DIR__,
  91. ));
  92. $config = $manager->getConfig();
  93. $this->assertTrue($config instanceof Session\Configuration\StandardConfiguration);
  94. $this->assertEquals(__DIR__, $config->getSavePath());
  95. }
  96. public function testPassingZendConfigObjectForConfigurationInstantiatesThatConfiguration()
  97. {
  98. $config = new \Zend\Config\Config(array(
  99. 'class' => 'Zend\\Session\\Configuration\\StandardConfiguration',
  100. 'save_path' => __DIR__,
  101. ));
  102. $manager = new SessionManager($config);
  103. $config = $manager->getConfig();
  104. $this->assertTrue($config instanceof Session\Configuration\StandardConfiguration);
  105. $this->assertEquals(__DIR__, $config->getSavePath());
  106. }
  107. public function testManagerUsesSessionStorageByDefault()
  108. {
  109. $storage = $this->manager->getStorage();
  110. $this->assertTrue($storage instanceof Session\Storage\SessionStorage);
  111. }
  112. public function testCanPassStorageToConstructor()
  113. {
  114. $storage = new Session\Storage\ArrayStorage();
  115. $manager = new SessionManager(null, $storage);
  116. $this->assertSame($storage, $manager->getStorage());
  117. }
  118. public function testCanPassStringStorageNameToConstructor()
  119. {
  120. $manager = new SessionManager(null, 'Zend\\Session\\Storage\\ArrayStorage');
  121. $storage = $manager->getStorage();
  122. $this->assertTrue($storage instanceof Session\Storage\ArrayStorage);
  123. }
  124. public function testCanPassStorageClassToConfigurationOptions()
  125. {
  126. $manager = new SessionManager(array('storage' => 'Zend\\Session\\Storage\\ArrayStorage'));
  127. $storage = $manager->getStorage();
  128. $this->assertTrue($storage instanceof Session\Storage\ArrayStorage);
  129. }
  130. public function testPassingStorageViaParamOverridesStorageInConfig()
  131. {
  132. $storage = new Session\Storage\ArrayStorage();
  133. $manager = new TestAsset\TestManager(array(
  134. 'class' => 'Zend\\Session\\Configuration\\StandardConfiguration',
  135. 'storage' => 'Zend\\Session\\Storage\\SessionStorage',
  136. ), $storage);
  137. $this->assertSame($storage, $manager->getStorage());
  138. }
  139. // Session-related functionality
  140. /**
  141. * @runInSeparateProcess
  142. */
  143. public function testSessionExistsReturnsFalseWhenNoSessionStarted()
  144. {
  145. $this->assertFalse($this->manager->sessionExists());
  146. }
  147. /**
  148. * @runInSeparateProcess
  149. */
  150. public function testSessionExistsReturnsTrueWhenSessionStarted()
  151. {
  152. session_start();
  153. $this->assertTrue($this->manager->sessionExists());
  154. }
  155. /**
  156. * @runInSeparateProcess
  157. */
  158. public function testSessionExistsReturnsTrueWhenSessionStartedThenWritten()
  159. {
  160. session_start();
  161. session_write_close();
  162. $this->assertTrue($this->manager->sessionExists());
  163. }
  164. /**
  165. * @runInSeparateProcess
  166. */
  167. public function testSessionExistsReturnsFalseWhenSessionStartedThenDestroyed()
  168. {
  169. session_start();
  170. session_destroy();
  171. $this->assertFalse($this->manager->sessionExists());
  172. }
  173. /**
  174. * @runInSeparateProcess
  175. */
  176. public function testSessionIsStartedAfterCallingStart()
  177. {
  178. $this->assertFalse($this->manager->sessionExists());
  179. $this->manager->start();
  180. $this->assertTrue($this->manager->sessionExists());
  181. }
  182. /**
  183. * @runInSeparateProcess
  184. */
  185. public function testStartDoesNothingWhenCalledAfterWriteCloseOperation()
  186. {
  187. $this->manager->start();
  188. $id1 = session_id();
  189. session_write_close();
  190. $this->manager->start();
  191. $id2 = session_id();
  192. $this->assertTrue($this->manager->sessionExists());
  193. $this->assertEquals($id1, $id2);
  194. }
  195. /**
  196. * @runInSeparateProcess
  197. */
  198. public function testStartCreatesNewSessionIfPreviousSessionHasBeenDestroyed()
  199. {
  200. $this->manager->start();
  201. $id1 = session_id();
  202. session_destroy();
  203. $this->manager->start();
  204. $id2 = session_id();
  205. $this->assertTrue($this->manager->sessionExists());
  206. $this->assertNotEquals($id1, $id2);
  207. }
  208. /**
  209. * @outputBuffering disabled
  210. */
  211. public function testStartWillNotBlockHeaderSentNotices()
  212. {
  213. if ('cli' == PHP_SAPI) {
  214. $this->markTestSkipped('session_start() will not raise headers_sent warnings in CLI');
  215. }
  216. set_error_handler(array($this, 'handleErrors'), E_WARNING);
  217. echo ' ';
  218. $this->assertTrue(headers_sent());
  219. $this->manager->start();
  220. restore_error_handler();
  221. $this->assertTrue(is_string($this->error));
  222. $this->assertContains('already sent', $this->error);
  223. }
  224. /**
  225. * @runInSeparateProcess
  226. */
  227. public function testGetNameReturnsSessionName()
  228. {
  229. $ini = ini_get('session.name');
  230. $this->assertEquals($ini, $this->manager->getName());
  231. }
  232. /**
  233. * @runInSeparateProcess
  234. */
  235. public function testSetNameRaisesExceptionOnInvalidName()
  236. {
  237. $this->setExpectedException('Zend\\Session\\Exception', 'invalid characters');
  238. $this->manager->setName('foo bar!');
  239. }
  240. /**
  241. * @runInSeparateProcess
  242. */
  243. public function testSetNameSetsSessionNameOnSuccess()
  244. {
  245. $this->manager->setName('foobar');
  246. $this->assertEquals('foobar', $this->manager->getName());
  247. $this->assertEquals('foobar', session_name());
  248. }
  249. /**
  250. * @runInSeparateProcess
  251. */
  252. public function testCanSetNewSessionNameAfterSessionDestroyed()
  253. {
  254. $this->manager->start();
  255. session_destroy();
  256. $this->manager->setName('foobar');
  257. $this->assertEquals('foobar', $this->manager->getName());
  258. $this->assertEquals('foobar', session_name());
  259. }
  260. /**
  261. * @runInSeparateProcess
  262. */
  263. public function testSettingNameWhenAnActiveSessionExistsRaisesException()
  264. {
  265. $this->setExpectedException('Zend\\Session\\Exception', 'already started');
  266. $this->manager->start();
  267. $this->manager->setName('foobar');
  268. }
  269. /**
  270. * @runInSeparateProcess
  271. */
  272. public function testDestroyByDefaultSendsAnExpireCookie()
  273. {
  274. $config = $this->manager->getConfig();
  275. $config->setUseCookies(true);
  276. $this->manager->start();
  277. $this->manager->destroy();
  278. echo '';
  279. $headers = xdebug_get_headers();
  280. $found = false;
  281. $sName = $this->manager->getName();
  282. foreach ($headers as $header) {
  283. if (stristr($header, 'Set-Cookie:') && stristr($header, $sName)) {
  284. $found = true;
  285. }
  286. }
  287. $this->assertTrue($found, 'No session cookie found: ' . var_export($headers, true));
  288. }
  289. /**
  290. * @runInSeparateProcess
  291. */
  292. public function testSendingFalseToSendExpireCookieWhenCallingDestroyShouldNotSendCookie()
  293. {
  294. $config = $this->manager->getConfig();
  295. $config->setUseCookies(true);
  296. $this->manager->start();
  297. $this->manager->destroy(array('send_expire_cookie' => false));
  298. echo '';
  299. $headers = xdebug_get_headers();
  300. $found = false;
  301. $sName = $this->manager->getName();
  302. foreach ($headers as $header) {
  303. if (stristr($header, 'Set-Cookie:') && stristr($header, $sName)) {
  304. $found = true;
  305. }
  306. }
  307. if ($found) {
  308. $this->assertNotContains('expires=', $header);
  309. } else {
  310. $this->assertFalse($found, 'Unexpected session cookie found: ' . var_export($headers, true));
  311. }
  312. }
  313. /**
  314. * @runInSeparateProcess
  315. */
  316. public function testDestroyDoesNotClearSessionStorageByDefault()
  317. {
  318. $this->manager->start();
  319. $storage = $this->manager->getStorage();
  320. $storage['foo'] = 'bar';
  321. $this->manager->destroy();
  322. $this->manager->start();
  323. $this->assertEquals('bar', $storage['foo']);
  324. }
  325. /**
  326. * @runInSeparateProcess
  327. */
  328. public function testPassingClearStorageOptionWhenCallingDestroyClearsStorage()
  329. {
  330. $this->manager->start();
  331. $storage = $this->manager->getStorage();
  332. $storage['foo'] = 'bar';
  333. $this->manager->destroy(array('clear_storage' => true));
  334. $this->assertSame(array(), (array) $storage);
  335. }
  336. /**
  337. * @runInSeparateProcess
  338. */
  339. public function testCallingWriteCloseMarksStorageAsImmutable()
  340. {
  341. $this->manager->start();
  342. $storage = $this->manager->getStorage();
  343. $storage['foo'] = 'bar';
  344. $this->manager->writeClose();
  345. $this->assertTrue($storage->isImmutable());
  346. }
  347. /**
  348. * @runInSeparateProcess
  349. */
  350. public function testCallingWriteCloseShouldNotAlterSessionExistsStatus()
  351. {
  352. $this->manager->start();
  353. $this->manager->writeClose();
  354. $this->assertTrue($this->manager->sessionExists());
  355. }
  356. /**
  357. * @runInSeparateProcess
  358. */
  359. public function testIdShouldBeEmptyPriorToCallingStart()
  360. {
  361. $this->assertSame('', $this->manager->getId());
  362. }
  363. /**
  364. * @runInSeparateProcess
  365. */
  366. public function testIdShouldBeMutablePriorToCallingStart()
  367. {
  368. $this->manager->setId(__CLASS__);
  369. $this->assertSame(__CLASS__, $this->manager->getId());
  370. $this->assertSame(__CLASS__, session_id());
  371. }
  372. /**
  373. * @runInSeparateProcess
  374. */
  375. public function testIdShouldBeMutablePriorAfterSessionStarted()
  376. {
  377. $this->manager->start();
  378. $origId = $this->manager->getId();
  379. $this->manager->setId(__METHOD__);
  380. $this->assertNotSame($origId, $this->manager->getId());
  381. $this->assertSame(__METHOD__, $this->manager->getId());
  382. $this->assertSame(__METHOD__, session_id());
  383. }
  384. /**
  385. * @runInSeparateProcess
  386. */
  387. public function testSettingIdAfterSessionStartedShouldSendExpireCookie()
  388. {
  389. $config = $this->manager->getConfig();
  390. $config->setUseCookies(true);
  391. $this->manager->start();
  392. $origId = $this->manager->getId();
  393. $this->manager->setId(__METHOD__);
  394. $headers = xdebug_get_headers();
  395. $found = false;
  396. $sName = $this->manager->getName();
  397. foreach ($headers as $header) {
  398. if (stristr($header, 'Set-Cookie:') && stristr($header, $sName)) {
  399. $found = true;
  400. }
  401. }
  402. $this->assertTrue($found, 'No session cookie found: ' . var_export($headers, true));
  403. }
  404. /**
  405. * @runInSeparateProcess
  406. */
  407. public function testRegenerateIdShouldWorkAfterSessionStarted()
  408. {
  409. $this->manager->start();
  410. $origId = $this->manager->getId();
  411. $this->manager->regenerateId();
  412. $this->assertNotSame($origId, $this->manager->getId());
  413. }
  414. /**
  415. * @runInSeparateProcess
  416. */
  417. public function testRegeneratingIdAfterSessionStartedShouldSendExpireCookie()
  418. {
  419. $config = $this->manager->getConfig();
  420. $config->setUseCookies(true);
  421. $this->manager->start();
  422. $origId = $this->manager->getId();
  423. $this->manager->regenerateId();
  424. $headers = xdebug_get_headers();
  425. $found = false;
  426. $sName = $this->manager->getName();
  427. foreach ($headers as $header) {
  428. if (stristr($header, 'Set-Cookie:') && stristr($header, $sName)) {
  429. $found = true;
  430. }
  431. }
  432. $this->assertTrue($found, 'No session cookie found: ' . var_export($headers, true));
  433. }
  434. /**
  435. * @runInSeparateProcess
  436. */
  437. public function testRememberMeShouldSendNewSessionCookieWithUpdatedTimestamp()
  438. {
  439. $config = $this->manager->getConfig();
  440. $config->setUseCookies(true);
  441. $this->manager->start();
  442. $this->manager->rememberMe(18600);
  443. $headers = xdebug_get_headers();
  444. $found = false;
  445. $sName = $this->manager->getName();
  446. $cookie = false;
  447. foreach ($headers as $header) {
  448. if (stristr($header, 'Set-Cookie:') && stristr($header, $sName) && !stristr($header, '=deleted')) {
  449. $found = true;
  450. $cookie = $header;
  451. }
  452. }
  453. $this->assertTrue($found, 'No session cookie found: ' . var_export($headers, true));
  454. $ts = $this->getTimestampFromCookie($cookie);
  455. if (!$ts) {
  456. $this->fail('Cookie did not contain expiry? ' . var_export($headers, true));
  457. }
  458. $this->assertGreaterThan($_SERVER['REQUEST_TIME'], $ts->getTimestamp(), 'Session cookie: ' . var_export($headers, 1));
  459. }
  460. /**
  461. * @runInSeparateProcess
  462. */
  463. public function testRememberMeShouldSetTimestampBasedOnConfigurationByDefault()
  464. {
  465. $config = $this->manager->getConfig();
  466. $config->setUseCookies(true);
  467. $config->setRememberMeSeconds(3600);
  468. $ttl = $config->getRememberMeSeconds();
  469. $this->manager->start();
  470. $this->manager->rememberMe();
  471. $headers = xdebug_get_headers();
  472. $found = false;
  473. $sName = $this->manager->getName();
  474. $cookie = false;
  475. foreach ($headers as $header) {
  476. if (stristr($header, 'Set-Cookie:') && stristr($header, $sName) && !stristr($header, '=deleted')) {
  477. $found = true;
  478. $cookie = $header;
  479. }
  480. }
  481. $this->assertTrue($found, 'No session cookie found: ' . var_export($headers, true));
  482. $ts = $this->getTimestampFromCookie($cookie);
  483. if (!$ts) {
  484. $this->fail('Cookie did not contain expiry? ' . var_export($headers, true));
  485. }
  486. $compare = $_SERVER['REQUEST_TIME'] + $ttl;
  487. $cookieTs = $ts->getTimestamp();
  488. $this->assertTrue(in_array($cookieTs, range($compare, $compare + 10)), 'Session cookie: ' . var_export($headers, 1));
  489. }
  490. /**
  491. * @runInSeparateProcess
  492. */
  493. public function testForgetMeShouldSendCookieWithZeroTimestamp()
  494. {
  495. $config = $this->manager->getConfig();
  496. $config->setUseCookies(true);
  497. $this->manager->start();
  498. $this->manager->forgetMe();
  499. $headers = xdebug_get_headers();
  500. $found = false;
  501. $sName = $this->manager->getName();
  502. foreach ($headers as $header) {
  503. if (stristr($header, 'Set-Cookie:') && stristr($header, $sName) && !stristr($header, '=deleted')) {
  504. $found = true;
  505. }
  506. }
  507. $this->assertTrue($found, 'No session cookie found: ' . var_export($headers, true));
  508. $this->assertNotContains('expires=', $header);
  509. }
  510. /**
  511. * @runInSeparateProcess
  512. */
  513. public function testStartingSessionThatFailsAValidatorShouldRaiseException()
  514. {
  515. $this->setExpectedException('Zend\\Session\\Exception', 'failed');
  516. $chain = $this->manager->getValidatorChain();
  517. $chain->connect('session.validate', function() {
  518. return false;
  519. });
  520. $this->manager->start();
  521. }
  522. }