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
@@ -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
{
}