CookieJarTest.php 13.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
<?php
namespace GuzzleHttp\Tests\CookieJar;

use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Cookie\SetCookie;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;

/**
 * @covers GuzzleHttp\Cookie\CookieJar
 */
class CookieJarTest extends TestCase
{
    /** @var CookieJar */
    private $jar;

    public function setUp()
    {
        $this->jar = new CookieJar();
    }

    protected function getTestCookies()
    {
        return [
            new SetCookie(['Name' => 'foo',  'Value' => 'bar', 'Domain' => 'foo.com', 'Path' => '/',    'Discard' => true]),
            new SetCookie(['Name' => 'test', 'Value' => '123', 'Domain' => 'baz.com', 'Path' => '/foo', 'Expires' => 2]),
            new SetCookie(['Name' => 'you',  'Value' => '123', 'Domain' => 'bar.com', 'Path' => '/boo', 'Expires' => time() + 1000])
        ];
    }

    public function testCreatesFromArray()
    {
        $jar = CookieJar::fromArray([
            'foo' => 'bar',
            'baz' => 'bam'
        ], 'example.com');
        $this->assertCount(2, $jar);
    }

    public function testEmptyJarIsCountable()
    {
        $this->assertCount(0, new CookieJar());
    }

    public function testGetsCookiesByName()
    {
        $cookies = $this->getTestCookies();
        foreach ($this->getTestCookies() as $cookie) {
            $this->jar->setCookie($cookie);
        }

        $testCookie = $cookies[0];
        $this->assertEquals($testCookie, $this->jar->getCookieByName($testCookie->getName()));
        $this->assertNull($this->jar->getCookieByName("doesnotexist"));
        $this->assertNull($this->jar->getCookieByName(""));
    }

    /**
     * Provides test data for cookie cookieJar retrieval
     */
    public function getCookiesDataProvider()
    {
        return [
            [['foo', 'baz', 'test', 'muppet', 'googoo'], '', '', '', false],
            [['foo', 'baz', 'muppet', 'googoo'], '', '', '', true],
            [['googoo'], 'www.example.com', '', '', false],
            [['muppet', 'googoo'], 'test.y.example.com', '', '', false],
            [['foo', 'baz'], 'example.com', '', '', false],
            [['muppet'], 'x.y.example.com', '/acme/', '', false],
            [['muppet'], 'x.y.example.com', '/acme/test/', '', false],
            [['googoo'], 'x.y.example.com', '/test/acme/test/', '', false],
            [['foo', 'baz'], 'example.com', '', '', false],
            [['baz'], 'example.com', '', 'baz', false],
        ];
    }

    public function testStoresAndRetrievesCookies()
    {
        $cookies = $this->getTestCookies();
        foreach ($cookies as $cookie) {
            $this->assertTrue($this->jar->setCookie($cookie));
        }

        $this->assertCount(3, $this->jar);
        $this->assertCount(3, $this->jar->getIterator());
        $this->assertEquals($cookies, $this->jar->getIterator()->getArrayCopy());
    }

    public function testRemovesTemporaryCookies()
    {
        $cookies = $this->getTestCookies();
        foreach ($this->getTestCookies() as $cookie) {
            $this->jar->setCookie($cookie);
        }
        $this->jar->clearSessionCookies();
        $this->assertEquals(
            [$cookies[1], $cookies[2]],
            $this->jar->getIterator()->getArrayCopy()
        );
    }

    public function testRemovesSelectively()
    {
        foreach ($this->getTestCookies() as $cookie) {
            $this->jar->setCookie($cookie);
        }

        // Remove foo.com cookies
        $this->jar->clear('foo.com');
        $this->assertCount(2, $this->jar);
        // Try again, removing no further cookies
        $this->jar->clear('foo.com');
        $this->assertCount(2, $this->jar);

        // Remove bar.com cookies with path of /boo
        $this->jar->clear('bar.com', '/boo');
        $this->assertCount(1, $this->jar);

        // Remove cookie by name
        $this->jar->clear(null, null, 'test');
        $this->assertCount(0, $this->jar);
    }

    public function testDoesNotAddIncompleteCookies()
    {
        $this->assertFalse($this->jar->setCookie(new SetCookie()));
        $this->assertFalse($this->jar->setCookie(new SetCookie(array(
            'Name' => 'foo'
        ))));
        $this->assertFalse($this->jar->setCookie(new SetCookie(array(
            'Name' => false
        ))));
        $this->assertFalse($this->jar->setCookie(new SetCookie(array(
            'Name' => true
        ))));
        $this->assertFalse($this->jar->setCookie(new SetCookie(array(
            'Name'   => 'foo',
            'Domain' => 'foo.com'
        ))));
    }

