SessionCookieJarTest.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace GuzzleHttp\Tests\CookieJar;
  3. use GuzzleHttp\Cookie\SessionCookieJar;
  4. use GuzzleHttp\Cookie\SetCookie;
  5. use PHPUnit\Framework\TestCase;
  6. /**
  7. * @covers GuzzleHttp\Cookie\SessionCookieJar
  8. */
  9. class SessionCookieJarTest extends TestCase
  10. {
  11. private $sessionVar;
  12. public function setUp()
  13. {
  14. $this->sessionVar = 'sessionKey';
  15. if (!isset($_SESSION)) {
  16. $_SESSION = array();
  17. }
  18. }
  19. /**
  20. * @expectedException \RuntimeException
  21. */
  22. public function testValidatesCookieSession()
  23. {
  24. $_SESSION[$this->sessionVar] = 'true';
  25. new SessionCookieJar($this->sessionVar);
  26. }
  27. public function testLoadsFromSession()
  28. {
  29. $jar = new SessionCookieJar($this->sessionVar);
  30. $this->assertSame([], $jar->getIterator()->getArrayCopy());
  31. unset($_SESSION[$this->sessionVar]);
  32. }
  33. /**
  34. * @dataProvider providerPersistsToSessionParameters
  35. */
  36. public function testPersistsToSession($testSaveSessionCookie = false)
  37. {
  38. $jar = new SessionCookieJar($this->sessionVar, $testSaveSessionCookie);
  39. $jar->setCookie(new SetCookie([
  40. 'Name' => 'foo',
  41. 'Value' => 'bar',
  42. 'Domain' => 'foo.com',
  43. 'Expires' => time() + 1000
  44. ]));
  45. $jar->setCookie(new SetCookie([
  46. 'Name' => 'baz',
  47. 'Value' => 'bar',
  48. 'Domain' => 'foo.com',
  49. 'Expires' => time() + 1000
  50. ]));
  51. $jar->setCookie(new SetCookie([
  52. 'Name' => 'boo',
  53. 'Value' => 'bar',
  54. 'Domain' => 'foo.com',
  55. ]));
  56. $this->assertCount(3, $jar);
  57. unset($jar);
  58. // Make sure it wrote to the sessionVar in $_SESSION
  59. $contents = $_SESSION[$this->sessionVar];
  60. $this->assertNotEmpty($contents);
  61. // Load the cookieJar from the file
  62. $jar = new SessionCookieJar($this->sessionVar);
  63. if ($testSaveSessionCookie) {
  64. $this->assertCount(3, $jar);
  65. } else {
  66. // Weeds out temporary and session cookies
  67. $this->assertCount(2, $jar);
  68. }
  69. unset($jar);
  70. unset($_SESSION[$this->sessionVar]);
  71. }
  72. public function providerPersistsToSessionParameters()
  73. {
  74. return array(
  75. array(false),
  76. array(true)
  77. );
  78. }
  79. }