Added Laravel project

This commit is contained in:
2017-09-17 00:35:10 +02:00
parent a3c19304d5
commit ecf605b8f5
6246 changed files with 682270 additions and 2 deletions

View File

@@ -0,0 +1,189 @@
<?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\Attribute;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
/**
* Tests AttributeBag.
*
* @author Drak <drak@zikula.org>
*/
class AttributeBagTest extends TestCase
{
/**
* @var array
*/
private $array;
/**
* @var AttributeBag
*/
private $bag;
protected function setUp()
{
$this->array = array(
'hello' => 'world',
'always' => 'be happy',
'user.login' => 'drak',
'csrf.token' => array(
'a' => '1234',
'b' => '4321',
),
'category' => array(
'fishing' => array(
'first' => 'cod',
'second' => 'sole',
),
),
);
$this->bag = new AttributeBag('_sf2');
$this->bag->initialize($this->array);
}
protected function tearDown()
{
$this->bag = null;
$this->array = array();
}
public function testInitialize()
{
$bag = new AttributeBag();
$bag->initialize($this->array);
$this->assertEquals($this->array, $bag->all());
$array = array('should' => 'change');
$bag->initialize($array);
$this->assertEquals($array, $bag->all());
}
public function testGetStorageKey()
{
$this->assertEquals('_sf2', $this->bag->getStorageKey());
$attributeBag = new AttributeBag('test');
$this->assertEquals('test', $attributeBag->getStorageKey());
}
public function testGetSetName()
{
$this->assertEquals('attributes', $this->bag->getName());
$this->bag->setName('foo');
$this->assertEquals('foo', $this->bag->getName());
}
/**
* @dataProvider attributesProvider
*/
public function testHas($key, $value, $exists)
{
$this->assertEquals($exists, $this->bag->has($key));
}
/**
* @dataProvider attributesProvider
*/
public function testGet($key, $value, $expected)
{
$this->assertEquals($value, $this->bag->get($key));
}
public function testGetDefaults()
{
$this->assertNull($this->bag->get('user2.login'));
$this->assertEquals('default', $this->bag->get('user2.login', 'default'));
}
/**
* @dataProvider attributesProvider
*/
public function testSet($key, $value, $expected)
{
$this->bag->set($key, $value);
$this->assertEquals($value, $this->bag->get($key));
}
public function testAll()
{
$this->assertEquals($this->array, $this->bag->all());
$this->bag->set('hello', 'fabien');
$array = $this->array;
$array['hello'] = 'fabien';
$this->assertEquals($array, $this->bag->all());
}
public function testReplace()
{
$array = array();
$array['name'] = 'jack';
$array['foo.bar'] = 'beep';
$this->bag->replace($array);
$this->assertEquals($array, $this->bag->all());
$this->assertNull($this->bag->get('hello'));
$this->assertNull($this->bag->get('always'));
$this->assertNull($this->bag->get('user.login'));
}
public function testRemove()
{
$this->assertEquals('world', $this->bag->get('hello'));
$this->bag->remove('hello');
$this->assertNull($this->bag->get('hello'));
$this->assertEquals('be happy', $this->bag->get('always'));
$this->bag->remove('always');
$this->assertNull($this->bag->get('always'));
$this->assertEquals('drak', $this->bag->get('user.login'));
$this->bag->remove('user.login');
$this->assertNull($this->bag->get('user.login'));
}
public function testClear()
{
$this->bag->clear();
$this->assertEquals(array(), $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),
);
}
public function testGetIterator()
{
$i = 0;
foreach ($this->bag as $key => $val) {
$this->assertEquals($this->array[$key], $val);
++$i;
}
$this->assertEquals(count($this->array), $i);
}
public function testCount()
{
$this->assertEquals(count($this->array), count($this->bag));
}
}

View File

@@ -0,0 +1,185 @@
<?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\Attribute;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag;
/**
* Tests NamespacedAttributeBag.
*
* @author Drak <drak@zikula.org>
*/
class NamespacedAttributeBagTest extends TestCase
{
/**
* @var array
*/
private $array;
/**
* @var NamespacedAttributeBag
*/
private $bag;
protected function setUp()
{
$this->array = array(
'hello' => 'world',
'always' => 'be happy',
'user.login' => 'drak',
'csrf.token' => array(
'a' => '1234',
'b' => '4321',
),
'category' => array(
'fishing' => array(
'first' => 'cod',
'second' => 'sole',
),
),
);
$this->bag = new NamespacedAttributeBag('_sf2', '/');
$this->bag->initialize($this->array);
}
protected function tearDown()
{
$this->bag = null;
$this->array = array();
}
public function testInitialize()
{
$bag = new NamespacedAttributeBag();
$bag->initialize($this->array);
$this->assertEquals($this->array, $this->bag->all());
$array = array('should' => 'not stick');
$bag->initialize($array);
// should have remained the same
$this->assertEquals($this->array, $this->bag->all());
}
public function testGetStorageKey()
{
$this->assertEquals('_sf2', $this->bag->getStorageKey());
$attributeBag = new NamespacedAttributeBag('test');
$this->assertEquals('test', $attributeBag->getStorageKey());
}
/**
* @dataProvider attributesProvider
*/
public function testHas($key, $value, $exists)
{
$this->assertEquals($exists, $this->bag->has($key));
}
/**
* @dataProvider attributesProvider
*/
public function testGet($key, $value, $expected)
{
$this->assertEquals($value, $this->bag->get($key));
}
public function testGetDefaults()
{
$this->assertNull($this->bag->get('user2.login'));
$this->assertEquals('default', $this->bag->get('user2.login', 'default'));
}
/**
* @dataProvider attributesProvider
*/
public function testSet($key, $value, $expected)
{
$this->bag->set($key, $value);
$this->assertEquals($value, $this->bag->get($key));
}
public function testAll()
{
$this->assertEquals($this->array, $this->bag->all());
$this->bag->set('hello', 'fabien');
$array = $this->array;
$array['hello'] = 'fabien';
$this->assertEquals($array, $this->bag->all());
}
public function testReplace()
{
$array = array();
$array['name'] = 'jack';
$array['foo.bar'] = 'beep';
$this->bag->replace($array);
$this->assertEquals($array, $this->bag->all());
$this->assertNull($this->bag->get('hello'));
$this->assertNull($this->bag->get('always'));
$this->assertNull($this->bag->get('user.login'));
}
public function testRemove()
{
$this->assertEquals('world', $this->bag->get('hello'));
$this->bag->remove('hello');
$this->assertNull($this->bag->get('hello'));
$this->assertEquals('be happy', $this->bag->get('always'));
$this->bag->remove('always');
$this->assertNull($this->bag->get('always'));
$this->assertEquals('drak', $this->bag->get('user.login'));
$this->bag->remove('user.login');
$this->assertNull($this->bag->get('user.login'));
}
public function testRemoveExistingNamespacedAttribute()
{
$this->assertSame('cod', $this->bag->remove('category/fishing/first'));
}
public function testRemoveNonexistingNamespacedAttribute()
{
$this->assertNull($this->bag->remove('foo/bar/baz'));
}
public function testClear()
{
$this->bag->clear();
$this->assertEquals(array(), $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),
);
}
}

View File