    public function testDoesNotAddEmptyCookies()
    {
        $this->assertFalse($this->jar->setCookie(new SetCookie(array(
            'Name'   => '',
            'Domain' => 'foo.com',
            'Value'  => 0
        ))));
    }

    public function testDoesAddValidCookies()
    {
        $this->assertTrue($this->jar->setCookie(new SetCookie(array(
            'Name'   => '0',
            'Domain' => 'foo.com',
            'Value'  => 0
        ))));
        $this->assertTrue($this->jar->setCookie(new SetCookie(array(
            'Name'   => 'foo',
            'Domain' => 'foo.com',
            'Value'  => 0
        ))));
        $this->assertTrue($this->jar->setCookie(new SetCookie(array(
            'Name'   => 'foo',
            'Domain' => 'foo.com',
            'Value'  => 0.0
        ))));
        $this->assertTrue($this->jar->setCookie(new SetCookie(array(
            'Name'   => 'foo',
            'Domain' => 'foo.com',
            'Value'  => '0'
        ))));
    }

    public function testOverwritesCookiesThatAreOlderOrDiscardable()
    {
        $t = time() + 1000;
        $data = array(
            'Name'    => 'foo',
            'Value'   => 'bar',
            'Domain'  => '.example.com',
            'Path'    => '/',
            'Max-Age' => '86400',
            'Secure'  => true,
            'Discard' => true,
            'Expires' => $t
        );

        // Make sure that the discard cookie is overridden with the non-discard
        $this->assertTrue($this->jar->setCookie(new SetCookie($data)));
        $this->assertCount(1, $this->jar);

        $data['Discard'] = false;
        $this->assertTrue($this->jar->setCookie(new SetCookie($data)));
        $this->assertCount(1, $this->jar);

        $c = $this->jar->getIterator()->getArrayCopy();
        $this->assertFalse($c[0]->getDiscard());

        // Make sure it doesn't duplicate the cookie
        $this->jar->setCookie(new SetCookie($data));
        $this->assertCount(1, $this->jar);

        // Make sure the more future-ful expiration date supersede the other
        $data['Expires'] = time() + 2000;
        $this->assertTrue($this->jar->setCookie(new SetCookie($data)));
        $this->assertCount(1, $this->jar);
        $c = $this->jar->getIterator()->getArrayCopy();
        $this->assertNotEquals($t, $c[0]->getExpires());
    }

    public function testOverwritesCookiesThatHaveChanged()
    {
        $t = time() + 1000;
        $data = array(
            'Name'    => 'foo',
            'Value'   => 'bar',
            'Domain'  => '.example.com',
            'Path'    => '/',
            'Max-Age' => '86400',
            'Secure'  => true,
            'Discard' => true,
            'Expires' => $t
        );

        // Make sure that the discard cookie is overridden with the non-discard
        $this->assertTrue($this->jar->setCookie(new SetCookie($data)));

        $data['Value'] = 'boo';
        $this->assertTrue($this->jar->setCookie(new SetCookie($data)));
        $this->assertCount(1, $this->jar);

        // Changing the value plus a parameter also must overwrite the existing one
        $data['Value'] = 'zoo';
        $data['Secure'] = false;
        $this->assertTrue($this->jar->setCookie(new SetCookie($data)));
        $this->assertCount(1, $this->jar);

        $c = $this->jar->getIterator()->getArrayCopy();
        $this->assertEquals('zoo', $c[0]->getValue());
    }

    public function testAddsCookiesFromResponseWithRequest()
    {
        $response = new Response(200, array(
            'Set-Cookie' => "fpc=d=.Hm.yh4.1XmJWjJfs4orLQzKzPImxklQoxXSHOZATHUSEFciRueW_7704iYUtsXNEXq0M92Px2glMdWypmJ7HIQl6XIUvrZimWjQ3vIdeuRbI.FNQMAfcxu_XN1zSx7l.AcPdKL6guHc2V7hIQFhnjRW0rxm2oHY1P4bGQxFNz7f.tHm12ZD3DbdMDiDy7TBXsuP4DM-&v=2; expires=Fri, 02-Mar-2019 02:17:40 GMT;"
        ));
        $request = new Request('GET', 'http://www.example.com');
        $this->jar->extractCookies($request, $response);
        $this->assertCount(1, $this->jar);
    }

    public function getMatchingCookiesDataProvider()
    {
        return array(
            array('https://example.com', 'foo=bar; baz=foobar'),
            array('http://example.com', ''),
            array('https://example.com:8912', 'foo=bar; baz=foobar'),
            array('https://foo.example.com', 'foo=bar; baz=foobar'),
            array('http://foo.example.com/test/acme/', 'googoo=gaga')
        );
    }

