Upgrade 1-11.38

This commit is contained in:
xesmyd
2026-03-30 14:10:30 +02:00
parent f2a7e6d1fc
commit ac648ef29d
24665 changed files with 69682 additions and 2205004 deletions
+27 -27
View File
@@ -28,24 +28,24 @@ class AcceptHeaderItemTest extends TestCase
public function provideFromStringData()
{
return array(
array(
return [
[
'text/html',
'text/html', array(),
),
array(
'text/html', [],
],
[
'"this;should,not=matter"',
'this;should,not=matter', array(),
),
array(
'this;should,not=matter', [],
],
[
"text/plain; charset=utf-8;param=\"this;should,not=matter\";\tfootnotes=true",
'text/plain', array('charset' => 'utf-8', 'param' => 'this;should,not=matter', 'footnotes' => 'true'),
),
array(
'text/plain', ['charset' => 'utf-8', 'param' => 'this;should,not=matter', 'footnotes' => 'true'],
],
[
'"this;should,not=matter";charset=utf-8',
'this;should,not=matter', array('charset' => 'utf-8'),
),
);
'this;should,not=matter', ['charset' => 'utf-8'],
],
];
}
/**
@@ -59,21 +59,21 @@ class AcceptHeaderItemTest extends TestCase
public function provideToStringData()
{
return array(
array(
'text/html', array(),
return [
[
'text/html', [],
'text/html',
),
array(
'text/plain', array('charset' => 'utf-8', 'param' => 'this;should,not=matter', 'footnotes' => 'true'),
],
[
'text/plain', ['charset' => 'utf-8', 'param' => 'this;should,not=matter', 'footnotes' => 'true'],
'text/plain;charset=utf-8;param="this;should,not=matter";footnotes=true',
),
);
],
];
}
public function testValue()
{
$item = new AcceptHeaderItem('value', array());
$item = new AcceptHeaderItem('value', []);
$this->assertEquals('value', $item->getValue());
$item->setValue('new value');
@@ -85,7 +85,7 @@ class AcceptHeaderItemTest extends TestCase
public function testQuality()
{
$item = new AcceptHeaderItem('value', array());
$item = new AcceptHeaderItem('value', []);
$this->assertEquals(1.0, $item->getQuality());
$item->setQuality(0.5);
@@ -98,14 +98,14 @@ class AcceptHeaderItemTest extends TestCase
public function testAttribute()
{
$item = new AcceptHeaderItem('value', array());
$this->assertEquals(array(), $item->getAttributes());
$item = new AcceptHeaderItem('value', []);
$this->assertEquals([], $item->getAttributes());
$this->assertFalse($item->hasAttribute('test'));
$this->assertNull($item->getAttribute('test'));
$this->assertEquals('default', $item->getAttribute('test', 'default'));
$item->setAttribute('test', 'value');
$this->assertEquals(array('test' => 'value'), $item->getAttributes());
$this->assertEquals(['test' => 'value'], $item->getAttributes());
$this->assertTrue($item->hasAttribute('test'));
$this->assertEquals('value', $item->getAttribute('test'));
$this->assertEquals('value', $item->getAttribute('test', 'default'));
+21 -21
View File
@@ -39,13 +39,13 @@ class AcceptHeaderTest extends TestCase
public function provideFromStringData()
{
return array(
array('', array()),
array('gzip', array(new AcceptHeaderItem('gzip'))),
array('gzip,deflate,sdch', array(new AcceptHeaderItem('gzip'), new AcceptHeaderItem('deflate'), new AcceptHeaderItem('sdch'))),
array("gzip, deflate\t,sdch", array(new AcceptHeaderItem('gzip'), new AcceptHeaderItem('deflate'), new AcceptHeaderItem('sdch'))),
array('"this;should,not=matter"', array(new AcceptHeaderItem('this;should,not=matter'))),
);
return [
['', []],
['gzip', [new AcceptHeaderItem('gzip')]],
['gzip,deflate,sdch', [new AcceptHeaderItem('gzip'), new AcceptHeaderItem('deflate'), new AcceptHeaderItem('sdch')]],
["gzip, deflate\t,sdch", [new AcceptHeaderItem('gzip'), new AcceptHeaderItem('deflate'), new AcceptHeaderItem('sdch')]],
['"this;should,not=matter"', [new AcceptHeaderItem('this;should,not=matter')]],
];
}
/**
@@ -59,12 +59,12 @@ class AcceptHeaderTest extends TestCase
public function provideToStringData()
{
return array(
array(array(), ''),
array(array(new AcceptHeaderItem('gzip')), 'gzip'),
array(array(new AcceptHeaderItem('gzip'), new AcceptHeaderItem('deflate'), new AcceptHeaderItem('sdch')), 'gzip,deflate,sdch'),
array(array(new AcceptHeaderItem('this;should,not=matter')), 'this;should,not=matter'),
);
return [
[[], ''],
[[new AcceptHeaderItem('gzip')], 'gzip'],
[[new AcceptHeaderItem('gzip'), new AcceptHeaderItem('deflate'), new AcceptHeaderItem('sdch')], 'gzip,deflate,sdch'],
[[new AcceptHeaderItem('this;should,not=matter')], 'this;should,not=matter'],
];
}
/**
@@ -78,9 +78,9 @@ class AcceptHeaderTest extends TestCase
public function provideFilterData()
{
return array(
array('fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4', '/fr.*/', array('fr-FR', 'fr')),
);
return [
['fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4', '/fr.*/', ['fr-FR', 'fr']],
];
}
/**
@@ -94,10 +94,10 @@ class AcceptHeaderTest extends TestCase
public function provideSortingData()
{
return array(
'quality has priority' => array('*;q=0.3,ISO-8859-1,utf-8;q=0.7', array('ISO-8859-1', 'utf-8', '*')),
'order matters when q is equal' => array('*;q=0.3,ISO-8859-1;q=0.7,utf-8;q=0.7', array('ISO-8859-1', 'utf-8', '*')),
'order matters when q is equal2' => array('*;q=0.3,utf-8;q=0.7,ISO-8859-1;q=0.7', array('utf-8', 'ISO-8859-1', '*')),
);
return [
'quality has priority' => ['*;q=0.3,ISO-8859-1,utf-8;q=0.7', ['ISO-8859-1', 'utf-8', '*']],
'order matters when q is equal' => ['*;q=0.3,ISO-8859-1;q=0.7,utf-8;q=0.7', ['ISO-8859-1', 'utf-8', '*']],
'order matters when q is equal2' => ['*;q=0.3,utf-8;q=0.7,ISO-8859-1;q=0.7', ['utf-8', 'ISO-8859-1', '*']],
];
}
}
+26 -26
View File
@@ -31,63 +31,63 @@ class ApacheRequestTest extends TestCase
public function provideServerVars()
{
return array(
array(
array(
return [
[
[
'REQUEST_URI' => '/foo/app_dev.php/bar',
'SCRIPT_NAME' => '/foo/app_dev.php',
'PATH_INFO' => '/bar',
),
],
'/foo/app_dev.php/bar',
'/foo/app_dev.php',
'/bar',
),
array(
array(
],
[
[
'REQUEST_URI' => '/foo/bar',
'SCRIPT_NAME' => '/foo/app_dev.php',
),
],
'/foo/bar',
'/foo',
'/bar',
),
array(
array(
],
[
[
'REQUEST_URI' => '/app_dev.php/foo/bar',
'SCRIPT_NAME' => '/app_dev.php',
'PATH_INFO' => '/foo/bar',
),
],
'/app_dev.php/foo/bar',
'/app_dev.php',
'/foo/bar',
),
array(
array(
],
[
[
'REQUEST_URI' => '/foo/bar',
'SCRIPT_NAME' => '/app_dev.php',
),
],
'/foo/bar',
'',
'/foo/bar',
),
array(
array(
],
[
[
'REQUEST_URI' => '/app_dev.php',
'SCRIPT_NAME' => '/app_dev.php',
),
],
'/app_dev.php',
'/app_dev.php',
'/',
),
array(
array(
],
[
[
'REQUEST_URI' => '/',
'SCRIPT_NAME' => '/app_dev.php',
),
],
'/',
'',
'/',
),
);
],
];
}
}
@@ -12,6 +12,7 @@
namespace Symfony\Component\HttpFoundation\Tests;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\File\Stream;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\Tests\File\FakeFile;
@@ -21,14 +22,14 @@ class BinaryFileResponseTest extends ResponseTestCase
public function testConstruction()
{
$file = __DIR__.'/../README.md';
$response = new BinaryFileResponse($file, 404, array('X-Header' => 'Foo'), true, null, true, true);
$response = new BinaryFileResponse($file, 404, ['X-Header' => 'Foo'], true, null, true, true);
$this->assertEquals(404, $response->getStatusCode());
$this->assertEquals('Foo', $response->headers->get('X-Header'));
$this->assertTrue($response->headers->has('ETag'));
$this->assertTrue($response->headers->has('Last-Modified'));
$this->assertFalse($response->headers->has('Content-Disposition'));
$response = BinaryFileResponse::create($file, 404, array(), true, ResponseHeaderBag::DISPOSITION_INLINE);
$response = BinaryFileResponse::create($file, 404, [], true, ResponseHeaderBag::DISPOSITION_INLINE);
$this->assertEquals(404, $response->getStatusCode());
$this->assertFalse($response->headers->has('ETag'));
$this->assertEquals('inline; filename="README.md"', $response->headers->get('Content-Disposition'));
@@ -38,18 +39,16 @@ class BinaryFileResponseTest extends ResponseTestCase
{
touch(sys_get_temp_dir().'/fööö.html');
$response = new BinaryFileResponse(sys_get_temp_dir().'/fööö.html', 200, array(), true, 'attachment');
$response = new BinaryFileResponse(sys_get_temp_dir().'/fööö.html', 200, [], true, 'attachment');
@unlink(sys_get_temp_dir().'/fööö.html');
$this->assertSame('fööö.html', $response->getFile()->getFilename());
}
/**
* @expectedException \LogicException
*/
public function testSetContent()
{
$this->expectException('LogicException');
$response = new BinaryFileResponse(__FILE__);
$response->setContent('foo');
}
@@ -84,7 +83,7 @@ class BinaryFileResponseTest extends ResponseTestCase
*/
public function testRequests($requestRange, $offset, $length, $responseRange)
{
$response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, array('Content-Type' => 'application/octet-stream'))->setAutoEtag();
$response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, ['Content-Type' => 'application/octet-stream'])->setAutoEtag();
// do a request to get the ETag
$request = Request::create('/');
@@ -108,6 +107,7 @@ class BinaryFileResponseTest extends ResponseTestCase
$this->assertEquals(206, $response->getStatusCode());
$this->assertEquals($responseRange, $response->headers->get('Content-Range'));
$this->assertSame((string) $length, $response->headers->get('Content-Length'));
}
/**
@@ -115,7 +115,7 @@ class BinaryFileResponseTest extends ResponseTestCase
*/
public function testRequestsWithoutEtag($requestRange, $offset, $length, $responseRange)
{
$response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, array('Content-Type' => 'application/octet-stream'));
$response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, ['Content-Type' => 'application/octet-stream']);
// do a request to get the LastModified
$request = Request::create('/');
@@ -143,19 +143,20 @@ class BinaryFileResponseTest extends ResponseTestCase
public function provideRanges()
{
return array(
array('bytes=1-4', 1, 4, 'bytes 1-4/35'),
array('bytes=-5', 30, 5, 'bytes 30-34/35'),
array('bytes=30-', 30, 5, 'bytes 30-34/35'),
array('bytes=30-30', 30, 1, 'bytes 30-30/35'),
array('bytes=30-34', 30, 5, 'bytes 30-34/35'),
);
return [
['bytes=1-4', 1, 4, 'bytes 1-4/35'],
['bytes=-5', 30, 5, 'bytes 30-34/35'],
['bytes=30-', 30, 5, 'bytes 30-34/35'],
['bytes=30-30', 30, 1, 'bytes 30-30/35'],
['bytes=30-34', 30, 5, 'bytes 30-34/35'],
['bytes=30-40', 30, 5, 'bytes 30-34/35'],
];
}
public function testRangeRequestsWithoutLastModifiedDate()
{
// prevent auto last modified
$response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, array('Content-Type' => 'application/octet-stream'), true, null, false, false);
$response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, ['Content-Type' => 'application/octet-stream'], true, null, false, false);
// prepare a request for a range of the testing file
$request = Request::create('/');
@@ -176,7 +177,7 @@ class BinaryFileResponseTest extends ResponseTestCase
*/
public function testFullFileRequests($requestRange)
{
$response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, array('Content-Type' => 'application/octet-stream'))->setAutoEtag();
$response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, ['Content-Type' => 'application/octet-stream'])->setAutoEtag();
// prepare a request for a range of the testing file
$request = Request::create('/');
@@ -196,14 +197,36 @@ class BinaryFileResponseTest extends ResponseTestCase
public function provideFullFileRanges()
{
return array(
array('bytes=0-'),
array('bytes=0-34'),
array('bytes=-35'),
return [
['bytes=0-'],
['bytes=0-34'],
['bytes=-35'],
// Syntactical invalid range-request should also return the full resource
array('bytes=20-10'),
array('bytes=50-40'),
);
['bytes=20-10'],
['bytes=50-40'],
// range units other than bytes must be ignored
['unknown=10-20'],
];
}
public function testRangeOnPostMethod()
{
$request = Request::create('/', 'POST');
$request->headers->set('Range', 'bytes=10-20');
$response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, ['Content-Type' => 'application/octet-stream']);
$file = fopen(__DIR__.'/File/Fixtures/test.gif', 'r');
$data = fread($file, 35);
fclose($file);
$this->expectOutputString($data);
$response = clone $response;
$response->prepare($request);
$response->sendContent();
$this->assertSame(200, $response->getStatusCode());
$this->assertSame('35', $response->headers->get('Content-Length'));
$this->assertNull($response->headers->get('Content-Range'));
}
public function testUnpreparedResponseSendsFullFile()
@@ -224,7 +247,7 @@ class BinaryFileResponseTest extends ResponseTestCase
*/
public function testInvalidRequests($requestRange)
{
$response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, array('Content-Type' => 'application/octet-stream'))->setAutoEtag();
$response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, ['Content-Type' => 'application/octet-stream'])->setAutoEtag();
// prepare a request for a range of the testing file
$request = Request::create('/');
@@ -240,10 +263,10 @@ class BinaryFileResponseTest extends ResponseTestCase
public function provideInvalidRanges()
{
return array(
array('bytes=-40'),
array('bytes=30-40'),
);
return [
['bytes=-40'],
['bytes=40-50'],
];
}
/**
@@ -255,21 +278,21 @@ class BinaryFileResponseTest extends ResponseTestCase
$request->headers->set('X-Sendfile-Type', 'X-Sendfile');
BinaryFileResponse::trustXSendfileTypeHeader();
$response = BinaryFileResponse::create($file, 200, array('Content-Type' => 'application/octet-stream'));
$response = BinaryFileResponse::create($file, 200, ['Content-Type' => 'application/octet-stream']);
$response->prepare($request);
$this->expectOutputString('');
$response->sendContent();
$this->assertContains('README.md', $response->headers->get('X-Sendfile'));
$this->assertStringContainsString('README.md', $response->headers->get('X-Sendfile'));
}
public function provideXSendfileFiles()
{
return array(
array(__DIR__.'/../README.md'),
array('file://'.__DIR__.'/../README.md'),
);
return [
[__DIR__.'/../README.md'],
['file://'.__DIR__.'/../README.md'],
];
}
/**
@@ -284,7 +307,7 @@ class BinaryFileResponseTest extends ResponseTestCase
$file = new FakeFile($realpath, __DIR__.'/File/Fixtures/test');
BinaryFileResponse::trustXSendfileTypeHeader();
$response = new BinaryFileResponse($file, 200, array('Content-Type' => 'application/octet-stream'));
$response = new BinaryFileResponse($file, 200, ['Content-Type' => 'application/octet-stream']);
$reflection = new \ReflectionObject($response);
$property = $reflection->getProperty('file');
$property->setAccessible(true);
@@ -303,19 +326,19 @@ class BinaryFileResponseTest extends ResponseTestCase
$realPath = realpath($path);
$this->assertFileExists($realPath);
$response = new BinaryFileResponse($realPath, 200, array('Content-Type' => 'application/octet-stream'));
$response = new BinaryFileResponse($realPath, 200, ['Content-Type' => 'application/octet-stream']);
$response->deleteFileAfterSend(true);
$response->prepare($request);
$response->sendContent();
$this->assertFileNotExists($path);
$this->assertFileDoesNotExist($path);
}
public function testAcceptRangeOnUnsafeMethods()
{
$request = Request::create('/', 'POST');
$response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, array('Content-Type' => 'application/octet-stream'));
$response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, ['Content-Type' => 'application/octet-stream']);
$response->prepare($request);
$this->assertEquals('none', $response->headers->get('Accept-Ranges'));
@@ -324,7 +347,7 @@ class BinaryFileResponseTest extends ResponseTestCase
public function testAcceptRangeNotOverriden()
{
$request = Request::create('/', 'POST');
$response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, array('Content-Type' => 'application/octet-stream'));
$response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif', 200, ['Content-Type' => 'application/octet-stream']);
$response->headers->set('Accept-Ranges', 'foo');
$response->prepare($request);
@@ -333,15 +356,25 @@ class BinaryFileResponseTest extends ResponseTestCase
public function getSampleXAccelMappings()
{
return array(
array('/var/www/var/www/files/foo.txt', '/var/www/=/files/', '/files/var/www/files/foo.txt'),
array('/home/foo/bar.txt', '/var/www/=/files/,/home/foo/=/baz/', '/baz/bar.txt'),
);
return [
['/var/www/var/www/files/foo.txt', '/var/www/=/files/', '/files/var/www/files/foo.txt'],
['/home/foo/bar.txt', '/var/www/=/files/,/home/foo/=/baz/', '/baz/bar.txt'],
['/tmp/bar.txt', '"/var/www/"="/files/", "/home/Foo/"="/baz/"', null],
];
}
public function testStream()
{
$request = Request::create('/');
$response = new BinaryFileResponse(new Stream(__DIR__.'/../README.md'), 200, ['Content-Type' => 'text/plain']);
$response->prepare($request);
$this->assertNull($response->headers->get('Content-Length'));
}
protected function provideResponse()
{
return new BinaryFileResponse(__DIR__.'/../README.md', 200, array('Content-Type' => 'application/octet-stream'));
return new BinaryFileResponse(__DIR__.'/../README.md', 200, ['Content-Type' => 'application/octet-stream']);
}
public static function tearDownAfterClass()
+89 -30
View File
@@ -24,35 +24,46 @@ use Symfony\Component\HttpFoundation\Cookie;
*/
class CookieTest extends TestCase
{
public function invalidNames()
public function namesWithSpecialCharacters()
{
return array(
array(''),
array(',MyName'),
array(';MyName'),
array(' MyName'),
array("\tMyName"),
array("\rMyName"),
array("\nMyName"),
array("\013MyName"),
array("\014MyName"),
);
return [
[',MyName'],
[';MyName'],
[' MyName'],
["\tMyName"],
["\rMyName"],
["\nMyName"],
["\013MyName"],
["\014MyName"],
];
}
/**
* @dataProvider invalidNames
* @expectedException \InvalidArgumentException
* @dataProvider namesWithSpecialCharacters
*/
public function testInstantiationThrowsExceptionIfCookieNameContainsInvalidCharacters($name)
public function testInstantiationThrowsExceptionIfRawCookieNameContainsSpecialCharacters($name)
{
new Cookie($name);
$this->expectException('InvalidArgumentException');
new Cookie($name, null, 0, null, null, null, false, true);
}
/**
* @expectedException \InvalidArgumentException
* @dataProvider namesWithSpecialCharacters
*/
public function testInstantiationSucceedNonRawCookieNameContainsSpecialCharacters($name)
{
$this->assertInstanceOf(Cookie::class, new Cookie($name));
}
public function testInstantiationThrowsExceptionIfCookieNameIsEmpty()
{
$this->expectException('InvalidArgumentException');
new Cookie('');
}
public function testInvalidExpiration()
{
$this->expectException('InvalidArgumentException');
new Cookie('MyCookie', 'foo', 'bar');
}
@@ -80,9 +91,13 @@ class CookieTest extends TestCase
public function testGetExpiresTime()
{
$cookie = new Cookie('foo', 'bar', 3600);
$cookie = new Cookie('foo', 'bar');
$this->assertEquals(3600, $cookie->getExpiresTime(), '->getExpiresTime() returns the expire date');
$this->assertEquals(0, $cookie->getExpiresTime(), '->getExpiresTime() returns the default expire date');
$cookie = new Cookie('foo', 'bar', $expire = time() + 3600);
$this->assertEquals($expire, $cookie->getExpiresTime(), '->getExpiresTime() returns the expire date');
}
public function testGetExpiresTimeIsCastToInt()
@@ -100,9 +115,6 @@ class CookieTest extends TestCase
$this->assertEquals($expire->format('U'), $cookie->getExpiresTime(), '->getExpiresTime() returns the expire date');
}
/**
* @requires PHP 5.5
*/
public function testConstructorWithDateTimeImmutable()
{
$expire = new \DateTimeImmutable();
@@ -117,26 +129,26 @@ class CookieTest extends TestCase
$cookie = new Cookie('foo', 'bar', $value);
$expire = strtotime($value);
$this->assertEquals($expire, $cookie->getExpiresTime(), '->getExpiresTime() returns the expire date', 1);
$this->assertEqualsWithDelta($expire, $cookie->getExpiresTime(), 1, '->getExpiresTime() returns the expire date');
}
public function testGetDomain()
{
$cookie = new Cookie('foo', 'bar', 3600, '/', '.myfoodomain.com');
$cookie = new Cookie('foo', 'bar', 0, '/', '.myfoodomain.com');
$this->assertEquals('.myfoodomain.com', $cookie->getDomain(), '->getDomain() returns the domain name on which the cookie is valid');
}
public function testIsSecure()
{
$cookie = new Cookie('foo', 'bar', 3600, '/', '.myfoodomain.com', true);
$cookie = new Cookie('foo', 'bar', 0, '/', '.myfoodomain.com', true);
$this->assertTrue($cookie->isSecure(), '->isSecure() returns whether the cookie is transmitted over HTTPS');
}
public function testIsHttpOnly()
{
$cookie = new Cookie('foo', 'bar', 3600, '/', '.myfoodomain.com', false, true);
$cookie = new Cookie('foo', 'bar', 0, '/', '.myfoodomain.com', false, true);
$this->assertTrue($cookie->isHttpOnly(), '->isHttpOnly() returns whether the cookie is only transmitted over HTTP');
}
@@ -169,16 +181,63 @@ class CookieTest extends TestCase
public function testToString()
{
$cookie = new Cookie('foo', 'bar', strtotime('Fri, 20-May-2011 15:25:52 GMT'), '/', '.myfoodomain.com', true);
$this->assertEquals('foo=bar; expires=Fri, 20-May-2011 15:25:52 GMT; path=/; domain=.myfoodomain.com; secure; httponly', (string) $cookie, '->__toString() returns string representation of the cookie');
$cookie = new Cookie('foo', 'bar', $expire = strtotime('Fri, 20-May-2011 15:25:52 GMT'), '/', '.myfoodomain.com', true);
$this->assertEquals('foo=bar; expires=Fri, 20-May-2011 15:25:52 GMT; Max-Age=0; path=/; domain=.myfoodomain.com; secure; httponly', (string) $cookie, '->__toString() returns string representation of the cookie');
$cookie = new Cookie('foo', 'bar with white spaces', strtotime('Fri, 20-May-2011 15:25:52 GMT'), '/', '.myfoodomain.com', true);
$this->assertEquals('foo=bar%20with%20white%20spaces; expires=Fri, 20-May-2011 15:25:52 GMT; path=/; domain=.myfoodomain.com; secure; httponly', (string) $cookie, '->__toString() encodes the value of the cookie according to RFC 3986 (white space = %20)');
$this->assertEquals('foo=bar%20with%20white%20spaces; expires=Fri, 20-May-2011 15:25:52 GMT; Max-Age=0; path=/; domain=.myfoodomain.com; secure; httponly', (string) $cookie, '->__toString() encodes the value of the cookie according to RFC 3986 (white space = %20)');
$cookie = new Cookie('foo', null, 1, '/admin/', '.myfoodomain.com');
$this->assertEquals('foo=deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; path=/admin/; domain=.myfoodomain.com; httponly', (string) $cookie, '->__toString() returns string representation of a cleared cookie if value is NULL');
$this->assertEquals('foo=deleted; expires='.gmdate('D, d-M-Y H:i:s T', $expire = time() - 31536001).'; Max-Age=0; path=/admin/; domain=.myfoodomain.com; httponly', (string) $cookie, '->__toString() returns string representation of a cleared cookie if value is NULL');
$cookie = new Cookie('foo', 'bar', 0, '/', '');
$this->assertEquals('foo=bar; path=/; httponly', (string) $cookie);
}
public function testRawCookie()
{
$cookie = new Cookie('foo', 'b a r', 0, '/', null, false, false);
$this->assertFalse($cookie->isRaw());
$this->assertEquals('foo=b%20a%20r; path=/', (string) $cookie);
$cookie = new Cookie('foo', 'b+a+r', 0, '/', null, false, false, true);
$this->assertTrue($cookie->isRaw());
$this->assertEquals('foo=b+a+r; path=/', (string) $cookie);
}
public function testGetMaxAge()
{
$cookie = new Cookie('foo', 'bar');
$this->assertEquals(0, $cookie->getMaxAge());
$cookie = new Cookie('foo', 'bar', $expire = time() + 100);
$this->assertEquals($expire - time(), $cookie->getMaxAge());
$cookie = new Cookie('foo', 'bar', $expire = time() - 100);
$this->assertEquals(0, $cookie->getMaxAge());
}
public function testFromString()
{
$cookie = Cookie::fromString('foo=bar; expires=Fri, 20-May-2011 15:25:52 GMT; path=/; domain=.myfoodomain.com; secure; httponly');
$this->assertEquals(new Cookie('foo', 'bar', strtotime('Fri, 20-May-2011 15:25:52 GMT'), '/', '.myfoodomain.com', true, true, true), $cookie);
$cookie = Cookie::fromString('foo=bar', true);
$this->assertEquals(new Cookie('foo', 'bar', 0, '/', null, false, false), $cookie);
}
public function testFromStringWithHttpOnly()
{
$cookie = Cookie::fromString('foo=bar; expires=Fri, 20-May-2011 15:25:52 GMT; path=/; domain=.myfoodomain.com; secure; httponly');
$this->assertTrue($cookie->isHttpOnly());
$cookie = Cookie::fromString('foo=bar; expires=Fri, 20-May-2011 15:25:52 GMT; path=/; domain=.myfoodomain.com; secure');
$this->assertFalse($cookie->isHttpOnly());
}
public function testSameSiteAttributeIsCaseInsensitive()
{
$cookie = new Cookie('foo', 'bar', 0, '/', null, false, true, false, 'Lax');
$this->assertEquals('lax', $cookie->getSameSite());
}
}
@@ -18,11 +18,9 @@ use Symfony\Component\HttpFoundation\Request;
class ExpressionRequestMatcherTest extends TestCase
{
/**
* @expectedException \LogicException
*/
public function testWhenNoExpressionIsSet()
{
$this->expectException('LogicException');
$expressionRequestMatcher = new ExpressionRequestMatcher();
$expressionRequestMatcher->matches(new Request());
}
@@ -55,15 +53,15 @@ class ExpressionRequestMatcherTest extends TestCase
public function provideExpressions()
{
return array(
array('request.getMethod() == method', true),
array('request.getPathInfo() == path', true),
array('request.getHost() == host', true),
array('request.getClientIp() == ip', true),
array('request.attributes.all() == attributes', true),
array('request.getMethod() == method && request.getPathInfo() == path && request.getHost() == host && request.getClientIp() == ip && request.attributes.all() == attributes', true),
array('request.getMethod() != method', false),
array('request.getMethod() != method && request.getPathInfo() == path && request.getHost() == host && request.getClientIp() == ip && request.attributes.all() == attributes', false),
);
return [
['request.getMethod() == method', true],
['request.getPathInfo() == path', true],
['request.getHost() == host', true],
['request.getClientIp() == ip', true],
['request.attributes.all() == attributes', true],
['request.getMethod() == method && request.getPathInfo() == path && request.getHost() == host && request.getClientIp() == ip && request.attributes.all() == attributes', true],
['request.getMethod() != method', false],
['request.getMethod() != method && request.getPathInfo() == path && request.getHost() == host && request.getClientIp() == ip && request.attributes.all() == attributes', false],
];
}
}
+14 -14
View File
@@ -64,7 +64,7 @@ class FileTest extends TestCase
public function testConstructWhenFileNotExists()
{
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException');
$this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException');
new File(__DIR__.'/Fixtures/not_here');
}
@@ -83,7 +83,7 @@ class FileTest extends TestCase
$this->assertInstanceOf('Symfony\Component\HttpFoundation\File\File', $movedFile);
$this->assertFileExists($targetPath);
$this->assertFileNotExists($path);
$this->assertFileDoesNotExist($path);
$this->assertEquals(realpath($targetPath), $movedFile->getRealPath());
@unlink($targetPath);
@@ -102,7 +102,7 @@ class FileTest extends TestCase
$movedFile = $file->move($targetDir, 'test.newname.gif');
$this->assertFileExists($targetPath);
$this->assertFileNotExists($path);
$this->assertFileDoesNotExist($path);
$this->assertEquals(realpath($targetPath), $movedFile->getRealPath());
@unlink($targetPath);
@@ -110,14 +110,14 @@ class FileTest extends TestCase
public function getFilenameFixtures()
{
return array(
array('original.gif', 'original.gif'),
array('..\\..\\original.gif', 'original.gif'),
array('../../original.gif', 'original.gif'),
array('файлfile.gif', 'файлfile.gif'),
array('..\\..\\файлfile.gif', 'файлfile.gif'),
array('../../файлfile.gif', 'файлfile.gif'),
);
return [
['original.gif', 'original.gif'],
['..\\..\\original.gif', 'original.gif'],
['../../original.gif', 'original.gif'],
['файлfile.gif', 'файлfile.gif'],
['..\\..\\файлfile.gif', 'файлfile.gif'],
['../../файлfile.gif', 'файлfile.gif'],
];
}
/**
@@ -137,7 +137,7 @@ class FileTest extends TestCase
$this->assertInstanceOf('Symfony\Component\HttpFoundation\File\File', $movedFile);
$this->assertFileExists($targetPath);
$this->assertFileNotExists($path);
$this->assertFileDoesNotExist($path);
$this->assertEquals(realpath($targetPath), $movedFile->getRealPath());
@unlink($targetPath);
@@ -157,7 +157,7 @@ class FileTest extends TestCase
$movedFile = $file->move($targetDir);
$this->assertFileExists($targetPath);
$this->assertFileNotExists($sourcePath);
$this->assertFileDoesNotExist($sourcePath);
$this->assertEquals(realpath($targetPath), $movedFile->getRealPath());
@unlink($sourcePath);
@@ -172,7 +172,7 @@ class FileTest extends TestCase
->expects($this->once())
->method('guess')
->with($this->equalTo($path))
->will($this->returnValue($mimeType))
->willReturn($mimeType)
;
return $guesser;
@@ -26,10 +26,8 @@ class MimeTypeTest extends TestCase
chdir(__DIR__.'/../Fixtures');
try {
$this->assertEquals('image/gif', MimeTypeGuesser::getInstance()->guess('-test'));
} finally {
chdir($cwd);
} catch(\Exception $e) {
chdir($cwd);
throw $e;
}
}
@@ -40,7 +38,7 @@ class MimeTypeTest extends TestCase
public function testGuessImageWithDirectory()
{
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException');
$this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException');
MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/directory');
}
@@ -62,9 +60,23 @@ class MimeTypeTest extends TestCase
$this->assertEquals('application/octet-stream', MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/.unknownextension'));
}
/**
* @requires PHP 7.0
*/
public function testGuessWithDuplicatedFileType()
{
if ('application/zip' === MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/test.docx')) {
$this->addToAssertionCount(1);
return;
}
$this->assertSame('application/vnd.openxmlformats-officedocument.wordprocessingml.document', MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/test.docx'));
}
public function testGuessWithIncorrectPath()
{
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException');
$this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException');
MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/not_here');
}
@@ -83,7 +95,7 @@ class MimeTypeTest extends TestCase
@chmod($path, 0333);
if ('0333' == substr(sprintf('%o', fileperms($path)), -4)) {
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException');
$this->expectException('Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException');
MimeTypeGuesser::getInstance()->guess($path);
} else {
$this->markTestSkipped('Can not verify chmod operations, change of file permissions failed');
@@ -25,7 +25,7 @@ class UploadedFileTest extends TestCase
public function testConstructWhenFileNotExists()
{
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException');
$this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException');
new UploadedFile(
__DIR__.'/Fixtures/not_here',
@@ -41,7 +41,7 @@ class UploadedFileTest extends TestCase
'original.gif',
null,
filesize(__DIR__.'/Fixtures/test.gif'),
UPLOAD_ERR_OK
\UPLOAD_ERR_OK
);
$this->assertEquals('application/octet-stream', $file->getClientMimeType());
@@ -58,7 +58,7 @@ class UploadedFileTest extends TestCase
'original.gif',
null,
filesize(__DIR__.'/Fixtures/.unknownextension'),
UPLOAD_ERR_OK
\UPLOAD_ERR_OK
);
$this->assertEquals('application/octet-stream', $file->getClientMimeType());
@@ -82,12 +82,25 @@ class UploadedFileTest extends TestCase
$file = new UploadedFile(
__DIR__.'/Fixtures/test.gif',
'original.gif',
'image/jpeg',
'image/png',
filesize(__DIR__.'/Fixtures/test.gif'),
null
);
$this->assertEquals('jpeg', $file->guessClientExtension());
$this->assertEquals('png', $file->guessClientExtension());
}
public function testCaseSensitiveMimeType()
{
$file = new UploadedFile(
__DIR__.'/Fixtures/case-sensitive-mime-type.xlsm',
'test.xlsm',
'application/vnd.ms-excel.sheet.macroEnabled.12',
filesize(__DIR__.'/Fixtures/case-sensitive-mime-type.xlsm'),
null
);
$this->assertEquals('xlsm', $file->guessClientExtension());
}
public function testErrorIsOkByDefault()
@@ -100,7 +113,7 @@ class UploadedFileTest extends TestCase
null
);
$this->assertEquals(UPLOAD_ERR_OK, $file->getError());
$this->assertEquals(\UPLOAD_ERR_OK, $file->getError());
}
public function testGetClientOriginalName()
@@ -129,20 +142,18 @@ class UploadedFileTest extends TestCase
$this->assertEquals('gif', $file->getClientOriginalExtension());
}
/**
* @expectedException \Symfony\Component\HttpFoundation\File\Exception\FileException
*/
public function testMoveLocalFileIsNotAllowed()
{
$this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileException');
$file = new UploadedFile(
__DIR__.'/Fixtures/test.gif',
'original.gif',
'image/gif',
filesize(__DIR__.'/Fixtures/test.gif'),
UPLOAD_ERR_OK
\UPLOAD_ERR_OK
);
$movedFile = $file->move(__DIR__.'/Fixtures/directory');
$file->move(__DIR__.'/Fixtures/directory');
}
public function testMoveLocalFileIsAllowedInTestMode()
@@ -159,14 +170,14 @@ class UploadedFileTest extends TestCase
'original.gif',
'image/gif',
filesize($path),
UPLOAD_ERR_OK,
\UPLOAD_ERR_OK,
true
);
$movedFile = $file->move(__DIR__.'/Fixtures/directory');
$this->assertFileExists($targetPath);
$this->assertFileNotExists($path);
$this->assertFileDoesNotExist($path);
$this->assertEquals(realpath($targetPath), $movedFile->getRealPath());
@unlink($targetPath);
@@ -224,7 +235,7 @@ class UploadedFileTest extends TestCase
'original.gif',
null,
filesize(__DIR__.'/Fixtures/test.gif'),
UPLOAD_ERR_OK,
\UPLOAD_ERR_OK,
true
);
@@ -249,13 +260,13 @@ class UploadedFileTest extends TestCase
public function uploadedFileErrorProvider()
{
return array(
array(UPLOAD_ERR_INI_SIZE),
array(UPLOAD_ERR_FORM_SIZE),
array(UPLOAD_ERR_PARTIAL),
array(UPLOAD_ERR_NO_TMP_DIR),
array(UPLOAD_ERR_EXTENSION),
);
return [
[\UPLOAD_ERR_INI_SIZE],
[\UPLOAD_ERR_FORM_SIZE],
[\UPLOAD_ERR_PARTIAL],
[\UPLOAD_ERR_NO_TMP_DIR],
[\UPLOAD_ERR_EXTENSION],
];
}
public function testIsInvalidIfNotHttpUpload()
@@ -265,9 +276,23 @@ class UploadedFileTest extends TestCase
'original.gif',
null,
filesize(__DIR__.'/Fixtures/test.gif'),
UPLOAD_ERR_OK
\UPLOAD_ERR_OK
);
$this->assertFalse($file->isValid());
}
public function testGetMaxFilesize()
{
$size = UploadedFile::getMaxFilesize();
$this->assertIsInt($size);
$this->assertGreaterThan(0, $size);
if (0 === (int) ini_get('post_max_size') && 0 === (int) ini_get('upload_max_filesize')) {
$this->assertSame(\PHP_INT_MAX, $size);
} else {
$this->assertLessThan(\PHP_INT_MAX, $size);
}
}
}
+59 -61
View File
@@ -23,12 +23,10 @@ use Symfony\Component\HttpFoundation\FileBag;
*/
class FileBagTest extends TestCase
{
/**
* @expectedException \InvalidArgumentException
*/
public function testFileMustBeAnArrayOrUploadedFile()
{
new FileBag(array('file' => 'foo'));
$this->expectException('InvalidArgumentException');
new FileBag(['file' => 'foo']);
}
public function testShouldConvertsUploadedFiles()
@@ -36,54 +34,54 @@ class FileBagTest extends TestCase
$tmpFile = $this->createTempFile();
$file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0);
$bag = new FileBag(array('file' => array(
$bag = new FileBag(['file' => [
'name' => basename($tmpFile),
'type' => 'text/plain',
'tmp_name' => $tmpFile,
'error' => 0,
'size' => 100,
)));
]]);
$this->assertEquals($file, $bag->get('file'));
}
public function testShouldSetEmptyUploadedFilesToNull()
{
$bag = new FileBag(array('file' => array(
$bag = new FileBag(['file' => [
'name' => '',
'type' => '',
'tmp_name' => '',
'error' => UPLOAD_ERR_NO_FILE,
'error' => \UPLOAD_ERR_NO_FILE,
'size' => 0,
)));
]]);
$this->assertNull($bag->get('file'));
}
public function testShouldRemoveEmptyUploadedFilesForMultiUpload()
{
$bag = new FileBag(array('files' => array(
'name' => array(''),
'type' => array(''),
'tmp_name' => array(''),
'error' => array(UPLOAD_ERR_NO_FILE),
'size' => array(0),
)));
$bag = new FileBag(['files' => [
'name' => [''],
'type' => [''],
'tmp_name' => [''],
'error' => [\UPLOAD_ERR_NO_FILE],
'size' => [0],
]]);
$this->assertSame(array(), $bag->get('files'));
$this->assertSame([], $bag->get('files'));
}
public function testShouldNotRemoveEmptyUploadedFilesForAssociativeArray()
{
$bag = new FileBag(array('files' => array(
'name' => array('file1' => ''),
'type' => array('file1' => ''),
'tmp_name' => array('file1' => ''),
'error' => array('file1' => UPLOAD_ERR_NO_FILE),
'size' => array('file1' => 0),
)));
$bag = new FileBag(['files' => [
'name' => ['file1' => ''],
'type' => ['file1' => ''],
'tmp_name' => ['file1' => ''],
'error' => ['file1' => \UPLOAD_ERR_NO_FILE],
'size' => ['file1' => 0],
]]);
$this->assertSame(array('file1' => null), $bag->get('files'));
$this->assertSame(['file1' => null], $bag->get('files'));
}
public function testShouldConvertUploadedFilesWithPhpBug()
@@ -91,25 +89,25 @@ class FileBagTest extends TestCase
$tmpFile = $this->createTempFile();
$file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0);
$bag = new FileBag(array(
'child' => array(
'name' => array(
$bag = new FileBag([
'child' => [
'name' => [
'file' => basename($tmpFile),
),
'type' => array(
],
'type' => [
'file' => 'text/plain',
),
'tmp_name' => array(
],
'tmp_name' => [
'file' => $tmpFile,
),
'error' => array(
],
'error' => [
'file' => 0,
),
'size' => array(
],
'size' => [
'file' => 100,
),
),
));
],
],
]);
$files = $bag->all();
$this->assertEquals($file, $files['child']['file']);
@@ -120,25 +118,25 @@ class FileBagTest extends TestCase
$tmpFile = $this->createTempFile();
$file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0);
$bag = new FileBag(array(
'child' => array(
'name' => array(
'sub' => array('file' => basename($tmpFile)),
),
'type' => array(
'sub' => array('file' => 'text/plain'),
),
'tmp_name' => array(
'sub' => array('file' => $tmpFile),
),
'error' => array(
'sub' => array('file' => 0),
),
'size' => array(
'sub' => array('file' => 100),
),
),
));
$bag = new FileBag([
'child' => [
'name' => [
'sub' => ['file' => basename($tmpFile)],
],
'type' => [
'sub' => ['file' => 'text/plain'],
],
'tmp_name' => [
'sub' => ['file' => $tmpFile],
],
'error' => [
'sub' => ['file' => 0],
],
'size' => [
'sub' => ['file' => 100],
],
],
]);
$files = $bag->all();
$this->assertEquals($file, $files['child']['sub']['file']);
@@ -148,7 +146,7 @@ class FileBagTest extends TestCase
{
$tmpFile = $this->createTempFile();
$file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0);
$bag = new FileBag(array('image' => array('file' => $file)));
$bag = new FileBag(['image' => ['file' => $file]]);
$files = $bag->all();
$this->assertEquals($file, $files['image']['file']);
@@ -167,9 +165,9 @@ class FileBagTest extends TestCase
protected function tearDown()
{
foreach (glob(sys_get_temp_dir().'/form_test/*') as $file) {
unlink($file);
@unlink($file);
}
rmdir(sys_get_temp_dir().'/form_test');
@rmdir(sys_get_temp_dir().'/form_test');
}
}
+47 -30
View File
@@ -18,7 +18,7 @@ class HeaderBagTest extends TestCase
{
public function testConstructor()
{
$bag = new HeaderBag(array('foo' => 'bar'));
$bag = new HeaderBag(['foo' => 'bar']);
$this->assertTrue($bag->has('foo'));
}
@@ -30,31 +30,36 @@ class HeaderBagTest extends TestCase
public function testToStringNotNull()
{
$bag = new HeaderBag(array('foo' => 'bar'));
$bag = new HeaderBag(['foo' => 'bar']);
$this->assertEquals("Foo: bar\r\n", $bag->__toString());
}
public function testKeys()
{
$bag = new HeaderBag(array('foo' => 'bar'));
$bag = new HeaderBag(['foo' => 'bar']);
$keys = $bag->keys();
$this->assertEquals('foo', $keys[0]);
}
public function testGetDate()
{
$bag = new HeaderBag(array('foo' => 'Tue, 4 Sep 2012 20:00:00 +0200'));
$bag = new HeaderBag(['foo' => 'Tue, 4 Sep 2012 20:00:00 +0200']);
$headerDate = $bag->getDate('foo');
$this->assertInstanceOf('DateTime', $headerDate);
}
/**
* @expectedException \RuntimeException
*/
public function testGetDateNull()
{
$bag = new HeaderBag(['foo' => null]);
$headerDate = $bag->getDate('foo');
$this->assertNull($headerDate);
}
public function testGetDateException()
{
$bag = new HeaderBag(array('foo' => 'Tue'));
$headerDate = $bag->getDate('foo');
$this->expectException('RuntimeException');
$bag = new HeaderBag(['foo' => 'Tue']);
$bag->getDate('foo');
}
public function testGetCacheControlHeader()
@@ -67,50 +72,53 @@ class HeaderBagTest extends TestCase
public function testAll()
{
$bag = new HeaderBag(array('foo' => 'bar'));
$this->assertEquals(array('foo' => array('bar')), $bag->all(), '->all() gets all the input');
$bag = new HeaderBag(['foo' => 'bar']);
$this->assertEquals(['foo' => ['bar']], $bag->all(), '->all() gets all the input');
$bag = new HeaderBag(array('FOO' => 'BAR'));
$this->assertEquals(array('foo' => array('BAR')), $bag->all(), '->all() gets all the input key are lower case');
$bag = new HeaderBag(['FOO' => 'BAR']);
$this->assertEquals(['foo' => ['BAR']], $bag->all(), '->all() gets all the input key are lower case');
}
public function testReplace()
{
$bag = new HeaderBag(array('foo' => 'bar'));
$bag = new HeaderBag(['foo' => 'bar']);
$bag->replace(array('NOPE' => 'BAR'));
$this->assertEquals(array('nope' => array('BAR')), $bag->all(), '->replace() replaces the input with the argument');
$bag->replace(['NOPE' => 'BAR']);
$this->assertEquals(['nope' => ['BAR']], $bag->all(), '->replace() replaces the input with the argument');
$this->assertFalse($bag->has('foo'), '->replace() overrides previously set the input');
}
public function testGet()
{
$bag = new HeaderBag(array('foo' => 'bar', 'fuzz' => 'bizz'));
$bag = new HeaderBag(['foo' => 'bar', 'fuzz' => 'bizz']);
$this->assertEquals('bar', $bag->get('foo'), '->get return current value');
$this->assertEquals('bar', $bag->get('FoO'), '->get key in case insensitive');
$this->assertEquals(array('bar'), $bag->get('foo', 'nope', false), '->get return the value as array');
$this->assertEquals(['bar'], $bag->get('foo', 'nope', false), '->get return the value as array');
// defaults
$this->assertNull($bag->get('none'), '->get unknown values returns null');
$this->assertEquals('default', $bag->get('none', 'default'), '->get unknown values returns default');
$this->assertEquals(array('default'), $bag->get('none', 'default', false), '->get unknown values returns default as array');
$this->assertEquals(['default'], $bag->get('none', 'default', false), '->get unknown values returns default as array');
$bag->set('foo', 'bor', false);
$this->assertEquals('bar', $bag->get('foo'), '->get return first value');
$this->assertEquals(array('bar', 'bor'), $bag->get('foo', 'nope', false), '->get return all values as array');
$this->assertEquals(['bar', 'bor'], $bag->get('foo', 'nope', false), '->get return all values as array');
$bag->set('baz', null);
$this->assertNull($bag->get('baz', 'nope'), '->get return null although different default value is given');
}
public function testSetAssociativeArray()
{
$bag = new HeaderBag();
$bag->set('foo', array('bad-assoc-index' => 'value'));
$bag->set('foo', ['bad-assoc-index' => 'value']);
$this->assertSame('value', $bag->get('foo'));
$this->assertEquals(array('value'), $bag->get('foo', 'nope', false), 'assoc indices of multi-valued headers are ignored');
$this->assertEquals(['value'], $bag->get('foo', 'nope', false), 'assoc indices of multi-valued headers are ignored');
}
public function testContains()
{
$bag = new HeaderBag(array('foo' => 'bar', 'fuzz' => 'bizz'));
$bag = new HeaderBag(['foo' => 'bar', 'fuzz' => 'bizz']);
$this->assertTrue($bag->contains('foo', 'bar'), '->contains first value');
$this->assertTrue($bag->contains('fuzz', 'bizz'), '->contains second value');
$this->assertFalse($bag->contains('nope', 'nope'), '->contains unknown value');
@@ -143,7 +151,7 @@ class HeaderBagTest extends TestCase
public function testCacheControlDirectiveParsing()
{
$bag = new HeaderBag(array('cache-control' => 'public, max-age=10'));
$bag = new HeaderBag(['cache-control' => 'public, max-age=10']);
$this->assertTrue($bag->hasCacheControlDirective('public'));
$this->assertTrue($bag->getCacheControlDirective('public'));
@@ -156,15 +164,15 @@ class HeaderBagTest extends TestCase
public function testCacheControlDirectiveParsingQuotedZero()
{
$bag = new HeaderBag(array('cache-control' => 'max-age="0"'));
$bag = new HeaderBag(['cache-control' => 'max-age="0"']);
$this->assertTrue($bag->hasCacheControlDirective('max-age'));
$this->assertEquals(0, $bag->getCacheControlDirective('max-age'));
}
public function testCacheControlDirectiveOverrideWithReplace()
{
$bag = new HeaderBag(array('cache-control' => 'private, max-age=100'));
$bag->replace(array('cache-control' => 'public, max-age=10'));
$bag = new HeaderBag(['cache-control' => 'private, max-age=100']);
$bag->replace(['cache-control' => 'public, max-age=10']);
$this->assertTrue($bag->hasCacheControlDirective('public'));
$this->assertTrue($bag->getCacheControlDirective('public'));
@@ -172,15 +180,24 @@ class HeaderBagTest extends TestCase
$this->assertEquals(10, $bag->getCacheControlDirective('max-age'));
}
public function testCacheControlClone()
{
$headers = ['foo' => 'bar'];
$bag1 = new HeaderBag($headers);
$bag2 = new HeaderBag($bag1->all());
$this->assertEquals($bag1->all(), $bag2->all());
}
public function testGetIterator()
{
$headers = array('foo' => 'bar', 'hello' => 'world', 'third' => 'charm');
$headers = ['foo' => 'bar', 'hello' => 'world', 'third' => 'charm'];
$headerBag = new HeaderBag($headers);
$i = 0;
foreach ($headerBag as $key => $val) {
++$i;
$this->assertEquals(array($headers[$key]), $val);
$this->assertEquals([$headers[$key]], $val);
}
$this->assertEquals(\count($headers), $i);
@@ -188,7 +205,7 @@ class HeaderBagTest extends TestCase
public function testCount()
{
$headers = array('foo' => 'bar', 'HELLO' => 'WORLD');
$headers = ['foo' => 'bar', 'HELLO' => 'WORLD'];
$headerBag = new HeaderBag($headers);
$this->assertCount(\count($headers), $headerBag);
+34 -34
View File
@@ -26,20 +26,20 @@ class IpUtilsTest extends TestCase
public function getIpv4Data()
{
return array(
array(true, '192.168.1.1', '192.168.1.1'),
array(true, '192.168.1.1', '192.168.1.1/1'),
array(true, '192.168.1.1', '192.168.1.0/24'),
array(false, '192.168.1.1', '1.2.3.4/1'),
array(false, '192.168.1.1', '192.168.1.1/33'), // invalid subnet
array(true, '192.168.1.1', array('1.2.3.4/1', '192.168.1.0/24')),
array(true, '192.168.1.1', array('192.168.1.0/24', '1.2.3.4/1')),
array(false, '192.168.1.1', array('1.2.3.4/1', '4.3.2.1/1')),
array(true, '1.2.3.4', '0.0.0.0/0'),
array(true, '1.2.3.4', '192.168.1.0/0'),
array(false, '1.2.3.4', '256.256.256/0'), // invalid CIDR notation
array(false, 'an_invalid_ip', '192.168.1.0/24'),
);
return [
[true, '192.168.1.1', '192.168.1.1'],
[true, '192.168.1.1', '192.168.1.1/1'],
[true, '192.168.1.1', '192.168.1.0/24'],
[false, '192.168.1.1', '1.2.3.4/1'],
[false, '192.168.1.1', '192.168.1.1/33'], // invalid subnet
[true, '192.168.1.1', ['1.2.3.4/1', '192.168.1.0/24']],
[true, '192.168.1.1', ['192.168.1.0/24', '1.2.3.4/1']],
[false, '192.168.1.1', ['1.2.3.4/1', '4.3.2.1/1']],
[true, '1.2.3.4', '0.0.0.0/0'],
[true, '1.2.3.4', '192.168.1.0/0'],
[false, '1.2.3.4', '256.256.256/0'], // invalid CIDR notation
[false, 'an_invalid_ip', '192.168.1.0/24'],
];
}
/**
@@ -56,28 +56,28 @@ class IpUtilsTest extends TestCase
public function getIpv6Data()
{
return array(
array(true, '2a01:198:603:0:396e:4789:8e99:890f', '2a01:198:603:0::/65'),
array(false, '2a00:198:603:0:396e:4789:8e99:890f', '2a01:198:603:0::/65'),
array(false, '2a01:198:603:0:396e:4789:8e99:890f', '::1'),
array(true, '0:0:0:0:0:0:0:1', '::1'),
array(false, '0:0:603:0:396e:4789:8e99:0001', '::1'),
array(true, '0:0:603:0:396e:4789:8e99:0001', '::/0'),
array(true, '0:0:603:0:396e:4789:8e99:0001', '2a01:198:603:0::/0'),
array(true, '2a01:198:603:0:396e:4789:8e99:890f', array('::1', '2a01:198:603:0::/65')),
array(true, '2a01:198:603:0:396e:4789:8e99:890f', array('2a01:198:603:0::/65', '::1')),
array(false, '2a01:198:603:0:396e:4789:8e99:890f', array('::1', '1a01:198:603:0::/65')),
array(false, '}__test|O:21:"JDatabaseDriverMysqli":3:{s:2', '::1'),
array(false, '2a01:198:603:0:396e:4789:8e99:890f', 'unknown'),
);
return [
[true, '2a01:198:603:0:396e:4789:8e99:890f', '2a01:198:603:0::/65'],
[false, '2a00:198:603:0:396e:4789:8e99:890f', '2a01:198:603:0::/65'],
[false, '2a01:198:603:0:396e:4789:8e99:890f', '::1'],
[true, '0:0:0:0:0:0:0:1', '::1'],
[false, '0:0:603:0:396e:4789:8e99:0001', '::1'],
[true, '0:0:603:0:396e:4789:8e99:0001', '::/0'],
[true, '0:0:603:0:396e:4789:8e99:0001', '2a01:198:603:0::/0'],
[true, '2a01:198:603:0:396e:4789:8e99:890f', ['::1', '2a01:198:603:0::/65']],
[true, '2a01:198:603:0:396e:4789:8e99:890f', ['2a01:198:603:0::/65', '::1']],
[false, '2a01:198:603:0:396e:4789:8e99:890f', ['::1', '1a01:198:603:0::/65']],
[false, '}__test|O:21:"JDatabaseDriverMysqli":3:{s:2', '::1'],
[false, '2a01:198:603:0:396e:4789:8e99:890f', 'unknown'],
];
}
/**
* @expectedException \RuntimeException
* @requires extension sockets
*/
public function testAnIpv6WithOptionDisabledIpv6()
{
$this->expectException('RuntimeException');
if (\defined('AF_INET6')) {
$this->markTestSkipped('Only works when PHP is compiled with the option "disable-ipv6".');
}
@@ -95,10 +95,10 @@ class IpUtilsTest extends TestCase
public function invalidIpAddressData()
{
return array(
'invalid proxy wildcard' => array('192.168.20.13', '*'),
'invalid proxy missing netmask' => array('192.168.20.13', '0.0.0.0'),
'invalid request IP with invalid proxy wildcard' => array('0.0.0.0', '*'),
);
return [
'invalid proxy wildcard' => ['192.168.20.13', '*'],
'invalid proxy missing netmask' => ['192.168.20.13', '0.0.0.0'],
'invalid request IP with invalid proxy wildcard' => ['0.0.0.0', '*'],
];
}
}
+45 -30
View File
@@ -33,13 +33,13 @@ class JsonResponseTest extends TestCase
public function testConstructorWithArrayCreatesJsonArray()
{
$response = new JsonResponse(array(0, 1, 2, 3));
$response = new JsonResponse([0, 1, 2, 3]);
$this->assertSame('[0,1,2,3]', $response->getContent());
}
public function testConstructorWithAssocArrayCreatesJsonObject()
{
$response = new JsonResponse(array('foo' => 'bar'));
$response = new JsonResponse(['foo' => 'bar']);
$this->assertSame('{"foo":"bar"}', $response->getContent());
}
@@ -52,7 +52,8 @@ class JsonResponseTest extends TestCase
$this->assertSame('0', $response->getContent());
$response = new JsonResponse(0.1);
$this->assertSame('0.1', $response->getContent());
$this->assertEquals(0.1, $response->getContent());
$this->assertIsString($response->getContent());
$response = new JsonResponse(true);
$this->assertSame('true', $response->getContent());
@@ -60,7 +61,7 @@ class JsonResponseTest extends TestCase
public function testConstructorWithCustomStatus()
{
$response = new JsonResponse(array(), 202);
$response = new JsonResponse([], 202);
$this->assertSame(202, $response->getStatusCode());
}
@@ -72,22 +73,35 @@ class JsonResponseTest extends TestCase
public function testConstructorWithCustomHeaders()
{
$response = new JsonResponse(array(), 200, array('ETag' => 'foo'));
$response = new JsonResponse([], 200, ['ETag' => 'foo']);
$this->assertSame('application/json', $response->headers->get('Content-Type'));
$this->assertSame('foo', $response->headers->get('ETag'));
}
public function testConstructorWithCustomContentType()
{
$headers = array('Content-Type' => 'application/vnd.acme.blog-v1+json');
$headers = ['Content-Type' => 'application/vnd.acme.blog-v1+json'];
$response = new JsonResponse(array(), 200, $headers);
$response = new JsonResponse([], 200, $headers);
$this->assertSame('application/vnd.acme.blog-v1+json', $response->headers->get('Content-Type'));
}
public function testSetJson()
{
$response = new JsonResponse('1', 200, [], true);
$this->assertEquals('1', $response->getContent());
$response = new JsonResponse('[1]', 200, [], true);
$this->assertEquals('[1]', $response->getContent());
$response = new JsonResponse(null, 200, []);
$response->setJson('true');
$this->assertEquals('true', $response->getContent());
}
public function testCreate()
{
$response = JsonResponse::create(array('foo' => 'bar'), 204);
$response = JsonResponse::create(['foo' => 'bar'], 204);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response);
$this->assertEquals('{"foo":"bar"}', $response->getContent());
@@ -103,14 +117,14 @@ class JsonResponseTest extends TestCase
public function testStaticCreateJsonArray()
{
$response = JsonResponse::create(array(0, 1, 2, 3));
$response = JsonResponse::create([0, 1, 2, 3]);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response);
$this->assertSame('[0,1,2,3]', $response->getContent());
}
public function testStaticCreateJsonObject()
{
$response = JsonResponse::create(array('foo' => 'bar'));
$response = JsonResponse::create(['foo' => 'bar']);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response);
$this->assertSame('{"foo":"bar"}', $response->getContent());
}
@@ -127,7 +141,8 @@ class JsonResponseTest extends TestCase
$response = JsonResponse::create(0.1);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response);
$this->assertSame('0.1', $response->getContent());
$this->assertEquals(0.1, $response->getContent());
$this->assertIsString($response->getContent());
$response = JsonResponse::create(true);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response);
@@ -136,7 +151,7 @@ class JsonResponseTest extends TestCase
public function testStaticCreateWithCustomStatus()
{
$response = JsonResponse::create(array(), 202);
$response = JsonResponse::create([], 202);
$this->assertSame(202, $response->getStatusCode());
}
@@ -148,22 +163,22 @@ class JsonResponseTest extends TestCase
public function testStaticCreateWithCustomHeaders()
{
$response = JsonResponse::create(array(), 200, array('ETag' => 'foo'));
$response = JsonResponse::create([], 200, ['ETag' => 'foo']);
$this->assertSame('application/json', $response->headers->get('Content-Type'));
$this->assertSame('foo', $response->headers->get('ETag'));
}
public function testStaticCreateWithCustomContentType()
{
$headers = array('Content-Type' => 'application/vnd.acme.blog-v1+json');
$headers = ['Content-Type' => 'application/vnd.acme.blog-v1+json'];
$response = JsonResponse::create(array(), 200, $headers);
$response = JsonResponse::create([], 200, $headers);
$this->assertSame('application/vnd.acme.blog-v1+json', $response->headers->get('Content-Type'));
}
public function testSetCallback()
{
$response = JsonResponse::create(array('foo' => 'bar'))->setCallback('callback');
$response = JsonResponse::create(['foo' => 'bar'])->setCallback('callback');
$this->assertEquals('/**/callback({"foo":"bar"});', $response->getContent());
$this->assertEquals('text/javascript', $response->headers->get('Content-Type'));
@@ -180,44 +195,44 @@ class JsonResponseTest extends TestCase
{
$response = new JsonResponse();
$this->assertEquals(JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT, $response->getEncodingOptions());
$this->assertEquals(\JSON_HEX_TAG | \JSON_HEX_APOS | \JSON_HEX_AMP | \JSON_HEX_QUOT, $response->getEncodingOptions());
}
public function testSetEncodingOptions()
{
$response = new JsonResponse();
$response->setData(array(array(1, 2, 3)));
$response->setData([[1, 2, 3]]);
$this->assertEquals('[[1,2,3]]', $response->getContent());
$response->setEncodingOptions(JSON_FORCE_OBJECT);
$response->setEncodingOptions(\JSON_FORCE_OBJECT);
$this->assertEquals('{"0":{"0":1,"1":2,"2":3}}', $response->getContent());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testItAcceptsJsonAsString()
{
$response = JsonResponse::fromJsonString('{"foo":"bar"}');
$this->assertSame('{"foo":"bar"}', $response->getContent());
}
public function testSetCallbackInvalidIdentifier()
{
$this->expectException('InvalidArgumentException');
$response = new JsonResponse('foo');
$response->setCallback('+invalid');
}
/**
* @expectedException \InvalidArgumentException
*/
public function testSetContent()
{
$this->expectException('InvalidArgumentException');
JsonResponse::create("\xB1\x31");
}
/**
* @expectedException \Exception
* @expectedExceptionMessage This error is expected
*/
public function testSetContentJsonSerializeError()
{
$this->expectException('Exception');
$this->expectExceptionMessage('This error is expected');
if (!interface_exists('JsonSerializable', false)) {
$this->markTestSkipped('JsonSerializable is required.');
}
@@ -229,7 +244,7 @@ class JsonResponseTest extends TestCase
public function testSetComplexCallback()
{
$response = JsonResponse::create(array('foo' => 'bar'));
$response = JsonResponse::create(['foo' => 'bar']);
$response->setCallback('ಠ_ಠ["foo"].bar[0]');
$this->assertEquals('/**/ಠ_ಠ["foo"].bar[0]({"foo":"bar"});', $response->getContent());
+41 -76
View File
@@ -23,44 +23,44 @@ class ParameterBagTest extends TestCase
public function testAll()
{
$bag = new ParameterBag(array('foo' => 'bar'));
$this->assertEquals(array('foo' => 'bar'), $bag->all(), '->all() gets all the input');
$bag = new ParameterBag(['foo' => 'bar']);
$this->assertEquals(['foo' => 'bar'], $bag->all(), '->all() gets all the input');
}
public function testKeys()
{
$bag = new ParameterBag(array('foo' => 'bar'));
$this->assertEquals(array('foo'), $bag->keys());
$bag = new ParameterBag(['foo' => 'bar']);
$this->assertEquals(['foo'], $bag->keys());
}
public function testAdd()
{
$bag = new ParameterBag(array('foo' => 'bar'));
$bag->add(array('bar' => 'bas'));
$this->assertEquals(array('foo' => 'bar', 'bar' => 'bas'), $bag->all());
$bag = new ParameterBag(['foo' => 'bar']);
$bag->add(['bar' => 'bas']);
$this->assertEquals(['foo' => 'bar', 'bar' => 'bas'], $bag->all());
}
public function testRemove()
{
$bag = new ParameterBag(array('foo' => 'bar'));
$bag->add(array('bar' => 'bas'));
$this->assertEquals(array('foo' => 'bar', 'bar' => 'bas'), $bag->all());
$bag = new ParameterBag(['foo' => 'bar']);
$bag->add(['bar' => 'bas']);
$this->assertEquals(['foo' => 'bar', 'bar' => 'bas'], $bag->all());
$bag->remove('bar');
$this->assertEquals(array('foo' => 'bar'), $bag->all());
$this->assertEquals(['foo' => 'bar'], $bag->all());
}
public function testReplace()
{
$bag = new ParameterBag(array('foo' => 'bar'));
$bag = new ParameterBag(['foo' => 'bar']);
$bag->replace(array('FOO' => 'BAR'));
$this->assertEquals(array('FOO' => 'BAR'), $bag->all(), '->replace() replaces the input with the argument');
$bag->replace(['FOO' => 'BAR']);
$this->assertEquals(['FOO' => 'BAR'], $bag->all(), '->replace() replaces the input with the argument');
$this->assertFalse($bag->has('foo'), '->replace() overrides previously set the input');
}
public function testGet()
{
$bag = new ParameterBag(array('foo' => 'bar', 'null' => null));
$bag = new ParameterBag(['foo' => 'bar', 'null' => null]);
$this->assertEquals('bar', $bag->get('foo'), '->get() gets the value of a parameter');
$this->assertEquals('default', $bag->get('unknown', 'default'), '->get() returns second argument as default if a parameter is not defined');
@@ -69,49 +69,14 @@ class ParameterBagTest extends TestCase
public function testGetDoesNotUseDeepByDefault()
{
$bag = new ParameterBag(array('foo' => array('bar' => 'moo')));
$bag = new ParameterBag(['foo' => ['bar' => 'moo']]);
$this->assertNull($bag->get('foo[bar]'));
}
/**
* @group legacy
* @dataProvider getInvalidPaths
* @expectedException \InvalidArgumentException
*/
public function testGetDeepWithInvalidPaths($path)
{
$bag = new ParameterBag(array('foo' => array('bar' => 'moo')));
$bag->get($path, null, true);
}
public function getInvalidPaths()
{
return array(
array('foo[['),
array('foo[d'),
array('foo[bar]]'),
array('foo[bar]d'),
);
}
/**
* @group legacy
*/
public function testGetDeep()
{
$bag = new ParameterBag(array('foo' => array('bar' => array('moo' => 'boo'))));
$this->assertEquals(array('moo' => 'boo'), $bag->get('foo[bar]', null, true));
$this->assertEquals('boo', $bag->get('foo[bar][moo]', null, true));
$this->assertEquals('default', $bag->get('foo[bar][foo]', 'default', true));
$this->assertEquals('default', $bag->get('bar[moo][foo]', 'default', true));
}
public function testSet()
{
$bag = new ParameterBag(array());
$bag = new ParameterBag([]);
$bag->set('foo', 'bar');
$this->assertEquals('bar', $bag->get('foo'), '->set() sets the value of parameter');
@@ -122,7 +87,7 @@ class ParameterBagTest extends TestCase
public function testHas()
{
$bag = new ParameterBag(array('foo' => 'bar'));
$bag = new ParameterBag(['foo' => 'bar']);
$this->assertTrue($bag->has('foo'), '->has() returns true if a parameter is defined');
$this->assertFalse($bag->has('unknown'), '->has() return false if a parameter is not defined');
@@ -130,7 +95,7 @@ class ParameterBagTest extends TestCase
public function testGetAlpha()
{
$bag = new ParameterBag(array('word' => 'foo_BAR_012'));
$bag = new ParameterBag(['word' => 'foo_BAR_012']);
$this->assertEquals('fooBAR', $bag->getAlpha('word'), '->getAlpha() gets only alphabetic characters');
$this->assertEquals('', $bag->getAlpha('unknown'), '->getAlpha() returns empty string if a parameter is not defined');
@@ -138,7 +103,7 @@ class ParameterBagTest extends TestCase
public function testGetAlnum()
{
$bag = new ParameterBag(array('word' => 'foo_BAR_012'));
$bag = new ParameterBag(['word' => 'foo_BAR_012']);
$this->assertEquals('fooBAR012', $bag->getAlnum('word'), '->getAlnum() gets only alphanumeric characters');
$this->assertEquals('', $bag->getAlnum('unknown'), '->getAlnum() returns empty string if a parameter is not defined');
@@ -146,7 +111,7 @@ class ParameterBagTest extends TestCase
public function testGetDigits()
{
$bag = new ParameterBag(array('word' => 'foo_BAR_012'));
$bag = new ParameterBag(['word' => 'foo_BAR_012']);
$this->assertEquals('012', $bag->getDigits('word'), '->getDigits() gets only digits as string');
$this->assertEquals('', $bag->getDigits('unknown'), '->getDigits() returns empty string if a parameter is not defined');
@@ -154,7 +119,7 @@ class ParameterBagTest extends TestCase
public function testGetInt()
{
$bag = new ParameterBag(array('digits' => '0123'));
$bag = new ParameterBag(['digits' => '0123']);
$this->assertEquals(123, $bag->getInt('digits'), '->getInt() gets a value of parameter as integer');
$this->assertEquals(0, $bag->getInt('unknown'), '->getInt() returns zero if a parameter is not defined');
@@ -162,42 +127,42 @@ class ParameterBagTest extends TestCase
public function testFilter()
{
$bag = new ParameterBag(array(
$bag = new ParameterBag([
'digits' => '0123ab',
'email' => 'example@example.com',
'url' => 'http://example.com/foo',
'dec' => '256',
'hex' => '0x100',
'array' => array('bang'),
));
'array' => ['bang'],
]);
$this->assertEmpty($bag->filter('nokey'), '->filter() should return empty by default if no key is found');
$this->assertEquals('0123', $bag->filter('digits', '', FILTER_SANITIZE_NUMBER_INT), '->filter() gets a value of parameter as integer filtering out invalid characters');
$this->assertEquals('0123', $bag->filter('digits', '', \FILTER_SANITIZE_NUMBER_INT), '->filter() gets a value of parameter as integer filtering out invalid characters');
$this->assertEquals('example@example.com', $bag->filter('email', '', FILTER_VALIDATE_EMAIL), '->filter() gets a value of parameter as email');
$this->assertEquals('example@example.com', $bag->filter('email', '', \FILTER_VALIDATE_EMAIL), '->filter() gets a value of parameter as email');
$this->assertEquals('http://example.com/foo', $bag->filter('url', '', FILTER_VALIDATE_URL, array('flags' => FILTER_FLAG_PATH_REQUIRED)), '->filter() gets a value of parameter as URL with a path');
$this->assertEquals('http://example.com/foo', $bag->filter('url', '', \FILTER_VALIDATE_URL, ['flags' => \FILTER_FLAG_PATH_REQUIRED]), '->filter() gets a value of parameter as URL with a path');
// This test is repeated for code-coverage
$this->assertEquals('http://example.com/foo', $bag->filter('url', '', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED), '->filter() gets a value of parameter as URL with a path');
$this->assertEquals('http://example.com/foo', $bag->filter('url', '', \FILTER_VALIDATE_URL, \FILTER_FLAG_PATH_REQUIRED), '->filter() gets a value of parameter as URL with a path');
$this->assertFalse($bag->filter('dec', '', FILTER_VALIDATE_INT, array(
'flags' => FILTER_FLAG_ALLOW_HEX,
'options' => array('min_range' => 1, 'max_range' => 0xff),
)), '->filter() gets a value of parameter as integer between boundaries');
$this->assertFalse($bag->filter('dec', '', \FILTER_VALIDATE_INT, [
'flags' => \FILTER_FLAG_ALLOW_HEX,
'options' => ['min_range' => 1, 'max_range' => 0xff],
]), '->filter() gets a value of parameter as integer between boundaries');
$this->assertFalse($bag->filter('hex', '', FILTER_VALIDATE_INT, array(
'flags' => FILTER_FLAG_ALLOW_HEX,
'options' => array('min_range' => 1, 'max_range' => 0xff),
)), '->filter() gets a value of parameter as integer between boundaries');
$this->assertFalse($bag->filter('hex', '', \FILTER_VALIDATE_INT, [
'flags' => \FILTER_FLAG_ALLOW_HEX,
'options' => ['min_range' => 1, 'max_range' => 0xff],
]), '->filter() gets a value of parameter as integer between boundaries');
$this->assertEquals(array('bang'), $bag->filter('array', ''), '->filter() gets a value of parameter as an array');
$this->assertEquals(['bang'], $bag->filter('array', ''), '->filter() gets a value of parameter as an array');
}
public function testGetIterator()
{
$parameters = array('foo' => 'bar', 'hello' => 'world');
$parameters = ['foo' => 'bar', 'hello' => 'world'];
$bag = new ParameterBag($parameters);
$i = 0;
@@ -211,7 +176,7 @@ class ParameterBagTest extends TestCase
public function testCount()
{
$parameters = array('foo' => 'bar', 'hello' => 'world');
$parameters = ['foo' => 'bar', 'hello' => 'world'];
$bag = new ParameterBag($parameters);
$this->assertCount(\count($parameters), $bag);
@@ -219,7 +184,7 @@ class ParameterBagTest extends TestCase
public function testGetBoolean()
{
$parameters = array('string_true' => 'true', 'string_false' => 'false');
$parameters = ['string_true' => 'true', 'string_false' => 'false'];
$bag = new ParameterBag($parameters);
$this->assertTrue($bag->getBoolean('string_true'), '->getBoolean() gets the string true as boolean true');
+23 -15
View File
@@ -20,26 +20,19 @@ class RedirectResponseTest extends TestCase
{
$response = new RedirectResponse('foo.bar');
$this->assertEquals(1, preg_match(
'#<meta http-equiv="refresh" content="\d+;url=foo\.bar" />#',
preg_replace(array('/\s+/', '/\'/'), array(' ', '"'), $response->getContent())
));
$this->assertMatchesRegularExpression('#<meta http-equiv="refresh" content="\d+;url=\'foo\.bar\'" />#', preg_replace('/\s+/', ' ', $response->getContent()));
}
/**
* @expectedException \InvalidArgumentException
*/
public function testRedirectResponseConstructorNullUrl()
{
$response = new RedirectResponse(null);
$this->expectException('InvalidArgumentException');
new RedirectResponse(null);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testRedirectResponseConstructorWrongStatusCode()
{
$response = new RedirectResponse('foo.bar', 404);
$this->expectException('InvalidArgumentException');
new RedirectResponse('foo.bar', 404);
}
public function testGenerateLocationHeader()
@@ -65,11 +58,9 @@ class RedirectResponseTest extends TestCase
$this->assertEquals('baz.beep', $response->getTargetUrl());
}
/**
* @expectedException \InvalidArgumentException
*/
public function testSetTargetUrlNull()
{
$this->expectException('InvalidArgumentException');
$response = new RedirectResponse('foo.bar');
$response->setTargetUrl(null);
}
@@ -81,4 +72,21 @@ class RedirectResponseTest extends TestCase
$this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response);
$this->assertEquals(301, $response->getStatusCode());
}
public function testCacheHeaders()
{
$response = new RedirectResponse('foo.bar', 301);
$this->assertFalse($response->headers->hasCacheControlDirective('no-cache'));
$response = new RedirectResponse('foo.bar', 301, ['cache-control' => 'max-age=86400']);
$this->assertFalse($response->headers->hasCacheControlDirective('no-cache'));
$this->assertTrue($response->headers->hasCacheControlDirective('max-age'));
$response = new RedirectResponse('foo.bar', 301, ['Cache-Control' => 'max-age=86400']);
$this->assertFalse($response->headers->hasCacheControlDirective('no-cache'));
$this->assertTrue($response->headers->hasCacheControlDirective('max-age'));
$response = new RedirectResponse('foo.bar', 302);
$this->assertTrue($response->headers->hasCacheControlDirective('no-cache'));
}
}
+20 -20
View File
@@ -34,20 +34,20 @@ class RequestMatcherTest extends TestCase
public function getMethodData()
{
return array(
array('get', 'get', true),
array('get', array('get', 'post'), true),
array('get', 'post', false),
array('get', 'GET', true),
array('get', array('GET', 'POST'), true),
array('get', 'POST', false),
);
return [
['get', 'get', true],
['get', ['get', 'post'], true],
['get', 'post', false],
['get', 'GET', true],
['get', ['GET', 'POST'], true],
['get', 'POST', false],
];
}
public function testScheme()
{
$httpRequest = $request = $request = Request::create('');
$httpsRequest = $request = $request = Request::create('', 'get', array(), array(), array(), array('HTTPS' => 'on'));
$httpsRequest = $request = $request = Request::create('', 'get', [], [], [], ['HTTPS' => 'on']);
$matcher = new RequestMatcher();
$matcher->matchScheme('https');
@@ -69,7 +69,7 @@ class RequestMatcherTest extends TestCase
public function testHost($pattern, $isMatch)
{
$matcher = new RequestMatcher();
$request = Request::create('', 'get', array(), array(), array(), array('HTTP_HOST' => 'foo.example.com'));
$request = Request::create('', 'get', [], [], [], ['HTTP_HOST' => 'foo.example.com']);
$matcher->matchHost($pattern);
$this->assertSame($isMatch, $matcher->matches($request));
@@ -80,16 +80,16 @@ class RequestMatcherTest extends TestCase
public function getHostData()
{
return array(
array('.*\.example\.com', true),
array('\.example\.com$', true),
array('^.*\.example\.com$', true),
array('.*\.sensio\.com', false),
array('.*\.example\.COM', true),
array('\.example\.COM$', true),
array('^.*\.example\.COM$', true),
array('.*\.sensio\.COM', false),
);
return [
['.*\.example\.com', true],
['\.example\.com$', true],
['^.*\.example\.com$', true],
['.*\.sensio\.com', false],
['.*\.example\.COM', true],
['\.example\.COM$', true],
['^.*\.example\.COM$', true],
['.*\.sensio\.COM', false],
];
}
public function testPath()
File diff suppressed because it is too large Load Diff
+146 -92
View File
@@ -20,91 +20,67 @@ use Symfony\Component\HttpFoundation\ResponseHeaderBag;
*/
class ResponseHeaderBagTest extends TestCase
{
/**
* @dataProvider provideAllPreserveCase
*/
public function testAllPreserveCase($headers, $expected)
public function testAllPreserveCase()
{
$headers = [
'fOo' => 'BAR',
'ETag' => 'xyzzy',
'Content-MD5' => 'Q2hlY2sgSW50ZWdyaXR5IQ==',
'P3P' => 'CP="CAO PSA OUR"',
'WWW-Authenticate' => 'Basic realm="WallyWorld"',
'X-UA-Compatible' => 'IE=edge,chrome=1',
'X-XSS-Protection' => '1; mode=block',
];
$bag = new ResponseHeaderBag($headers);
$allPreservedCase = $bag->allPreserveCase();
$this->assertEquals($expected, $bag->allPreserveCase(), '->allPreserveCase() gets all input keys in original case');
}
public function provideAllPreserveCase()
{
return array(
array(
array('fOo' => 'BAR'),
array('fOo' => array('BAR'), 'Cache-Control' => array('no-cache')),
),
array(
array('ETag' => 'xyzzy'),
array('ETag' => array('xyzzy'), 'Cache-Control' => array('private, must-revalidate')),
),
array(
array('Content-MD5' => 'Q2hlY2sgSW50ZWdyaXR5IQ=='),
array('Content-MD5' => array('Q2hlY2sgSW50ZWdyaXR5IQ=='), 'Cache-Control' => array('no-cache')),
),
array(
array('P3P' => 'CP="CAO PSA OUR"'),
array('P3P' => array('CP="CAO PSA OUR"'), 'Cache-Control' => array('no-cache')),
),
array(
array('WWW-Authenticate' => 'Basic realm="WallyWorld"'),
array('WWW-Authenticate' => array('Basic realm="WallyWorld"'), 'Cache-Control' => array('no-cache')),
),
array(
array('X-UA-Compatible' => 'IE=edge,chrome=1'),
array('X-UA-Compatible' => array('IE=edge,chrome=1'), 'Cache-Control' => array('no-cache')),
),
array(
array('X-XSS-Protection' => '1; mode=block'),
array('X-XSS-Protection' => array('1; mode=block'), 'Cache-Control' => array('no-cache')),
),
);
foreach (array_keys($headers) as $headerName) {
$this->assertArrayHasKey($headerName, $allPreservedCase, '->allPreserveCase() gets all input keys in original case');
}
}
public function testCacheControlHeader()
{
$bag = new ResponseHeaderBag(array());
$this->assertEquals('no-cache', $bag->get('Cache-Control'));
$bag = new ResponseHeaderBag([]);
$this->assertEquals('no-cache, private', $bag->get('Cache-Control'));
$this->assertTrue($bag->hasCacheControlDirective('no-cache'));
$bag = new ResponseHeaderBag(array('Cache-Control' => 'public'));
$bag = new ResponseHeaderBag(['Cache-Control' => 'public']);
$this->assertEquals('public', $bag->get('Cache-Control'));
$this->assertTrue($bag->hasCacheControlDirective('public'));
$bag = new ResponseHeaderBag(array('ETag' => 'abcde'));
$this->assertEquals('private, must-revalidate', $bag->get('Cache-Control'));
$bag = new ResponseHeaderBag(['ETag' => 'abcde']);
$this->assertEquals('no-cache, private', $bag->get('Cache-Control'));
$this->assertTrue($bag->hasCacheControlDirective('private'));
$this->assertTrue($bag->hasCacheControlDirective('must-revalidate'));
$this->assertTrue($bag->hasCacheControlDirective('no-cache'));
$this->assertFalse($bag->hasCacheControlDirective('max-age'));
$bag = new ResponseHeaderBag(array('Expires' => 'Wed, 16 Feb 2011 14:17:43 GMT'));
$bag = new ResponseHeaderBag(['Expires' => 'Wed, 16 Feb 2011 14:17:43 GMT']);
$this->assertEquals('private, must-revalidate', $bag->get('Cache-Control'));
$bag = new ResponseHeaderBag(array(
$bag = new ResponseHeaderBag([
'Expires' => 'Wed, 16 Feb 2011 14:17:43 GMT',
'Cache-Control' => 'max-age=3600',
));
]);
$this->assertEquals('max-age=3600, private', $bag->get('Cache-Control'));
$bag = new ResponseHeaderBag(array('Last-Modified' => 'abcde'));
$bag = new ResponseHeaderBag(['Last-Modified' => 'abcde']);
$this->assertEquals('private, must-revalidate', $bag->get('Cache-Control'));
$bag = new ResponseHeaderBag(array('Etag' => 'abcde', 'Last-Modified' => 'abcde'));
$bag = new ResponseHeaderBag(['Etag' => 'abcde', 'Last-Modified' => 'abcde']);
$this->assertEquals('private, must-revalidate', $bag->get('Cache-Control'));
$bag = new ResponseHeaderBag(array('cache-control' => 'max-age=100'));
$bag = new ResponseHeaderBag(['cache-control' => 'max-age=100']);
$this->assertEquals('max-age=100, private', $bag->get('Cache-Control'));
$bag = new ResponseHeaderBag(array('cache-control' => 's-maxage=100'));
$bag = new ResponseHeaderBag(['cache-control' => 's-maxage=100']);
$this->assertEquals('s-maxage=100', $bag->get('Cache-Control'));
$bag = new ResponseHeaderBag(array('cache-control' => 'private, max-age=100'));
$bag = new ResponseHeaderBag(['cache-control' => 'private, max-age=100']);
$this->assertEquals('max-age=100, private', $bag->get('Cache-Control'));
$bag = new ResponseHeaderBag(array('cache-control' => 'public, max-age=100'));
$bag = new ResponseHeaderBag(['cache-control' => 'public, max-age=100']);
$this->assertEquals('max-age=100, public', $bag->get('Cache-Control'));
$bag = new ResponseHeaderBag();
@@ -112,7 +88,7 @@ class ResponseHeaderBagTest extends TestCase
$this->assertEquals('private, must-revalidate', $bag->get('Cache-Control'));
$bag = new ResponseHeaderBag();
$bag->set('Cache-Control', array('public', 'must-revalidate'));
$bag->set('Cache-Control', ['public', 'must-revalidate']);
$this->assertCount(1, $bag->get('Cache-Control', null, false));
$this->assertEquals('must-revalidate, public', $bag->get('Cache-Control'));
@@ -123,47 +99,63 @@ class ResponseHeaderBagTest extends TestCase
$this->assertEquals('must-revalidate, public', $bag->get('Cache-Control'));
}
public function testCacheControlClone()
{
$headers = ['foo' => 'bar'];
$bag1 = new ResponseHeaderBag($headers);
$bag2 = new ResponseHeaderBag($bag1->allPreserveCase());
$this->assertEquals($bag1->allPreserveCase(), $bag2->allPreserveCase());
}
public function testToStringIncludesCookieHeaders()
{
$bag = new ResponseHeaderBag(array());
$bag = new ResponseHeaderBag([]);
$bag->setCookie(new Cookie('foo', 'bar'));
$this->assertSetCookieHeader('foo=bar; path=/; httponly', $bag);
$bag->clearCookie('foo');
$this->assertSetCookieHeader('foo=deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; path=/; httponly', $bag);
$this->assertSetCookieHeader('foo=deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; Max-Age=0; path=/; httponly', $bag);
}
public function testClearCookieSecureNotHttpOnly()
{
$bag = new ResponseHeaderBag(array());
$bag = new ResponseHeaderBag([]);
$bag->clearCookie('foo', '/', null, true, false);
$this->assertSetCookieHeader('foo=deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; path=/; secure', $bag);
$this->assertSetCookieHeader('foo=deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; Max-Age=0; path=/; secure', $bag);
}
public function testClearCookieSamesite()
{
$bag = new ResponseHeaderBag([]);
$bag->clearCookie('foo', '/', null, true, false, 'none');
$this->assertSetCookieHeader('foo=deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; Max-Age=0; path=/; secure; samesite=none', $bag);
}
public function testReplace()
{
$bag = new ResponseHeaderBag(array());
$this->assertEquals('no-cache', $bag->get('Cache-Control'));
$bag = new ResponseHeaderBag([]);
$this->assertEquals('no-cache, private', $bag->get('Cache-Control'));
$this->assertTrue($bag->hasCacheControlDirective('no-cache'));
$bag->replace(array('Cache-Control' => 'public'));
$bag->replace(['Cache-Control' => 'public']);
$this->assertEquals('public', $bag->get('Cache-Control'));
$this->assertTrue($bag->hasCacheControlDirective('public'));
}
public function testReplaceWithRemove()
{
$bag = new ResponseHeaderBag(array());
$this->assertEquals('no-cache', $bag->get('Cache-Control'));
$bag = new ResponseHeaderBag([]);
$this->assertEquals('no-cache, private', $bag->get('Cache-Control'));
$this->assertTrue($bag->hasCacheControlDirective('no-cache'));
$bag->remove('Cache-Control');
$bag->replace(array());
$this->assertEquals('no-cache', $bag->get('Cache-Control'));
$bag->replace([]);
$this->assertEquals('no-cache, private', $bag->get('Cache-Control'));
$this->assertTrue($bag->hasCacheControlDirective('no-cache'));
}
@@ -176,6 +168,13 @@ class ResponseHeaderBagTest extends TestCase
$bag->setCookie(new Cookie('foo', 'bar'));
$this->assertCount(4, $bag->getCookies());
$this->assertEquals('foo=bar; path=/path/foo; domain=foo.bar; httponly', $bag->get('set-cookie'));
$this->assertEquals([
'foo=bar; path=/path/foo; domain=foo.bar; httponly',
'foo=bar; path=/path/bar; domain=foo.bar; httponly',
'foo=bar; path=/path/bar; domain=bar.foo; httponly',
'foo=bar; path=/; httponly',
], $bag->get('set-cookie', null, false));
$this->assertSetCookieHeader('foo=bar; path=/path/foo; domain=foo.bar; httponly', $bag);
$this->assertSetCookieHeader('foo=bar; path=/path/bar; domain=foo.bar; httponly', $bag);
@@ -183,6 +182,7 @@ class ResponseHeaderBagTest extends TestCase
$this->assertSetCookieHeader('foo=bar; path=/; httponly', $bag);
$cookies = $bag->getCookies(ResponseHeaderBag::COOKIES_ARRAY);
$this->assertArrayHasKey('foo', $cookies['foo.bar']['/path/foo']);
$this->assertArrayHasKey('foo', $cookies['foo.bar']['/path/bar']);
$this->assertArrayHasKey('foo', $cookies['bar.foo']['/path/bar']);
@@ -192,18 +192,23 @@ class ResponseHeaderBagTest extends TestCase
public function testRemoveCookie()
{
$bag = new ResponseHeaderBag();
$this->assertFalse($bag->has('set-cookie'));
$bag->setCookie(new Cookie('foo', 'bar', 0, '/path/foo', 'foo.bar'));
$bag->setCookie(new Cookie('bar', 'foo', 0, '/path/bar', 'foo.bar'));
$this->assertTrue($bag->has('set-cookie'));
$cookies = $bag->getCookies(ResponseHeaderBag::COOKIES_ARRAY);
$this->assertArrayHasKey('/path/foo', $cookies['foo.bar']);
$bag->removeCookie('foo', '/path/foo', 'foo.bar');
$this->assertTrue($bag->has('set-cookie'));
$cookies = $bag->getCookies(ResponseHeaderBag::COOKIES_ARRAY);
$this->assertArrayNotHasKey('/path/foo', $cookies['foo.bar']);
$bag->removeCookie('bar', '/path/bar', 'foo.bar');
$this->assertFalse($bag->has('set-cookie'));
$cookies = $bag->getCookies(ResponseHeaderBag::COOKIES_ARRAY);
$this->assertArrayNotHasKey('foo.bar', $cookies);
@@ -227,21 +232,33 @@ class ResponseHeaderBagTest extends TestCase
$this->assertFalse(isset($cookies['']['/']['bar']));
}
/**
* @expectedException \InvalidArgumentException
*/
public function testSetCookieHeader()
{
$bag = new ResponseHeaderBag();
$bag->set('set-cookie', 'foo=bar');
$this->assertEquals([new Cookie('foo', 'bar', 0, '/', null, false, false, true)], $bag->getCookies());
$bag->set('set-cookie', 'foo2=bar2', false);
$this->assertEquals([
new Cookie('foo', 'bar', 0, '/', null, false, false, true),
new Cookie('foo2', 'bar2', 0, '/', null, false, false, true),
], $bag->getCookies());
$bag->remove('set-cookie');
$this->assertEquals([], $bag->getCookies());
}
public function testGetCookiesWithInvalidArgument()
{
$this->expectException('InvalidArgumentException');
$bag = new ResponseHeaderBag();
$bag->getCookies('invalid_argument');
}
/**
* @expectedException \InvalidArgumentException
*/
public function testMakeDispositionInvalidDisposition()
{
$this->expectException('InvalidArgumentException');
$headers = new ResponseHeaderBag();
$headers->makeDisposition('invalid', 'foo.html');
@@ -267,28 +284,28 @@ class ResponseHeaderBagTest extends TestCase
(string) $headers;
$allHeaders = $headers->allPreserveCase();
$this->assertEquals(array('http://www.symfony.com'), $allHeaders['Location']);
$this->assertEquals(array('text/html'), $allHeaders['Content-type']);
$this->assertEquals(['http://www.symfony.com'], $allHeaders['Location']);
$this->assertEquals(['text/html'], $allHeaders['Content-type']);
}
public function provideMakeDisposition()
{
return array(
array('attachment', 'foo.html', 'foo.html', 'attachment; filename="foo.html"'),
array('attachment', 'foo.html', '', 'attachment; filename="foo.html"'),
array('attachment', 'foo bar.html', '', 'attachment; filename="foo bar.html"'),
array('attachment', 'foo "bar".html', '', 'attachment; filename="foo \\"bar\\".html"'),
array('attachment', 'foo%20bar.html', 'foo bar.html', 'attachment; filename="foo bar.html"; filename*=utf-8\'\'foo%2520bar.html'),
array('attachment', 'föö.html', 'foo.html', 'attachment; filename="foo.html"; filename*=utf-8\'\'f%C3%B6%C3%B6.html'),
);
return [
['attachment', 'foo.html', 'foo.html', 'attachment; filename="foo.html"'],
['attachment', 'foo.html', '', 'attachment; filename="foo.html"'],
['attachment', 'foo bar.html', '', 'attachment; filename="foo bar.html"'],
['attachment', 'foo "bar".html', '', 'attachment; filename="foo \\"bar\\".html"'],
['attachment', 'foo%20bar.html', 'foo bar.html', 'attachment; filename="foo bar.html"; filename*=utf-8\'\'foo%2520bar.html'],
['attachment', 'föö.html', 'foo.html', 'attachment; filename="foo.html"; filename*=utf-8\'\'f%C3%B6%C3%B6.html'],
];
}
/**
* @dataProvider provideMakeDispositionFail
* @expectedException \InvalidArgumentException
*/
public function testMakeDispositionFail($disposition, $filename)
{
$this->expectException('InvalidArgumentException');
$headers = new ResponseHeaderBag();
$headers->makeDisposition($disposition, $filename);
@@ -296,18 +313,55 @@ class ResponseHeaderBagTest extends TestCase
public function provideMakeDispositionFail()
{
return array(
array('attachment', 'foo%20bar.html'),
array('attachment', 'foo/bar.html'),
array('attachment', '/foo.html'),
array('attachment', 'foo\bar.html'),
array('attachment', '\foo.html'),
array('attachment', 'föö.html'),
);
return [
['attachment', 'foo%20bar.html'],
['attachment', 'foo/bar.html'],
['attachment', '/foo.html'],
['attachment', 'foo\bar.html'],
['attachment', '\foo.html'],
['attachment', 'föö.html'],
];
}
public function testDateHeaderAddedOnCreation()
{
$now = time();
$bag = new ResponseHeaderBag();
$this->assertTrue($bag->has('Date'));
$this->assertEquals($now, $bag->getDate('Date')->getTimestamp());
}
public function testDateHeaderCanBeSetOnCreation()
{
$someDate = 'Thu, 23 Mar 2017 09:15:12 GMT';
$bag = new ResponseHeaderBag(['Date' => $someDate]);
$this->assertEquals($someDate, $bag->get('Date'));
}
public function testDateHeaderWillBeRecreatedWhenRemoved()
{
$someDate = 'Thu, 23 Mar 2017 09:15:12 GMT';
$bag = new ResponseHeaderBag(['Date' => $someDate]);
$bag->remove('Date');
// a (new) Date header is still present
$this->assertTrue($bag->has('Date'));
$this->assertNotEquals($someDate, $bag->get('Date'));
}
public function testDateHeaderWillBeRecreatedWhenHeadersAreReplaced()
{
$bag = new ResponseHeaderBag();
$bag->replace([]);
$this->assertTrue($bag->has('Date'));
}
private function assertSetCookieHeader($expected, ResponseHeaderBag $actual)
{
$this->assertRegExp('#^Set-Cookie:\s+'.preg_quote($expected, '#').'$#m', str_replace("\r\n", "\n", (string) $actual));
$this->assertMatchesRegularExpression('#^Set-Cookie:\s+'.preg_quote($expected, '#').'$#m', str_replace("\r\n", "\n", (string) $actual));
}
}
+127 -81
View File
@@ -21,7 +21,7 @@ class ResponseTest extends ResponseTestCase
{
public function testCreate()
{
$response = Response::create('foo', 301, array('Foo' => 'bar'));
$response = Response::create('foo', 301, ['Foo' => 'bar']);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response);
$this->assertEquals(301, $response->getStatusCode());
@@ -33,7 +33,7 @@ class ResponseTest extends ResponseTestCase
$response = new Response();
$response = explode("\r\n", $response);
$this->assertEquals('HTTP/1.0 200 OK', $response[0]);
$this->assertEquals('Cache-Control: no-cache', $response[1]);
$this->assertEquals('Cache-Control: no-cache, private', $response[1]);
}
public function testClone()
@@ -253,10 +253,10 @@ class ResponseTest extends ResponseTestCase
public function testIsValidateable()
{
$response = new Response('', 200, array('Last-Modified' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822)));
$response = new Response('', 200, ['Last-Modified' => $this->createDateTimeOneHourAgo()->format(\DATE_RFC2822)]);
$this->assertTrue($response->isValidateable(), '->isValidateable() returns true if Last-Modified is present');
$response = new Response('', 200, array('ETag' => '"12345"'));
$response = new Response('', 200, ['ETag' => '"12345"']);
$this->assertTrue($response->isValidateable(), '->isValidateable() returns true if ETag is present');
$response = new Response();
@@ -266,7 +266,7 @@ class ResponseTest extends ResponseTestCase
public function testGetDate()
{
$oneHourAgo = $this->createDateTimeOneHourAgo();
$response = new Response('', 200, array('Date' => $oneHourAgo->format(DATE_RFC2822)));
$response = new Response('', 200, ['Date' => $oneHourAgo->format(\DATE_RFC2822)]);
$date = $response->getDate();
$this->assertEquals($oneHourAgo->getTimestamp(), $date->getTimestamp(), '->getDate() returns the Date header if present');
@@ -274,9 +274,9 @@ class ResponseTest extends ResponseTestCase
$date = $response->getDate();
$this->assertEquals(time(), $date->getTimestamp(), '->getDate() returns the current Date if no Date header present');
$response = new Response('', 200, array('Date' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822)));
$response = new Response('', 200, ['Date' => $this->createDateTimeOneHourAgo()->format(\DATE_RFC2822)]);
$now = $this->createDateTimeNow();
$response->headers->set('Date', $now->format(DATE_RFC2822));
$response->headers->set('Date', $now->format(\DATE_RFC2822));
$date = $response->getDate();
$this->assertEquals($now->getTimestamp(), $date->getTimestamp(), '->getDate() returns the date when the header has been modified');
@@ -299,13 +299,13 @@ class ResponseTest extends ResponseTestCase
$response = new Response();
$response->headers->set('Cache-Control', 'must-revalidate');
$response->headers->set('Expires', $this->createDateTimeOneHourLater()->format(DATE_RFC2822));
$response->headers->set('Expires', $this->createDateTimeOneHourLater()->format(\DATE_RFC2822));
$this->assertEquals(3600, $response->getMaxAge(), '->getMaxAge() falls back to Expires when no max-age or s-maxage directive present');
$response = new Response();
$response->headers->set('Cache-Control', 'must-revalidate');
$response->headers->set('Expires', -1);
$this->assertEquals('Sat, 01 Jan 00 00:00:00 +0000', $response->getExpires()->format(DATE_RFC822));
$this->assertEquals('Sat, 01 Jan 00 00:00:00 +0000', $response->getExpires()->format(\DATE_RFC822));
$response = new Response();
$this->assertNull($response->getMaxAge(), '->getMaxAge() returns null if no freshness information available');
@@ -364,26 +364,32 @@ class ResponseTest extends ResponseTestCase
$this->assertNull($response->headers->get('Age'), '->expire() does not set the Age when the response is expired');
$response = new Response();
$response->headers->set('Expires', date(DATE_RFC2822, time() + 600));
$response->headers->set('Expires', date(\DATE_RFC2822, time() + 600));
$response->expire();
$this->assertNull($response->headers->get('Expires'), '->expire() removes the Expires header when the response is fresh');
}
public function testNullExpireHeader()
{
$response = new Response(null, 200, ['Expires' => null]);
$this->assertNull($response->getExpires());
}
public function testGetTtl()
{
$response = new Response();
$this->assertNull($response->getTtl(), '->getTtl() returns null when no Expires or Cache-Control headers are present');
$response = new Response();
$response->headers->set('Expires', $this->createDateTimeOneHourLater()->format(DATE_RFC2822));
$response->headers->set('Expires', $this->createDateTimeOneHourLater()->format(\DATE_RFC2822));
$this->assertEquals(3600, $response->getTtl(), '->getTtl() uses the Expires header when no max-age is present');
$response = new Response();
$response->headers->set('Expires', $this->createDateTimeOneHourAgo()->format(DATE_RFC2822));
$response->headers->set('Expires', $this->createDateTimeOneHourAgo()->format(\DATE_RFC2822));
$this->assertLessThan(0, $response->getTtl(), '->getTtl() returns negative values when Expires is in past');
$response = new Response();
$response->headers->set('Expires', $response->getDate()->format(DATE_RFC2822));
$response->headers->set('Expires', $response->getDate()->format(\DATE_RFC2822));
$response->headers->set('Age', 0);
$this->assertSame(0, $response->getTtl(), '->getTtl() correctly handles zero');
@@ -414,21 +420,21 @@ class ResponseTest extends ResponseTestCase
public function testGetVary()
{
$response = new Response();
$this->assertEquals(array(), $response->getVary(), '->getVary() returns an empty array if no Vary header is present');
$this->assertEquals([], $response->getVary(), '->getVary() returns an empty array if no Vary header is present');
$response = new Response();
$response->headers->set('Vary', 'Accept-Language');
$this->assertEquals(array('Accept-Language'), $response->getVary(), '->getVary() parses a single header name value');
$this->assertEquals(['Accept-Language'], $response->getVary(), '->getVary() parses a single header name value');
$response = new Response();
$response->headers->set('Vary', 'Accept-Language User-Agent X-Foo');
$this->assertEquals(array('Accept-Language', 'User-Agent', 'X-Foo'), $response->getVary(), '->getVary() parses multiple header name values separated by spaces');
$this->assertEquals(['Accept-Language', 'User-Agent', 'X-Foo'], $response->getVary(), '->getVary() parses multiple header name values separated by spaces');
$response = new Response();
$response->headers->set('Vary', 'Accept-Language,User-Agent, X-Foo');
$this->assertEquals(array('Accept-Language', 'User-Agent', 'X-Foo'), $response->getVary(), '->getVary() parses multiple header name values separated by commas');
$this->assertEquals(['Accept-Language', 'User-Agent', 'X-Foo'], $response->getVary(), '->getVary() parses multiple header name values separated by commas');
$vary = array('Accept-Language', 'User-Agent', 'X-foo');
$vary = ['Accept-Language', 'User-Agent', 'X-foo'];
$response = new Response();
$response->headers->set('Vary', $vary);
@@ -443,24 +449,24 @@ class ResponseTest extends ResponseTestCase
{
$response = new Response();
$response->setVary('Accept-Language');
$this->assertEquals(array('Accept-Language'), $response->getVary());
$this->assertEquals(['Accept-Language'], $response->getVary());
$response->setVary('Accept-Language, User-Agent');
$this->assertEquals(array('Accept-Language', 'User-Agent'), $response->getVary(), '->setVary() replace the vary header by default');
$this->assertEquals(['Accept-Language', 'User-Agent'], $response->getVary(), '->setVary() replace the vary header by default');
$response->setVary('X-Foo', false);
$this->assertEquals(array('Accept-Language', 'User-Agent', 'X-Foo'), $response->getVary(), '->setVary() doesn\'t wipe out earlier Vary headers if replace is set to false');
$this->assertEquals(['Accept-Language', 'User-Agent', 'X-Foo'], $response->getVary(), '->setVary() doesn\'t wipe out earlier Vary headers if replace is set to false');
}
public function testDefaultContentType()
{
$headerMock = $this->getMockBuilder('Symfony\Component\HttpFoundation\ResponseHeaderBag')->setMethods(array('set'))->getMock();
$headerMock->expects($this->at(0))
$headerMock = $this->getMockBuilder('Symfony\Component\HttpFoundation\ResponseHeaderBag')->setMethods(['set'])->getMock();
$headerMock->expects($this->exactly(2))
->method('set')
->with('Content-Type', 'text/html');
$headerMock->expects($this->at(1))
->method('set')
->with('Content-Type', 'text/html; charset=UTF-8');
->withConsecutive(
['Content-Type', 'text/html'],
['Content-Type', 'text/html; charset=UTF-8']
);
$response = new Response('foo');
$response->headers = $headerMock;
@@ -532,7 +538,6 @@ class ResponseTest extends ResponseTestCase
$response->prepare($request);
$this->assertEquals('', $response->getContent());
$this->assertFalse($response->headers->has('Content-Type'));
$this->assertFalse($response->headers->has('Content-Type'));
$response->setContent('content');
$response->setStatusCode(304);
@@ -576,50 +581,56 @@ class ResponseTest extends ResponseTestCase
public function testSetCache()
{
$response = new Response();
//array('etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public')
// ['etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public']
try {
$response->setCache(array('wrong option' => 'value'));
$response->setCache(['wrong option' => 'value']);
$this->fail('->setCache() throws an InvalidArgumentException if an option is not supported');
} catch (\Exception $e) {
$this->assertInstanceOf('InvalidArgumentException', $e, '->setCache() throws an InvalidArgumentException if an option is not supported');
$this->assertContains('"wrong option"', $e->getMessage());
$this->assertStringContainsString('"wrong option"', $e->getMessage());
}
$options = array('etag' => '"whatever"');
$options = ['etag' => '"whatever"'];
$response->setCache($options);
$this->assertEquals($response->getEtag(), '"whatever"');
$this->assertEquals('"whatever"', $response->getEtag());
$now = $this->createDateTimeNow();
$options = array('last_modified' => $now);
$options = ['last_modified' => $now];
$response->setCache($options);
$this->assertEquals($response->getLastModified()->getTimestamp(), $now->getTimestamp());
$this->assertEquals($now->getTimestamp(), $response->getLastModified()->getTimestamp());
$options = array('max_age' => 100);
$options = ['max_age' => 100];
$response->setCache($options);
$this->assertEquals($response->getMaxAge(), 100);
$this->assertEquals(100, $response->getMaxAge());
$options = array('s_maxage' => 200);
$options = ['s_maxage' => 200];
$response->setCache($options);
$this->assertEquals($response->getMaxAge(), 200);
$this->assertEquals(200, $response->getMaxAge());
$this->assertTrue($response->headers->hasCacheControlDirective('public'));
$this->assertFalse($response->headers->hasCacheControlDirective('private'));
$response->setCache(array('public' => true));
$response->setCache(['public' => true]);
$this->assertTrue($response->headers->hasCacheControlDirective('public'));
$this->assertFalse($response->headers->hasCacheControlDirective('private'));
$response->setCache(array('public' => false));
$response->setCache(['public' => false]);
$this->assertFalse($response->headers->hasCacheControlDirective('public'));
$this->assertTrue($response->headers->hasCacheControlDirective('private'));
$response->setCache(array('private' => true));
$response->setCache(['private' => true]);
$this->assertFalse($response->headers->hasCacheControlDirective('public'));
$this->assertTrue($response->headers->hasCacheControlDirective('private'));
$response->setCache(array('private' => false));
$response->setCache(['private' => false]);
$this->assertTrue($response->headers->hasCacheControlDirective('public'));
$this->assertFalse($response->headers->hasCacheControlDirective('private'));
$response->setCache(['immutable' => true]);
$this->assertTrue($response->headers->hasCacheControlDirective('immutable'));
$response->setCache(['immutable' => false]);
$this->assertFalse($response->headers->hasCacheControlDirective('immutable'));
}
public function testSendContent()
@@ -629,7 +640,7 @@ class ResponseTest extends ResponseTestCase
ob_start();
$response->sendContent();
$string = ob_get_clean();
$this->assertContains('test response rendering', $string);
$this->assertStringContainsString('test response rendering', $string);
}
public function testSetPublic()
@@ -641,6 +652,22 @@ class ResponseTest extends ResponseTestCase
$this->assertFalse($response->headers->hasCacheControlDirective('private'));
}
public function testSetImmutable()
{
$response = new Response();
$response->setImmutable();
$this->assertTrue($response->headers->hasCacheControlDirective('immutable'));
}
public function testIsImmutable()
{
$response = new Response();
$response->setImmutable();
$this->assertTrue($response->isImmutable());
}
public function testSetExpires()
{
$response = new Response();
@@ -703,14 +730,14 @@ class ResponseTest extends ResponseTestCase
public function getStatusCodeFixtures()
{
return array(
array('200', null, 'OK'),
array('200', false, ''),
array('200', 'foo', 'foo'),
array('199', null, 'unknown status'),
array('199', false, ''),
array('199', 'foo', 'foo'),
);
return [
['200', null, 'OK'],
['200', false, ''],
['200', 'foo', 'foo'],
['199', null, 'unknown status'],
['199', false, ''],
['199', 'foo', 'foo'],
];
}
public function testIsInformational()
@@ -724,7 +751,7 @@ class ResponseTest extends ResponseTestCase
public function testIsRedirectRedirection()
{
foreach (array(301, 302, 303, 307) as $code) {
foreach ([301, 302, 303, 307] as $code) {
$response = new Response('', $code);
$this->assertTrue($response->isRedirection());
$this->assertTrue($response->isRedirect());
@@ -742,7 +769,7 @@ class ResponseTest extends ResponseTestCase
$this->assertFalse($response->isRedirection());
$this->assertFalse($response->isRedirect());
$response = new Response('', 301, array('Location' => '/good-uri'));
$response = new Response('', 301, ['Location' => '/good-uri']);
$this->assertFalse($response->isRedirect('/bad-uri'));
$this->assertTrue($response->isRedirect('/good-uri'));
}
@@ -758,7 +785,7 @@ class ResponseTest extends ResponseTestCase
public function testIsEmpty()
{
foreach (array(204, 304) as $code) {
foreach ([204, 304] as $code) {
$response = new Response('', $code);
$this->assertTrue($response->isEmpty());
}
@@ -807,7 +834,7 @@ class ResponseTest extends ResponseTestCase
public function testSetEtag()
{
$response = new Response('', 200, array('ETag' => '"12345"'));
$response = new Response('', 200, ['ETag' => '"12345"']);
$response->setEtag();
$this->assertNull($response->headers->get('Etag'), '->setEtag() removes Etags when call with null');
@@ -824,11 +851,11 @@ class ResponseTest extends ResponseTestCase
}
/**
* @expectedException \UnexpectedValueException
* @dataProvider invalidContentProvider
*/
public function testSetContentInvalid($content)
{
$this->expectException('UnexpectedValueException');
$response = new Response();
$response->setContent($content);
}
@@ -837,7 +864,7 @@ class ResponseTest extends ResponseTestCase
{
$response = new Response();
$setters = array(
$setters = [
'setProtocolVersion' => '1.0',
'setCharset' => 'UTF-8',
'setPublic' => null,
@@ -848,29 +875,39 @@ class ResponseTest extends ResponseTestCase
'setSharedMaxAge' => 1,
'setTtl' => 1,
'setClientTtl' => 1,
);
];
foreach ($setters as $setter => $arg) {
$this->assertEquals($response, $response->{$setter}($arg));
}
}
public function testNoDeprecationsAreTriggered()
{
new DefaultResponse();
$this->getMockBuilder(Response::class)->getMock();
// we just need to ensure that subclasses of Response can be created without any deprecations
// being triggered if the subclass does not override any final methods
$this->addToAssertionCount(1);
}
public function validContentProvider()
{
return array(
'obj' => array(new StringableObject()),
'string' => array('Foo'),
'int' => array(2),
);
return [
'obj' => [new StringableObject()],
'string' => ['Foo'],
'int' => [2],
];
}
public function invalidContentProvider()
{
return array(
'obj' => array(new \stdClass()),
'array' => array(array()),
'bool' => array(true, '1'),
);
return [
'obj' => [new \stdClass()],
'array' => [[]],
'bool' => [true, '1'],
];
}
protected function createDateTimeOneHourAgo()
@@ -896,11 +933,11 @@ class ResponseTest extends ResponseTestCase
}
/**
* @see http://github.com/zendframework/zend-diactoros for the canonical source repository
* @see http://github.com/zendframework/zend-diactoros for the canonical source repository
*
* @author Fábio Pacheco
* @author Fábio Pacheco
* @copyright Copyright (c) 2015-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License
* @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License
*/
public function ianaCodesReasonPhrasesProvider()
{
@@ -910,19 +947,24 @@ class ResponseTest extends ResponseTestCase
$ianaHttpStatusCodes = new \DOMDocument();
libxml_set_streams_context(stream_context_create(array(
'http' => array(
$context = stream_context_create([
'http' => [
'method' => 'GET',
'timeout' => 30,
),
)));
'user_agent' => __METHOD__,
],
]);
$ianaHttpStatusCodes->load('https://www.iana.org/assignments/http-status-codes/http-status-codes.xml');
if (!$rawStatusCodes = file_get_contents('https://www.iana.org/assignments/http-status-codes/http-status-codes.xml', false, $context)) {
$this->markTestSkipped('The IANA server is throttling the list of status codes');
}
$ianaHttpStatusCodes->loadXML($rawStatusCodes);
if (!$ianaHttpStatusCodes->relaxNGValidate(__DIR__.'/schema/http-status-codes.rng')) {
self::fail('Invalid IANA\'s HTTP status code list.');
}
$ianaCodesReasonPhrases = array();
$ianaCodesReasonPhrases = [];
$xpath = new \DOMXPath($ianaHttpStatusCodes);
$xpath->registerNamespace('ns', 'http://www.iana.org/assignments');
@@ -932,16 +974,16 @@ class ResponseTest extends ResponseTestCase
$value = $xpath->query('.//ns:value', $record)->item(0)->nodeValue;
$description = $xpath->query('.//ns:description', $record)->item(0)->nodeValue;
if (\in_array($description, array('Unassigned', '(Unused)'), true)) {
if (\in_array($description, ['Unassigned', '(Unused)'], true)) {
continue;
}
if (preg_match('/^([0-9]+)\s*\-\s*([0-9]+)$/', $value, $matches)) {
for ($value = $matches[1]; $value <= $matches[2]; ++$value) {
$ianaCodesReasonPhrases[] = array($value, $description);
$ianaCodesReasonPhrases[] = [$value, $description];
}
} else {
$ianaCodesReasonPhrases[] = array($value, $description);
$ianaCodesReasonPhrases[] = [$value, $description];
}
}
@@ -964,3 +1006,7 @@ class StringableObject
return 'Foo';
}
}
class DefaultResponse extends Response
{
}
+33 -33
View File
@@ -23,7 +23,7 @@ class ServerBagTest extends TestCase
{
public function testShouldExtractHeadersFromServerArray()
{
$server = array(
$server = [
'SOME_SERVER_VARIABLE' => 'value',
'SOME_SERVER_VARIABLE2' => 'value',
'ROOT' => 'value',
@@ -32,45 +32,45 @@ class ServerBagTest extends TestCase
'HTTP_ETAG' => 'asdf',
'PHP_AUTH_USER' => 'foo',
'PHP_AUTH_PW' => 'bar',
);
];
$bag = new ServerBag($server);
$this->assertEquals(array(
$this->assertEquals([
'CONTENT_TYPE' => 'text/html',
'CONTENT_LENGTH' => '0',
'ETAG' => 'asdf',
'AUTHORIZATION' => 'Basic '.base64_encode('foo:bar'),
'PHP_AUTH_USER' => 'foo',
'PHP_AUTH_PW' => 'bar',
), $bag->getHeaders());
], $bag->getHeaders());
}
public function testHttpPasswordIsOptional()
{
$bag = new ServerBag(array('PHP_AUTH_USER' => 'foo'));
$bag = new ServerBag(['PHP_AUTH_USER' => 'foo']);
$this->assertEquals(array(
$this->assertEquals([
'AUTHORIZATION' => 'Basic '.base64_encode('foo:'),
'PHP_AUTH_USER' => 'foo',
'PHP_AUTH_PW' => '',
), $bag->getHeaders());
], $bag->getHeaders());
}
public function testHttpBasicAuthWithPhpCgi()
{
$bag = new ServerBag(array('HTTP_AUTHORIZATION' => 'Basic '.base64_encode('foo:bar')));
$bag = new ServerBag(['HTTP_AUTHORIZATION' => 'Basic '.base64_encode('foo:bar')]);
$this->assertEquals(array(
$this->assertEquals([
'AUTHORIZATION' => 'Basic '.base64_encode('foo:bar'),
'PHP_AUTH_USER' => 'foo',
'PHP_AUTH_PW' => 'bar',
), $bag->getHeaders());
], $bag->getHeaders());
}
public function testHttpBasicAuthWithPhpCgiBogus()
{
$bag = new ServerBag(array('HTTP_AUTHORIZATION' => 'Basic_'.base64_encode('foo:bar')));
$bag = new ServerBag(['HTTP_AUTHORIZATION' => 'Basic_'.base64_encode('foo:bar')]);
// Username and passwords should not be set as the header is bogus
$headers = $bag->getHeaders();
@@ -80,41 +80,41 @@ class ServerBagTest extends TestCase
public function testHttpBasicAuthWithPhpCgiRedirect()
{
$bag = new ServerBag(array('REDIRECT_HTTP_AUTHORIZATION' => 'Basic '.base64_encode('username:pass:word')));
$bag = new ServerBag(['REDIRECT_HTTP_AUTHORIZATION' => 'Basic '.base64_encode('username:pass:word')]);
$this->assertEquals(array(
$this->assertEquals([
'AUTHORIZATION' => 'Basic '.base64_encode('username:pass:word'),
'PHP_AUTH_USER' => 'username',
'PHP_AUTH_PW' => 'pass:word',
), $bag->getHeaders());
], $bag->getHeaders());
}
public function testHttpBasicAuthWithPhpCgiEmptyPassword()
{
$bag = new ServerBag(array('HTTP_AUTHORIZATION' => 'Basic '.base64_encode('foo:')));
$bag = new ServerBag(['HTTP_AUTHORIZATION' => 'Basic '.base64_encode('foo:')]);
$this->assertEquals(array(
$this->assertEquals([
'AUTHORIZATION' => 'Basic '.base64_encode('foo:'),
'PHP_AUTH_USER' => 'foo',
'PHP_AUTH_PW' => '',
), $bag->getHeaders());
], $bag->getHeaders());
}
public function testHttpDigestAuthWithPhpCgi()
{
$digest = 'Digest username="foo", realm="acme", nonce="'.md5('secret').'", uri="/protected, qop="auth"';
$bag = new ServerBag(array('HTTP_AUTHORIZATION' => $digest));
$bag = new ServerBag(['HTTP_AUTHORIZATION' => $digest]);
$this->assertEquals(array(
$this->assertEquals([
'AUTHORIZATION' => $digest,
'PHP_AUTH_DIGEST' => $digest,
), $bag->getHeaders());
], $bag->getHeaders());
}
public function testHttpDigestAuthWithPhpCgiBogus()
{
$digest = 'Digest_username="foo", realm="acme", nonce="'.md5('secret').'", uri="/protected, qop="auth"';
$bag = new ServerBag(array('HTTP_AUTHORIZATION' => $digest));
$bag = new ServerBag(['HTTP_AUTHORIZATION' => $digest]);
// Username and passwords should not be set as the header is bogus
$headers = $bag->getHeaders();
@@ -125,32 +125,32 @@ class ServerBagTest extends TestCase
public function testHttpDigestAuthWithPhpCgiRedirect()
{
$digest = 'Digest username="foo", realm="acme", nonce="'.md5('secret').'", uri="/protected, qop="auth"';
$bag = new ServerBag(array('REDIRECT_HTTP_AUTHORIZATION' => $digest));
$bag = new ServerBag(['REDIRECT_HTTP_AUTHORIZATION' => $digest]);
$this->assertEquals(array(
$this->assertEquals([
'AUTHORIZATION' => $digest,
'PHP_AUTH_DIGEST' => $digest,
), $bag->getHeaders());
], $bag->getHeaders());
}
public function testOAuthBearerAuth()
{
$headerContent = 'Bearer L-yLEOr9zhmUYRkzN1jwwxwQ-PBNiKDc8dgfB4hTfvo';
$bag = new ServerBag(array('HTTP_AUTHORIZATION' => $headerContent));
$bag = new ServerBag(['HTTP_AUTHORIZATION' => $headerContent]);
$this->assertEquals(array(
$this->assertEquals([
'AUTHORIZATION' => $headerContent,
), $bag->getHeaders());
], $bag->getHeaders());
}
public function testOAuthBearerAuthWithRedirect()
{
$headerContent = 'Bearer L-yLEOr9zhmUYRkzN1jwwxwQ-PBNiKDc8dgfB4hTfvo';
$bag = new ServerBag(array('REDIRECT_HTTP_AUTHORIZATION' => $headerContent));
$bag = new ServerBag(['REDIRECT_HTTP_AUTHORIZATION' => $headerContent]);
$this->assertEquals(array(
$this->assertEquals([
'AUTHORIZATION' => $headerContent,
), $bag->getHeaders());
], $bag->getHeaders());
}
/**
@@ -159,12 +159,12 @@ class ServerBagTest extends TestCase
public function testItDoesNotOverwriteTheAuthorizationHeaderIfItIsAlreadySet()
{
$headerContent = 'Bearer L-yLEOr9zhmUYRkzN1jwwxwQ-PBNiKDc8dgfB4hTfvo';
$bag = new ServerBag(array('PHP_AUTH_USER' => 'foo', 'HTTP_AUTHORIZATION' => $headerContent));
$bag = new ServerBag(['PHP_AUTH_USER' => 'foo', 'HTTP_AUTHORIZATION' => $headerContent]);
$this->assertEquals(array(
$this->assertEquals([
'AUTHORIZATION' => $headerContent,
'PHP_AUTH_USER' => 'foo',
'PHP_AUTH_PW' => '',
), $bag->getHeaders());
], $bag->getHeaders());
}
}
@@ -21,7 +21,7 @@ use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
*/
class AttributeBagTest extends TestCase
{
private $array = array();
private $array = [];
/**
* @var AttributeBag
@@ -30,21 +30,21 @@ class AttributeBagTest extends TestCase
protected function setUp()
{
$this->array = array(
$this->array = [
'hello' => 'world',
'always' => 'be happy',
'user.login' => 'drak',
'csrf.token' => array(
'csrf.token' => [
'a' => '1234',
'b' => '4321',
),
'category' => array(
'fishing' => array(
],
'category' => [
'fishing' => [
'first' => 'cod',
'second' => 'sole',
),
),
);
],
],
];
$this->bag = new AttributeBag('_sf2');
$this->bag->initialize($this->array);
}
@@ -52,7 +52,7 @@ class AttributeBagTest extends TestCase
protected function tearDown()
{
$this->bag = null;
$this->array = array();
$this->array = [];
}
public function testInitialize()
@@ -60,7 +60,7 @@ class AttributeBagTest extends TestCase
$bag = new AttributeBag();
$bag->initialize($this->array);
$this->assertEquals($this->array, $bag->all());
$array = array('should' => 'change');
$array = ['should' => 'change'];
$bag->initialize($array);
$this->assertEquals($array, $bag->all());
}
@@ -122,7 +122,7 @@ class AttributeBagTest extends TestCase
public function testReplace()
{
$array = array();
$array = [];
$array['name'] = 'jack';
$array['foo.bar'] = 'beep';
$this->bag->replace($array);
@@ -150,22 +150,22 @@ class AttributeBagTest extends TestCase
public function testClear()
{
$this->bag->clear();
$this->assertEquals(array(), $this->bag->all());
$this->assertEquals([], $this->bag->all());
}
public function attributesProvider()
{
return array(
array('hello', 'world', true),
array('always', 'be happy', true),
array('user.login', 'drak', true),
array('csrf.token', array('a' => '1234', 'b' => '4321'), true),
array('category', array('fishing' => array('first' => 'cod', 'second' => 'sole')), true),
array('user2.login', null, false),
array('never', null, false),
array('bye', null, false),
array('bye/for/now', null, false),
);
return [
['hello', 'world', true],
['always', 'be happy', true],
['user.login', 'drak', true],
['csrf.token', ['a' => '1234', 'b' => '4321'], true],
['category', ['fishing' => ['first' => 'cod', 'second' => 'sole']], true],
['user2.login', null, false],
['never', null, false],
['bye', null, false],
['bye/for/now', null, false],
];
}
public function testGetIterator()
@@ -21,7 +21,7 @@ use Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag;
*/
class NamespacedAttributeBagTest extends TestCase
{
private $array = array();
private $array = [];
/**
* @var NamespacedAttributeBag
@@ -30,21 +30,21 @@ class NamespacedAttributeBagTest extends TestCase
protected function setUp()
{
$this->array = array(
$this->array = [
'hello' => 'world',
'always' => 'be happy',
'user.login' => 'drak',
'csrf.token' => array(
'csrf.token' => [
'a' => '1234',
'b' => '4321',
),
'category' => array(
'fishing' => array(
],
'category' => [
'fishing' => [
'first' => 'cod',
'second' => 'sole',
),
),
);
],
],
];
$this->bag = new NamespacedAttributeBag('_sf2', '/');
$this->bag->initialize($this->array);
}
@@ -52,7 +52,7 @@ class NamespacedAttributeBagTest extends TestCase
protected function tearDown()
{
$this->bag = null;
$this->array = array();
$this->array = [];
}
public function testInitialize()
@@ -60,7 +60,7 @@ class NamespacedAttributeBagTest extends TestCase
$bag = new NamespacedAttributeBag();
$bag->initialize($this->array);
$this->assertEquals($this->array, $this->bag->all());
$array = array('should' => 'not stick');
$array = ['should' => 'not stick'];
$bag->initialize($array);
// should have remained the same
@@ -139,7 +139,7 @@ class NamespacedAttributeBagTest extends TestCase
public function testReplace()
{
$array = array();
$array = [];
$array['name'] = 'jack';
$array['foo.bar'] = 'beep';
$this->bag->replace($array);
@@ -177,28 +177,28 @@ class NamespacedAttributeBagTest extends TestCase
public function testClear()
{
$this->bag->clear();
$this->assertEquals(array(), $this->bag->all());
$this->assertEquals([], $this->bag->all());
}
public function attributesProvider()
{
return array(
array('hello', 'world', true),
array('always', 'be happy', true),
array('user.login', 'drak', true),
array('csrf.token', array('a' => '1234', 'b' => '4321'), true),
array('csrf.token/a', '1234', true),
array('csrf.token/b', '4321', true),
array('category', array('fishing' => array('first' => 'cod', 'second' => 'sole')), true),
array('category/fishing', array('first' => 'cod', 'second' => 'sole'), true),
array('category/fishing/missing/first', null, false),
array('category/fishing/first', 'cod', true),
array('category/fishing/second', 'sole', true),
array('category/fishing/missing/second', null, false),
array('user2.login', null, false),
array('never', null, false),
array('bye', null, false),
array('bye/for/now', null, false),
);
return [
['hello', 'world', true],
['always', 'be happy', true],
['user.login', 'drak', true],
['csrf.token', ['a' => '1234', 'b' => '4321'], true],
['csrf.token/a', '1234', true],
['csrf.token/b', '4321', true],
['category', ['fishing' => ['first' => 'cod', 'second' => 'sole']], true],
['category/fishing', ['first' => 'cod', 'second' => 'sole'], true],
['category/fishing/missing/first', null, false],
['category/fishing/first', 'cod', true],
['category/fishing/second', 'sole', true],
['category/fishing/missing/second', null, false],
['user2.login', null, false],
['never', null, false],
['bye', null, false],
['bye/for/now', null, false],
];
}
}
@@ -26,13 +26,13 @@ class AutoExpireFlashBagTest extends TestCase
*/
private $bag;
protected $array = array();
protected $array = [];
protected function setUp()
{
parent::setUp();
$this->bag = new FlashBag();
$this->array = array('new' => array('notice' => array('A previous flash message')));
$this->array = ['new' => ['notice' => ['A previous flash message']]];
$this->bag->initialize($this->array);
}
@@ -45,21 +45,21 @@ class AutoExpireFlashBagTest extends TestCase
public function testInitialize()
{
$bag = new FlashBag();
$array = array('new' => array('notice' => array('A previous flash message')));
$array = ['new' => ['notice' => ['A previous flash message']]];
$bag->initialize($array);
$this->assertEquals(array('A previous flash message'), $bag->peek('notice'));
$array = array('new' => array(
'notice' => array('Something else'),
'error' => array('a'),
));
$this->assertEquals(['A previous flash message'], $bag->peek('notice'));
$array = ['new' => [
'notice' => ['Something else'],
'error' => ['a'],
]];
$bag->initialize($array);
$this->assertEquals(array('Something else'), $bag->peek('notice'));
$this->assertEquals(array('a'), $bag->peek('error'));
$this->assertEquals(['Something else'], $bag->peek('notice'));
$this->assertEquals(['a'], $bag->peek('error'));
}
public function testGetStorageKey()
{
$this->assertEquals('_sf2_flashes', $this->bag->getStorageKey());
$this->assertEquals('_symfony_flashes', $this->bag->getStorageKey());
$attributeBag = new FlashBag('test');
$this->assertEquals('test', $attributeBag->getStorageKey());
}
@@ -73,16 +73,16 @@ class AutoExpireFlashBagTest extends TestCase
public function testPeek()
{
$this->assertEquals(array(), $this->bag->peek('non_existing'));
$this->assertEquals(array('default'), $this->bag->peek('non_existing', array('default')));
$this->assertEquals(array('A previous flash message'), $this->bag->peek('notice'));
$this->assertEquals(array('A previous flash message'), $this->bag->peek('notice'));
$this->assertEquals([], $this->bag->peek('non_existing'));
$this->assertEquals(['default'], $this->bag->peek('non_existing', ['default']));
$this->assertEquals(['A previous flash message'], $this->bag->peek('notice'));
$this->assertEquals(['A previous flash message'], $this->bag->peek('notice'));
}
public function testSet()
{
$this->bag->set('notice', 'Foo');
$this->assertEquals(array('A previous flash message'), $this->bag->peek('notice'));
$this->assertEquals(['A previous flash message'], $this->bag->peek('notice'));
}
public function testHas()
@@ -93,43 +93,43 @@ class AutoExpireFlashBagTest extends TestCase
public function testKeys()
{
$this->assertEquals(array('notice'), $this->bag->keys());
$this->assertEquals(['notice'], $this->bag->keys());
}
public function testPeekAll()
{
$array = array(
'new' => array(
$array = [
'new' => [
'notice' => 'Foo',
'error' => 'Bar',
),
);
],
];
$this->bag->initialize($array);
$this->assertEquals(array(
$this->assertEquals([
'notice' => 'Foo',
'error' => 'Bar',
), $this->bag->peekAll()
], $this->bag->peekAll()
);
$this->assertEquals(array(
$this->assertEquals([
'notice' => 'Foo',
'error' => 'Bar',
), $this->bag->peekAll()
], $this->bag->peekAll()
);
}
public function testGet()
{
$this->assertEquals(array(), $this->bag->get('non_existing'));
$this->assertEquals(array('default'), $this->bag->get('non_existing', array('default')));
$this->assertEquals(array('A previous flash message'), $this->bag->get('notice'));
$this->assertEquals(array(), $this->bag->get('notice'));
$this->assertEquals([], $this->bag->get('non_existing'));
$this->assertEquals(['default'], $this->bag->get('non_existing', ['default']));
$this->assertEquals(['A previous flash message'], $this->bag->get('notice'));
$this->assertEquals([], $this->bag->get('notice'));
}
public function testSetAll()
{
$this->bag->setAll(array('a' => 'first', 'b' => 'second'));
$this->bag->setAll(['a' => 'first', 'b' => 'second']);
$this->assertFalse($this->bag->has('a'));
$this->assertFalse($this->bag->has('b'));
}
@@ -138,17 +138,17 @@ class AutoExpireFlashBagTest extends TestCase
{
$this->bag->set('notice', 'Foo');
$this->bag->set('error', 'Bar');
$this->assertEquals(array(
'notice' => array('A previous flash message'),
), $this->bag->all()
$this->assertEquals([
'notice' => ['A previous flash message'],
], $this->bag->all()
);
$this->assertEquals(array(), $this->bag->all());
$this->assertEquals([], $this->bag->all());
}
public function testClear()
{
$this->assertEquals(array('notice' => array('A previous flash message')), $this->bag->clear());
$this->assertEquals(['notice' => ['A previous flash message']], $this->bag->clear());
}
public function testDoNotRemoveTheNewFlashesWhenDisplayingTheExistingOnes()
@@ -156,6 +156,6 @@ class AutoExpireFlashBagTest extends TestCase
$this->bag->add('success', 'Something');
$this->bag->all();
$this->assertEquals(array('new' => array('success' => array('Something')), 'display' => array()), $this->array);
$this->assertEquals(['new' => ['success' => ['Something']], 'display' => []], $this->array);
}
}
@@ -26,13 +26,13 @@ class FlashBagTest extends TestCase
*/
private $bag;
protected $array = array();
protected $array = [];
protected function setUp()
{
parent::setUp();
$this->bag = new FlashBag();
$this->array = array('notice' => array('A previous flash message'));
$this->array = ['notice' => ['A previous flash message']];
$this->bag->initialize($this->array);
}
@@ -47,14 +47,14 @@ class FlashBagTest extends TestCase
$bag = new FlashBag();
$bag->initialize($this->array);
$this->assertEquals($this->array, $bag->peekAll());
$array = array('should' => array('change'));
$array = ['should' => ['change']];
$bag->initialize($array);
$this->assertEquals($array, $bag->peekAll());
}
public function testGetStorageKey()
{
$this->assertEquals('_sf2_flashes', $this->bag->getStorageKey());
$this->assertEquals('_symfony_flashes', $this->bag->getStorageKey());
$attributeBag = new FlashBag('test');
$this->assertEquals('test', $attributeBag->getStorageKey());
}
@@ -68,49 +68,49 @@ class FlashBagTest extends TestCase
public function testPeek()
{
$this->assertEquals(array(), $this->bag->peek('non_existing'));
$this->assertEquals(array('default'), $this->bag->peek('not_existing', array('default')));
$this->assertEquals(array('A previous flash message'), $this->bag->peek('notice'));
$this->assertEquals(array('A previous flash message'), $this->bag->peek('notice'));
$this->assertEquals([], $this->bag->peek('non_existing'));
$this->assertEquals(['default'], $this->bag->peek('not_existing', ['default']));
$this->assertEquals(['A previous flash message'], $this->bag->peek('notice'));
$this->assertEquals(['A previous flash message'], $this->bag->peek('notice'));
}
public function testAdd()
{
$tab = array('bar' => 'baz');
$tab = ['bar' => 'baz'];
$this->bag->add('string_message', 'lorem');
$this->bag->add('object_message', new \stdClass());
$this->bag->add('array_message', $tab);
$this->assertEquals(array('lorem'), $this->bag->get('string_message'));
$this->assertEquals(array(new \stdClass()), $this->bag->get('object_message'));
$this->assertEquals(array($tab), $this->bag->get('array_message'));
$this->assertEquals(['lorem'], $this->bag->get('string_message'));
$this->assertEquals([new \stdClass()], $this->bag->get('object_message'));
$this->assertEquals([$tab], $this->bag->get('array_message'));
}
public function testGet()
{
$this->assertEquals(array(), $this->bag->get('non_existing'));
$this->assertEquals(array('default'), $this->bag->get('not_existing', array('default')));
$this->assertEquals(array('A previous flash message'), $this->bag->get('notice'));
$this->assertEquals(array(), $this->bag->get('notice'));
$this->assertEquals([], $this->bag->get('non_existing'));
$this->assertEquals(['default'], $this->bag->get('not_existing', ['default']));
$this->assertEquals(['A previous flash message'], $this->bag->get('notice'));
$this->assertEquals([], $this->bag->get('notice'));
}
public function testAll()
{
$this->bag->set('notice', 'Foo');
$this->bag->set('error', 'Bar');
$this->assertEquals(array(
'notice' => array('Foo'),
'error' => array('Bar'), ), $this->bag->all()
$this->assertEquals([
'notice' => ['Foo'],
'error' => ['Bar'], ], $this->bag->all()
);
$this->assertEquals(array(), $this->bag->all());
$this->assertEquals([], $this->bag->all());
}
public function testSet()
{
$this->bag->set('notice', 'Foo');
$this->bag->set('notice', 'Bar');
$this->assertEquals(array('Bar'), $this->bag->peek('notice'));
$this->assertEquals(['Bar'], $this->bag->peek('notice'));
}
public function testHas()
@@ -121,7 +121,7 @@ class FlashBagTest extends TestCase
public function testKeys()
{
$this->assertEquals(array('notice'), $this->bag->keys());
$this->assertEquals(['notice'], $this->bag->keys());
}
public function testSetAll()
@@ -130,48 +130,28 @@ class FlashBagTest extends TestCase
$this->bag->add('another_flash', 'Bar');
$this->assertTrue($this->bag->has('one_flash'));
$this->assertTrue($this->bag->has('another_flash'));
$this->bag->setAll(array('unique_flash' => 'FooBar'));
$this->bag->setAll(['unique_flash' => 'FooBar']);
$this->assertFalse($this->bag->has('one_flash'));
$this->assertFalse($this->bag->has('another_flash'));
$this->assertSame(array('unique_flash' => 'FooBar'), $this->bag->all());
$this->assertSame(array(), $this->bag->all());
$this->assertSame(['unique_flash' => 'FooBar'], $this->bag->all());
$this->assertSame([], $this->bag->all());
}
public function testPeekAll()
{
$this->bag->set('notice', 'Foo');
$this->bag->set('error', 'Bar');
$this->assertEquals(array(
'notice' => array('Foo'),
'error' => array('Bar'),
), $this->bag->peekAll()
$this->assertEquals([
'notice' => ['Foo'],
'error' => ['Bar'],
], $this->bag->peekAll()
);
$this->assertTrue($this->bag->has('notice'));
$this->assertTrue($this->bag->has('error'));
$this->assertEquals(array(
'notice' => array('Foo'),
'error' => array('Bar'),
), $this->bag->peekAll()
$this->assertEquals([
'notice' => ['Foo'],
'error' => ['Bar'],
], $this->bag->peekAll()
);
}
/**
* @group legacy
*/
public function testLegacyGetIterator()
{
$flashes = array('hello' => 'world', 'beep' => 'boop', 'notice' => 'nope');
foreach ($flashes as $key => $val) {
$this->bag->set($key, $val);
}
$i = 0;
foreach ($this->bag as $key => $val) {
$this->assertEquals(array($flashes[$key]), $val);
++$i;
}
$this->assertEquals(\count($flashes), $i);
$this->assertCount(0, $this->bag->all());
}
}
+56 -13
View File
@@ -15,6 +15,7 @@ use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionBagProxy;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
/**
@@ -127,10 +128,10 @@ class SessionTest extends TestCase
public function testReplace()
{
$this->session->replace(array('happiness' => 'be good', 'symfony' => 'awesome'));
$this->assertEquals(array('happiness' => 'be good', 'symfony' => 'awesome'), $this->session->all());
$this->session->replace(array());
$this->assertEquals(array(), $this->session->all());
$this->session->replace(['happiness' => 'be good', 'symfony' => 'awesome']);
$this->assertEquals(['happiness' => 'be good', 'symfony' => 'awesome'], $this->session->all());
$this->session->replace([]);
$this->assertEquals([], $this->session->all());
}
/**
@@ -150,16 +151,16 @@ class SessionTest extends TestCase
$this->session->set('hi', 'fabien');
$this->session->set($key, $value);
$this->session->clear();
$this->assertEquals(array(), $this->session->all());
$this->assertEquals([], $this->session->all());
}
public function setProvider()
{
return array(
array('foo', 'bar', array('foo' => 'bar')),
array('foo.bar', 'too much beer', array('foo.bar' => 'too much beer')),
array('great', 'symfony is great', array('great' => 'symfony is great')),
);
return [
['foo', 'bar', ['foo' => 'bar']],
['foo.bar', 'too much beer', ['foo.bar' => 'too much beer']],
['great', 'symfony is great', ['great' => 'symfony is great']],
];
}
/**
@@ -170,14 +171,14 @@ class SessionTest extends TestCase
$this->session->set('hi.world', 'have a nice day');
$this->session->set($key, $value);
$this->session->remove($key);
$this->assertEquals(array('hi.world' => 'have a nice day'), $this->session->all());
$this->assertEquals(['hi.world' => 'have a nice day'], $this->session->all());
}
public function testInvalidate()
{
$this->session->set('invalidate', 123);
$this->session->invalidate();
$this->assertEquals(array(), $this->session->all());
$this->assertEquals([], $this->session->all());
}
public function testMigrate()
@@ -216,7 +217,7 @@ class SessionTest extends TestCase
public function testGetIterator()
{
$attributes = array('hello' => 'world', 'symfony' => 'rocks');
$attributes = ['hello' => 'world', 'symfony' => 'rocks'];
foreach ($attributes as $key => $val) {
$this->session->set($key, $val);
}
@@ -242,4 +243,46 @@ class SessionTest extends TestCase
{
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\MetadataBag', $this->session->getMetadataBag());
}
public function testIsEmpty()
{
$this->assertTrue($this->session->isEmpty());
$this->session->set('hello', 'world');
$this->assertFalse($this->session->isEmpty());
$this->session->remove('hello');
$this->assertTrue($this->session->isEmpty());
$flash = $this->session->getFlashBag();
$flash->set('hello', 'world');
$this->assertFalse($this->session->isEmpty());
$flash->get('hello');
$this->assertTrue($this->session->isEmpty());
}
public function testGetBagWithBagImplementingGetBag()
{
$bag = new AttributeBag();
$bag->setName('foo');
$storage = new MockArraySessionStorage();
$storage->registerBag($bag);
$this->assertSame($bag, (new Session($storage))->getBag('foo'));
}
public function testGetBagWithBagNotImplementingGetBag()
{
$data = [];
$bag = new AttributeBag();
$bag->setName('foo');
$storage = new MockArraySessionStorage();
$storage->registerBag(new SessionBagProxy($bag, $data, $usageIndex));
$this->assertSame($bag, (new Session($storage))->getBag('foo'));
}
}
@@ -1,114 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\LegacyPdoSessionHandler;
/**
* @group legacy
* @group time-sensitive
* @requires extension pdo_sqlite
*/
class LegacyPdoSessionHandlerTest extends TestCase
{
private $pdo;
protected function setUp()
{
parent::setUp();
$this->pdo = new \PDO('sqlite::memory:');
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$sql = 'CREATE TABLE sessions (sess_id VARCHAR(128) PRIMARY KEY, sess_data TEXT, sess_time INTEGER)';
$this->pdo->exec($sql);
}
public function testIncompleteOptions()
{
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('InvalidArgumentException');
$storage = new LegacyPdoSessionHandler($this->pdo, array());
}
public function testWrongPdoErrMode()
{
$pdo = new \PDO('sqlite::memory:');
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_SILENT);
$pdo->exec('CREATE TABLE sessions (sess_id VARCHAR(128) PRIMARY KEY, sess_data TEXT, sess_time INTEGER)');
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('InvalidArgumentException');
$storage = new LegacyPdoSessionHandler($pdo, array('db_table' => 'sessions'));
}
public function testWrongTableOptionsWrite()
{
$storage = new LegacyPdoSessionHandler($this->pdo, array('db_table' => 'bad_name'));
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('RuntimeException');
$storage->write('foo', 'bar');
}
public function testWrongTableOptionsRead()
{
$storage = new LegacyPdoSessionHandler($this->pdo, array('db_table' => 'bad_name'));
$this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('RuntimeException');
$storage->read('foo');
}
public function testWriteRead()
{
$storage = new LegacyPdoSessionHandler($this->pdo, array('db_table' => 'sessions'));
$storage->write('foo', 'bar');
$this->assertEquals('bar', $storage->read('foo'), 'written value can be read back correctly');
}
public function testMultipleInstances()
{
$storage1 = new LegacyPdoSessionHandler($this->pdo, array('db_table' => 'sessions'));
$storage1->write('foo', 'bar');
$storage2 = new LegacyPdoSessionHandler($this->pdo, array('db_table' => 'sessions'));
$this->assertEquals('bar', $storage2->read('foo'), 'values persist between instances');
}
public function testSessionDestroy()
{
$storage = new LegacyPdoSessionHandler($this->pdo, array('db_table' => 'sessions'));
$storage->write('foo', 'bar');
$this->assertCount(1, $this->pdo->query('SELECT * FROM sessions')->fetchAll());
$storage->destroy('foo');
$this->assertCount(0, $this->pdo->query('SELECT * FROM sessions')->fetchAll());
}
public function testSessionGC()
{
$storage = new LegacyPdoSessionHandler($this->pdo, array('db_table' => 'sessions'));
$storage->write('foo', 'bar');
$storage->write('baz', 'bar');
$this->assertCount(2, $this->pdo->query('SELECT * FROM sessions')->fetchAll());
$storage->gc(-1);
$this->assertCount(0, $this->pdo->query('SELECT * FROM sessions')->fetchAll());
}
public function testGetConnection()
{
$storage = new LegacyPdoSessionHandler($this->pdo, array('db_table' => 'sessions'), array());
$method = new \ReflectionMethod($storage, 'getConnection');
$method->setAccessible(true);
$this->assertInstanceOf('\PDO', $method->invoke($storage));
}
}
@@ -17,6 +17,7 @@ use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcacheSessionHand
/**
* @requires extension memcache
* @group time-sensitive
* @group legacy
*/
class MemcacheSessionHandlerTest extends TestCase
{
@@ -40,7 +41,7 @@ class MemcacheSessionHandlerTest extends TestCase
$this->memcache = $this->getMockBuilder('Memcache')->getMock();
$this->storage = new MemcacheSessionHandler(
$this->memcache,
array('prefix' => self::PREFIX, 'expiretime' => self::TTL)
['prefix' => self::PREFIX, 'expiretime' => self::TTL]
);
}
@@ -78,7 +79,7 @@ class MemcacheSessionHandlerTest extends TestCase
->expects($this->once())
->method('set')
->with(self::PREFIX.'id', 'data', 0, $this->equalTo(time() + self::TTL, 2))
->will($this->returnValue(true))
->willReturn(true)
;
$this->assertTrue($this->storage->write('id', 'data'));
@@ -90,7 +91,7 @@ class MemcacheSessionHandlerTest extends TestCase
->expects($this->once())
->method('delete')
->with(self::PREFIX.'id')
->will($this->returnValue(true))
->willReturn(true)
;
$this->assertTrue($this->storage->destroy('id'));
@@ -116,12 +117,12 @@ class MemcacheSessionHandlerTest extends TestCase
public function getOptionFixtures()
{
return array(
array(array('prefix' => 'session'), true),
array(array('expiretime' => 100), true),
array(array('prefix' => 'session', 'expiretime' => 200), true),
array(array('expiretime' => 100, 'foo' => 'bar'), false),
);
return [
[['prefix' => 'session'], true],
[['expiretime' => 100], true],
[['prefix' => 'session', 'expiretime' => 200], true],
[['expiretime' => 100, 'foo' => 'bar'], false],
];
}
public function testGetConnection()
@@ -45,7 +45,7 @@ class MemcachedSessionHandlerTest extends TestCase
$this->memcached = $this->getMockBuilder('Memcached')->getMock();
$this->storage = new MemcachedSessionHandler(
$this->memcached,
array('prefix' => self::PREFIX, 'expiretime' => self::TTL)
['prefix' => self::PREFIX, 'expiretime' => self::TTL]
);
}
@@ -63,6 +63,12 @@ class MemcachedSessionHandlerTest extends TestCase
public function testCloseSession()
{
$this->memcached
->expects($this->once())
->method('quit')
->willReturn(true)
;
$this->assertTrue($this->storage->close());
}
@@ -83,7 +89,7 @@ class MemcachedSessionHandlerTest extends TestCase
->expects($this->once())
->method('set')
->with(self::PREFIX.'id', 'data', $this->equalTo(time() + self::TTL, 2))
->will($this->returnValue(true))
->willReturn(true)
;
$this->assertTrue($this->storage->write('id', 'data'));
@@ -95,7 +101,7 @@ class MemcachedSessionHandlerTest extends TestCase
->expects($this->once())
->method('delete')
->with(self::PREFIX.'id')
->will($this->returnValue(true))
->willReturn(true)
;
$this->assertTrue($this->storage->destroy('id'));
@@ -121,12 +127,12 @@ class MemcachedSessionHandlerTest extends TestCase
public function getOptionFixtures()
{
return array(
array(array('prefix' => 'session'), true),
array(array('expiretime' => 100), true),
array(array('prefix' => 'session', 'expiretime' => 200), true),
array(array('expiretime' => 100, 'foo' => 'bar'), false),
);
return [
[['prefix' => 'session'], true],
[['expiretime' => 100], true],
[['prefix' => 'session', 'expiretime' => 200], true],
[['expiretime' => 100, 'foo' => 'bar'], false],
];
}
public function testGetConnection()
@@ -11,17 +11,19 @@
namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler;
/**
* @author Markus Bachmann <markus.bachmann@bachi.biz>
* @group time-sensitive
* @group legacy
*/
class MongoDbSessionHandlerTest extends TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject
* @var MockObject
*/
private $mongo;
private $storage;
@@ -49,32 +51,28 @@ class MongoDbSessionHandlerTest extends TestCase
->disableOriginalConstructor()
->getMock();
$this->options = array(
$this->options = [
'id_field' => '_id',
'data_field' => 'data',
'time_field' => 'time',
'expiry_field' => 'expires_at',
'database' => 'sf2-test',
'collection' => 'session-test',
);
];
$this->storage = new MongoDbSessionHandler($this->mongo, $this->options);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testConstructorShouldThrowExceptionForInvalidMongo()
{
$this->expectException('InvalidArgumentException');
new MongoDbSessionHandler(new \stdClass(), $this->options);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testConstructorShouldThrowExceptionForMissingOptions()
{
new MongoDbSessionHandler($this->mongo, array());
$this->expectException('InvalidArgumentException');
new MongoDbSessionHandler($this->mongo, []);
}
public function testOpenMethodAlwaysReturnTrue()
@@ -94,9 +92,7 @@ class MongoDbSessionHandlerTest extends TestCase
$this->mongo->expects($this->once())
->method('selectCollection')
->with($this->options['database'], $this->options['collection'])
->will($this->returnValue($collection));
$that = $this;
->willReturn($collection);
// defining the timeout before the actual method call
// allows to test for "greater than" values in the $criteria
@@ -104,35 +100,35 @@ class MongoDbSessionHandlerTest extends TestCase
$collection->expects($this->once())
->method('findOne')
->will($this->returnCallback(function ($criteria) use ($that, $testTimeout) {
$that->assertArrayHasKey($that->options['id_field'], $criteria);
$that->assertEquals($criteria[$that->options['id_field']], 'foo');
->willReturnCallback(function ($criteria) use ($testTimeout) {
$this->assertArrayHasKey($this->options['id_field'], $criteria);
$this->assertEquals('foo', $criteria[$this->options['id_field']]);
$that->assertArrayHasKey($that->options['expiry_field'], $criteria);
$that->assertArrayHasKey('$gte', $criteria[$that->options['expiry_field']]);
$this->assertArrayHasKey($this->options['expiry_field'], $criteria);
$this->assertArrayHasKey('$gte', $criteria[$this->options['expiry_field']]);
if (phpversion('mongodb')) {
$that->assertInstanceOf('MongoDB\BSON\UTCDateTime', $criteria[$that->options['expiry_field']]['$gte']);
$that->assertGreaterThanOrEqual(round((string) $criteria[$that->options['expiry_field']]['$gte'] / 1000), $testTimeout);
$this->assertInstanceOf('MongoDB\BSON\UTCDateTime', $criteria[$this->options['expiry_field']]['$gte']);
$this->assertGreaterThanOrEqual(round((string) $criteria[$this->options['expiry_field']]['$gte'] / 1000), $testTimeout);
} else {
$that->assertInstanceOf('MongoDate', $criteria[$that->options['expiry_field']]['$gte']);
$that->assertGreaterThanOrEqual($criteria[$that->options['expiry_field']]['$gte']->sec, $testTimeout);
$this->assertInstanceOf('MongoDate', $criteria[$this->options['expiry_field']]['$gte']);
$this->assertGreaterThanOrEqual($criteria[$this->options['expiry_field']]['$gte']->sec, $testTimeout);
}
$fields = array(
$that->options['id_field'] => 'foo',
);
$fields = [
$this->options['id_field'] => 'foo',
];
if (phpversion('mongodb')) {
$fields[$that->options['data_field']] = new \MongoDB\BSON\Binary('bar', \MongoDB\BSON\Binary::TYPE_OLD_BINARY);
$fields[$that->options['id_field']] = new \MongoDB\BSON\UTCDateTime(time() * 1000);
$fields[$this->options['data_field']] = new \MongoDB\BSON\Binary('bar', \MongoDB\BSON\Binary::TYPE_OLD_BINARY);
$fields[$this->options['id_field']] = new \MongoDB\BSON\UTCDateTime(time() * 1000);
} else {
$fields[$that->options['data_field']] = new \MongoBinData('bar', \MongoBinData::BYTE_ARRAY);
$fields[$that->options['id_field']] = new \MongoDate();
$fields[$this->options['data_field']] = new \MongoBinData('bar', \MongoBinData::BYTE_ARRAY);
$fields[$this->options['id_field']] = new \MongoDate();
}
return $fields;
}));
});
$this->assertEquals('bar', $this->storage->read('foo'));
}
@@ -144,53 +140,52 @@ class MongoDbSessionHandlerTest extends TestCase
$this->mongo->expects($this->once())
->method('selectCollection')
->with($this->options['database'], $this->options['collection'])
->will($this->returnValue($collection));
->willReturn($collection);
$that = $this;
$data = array();
$data = [];
$methodName = phpversion('mongodb') ? 'updateOne' : 'update';
$collection->expects($this->once())
->method($methodName)
->will($this->returnCallback(function ($criteria, $updateData, $options) use ($that, &$data) {
$that->assertEquals(array($that->options['id_field'] => 'foo'), $criteria);
->willReturnCallback(function ($criteria, $updateData, $options) use (&$data) {
$this->assertEquals([$this->options['id_field'] => 'foo'], $criteria);
if (phpversion('mongodb')) {
$that->assertEquals(array('upsert' => true), $options);
$this->assertEquals(['upsert' => true], $options);
} else {
$that->assertEquals(array('upsert' => true, 'multiple' => false), $options);
$this->assertEquals(['upsert' => true, 'multiple' => false], $options);
}
$data = $updateData['$set'];
}));
});
$expectedExpiry = time() + (int) ini_get('session.gc_maxlifetime');
$this->assertTrue($this->storage->write('foo', 'bar'));
if (phpversion('mongodb')) {
$that->assertEquals('bar', $data[$that->options['data_field']]->getData());
$that->assertInstanceOf('MongoDB\BSON\UTCDateTime', $data[$that->options['time_field']]);
$that->assertInstanceOf('MongoDB\BSON\UTCDateTime', $data[$that->options['expiry_field']]);
$that->assertGreaterThanOrEqual($expectedExpiry, round((string) $data[$that->options['expiry_field']] / 1000));
$this->assertEquals('bar', $data[$this->options['data_field']]->getData());
$this->assertInstanceOf('MongoDB\BSON\UTCDateTime', $data[$this->options['time_field']]);
$this->assertInstanceOf('MongoDB\BSON\UTCDateTime', $data[$this->options['expiry_field']]);
$this->assertGreaterThanOrEqual($expectedExpiry, round((string) $data[$this->options['expiry_field']] / 1000));
} else {
$that->assertEquals('bar', $data[$that->options['data_field']]->bin);
$that->assertInstanceOf('MongoDate', $data[$that->options['time_field']]);
$that->assertInstanceOf('MongoDate', $data[$that->options['expiry_field']]);
$that->assertGreaterThanOrEqual($expectedExpiry, $data[$that->options['expiry_field']]->sec);
$this->assertEquals('bar', $data[$this->options['data_field']]->bin);
$this->assertInstanceOf('MongoDate', $data[$this->options['time_field']]);
$this->assertInstanceOf('MongoDate', $data[$this->options['expiry_field']]);
$this->assertGreaterThanOrEqual($expectedExpiry, $data[$this->options['expiry_field']]->sec);
}
}
public function testWriteWhenUsingExpiresField()
{
$this->options = array(
$this->options = [
'id_field' => '_id',
'data_field' => 'data',
'time_field' => 'time',
'database' => 'sf2-test',
'collection' => 'session-test',
'expiry_field' => 'expiresAt',
);
];
$this->storage = new MongoDbSessionHandler($this->mongo, $this->options);
@@ -199,37 +194,36 @@ class MongoDbSessionHandlerTest extends TestCase
$this->mongo->expects($this->once())
->method('selectCollection')
->with($this->options['database'], $this->options['collection'])
->will($this->returnValue($collection));
->willReturn($collection);
$that = $this;
$data = array();
$data = [];
$methodName = phpversion('mongodb') ? 'updateOne' : 'update';
$collection->expects($this->once())
->method($methodName)
->will($this->returnCallback(function ($criteria, $updateData, $options) use ($that, &$data) {
$that->assertEquals(array($that->options['id_field'] => 'foo'), $criteria);
->willReturnCallback(function ($criteria, $updateData, $options) use (&$data) {
$this->assertEquals([$this->options['id_field'] => 'foo'], $criteria);
if (phpversion('mongodb')) {
$that->assertEquals(array('upsert' => true), $options);
$this->assertEquals(['upsert' => true], $options);
} else {
$that->assertEquals(array('upsert' => true, 'multiple' => false), $options);
$this->assertEquals(['upsert' => true, 'multiple' => false], $options);
}
$data = $updateData['$set'];
}));
});
$this->assertTrue($this->storage->write('foo', 'bar'));
if (phpversion('mongodb')) {
$that->assertEquals('bar', $data[$that->options['data_field']]->getData());
$that->assertInstanceOf('MongoDB\BSON\UTCDateTime', $data[$that->options['time_field']]);
$that->assertInstanceOf('MongoDB\BSON\UTCDateTime', $data[$that->options['expiry_field']]);
$this->assertEquals('bar', $data[$this->options['data_field']]->getData());
$this->assertInstanceOf('MongoDB\BSON\UTCDateTime', $data[$this->options['time_field']]);
$this->assertInstanceOf('MongoDB\BSON\UTCDateTime', $data[$this->options['expiry_field']]);
} else {
$that->assertEquals('bar', $data[$that->options['data_field']]->bin);
$that->assertInstanceOf('MongoDate', $data[$that->options['time_field']]);
$that->assertInstanceOf('MongoDate', $data[$that->options['expiry_field']]);
$this->assertEquals('bar', $data[$this->options['data_field']]->bin);
$this->assertInstanceOf('MongoDate', $data[$this->options['time_field']]);
$this->assertInstanceOf('MongoDate', $data[$this->options['expiry_field']]);
}
}
@@ -240,17 +234,17 @@ class MongoDbSessionHandlerTest extends TestCase
$this->mongo->expects($this->once())
->method('selectCollection')
->with($this->options['database'], $this->options['collection'])
->will($this->returnValue($collection));
->willReturn($collection);
$data = array();
$data = [];
$methodName = phpversion('mongodb') ? 'updateOne' : 'update';
$collection->expects($this->exactly(2))
->method($methodName)
->will($this->returnCallback(function ($criteria, $updateData, $options) use (&$data) {
->willReturnCallback(function ($criteria, $updateData, $options) use (&$data) {
$data = $updateData;
}));
});
$this->storage->write('foo', 'bar');
$this->storage->write('foo', 'foobar');
@@ -269,13 +263,13 @@ class MongoDbSessionHandlerTest extends TestCase
$this->mongo->expects($this->once())
->method('selectCollection')
->with($this->options['database'], $this->options['collection'])
->will($this->returnValue($collection));
->willReturn($collection);
$methodName = phpversion('mongodb') ? 'deleteOne' : 'remove';
$collection->expects($this->once())
->method($methodName)
->with(array($this->options['id_field'] => 'foo'));
->with([$this->options['id_field'] => 'foo']);
$this->assertTrue($this->storage->destroy('foo'));
}
@@ -287,23 +281,21 @@ class MongoDbSessionHandlerTest extends TestCase
$this->mongo->expects($this->once())
->method('selectCollection')
->with($this->options['database'], $this->options['collection'])
->will($this->returnValue($collection));
$that = $this;
->willReturn($collection);
$methodName = phpversion('mongodb') ? 'deleteMany' : 'remove';
$collection->expects($this->once())
->method($methodName)
->will($this->returnCallback(function ($criteria) use ($that) {
->willReturnCallback(function ($criteria) {
if (phpversion('mongodb')) {
$that->assertInstanceOf('MongoDB\BSON\UTCDateTime', $criteria[$that->options['expiry_field']]['$lt']);
$that->assertGreaterThanOrEqual(time() - 1, round((string) $criteria[$that->options['expiry_field']]['$lt'] / 1000));
$this->assertInstanceOf('MongoDB\BSON\UTCDateTime', $criteria[$this->options['expiry_field']]['$lt']);
$this->assertGreaterThanOrEqual(time() - 1, round((string) $criteria[$this->options['expiry_field']]['$lt'] / 1000));
} else {
$that->assertInstanceOf('MongoDate', $criteria[$that->options['expiry_field']]['$lt']);
$that->assertGreaterThanOrEqual(time() - 1, $criteria[$that->options['expiry_field']]['$lt']->sec);
$this->assertInstanceOf('MongoDate', $criteria[$this->options['expiry_field']]['$lt']);
$this->assertGreaterThanOrEqual(time() - 1, $criteria[$this->options['expiry_field']]['$lt']->sec);
}
}));
});
$this->assertTrue($this->storage->gc(1));
}
@@ -27,15 +27,10 @@ class NativeFileSessionHandlerTest extends TestCase
{
public function testConstruct()
{
$storage = new NativeSessionStorage(array('name' => 'TESTING'), new NativeFileSessionHandler(sys_get_temp_dir()));
$storage = new NativeSessionStorage(['name' => 'TESTING'], new NativeFileSessionHandler(sys_get_temp_dir()));
if (\PHP_VERSION_ID < 50400) {
$this->assertEquals('files', $storage->getSaveHandler()->getSaveHandlerName());
$this->assertEquals('files', ini_get('session.save_handler'));
} else {
$this->assertEquals('files', $storage->getSaveHandler()->getSaveHandlerName());
$this->assertEquals('user', ini_get('session.save_handler'));
}
$this->assertEquals('files', $storage->getSaveHandler()->getSaveHandlerName());
$this->assertEquals('user', ini_get('session.save_handler'));
$this->assertEquals(sys_get_temp_dir(), ini_get('session.save_path'));
$this->assertEquals('TESTING', ini_get('session.name'));
@@ -46,9 +41,9 @@ class NativeFileSessionHandlerTest extends TestCase
*/
public function testConstructSavePath($savePath, $expectedSavePath, $path)
{
$handler = new NativeFileSessionHandler($savePath);
new NativeFileSessionHandler($savePath);
$this->assertEquals($expectedSavePath, ini_get('session.save_path'));
$this->assertTrue(is_dir(realpath($path)));
$this->assertDirectoryExists(realpath($path));
rmdir($path);
}
@@ -57,25 +52,23 @@ class NativeFileSessionHandlerTest extends TestCase
{
$base = sys_get_temp_dir();
return array(
array("$base/foo", "$base/foo", "$base/foo"),
array("5;$base/foo", "5;$base/foo", "$base/foo"),
array("5;0600;$base/foo", "5;0600;$base/foo", "$base/foo"),
);
return [
["$base/foo", "$base/foo", "$base/foo"],
["5;$base/foo", "5;$base/foo", "$base/foo"],
["5;0600;$base/foo", "5;0600;$base/foo", "$base/foo"],
];
}
/**
* @expectedException \InvalidArgumentException
*/
public function testConstructException()
{
$handler = new NativeFileSessionHandler('something;invalid;with;too-many-args');
$this->expectException('InvalidArgumentException');
new NativeFileSessionHandler('something;invalid;with;too-many-args');
}
public function testConstructDefault()
{
$path = ini_get('session.save_path');
$storage = new NativeSessionStorage(array('name' => 'TESTING'), new NativeFileSessionHandler());
new NativeSessionStorage(['name' => 'TESTING'], new NativeFileSessionHandler());
$this->assertEquals($path, ini_get('session.save_path'));
}
@@ -21,21 +21,18 @@ use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeSessionHandle
*
* @runTestsInSeparateProcesses
* @preserveGlobalState disabled
* @group legacy
*/
class NativeSessionHandlerTest extends TestCase
{
/**
* @expectedDeprecation The Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeSessionHandler class is deprecated since Symfony 3.4 and will be removed in 4.0. Use the \SessionHandler class instead.
*/
public function testConstruct()
{
$handler = new NativeSessionHandler();
// note for PHPUnit optimisers - the use of assertTrue/False
// here is deliberate since the tests do not require the classes to exist - drak
if (\PHP_VERSION_ID < 50400) {
$this->assertFalse($handler instanceof \SessionHandler);
$this->assertTrue($handler instanceof NativeSessionHandler);
} else {
$this->assertTrue($handler instanceof \SessionHandler);
$this->assertTrue($handler instanceof NativeSessionHandler);
}
$this->assertInstanceOf('SessionHandler', $handler);
$this->assertTrue($handler instanceof NativeSessionHandler);
}
}
@@ -28,7 +28,7 @@ class NullSessionHandlerTest extends TestCase
{
public function testSaveHandlers()
{
$storage = $this->getStorage();
$this->getStorage();
$this->assertEquals('user', ini_get('session.save_handler'));
}
@@ -54,6 +54,6 @@ class NullSessionHandlerTest extends TestCase
public function getStorage()
{
return new NativeSessionStorage(array(), new NullSessionHandler());
return new NativeSessionStorage([], new NullSessionHandler());
}
}
@@ -48,34 +48,28 @@ class PdoSessionHandlerTest extends TestCase
return $pdo;
}
/**
* @expectedException \InvalidArgumentException
*/
public function testWrongPdoErrMode()
{
$this->expectException('InvalidArgumentException');
$pdo = $this->getMemorySqlitePdo();
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_SILENT);
$storage = new PdoSessionHandler($pdo);
new PdoSessionHandler($pdo);
}
/**
* @expectedException \RuntimeException
*/
public function testInexistentTable()
{
$storage = new PdoSessionHandler($this->getMemorySqlitePdo(), array('db_table' => 'inexistent_table'));
$this->expectException('RuntimeException');
$storage = new PdoSessionHandler($this->getMemorySqlitePdo(), ['db_table' => 'inexistent_table']);
$storage->open('', 'sid');
$storage->read('id');
$storage->write('id', 'data');
$storage->close();
}
/**
* @expectedException \RuntimeException
*/
public function testCreateTableTwice()
{
$this->expectException('RuntimeException');
$storage = new PdoSessionHandler($this->getMemorySqlitePdo());
$storage->createTable();
}
@@ -147,7 +141,7 @@ class PdoSessionHandlerTest extends TestCase
$stream = $this->createStream($content);
$pdo->prepareResult->expects($this->once())->method('fetchAll')
->will($this->returnValue(array(array($stream, 42, time()))));
->willReturn([[$stream, 42, time()]]);
$storage = new PdoSessionHandler($pdo);
$result = $storage->read('foo');
@@ -160,6 +154,9 @@ class PdoSessionHandlerTest extends TestCase
if (\defined('HHVM_VERSION')) {
$this->markTestSkipped('PHPUnit_MockObject cannot mock the PDOStatement class on HHVM. See https://github.com/sebastianbergmann/phpunit-mock-objects/pull/289');
}
if (filter_var(ini_get('session.use_strict_mode'), \FILTER_VALIDATE_BOOLEAN)) {
$this->markTestSkipped('Strict mode needs no locking for new sessions.');
}
$pdo = new MockPdo('pgsql');
$selectStmt = $this->getMockBuilder('PDOStatement')->getMock();
@@ -174,14 +171,14 @@ class PdoSessionHandlerTest extends TestCase
$exception = null;
$selectStmt->expects($this->atLeast(2))->method('fetchAll')
->will($this->returnCallback(function () use (&$exception, $stream) {
return $exception ? array(array($stream, 42, time())) : array();
}));
->willReturnCallback(function () use (&$exception, $stream) {
return $exception ? [[$stream, 42, time()]] : [];
});
$insertStmt->expects($this->once())->method('execute')
->will($this->returnCallback(function () use (&$exception) {
->willReturnCallback(function () use (&$exception) {
throw $exception = new \PDOException('', '23');
}));
});
$storage = new PdoSessionHandler($pdo);
$result = $storage->read('foo');
@@ -321,6 +318,41 @@ class PdoSessionHandlerTest extends TestCase
$this->assertInstanceOf('\PDO', $method->invoke($storage));
}
/**
* @dataProvider provideUrlDsnPairs
*/
public function testUrlDsn($url, $expectedDsn, $expectedUser = null, $expectedPassword = null)
{
$storage = new PdoSessionHandler($url);
$reflection = new \ReflectionClass(PdoSessionHandler::class);
foreach (['dsn' => $expectedDsn, 'username' => $expectedUser, 'password' => $expectedPassword] as $property => $expectedValue) {
if (!isset($expectedValue)) {
continue;
}
$property = $reflection->getProperty($property);
$property->setAccessible(true);
$this->assertSame($expectedValue, $property->getValue($storage));
}
}
public function provideUrlDsnPairs()
{
yield ['mysql://localhost/test', 'mysql:host=localhost;dbname=test;'];
yield ['mysql://localhost:56/test', 'mysql:host=localhost;port=56;dbname=test;'];
yield ['mysql2://root:pwd@localhost/test', 'mysql:host=localhost;dbname=test;', 'root', 'pwd'];
yield ['postgres://localhost/test', 'pgsql:host=localhost;dbname=test;'];
yield ['postgresql://localhost:5634/test', 'pgsql:host=localhost;port=5634;dbname=test;'];
yield ['postgres://root:pwd@localhost/test', 'pgsql:host=localhost;dbname=test;', 'root', 'pwd'];
yield 'sqlite relative path' => ['sqlite://localhost/tmp/test', 'sqlite:tmp/test'];
yield 'sqlite absolute path' => ['sqlite://localhost//tmp/test', 'sqlite:/tmp/test'];
yield 'sqlite relative path without host' => ['sqlite:///tmp/test', 'sqlite:tmp/test'];
yield 'sqlite absolute path without host' => ['sqlite3:////tmp/test', 'sqlite:/tmp/test'];
yield ['sqlite://localhost/:memory:', 'sqlite::memory:'];
yield ['mssql://localhost/test', 'sqlsrv:server=localhost;Database=test'];
yield ['mssql://localhost:56/test', 'sqlsrv:server=localhost,56;Database=test'];
}
private function createStream($content)
{
$stream = tmpfile();
@@ -356,7 +388,7 @@ class MockPdo extends \PDO
return parent::getAttribute($attribute);
}
public function prepare($statement, $driverOptions = array())
public function prepare($statement, $driverOptions = [])
{
return \is_callable($this->prepareResult)
? \call_user_func($this->prepareResult, $statement, $driverOptions)
@@ -16,6 +16,8 @@ use Symfony\Component\HttpFoundation\Session\Storage\Handler\WriteCheckSessionHa
/**
* @author Adrien Brault <adrien.brault@gmail.com>
*
* @group legacy
*/
class WriteCheckSessionHandlerTest extends TestCase
{
@@ -28,7 +30,7 @@ class WriteCheckSessionHandlerTest extends TestCase
->expects($this->once())
->method('close')
->with()
->will($this->returnValue(true))
->willReturn(true)
;
$this->assertTrue($writeCheckSessionHandler->close());
@@ -43,7 +45,7 @@ class WriteCheckSessionHandlerTest extends TestCase
->expects($this->once())
->method('write')
->with('foo', 'bar')
->will($this->returnValue(true))
->willReturn(true)
;
$this->assertTrue($writeCheckSessionHandler->write('foo', 'bar'));
@@ -58,7 +60,7 @@ class WriteCheckSessionHandlerTest extends TestCase
->expects($this->once())
->method('read')
->with('foo')
->will($this->returnValue('bar'))
->willReturn('bar')
;
$wrappedSessionHandlerMock
@@ -79,14 +81,14 @@ class WriteCheckSessionHandlerTest extends TestCase
->expects($this->once())
->method('read')
->with('foo')
->will($this->returnValue('bar'))
->willReturn('bar')
;
$wrappedSessionHandlerMock
->expects($this->once())
->method('write')
->with('foo', 'baZZZ')
->will($this->returnValue(true))
->willReturn(true)
;
$this->assertEquals('bar', $writeCheckSessionHandler->read('foo'));
@@ -26,26 +26,26 @@ class MetadataBagTest extends TestCase
*/
protected $bag;
protected $array = array();
protected $array = [];
protected function setUp()
{
parent::setUp();
$this->bag = new MetadataBag();
$this->array = array(MetadataBag::CREATED => 1234567, MetadataBag::UPDATED => 12345678, MetadataBag::LIFETIME => 0);
$this->array = [MetadataBag::CREATED => 1234567, MetadataBag::UPDATED => 12345678, MetadataBag::LIFETIME => 0];
$this->bag->initialize($this->array);
}
protected function tearDown()
{
$this->array = array();
$this->array = [];
$this->bag = null;
parent::tearDown();
}
public function testInitialize()
{
$sessionMetadata = array();
$sessionMetadata = [];
$bag1 = new MetadataBag();
$bag1->initialize($sessionMetadata);
@@ -82,7 +82,7 @@ class MetadataBagTest extends TestCase
public function testGetLifetime()
{
$bag = new MetadataBag();
$array = array(MetadataBag::CREATED => 1234567, MetadataBag::UPDATED => 12345678, MetadataBag::LIFETIME => 1000);
$array = [MetadataBag::CREATED => 1234567, MetadataBag::UPDATED => 12345678, MetadataBag::LIFETIME => 1000];
$bag->initialize($array);
$this->assertEquals(1000, $bag->getLifetime());
}
@@ -111,11 +111,11 @@ class MetadataBagTest extends TestCase
$timeStamp = time();
$created = $timeStamp - 15;
$sessionMetadata = array(
$sessionMetadata = [
MetadataBag::CREATED => $created,
MetadataBag::UPDATED => $created,
MetadataBag::LIFETIME => 1000,
);
];
$bag->initialize($sessionMetadata);
$this->assertEquals($created, $sessionMetadata[MetadataBag::UPDATED]);
@@ -127,11 +127,11 @@ class MetadataBagTest extends TestCase
$timeStamp = time();
$created = $timeStamp - 45;
$sessionMetadata = array(
$sessionMetadata = [
MetadataBag::CREATED => $created,
MetadataBag::UPDATED => $created,
MetadataBag::LIFETIME => 1000,
);
];
$bag->initialize($sessionMetadata);
$this->assertEquals($timeStamp, $sessionMetadata[MetadataBag::UPDATED]);
@@ -45,10 +45,10 @@ class MockArraySessionStorageTest extends TestCase
$this->attributes = new AttributeBag();
$this->flashes = new FlashBag();
$this->data = array(
$this->attributes->getStorageKey() => array('foo' => 'bar'),
$this->flashes->getStorageKey() => array('notice' => 'hello'),
);
$this->data = [
$this->attributes->getStorageKey() => ['foo' => 'bar'],
$this->flashes->getStorageKey() => ['notice' => 'hello'],
];
$this->storage = new MockArraySessionStorage();
$this->storage->registerBag($this->flashes);
@@ -80,14 +80,14 @@ class MockArraySessionStorageTest extends TestCase
$id = $this->storage->getId();
$this->storage->regenerate();
$this->assertNotEquals($id, $this->storage->getId());
$this->assertEquals(array('foo' => 'bar'), $this->storage->getBag('attributes')->all());
$this->assertEquals(array('notice' => 'hello'), $this->storage->getBag('flashes')->peekAll());
$this->assertEquals(['foo' => 'bar'], $this->storage->getBag('attributes')->all());
$this->assertEquals(['notice' => 'hello'], $this->storage->getBag('flashes')->peekAll());
$id = $this->storage->getId();
$this->storage->regenerate(true);
$this->assertNotEquals($id, $this->storage->getId());
$this->assertEquals(array('foo' => 'bar'), $this->storage->getBag('attributes')->all());
$this->assertEquals(array('notice' => 'hello'), $this->storage->getBag('flashes')->peekAll());
$this->assertEquals(['foo' => 'bar'], $this->storage->getBag('attributes')->all());
$this->assertEquals(['notice' => 'hello'], $this->storage->getBag('flashes')->peekAll());
}
public function testGetId()
@@ -101,8 +101,8 @@ class MockArraySessionStorageTest extends TestCase
{
$this->storage->clear();
$this->assertSame(array(), $this->storage->getBag('attributes')->all());
$this->assertSame(array(), $this->storage->getBag('flashes')->peekAll());
$this->assertSame([], $this->storage->getBag('attributes')->all());
$this->assertSame([], $this->storage->getBag('flashes')->peekAll());
}
public function testClearStartsSession()
@@ -121,11 +121,9 @@ class MockArraySessionStorageTest extends TestCase
$this->assertTrue($storage->isStarted());
}
/**
* @expectedException \RuntimeException
*/
public function testUnstartedSave()
{
$this->expectException('RuntimeException');
$this->storage->save();
}
}
@@ -41,12 +41,12 @@ class MockFileSessionStorageTest extends TestCase
protected function tearDown()
{
array_map('unlink', glob($this->sessionDir.'/*'));
if (is_dir($this->sessionDir)) {
@rmdir($this->sessionDir);
}
$this->sessionDir = null;
$this->storage = null;
array_map('unlink', glob($this->sessionDir.'/*.session'));
if (is_dir($this->sessionDir)) {
rmdir($this->sessionDir);
}
}
public function testStart()
@@ -91,7 +91,7 @@ class MockFileSessionStorageTest extends TestCase
$storage->start();
$this->assertEquals('108', $storage->getBag('attributes')->get('new'));
$this->assertTrue($storage->getBag('flashes')->has('newkey'));
$this->assertEquals(array('test'), $storage->getBag('flashes')->peek('newkey'));
$this->assertEquals(['test'], $storage->getBag('flashes')->peek('newkey'));
}
public function testMultipleInstances()
@@ -107,11 +107,9 @@ class MockFileSessionStorageTest extends TestCase
$this->assertEquals('bar', $storage2->getBag('attributes')->get('foo'), 'values persist between instances');
}
/**
* @expectedException \RuntimeException
*/
public function testSaveWithoutStart()
{
$this->expectException('RuntimeException');
$storage1 = $this->getStorage();
$storage1->save();
}
@@ -14,10 +14,9 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeFileSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\NullSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
use Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy;
use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy;
/**
@@ -37,7 +36,7 @@ class NativeSessionStorageTest extends TestCase
protected function setUp()
{
$this->iniSet('session.save_handler', 'files');
$this->iniSet('session.save_path', $this->savePath = sys_get_temp_dir().'/sf2test');
$this->iniSet('session.save_path', $this->savePath = sys_get_temp_dir().'/sftest');
if (!is_dir($this->savePath)) {
mkdir($this->savePath);
}
@@ -48,7 +47,7 @@ class NativeSessionStorageTest extends TestCase
session_write_close();
array_map('unlink', glob($this->savePath.'/*'));
if (is_dir($this->savePath)) {
rmdir($this->savePath);
@rmdir($this->savePath);
}
$this->savePath = null;
@@ -57,7 +56,7 @@ class NativeSessionStorageTest extends TestCase
/**
* @return NativeSessionStorage
*/
protected function getStorage(array $options = array())
protected function getStorage(array $options = [])
{
$storage = new NativeSessionStorage($options);
$storage->registerBag(new AttributeBag());
@@ -73,20 +72,16 @@ class NativeSessionStorageTest extends TestCase
$this->assertSame($bag, $storage->getBag($bag->getName()));
}
/**
* @expectedException \InvalidArgumentException
*/
public function testRegisterBagException()
{
$this->expectException('InvalidArgumentException');
$storage = $this->getStorage();
$storage->getBag('non_existing');
}
/**
* @expectedException \LogicException
*/
public function testRegisterBagForAStartedSessionThrowsException()
{
$this->expectException('LogicException');
$storage = $this->getStorage();
$storage->start();
$storage->registerBag(new AttributeBag());
@@ -99,7 +94,7 @@ class NativeSessionStorageTest extends TestCase
$storage->start();
$id = $storage->getId();
$this->assertInternalType('string', $id);
$this->assertIsString($id);
$this->assertNotSame('', $id);
$storage->save();
@@ -128,6 +123,19 @@ class NativeSessionStorageTest extends TestCase
$this->assertEquals(11, $storage->getBag('attributes')->get('legs'));
}
public function testRegenerateWithCustomLifetime()
{
$storage = $this->getStorage();
$storage->start();
$id = $storage->getId();
$lifetime = 999999;
$storage->getBag('attributes')->set('legs', 11);
$storage->regenerate(false, $lifetime);
$this->assertNotEquals($id, $storage->getId());
$this->assertEquals(11, $storage->getBag('attributes')->get('legs'));
$this->assertEquals($lifetime, ini_get('session.cookie_lifetime'));
}
public function testSessionGlobalIsUpToDateAfterIdRegeneration()
{
$storage = $this->getStorage();
@@ -150,7 +158,7 @@ class NativeSessionStorageTest extends TestCase
{
$this->iniSet('session.cache_limiter', 'nocache');
$storage = new NativeSessionStorage();
new NativeSessionStorage();
$this->assertEquals('', ini_get('session.cache_limiter'));
}
@@ -158,23 +166,27 @@ class NativeSessionStorageTest extends TestCase
{
$this->iniSet('session.cache_limiter', 'nocache');
$storage = new NativeSessionStorage(array('cache_limiter' => 'public'));
new NativeSessionStorage(['cache_limiter' => 'public']);
$this->assertEquals('public', ini_get('session.cache_limiter'));
}
public function testCookieOptions()
{
$options = array(
$options = [
'cookie_lifetime' => 123456,
'cookie_path' => '/my/cookie/path',
'cookie_domain' => 'symfony.example.com',
'cookie_secure' => true,
'cookie_httponly' => false,
);
];
if (\PHP_VERSION_ID >= 70300) {
$options['cookie_samesite'] = 'lax';
}
$this->getStorage($options);
$temp = session_get_cookie_params();
$gco = array();
$gco = [];
foreach ($temp as $key => $value) {
$gco['cookie_'.$key] = $value;
@@ -189,10 +201,10 @@ class NativeSessionStorageTest extends TestCase
$this->markTestSkipped('HHVM is not handled in this test case.');
}
$options = array(
$options = [
'url_rewriter.tags' => 'a=href',
'cache_expire' => '200',
);
];
$this->getStorage($options);
@@ -200,41 +212,14 @@ class NativeSessionStorageTest extends TestCase
$this->assertSame('200', ini_get('session.cache_expire'));
}
/**
* @expectedException \InvalidArgumentException
*/
public function testSetSaveHandlerException()
{
$this->expectException('InvalidArgumentException');
$storage = $this->getStorage();
$storage->setSaveHandler(new \stdClass());
}
public function testSetSaveHandler53()
{
if (\PHP_VERSION_ID >= 50400) {
$this->markTestSkipped('Test skipped, for PHP 5.3 only.');
}
$this->iniSet('session.save_handler', 'files');
$storage = $this->getStorage();
$storage->setSaveHandler();
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy', $storage->getSaveHandler());
$storage->setSaveHandler(null);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy', $storage->getSaveHandler());
$storage->setSaveHandler(new NativeSessionHandler());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy', $storage->getSaveHandler());
$storage->setSaveHandler(new SessionHandlerProxy(new NullSessionHandler()));
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
$storage->setSaveHandler(new NullSessionHandler());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
$storage->setSaveHandler(new NativeProxy());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy', $storage->getSaveHandler());
}
/**
* @requires PHP 5.4
*/
public function testSetSaveHandler54()
public function testSetSaveHandler()
{
$this->iniSet('session.save_handler', 'files');
$storage = $this->getStorage();
@@ -242,9 +227,9 @@ class NativeSessionStorageTest extends TestCase
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
$storage->setSaveHandler(null);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
$storage->setSaveHandler(new SessionHandlerProxy(new NativeSessionHandler()));
$storage->setSaveHandler(new SessionHandlerProxy(new NativeFileSessionHandler()));
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
$storage->setSaveHandler(new NativeSessionHandler());
$storage->setSaveHandler(new NativeFileSessionHandler());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
$storage->setSaveHandler(new SessionHandlerProxy(new NullSessionHandler()));
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
@@ -252,11 +237,9 @@ class NativeSessionStorageTest extends TestCase
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
}
/**
* @expectedException \RuntimeException
*/
public function testStartedOutside()
public function testStarted()
{
$this->expectException('RuntimeException');
$storage = $this->getStorage();
$this->assertFalse($storage->getSaveHandler()->isActive());
@@ -264,10 +247,8 @@ class NativeSessionStorageTest extends TestCase
session_start();
$this->assertTrue(isset($_SESSION));
if (\PHP_VERSION_ID >= 50400) {
// this only works in PHP >= 5.4 where session_status is available
$this->assertTrue($storage->getSaveHandler()->isActive());
}
$this->assertTrue($storage->getSaveHandler()->isActive());
// PHP session might have started, but the storage driver has not, so false is correct here
$this->assertFalse($storage->isStarted());
@@ -288,9 +269,6 @@ class NativeSessionStorageTest extends TestCase
$this->assertSame(7, $storage->getBag('attributes')->get('lucky'), 'Data still available');
}
/**
* @requires PHP 5.4
*/
public function testCanCreateNativeSessionStorageWhenSessionAlreadyStarted()
{
session_start();
@@ -300,23 +278,17 @@ class NativeSessionStorageTest extends TestCase
$this->addToAssertionCount(1);
}
/**
* @requires PHP 5.4
*/
public function testSetSessionOptionsOnceSessionStartedIsIgnored()
{
session_start();
$this->getStorage(array(
$this->getStorage([
'name' => 'something-else',
));
]);
// Assert no exception has been thrown by `getStorage()`
$this->addToAssertionCount(1);
}
/**
* @requires PHP 5.4
*/
public function testGetBagsOnceSessionStartedIsIgnored()
{
session_start();
@@ -43,7 +43,7 @@ class PhpBridgeSessionStorageTest extends TestCase
session_write_close();
array_map('unlink', glob($this->savePath.'/*'));
if (is_dir($this->savePath)) {
rmdir($this->savePath);
@rmdir($this->savePath);
}
$this->savePath = null;
@@ -60,34 +60,7 @@ class PhpBridgeSessionStorageTest extends TestCase
return $storage;
}
public function testPhpSession53()
{
if (\PHP_VERSION_ID >= 50400) {
$this->markTestSkipped('Test skipped, for PHP 5.3 only.');
}
$storage = $this->getStorage();
$this->assertFalse(isset($_SESSION));
$this->assertFalse($storage->getSaveHandler()->isActive());
session_start();
$this->assertTrue(isset($_SESSION));
// in PHP 5.3 we cannot reliably tell if a session has started
$this->assertFalse($storage->getSaveHandler()->isActive());
// PHP session might have started, but the storage driver has not, so false is correct here
$this->assertFalse($storage->isStarted());
$key = $storage->getMetadataBag()->getStorageKey();
$this->assertArrayNotHasKey($key, $_SESSION);
$storage->start();
$this->assertArrayHasKey($key, $_SESSION);
}
/**
* @requires PHP 5.4
*/
public function testPhpSession54()
public function testPhpSession()
{
$storage = $this->getStorage();
@@ -114,10 +87,10 @@ class PhpBridgeSessionStorageTest extends TestCase
$_SESSION['drak'] = 'loves symfony';
$storage->getBag('attributes')->set('symfony', 'greatness');
$key = $storage->getBag('attributes')->getStorageKey();
$this->assertEquals($_SESSION[$key], array('symfony' => 'greatness'));
$this->assertEquals($_SESSION['drak'], 'loves symfony');
$this->assertEquals(['symfony' => 'greatness'], $_SESSION[$key]);
$this->assertEquals('loves symfony', $_SESSION['drak']);
$storage->clear();
$this->assertEquals($_SESSION[$key], array());
$this->assertEquals($_SESSION['drak'], 'loves symfony');
$this->assertEquals([], $_SESSION[$key]);
$this->assertEquals('loves symfony', $_SESSION['drak']);
}
}
@@ -13,39 +13,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Proxy;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy;
// Note until PHPUnit_Mock_Objects 1.2 is released you cannot mock abstracts due to
// https://github.com/sebastianbergmann/phpunit-mock-objects/issues/73
class ConcreteProxy extends AbstractProxy
{
}
class ConcreteSessionHandlerInterfaceProxy extends AbstractProxy implements \SessionHandlerInterface
{
public function open($savePath, $sessionName)
{
}
public function close()
{
}
public function read($id)
{
}
public function write($id, $data)
{
}
public function destroy($id)
{
}
public function gc($maxlifetime)
{
}
}
use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy;
/**
* Test class for AbstractProxy.
@@ -61,7 +29,7 @@ class AbstractProxyTest extends TestCase
protected function setUp()
{
$this->proxy = new ConcreteProxy();
$this->proxy = $this->getMockForAbstractClass(AbstractProxy::class);
}
protected function tearDown()
@@ -77,7 +45,7 @@ class AbstractProxyTest extends TestCase
public function testIsSessionHandlerInterface()
{
$this->assertFalse($this->proxy->isSessionHandlerInterface());
$sh = new ConcreteSessionHandlerInterfaceProxy();
$sh = new SessionHandlerProxy(new \SessionHandler());
$this->assertTrue($sh->isSessionHandlerInterface());
}
@@ -86,50 +54,17 @@ class AbstractProxyTest extends TestCase
$this->assertFalse($this->proxy->isWrapper());
}
public function testIsActivePhp53()
{
if (\PHP_VERSION_ID >= 50400) {
$this->markTestSkipped('Test skipped, for PHP 5.3 only.');
}
$this->assertFalse($this->proxy->isActive());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
* @requires PHP 5.4
*/
public function testIsActivePhp54()
public function testIsActive()
{
$this->assertFalse($this->proxy->isActive());
session_start();
$this->assertTrue($this->proxy->isActive());
}
public function testSetActivePhp53()
{
if (\PHP_VERSION_ID >= 50400) {
$this->markTestSkipped('Test skipped, for PHP 5.3 only.');
}
$this->proxy->setActive(true);
$this->assertTrue($this->proxy->isActive());
$this->proxy->setActive(false);
$this->assertFalse($this->proxy->isActive());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
* @expectedException \LogicException
* @requires PHP 5.4
*/
public function testSetActivePhp54()
{
$this->proxy->setActive(true);
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
@@ -142,27 +77,13 @@ class AbstractProxyTest extends TestCase
$this->assertEquals(session_name(), $this->proxy->getName());
}
/**
* @expectedException \LogicException
*/
public function testNameExceptionPhp53()
{
if (\PHP_VERSION_ID >= 50400) {
$this->markTestSkipped('Test skipped, for PHP 5.3 only.');
}
$this->proxy->setActive(true);
$this->proxy->setName('foo');
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
* @expectedException \LogicException
* @requires PHP 5.4
*/
public function testNameExceptionPhp54()
public function testNameException()
{
$this->expectException('LogicException');
session_start();
$this->proxy->setName('foo');
}
@@ -179,27 +100,13 @@ class AbstractProxyTest extends TestCase
$this->assertEquals(session_id(), $this->proxy->getId());
}
/**
* @expectedException \LogicException
*/
public function testIdExceptionPhp53()
{
if (\PHP_VERSION_ID >= 50400) {
$this->markTestSkipped('Test skipped, for PHP 5.3 only.');
}
$this->proxy->setActive(true);
$this->proxy->setId('foo');
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
* @expectedException \LogicException
* @requires PHP 5.4
*/
public function testIdExceptionPhp54()
public function testIdException()
{
$this->expectException('LogicException');
session_start();
$this->proxy->setId('foo');
}
@@ -17,6 +17,8 @@ use Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy;
/**
* Test class for NativeProxy.
*
* @group legacy
*
* @author Drak <drak@zikula.org>
*/
class NativeProxyTest extends TestCase
@@ -25,7 +25,7 @@ use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy;
class SessionHandlerProxyTest extends TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_Matcher
* @var \PHPUnit\Framework\MockObject\Matcher
*/
private $mock;
@@ -46,26 +46,22 @@ class SessionHandlerProxyTest extends TestCase
$this->proxy = null;
}
public function testOpen()
public function testOpenTrue()
{
$this->mock->expects($this->once())
->method('open')
->will($this->returnValue(true));
->willReturn(true);
$this->assertFalse($this->proxy->isActive());
$this->proxy->open('name', 'id');
if (\PHP_VERSION_ID < 50400) {
$this->assertTrue($this->proxy->isActive());
} else {
$this->assertFalse($this->proxy->isActive());
}
$this->assertFalse($this->proxy->isActive());
}
public function testOpenFalse()
{
$this->mock->expects($this->once())
->method('open')
->will($this->returnValue(false));
->willReturn(false);
$this->assertFalse($this->proxy->isActive());
$this->proxy->open('name', 'id');
@@ -76,7 +72,7 @@ class SessionHandlerProxyTest extends TestCase
{
$this->mock->expects($this->once())
->method('close')
->will($this->returnValue(true));
->willReturn(true);
$this->assertFalse($this->proxy->isActive());
$this->proxy->close();
@@ -87,7 +83,7 @@ class SessionHandlerProxyTest extends TestCase
{
$this->mock->expects($this->once())
->method('close')
->will($this->returnValue(false));
->willReturn(false);
$this->assertFalse($this->proxy->isActive());
$this->proxy->close();
@@ -125,4 +121,42 @@ class SessionHandlerProxyTest extends TestCase
$this->proxy->gc(86400);
}
/**
* @requires PHPUnit 5.1
*/
public function testValidateId()
{
$mock = $this->getMockBuilder(TestSessionHandler::class)->getMock();
$mock->expects($this->once())
->method('validateId');
$proxy = new SessionHandlerProxy($mock);
$proxy->validateId('id');
$this->assertTrue($this->proxy->validateId('id'));
}
/**
* @requires PHPUnit 5.1
*/
public function testUpdateTimestamp()
{
$mock = $this->getMockBuilder(TestSessionHandler::class)->getMock();
$mock->expects($this->once())
->method('updateTimestamp')
->willReturn(false);
$proxy = new SessionHandlerProxy($mock);
$proxy->updateTimestamp('id', 'data');
$this->mock->expects($this->once())
->method('write');
$this->proxy->updateTimestamp('id', 'data');
}
}
abstract class TestSessionHandler implements \SessionHandlerInterface, \SessionUpdateTimestampHandlerInterface
{
}
@@ -19,7 +19,7 @@ class StreamedResponseTest extends TestCase
{
public function testConstructor()
{
$response = new StreamedResponse(function () { echo 'foo'; }, 404, array('Content-Type' => 'text/plain'));
$response = new StreamedResponse(function () { echo 'foo'; }, 404, ['Content-Type' => 'text/plain']);
$this->assertEquals(404, $response->getStatusCode());
$this->assertEquals('text/plain', $response->headers->get('Content-Type'));
@@ -51,7 +51,7 @@ class StreamedResponseTest extends TestCase
public function testPrepareWithHeadRequest()
{
$response = new StreamedResponse(function () { echo 'foo'; }, 200, array('Content-Length' => '123'));
$response = new StreamedResponse(function () { echo 'foo'; }, 200, ['Content-Length' => '123']);
$request = Request::create('/', 'HEAD');
$response->prepare($request);
@@ -61,7 +61,7 @@ class StreamedResponseTest extends TestCase
public function testPrepareWithCacheHeaders()
{
$response = new StreamedResponse(function () { echo 'foo'; }, 200, array('Cache-Control' => 'max-age=600, public'));
$response = new StreamedResponse(function () { echo 'foo'; }, 200, ['Cache-Control' => 'max-age=600, public']);
$request = Request::create('/', 'GET');
$response->prepare($request);
@@ -81,29 +81,16 @@ class StreamedResponseTest extends TestCase
$this->assertEquals(1, $called);
}
/**
* @expectedException \LogicException
*/
public function testSendContentWithNonCallable()
{
$this->expectException('LogicException');
$response = new StreamedResponse(null);
$response->sendContent();
}
/**
* @expectedException \LogicException
*/
public function testSetCallbackNonCallable()
{
$response = new StreamedResponse(null);
$response->setCallback(null);
}
/**
* @expectedException \LogicException
*/
public function testSetContent()
{
$this->expectException('LogicException');
$response = new StreamedResponse(function () { echo 'foo'; });
$response->setContent('foo');
}