@@ -0,0 +1,156 @@
<?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\Flash;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Flash\AutoExpireFlashBag as FlashBag;
/**
* AutoExpireFlashBagTest.
*
* @author Drak <drak@zikula.org>
*/
class AutoExpireFlashBagTest extends TestCase
{
/**
* @var \Symfony\Component\HttpFoundation\Session\Flash\AutoExpireFlashBag
*/
private $bag;
/**
* @var array
*/
protected $array = array();
protected function setUp()
{
parent::setUp();
$this->bag = new FlashBag();
$this->array = array('new' => array('notice' => array('A previous flash message')));
$this->bag->initialize($this->array);
}
protected function tearDown()
{
$this->bag = null;
parent::tearDown();
}
public function testInitialize()
{
$bag = new FlashBag();
$array = array('new' => array('notice' => array('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'),
));
$bag->initialize($array);
$this->assertEquals(array('Something else'), $bag->peek('notice'));
$this->assertEquals(array('a'), $bag->peek('error'));
}
public function testGetStorageKey()
{
$this->assertEquals('_sf2_flashes', $this->bag->getStorageKey());
$attributeBag = new FlashBag('test');
$this->assertEquals('test', $attributeBag->getStorageKey());
}
public function testGetSetName()
{
$this->assertEquals('flashes', $this->bag->getName());
$this->bag->setName('foo');
$this->assertEquals('foo', $this->bag->getName());
}
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'));
}
public function testSet()
{
$this->bag->set('notice', 'Foo');
$this->assertEquals(array('A previous flash message'), $this->bag->peek('notice'));
}
public function testHas()
{
$this->assertFalse($this->bag->has('nothing'));
$this->assertTrue($this->bag->has('notice'));
}
public function testKeys()
{
$this->assertEquals(array('notice'), $this->bag->keys());
}
public function testPeekAll()
{
$array = array(
'new' => array(
'notice' => 'Foo',
'error' => 'Bar',
),
);
$this->bag->initialize($array);
$this->assertEquals(array(
'notice' => 'Foo',
'error' => 'Bar',
), $this->bag->peekAll()
);
$this->assertEquals(array(
'notice' => 'Foo',
'error' => 'Bar',
), $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'));
}
public function testSetAll()
{
$this->bag->setAll(array('a' => 'first', 'b' => 'second'));
$this->assertFalse($this->bag->has('a'));
$this->assertFalse($this->bag->has('b'));
}
public function testAll()
{
$this->bag->set('notice', 'Foo');
$this->bag->set('error', 'Bar');
$this->assertEquals(array(
'notice' => array('A previous flash message'),
), $this->bag->all()
);
$this->assertEquals(array(), $this->bag->all());
}
public function testClear()
{
$this->assertEquals(array('notice' => array('A previous flash message')), $this->bag->clear());
}
}

View File

@@ -0,0 +1,135 @@
<?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\Flash;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
/**
* FlashBagTest.
*
* @author Drak <drak@zikula.org>
*/
class FlashBagTest extends TestCase
{
/**
* @var \Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface
*/
private $bag;
/**
* @var array
*/
protected $array = array();
protected function setUp()
{
parent::setUp();
$this->bag = new FlashBag();
$this->array = array('notice' => array('A previous flash message'));
$this->bag->initialize($this->array);
}
protected function tearDown()
{
$this->bag = null;
parent::tearDown();
}
public function testInitialize()
{
$bag = new FlashBag();
$bag->initialize($this->array);
$this->assertEquals($this->array, $bag->peekAll());
$array = array('should' => array('change'));
$bag->initialize($array);
$this->assertEquals($array, $bag->peekAll());
}
public function testGetStorageKey()
{
$this->assertEquals('_sf2_flashes', $this->bag->getStorageKey());
$attributeBag = new FlashBag('test');
$this->assertEquals('test', $attributeBag->getStorageKey());
}
public function testGetSetName()
{
$this->assertEquals('flashes', $this->bag->getName());
$this->bag->setName('foo');
$this->assertEquals('foo', $this->bag->getName());
}
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'));
}
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'));
}
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(array(), $this->bag->all());
}
public function testSet()
{
$this->bag->set('notice', 'Foo');
$this->bag->set('notice', 'Bar');
$this->assertEquals(array('Bar'), $this->bag->peek('notice'));
}
public function testHas()
{
$this->assertFalse($this->bag->has('nothing'));
$this->assertTrue($this->bag->has('notice'));
}
public function testKeys()
{
$this->assertEquals(array('notice'), $this->bag->keys());
}
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->assertTrue($this->bag->has('notice'));
$this->assertTrue($this->bag->has('error'));
$this->assertEquals(array(
'notice' => array('Foo'),
'error' => array('Bar'),
), $this->bag->peekAll()
);
}
}

View File

@@ -0,0 +1,224 @@
<?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;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
/**
* SessionTest.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Robert Schönthal <seroscho@googlemail.com>
* @author Drak <drak@zikula.org>
*/
class SessionTest extends TestCase
{
/**
* @var \Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface
*/
protected $storage;
/**
* @var \Symfony\Component\HttpFoundation\Session\SessionInterface
*/
protected $session;
protected function setUp()
{
$this->storage = new MockArraySessionStorage();
$this->session = new Session($this->storage, new AttributeBag(), new FlashBag());
}
protected function tearDown()
{
$this->storage = null;
$this->session = null;
}
public function testStart()
{
$this->assertEquals('', $this->session->getId());
$this->assertTrue($this->session->start());
$this->assertNotEquals('', $this->session->getId());
}
public function testIsStarted()
{
$this->assertFalse($this->session->isStarted());
$this->session->start();
$this->assertTrue($this->session->isStarted());
}
public function testSetId()
{
$this->assertEquals('', $this->session->getId());
$this->session->setId('0123456789abcdef');
$this->session->start();
$this->assertEquals('0123456789abcdef', $this->session->getId());
}
public function testSetName()
{
$this->assertEquals('MOCKSESSID', $this->session->getName());
$this->session->setName('session.test.com');
$this->session->start();
$this->assertEquals('session.test.com', $this->session->getName());
}
public function testGet()
{
// tests defaults
$this->assertNull($this->session->get('foo'));
$this->assertEquals(1, $this->session->get('foo', 1));
}
/**
* @dataProvider setProvider
*/
public function testSet($key, $value)
{
$this->session->set($key, $value);
$this->assertEquals($value, $this->session->get($key));
}
/**
* @dataProvider setProvider
*/
public function testHas($key, $value)
{
$this->session->set($key, $value);
$this->assertTrue($this->session->has($key));
$this->assertFalse($this->session->has($key.'non_value'));
}
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());
}
/**
* @dataProvider setProvider
*/
public function testAll($key, $value, $result)
{
$this->session->set($key, $value);
$this->assertEquals($result, $this->session->all());
}
/**
* @dataProvider setProvider
*/
public function testClear($key, $value)
{
$this->session->set('hi', 'fabien');
$this->session->set($key, $value);
$this->session->clear();
$this->assertEquals(array(), $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')),
);
}
/**
* @dataProvider setProvider
*/
public function testRemove($key, $value)
{
$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());
}
public function testInvalidate()
{
$this->session->set('invalidate', 123);
$this->session->invalidate();
$this->assertEquals(array(), $this->session->all());
}
public function testMigrate()
{
$this->session->set('migrate', 321);
$this->session->migrate();
$this->assertEquals(321, $this->session->get('migrate'));
}
public function testMigrateDestroy()
{
$this->session->set('migrate', 333);
$this->session->migrate(true);
$this->assertEquals(333, $this->session->get('migrate'));
}
public function testSave()
{
$this->session->start();
$this->session->save();
$this->assertFalse($this->session->isStarted());
}
public function testGetId()
{
$this->assertEquals('', $this->session->getId());
$this->session->start();
$this->assertNotEquals('', $this->session->getId());
}
public function testGetFlashBag()
{
$this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBagInterface', $this->session->getFlashBag());
}
public function testGetIterator()
{
$attributes = array('hello' => 'world', 'symfony' => 'rocks');
foreach ($attributes as $key => $val) {
$this->session->set($key, $val);
}
$i = 0;
foreach ($this->session as $key => $val) {
$this->assertEquals($attributes[$key], $val);
++$i;
}
$this->assertEquals(count($attributes), $i);
}
public function testGetCount()
{
$this->session->set('hello', 'world');
$this->session->set('symfony', 'rocks');
$this->assertCount(2, $this->session);
}
public function testGetMeta()
{
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\MetadataBag', $this->session->getMetadataBag());
}
}

