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(): void
  13. {
  14. $this->sessionVar = 'sessionKey';
  15. if (!isset($_SESSION)) {
  16. $_SESSION = [];
  17. }
  18. }
  19. public function testValidatesCookieSession()
  20. {
  21. $_SESSION[$this->sessionVar] = 'true';
  22. $this->expectException(\RuntimeException::class);
  23. new SessionCookieJar($this->sessionVar);
  24. }
  25. public function testLoadsFromSession()
  26. {
  27. $jar = new SessionCookieJar($this->sessionVar);
  28. self::assertSame([], $jar->getIterator()->getArrayCopy());
  29. unset($_SESSION[$this->sessionVar]);
  30. }
  31. /**
  32. * @dataProvider providerPersistsToSessionParameters
  33. */
  34. public function testPersistsToSession($testSaveSessionCookie = false)
  35. {
  36. $jar = new SessionCookieJar($this->sessionVar, $testSaveSessionCookie);
  37. $jar->setCookie(new SetCookie([
  38. 'Name' => 'foo',
  39. 'Value' => 'bar',
  40. 'Domain' => 'foo.com',
  41. 'Expires' => \time() + 1000,
  42. ]));
  43. $jar->setCookie(new SetCookie([
  44. 'Name' => 'baz',
  45. 'Value' => 'bar',
  46. 'Domain' => 'foo.com',
  47. 'Expires' => \time() + 1000,
  48. ]));
  49. $jar->setCookie(new SetCookie([
  50. 'Name' => 'boo',
  51. 'Value' => 'bar',
  52. 'Domain' => 'foo.com',
  53. ]));
  54. self::assertCount(3, $jar);
  55. unset($jar);
  56. // Make sure it wrote to the sessionVar in $_SESSION
  57. $contents = $_SESSION[$this->sessionVar];
  58. self::assertNotEmpty($contents);
  59. // Load the cookieJar from the file
  60. $jar = new SessionCookieJar($this->sessionVar);
  61. if ($testSaveSessionCookie) {
  62. self::assertCount(3, $jar);
  63. } else {
  64. // Weeds out temporary and session cookies
  65. self::assertCount(2, $jar);
  66. }
  67. unset($jar);
  68. unset($_SESSION[$this->sessionVar]);
  69. }
  70. public function providerPersistsToSessionParameters()
  71. {
  72. return [
  73. [false],
  74. [true],
  75. ];
  76. }
  77. }