    /**
     * @dataProvider getMatchingCookiesDataProvider
     */
    public function testReturnsCookiesMatchingRequests($url, $cookies)
    {
        $bag = [
            new SetCookie([
                'Name'    => 'foo',
                'Value'   => 'bar',
                'Domain'  => 'example.com',
                'Path'    => '/',
                'Max-Age' => '86400',
                'Secure'  => true
            ]),
            new SetCookie([
                'Name'    => 'baz',
                'Value'   => 'foobar',
                'Domain'  => 'example.com',
                'Path'    => '/',
                'Max-Age' => '86400',
                'Secure'  => true
            ]),
            new SetCookie([
                'Name'    => 'test',
                'Value'   => '123',
                'Domain'  => 'www.foobar.com',
                'Path'    => '/path/',
                'Discard' => true
            ]),
            new SetCookie([
                'Name'    => 'muppet',
                'Value'   => 'cookie_monster',
                'Domain'  => '.y.example.com',
                'Path'    => '/acme/',
                'Expires' => time() + 86400
            ]),
            new SetCookie([
                'Name'    => 'googoo',
                'Value'   => 'gaga',
                'Domain'  => '.example.com',
                'Path'    => '/test/acme/',
                'Max-Age' => 1500
            ])
        ];

        foreach ($bag as $cookie) {
            $this->jar->setCookie($cookie);
        }

        $request = new Request('GET', $url);
        $request = $this->jar->withCookieHeader($request);
        $this->assertEquals($cookies, $request->getHeaderLine('Cookie'));
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Invalid cookie: Cookie name must not contain invalid characters: ASCII Control characters (0-31;127), space, tab and the following characters: ()<>@,;:\"/?={}
     */
    public function testThrowsExceptionWithStrictMode()
    {
        $a = new CookieJar(true);
        $a->setCookie(new SetCookie(['Name' => "abc\n", 'Value' => 'foo', 'Domain' => 'bar']));
    }

    public function testDeletesCookiesByName()
    {
        $cookies = $this->getTestCookies();
        $cookies[] = new SetCookie([
            'Name' => 'other',
            'Value' => '123',
            'Domain' => 'bar.com',
            'Path' => '/boo',
            'Expires' => time() + 1000
        ]);
        $jar = new CookieJar();
        foreach ($cookies as $cookie) {
            $jar->setCookie($cookie);
        }
        $this->assertCount(4, $jar);
        $jar->clear('bar.com', '/boo', 'other');
        $this->assertCount(3, $jar);
        $names = array_map(function (SetCookie $c) {
            return $c->getName();
        }, $jar->getIterator()->getArrayCopy());
        $this->assertEquals(['foo', 'test', 'you'], $names);
    }

    public function testCanConvertToAndLoadFromArray()
    {
        $jar = new CookieJar(true);
        foreach ($this->getTestCookies() as $cookie) {
            $jar->setCookie($cookie);
        }
        $this->assertCount(3, $jar);
        $arr = $jar->toArray();
        $this->assertCount(3, $arr);
        $newCookieJar = new CookieJar(false, $arr);
        $this->assertCount(3, $newCookieJar);
        $this->assertSame($jar->toArray(), $newCookieJar->toArray());
    }

    public function testAddsCookiesWithEmptyPathFromResponse()
    {
        $response = new Response(200, array(
            'Set-Cookie' => "fpc=foobar; expires=Fri, 02-Mar-2019 02:17:40 GMT; path=;"
        ));
        $request = new Request('GET', 'http://www.example.com');
        $this->jar->extractCookies($request, $response);
        $newRequest = $this->jar->withCookieHeader(new Request('GET', 'http://www.example.com/foo'));
        $this->assertTrue($newRequest->hasHeader('Cookie'));
    }

    public function getCookiePathsDataProvider()
    {
        return [
            ['', '/'],
            ['/', '/'],
            ['/foo', '/'],
            ['/foo/bar', '/foo'],
            ['/foo/bar/', '/foo/bar'],
            ['foo', '/'],
            ['foo/bar', '/'],
            ['foo/bar/', '/'],
        ];
    }

    /**
     * @dataProvider getCookiePathsDataProvider
     */
    public function testCookiePathWithEmptySetCookiePath($uriPath, $cookiePath)
    {
        $response = (new Response(200))
            ->withAddedHeader('Set-Cookie', "foo=bar; expires=Fri, 02-Mar-2019 02:17:40 GMT; domain=www.example.com; path=;")
            ->withAddedHeader('Set-Cookie', "bar=foo; expires=Fri, 02-Mar-2019 02:17:40 GMT; domain=www.example.com; path=foobar;")
        ;
        $request = (new Request('GET', $uriPath))->withHeader('Host', 'www.example.com');
        $this->jar->extractCookies($request, $response);

        $this->assertEquals($cookiePath, $this->jar->toArray()[0]['Path']);
        $this->assertEquals($cookiePath, $this->jar->toArray()[1]['Path']);
    }
}