View File

@@ -0,0 +1,133 @@
<?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\MemcacheSessionHandler;
/**
* @requires extension memcache
* @group time-sensitive
*/
class MemcacheSessionHandlerTest extends TestCase
{
const PREFIX = 'prefix_';
const TTL = 1000;
/**
* @var MemcacheSessionHandler
*/
protected $storage;
protected $memcache;
protected function setUp()
{
if (defined('HHVM_VERSION')) {
$this->markTestSkipped('PHPUnit_MockObject cannot mock the Memcache class on HHVM. See https://github.com/sebastianbergmann/phpunit-mock-objects/pull/289');
}
parent::setUp();
$this->memcache = $this->getMockBuilder('Memcache')->getMock();
$this->storage = new MemcacheSessionHandler(
$this->memcache,
array('prefix' => self::PREFIX, 'expiretime' => self::TTL)
);
}
protected function tearDown()
{
$this->memcache = null;
$this->storage = null;
parent::tearDown();
}
public function testOpenSession()
{
$this->assertTrue($this->storage->open('', ''));
}
public function testCloseSession()
{
$this->assertTrue($this->storage->close());
}
public function testReadSession()
{
$this->memcache
->expects($this->once())
->method('get')
->with(self::PREFIX.'id')
;
$this->assertEquals('', $this->storage->read('id'));
}
public function testWriteSession()
{
$this->memcache
->expects($this->once())
->method('set')
->with(self::PREFIX.'id', 'data', 0, $this->equalTo(time() + self::TTL, 2))
->will($this->returnValue(true))
;
$this->assertTrue($this->storage->write('id', 'data'));
}
public function testDestroySession()
{
$this->memcache
->expects($this->once())
->method('delete')
->with(self::PREFIX.'id')
->will($this->returnValue(true))
;
$this->assertTrue($this->storage->destroy('id'));
}
public function testGcSession()
{
$this->assertTrue($this->storage->gc(123));
}
/**
* @dataProvider getOptionFixtures
*/
public function testSupportedOptions($options, $supported)
{
try {
new MemcacheSessionHandler($this->memcache, $options);
$this->assertTrue($supported);
} catch (\InvalidArgumentException $e) {
$this->assertFalse($supported);
}
}
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),
);
}
public function testGetConnection()
{
$method = new \ReflectionMethod($this->storage, 'getMemcache');
$method->setAccessible(true);
$this->assertInstanceOf('\Memcache', $method->invoke($this->storage));
}
}

View File

@@ -0,0 +1,139 @@
<?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\MemcachedSessionHandler;
/**
* @requires extension memcached
* @group time-sensitive
*/
class MemcachedSessionHandlerTest extends TestCase
{
const PREFIX = 'prefix_';
const TTL = 1000;
/**
* @var MemcachedSessionHandler
*/
protected $storage;
protected $memcached;
protected function setUp()
{
if (defined('HHVM_VERSION')) {
$this->markTestSkipped('PHPUnit_MockObject cannot mock the Memcached class on HHVM. See https://github.com/sebastianbergmann/phpunit-mock-objects/pull/289');
}
parent::setUp();
if (version_compare(phpversion('memcached'), '2.2.0', '>=') && version_compare(phpversion('memcached'), '3.0.0b1', '<')) {
$this->markTestSkipped('Tests can only be run with memcached extension 2.1.0 or lower, or 3.0.0b1 or higher');
}
$this->memcached = $this->getMockBuilder('Memcached')->getMock();
$this->storage = new MemcachedSessionHandler(
$this->memcached,
array('prefix' => self::PREFIX, 'expiretime' => self::TTL)
);
}
protected function tearDown()
{
$this->memcached = null;
$this->storage = null;
parent::tearDown();
}
public function testOpenSession()
{
$this->assertTrue($this->storage->open('', ''));
}
public function testCloseSession()
{
$this->assertTrue($this->storage->close());
}
public function testReadSession()
{
$this->memcached
->expects($this->once())
->method('get')
->with(self::PREFIX.'id')
;
$this->assertEquals('', $this->storage->read('id'));
}
public function testWriteSession()
{
$this->memcached
->expects($this->once())
->method('set')
->with(self::PREFIX.'id', 'data', $this->equalTo(time() + self::TTL, 2))
->will($this->returnValue(true))
;
$this->assertTrue($this->storage->write('id', 'data'));
}
public function testDestroySession()
{
$this->memcached
->expects($this->once())
->method('delete')
->with(self::PREFIX.'id')
->will($this->returnValue(true))
;
$this->assertTrue($this->storage->destroy('id'));
}
public function testGcSession()
{
$this->assertTrue($this->storage->gc(123));
}
/**
* @dataProvider getOptionFixtures
*/
public function testSupportedOptions($options, $supported)
{
try {
new MemcachedSessionHandler($this->memcached, $options);
$this->assertTrue($supported);
} catch (\InvalidArgumentException $e) {
$this->assertFalse($supported);
}
}
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),
);
}
public function testGetConnection()
{
$method = new \ReflectionMethod($this->storage, 'getMemcached');
$method->setAccessible(true);
$this->assertInstanceOf('\Memcached', $method->invoke($this->storage));
}
}

View File

@@ -0,0 +1,332 @@
<?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\MongoDbSessionHandler;
/**
* @author Markus Bachmann <markus.bachmann@bachi.biz>
* @group time-sensitive
*/
class MongoDbSessionHandlerTest extends TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
private $mongo;
private $storage;
public $options;
protected function setUp()
{
parent::setUp();
if (extension_loaded('mongodb')) {
if (!class_exists('MongoDB\Client')) {
$this->markTestSkipped('The mongodb/mongodb package is required.');
}
} elseif (!extension_loaded('mongo')) {
$this->markTestSkipped('The Mongo or MongoDB extension is required.');
}
if (phpversion('mongodb')) {
$mongoClass = 'MongoDB\Client';
} else {
$mongoClass = version_compare(phpversion('mongo'), '1.3.0', '<') ? 'Mongo' : 'MongoClient';
}
$this->mongo = $this->getMockBuilder($mongoClass)
->disableOriginalConstructor()
->getMock();
$this->options = array(
'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()
{
new MongoDbSessionHandler(new \stdClass(), $this->options);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testConstructorShouldThrowExceptionForMissingOptions()
{
new MongoDbSessionHandler($this->mongo, array());
}
public function testOpenMethodAlwaysReturnTrue()
{
$this->assertTrue($this->storage->open('test', 'test'), 'The "open" method should always return true');
}
public function testCloseMethodAlwaysReturnTrue()
{
$this->assertTrue($this->storage->close(), 'The "close" method should always return true');
}
public function testRead()
{
$collection = $this->createMongoCollectionMock();
$this->mongo->expects($this->once())
->method('selectCollection')
->with($this->options['database'], $this->options['collection'])
->will($this->returnValue($collection));
// defining the timeout before the actual method call
// allows to test for "greater than" values in the $criteria
$testTimeout = time() + 1;
$collection->expects($this->once())
->method('findOne')
->will($this->returnCallback(function ($criteria) use ($testTimeout) {
$this->assertArrayHasKey($this->options['id_field'], $criteria);
$this->assertEquals($criteria[$this->options['id_field']], 'foo');
$this->assertArrayHasKey($this->options['expiry_field'], $criteria);
$this->assertArrayHasKey('$gte', $criteria[$this->options['expiry_field']]);
if (phpversion('mongodb')) {
$this->assertInstanceOf('MongoDB\BSON\UTCDateTime', $criteria[$this->options['expiry_field']]['$gte']);
$this->assertGreaterThanOrEqual(round((string) $criteria[$this->options['expiry_field']]['$gte'] / 1000), $testTimeout);
} else {
$this->assertInstanceOf('MongoDate', $criteria[$this->options['expiry_field']]['$gte']);
$this->assertGreaterThanOrEqual($criteria[$this->options['expiry_field']]['$gte']->sec, $testTimeout);
}
$fields = array(
$this->options['id_field'] => 'foo',
);
if (phpversion('mongodb')) {
$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[$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'));
}
public function testWrite()
{
$collection = $this->createMongoCollectionMock();
$this->mongo->expects($this->once())
->method('selectCollection')
->with($this->options['database'], $this->options['collection'])
->will($this->returnValue($collection));
$data = array();
$methodName = phpversion('mongodb') ? 'updateOne' : 'update';
$collection->expects($this->once())
->method($methodName)
->will($this->returnCallback(function ($criteria, $updateData, $options) use (&$data) {
$this->assertEquals(array($this->options['id_field'] => 'foo'), $criteria);
if (phpversion('mongodb')) {
$this->assertEquals(array('upsert' => true), $options);
} else {
$this->assertEquals(array('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')) {
$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 {
$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(
'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);
$collection = $this->createMongoCollectionMock();
$this->mongo->expects($this->once())
->method('selectCollection')
->with($this->options['database'], $this->options['collection'])
->will($this->returnValue($collection));
$data = array();
$methodName = phpversion('mongodb') ? 'updateOne' : 'update';
$collection->expects($this->once())
->method($methodName)
->will($this->returnCallback(function ($criteria, $updateData, $options) use (&$data) {
$this->assertEquals(array($this->options['id_field'] => 'foo'), $criteria);
if (phpversion('mongodb')) {
$this->assertEquals(array('upsert' => true), $options);
} else {
$this->assertEquals(array('upsert' => true, 'multiple' => false), $options);
}
$data = $updateData['$set'];
}));
$this->assertTrue($this->storage->write('foo', 'bar'));
if (phpversion('mongodb')) {
$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 {
$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']]);
}
}
public function testReplaceSessionData()
{
$collection = $this->createMongoCollectionMock();
$this->mongo->expects($this->once())
->method('selectCollection')
->with($this->options['database'], $this->options['collection'])
->will($this->returnValue($collection));
$data = array();
$methodName = phpversion('mongodb') ? 'updateOne' : 'update';
$collection->expects($this->exactly(2))
->method($methodName)
->will($this->returnCallback(function ($criteria, $updateData, $options) use (&$data) {
$data = $updateData;
}));
$this->storage->write('foo', 'bar');
$this->storage->write('foo', 'foobar');
if (phpversion('mongodb')) {
$this->assertEquals('foobar', $data['$set'][$this->options['data_field']]->getData());
} else {
$this->assertEquals('foobar', $data['$set'][$this->options['data_field']]->bin);
}
}
public function testDestroy()
{
$collection = $this->createMongoCollectionMock();
$this->mongo->expects($this->once())
->method('selectCollection')
->with($this->options['database'], $this->options['collection'])
->will($this->returnValue($collection));
$methodName = phpversion('mongodb') ? 'deleteOne' : 'remove';
$collection->expects($this->once())
->method($methodName)
->with(array($this->options['id_field'] => 'foo'));
$this->assertTrue($this->storage->destroy('foo'));
}
public function testGc()
{
$collection = $this->createMongoCollectionMock();
$this->mongo->expects($this->once())
->method('selectCollection')
->with($this->options['database'], $this->options['collection'])
->will($this->returnValue($collection));
$methodName = phpversion('mongodb') ? 'deleteOne' : 'remove';
$collection->expects($this->once())
->method($methodName)
->will($this->returnCallback(function ($criteria) {
if (phpversion('mongodb')) {
$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 {
$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));
}
public function testGetConnection()
{
$method = new \ReflectionMethod($this->storage, 'getMongo');
$method->setAccessible(true);
if (phpversion('mongodb')) {
$mongoClass = 'MongoDB\Client';
} else {
$mongoClass = version_compare(phpversion('mongo'), '1.3.0', '<') ? 'Mongo' : 'MongoClient';
}
$this->assertInstanceOf($mongoClass, $method->invoke($this->storage));
}
private function createMongoCollectionMock()
{
$collectionClass = 'MongoCollection';
if (phpversion('mongodb')) {
$collectionClass = 'MongoDB\Collection';
}
$collection = $this->getMockBuilder($collectionClass)
->disableOriginalConstructor()
->getMock();
return $collection;
}
}

View File

@@ -0,0 +1,77 @@
<?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\NativeFileSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
/**
* Test class for NativeFileSessionHandler.
*
* @author Drak <drak@zikula.org>
*
* @runTestsInSeparateProcesses
* @preserveGlobalState disabled
*/
class NativeFileSessionHandlerTest extends TestCase
{
public function testConstruct()
{
$storage = new NativeSessionStorage(array('name' => 'TESTING'), new NativeFileSessionHandler(sys_get_temp_dir()));
$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'));
}
/**
* @dataProvider savePathDataProvider
*/
public function testConstructSavePath($savePath, $expectedSavePath, $path)
{
$handler = new NativeFileSessionHandler($savePath);
$this->assertEquals($expectedSavePath, ini_get('session.save_path'));
$this->assertTrue(is_dir(realpath($path)));
rmdir($path);
}
public function savePathDataProvider()
{
$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"),
);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testConstructException()
{
$handler = 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());
$this->assertEquals($path, ini_get('session.save_path'));
}
}

View File

@@ -0,0 +1,34 @@
<?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\NativeSessionHandler;
/**
* Test class for NativeSessionHandler.
*
* @author Drak <drak@zikula.org>
*
* @runTestsInSeparateProcesses
* @preserveGlobalState disabled
*/
class NativeSessionHandlerTest extends TestCase
{
public function testConstruct()
{
$handler = new NativeSessionHandler();
$this->assertTrue($handler instanceof \SessionHandler);
$this->assertTrue($handler instanceof NativeSessionHandler);
}
}

View File

@@ -0,0 +1,59 @@
<?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\NullSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
use Symfony\Component\HttpFoundation\Session\Session;
/**
* Test class for NullSessionHandler.
*
* @author Drak <drak@zikula.org>
*
* @runTestsInSeparateProcesses
* @preserveGlobalState disabled
*/
class NullSessionHandlerTest extends TestCase
{
public function testSaveHandlers()
{
$storage = $this->getStorage();
$this->assertEquals('user', ini_get('session.save_handler'));
}
public function testSession()
{
session_id('nullsessionstorage');
$storage = $this->getStorage();
$session = new Session($storage);
$this->assertNull($session->get('something'));
$session->set('something', 'unique');
$this->assertEquals('unique', $session->get('something'));
}
public function testNothingIsPersisted()
{
session_id('nullsessionstorage');
$storage = $this->getStorage();
$session = new Session($storage);
$session->start();
$this->assertEquals('nullsessionstorage', $session->getId());
$this->assertNull($session->get('something'));
}
public function getStorage()
{
return new NativeSessionStorage(array(), new NullSessionHandler());
}
}

View File

@@ -0,0 +1,370 @@
<?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\PdoSessionHandler;
/**
* @requires extension pdo_sqlite
* @group time-sensitive
*/
class PdoSessionHandlerTest extends TestCase
{
private $dbFile;
protected function tearDown()
{
// make sure the temporary database file is deleted when it has been created (even when a test fails)
if ($this->dbFile) {
@unlink($this->dbFile);
}
parent::tearDown();
}
protected function getPersistentSqliteDsn()
{
$this->dbFile = tempnam(sys_get_temp_dir(), 'sf2_sqlite_sessions');
return 'sqlite:'.$this->dbFile;
}
protected function getMemorySqlitePdo()
{
$pdo = new \PDO('sqlite::memory:');
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$storage = new PdoSessionHandler($pdo);
$storage->createTable();
return $pdo;
}
/**
* @expectedException \InvalidArgumentException
*/
public function testWrongPdoErrMode()
{
$pdo = $this->getMemorySqlitePdo();
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_SILENT);
$storage = new PdoSessionHandler($pdo);
}
/**
* @expectedException \RuntimeException
*/
public function testInexistentTable()
{
$storage = new PdoSessionHandler($this->getMemorySqlitePdo(), array('db_table' => 'inexistent_table'));
$storage->open('', 'sid');
$storage->read('id');
$storage->write('id', 'data');
$storage->close();
}
/**
* @expectedException \RuntimeException
*/
public function testCreateTableTwice()
{
$storage = new PdoSessionHandler($this->getMemorySqlitePdo());
$storage->createTable();
}
public function testWithLazyDsnConnection()
{
$dsn = $this->getPersistentSqliteDsn();
$storage = new PdoSessionHandler($dsn);
$storage->createTable();
$storage->open('', 'sid');
$data = $storage->read('id');
$storage->write('id', 'data');
$storage->close();
$this->assertSame('', $data, 'New session returns empty string data');
$storage->open('', 'sid');
$data = $storage->read('id');
$storage->close();
$this->assertSame('data', $data, 'Written value can be read back correctly');
}
public function testWithLazySavePathConnection()
{
$dsn = $this->getPersistentSqliteDsn();
// Open is called with what ini_set('session.save_path', $dsn) would mean
$storage = new PdoSessionHandler(null);
$storage->open($dsn, 'sid');
$storage->createTable();
$data = $storage->read('id');
$storage->write('id', 'data');
$storage->close();
$this->assertSame('', $data, 'New session returns empty string data');
$storage->open($dsn, 'sid');
$data = $storage->read('id');
$storage->close();
$this->assertSame('data', $data, 'Written value can be read back correctly');
}
public function testReadWriteReadWithNullByte()
{
$sessionData = 'da'."\0".'ta';
$storage = new PdoSessionHandler($this->getMemorySqlitePdo());
$storage->open('', 'sid');
$readData = $storage->read('id');
$storage->write('id', $sessionData);
$storage->close();
$this->assertSame('', $readData, 'New session returns empty string data');
$storage->open('', 'sid');
$readData = $storage->read('id');
$storage->close();
$this->assertSame($sessionData, $readData, 'Written value can be read back correctly');
}
public function testReadConvertsStreamToString()
{
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');
}
$pdo = new MockPdo('pgsql');
$pdo->prepareResult = $this->getMockBuilder('PDOStatement')->getMock();
$content = 'foobar';
$stream = $this->createStream($content);
$pdo->prepareResult->expects($this->once())->method('fetchAll')
->will($this->returnValue(array(array($stream, 42, time()))));
$storage = new PdoSessionHandler($pdo);
$result = $storage->read('foo');
$this->assertSame($content, $result);
}
public function testReadLockedConvertsStreamToString()
{
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');
}
$pdo = new MockPdo('pgsql');
$selectStmt = $this->getMockBuilder('PDOStatement')->getMock();
$insertStmt = $this->getMockBuilder('PDOStatement')->getMock();
$pdo->prepareResult = function ($statement) use ($selectStmt, $insertStmt) {
return 0 === strpos($statement, 'INSERT') ? $insertStmt : $selectStmt;
};
$content = 'foobar';
$stream = $this->createStream($content);
$exception = null;
$selectStmt->expects($this->atLeast(2))->method('fetchAll')
->will($this->returnCallback(function () use (&$exception, $stream) {
return $exception ? array(array($stream, 42, time())) : array();
}));
$insertStmt->expects($this->once())->method('execute')
->will($this->returnCallback(function () use (&$exception) {
throw $exception = new \PDOException('', '23');
}));
$storage = new PdoSessionHandler($pdo);
$result = $storage->read('foo');
$this->assertSame($content, $result);
}
public function testReadingRequiresExactlySameId()
{
$storage = new PdoSessionHandler($this->getMemorySqlitePdo());
$storage->open('', 'sid');
$storage->write('id', 'data');
$storage->write('test', 'data');
$storage->write('space ', 'data');
$storage->close();
$storage->open('', 'sid');
$readDataCaseSensitive = $storage->read('ID');
$readDataNoCharFolding = $storage->read('tést');
$readDataKeepSpace = $storage->read('space ');
$readDataExtraSpace = $storage->read('space ');
$storage->close();
$this->assertSame('', $readDataCaseSensitive, 'Retrieval by ID should be case-sensitive (collation setting)');
$this->assertSame('', $readDataNoCharFolding, 'Retrieval by ID should not do character folding (collation setting)');
$this->assertSame('data', $readDataKeepSpace, 'Retrieval by ID requires spaces as-is');
$this->assertSame('', $readDataExtraSpace, 'Retrieval by ID requires spaces as-is');
}
/**
* Simulates session_regenerate_id(true) which will require an INSERT or UPDATE (replace).
*/
public function testWriteDifferentSessionIdThanRead()
{
$storage = new PdoSessionHandler($this->getMemorySqlitePdo());
$storage->open('', 'sid');
$storage->read('id');
$storage->destroy('id');
$storage->write('new_id', 'data_of_new_session_id');
$storage->close();
$storage->open('', 'sid');
$data = $storage->read('new_id');
$storage->close();
$this->assertSame('data_of_new_session_id', $data, 'Data of regenerated session id is available');
}
public function testWrongUsageStillWorks()
{
// wrong method sequence that should no happen, but still works
$storage = new PdoSessionHandler($this->getMemorySqlitePdo());
$storage->write('id', 'data');
$storage->write('other_id', 'other_data');
$storage->destroy('inexistent');
$storage->open('', 'sid');
$data = $storage->read('id');
$otherData = $storage->read('other_id');
$storage->close();
$this->assertSame('data', $data);
$this->assertSame('other_data', $otherData);
}
public function testSessionDestroy()
{
$pdo = $this->getMemorySqlitePdo();
$storage = new PdoSessionHandler($pdo);
$storage->open('', 'sid');
$storage->read('id');
$storage->write('id', 'data');
$storage->close();
$this->assertEquals(1, $pdo->query('SELECT COUNT(*) FROM sessions')->fetchColumn());
$storage->open('', 'sid');
$storage->read('id');
$storage->destroy('id');
$storage->close();
$this->assertEquals(0, $pdo->query('SELECT COUNT(*) FROM sessions')->fetchColumn());
$storage->open('', 'sid');
$data = $storage->read('id');
$storage->close();
$this->assertSame('', $data, 'Destroyed session returns empty string');
}
public function testSessionGC()
{
$previousLifeTime = ini_set('session.gc_maxlifetime', 1000);
$pdo = $this->getMemorySqlitePdo();
$storage = new PdoSessionHandler($pdo);
$storage->open('', 'sid');
$storage->read('id');
$storage->write('id', 'data');
$storage->close();
$storage->open('', 'sid');
$storage->read('gc_id');
ini_set('session.gc_maxlifetime', -1); // test that you can set lifetime of a session after it has been read
$storage->write('gc_id', 'data');
$storage->close();
$this->assertEquals(2, $pdo->query('SELECT COUNT(*) FROM sessions')->fetchColumn(), 'No session pruned because gc not called');
$storage->open('', 'sid');
$data = $storage->read('gc_id');
$storage->gc(-1);
$storage->close();
ini_set('session.gc_maxlifetime', $previousLifeTime);
$this->assertSame('', $data, 'Session already considered garbage, so not returning data even if it is not pruned yet');
$this->assertEquals(1, $pdo->query('SELECT COUNT(*) FROM sessions')->fetchColumn(), 'Expired session is pruned');
}
public function testGetConnection()
{
$storage = new PdoSessionHandler($this->getMemorySqlitePdo());
$method = new \ReflectionMethod($storage, 'getConnection');
$method->setAccessible(true);
$this->assertInstanceOf('\PDO', $method->invoke($storage));
}
public function testGetConnectionConnectsIfNeeded()
{
$storage = new PdoSessionHandler('sqlite::memory:');
$method = new \ReflectionMethod($storage, 'getConnection');
$method->setAccessible(true);
$this->assertInstanceOf('\PDO', $method->invoke($storage));
}
private function createStream($content)
{
$stream = tmpfile();
fwrite($stream, $content);
fseek($stream, 0);
return $stream;
}
}
class MockPdo extends \PDO
{
public $prepareResult;
private $driverName;
private $errorMode;
public function __construct($driverName = null, $errorMode = null)
{
$this->driverName = $driverName;
$this->errorMode = null !== $errorMode ?: \PDO::ERRMODE_EXCEPTION;
}
public function getAttribute($attribute)
{
if (\PDO::ATTR_ERRMODE === $attribute) {
return $this->errorMode;
}
if (\PDO::ATTR_DRIVER_NAME === $attribute) {
return $this->driverName;
}
return parent::getAttribute($attribute);
}
public function prepare($statement, $driverOptions = array())
{
return is_callable($this->prepareResult)
? call_user_func($this->prepareResult, $statement, $driverOptions)
: $this->prepareResult;
}
public function beginTransaction()
{
}
public function rollBack()
{
}
}

View File

@@ -0,0 +1,95 @@
<?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\WriteCheckSessionHandler;
/**
* @author Adrien Brault <adrien.brault@gmail.com>
*/
class WriteCheckSessionHandlerTest extends TestCase
{
public function test()
{
$wrappedSessionHandlerMock = $this->getMockBuilder('SessionHandlerInterface')->getMock();
$writeCheckSessionHandler = new WriteCheckSessionHandler($wrappedSessionHandlerMock);
$wrappedSessionHandlerMock
->expects($this->once())
->method('close')
->with()
->will($this->returnValue(true))
;
$this->assertTrue($writeCheckSessionHandler->close());
}
public function testWrite()
{
$wrappedSessionHandlerMock = $this->getMockBuilder('SessionHandlerInterface')->getMock();
$writeCheckSessionHandler = new WriteCheckSessionHandler($wrappedSessionHandlerMock);
$wrappedSessionHandlerMock
->expects($this->once())
->method('write')
->with('foo', 'bar')
->will($this->returnValue(true))
;
$this->assertTrue($writeCheckSessionHandler->write('foo', 'bar'));
}
public function testSkippedWrite()
{
$wrappedSessionHandlerMock = $this->getMockBuilder('SessionHandlerInterface')->getMock();
$writeCheckSessionHandler = new WriteCheckSessionHandler($wrappedSessionHandlerMock);
$wrappedSessionHandlerMock
->expects($this->once())
->method('read')
->with('foo')
->will($this->returnValue('bar'))
;
$wrappedSessionHandlerMock
->expects($this->never())
->method('write')
;
$this->assertEquals('bar', $writeCheckSessionHandler->read('foo'));
$this->assertTrue($writeCheckSessionHandler->write('foo', 'bar'));
}
public function testNonSkippedWrite()
{
$wrappedSessionHandlerMock = $this->getMockBuilder('SessionHandlerInterface')->getMock();
$writeCheckSessionHandler = new WriteCheckSessionHandler($wrappedSessionHandlerMock);
$wrappedSessionHandlerMock
->expects($this->once())
->method('read')
->with('foo')
->will($this->returnValue('bar'))
;
$wrappedSessionHandlerMock
->expects($this->once())
->method('write')
->with('foo', 'baZZZ')
->will($this->returnValue(true))
;
$this->assertEquals('bar', $writeCheckSessionHandler->read('foo'));
$this->assertTrue($writeCheckSessionHandler->write('foo', 'baZZZ'));
}
}

View File

@@ -0,0 +1,142 @@
<?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;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Storage\MetadataBag;
/**
* Test class for MetadataBag.
*
* @group time-sensitive
*/
class MetadataBagTest extends TestCase
{
/**
* @var MetadataBag
*/
protected $bag;
/**
* @var array
*/
protected $array = array();
protected function setUp()
{
parent::setUp();
$this->bag = new MetadataBag();
$this->array = array(MetadataBag::CREATED => 1234567, MetadataBag::UPDATED => 12345678, MetadataBag::LIFETIME => 0);
$this->bag->initialize($this->array);
}
protected function tearDown()
{
$this->array = array();
$this->bag = null;
parent::tearDown();
}
public function testInitialize()
{
$sessionMetadata = array();
$bag1 = new MetadataBag();
$bag1->initialize($sessionMetadata);
$this->assertGreaterThanOrEqual(time(), $bag1->getCreated());
$this->assertEquals($bag1->getCreated(), $bag1->getLastUsed());
sleep(1);
$bag2 = new MetadataBag();
$bag2->initialize($sessionMetadata);
$this->assertEquals($bag1->getCreated(), $bag2->getCreated());
$this->assertEquals($bag1->getLastUsed(), $bag2->getLastUsed());
$this->assertEquals($bag2->getCreated(), $bag2->getLastUsed());
sleep(1);
$bag3 = new MetadataBag();
$bag3->initialize($sessionMetadata);
$this->assertEquals($bag1->getCreated(), $bag3->getCreated());
$this->assertGreaterThan($bag2->getLastUsed(), $bag3->getLastUsed());
$this->assertNotEquals($bag3->getCreated(), $bag3->getLastUsed());
}
public function testGetSetName()
{
$this->assertEquals('__metadata', $this->bag->getName());
$this->bag->setName('foo');
$this->assertEquals('foo', $this->bag->getName());
}
public function testGetStorageKey()
{
$this->assertEquals('_sf2_meta', $this->bag->getStorageKey());
}
public function testGetLifetime()
{
$bag = new MetadataBag();
$array = array(MetadataBag::CREATED => 1234567, MetadataBag::UPDATED => 12345678, MetadataBag::LIFETIME => 1000);
$bag->initialize($array);
$this->assertEquals(1000, $bag->getLifetime());
}
public function testGetCreated()
{
$this->assertEquals(1234567, $this->bag->getCreated());
}
public function testGetLastUsed()
{
$this->assertLessThanOrEqual(time(), $this->bag->getLastUsed());
}
public function testClear()
{
$this->bag->clear();
// the clear method has no side effects, we just want to ensure it doesn't trigger any exceptions
$this->addToAssertionCount(1);
}
public function testSkipLastUsedUpdate()
{
$bag = new MetadataBag('', 30);
$timeStamp = time();
$created = $timeStamp - 15;
$sessionMetadata = array(
MetadataBag::CREATED => $created,
MetadataBag::UPDATED => $created,
MetadataBag::LIFETIME => 1000,
);
$bag->initialize($sessionMetadata);
$this->assertEquals($created, $sessionMetadata[MetadataBag::UPDATED]);
}
public function testDoesNotSkipLastUsedUpdate()
{
$bag = new MetadataBag('', 30);
$timeStamp = time();
$created = $timeStamp - 45;
$sessionMetadata = array(
MetadataBag::CREATED => $created,
MetadataBag::UPDATED => $created,
MetadataBag::LIFETIME => 1000,
);
$bag->initialize($sessionMetadata);
$this->assertEquals($timeStamp, $sessionMetadata[MetadataBag::UPDATED]);
}
}

View File

@@ -0,0 +1,131 @@
<?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;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
/**
* Test class for MockArraySessionStorage.
*
* @author Drak <drak@zikula.org>
*/
class MockArraySessionStorageTest extends TestCase
{
/**
* @var MockArraySessionStorage
*/
private $storage;
/**
* @var AttributeBag
*/
private $attributes;
/**
* @var FlashBag
*/
private $flashes;
private $data;
protected function setUp()
{
$this->attributes = new AttributeBag();
$this->flashes = new FlashBag();
$this->data = array(
$this->attributes->getStorageKey() => array('foo' => 'bar'),
$this->flashes->getStorageKey() => array('notice' => 'hello'),
);
$this->storage = new MockArraySessionStorage();
$this->storage->registerBag($this->flashes);
$this->storage->registerBag($this->attributes);
$this->storage->setSessionData($this->data);
}
protected function tearDown()
{
$this->data = null;
$this->flashes = null;
$this->attributes = null;
$this->storage = null;
}
public function testStart()
{
$this->assertEquals('', $this->storage->getId());
$this->storage->start();
$id = $this->storage->getId();
$this->assertNotEquals('', $id);
$this->storage->start();
$this->assertEquals($id, $this->storage->getId());
}
public function testRegenerate()
{
$this->storage->start();
$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());
$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());
}
public function testGetId()
{
$this->assertEquals('', $this->storage->getId());
$this->storage->start();
$this->assertNotEquals('', $this->storage->getId());
}
public function testClearClearsBags()
{
$this->storage->clear();
$this->assertSame(array(), $this->storage->getBag('attributes')->all());
$this->assertSame(array(), $this->storage->getBag('flashes')->peekAll());
}
public function testClearStartsSession()
{
$this->storage->clear();
$this->assertTrue($this->storage->isStarted());
}
public function testClearWithNoBagsStartsSession()
{
$storage = new MockArraySessionStorage();
$storage->clear();
$this->assertTrue($storage->isStarted());
}
/**
* @expectedException \RuntimeException
*/
public function testUnstartedSave()
{
$this->storage->save();
}
}

View File

@@ -0,0 +1,127 @@
<?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;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
/**
* Test class for MockFileSessionStorage.
*
* @author Drak <drak@zikula.org>
*/
class MockFileSessionStorageTest extends TestCase
{
/**
* @var string
*/
private $sessionDir;
/**
* @var MockFileSessionStorage
*/
protected $storage;
protected function setUp()
{
$this->sessionDir = sys_get_temp_dir().'/sf2test';
$this->storage = $this->getStorage();
}
protected function tearDown()
{
$this->sessionDir = null;
$this->storage = null;
array_map('unlink', glob($this->sessionDir.'/*.session'));
if (is_dir($this->sessionDir)) {
rmdir($this->sessionDir);
}
}
public function testStart()
{
$this->assertEquals('', $this->storage->getId());
$this->assertTrue($this->storage->start());
$id = $this->storage->getId();
$this->assertNotEquals('', $this->storage->getId());
$this->assertTrue($this->storage->start());
$this->assertEquals($id, $this->storage->getId());
}
public function testRegenerate()
{
$this->storage->start();
$this->storage->getBag('attributes')->set('regenerate', 1234);
$this->storage->regenerate();
$this->assertEquals(1234, $this->storage->getBag('attributes')->get('regenerate'));
$this->storage->regenerate(true);
$this->assertEquals(1234, $this->storage->getBag('attributes')->get('regenerate'));
}
public function testGetId()
{
$this->assertEquals('', $this->storage->getId());
$this->storage->start();
$this->assertNotEquals('', $this->storage->getId());
}
public function testSave()
{
$this->storage->start();
$id = $this->storage->getId();
$this->assertNotEquals('108', $this->storage->getBag('attributes')->get('new'));
$this->assertFalse($this->storage->getBag('flashes')->has('newkey'));
$this->storage->getBag('attributes')->set('new', '108');
$this->storage->getBag('flashes')->set('newkey', 'test');
$this->storage->save();
$storage = $this->getStorage();
$storage->setId($id);
$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'));
}
public function testMultipleInstances()
{
$storage1 = $this->getStorage();
$storage1->start();
$storage1->getBag('attributes')->set('foo', 'bar');
$storage1->save();
$storage2 = $this->getStorage();
$storage2->setId($storage1->getId());
$storage2->start();
$this->assertEquals('bar', $storage2->getBag('attributes')->get('foo'), 'values persist between instances');
}
/**
* @expectedException \RuntimeException
*/
public function testSaveWithoutStart()
{
$storage1 = $this->getStorage();
$storage1->save();
}
private function getStorage()
{
$storage = new MockFileSessionStorage($this->sessionDir);
$storage->registerBag(new FlashBag());
$storage->registerBag(new AttributeBag());
return $storage;
}
}

View File

@@ -0,0 +1,247 @@
<?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;
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\NullSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy;
/**
* Test class for NativeSessionStorage.
*
* @author Drak <drak@zikula.org>
*
* These tests require separate processes.
*
* @runTestsInSeparateProcesses
* @preserveGlobalState disabled
*/
class NativeSessionStorageTest extends TestCase
{
private $savePath;
protected function setUp()
{
$this->iniSet('session.save_handler', 'files');
$this->iniSet('session.save_path', $this->savePath = sys_get_temp_dir().'/sf2test');
if (!is_dir($this->savePath)) {
mkdir($this->savePath);
}
}
protected function tearDown()
{
session_write_close();
array_map('unlink', glob($this->savePath.'/*'));
if (is_dir($this->savePath)) {
rmdir($this->savePath);
}
$this->savePath = null;
}
/**
* @param array $options
*
* @return NativeSessionStorage
*/
protected function getStorage(array $options = array())
{
$storage = new NativeSessionStorage($options);
$storage->registerBag(new AttributeBag());
return $storage;
}
public function testBag()
{
$storage = $this->getStorage();
$bag = new FlashBag();
$storage->registerBag($bag);
$this->assertSame($bag, $storage->getBag($bag->getName()));
}
/**
* @expectedException \InvalidArgumentException
*/
public function testRegisterBagException()
{
$storage = $this->getStorage();
$storage->getBag('non_existing');
}
/**
* @expectedException \LogicException
*/
public function testRegisterBagForAStartedSessionThrowsException()
{
$storage = $this->getStorage();
$storage->start();
$storage->registerBag(new AttributeBag());
}
public function testGetId()
{
$storage = $this->getStorage();
$this->assertSame('', $storage->getId(), 'Empty ID before starting session');
$storage->start();
$id = $storage->getId();
$this->assertInternalType('string', $id);
$this->assertNotSame('', $id);
$storage->save();
$this->assertSame($id, $storage->getId(), 'ID stays after saving session');
}
public function testRegenerate()
{
$storage = $this->getStorage();
$storage->start();
$id = $storage->getId();
$storage->getBag('attributes')->set('lucky', 7);
$storage->regenerate();
$this->assertNotEquals($id, $storage->getId());
$this->assertEquals(7, $storage->getBag('attributes')->get('lucky'));
}
public function testRegenerateDestroy()
{
$storage = $this->getStorage();
$storage->start();
$id = $storage->getId();
$storage->getBag('attributes')->set('legs', 11);
$storage->regenerate(true);
$this->assertNotEquals($id, $storage->getId());
$this->assertEquals(11, $storage->getBag('attributes')->get('legs'));
}
public function testSessionGlobalIsUpToDateAfterIdRegeneration()
{
$storage = $this->getStorage();
$storage->start();
$storage->getBag('attributes')->set('lucky', 7);
$storage->regenerate();
$storage->getBag('attributes')->set('lucky', 42);
$this->assertEquals(42, $_SESSION['_sf2_attributes']['lucky']);
}
public function testRegenerationFailureDoesNotFlagStorageAsStarted()
{
$storage = $this->getStorage();
$this->assertFalse($storage->regenerate());
$this->assertFalse($storage->isStarted());
}
public function testDefaultSessionCacheLimiter()
{
$this->iniSet('session.cache_limiter', 'nocache');
$storage = new NativeSessionStorage();
$this->assertEquals('', ini_get('session.cache_limiter'));
}
public function testExplicitSessionCacheLimiter()
{
$this->iniSet('session.cache_limiter', 'nocache');
$storage = new NativeSessionStorage(array('cache_limiter' => 'public'));
$this->assertEquals('public', ini_get('session.cache_limiter'));
}
public function testCookieOptions()
{
$options = array(
'cookie_lifetime' => 123456,
'cookie_path' => '/my/cookie/path',
'cookie_domain' => 'symfony.example.com',
'cookie_secure' => true,
'cookie_httponly' => false,
);
$this->getStorage($options);
$temp = session_get_cookie_params();
$gco = array();
foreach ($temp as $key => $value) {
$gco['cookie_'.$key] = $value;
}
$this->assertEquals($options, $gco);
}
/**
* @expectedException \InvalidArgumentException
*/
public function testSetSaveHandlerException()
{
$storage = $this->getStorage();
$storage->setSaveHandler(new \stdClass());
}
public function testSetSaveHandler()
{
$this->iniSet('session.save_handler', 'files');
$storage = $this->getStorage();
$storage->setSaveHandler();
$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()));
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
$storage->setSaveHandler(new NativeSessionHandler());
$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());
$storage->setSaveHandler(new NullSessionHandler());
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
}
/**
* @expectedException \RuntimeException
*/
public function testStarted()
{
$storage = $this->getStorage();
$this->assertFalse($storage->getSaveHandler()->isActive());
$this->assertFalse($storage->isStarted());
session_start();
$this->assertTrue(isset($_SESSION));
$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());
$key = $storage->getMetadataBag()->getStorageKey();
$this->assertFalse(isset($_SESSION[$key]));
$storage->start();
}
public function testRestart()
{
$storage = $this->getStorage();
$storage->start();
$id = $storage->getId();
$storage->getBag('attributes')->set('lucky', 7);
$storage->save();
$storage->start();
$this->assertSame($id, $storage->getId(), 'Same session ID after restarting');
$this->assertSame(7, $storage->getBag('attributes')->get('lucky'), 'Data still available');
}
}

View File

@@ -0,0 +1,96 @@
<?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;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
/**
* Test class for PhpSessionStorage.
*
* @author Drak <drak@zikula.org>
*
* These tests require separate processes.
*
* @runTestsInSeparateProcesses
* @preserveGlobalState disabled
*/
class PhpBridgeSessionStorageTest extends TestCase
{
private $savePath;
protected function setUp()
{
$this->iniSet('session.save_handler', 'files');
$this->iniSet('session.save_path', $this->savePath = sys_get_temp_dir().'/sf2test');
if (!is_dir($this->savePath)) {
mkdir($this->savePath);
}
}
protected function tearDown()
{
session_write_close();
array_map('unlink', glob($this->savePath.'/*'));
if (is_dir($this->savePath)) {
rmdir($this->savePath);
}
$this->savePath = null;
}
/**
* @return PhpBridgeSessionStorage
*/
protected function getStorage()
{
$storage = new PhpBridgeSessionStorage();
$storage->registerBag(new AttributeBag());
return $storage;
}
public function testPhpSession()
{
$storage = $this->getStorage();
$this->assertFalse($storage->getSaveHandler()->isActive());
$this->assertFalse($storage->isStarted());
session_start();
$this->assertTrue(isset($_SESSION));
// in PHP 5.4 we can reliably detect a session started
$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());
$key = $storage->getMetadataBag()->getStorageKey();
$this->assertFalse(isset($_SESSION[$key]));
$storage->start();
$this->assertTrue(isset($_SESSION[$key]));
}
public function testClear()
{
$storage = $this->getStorage();
session_start();
$_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');
$storage->clear();
$this->assertEquals($_SESSION[$key], array());
$this->assertEquals($_SESSION['drak'], 'loves symfony');
}
}

View File

@@ -0,0 +1,145 @@
<?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\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)
{
}
}
/**
* Test class for AbstractProxy.
*
* @author Drak <drak@zikula.org>
*/
class AbstractProxyTest extends TestCase
{
/**
* @var AbstractProxy
*/
protected $proxy;
protected function setUp()
{
$this->proxy = new ConcreteProxy();
}
protected function tearDown()
{
$this->proxy = null;
}
public function testGetSaveHandlerName()
{
$this->assertNull($this->proxy->getSaveHandlerName());
}
public function testIsSessionHandlerInterface()
{
$this->assertFalse($this->proxy->isSessionHandlerInterface());
$sh = new ConcreteSessionHandlerInterfaceProxy();
$this->assertTrue($sh->isSessionHandlerInterface());
}
public function testIsWrapper()
{
$this->assertFalse($this->proxy->isWrapper());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testIsActive()
{
$this->assertFalse($this->proxy->isActive());
session_start();
$this->assertTrue($this->proxy->isActive());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testName()
{
$this->assertEquals(session_name(), $this->proxy->getName());
$this->proxy->setName('foo');
$this->assertEquals('foo', $this->proxy->getName());
$this->assertEquals(session_name(), $this->proxy->getName());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
* @expectedException \LogicException
*/
public function testNameException()
{
session_start();
$this->proxy->setName('foo');
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testId()
{
$this->assertEquals(session_id(), $this->proxy->getId());
$this->proxy->setId('foo');
$this->assertEquals('foo', $this->proxy->getId());
$this->assertEquals(session_id(), $this->proxy->getId());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
* @expectedException \LogicException
*/
public function testIdException()
{
session_start();
$this->proxy->setId('foo');
}
}

View File

@@ -0,0 +1,36 @@
<?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\Proxy;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy;
/**
* Test class for NativeProxy.
*
* @author Drak <drak@zikula.org>
*/
class NativeProxyTest extends TestCase
{
public function testIsWrapper()
{
$proxy = new NativeProxy();
$this->assertFalse($proxy->isWrapper());
}
public function testGetSaveHandlerName()
{
$name = ini_get('session.save_handler');
$proxy = new NativeProxy();
$this->assertEquals($name, $proxy->getSaveHandlerName());
}
}

View File

@@ -0,0 +1,124 @@
<?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\Proxy;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy;
/**
* Tests for SessionHandlerProxy class.
*
* @author Drak <drak@zikula.org>
*
* @runTestsInSeparateProcesses
* @preserveGlobalState disabled
*/
class SessionHandlerProxyTest extends TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_Matcher
*/
private $mock;
/**
* @var SessionHandlerProxy
*/
private $proxy;
protected function setUp()
{
$this->mock = $this->getMockBuilder('SessionHandlerInterface')->getMock();
$this->proxy = new SessionHandlerProxy($this->mock);
}
protected function tearDown()
{
$this->mock = null;
$this->proxy = null;
}
public function testOpenTrue()
{
$this->mock->expects($this->once())
->method('open')
->will($this->returnValue(true));
$this->assertFalse($this->proxy->isActive());
$this->proxy->open('name', 'id');
$this->assertFalse($this->proxy->isActive());
}
public function testOpenFalse()
{
$this->mock->expects($this->once())
->method('open')
->will($this->returnValue(false));
$this->assertFalse($this->proxy->isActive());
$this->proxy->open('name', 'id');
$this->assertFalse($this->proxy->isActive());
}
public function testClose()
{
$this->mock->expects($this->once())
->method('close')
->will($this->returnValue(true));
$this->assertFalse($this->proxy->isActive());
$this->proxy->close();
$this->assertFalse($this->proxy->isActive());
}
public function testCloseFalse()
{
$this->mock->expects($this->once())
->method('close')
->will($this->returnValue(false));
$this->assertFalse($this->proxy->isActive());
$this->proxy->close();
$this->assertFalse($this->proxy->isActive());
}
public function testRead()
{
$this->mock->expects($this->once())
->method('read');
$this->proxy->read('id');
}
public function testWrite()
{
$this->mock->expects($this->once())
->method('write');
$this->proxy->write('id', 'data');
}
public function testDestroy()
{
$this->mock->expects($this->once())
->method('destroy');
$this->proxy->destroy('id');
}
public function testGc()
{
$this->mock->expects($this->once())
->method('gc');
$this->proxy->gc(86400);
}
}