diff --git a/.gitignore b/.gitignore index 51f650a97..d38435f9b 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,11 @@ # composer reserver directory, from sources, populate/update using "composer install" vendor/* test/vendor/* +# remove tests from libs (N°2651) +/lib/**/test/** +/lib/**/tests/** +/lib/**/Test/** +/lib/**/Tests/** # all datas but listing prevention /data/** diff --git a/lib/pear/pear_exception/tests/PEAR/ExceptionTest.php b/lib/pear/pear_exception/tests/PEAR/ExceptionTest.php deleted file mode 100644 index 61d2df4f1..000000000 --- a/lib/pear/pear_exception/tests/PEAR/ExceptionTest.php +++ /dev/null @@ -1,78 +0,0 @@ -assertNull($e->getCause()); - } - - public function testGetCauseException() - { - $cause = new Exception('foo bar'); - $e = new PEAR_Exception('I caught an exception', $cause); - $this->assertNotNull($e->getCause()); - $this->assertInstanceOf('Exception', $e->getCause()); - $this->assertEquals($cause, $e->getCause()); - } - - public function testGetCauseMessage() - { - $cause = new Exception('foo bar'); - $e = new PEAR_Exception('I caught an exception', $cause); - - $e->getCauseMessage($causes); - $this->assertEquals('I caught an exception', $causes[0]['message']); - $this->assertEquals('foo bar', $causes[1]['message']); - } - - public function testGetTraceSafe() - { - $e = new PEAR_Exception('oops'); - $this->assertInternalType('array', $e->getTraceSafe()); - } - - public function testGetErrorClass() - { - $e = new PEAR_Exception('oops'); - $this->assertEquals('PEAR_ExceptionTest', $e->getErrorClass()); - } - - public function testGetErrorMethod() - { - $e = new PEAR_Exception('oops'); - $this->assertEquals('testGetErrorMethod', $e->getErrorMethod()); - } - - public function test__toString() - { - $e = new PEAR_Exception('oops'); - $this->assertInternalType('string', (string) $e); - $this->assertContains('oops', (string) $e); - } - - public function testToHtml() - { - $e = new PEAR_Exception('oops'); - $html = $e->toHtml(); - $this->assertInternalType('string', $html); - $this->assertContains('oops', $html); - } -} -?> diff --git a/lib/psr/log/Psr/Log/Test/LoggerInterfaceTest.php b/lib/psr/log/Psr/Log/Test/LoggerInterfaceTest.php deleted file mode 100644 index 9ecb6c4b0..000000000 --- a/lib/psr/log/Psr/Log/Test/LoggerInterfaceTest.php +++ /dev/null @@ -1,146 +0,0 @@ - ". - * - * Example ->error('Foo') would yield "error Foo". - * - * @return string[] - */ - abstract public function getLogs(); - - public function testImplements() - { - $this->assertInstanceOf('Psr\Log\LoggerInterface', $this->getLogger()); - } - - /** - * @dataProvider provideLevelsAndMessages - */ - public function testLogsAtAllLevels($level, $message) - { - $logger = $this->getLogger(); - $logger->{$level}($message, array('user' => 'Bob')); - $logger->log($level, $message, array('user' => 'Bob')); - - $expected = array( - $level.' message of level '.$level.' with context: Bob', - $level.' message of level '.$level.' with context: Bob', - ); - $this->assertEquals($expected, $this->getLogs()); - } - - public function provideLevelsAndMessages() - { - return array( - LogLevel::EMERGENCY => array(LogLevel::EMERGENCY, 'message of level emergency with context: {user}'), - LogLevel::ALERT => array(LogLevel::ALERT, 'message of level alert with context: {user}'), - LogLevel::CRITICAL => array(LogLevel::CRITICAL, 'message of level critical with context: {user}'), - LogLevel::ERROR => array(LogLevel::ERROR, 'message of level error with context: {user}'), - LogLevel::WARNING => array(LogLevel::WARNING, 'message of level warning with context: {user}'), - LogLevel::NOTICE => array(LogLevel::NOTICE, 'message of level notice with context: {user}'), - LogLevel::INFO => array(LogLevel::INFO, 'message of level info with context: {user}'), - LogLevel::DEBUG => array(LogLevel::DEBUG, 'message of level debug with context: {user}'), - ); - } - - /** - * @expectedException \Psr\Log\InvalidArgumentException - */ - public function testThrowsOnInvalidLevel() - { - $logger = $this->getLogger(); - $logger->log('invalid level', 'Foo'); - } - - public function testContextReplacement() - { - $logger = $this->getLogger(); - $logger->info('{Message {nothing} {user} {foo.bar} a}', array('user' => 'Bob', 'foo.bar' => 'Bar')); - - $expected = array('info {Message {nothing} Bob Bar a}'); - $this->assertEquals($expected, $this->getLogs()); - } - - public function testObjectCastToString() - { - if (method_exists($this, 'createPartialMock')) { - $dummy = $this->createPartialMock('Psr\Log\Test\DummyTest', array('__toString')); - } else { - $dummy = $this->getMock('Psr\Log\Test\DummyTest', array('__toString')); - } - $dummy->expects($this->once()) - ->method('__toString') - ->will($this->returnValue('DUMMY')); - - $this->getLogger()->warning($dummy); - - $expected = array('warning DUMMY'); - $this->assertEquals($expected, $this->getLogs()); - } - - public function testContextCanContainAnything() - { - $closed = fopen('php://memory', 'r'); - fclose($closed); - - $context = array( - 'bool' => true, - 'null' => null, - 'string' => 'Foo', - 'int' => 0, - 'float' => 0.5, - 'nested' => array('with object' => new DummyTest), - 'object' => new \DateTime, - 'resource' => fopen('php://memory', 'r'), - 'closed' => $closed, - ); - - $this->getLogger()->warning('Crazy context data', $context); - - $expected = array('warning Crazy context data'); - $this->assertEquals($expected, $this->getLogs()); - } - - public function testContextExceptionKeyCanBeExceptionOrOtherValues() - { - $logger = $this->getLogger(); - $logger->warning('Random message', array('exception' => 'oops')); - $logger->critical('Uncaught Exception!', array('exception' => new \LogicException('Fail'))); - - $expected = array( - 'warning Random message', - 'critical Uncaught Exception!' - ); - $this->assertEquals($expected, $this->getLogs()); - } -} - -class DummyTest -{ - public function __toString() - { - return 'DummyTest'; - } -} diff --git a/lib/psr/log/Psr/Log/Test/TestLogger.php b/lib/psr/log/Psr/Log/Test/TestLogger.php deleted file mode 100644 index 1be323049..000000000 --- a/lib/psr/log/Psr/Log/Test/TestLogger.php +++ /dev/null @@ -1,147 +0,0 @@ - $level, - 'message' => $message, - 'context' => $context, - ]; - - $this->recordsByLevel[$record['level']][] = $record; - $this->records[] = $record; - } - - public function hasRecords($level) - { - return isset($this->recordsByLevel[$level]); - } - - public function hasRecord($record, $level) - { - if (is_string($record)) { - $record = ['message' => $record]; - } - return $this->hasRecordThatPasses(function ($rec) use ($record) { - if ($rec['message'] !== $record['message']) { - return false; - } - if (isset($record['context']) && $rec['context'] !== $record['context']) { - return false; - } - return true; - }, $level); - } - - public function hasRecordThatContains($message, $level) - { - return $this->hasRecordThatPasses(function ($rec) use ($message) { - return strpos($rec['message'], $message) !== false; - }, $level); - } - - public function hasRecordThatMatches($regex, $level) - { - return $this->hasRecordThatPasses(function ($rec) use ($regex) { - return preg_match($regex, $rec['message']) > 0; - }, $level); - } - - public function hasRecordThatPasses(callable $predicate, $level) - { - if (!isset($this->recordsByLevel[$level])) { - return false; - } - foreach ($this->recordsByLevel[$level] as $i => $rec) { - if (call_user_func($predicate, $rec, $i)) { - return true; - } - } - return false; - } - - public function __call($method, $args) - { - if (preg_match('/(.*)(Debug|Info|Notice|Warning|Error|Critical|Alert|Emergency)(.*)/', $method, $matches) > 0) { - $genericMethod = $matches[1] . ('Records' !== $matches[3] ? 'Record' : '') . $matches[3]; - $level = strtolower($matches[2]); - if (method_exists($this, $genericMethod)) { - $args[] = $level; - return call_user_func_array([$this, $genericMethod], $args); - } - } - throw new \BadMethodCallException('Call to undefined method ' . get_class($this) . '::' . $method . '()'); - } - - public function reset() - { - $this->records = []; - $this->recordsByLevel = []; - } -} diff --git a/lib/symfony/cache/Tests/Adapter/AbstractRedisAdapterTest.php b/lib/symfony/cache/Tests/Adapter/AbstractRedisAdapterTest.php deleted file mode 100644 index d1fa9535c..000000000 --- a/lib/symfony/cache/Tests/Adapter/AbstractRedisAdapterTest.php +++ /dev/null @@ -1,46 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use Symfony\Component\Cache\Adapter\RedisAdapter; - -abstract class AbstractRedisAdapterTest extends AdapterTestCase -{ - protected $skippedTests = [ - 'testExpiration' => 'Testing expiration slows down the test suite', - 'testHasItemReturnsFalseWhenDeferredItemIsExpired' => 'Testing expiration slows down the test suite', - 'testDefaultLifeTime' => 'Testing expiration slows down the test suite', - ]; - - protected static $redis; - - public function createCachePool($defaultLifetime = 0) - { - return new RedisAdapter(self::$redis, str_replace('\\', '.', __CLASS__), $defaultLifetime); - } - - public static function setUpBeforeClass() - { - if (!\extension_loaded('redis')) { - self::markTestSkipped('Extension redis required.'); - } - if (!@((new \Redis())->connect(getenv('REDIS_HOST')))) { - $e = error_get_last(); - self::markTestSkipped($e['message']); - } - } - - public static function tearDownAfterClass() - { - self::$redis = null; - } -} diff --git a/lib/symfony/cache/Tests/Adapter/AdapterTestCase.php b/lib/symfony/cache/Tests/Adapter/AdapterTestCase.php deleted file mode 100644 index 5758a2861..000000000 --- a/lib/symfony/cache/Tests/Adapter/AdapterTestCase.php +++ /dev/null @@ -1,175 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use Cache\IntegrationTests\CachePoolTest; -use Psr\Cache\CacheItemPoolInterface; -use Symfony\Component\Cache\PruneableInterface; - -abstract class AdapterTestCase extends CachePoolTest -{ - protected function setUp() - { - parent::setUp(); - - if (!\array_key_exists('testDeferredSaveWithoutCommit', $this->skippedTests) && \defined('HHVM_VERSION')) { - $this->skippedTests['testDeferredSaveWithoutCommit'] = 'Destructors are called late on HHVM.'; - } - - if (!\array_key_exists('testPrune', $this->skippedTests) && !$this->createCachePool() instanceof PruneableInterface) { - $this->skippedTests['testPrune'] = 'Not a pruneable cache pool.'; - } - } - - public function testDefaultLifeTime() - { - if (isset($this->skippedTests[__FUNCTION__])) { - $this->markTestSkipped($this->skippedTests[__FUNCTION__]); - } - - $cache = $this->createCachePool(2); - - $item = $cache->getItem('key.dlt'); - $item->set('value'); - $cache->save($item); - sleep(1); - - $item = $cache->getItem('key.dlt'); - $this->assertTrue($item->isHit()); - - sleep(2); - $item = $cache->getItem('key.dlt'); - $this->assertFalse($item->isHit()); - } - - public function testExpiration() - { - if (isset($this->skippedTests[__FUNCTION__])) { - $this->markTestSkipped($this->skippedTests[__FUNCTION__]); - } - - $cache = $this->createCachePool(); - $cache->save($cache->getItem('k1')->set('v1')->expiresAfter(2)); - $cache->save($cache->getItem('k2')->set('v2')->expiresAfter(366 * 86400)); - - sleep(3); - $item = $cache->getItem('k1'); - $this->assertFalse($item->isHit()); - $this->assertNull($item->get(), "Item's value must be null when isHit() is false."); - - $item = $cache->getItem('k2'); - $this->assertTrue($item->isHit()); - $this->assertSame('v2', $item->get()); - } - - public function testNotUnserializable() - { - if (isset($this->skippedTests[__FUNCTION__])) { - $this->markTestSkipped($this->skippedTests[__FUNCTION__]); - } - - $cache = $this->createCachePool(); - - $item = $cache->getItem('foo'); - $cache->save($item->set(new NotUnserializable())); - - $item = $cache->getItem('foo'); - $this->assertFalse($item->isHit()); - - foreach ($cache->getItems(['foo']) as $item) { - } - $cache->save($item->set(new NotUnserializable())); - - foreach ($cache->getItems(['foo']) as $item) { - } - $this->assertFalse($item->isHit()); - } - - public function testPrune() - { - if (isset($this->skippedTests[__FUNCTION__])) { - $this->markTestSkipped($this->skippedTests[__FUNCTION__]); - } - - if (!method_exists($this, 'isPruned')) { - $this->fail('Test classes for pruneable caches must implement `isPruned($cache, $name)` method.'); - } - - /** @var PruneableInterface|CacheItemPoolInterface $cache */ - $cache = $this->createCachePool(); - - $doSet = function ($name, $value, \DateInterval $expiresAfter = null) use ($cache) { - $item = $cache->getItem($name); - $item->set($value); - - if ($expiresAfter) { - $item->expiresAfter($expiresAfter); - } - - $cache->save($item); - }; - - $doSet('foo', 'foo-val', new \DateInterval('PT05S')); - $doSet('bar', 'bar-val', new \DateInterval('PT10S')); - $doSet('baz', 'baz-val', new \DateInterval('PT15S')); - $doSet('qux', 'qux-val', new \DateInterval('PT20S')); - - sleep(30); - $cache->prune(); - $this->assertTrue($this->isPruned($cache, 'foo')); - $this->assertTrue($this->isPruned($cache, 'bar')); - $this->assertTrue($this->isPruned($cache, 'baz')); - $this->assertTrue($this->isPruned($cache, 'qux')); - - $doSet('foo', 'foo-val'); - $doSet('bar', 'bar-val', new \DateInterval('PT20S')); - $doSet('baz', 'baz-val', new \DateInterval('PT40S')); - $doSet('qux', 'qux-val', new \DateInterval('PT80S')); - - $cache->prune(); - $this->assertFalse($this->isPruned($cache, 'foo')); - $this->assertFalse($this->isPruned($cache, 'bar')); - $this->assertFalse($this->isPruned($cache, 'baz')); - $this->assertFalse($this->isPruned($cache, 'qux')); - - sleep(30); - $cache->prune(); - $this->assertFalse($this->isPruned($cache, 'foo')); - $this->assertTrue($this->isPruned($cache, 'bar')); - $this->assertFalse($this->isPruned($cache, 'baz')); - $this->assertFalse($this->isPruned($cache, 'qux')); - - sleep(30); - $cache->prune(); - $this->assertFalse($this->isPruned($cache, 'foo')); - $this->assertTrue($this->isPruned($cache, 'baz')); - $this->assertFalse($this->isPruned($cache, 'qux')); - - sleep(30); - $cache->prune(); - $this->assertFalse($this->isPruned($cache, 'foo')); - $this->assertTrue($this->isPruned($cache, 'qux')); - } -} - -class NotUnserializable implements \Serializable -{ - public function serialize() - { - return serialize(123); - } - - public function unserialize($ser) - { - throw new \Exception(__CLASS__); - } -} diff --git a/lib/symfony/cache/Tests/Adapter/ApcuAdapterTest.php b/lib/symfony/cache/Tests/Adapter/ApcuAdapterTest.php deleted file mode 100644 index 5cca73f56..000000000 --- a/lib/symfony/cache/Tests/Adapter/ApcuAdapterTest.php +++ /dev/null @@ -1,124 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use Psr\Log\NullLogger; -use Symfony\Component\Cache\Adapter\ApcuAdapter; - -class ApcuAdapterTest extends AdapterTestCase -{ - protected $skippedTests = [ - 'testExpiration' => 'Testing expiration slows down the test suite', - 'testHasItemReturnsFalseWhenDeferredItemIsExpired' => 'Testing expiration slows down the test suite', - 'testDefaultLifeTime' => 'Testing expiration slows down the test suite', - ]; - - public function createCachePool($defaultLifetime = 0) - { - if (!\function_exists('apcu_fetch') || !filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN)) { - $this->markTestSkipped('APCu extension is required.'); - } - if ('cli' === \PHP_SAPI && !filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOLEAN)) { - if ('testWithCliSapi' !== $this->getName()) { - $this->markTestSkipped('apc.enable_cli=1 is required.'); - } - } - if ('\\' === \DIRECTORY_SEPARATOR) { - $this->markTestSkipped('Fails transiently on Windows.'); - } - - return new ApcuAdapter(str_replace('\\', '.', __CLASS__), $defaultLifetime); - } - - public function testUnserializable() - { - $pool = $this->createCachePool(); - - $item = $pool->getItem('foo'); - $item->set(function () {}); - - $this->assertFalse($pool->save($item)); - - $item = $pool->getItem('foo'); - $this->assertFalse($item->isHit()); - } - - public function testVersion() - { - $namespace = str_replace('\\', '.', \get_class($this)); - - $pool1 = new ApcuAdapter($namespace, 0, 'p1'); - - $item = $pool1->getItem('foo'); - $this->assertFalse($item->isHit()); - $this->assertTrue($pool1->save($item->set('bar'))); - - $item = $pool1->getItem('foo'); - $this->assertTrue($item->isHit()); - $this->assertSame('bar', $item->get()); - - $pool2 = new ApcuAdapter($namespace, 0, 'p2'); - - $item = $pool2->getItem('foo'); - $this->assertFalse($item->isHit()); - $this->assertNull($item->get()); - - $item = $pool1->getItem('foo'); - $this->assertFalse($item->isHit()); - $this->assertNull($item->get()); - } - - public function testNamespace() - { - $namespace = str_replace('\\', '.', \get_class($this)); - - $pool1 = new ApcuAdapter($namespace.'_1', 0, 'p1'); - - $item = $pool1->getItem('foo'); - $this->assertFalse($item->isHit()); - $this->assertTrue($pool1->save($item->set('bar'))); - - $item = $pool1->getItem('foo'); - $this->assertTrue($item->isHit()); - $this->assertSame('bar', $item->get()); - - $pool2 = new ApcuAdapter($namespace.'_2', 0, 'p1'); - - $item = $pool2->getItem('foo'); - $this->assertFalse($item->isHit()); - $this->assertNull($item->get()); - - $item = $pool1->getItem('foo'); - $this->assertTrue($item->isHit()); - $this->assertSame('bar', $item->get()); - } - - public function testWithCliSapi() - { - try { - // disable PHPUnit error handler to mimic a production environment - $isCalled = false; - set_error_handler(function () use (&$isCalled) { - $isCalled = true; - }); - $pool = new ApcuAdapter(str_replace('\\', '.', __CLASS__)); - $pool->setLogger(new NullLogger()); - - $item = $pool->getItem('foo'); - $item->isHit(); - $pool->save($item->set('bar')); - $this->assertFalse($isCalled); - } finally { - restore_error_handler(); - } - } -} diff --git a/lib/symfony/cache/Tests/Adapter/ArrayAdapterTest.php b/lib/symfony/cache/Tests/Adapter/ArrayAdapterTest.php deleted file mode 100644 index e6adc9d01..000000000 --- a/lib/symfony/cache/Tests/Adapter/ArrayAdapterTest.php +++ /dev/null @@ -1,56 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use Symfony\Component\Cache\Adapter\ArrayAdapter; - -/** - * @group time-sensitive - */ -class ArrayAdapterTest extends AdapterTestCase -{ - protected $skippedTests = [ - 'testDeferredSaveWithoutCommit' => 'Assumes a shared cache which ArrayAdapter is not.', - 'testSaveWithoutExpire' => 'Assumes a shared cache which ArrayAdapter is not.', - ]; - - public function createCachePool($defaultLifetime = 0) - { - return new ArrayAdapter($defaultLifetime); - } - - public function testGetValuesHitAndMiss() - { - /** @var ArrayAdapter $cache */ - $cache = $this->createCachePool(); - - // Hit - $item = $cache->getItem('foo'); - $item->set('4711'); - $cache->save($item); - - $fooItem = $cache->getItem('foo'); - $this->assertTrue($fooItem->isHit()); - $this->assertEquals('4711', $fooItem->get()); - - // Miss (should be present as NULL in $values) - $cache->getItem('bar'); - - $values = $cache->getValues(); - - $this->assertCount(2, $values); - $this->assertArrayHasKey('foo', $values); - $this->assertSame(serialize('4711'), $values['foo']); - $this->assertArrayHasKey('bar', $values); - $this->assertNull($values['bar']); - } -} diff --git a/lib/symfony/cache/Tests/Adapter/ChainAdapterTest.php b/lib/symfony/cache/Tests/Adapter/ChainAdapterTest.php deleted file mode 100644 index 5e48930dd..000000000 --- a/lib/symfony/cache/Tests/Adapter/ChainAdapterTest.php +++ /dev/null @@ -1,115 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use PHPUnit\Framework\MockObject\MockObject; -use Symfony\Component\Cache\Adapter\AdapterInterface; -use Symfony\Component\Cache\Adapter\ArrayAdapter; -use Symfony\Component\Cache\Adapter\ChainAdapter; -use Symfony\Component\Cache\Adapter\FilesystemAdapter; -use Symfony\Component\Cache\PruneableInterface; -use Symfony\Component\Cache\Tests\Fixtures\ExternalAdapter; - -/** - * @author Kévin Dunglas - * @group time-sensitive - */ -class ChainAdapterTest extends AdapterTestCase -{ - public function createCachePool($defaultLifetime = 0) - { - return new ChainAdapter([new ArrayAdapter($defaultLifetime), new ExternalAdapter(), new FilesystemAdapter('', $defaultLifetime)], $defaultLifetime); - } - - public function testEmptyAdaptersException() - { - $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); - $this->expectExceptionMessage('At least one adapter must be specified.'); - new ChainAdapter([]); - } - - public function testInvalidAdapterException() - { - $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); - $this->expectExceptionMessage('The class "stdClass" does not implement'); - new ChainAdapter([new \stdClass()]); - } - - public function testPrune() - { - if (isset($this->skippedTests[__FUNCTION__])) { - $this->markTestSkipped($this->skippedTests[__FUNCTION__]); - } - - $cache = new ChainAdapter([ - $this->getPruneableMock(), - $this->getNonPruneableMock(), - $this->getPruneableMock(), - ]); - $this->assertTrue($cache->prune()); - - $cache = new ChainAdapter([ - $this->getPruneableMock(), - $this->getFailingPruneableMock(), - $this->getPruneableMock(), - ]); - $this->assertFalse($cache->prune()); - } - - /** - * @return MockObject|PruneableCacheInterface - */ - private function getPruneableMock() - { - $pruneable = $this - ->getMockBuilder(PruneableCacheInterface::class) - ->getMock(); - - $pruneable - ->expects($this->atLeastOnce()) - ->method('prune') - ->willReturn(true); - - return $pruneable; - } - - /** - * @return MockObject|PruneableCacheInterface - */ - private function getFailingPruneableMock() - { - $pruneable = $this - ->getMockBuilder(PruneableCacheInterface::class) - ->getMock(); - - $pruneable - ->expects($this->atLeastOnce()) - ->method('prune') - ->willReturn(false); - - return $pruneable; - } - - /** - * @return MockObject|AdapterInterface - */ - private function getNonPruneableMock() - { - return $this - ->getMockBuilder(AdapterInterface::class) - ->getMock(); - } -} - -interface PruneableCacheInterface extends PruneableInterface, AdapterInterface -{ -} diff --git a/lib/symfony/cache/Tests/Adapter/DoctrineAdapterTest.php b/lib/symfony/cache/Tests/Adapter/DoctrineAdapterTest.php deleted file mode 100644 index 8f520cb59..000000000 --- a/lib/symfony/cache/Tests/Adapter/DoctrineAdapterTest.php +++ /dev/null @@ -1,32 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use Symfony\Component\Cache\Adapter\DoctrineAdapter; -use Symfony\Component\Cache\Tests\Fixtures\ArrayCache; - -/** - * @group time-sensitive - */ -class DoctrineAdapterTest extends AdapterTestCase -{ - protected $skippedTests = [ - 'testDeferredSaveWithoutCommit' => 'Assumes a shared cache which ArrayCache is not.', - 'testSaveWithoutExpire' => 'Assumes a shared cache which ArrayCache is not.', - 'testNotUnserializable' => 'ArrayCache does not use serialize/unserialize', - ]; - - public function createCachePool($defaultLifetime = 0) - { - return new DoctrineAdapter(new ArrayCache($defaultLifetime), '', $defaultLifetime); - } -} diff --git a/lib/symfony/cache/Tests/Adapter/FilesystemAdapterTest.php b/lib/symfony/cache/Tests/Adapter/FilesystemAdapterTest.php deleted file mode 100644 index fa8306826..000000000 --- a/lib/symfony/cache/Tests/Adapter/FilesystemAdapterTest.php +++ /dev/null @@ -1,61 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use Psr\Cache\CacheItemPoolInterface; -use Symfony\Component\Cache\Adapter\FilesystemAdapter; - -/** - * @group time-sensitive - */ -class FilesystemAdapterTest extends AdapterTestCase -{ - public function createCachePool($defaultLifetime = 0) - { - return new FilesystemAdapter('', $defaultLifetime); - } - - public static function tearDownAfterClass() - { - self::rmdir(sys_get_temp_dir().'/symfony-cache'); - } - - public static function rmdir($dir) - { - if (!file_exists($dir)) { - return; - } - if (!$dir || 0 !== strpos(\dirname($dir), sys_get_temp_dir())) { - throw new \Exception(__METHOD__."() operates only on subdirs of system's temp dir"); - } - $children = new \RecursiveIteratorIterator( - new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS), - \RecursiveIteratorIterator::CHILD_FIRST - ); - foreach ($children as $child) { - if ($child->isDir()) { - rmdir($child); - } else { - unlink($child); - } - } - rmdir($dir); - } - - protected function isPruned(CacheItemPoolInterface $cache, $name) - { - $getFileMethod = (new \ReflectionObject($cache))->getMethod('getFile'); - $getFileMethod->setAccessible(true); - - return !file_exists($getFileMethod->invoke($cache, $name)); - } -} diff --git a/lib/symfony/cache/Tests/Adapter/MaxIdLengthAdapterTest.php b/lib/symfony/cache/Tests/Adapter/MaxIdLengthAdapterTest.php deleted file mode 100644 index 536e2c2d4..000000000 --- a/lib/symfony/cache/Tests/Adapter/MaxIdLengthAdapterTest.php +++ /dev/null @@ -1,87 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Cache\Adapter\AbstractAdapter; - -class MaxIdLengthAdapterTest extends TestCase -{ - public function testLongKey() - { - $cache = $this->getMockBuilder(MaxIdLengthAdapter::class) - ->setConstructorArgs([str_repeat('-', 10)]) - ->setMethods(['doHave', 'doFetch', 'doDelete', 'doSave', 'doClear']) - ->getMock(); - - $cache->expects($this->exactly(2)) - ->method('doHave') - ->withConsecutive( - [$this->equalTo('----------:0GTYWa9n4ed8vqNlOT2iEr:')], - [$this->equalTo('----------:---------------------------------------')] - ); - - $cache->hasItem(str_repeat('-', 40)); - $cache->hasItem(str_repeat('-', 39)); - } - - public function testLongKeyVersioning() - { - $cache = $this->getMockBuilder(MaxIdLengthAdapter::class) - ->setConstructorArgs([str_repeat('-', 26)]) - ->getMock(); - - $cache - ->method('doFetch') - ->willReturn(['2:']); - - $reflectionClass = new \ReflectionClass(AbstractAdapter::class); - - $reflectionMethod = $reflectionClass->getMethod('getId'); - $reflectionMethod->setAccessible(true); - - // No versioning enabled - $this->assertEquals('--------------------------:------------', $reflectionMethod->invokeArgs($cache, [str_repeat('-', 12)])); - $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 12)]))); - $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 23)]))); - $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 40)]))); - - $reflectionProperty = $reflectionClass->getProperty('versioningIsEnabled'); - $reflectionProperty->setAccessible(true); - $reflectionProperty->setValue($cache, true); - - // Versioning enabled - $this->assertEquals('--------------------------:2:------------', $reflectionMethod->invokeArgs($cache, [str_repeat('-', 12)])); - $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 12)]))); - $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 23)]))); - $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 40)]))); - } - - public function testTooLongNamespace() - { - $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); - $this->expectExceptionMessage('Namespace must be 26 chars max, 40 given ("----------------------------------------")'); - $this->getMockBuilder(MaxIdLengthAdapter::class) - ->setConstructorArgs([str_repeat('-', 40)]) - ->getMock(); - } -} - -abstract class MaxIdLengthAdapter extends AbstractAdapter -{ - protected $maxIdLength = 50; - - public function __construct($ns) - { - parent::__construct($ns); - } -} diff --git a/lib/symfony/cache/Tests/Adapter/MemcachedAdapterTest.php b/lib/symfony/cache/Tests/Adapter/MemcachedAdapterTest.php deleted file mode 100644 index 3a996079a..000000000 --- a/lib/symfony/cache/Tests/Adapter/MemcachedAdapterTest.php +++ /dev/null @@ -1,198 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use Symfony\Component\Cache\Adapter\AbstractAdapter; -use Symfony\Component\Cache\Adapter\MemcachedAdapter; - -class MemcachedAdapterTest extends AdapterTestCase -{ - protected $skippedTests = [ - 'testHasItemReturnsFalseWhenDeferredItemIsExpired' => 'Testing expiration slows down the test suite', - 'testDefaultLifeTime' => 'Testing expiration slows down the test suite', - ]; - - protected static $client; - - public static function setUpBeforeClass() - { - if (!MemcachedAdapter::isSupported()) { - self::markTestSkipped('Extension memcached >=2.2.0 required.'); - } - self::$client = AbstractAdapter::createConnection('memcached://'.getenv('MEMCACHED_HOST'), ['binary_protocol' => false]); - self::$client->get('foo'); - $code = self::$client->getResultCode(); - - if (\Memcached::RES_SUCCESS !== $code && \Memcached::RES_NOTFOUND !== $code) { - self::markTestSkipped('Memcached error: '.strtolower(self::$client->getResultMessage())); - } - } - - public function createCachePool($defaultLifetime = 0) - { - $client = $defaultLifetime ? AbstractAdapter::createConnection('memcached://'.getenv('MEMCACHED_HOST')) : self::$client; - - return new MemcachedAdapter($client, str_replace('\\', '.', __CLASS__), $defaultLifetime); - } - - public function testOptions() - { - $client = MemcachedAdapter::createConnection([], [ - 'libketama_compatible' => false, - 'distribution' => 'modula', - 'compression' => true, - 'serializer' => 'php', - 'hash' => 'md5', - ]); - - $this->assertSame(\Memcached::SERIALIZER_PHP, $client->getOption(\Memcached::OPT_SERIALIZER)); - $this->assertSame(\Memcached::HASH_MD5, $client->getOption(\Memcached::OPT_HASH)); - $this->assertTrue($client->getOption(\Memcached::OPT_COMPRESSION)); - $this->assertSame(0, $client->getOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE)); - $this->assertSame(\Memcached::DISTRIBUTION_MODULA, $client->getOption(\Memcached::OPT_DISTRIBUTION)); - } - - /** - * @dataProvider provideBadOptions - */ - public function testBadOptions($name, $value) - { - $this->expectException('ErrorException'); - $this->expectExceptionMessage('constant(): Couldn\'t find constant Memcached::'); - MemcachedAdapter::createConnection([], [$name => $value]); - } - - public function provideBadOptions() - { - return [ - ['foo', 'bar'], - ['hash', 'zyx'], - ['serializer', 'zyx'], - ['distribution', 'zyx'], - ]; - } - - public function testDefaultOptions() - { - $this->assertTrue(MemcachedAdapter::isSupported()); - - $client = MemcachedAdapter::createConnection([]); - - $this->assertTrue($client->getOption(\Memcached::OPT_COMPRESSION)); - $this->assertSame(1, $client->getOption(\Memcached::OPT_BINARY_PROTOCOL)); - $this->assertSame(1, $client->getOption(\Memcached::OPT_TCP_NODELAY)); - $this->assertSame(1, $client->getOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE)); - } - - public function testOptionSerializer() - { - $this->expectException('Symfony\Component\Cache\Exception\CacheException'); - $this->expectExceptionMessage('MemcachedAdapter: "serializer" option must be "php" or "igbinary".'); - if (!\Memcached::HAVE_JSON) { - $this->markTestSkipped('Memcached::HAVE_JSON required'); - } - - new MemcachedAdapter(MemcachedAdapter::createConnection([], ['serializer' => 'json'])); - } - - /** - * @dataProvider provideServersSetting - */ - public function testServersSetting($dsn, $host, $port) - { - $client1 = MemcachedAdapter::createConnection($dsn); - $client2 = MemcachedAdapter::createConnection([$dsn]); - $client3 = MemcachedAdapter::createConnection([[$host, $port]]); - $expect = [ - 'host' => $host, - 'port' => $port, - ]; - - $f = function ($s) { return ['host' => $s['host'], 'port' => $s['port']]; }; - $this->assertSame([$expect], array_map($f, $client1->getServerList())); - $this->assertSame([$expect], array_map($f, $client2->getServerList())); - $this->assertSame([$expect], array_map($f, $client3->getServerList())); - } - - public function provideServersSetting() - { - yield [ - 'memcached://127.0.0.1/50', - '127.0.0.1', - 11211, - ]; - yield [ - 'memcached://localhost:11222?weight=25', - 'localhost', - 11222, - ]; - if (filter_var(ini_get('memcached.use_sasl'), FILTER_VALIDATE_BOOLEAN)) { - yield [ - 'memcached://user:password@127.0.0.1?weight=50', - '127.0.0.1', - 11211, - ]; - } - yield [ - 'memcached:///var/run/memcached.sock?weight=25', - '/var/run/memcached.sock', - 0, - ]; - yield [ - 'memcached:///var/local/run/memcached.socket?weight=25', - '/var/local/run/memcached.socket', - 0, - ]; - if (filter_var(ini_get('memcached.use_sasl'), FILTER_VALIDATE_BOOLEAN)) { - yield [ - 'memcached://user:password@/var/local/run/memcached.socket?weight=25', - '/var/local/run/memcached.socket', - 0, - ]; - } - } - - /** - * @dataProvider provideDsnWithOptions - */ - public function testDsnWithOptions($dsn, array $options, array $expectedOptions) - { - $client = MemcachedAdapter::createConnection($dsn, $options); - - foreach ($expectedOptions as $option => $expect) { - $this->assertSame($expect, $client->getOption($option)); - } - } - - public function provideDsnWithOptions() - { - if (!class_exists('\Memcached')) { - self::markTestSkipped('Extension memcached required.'); - } - - yield [ - 'memcached://localhost:11222?retry_timeout=10', - [\Memcached::OPT_RETRY_TIMEOUT => 8], - [\Memcached::OPT_RETRY_TIMEOUT => 10], - ]; - yield [ - 'memcached://localhost:11222?socket_recv_size=1&socket_send_size=2', - [\Memcached::OPT_RETRY_TIMEOUT => 8], - [\Memcached::OPT_SOCKET_RECV_SIZE => 1, \Memcached::OPT_SOCKET_SEND_SIZE => 2, \Memcached::OPT_RETRY_TIMEOUT => 8], - ]; - } - - public function testClear() - { - $this->assertTrue($this->createCachePool()->clear()); - } -} diff --git a/lib/symfony/cache/Tests/Adapter/NamespacedProxyAdapterTest.php b/lib/symfony/cache/Tests/Adapter/NamespacedProxyAdapterTest.php deleted file mode 100644 index c27140333..000000000 --- a/lib/symfony/cache/Tests/Adapter/NamespacedProxyAdapterTest.php +++ /dev/null @@ -1,26 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use Symfony\Component\Cache\Adapter\ArrayAdapter; -use Symfony\Component\Cache\Adapter\ProxyAdapter; - -/** - * @group time-sensitive - */ -class NamespacedProxyAdapterTest extends ProxyAdapterTest -{ - public function createCachePool($defaultLifetime = 0) - { - return new ProxyAdapter(new ArrayAdapter($defaultLifetime), 'foo', $defaultLifetime); - } -} diff --git a/lib/symfony/cache/Tests/Adapter/NullAdapterTest.php b/lib/symfony/cache/Tests/Adapter/NullAdapterTest.php deleted file mode 100644 index b771fa0ed..000000000 --- a/lib/symfony/cache/Tests/Adapter/NullAdapterTest.php +++ /dev/null @@ -1,128 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use PHPUnit\Framework\TestCase; -use Psr\Cache\CacheItemInterface; -use Symfony\Component\Cache\Adapter\NullAdapter; - -/** - * @group time-sensitive - */ -class NullAdapterTest extends TestCase -{ - public function createCachePool() - { - return new NullAdapter(); - } - - public function testGetItem() - { - $adapter = $this->createCachePool(); - - $item = $adapter->getItem('key'); - $this->assertFalse($item->isHit()); - $this->assertNull($item->get(), "Item's value must be null when isHit is false."); - } - - public function testHasItem() - { - $this->assertFalse($this->createCachePool()->hasItem('key')); - } - - public function testGetItems() - { - $adapter = $this->createCachePool(); - - $keys = ['foo', 'bar', 'baz', 'biz']; - - /** @var CacheItemInterface[] $items */ - $items = $adapter->getItems($keys); - $count = 0; - - foreach ($items as $key => $item) { - $itemKey = $item->getKey(); - - $this->assertEquals($itemKey, $key, 'Keys must be preserved when fetching multiple items'); - $this->assertContains($key, $keys, 'Cache key can not change.'); - $this->assertFalse($item->isHit()); - - // Remove $key for $keys - foreach ($keys as $k => $v) { - if ($v === $key) { - unset($keys[$k]); - } - } - - ++$count; - } - - $this->assertSame(4, $count); - } - - public function testIsHit() - { - $adapter = $this->createCachePool(); - - $item = $adapter->getItem('key'); - $this->assertFalse($item->isHit()); - } - - public function testClear() - { - $this->assertTrue($this->createCachePool()->clear()); - } - - public function testDeleteItem() - { - $this->assertTrue($this->createCachePool()->deleteItem('key')); - } - - public function testDeleteItems() - { - $this->assertTrue($this->createCachePool()->deleteItems(['key', 'foo', 'bar'])); - } - - public function testSave() - { - $adapter = $this->createCachePool(); - - $item = $adapter->getItem('key'); - $this->assertFalse($item->isHit()); - $this->assertNull($item->get(), "Item's value must be null when isHit is false."); - - $this->assertFalse($adapter->save($item)); - } - - public function testDeferredSave() - { - $adapter = $this->createCachePool(); - - $item = $adapter->getItem('key'); - $this->assertFalse($item->isHit()); - $this->assertNull($item->get(), "Item's value must be null when isHit is false."); - - $this->assertFalse($adapter->saveDeferred($item)); - } - - public function testCommit() - { - $adapter = $this->createCachePool(); - - $item = $adapter->getItem('key'); - $this->assertFalse($item->isHit()); - $this->assertNull($item->get(), "Item's value must be null when isHit is false."); - - $this->assertFalse($adapter->saveDeferred($item)); - $this->assertFalse($this->createCachePool()->commit()); - } -} diff --git a/lib/symfony/cache/Tests/Adapter/PdoAdapterTest.php b/lib/symfony/cache/Tests/Adapter/PdoAdapterTest.php deleted file mode 100644 index dd2a91185..000000000 --- a/lib/symfony/cache/Tests/Adapter/PdoAdapterTest.php +++ /dev/null @@ -1,73 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use Symfony\Component\Cache\Adapter\PdoAdapter; -use Symfony\Component\Cache\Tests\Traits\PdoPruneableTrait; - -/** - * @group time-sensitive - */ -class PdoAdapterTest extends AdapterTestCase -{ - use PdoPruneableTrait; - - protected static $dbFile; - - public static function setUpBeforeClass() - { - if (!\extension_loaded('pdo_sqlite')) { - self::markTestSkipped('Extension pdo_sqlite required.'); - } - - self::$dbFile = tempnam(sys_get_temp_dir(), 'sf_sqlite_cache'); - - $pool = new PdoAdapter('sqlite:'.self::$dbFile); - $pool->createTable(); - } - - public static function tearDownAfterClass() - { - @unlink(self::$dbFile); - } - - public function createCachePool($defaultLifetime = 0) - { - return new PdoAdapter('sqlite:'.self::$dbFile, 'ns', $defaultLifetime); - } - - public function testCleanupExpiredItems() - { - $pdo = new \PDO('sqlite:'.self::$dbFile); - - $getCacheItemCount = function () use ($pdo) { - return (int) $pdo->query('SELECT COUNT(*) FROM cache_items')->fetch(\PDO::FETCH_COLUMN); - }; - - $this->assertSame(0, $getCacheItemCount()); - - $cache = $this->createCachePool(); - - $item = $cache->getItem('some_nice_key'); - $item->expiresAfter(1); - $item->set(1); - - $cache->save($item); - $this->assertSame(1, $getCacheItemCount()); - - sleep(2); - - $newItem = $cache->getItem($item->getKey()); - $this->assertFalse($newItem->isHit()); - $this->assertSame(0, $getCacheItemCount(), 'PDOAdapter must clean up expired items'); - } -} diff --git a/lib/symfony/cache/Tests/Adapter/PdoDbalAdapterTest.php b/lib/symfony/cache/Tests/Adapter/PdoDbalAdapterTest.php deleted file mode 100644 index aa53958cf..000000000 --- a/lib/symfony/cache/Tests/Adapter/PdoDbalAdapterTest.php +++ /dev/null @@ -1,48 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use Doctrine\DBAL\DriverManager; -use Symfony\Component\Cache\Adapter\PdoAdapter; -use Symfony\Component\Cache\Tests\Traits\PdoPruneableTrait; - -/** - * @group time-sensitive - */ -class PdoDbalAdapterTest extends AdapterTestCase -{ - use PdoPruneableTrait; - - protected static $dbFile; - - public static function setUpBeforeClass() - { - if (!\extension_loaded('pdo_sqlite')) { - self::markTestSkipped('Extension pdo_sqlite required.'); - } - - self::$dbFile = tempnam(sys_get_temp_dir(), 'sf_sqlite_cache'); - - $pool = new PdoAdapter(DriverManager::getConnection(['driver' => 'pdo_sqlite', 'path' => self::$dbFile])); - $pool->createTable(); - } - - public static function tearDownAfterClass() - { - @unlink(self::$dbFile); - } - - public function createCachePool($defaultLifetime = 0) - { - return new PdoAdapter(DriverManager::getConnection(['driver' => 'pdo_sqlite', 'path' => self::$dbFile]), '', $defaultLifetime); - } -} diff --git a/lib/symfony/cache/Tests/Adapter/PhpArrayAdapterTest.php b/lib/symfony/cache/Tests/Adapter/PhpArrayAdapterTest.php deleted file mode 100644 index 751f758cc..000000000 --- a/lib/symfony/cache/Tests/Adapter/PhpArrayAdapterTest.php +++ /dev/null @@ -1,133 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use Psr\Cache\CacheItemInterface; -use Symfony\Component\Cache\Adapter\NullAdapter; -use Symfony\Component\Cache\Adapter\PhpArrayAdapter; - -/** - * @group time-sensitive - */ -class PhpArrayAdapterTest extends AdapterTestCase -{ - protected $skippedTests = [ - 'testBasicUsage' => 'PhpArrayAdapter is read-only.', - 'testBasicUsageWithLongKey' => 'PhpArrayAdapter is read-only.', - 'testClear' => 'PhpArrayAdapter is read-only.', - 'testClearWithDeferredItems' => 'PhpArrayAdapter is read-only.', - 'testDeleteItem' => 'PhpArrayAdapter is read-only.', - 'testSaveExpired' => 'PhpArrayAdapter is read-only.', - 'testSaveWithoutExpire' => 'PhpArrayAdapter is read-only.', - 'testDeferredSave' => 'PhpArrayAdapter is read-only.', - 'testDeferredSaveWithoutCommit' => 'PhpArrayAdapter is read-only.', - 'testDeleteItems' => 'PhpArrayAdapter is read-only.', - 'testDeleteDeferredItem' => 'PhpArrayAdapter is read-only.', - 'testCommit' => 'PhpArrayAdapter is read-only.', - 'testSaveDeferredWhenChangingValues' => 'PhpArrayAdapter is read-only.', - 'testSaveDeferredOverwrite' => 'PhpArrayAdapter is read-only.', - 'testIsHitDeferred' => 'PhpArrayAdapter is read-only.', - - 'testExpiresAt' => 'PhpArrayAdapter does not support expiration.', - 'testExpiresAtWithNull' => 'PhpArrayAdapter does not support expiration.', - 'testExpiresAfterWithNull' => 'PhpArrayAdapter does not support expiration.', - 'testDeferredExpired' => 'PhpArrayAdapter does not support expiration.', - 'testExpiration' => 'PhpArrayAdapter does not support expiration.', - - 'testGetItemInvalidKeys' => 'PhpArrayAdapter does not throw exceptions on invalid key.', - 'testGetItemsInvalidKeys' => 'PhpArrayAdapter does not throw exceptions on invalid key.', - 'testHasItemInvalidKeys' => 'PhpArrayAdapter does not throw exceptions on invalid key.', - 'testDeleteItemInvalidKeys' => 'PhpArrayAdapter does not throw exceptions on invalid key.', - 'testDeleteItemsInvalidKeys' => 'PhpArrayAdapter does not throw exceptions on invalid key.', - - 'testDefaultLifeTime' => 'PhpArrayAdapter does not allow configuring a default lifetime.', - 'testPrune' => 'PhpArrayAdapter just proxies', - ]; - - protected static $file; - - public static function setUpBeforeClass() - { - self::$file = sys_get_temp_dir().'/symfony-cache/php-array-adapter-test.php'; - } - - protected function tearDown() - { - if (file_exists(sys_get_temp_dir().'/symfony-cache')) { - FilesystemAdapterTest::rmdir(sys_get_temp_dir().'/symfony-cache'); - } - } - - public function createCachePool() - { - return new PhpArrayAdapterWrapper(self::$file, new NullAdapter()); - } - - public function testStore() - { - $arrayWithRefs = []; - $arrayWithRefs[0] = 123; - $arrayWithRefs[1] = &$arrayWithRefs[0]; - - $object = (object) [ - 'foo' => 'bar', - 'foo2' => 'bar2', - ]; - - $expected = [ - 'null' => null, - 'serializedString' => serialize($object), - 'arrayWithRefs' => $arrayWithRefs, - 'object' => $object, - 'arrayWithObject' => ['bar' => $object], - ]; - - $adapter = $this->createCachePool(); - $adapter->warmUp($expected); - - foreach ($expected as $key => $value) { - $this->assertSame(serialize($value), serialize($adapter->getItem($key)->get()), 'Warm up should create a PHP file that OPCache can load in memory'); - } - } - - public function testStoredFile() - { - $expected = [ - 'integer' => 42, - 'float' => 42.42, - 'boolean' => true, - 'array_simple' => ['foo', 'bar'], - 'array_associative' => ['foo' => 'bar', 'foo2' => 'bar2'], - ]; - - $adapter = $this->createCachePool(); - $adapter->warmUp($expected); - - $values = eval(substr(file_get_contents(self::$file), 6)); - - $this->assertSame($expected, $values, 'Warm up should create a PHP file that OPCache can load in memory'); - } -} - -class PhpArrayAdapterWrapper extends PhpArrayAdapter -{ - public function save(CacheItemInterface $item) - { - \call_user_func(\Closure::bind(function () use ($item) { - $this->values[$item->getKey()] = $item->get(); - $this->warmUp($this->values); - $this->values = eval(substr(file_get_contents($this->file), 6)); - }, $this, PhpArrayAdapter::class)); - - return true; - } -} diff --git a/lib/symfony/cache/Tests/Adapter/PhpArrayAdapterWithFallbackTest.php b/lib/symfony/cache/Tests/Adapter/PhpArrayAdapterWithFallbackTest.php deleted file mode 100644 index 4bdd7580f..000000000 --- a/lib/symfony/cache/Tests/Adapter/PhpArrayAdapterWithFallbackTest.php +++ /dev/null @@ -1,49 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use Symfony\Component\Cache\Adapter\FilesystemAdapter; -use Symfony\Component\Cache\Adapter\PhpArrayAdapter; - -/** - * @group time-sensitive - */ -class PhpArrayAdapterWithFallbackTest extends AdapterTestCase -{ - protected $skippedTests = [ - 'testGetItemInvalidKeys' => 'PhpArrayAdapter does not throw exceptions on invalid key.', - 'testGetItemsInvalidKeys' => 'PhpArrayAdapter does not throw exceptions on invalid key.', - 'testHasItemInvalidKeys' => 'PhpArrayAdapter does not throw exceptions on invalid key.', - 'testDeleteItemInvalidKeys' => 'PhpArrayAdapter does not throw exceptions on invalid key.', - 'testDeleteItemsInvalidKeys' => 'PhpArrayAdapter does not throw exceptions on invalid key.', - 'testPrune' => 'PhpArrayAdapter just proxies', - ]; - - protected static $file; - - public static function setUpBeforeClass() - { - self::$file = sys_get_temp_dir().'/symfony-cache/php-array-adapter-test.php'; - } - - protected function tearDown() - { - if (file_exists(sys_get_temp_dir().'/symfony-cache')) { - FilesystemAdapterTest::rmdir(sys_get_temp_dir().'/symfony-cache'); - } - } - - public function createCachePool($defaultLifetime = 0) - { - return new PhpArrayAdapter(self::$file, new FilesystemAdapter('php-array-fallback', $defaultLifetime)); - } -} diff --git a/lib/symfony/cache/Tests/Adapter/PhpFilesAdapterTest.php b/lib/symfony/cache/Tests/Adapter/PhpFilesAdapterTest.php deleted file mode 100644 index 247160d53..000000000 --- a/lib/symfony/cache/Tests/Adapter/PhpFilesAdapterTest.php +++ /dev/null @@ -1,47 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use Psr\Cache\CacheItemPoolInterface; -use Symfony\Component\Cache\Adapter\PhpFilesAdapter; - -/** - * @group time-sensitive - */ -class PhpFilesAdapterTest extends AdapterTestCase -{ - protected $skippedTests = [ - 'testDefaultLifeTime' => 'PhpFilesAdapter does not allow configuring a default lifetime.', - ]; - - public function createCachePool() - { - if (!PhpFilesAdapter::isSupported()) { - $this->markTestSkipped('OPcache extension is not enabled.'); - } - - return new PhpFilesAdapter('sf-cache'); - } - - public static function tearDownAfterClass() - { - FilesystemAdapterTest::rmdir(sys_get_temp_dir().'/symfony-cache'); - } - - protected function isPruned(CacheItemPoolInterface $cache, $name) - { - $getFileMethod = (new \ReflectionObject($cache))->getMethod('getFile'); - $getFileMethod->setAccessible(true); - - return !file_exists($getFileMethod->invoke($cache, $name)); - } -} diff --git a/lib/symfony/cache/Tests/Adapter/PredisAdapterTest.php b/lib/symfony/cache/Tests/Adapter/PredisAdapterTest.php deleted file mode 100644 index 6aadbf266..000000000 --- a/lib/symfony/cache/Tests/Adapter/PredisAdapterTest.php +++ /dev/null @@ -1,53 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use Predis\Connection\StreamConnection; -use Symfony\Component\Cache\Adapter\RedisAdapter; - -class PredisAdapterTest extends AbstractRedisAdapterTest -{ - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - self::$redis = new \Predis\Client(['host' => getenv('REDIS_HOST')]); - } - - public function testCreateConnection() - { - $redisHost = getenv('REDIS_HOST'); - - $redis = RedisAdapter::createConnection('redis://'.$redisHost.'/1', ['class' => \Predis\Client::class, 'timeout' => 3]); - $this->assertInstanceOf(\Predis\Client::class, $redis); - - $connection = $redis->getConnection(); - $this->assertInstanceOf(StreamConnection::class, $connection); - - $params = [ - 'scheme' => 'tcp', - 'host' => $redisHost, - 'path' => '', - 'dbindex' => '1', - 'port' => 6379, - 'class' => 'Predis\Client', - 'timeout' => 3, - 'persistent' => 0, - 'persistent_id' => null, - 'read_timeout' => 0, - 'retry_interval' => 0, - 'lazy' => false, - 'database' => '1', - 'password' => null, - ]; - $this->assertSame($params, $connection->getParameters()->toArray()); - } -} diff --git a/lib/symfony/cache/Tests/Adapter/PredisClusterAdapterTest.php b/lib/symfony/cache/Tests/Adapter/PredisClusterAdapterTest.php deleted file mode 100644 index 1afabaf1d..000000000 --- a/lib/symfony/cache/Tests/Adapter/PredisClusterAdapterTest.php +++ /dev/null @@ -1,26 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -class PredisClusterAdapterTest extends AbstractRedisAdapterTest -{ - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - self::$redis = new \Predis\Client([['host' => getenv('REDIS_HOST')]]); - } - - public static function tearDownAfterClass() - { - self::$redis = null; - } -} diff --git a/lib/symfony/cache/Tests/Adapter/PredisRedisClusterAdapterTest.php b/lib/symfony/cache/Tests/Adapter/PredisRedisClusterAdapterTest.php deleted file mode 100644 index 5b09919e2..000000000 --- a/lib/symfony/cache/Tests/Adapter/PredisRedisClusterAdapterTest.php +++ /dev/null @@ -1,28 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -class PredisRedisClusterAdapterTest extends AbstractRedisAdapterTest -{ - public static function setUpBeforeClass() - { - if (!$hosts = getenv('REDIS_CLUSTER_HOSTS')) { - self::markTestSkipped('REDIS_CLUSTER_HOSTS env var is not defined.'); - } - self::$redis = new \Predis\Client(explode(' ', $hosts), ['cluster' => 'redis']); - } - - public static function tearDownAfterClass() - { - self::$redis = null; - } -} diff --git a/lib/symfony/cache/Tests/Adapter/ProxyAdapterTest.php b/lib/symfony/cache/Tests/Adapter/ProxyAdapterTest.php deleted file mode 100644 index 810cb31a2..000000000 --- a/lib/symfony/cache/Tests/Adapter/ProxyAdapterTest.php +++ /dev/null @@ -1,69 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use Psr\Cache\CacheItemInterface; -use Symfony\Component\Cache\Adapter\ArrayAdapter; -use Symfony\Component\Cache\Adapter\ProxyAdapter; -use Symfony\Component\Cache\CacheItem; - -/** - * @group time-sensitive - */ -class ProxyAdapterTest extends AdapterTestCase -{ - protected $skippedTests = [ - 'testDeferredSaveWithoutCommit' => 'Assumes a shared cache which ArrayAdapter is not.', - 'testSaveWithoutExpire' => 'Assumes a shared cache which ArrayAdapter is not.', - 'testPrune' => 'ProxyAdapter just proxies', - ]; - - public function createCachePool($defaultLifetime = 0) - { - return new ProxyAdapter(new ArrayAdapter(), '', $defaultLifetime); - } - - public function testProxyfiedItem() - { - $this->expectException('Exception'); - $this->expectExceptionMessage('OK bar'); - $item = new CacheItem(); - $pool = new ProxyAdapter(new TestingArrayAdapter($item)); - - $proxyItem = $pool->getItem('foo'); - - $this->assertNotSame($item, $proxyItem); - $pool->save($proxyItem->set('bar')); - } -} - -class TestingArrayAdapter extends ArrayAdapter -{ - private $item; - - public function __construct(CacheItemInterface $item) - { - $this->item = $item; - } - - public function getItem($key) - { - return $this->item; - } - - public function save(CacheItemInterface $item) - { - if ($item === $this->item) { - throw new \Exception('OK '.$item->get()); - } - } -} diff --git a/lib/symfony/cache/Tests/Adapter/RedisAdapterTest.php b/lib/symfony/cache/Tests/Adapter/RedisAdapterTest.php deleted file mode 100644 index edc6a9934..000000000 --- a/lib/symfony/cache/Tests/Adapter/RedisAdapterTest.php +++ /dev/null @@ -1,92 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use Symfony\Component\Cache\Adapter\AbstractAdapter; -use Symfony\Component\Cache\Adapter\RedisAdapter; -use Symfony\Component\Cache\Traits\RedisProxy; - -class RedisAdapterTest extends AbstractRedisAdapterTest -{ - public static function setUpBeforeClass() - { - parent::setUpBeforeClass(); - self::$redis = AbstractAdapter::createConnection('redis://'.getenv('REDIS_HOST'), ['lazy' => true]); - } - - public function createCachePool($defaultLifetime = 0) - { - $adapter = parent::createCachePool($defaultLifetime); - $this->assertInstanceOf(RedisProxy::class, self::$redis); - - return $adapter; - } - - public function testCreateConnection() - { - $redisHost = getenv('REDIS_HOST'); - - $redis = RedisAdapter::createConnection('redis://'.$redisHost); - $this->assertInstanceOf(\Redis::class, $redis); - $this->assertTrue($redis->isConnected()); - $this->assertSame(0, $redis->getDbNum()); - - $redis = RedisAdapter::createConnection('redis://'.$redisHost.'/2'); - $this->assertSame(2, $redis->getDbNum()); - - $redis = RedisAdapter::createConnection('redis://'.$redisHost, ['timeout' => 3]); - $this->assertEquals(3, $redis->getTimeout()); - - $redis = RedisAdapter::createConnection('redis://'.$redisHost.'?timeout=4'); - $this->assertEquals(4, $redis->getTimeout()); - - $redis = RedisAdapter::createConnection('redis://'.$redisHost, ['read_timeout' => 5]); - $this->assertEquals(5, $redis->getReadTimeout()); - } - - /** - * @dataProvider provideFailedCreateConnection - */ - public function testFailedCreateConnection($dsn) - { - $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); - $this->expectExceptionMessage('Redis connection failed'); - RedisAdapter::createConnection($dsn); - } - - public function provideFailedCreateConnection() - { - return [ - ['redis://localhost:1234'], - ['redis://foo@localhost'], - ['redis://localhost/123'], - ]; - } - - /** - * @dataProvider provideInvalidCreateConnection - */ - public function testInvalidCreateConnection($dsn) - { - $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); - $this->expectExceptionMessage('Invalid Redis DSN'); - RedisAdapter::createConnection($dsn); - } - - public function provideInvalidCreateConnection() - { - return [ - ['foo://localhost'], - ['redis://'], - ]; - } -} diff --git a/lib/symfony/cache/Tests/Adapter/RedisArrayAdapterTest.php b/lib/symfony/cache/Tests/Adapter/RedisArrayAdapterTest.php deleted file mode 100644 index bd9def326..000000000 --- a/lib/symfony/cache/Tests/Adapter/RedisArrayAdapterTest.php +++ /dev/null @@ -1,24 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -class RedisArrayAdapterTest extends AbstractRedisAdapterTest -{ - public static function setUpBeforeClass() - { - parent::setupBeforeClass(); - if (!class_exists('RedisArray')) { - self::markTestSkipped('The RedisArray class is required.'); - } - self::$redis = new \RedisArray([getenv('REDIS_HOST')], ['lazy_connect' => true]); - } -} diff --git a/lib/symfony/cache/Tests/Adapter/RedisClusterAdapterTest.php b/lib/symfony/cache/Tests/Adapter/RedisClusterAdapterTest.php deleted file mode 100644 index 9c339d2dd..000000000 --- a/lib/symfony/cache/Tests/Adapter/RedisClusterAdapterTest.php +++ /dev/null @@ -1,27 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -class RedisClusterAdapterTest extends AbstractRedisAdapterTest -{ - public static function setUpBeforeClass() - { - if (!class_exists('RedisCluster')) { - self::markTestSkipped('The RedisCluster class is required.'); - } - if (!$hosts = getenv('REDIS_CLUSTER_HOSTS')) { - self::markTestSkipped('REDIS_CLUSTER_HOSTS env var is not defined.'); - } - - self::$redis = new \RedisCluster(null, explode(' ', $hosts)); - } -} diff --git a/lib/symfony/cache/Tests/Adapter/SimpleCacheAdapterTest.php b/lib/symfony/cache/Tests/Adapter/SimpleCacheAdapterTest.php deleted file mode 100644 index d8470a2e7..000000000 --- a/lib/symfony/cache/Tests/Adapter/SimpleCacheAdapterTest.php +++ /dev/null @@ -1,41 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use Symfony\Component\Cache\Adapter\SimpleCacheAdapter; -use Symfony\Component\Cache\Simple\ArrayCache; -use Symfony\Component\Cache\Simple\FilesystemCache; - -/** - * @group time-sensitive - */ -class SimpleCacheAdapterTest extends AdapterTestCase -{ - protected $skippedTests = [ - 'testPrune' => 'SimpleCache just proxies', - ]; - - public function createCachePool($defaultLifetime = 0) - { - return new SimpleCacheAdapter(new FilesystemCache(), '', $defaultLifetime); - } - - public function testValidCacheKeyWithNamespace() - { - $cache = new SimpleCacheAdapter(new ArrayCache(), 'some_namespace', 0); - $item = $cache->getItem('my_key'); - $item->set('someValue'); - $cache->save($item); - - $this->assertTrue($cache->getItem('my_key')->isHit(), 'Stored item is successfully retrieved.'); - } -} diff --git a/lib/symfony/cache/Tests/Adapter/TagAwareAdapterTest.php b/lib/symfony/cache/Tests/Adapter/TagAwareAdapterTest.php deleted file mode 100644 index 0108b9250..000000000 --- a/lib/symfony/cache/Tests/Adapter/TagAwareAdapterTest.php +++ /dev/null @@ -1,318 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use PHPUnit\Framework\MockObject\MockObject; -use Psr\Cache\CacheItemInterface; -use Symfony\Component\Cache\Adapter\AdapterInterface; -use Symfony\Component\Cache\Adapter\FilesystemAdapter; -use Symfony\Component\Cache\Adapter\TagAwareAdapter; - -/** - * @group time-sensitive - */ -class TagAwareAdapterTest extends AdapterTestCase -{ - public function createCachePool($defaultLifetime = 0) - { - return new TagAwareAdapter(new FilesystemAdapter('', $defaultLifetime)); - } - - public static function tearDownAfterClass() - { - FilesystemAdapterTest::rmdir(sys_get_temp_dir().'/symfony-cache'); - } - - public function testInvalidTag() - { - $this->expectException('Psr\Cache\InvalidArgumentException'); - $pool = $this->createCachePool(); - $item = $pool->getItem('foo'); - $item->tag(':'); - } - - public function testInvalidateTags() - { - $pool = $this->createCachePool(); - - $i0 = $pool->getItem('i0'); - $i1 = $pool->getItem('i1'); - $i2 = $pool->getItem('i2'); - $i3 = $pool->getItem('i3'); - $foo = $pool->getItem('foo'); - - $pool->save($i0->tag('bar')); - $pool->save($i1->tag('foo')); - $pool->save($i2->tag('foo')->tag('bar')); - $pool->save($i3->tag('foo')->tag('baz')); - $pool->save($foo); - - $pool->invalidateTags(['bar']); - - $this->assertFalse($pool->getItem('i0')->isHit()); - $this->assertTrue($pool->getItem('i1')->isHit()); - $this->assertFalse($pool->getItem('i2')->isHit()); - $this->assertTrue($pool->getItem('i3')->isHit()); - $this->assertTrue($pool->getItem('foo')->isHit()); - - $pool->invalidateTags(['foo']); - - $this->assertFalse($pool->getItem('i1')->isHit()); - $this->assertFalse($pool->getItem('i3')->isHit()); - $this->assertTrue($pool->getItem('foo')->isHit()); - - $anotherPoolInstance = $this->createCachePool(); - - $this->assertFalse($anotherPoolInstance->getItem('i1')->isHit()); - $this->assertFalse($anotherPoolInstance->getItem('i3')->isHit()); - $this->assertTrue($anotherPoolInstance->getItem('foo')->isHit()); - } - - public function testInvalidateCommits() - { - $pool1 = $this->createCachePool(); - - $foo = $pool1->getItem('foo'); - $foo->tag('tag'); - - $pool1->saveDeferred($foo->set('foo')); - $pool1->invalidateTags(['tag']); - - $pool2 = $this->createCachePool(); - $foo = $pool2->getItem('foo'); - - $this->assertTrue($foo->isHit()); - } - - public function testTagsAreCleanedOnSave() - { - $pool = $this->createCachePool(); - - $i = $pool->getItem('k'); - $pool->save($i->tag('foo')); - - $i = $pool->getItem('k'); - $pool->save($i->tag('bar')); - - $pool->invalidateTags(['foo']); - $this->assertTrue($pool->getItem('k')->isHit()); - } - - public function testTagsAreCleanedOnDelete() - { - $pool = $this->createCachePool(); - - $i = $pool->getItem('k'); - $pool->save($i->tag('foo')); - $pool->deleteItem('k'); - - $pool->save($pool->getItem('k')); - $pool->invalidateTags(['foo']); - - $this->assertTrue($pool->getItem('k')->isHit()); - } - - public function testTagItemExpiry() - { - $pool = $this->createCachePool(10); - - $item = $pool->getItem('foo'); - $item->tag(['baz']); - $item->expiresAfter(100); - - $pool->save($item); - $pool->invalidateTags(['baz']); - $this->assertFalse($pool->getItem('foo')->isHit()); - - sleep(20); - - $this->assertFalse($pool->getItem('foo')->isHit()); - } - - public function testGetPreviousTags() - { - $pool = $this->createCachePool(); - - $i = $pool->getItem('k'); - $pool->save($i->tag('foo')); - - $i = $pool->getItem('k'); - $this->assertSame(['foo' => 'foo'], $i->getPreviousTags()); - } - - public function testPrune() - { - $cache = new TagAwareAdapter($this->getPruneableMock()); - $this->assertTrue($cache->prune()); - - $cache = new TagAwareAdapter($this->getNonPruneableMock()); - $this->assertFalse($cache->prune()); - - $cache = new TagAwareAdapter($this->getFailingPruneableMock()); - $this->assertFalse($cache->prune()); - } - - public function testKnownTagVersionsTtl() - { - $itemsPool = new FilesystemAdapter('', 10); - $tagsPool = $this - ->getMockBuilder(AdapterInterface::class) - ->getMock(); - - $pool = new TagAwareAdapter($itemsPool, $tagsPool, 10); - - $item = $pool->getItem('foo'); - $item->tag(['baz']); - $item->expiresAfter(100); - - $tag = $this->getMockBuilder(CacheItemInterface::class)->getMock(); - $tag->expects(self::exactly(2))->method('get')->willReturn(10); - - $tagsPool->expects(self::exactly(2))->method('getItems')->willReturn([ - 'baz'.TagAwareAdapter::TAGS_PREFIX => $tag, - ]); - - $pool->save($item); - $this->assertTrue($pool->getItem('foo')->isHit()); - $this->assertTrue($pool->getItem('foo')->isHit()); - - sleep(20); - - $this->assertTrue($pool->getItem('foo')->isHit()); - - sleep(5); - - $this->assertTrue($pool->getItem('foo')->isHit()); - } - - public function testTagEntryIsCreatedForItemWithoutTags() - { - $pool = $this->createCachePool(); - - $itemKey = 'foo'; - $item = $pool->getItem($itemKey); - $pool->save($item); - - $adapter = new FilesystemAdapter(); - $this->assertTrue($adapter->hasItem(TagAwareAdapter::TAGS_PREFIX.$itemKey)); - } - - public function testHasItemReturnsFalseWhenPoolDoesNotHaveItemTags() - { - $pool = $this->createCachePool(); - - $itemKey = 'foo'; - $item = $pool->getItem($itemKey); - $pool->save($item); - - $anotherPool = $this->createCachePool(); - - $adapter = new FilesystemAdapter(); - $adapter->deleteItem(TagAwareAdapter::TAGS_PREFIX.$itemKey); //simulate item losing tags pair - - $this->assertFalse($anotherPool->hasItem($itemKey)); - } - - public function testGetItemReturnsCacheMissWhenPoolDoesNotHaveItemTags() - { - $pool = $this->createCachePool(); - - $itemKey = 'foo'; - $item = $pool->getItem($itemKey); - $pool->save($item); - - $anotherPool = $this->createCachePool(); - - $adapter = new FilesystemAdapter(); - $adapter->deleteItem(TagAwareAdapter::TAGS_PREFIX.$itemKey); //simulate item losing tags pair - - $item = $anotherPool->getItem($itemKey); - $this->assertFalse($item->isHit()); - } - - public function testHasItemReturnsFalseWhenPoolDoesNotHaveItemAndOnlyHasTags() - { - $pool = $this->createCachePool(); - - $itemKey = 'foo'; - $item = $pool->getItem($itemKey); - $pool->save($item); - - $anotherPool = $this->createCachePool(); - - $adapter = new FilesystemAdapter(); - $adapter->deleteItem($itemKey); //simulate losing item but keeping tags - - $this->assertFalse($anotherPool->hasItem($itemKey)); - } - - public function testGetItemReturnsCacheMissWhenPoolDoesNotHaveItemAndOnlyHasTags() - { - $pool = $this->createCachePool(); - - $itemKey = 'foo'; - $item = $pool->getItem($itemKey); - $pool->save($item); - - $anotherPool = $this->createCachePool(); - - $adapter = new FilesystemAdapter(); - $adapter->deleteItem($itemKey); //simulate losing item but keeping tags - - $item = $anotherPool->getItem($itemKey); - $this->assertFalse($item->isHit()); - } - - /** - * @return MockObject|PruneableCacheInterface - */ - private function getPruneableMock() - { - $pruneable = $this - ->getMockBuilder(PruneableCacheInterface::class) - ->getMock(); - - $pruneable - ->expects($this->atLeastOnce()) - ->method('prune') - ->willReturn(true); - - return $pruneable; - } - - /** - * @return MockObject|PruneableCacheInterface - */ - private function getFailingPruneableMock() - { - $pruneable = $this - ->getMockBuilder(PruneableCacheInterface::class) - ->getMock(); - - $pruneable - ->expects($this->atLeastOnce()) - ->method('prune') - ->willReturn(false); - - return $pruneable; - } - - /** - * @return MockObject|AdapterInterface - */ - private function getNonPruneableMock() - { - return $this - ->getMockBuilder(AdapterInterface::class) - ->getMock(); - } -} diff --git a/lib/symfony/cache/Tests/Adapter/TagAwareAndProxyAdapterIntegrationTest.php b/lib/symfony/cache/Tests/Adapter/TagAwareAndProxyAdapterIntegrationTest.php deleted file mode 100644 index b11c1f287..000000000 --- a/lib/symfony/cache/Tests/Adapter/TagAwareAndProxyAdapterIntegrationTest.php +++ /dev/null @@ -1,38 +0,0 @@ -getItem('foo'); - $item->tag(['tag1', 'tag2']); - $item->set('bar'); - $cache->save($item); - - $this->assertSame('bar', $cache->getItem('foo')->get()); - } - - public function dataProvider() - { - return [ - [new ArrayAdapter()], - // also testing with a non-AdapterInterface implementation - // because the ProxyAdapter behaves slightly different for those - [new ExternalAdapter()], - ]; - } -} diff --git a/lib/symfony/cache/Tests/Adapter/TraceableAdapterTest.php b/lib/symfony/cache/Tests/Adapter/TraceableAdapterTest.php deleted file mode 100644 index 35eba7d77..000000000 --- a/lib/symfony/cache/Tests/Adapter/TraceableAdapterTest.php +++ /dev/null @@ -1,191 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use Symfony\Component\Cache\Adapter\FilesystemAdapter; -use Symfony\Component\Cache\Adapter\TraceableAdapter; - -/** - * @group time-sensitive - */ -class TraceableAdapterTest extends AdapterTestCase -{ - protected $skippedTests = [ - 'testPrune' => 'TraceableAdapter just proxies', - ]; - - public function createCachePool($defaultLifetime = 0) - { - return new TraceableAdapter(new FilesystemAdapter('', $defaultLifetime)); - } - - public function testGetItemMissTrace() - { - $pool = $this->createCachePool(); - $pool->getItem('k'); - $calls = $pool->getCalls(); - $this->assertCount(1, $calls); - - $call = $calls[0]; - $this->assertSame('getItem', $call->name); - $this->assertSame(['k' => false], $call->result); - $this->assertSame(0, $call->hits); - $this->assertSame(1, $call->misses); - $this->assertNotEmpty($call->start); - $this->assertNotEmpty($call->end); - } - - public function testGetItemHitTrace() - { - $pool = $this->createCachePool(); - $item = $pool->getItem('k')->set('foo'); - $pool->save($item); - $pool->getItem('k'); - $calls = $pool->getCalls(); - $this->assertCount(3, $calls); - - $call = $calls[2]; - $this->assertSame(1, $call->hits); - $this->assertSame(0, $call->misses); - } - - public function testGetItemsMissTrace() - { - $pool = $this->createCachePool(); - $arg = ['k0', 'k1']; - $items = $pool->getItems($arg); - foreach ($items as $item) { - } - $calls = $pool->getCalls(); - $this->assertCount(1, $calls); - - $call = $calls[0]; - $this->assertSame('getItems', $call->name); - $this->assertSame(['k0' => false, 'k1' => false], $call->result); - $this->assertSame(2, $call->misses); - $this->assertNotEmpty($call->start); - $this->assertNotEmpty($call->end); - } - - public function testHasItemMissTrace() - { - $pool = $this->createCachePool(); - $pool->hasItem('k'); - $calls = $pool->getCalls(); - $this->assertCount(1, $calls); - - $call = $calls[0]; - $this->assertSame('hasItem', $call->name); - $this->assertSame(['k' => false], $call->result); - $this->assertNotEmpty($call->start); - $this->assertNotEmpty($call->end); - } - - public function testHasItemHitTrace() - { - $pool = $this->createCachePool(); - $item = $pool->getItem('k')->set('foo'); - $pool->save($item); - $pool->hasItem('k'); - $calls = $pool->getCalls(); - $this->assertCount(3, $calls); - - $call = $calls[2]; - $this->assertSame('hasItem', $call->name); - $this->assertSame(['k' => true], $call->result); - $this->assertNotEmpty($call->start); - $this->assertNotEmpty($call->end); - } - - public function testDeleteItemTrace() - { - $pool = $this->createCachePool(); - $pool->deleteItem('k'); - $calls = $pool->getCalls(); - $this->assertCount(1, $calls); - - $call = $calls[0]; - $this->assertSame('deleteItem', $call->name); - $this->assertSame(['k' => true], $call->result); - $this->assertSame(0, $call->hits); - $this->assertSame(0, $call->misses); - $this->assertNotEmpty($call->start); - $this->assertNotEmpty($call->end); - } - - public function testDeleteItemsTrace() - { - $pool = $this->createCachePool(); - $arg = ['k0', 'k1']; - $pool->deleteItems($arg); - $calls = $pool->getCalls(); - $this->assertCount(1, $calls); - - $call = $calls[0]; - $this->assertSame('deleteItems', $call->name); - $this->assertSame(['keys' => $arg, 'result' => true], $call->result); - $this->assertSame(0, $call->hits); - $this->assertSame(0, $call->misses); - $this->assertNotEmpty($call->start); - $this->assertNotEmpty($call->end); - } - - public function testSaveTrace() - { - $pool = $this->createCachePool(); - $item = $pool->getItem('k')->set('foo'); - $pool->save($item); - $calls = $pool->getCalls(); - $this->assertCount(2, $calls); - - $call = $calls[1]; - $this->assertSame('save', $call->name); - $this->assertSame(['k' => true], $call->result); - $this->assertSame(0, $call->hits); - $this->assertSame(0, $call->misses); - $this->assertNotEmpty($call->start); - $this->assertNotEmpty($call->end); - } - - public function testSaveDeferredTrace() - { - $pool = $this->createCachePool(); - $item = $pool->getItem('k')->set('foo'); - $pool->saveDeferred($item); - $calls = $pool->getCalls(); - $this->assertCount(2, $calls); - - $call = $calls[1]; - $this->assertSame('saveDeferred', $call->name); - $this->assertSame(['k' => true], $call->result); - $this->assertSame(0, $call->hits); - $this->assertSame(0, $call->misses); - $this->assertNotEmpty($call->start); - $this->assertNotEmpty($call->end); - } - - public function testCommitTrace() - { - $pool = $this->createCachePool(); - $pool->commit(); - $calls = $pool->getCalls(); - $this->assertCount(1, $calls); - - $call = $calls[0]; - $this->assertSame('commit', $call->name); - $this->assertTrue($call->result); - $this->assertSame(0, $call->hits); - $this->assertSame(0, $call->misses); - $this->assertNotEmpty($call->start); - $this->assertNotEmpty($call->end); - } -} diff --git a/lib/symfony/cache/Tests/Adapter/TraceableTagAwareAdapterTest.php b/lib/symfony/cache/Tests/Adapter/TraceableTagAwareAdapterTest.php deleted file mode 100644 index 5cd4185cb..000000000 --- a/lib/symfony/cache/Tests/Adapter/TraceableTagAwareAdapterTest.php +++ /dev/null @@ -1,37 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Adapter; - -use Symfony\Component\Cache\Adapter\FilesystemAdapter; -use Symfony\Component\Cache\Adapter\TagAwareAdapter; -use Symfony\Component\Cache\Adapter\TraceableTagAwareAdapter; - -/** - * @group time-sensitive - */ -class TraceableTagAwareAdapterTest extends TraceableAdapterTest -{ - public function testInvalidateTags() - { - $pool = new TraceableTagAwareAdapter(new TagAwareAdapter(new FilesystemAdapter())); - $pool->invalidateTags(['foo']); - $calls = $pool->getCalls(); - $this->assertCount(1, $calls); - - $call = $calls[0]; - $this->assertSame('invalidateTags', $call->name); - $this->assertSame(0, $call->hits); - $this->assertSame(0, $call->misses); - $this->assertNotEmpty($call->start); - $this->assertNotEmpty($call->end); - } -} diff --git a/lib/symfony/cache/Tests/CacheItemTest.php b/lib/symfony/cache/Tests/CacheItemTest.php deleted file mode 100644 index 28c681d15..000000000 --- a/lib/symfony/cache/Tests/CacheItemTest.php +++ /dev/null @@ -1,77 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Cache\CacheItem; - -class CacheItemTest extends TestCase -{ - public function testValidKey() - { - $this->assertSame('foo', CacheItem::validateKey('foo')); - } - - /** - * @dataProvider provideInvalidKey - */ - public function testInvalidKey($key) - { - $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); - $this->expectExceptionMessage('Cache key'); - CacheItem::validateKey($key); - } - - public function provideInvalidKey() - { - return [ - [''], - ['{'], - ['}'], - ['('], - [')'], - ['/'], - ['\\'], - ['@'], - [':'], - [true], - [null], - [1], - [1.1], - [[[]]], - [new \Exception('foo')], - ]; - } - - public function testTag() - { - $item = new CacheItem(); - - $this->assertSame($item, $item->tag('foo')); - $this->assertSame($item, $item->tag(['bar', 'baz'])); - - \call_user_func(\Closure::bind(function () use ($item) { - $this->assertSame(['foo' => 'foo', 'bar' => 'bar', 'baz' => 'baz'], $item->tags); - }, $this, CacheItem::class)); - } - - /** - * @dataProvider provideInvalidKey - */ - public function testInvalidTag($tag) - { - $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); - $this->expectExceptionMessage('Cache tag'); - $item = new CacheItem(); - $item->tag($tag); - } -} diff --git a/lib/symfony/cache/Tests/DoctrineProviderTest.php b/lib/symfony/cache/Tests/DoctrineProviderTest.php deleted file mode 100644 index 91a5516ab..000000000 --- a/lib/symfony/cache/Tests/DoctrineProviderTest.php +++ /dev/null @@ -1,45 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests; - -use Doctrine\Common\Cache\CacheProvider; -use PHPUnit\Framework\TestCase; -use Symfony\Component\Cache\Adapter\ArrayAdapter; -use Symfony\Component\Cache\DoctrineProvider; - -class DoctrineProviderTest extends TestCase -{ - public function testProvider() - { - $pool = new ArrayAdapter(); - $cache = new DoctrineProvider($pool); - - $this->assertInstanceOf(CacheProvider::class, $cache); - - $key = '{}()/\@:'; - - $this->assertTrue($cache->delete($key)); - $this->assertFalse($cache->contains($key)); - - $this->assertTrue($cache->save($key, 'bar')); - $this->assertTrue($cache->contains($key)); - $this->assertSame('bar', $cache->fetch($key)); - - $this->assertTrue($cache->delete($key)); - $this->assertFalse($cache->fetch($key)); - $this->assertTrue($cache->save($key, 'bar')); - - $cache->flushAll(); - $this->assertFalse($cache->fetch($key)); - $this->assertFalse($cache->contains($key)); - } -} diff --git a/lib/symfony/cache/Tests/Fixtures/ArrayCache.php b/lib/symfony/cache/Tests/Fixtures/ArrayCache.php deleted file mode 100644 index 13b4f3306..000000000 --- a/lib/symfony/cache/Tests/Fixtures/ArrayCache.php +++ /dev/null @@ -1,52 +0,0 @@ -doContains($id) ? $this->data[$id][0] : false; - } - - protected function doContains($id) - { - if (!isset($this->data[$id])) { - return false; - } - - $expiry = $this->data[$id][1]; - - return !$expiry || time() < $expiry || !$this->doDelete($id); - } - - protected function doSave($id, $data, $lifeTime = 0) - { - $this->data[$id] = [$data, $lifeTime ? time() + $lifeTime : false]; - - return true; - } - - protected function doDelete($id) - { - unset($this->data[$id]); - - return true; - } - - protected function doFlush() - { - $this->data = []; - - return true; - } - - protected function doGetStats() - { - return null; - } -} diff --git a/lib/symfony/cache/Tests/Fixtures/ExternalAdapter.php b/lib/symfony/cache/Tests/Fixtures/ExternalAdapter.php deleted file mode 100644 index 779a374ec..000000000 --- a/lib/symfony/cache/Tests/Fixtures/ExternalAdapter.php +++ /dev/null @@ -1,76 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Fixtures; - -use Psr\Cache\CacheItemInterface; -use Psr\Cache\CacheItemPoolInterface; -use Symfony\Component\Cache\Adapter\ArrayAdapter; - -/** - * Adapter not implementing the {@see \Symfony\Component\Cache\Adapter\AdapterInterface}. - * - * @author Kévin Dunglas - */ -class ExternalAdapter implements CacheItemPoolInterface -{ - private $cache; - - public function __construct() - { - $this->cache = new ArrayAdapter(); - } - - public function getItem($key) - { - return $this->cache->getItem($key); - } - - public function getItems(array $keys = []) - { - return $this->cache->getItems($keys); - } - - public function hasItem($key) - { - return $this->cache->hasItem($key); - } - - public function clear() - { - return $this->cache->clear(); - } - - public function deleteItem($key) - { - return $this->cache->deleteItem($key); - } - - public function deleteItems(array $keys) - { - return $this->cache->deleteItems($keys); - } - - public function save(CacheItemInterface $item) - { - return $this->cache->save($item); - } - - public function saveDeferred(CacheItemInterface $item) - { - return $this->cache->saveDeferred($item); - } - - public function commit() - { - return $this->cache->commit(); - } -} diff --git a/lib/symfony/cache/Tests/Simple/AbstractRedisCacheTest.php b/lib/symfony/cache/Tests/Simple/AbstractRedisCacheTest.php deleted file mode 100644 index e6d10284e..000000000 --- a/lib/symfony/cache/Tests/Simple/AbstractRedisCacheTest.php +++ /dev/null @@ -1,46 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Simple; - -use Symfony\Component\Cache\Simple\RedisCache; - -abstract class AbstractRedisCacheTest extends CacheTestCase -{ - protected $skippedTests = [ - 'testSetTtl' => 'Testing expiration slows down the test suite', - 'testSetMultipleTtl' => 'Testing expiration slows down the test suite', - 'testDefaultLifeTime' => 'Testing expiration slows down the test suite', - ]; - - protected static $redis; - - public function createSimpleCache($defaultLifetime = 0) - { - return new RedisCache(self::$redis, str_replace('\\', '.', __CLASS__), $defaultLifetime); - } - - public static function setUpBeforeClass() - { - if (!\extension_loaded('redis')) { - self::markTestSkipped('Extension redis required.'); - } - if (!@((new \Redis())->connect(getenv('REDIS_HOST')))) { - $e = error_get_last(); - self::markTestSkipped($e['message']); - } - } - - public static function tearDownAfterClass() - { - self::$redis = null; - } -} diff --git a/lib/symfony/cache/Tests/Simple/ApcuCacheTest.php b/lib/symfony/cache/Tests/Simple/ApcuCacheTest.php deleted file mode 100644 index f37b95a09..000000000 --- a/lib/symfony/cache/Tests/Simple/ApcuCacheTest.php +++ /dev/null @@ -1,35 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Simple; - -use Symfony\Component\Cache\Simple\ApcuCache; - -class ApcuCacheTest extends CacheTestCase -{ - protected $skippedTests = [ - 'testSetTtl' => 'Testing expiration slows down the test suite', - 'testSetMultipleTtl' => 'Testing expiration slows down the test suite', - 'testDefaultLifeTime' => 'Testing expiration slows down the test suite', - ]; - - public function createSimpleCache($defaultLifetime = 0) - { - if (!\function_exists('apcu_fetch') || !filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) || ('cli' === \PHP_SAPI && !filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOLEAN))) { - $this->markTestSkipped('APCu extension is required.'); - } - if ('\\' === \DIRECTORY_SEPARATOR) { - $this->markTestSkipped('Fails transiently on Windows.'); - } - - return new ApcuCache(str_replace('\\', '.', __CLASS__), $defaultLifetime); - } -} diff --git a/lib/symfony/cache/Tests/Simple/ArrayCacheTest.php b/lib/symfony/cache/Tests/Simple/ArrayCacheTest.php deleted file mode 100644 index 26c3e14d0..000000000 --- a/lib/symfony/cache/Tests/Simple/ArrayCacheTest.php +++ /dev/null @@ -1,25 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Simple; - -use Symfony\Component\Cache\Simple\ArrayCache; - -/** - * @group time-sensitive - */ -class ArrayCacheTest extends CacheTestCase -{ - public function createSimpleCache($defaultLifetime = 0) - { - return new ArrayCache($defaultLifetime); - } -} diff --git a/lib/symfony/cache/Tests/Simple/CacheTestCase.php b/lib/symfony/cache/Tests/Simple/CacheTestCase.php deleted file mode 100644 index ff9944a34..000000000 --- a/lib/symfony/cache/Tests/Simple/CacheTestCase.php +++ /dev/null @@ -1,150 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Simple; - -use Cache\IntegrationTests\SimpleCacheTest; -use Psr\SimpleCache\CacheInterface; -use Symfony\Component\Cache\PruneableInterface; - -abstract class CacheTestCase extends SimpleCacheTest -{ - protected function setUp() - { - parent::setUp(); - - if (!\array_key_exists('testPrune', $this->skippedTests) && !$this->createSimpleCache() instanceof PruneableInterface) { - $this->skippedTests['testPrune'] = 'Not a pruneable cache pool.'; - } - } - - public static function validKeys() - { - if (\defined('HHVM_VERSION')) { - return parent::validKeys(); - } - - return array_merge(parent::validKeys(), [["a\0b"]]); - } - - public function testDefaultLifeTime() - { - if (isset($this->skippedTests[__FUNCTION__])) { - $this->markTestSkipped($this->skippedTests[__FUNCTION__]); - } - - $cache = $this->createSimpleCache(2); - $cache->clear(); - - $cache->set('key.dlt', 'value'); - sleep(1); - - $this->assertSame('value', $cache->get('key.dlt')); - - sleep(2); - $this->assertNull($cache->get('key.dlt')); - - $cache->clear(); - } - - public function testNotUnserializable() - { - if (isset($this->skippedTests[__FUNCTION__])) { - $this->markTestSkipped($this->skippedTests[__FUNCTION__]); - } - - $cache = $this->createSimpleCache(); - $cache->clear(); - - $cache->set('foo', new NotUnserializable()); - - $this->assertNull($cache->get('foo')); - - $cache->setMultiple(['foo' => new NotUnserializable()]); - - foreach ($cache->getMultiple(['foo']) as $value) { - } - $this->assertNull($value); - - $cache->clear(); - } - - public function testPrune() - { - if (isset($this->skippedTests[__FUNCTION__])) { - $this->markTestSkipped($this->skippedTests[__FUNCTION__]); - } - - if (!method_exists($this, 'isPruned')) { - $this->fail('Test classes for pruneable caches must implement `isPruned($cache, $name)` method.'); - } - - /** @var PruneableInterface|CacheInterface $cache */ - $cache = $this->createSimpleCache(); - $cache->clear(); - - $cache->set('foo', 'foo-val', new \DateInterval('PT05S')); - $cache->set('bar', 'bar-val', new \DateInterval('PT10S')); - $cache->set('baz', 'baz-val', new \DateInterval('PT15S')); - $cache->set('qux', 'qux-val', new \DateInterval('PT20S')); - - sleep(30); - $cache->prune(); - $this->assertTrue($this->isPruned($cache, 'foo')); - $this->assertTrue($this->isPruned($cache, 'bar')); - $this->assertTrue($this->isPruned($cache, 'baz')); - $this->assertTrue($this->isPruned($cache, 'qux')); - - $cache->set('foo', 'foo-val'); - $cache->set('bar', 'bar-val', new \DateInterval('PT20S')); - $cache->set('baz', 'baz-val', new \DateInterval('PT40S')); - $cache->set('qux', 'qux-val', new \DateInterval('PT80S')); - - $cache->prune(); - $this->assertFalse($this->isPruned($cache, 'foo')); - $this->assertFalse($this->isPruned($cache, 'bar')); - $this->assertFalse($this->isPruned($cache, 'baz')); - $this->assertFalse($this->isPruned($cache, 'qux')); - - sleep(30); - $cache->prune(); - $this->assertFalse($this->isPruned($cache, 'foo')); - $this->assertTrue($this->isPruned($cache, 'bar')); - $this->assertFalse($this->isPruned($cache, 'baz')); - $this->assertFalse($this->isPruned($cache, 'qux')); - - sleep(30); - $cache->prune(); - $this->assertFalse($this->isPruned($cache, 'foo')); - $this->assertTrue($this->isPruned($cache, 'baz')); - $this->assertFalse($this->isPruned($cache, 'qux')); - - sleep(30); - $cache->prune(); - $this->assertFalse($this->isPruned($cache, 'foo')); - $this->assertTrue($this->isPruned($cache, 'qux')); - - $cache->clear(); - } -} - -class NotUnserializable implements \Serializable -{ - public function serialize() - { - return serialize(123); - } - - public function unserialize($ser) - { - throw new \Exception(__CLASS__); - } -} diff --git a/lib/symfony/cache/Tests/Simple/ChainCacheTest.php b/lib/symfony/cache/Tests/Simple/ChainCacheTest.php deleted file mode 100644 index f216bc1f3..000000000 --- a/lib/symfony/cache/Tests/Simple/ChainCacheTest.php +++ /dev/null @@ -1,113 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Simple; - -use PHPUnit\Framework\MockObject\MockObject; -use Psr\SimpleCache\CacheInterface; -use Symfony\Component\Cache\PruneableInterface; -use Symfony\Component\Cache\Simple\ArrayCache; -use Symfony\Component\Cache\Simple\ChainCache; -use Symfony\Component\Cache\Simple\FilesystemCache; - -/** - * @group time-sensitive - */ -class ChainCacheTest extends CacheTestCase -{ - public function createSimpleCache($defaultLifetime = 0) - { - return new ChainCache([new ArrayCache($defaultLifetime), new FilesystemCache('', $defaultLifetime)], $defaultLifetime); - } - - public function testEmptyCachesException() - { - $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); - $this->expectExceptionMessage('At least one cache must be specified.'); - new ChainCache([]); - } - - public function testInvalidCacheException() - { - $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); - $this->expectExceptionMessage('The class "stdClass" does not implement'); - new ChainCache([new \stdClass()]); - } - - public function testPrune() - { - if (isset($this->skippedTests[__FUNCTION__])) { - $this->markTestSkipped($this->skippedTests[__FUNCTION__]); - } - - $cache = new ChainCache([ - $this->getPruneableMock(), - $this->getNonPruneableMock(), - $this->getPruneableMock(), - ]); - $this->assertTrue($cache->prune()); - - $cache = new ChainCache([ - $this->getPruneableMock(), - $this->getFailingPruneableMock(), - $this->getPruneableMock(), - ]); - $this->assertFalse($cache->prune()); - } - - /** - * @return MockObject|PruneableCacheInterface - */ - private function getPruneableMock() - { - $pruneable = $this - ->getMockBuilder(PruneableCacheInterface::class) - ->getMock(); - - $pruneable - ->expects($this->atLeastOnce()) - ->method('prune') - ->willReturn(true); - - return $pruneable; - } - - /** - * @return MockObject|PruneableCacheInterface - */ - private function getFailingPruneableMock() - { - $pruneable = $this - ->getMockBuilder(PruneableCacheInterface::class) - ->getMock(); - - $pruneable - ->expects($this->atLeastOnce()) - ->method('prune') - ->willReturn(false); - - return $pruneable; - } - - /** - * @return MockObject|CacheInterface - */ - private function getNonPruneableMock() - { - return $this - ->getMockBuilder(CacheInterface::class) - ->getMock(); - } -} - -interface PruneableCacheInterface extends PruneableInterface, CacheInterface -{ -} diff --git a/lib/symfony/cache/Tests/Simple/DoctrineCacheTest.php b/lib/symfony/cache/Tests/Simple/DoctrineCacheTest.php deleted file mode 100644 index af4331d69..000000000 --- a/lib/symfony/cache/Tests/Simple/DoctrineCacheTest.php +++ /dev/null @@ -1,31 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Simple; - -use Symfony\Component\Cache\Simple\DoctrineCache; -use Symfony\Component\Cache\Tests\Fixtures\ArrayCache; - -/** - * @group time-sensitive - */ -class DoctrineCacheTest extends CacheTestCase -{ - protected $skippedTests = [ - 'testObjectDoesNotChangeInCache' => 'ArrayCache does not use serialize/unserialize', - 'testNotUnserializable' => 'ArrayCache does not use serialize/unserialize', - ]; - - public function createSimpleCache($defaultLifetime = 0) - { - return new DoctrineCache(new ArrayCache($defaultLifetime), '', $defaultLifetime); - } -} diff --git a/lib/symfony/cache/Tests/Simple/FilesystemCacheTest.php b/lib/symfony/cache/Tests/Simple/FilesystemCacheTest.php deleted file mode 100644 index 620305a58..000000000 --- a/lib/symfony/cache/Tests/Simple/FilesystemCacheTest.php +++ /dev/null @@ -1,34 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Simple; - -use Psr\SimpleCache\CacheInterface; -use Symfony\Component\Cache\Simple\FilesystemCache; - -/** - * @group time-sensitive - */ -class FilesystemCacheTest extends CacheTestCase -{ - public function createSimpleCache($defaultLifetime = 0) - { - return new FilesystemCache('', $defaultLifetime); - } - - protected function isPruned(CacheInterface $cache, $name) - { - $getFileMethod = (new \ReflectionObject($cache))->getMethod('getFile'); - $getFileMethod->setAccessible(true); - - return !file_exists($getFileMethod->invoke($cache, $name)); - } -} diff --git a/lib/symfony/cache/Tests/Simple/MemcachedCacheTest.php b/lib/symfony/cache/Tests/Simple/MemcachedCacheTest.php deleted file mode 100644 index 21332232b..000000000 --- a/lib/symfony/cache/Tests/Simple/MemcachedCacheTest.php +++ /dev/null @@ -1,172 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Simple; - -use Symfony\Component\Cache\Adapter\AbstractAdapter; -use Symfony\Component\Cache\Simple\MemcachedCache; - -class MemcachedCacheTest extends CacheTestCase -{ - protected $skippedTests = [ - 'testSetTtl' => 'Testing expiration slows down the test suite', - 'testSetMultipleTtl' => 'Testing expiration slows down the test suite', - 'testDefaultLifeTime' => 'Testing expiration slows down the test suite', - ]; - - protected static $client; - - public static function setUpBeforeClass() - { - if (!MemcachedCache::isSupported()) { - self::markTestSkipped('Extension memcached >=2.2.0 required.'); - } - self::$client = AbstractAdapter::createConnection('memcached://'.getenv('MEMCACHED_HOST')); - self::$client->get('foo'); - $code = self::$client->getResultCode(); - - if (\Memcached::RES_SUCCESS !== $code && \Memcached::RES_NOTFOUND !== $code) { - self::markTestSkipped('Memcached error: '.strtolower(self::$client->getResultMessage())); - } - } - - public function createSimpleCache($defaultLifetime = 0) - { - $client = $defaultLifetime ? AbstractAdapter::createConnection('memcached://'.getenv('MEMCACHED_HOST'), ['binary_protocol' => false]) : self::$client; - - return new MemcachedCache($client, str_replace('\\', '.', __CLASS__), $defaultLifetime); - } - - public function testCreatePersistentConnectionShouldNotDupServerList() - { - $instance = MemcachedCache::createConnection('memcached://'.getenv('MEMCACHED_HOST'), ['persistent_id' => 'persistent']); - $this->assertCount(1, $instance->getServerList()); - - $instance = MemcachedCache::createConnection('memcached://'.getenv('MEMCACHED_HOST'), ['persistent_id' => 'persistent']); - $this->assertCount(1, $instance->getServerList()); - } - - public function testOptions() - { - $client = MemcachedCache::createConnection([], [ - 'libketama_compatible' => false, - 'distribution' => 'modula', - 'compression' => true, - 'serializer' => 'php', - 'hash' => 'md5', - ]); - - $this->assertSame(\Memcached::SERIALIZER_PHP, $client->getOption(\Memcached::OPT_SERIALIZER)); - $this->assertSame(\Memcached::HASH_MD5, $client->getOption(\Memcached::OPT_HASH)); - $this->assertTrue($client->getOption(\Memcached::OPT_COMPRESSION)); - $this->assertSame(0, $client->getOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE)); - $this->assertSame(\Memcached::DISTRIBUTION_MODULA, $client->getOption(\Memcached::OPT_DISTRIBUTION)); - } - - /** - * @dataProvider provideBadOptions - */ - public function testBadOptions($name, $value) - { - $this->expectException('ErrorException'); - $this->expectExceptionMessage('constant(): Couldn\'t find constant Memcached::'); - MemcachedCache::createConnection([], [$name => $value]); - } - - public function provideBadOptions() - { - return [ - ['foo', 'bar'], - ['hash', 'zyx'], - ['serializer', 'zyx'], - ['distribution', 'zyx'], - ]; - } - - public function testDefaultOptions() - { - $this->assertTrue(MemcachedCache::isSupported()); - - $client = MemcachedCache::createConnection([]); - - $this->assertTrue($client->getOption(\Memcached::OPT_COMPRESSION)); - $this->assertSame(1, $client->getOption(\Memcached::OPT_BINARY_PROTOCOL)); - $this->assertSame(1, $client->getOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE)); - } - - public function testOptionSerializer() - { - $this->expectException('Symfony\Component\Cache\Exception\CacheException'); - $this->expectExceptionMessage('MemcachedAdapter: "serializer" option must be "php" or "igbinary".'); - if (!\Memcached::HAVE_JSON) { - $this->markTestSkipped('Memcached::HAVE_JSON required'); - } - - new MemcachedCache(MemcachedCache::createConnection([], ['serializer' => 'json'])); - } - - /** - * @dataProvider provideServersSetting - */ - public function testServersSetting($dsn, $host, $port) - { - $client1 = MemcachedCache::createConnection($dsn); - $client2 = MemcachedCache::createConnection([$dsn]); - $client3 = MemcachedCache::createConnection([[$host, $port]]); - $expect = [ - 'host' => $host, - 'port' => $port, - ]; - - $f = function ($s) { return ['host' => $s['host'], 'port' => $s['port']]; }; - $this->assertSame([$expect], array_map($f, $client1->getServerList())); - $this->assertSame([$expect], array_map($f, $client2->getServerList())); - $this->assertSame([$expect], array_map($f, $client3->getServerList())); - } - - public function provideServersSetting() - { - yield [ - 'memcached://127.0.0.1/50', - '127.0.0.1', - 11211, - ]; - yield [ - 'memcached://localhost:11222?weight=25', - 'localhost', - 11222, - ]; - if (filter_var(ini_get('memcached.use_sasl'), FILTER_VALIDATE_BOOLEAN)) { - yield [ - 'memcached://user:password@127.0.0.1?weight=50', - '127.0.0.1', - 11211, - ]; - } - yield [ - 'memcached:///var/run/memcached.sock?weight=25', - '/var/run/memcached.sock', - 0, - ]; - yield [ - 'memcached:///var/local/run/memcached.socket?weight=25', - '/var/local/run/memcached.socket', - 0, - ]; - if (filter_var(ini_get('memcached.use_sasl'), FILTER_VALIDATE_BOOLEAN)) { - yield [ - 'memcached://user:password@/var/local/run/memcached.socket?weight=25', - '/var/local/run/memcached.socket', - 0, - ]; - } - } -} diff --git a/lib/symfony/cache/Tests/Simple/MemcachedCacheTextModeTest.php b/lib/symfony/cache/Tests/Simple/MemcachedCacheTextModeTest.php deleted file mode 100644 index 13865a609..000000000 --- a/lib/symfony/cache/Tests/Simple/MemcachedCacheTextModeTest.php +++ /dev/null @@ -1,25 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Simple; - -use Symfony\Component\Cache\Adapter\AbstractAdapter; -use Symfony\Component\Cache\Simple\MemcachedCache; - -class MemcachedCacheTextModeTest extends MemcachedCacheTest -{ - public function createSimpleCache($defaultLifetime = 0) - { - $client = AbstractAdapter::createConnection('memcached://'.getenv('MEMCACHED_HOST'), ['binary_protocol' => false]); - - return new MemcachedCache($client, str_replace('\\', '.', __CLASS__), $defaultLifetime); - } -} diff --git a/lib/symfony/cache/Tests/Simple/NullCacheTest.php b/lib/symfony/cache/Tests/Simple/NullCacheTest.php deleted file mode 100644 index 31f42c32b..000000000 --- a/lib/symfony/cache/Tests/Simple/NullCacheTest.php +++ /dev/null @@ -1,96 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Simple; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Cache\Simple\NullCache; - -/** - * @group time-sensitive - */ -class NullCacheTest extends TestCase -{ - public function createCachePool() - { - return new NullCache(); - } - - public function testGetItem() - { - $cache = $this->createCachePool(); - - $this->assertNull($cache->get('key')); - } - - public function testHas() - { - $this->assertFalse($this->createCachePool()->has('key')); - } - - public function testGetMultiple() - { - $cache = $this->createCachePool(); - - $keys = ['foo', 'bar', 'baz', 'biz']; - - $default = new \stdClass(); - $items = $cache->getMultiple($keys, $default); - $count = 0; - - foreach ($items as $key => $item) { - $this->assertContains($key, $keys, 'Cache key can not change.'); - $this->assertSame($default, $item); - - // Remove $key for $keys - foreach ($keys as $k => $v) { - if ($v === $key) { - unset($keys[$k]); - } - } - - ++$count; - } - - $this->assertSame(4, $count); - } - - public function testClear() - { - $this->assertTrue($this->createCachePool()->clear()); - } - - public function testDelete() - { - $this->assertTrue($this->createCachePool()->delete('key')); - } - - public function testDeleteMultiple() - { - $this->assertTrue($this->createCachePool()->deleteMultiple(['key', 'foo', 'bar'])); - } - - public function testSet() - { - $cache = $this->createCachePool(); - - $this->assertFalse($cache->set('key', 'val')); - $this->assertNull($cache->get('key')); - } - - public function testSetMultiple() - { - $cache = $this->createCachePool(); - - $this->assertFalse($cache->setMultiple(['key' => 'val'])); - $this->assertNull($cache->get('key')); - } -} diff --git a/lib/symfony/cache/Tests/Simple/PdoCacheTest.php b/lib/symfony/cache/Tests/Simple/PdoCacheTest.php deleted file mode 100644 index f5a26341f..000000000 --- a/lib/symfony/cache/Tests/Simple/PdoCacheTest.php +++ /dev/null @@ -1,47 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Simple; - -use Symfony\Component\Cache\Simple\PdoCache; -use Symfony\Component\Cache\Tests\Traits\PdoPruneableTrait; - -/** - * @group time-sensitive - */ -class PdoCacheTest extends CacheTestCase -{ - use PdoPruneableTrait; - - protected static $dbFile; - - public static function setUpBeforeClass() - { - if (!\extension_loaded('pdo_sqlite')) { - self::markTestSkipped('Extension pdo_sqlite required.'); - } - - self::$dbFile = tempnam(sys_get_temp_dir(), 'sf_sqlite_cache'); - - $pool = new PdoCache('sqlite:'.self::$dbFile); - $pool->createTable(); - } - - public static function tearDownAfterClass() - { - @unlink(self::$dbFile); - } - - public function createSimpleCache($defaultLifetime = 0) - { - return new PdoCache('sqlite:'.self::$dbFile, 'ns', $defaultLifetime); - } -} diff --git a/lib/symfony/cache/Tests/Simple/PdoDbalCacheTest.php b/lib/symfony/cache/Tests/Simple/PdoDbalCacheTest.php deleted file mode 100644 index 4da2b603c..000000000 --- a/lib/symfony/cache/Tests/Simple/PdoDbalCacheTest.php +++ /dev/null @@ -1,48 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Simple; - -use Doctrine\DBAL\DriverManager; -use Symfony\Component\Cache\Simple\PdoCache; -use Symfony\Component\Cache\Tests\Traits\PdoPruneableTrait; - -/** - * @group time-sensitive - */ -class PdoDbalCacheTest extends CacheTestCase -{ - use PdoPruneableTrait; - - protected static $dbFile; - - public static function setUpBeforeClass() - { - if (!\extension_loaded('pdo_sqlite')) { - self::markTestSkipped('Extension pdo_sqlite required.'); - } - - self::$dbFile = tempnam(sys_get_temp_dir(), 'sf_sqlite_cache'); - - $pool = new PdoCache(DriverManager::getConnection(['driver' => 'pdo_sqlite', 'path' => self::$dbFile])); - $pool->createTable(); - } - - public static function tearDownAfterClass() - { - @unlink(self::$dbFile); - } - - public function createSimpleCache($defaultLifetime = 0) - { - return new PdoCache(DriverManager::getConnection(['driver' => 'pdo_sqlite', 'path' => self::$dbFile]), '', $defaultLifetime); - } -} diff --git a/lib/symfony/cache/Tests/Simple/PhpArrayCacheTest.php b/lib/symfony/cache/Tests/Simple/PhpArrayCacheTest.php deleted file mode 100644 index c18f71442..000000000 --- a/lib/symfony/cache/Tests/Simple/PhpArrayCacheTest.php +++ /dev/null @@ -1,143 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Simple; - -use Symfony\Component\Cache\Simple\NullCache; -use Symfony\Component\Cache\Simple\PhpArrayCache; -use Symfony\Component\Cache\Tests\Adapter\FilesystemAdapterTest; - -/** - * @group time-sensitive - */ -class PhpArrayCacheTest extends CacheTestCase -{ - protected $skippedTests = [ - 'testBasicUsageWithLongKey' => 'PhpArrayCache does no writes', - - 'testDelete' => 'PhpArrayCache does no writes', - 'testDeleteMultiple' => 'PhpArrayCache does no writes', - 'testDeleteMultipleGenerator' => 'PhpArrayCache does no writes', - - 'testSetTtl' => 'PhpArrayCache does no expiration', - 'testSetMultipleTtl' => 'PhpArrayCache does no expiration', - 'testSetExpiredTtl' => 'PhpArrayCache does no expiration', - 'testSetMultipleExpiredTtl' => 'PhpArrayCache does no expiration', - - 'testGetInvalidKeys' => 'PhpArrayCache does no validation', - 'testGetMultipleInvalidKeys' => 'PhpArrayCache does no validation', - 'testSetInvalidKeys' => 'PhpArrayCache does no validation', - 'testDeleteInvalidKeys' => 'PhpArrayCache does no validation', - 'testDeleteMultipleInvalidKeys' => 'PhpArrayCache does no validation', - 'testSetInvalidTtl' => 'PhpArrayCache does no validation', - 'testSetMultipleInvalidKeys' => 'PhpArrayCache does no validation', - 'testSetMultipleInvalidTtl' => 'PhpArrayCache does no validation', - 'testHasInvalidKeys' => 'PhpArrayCache does no validation', - 'testSetValidData' => 'PhpArrayCache does no validation', - - 'testDefaultLifeTime' => 'PhpArrayCache does not allow configuring a default lifetime.', - 'testPrune' => 'PhpArrayCache just proxies', - ]; - - protected static $file; - - public static function setUpBeforeClass() - { - self::$file = sys_get_temp_dir().'/symfony-cache/php-array-adapter-test.php'; - } - - protected function tearDown() - { - if (file_exists(sys_get_temp_dir().'/symfony-cache')) { - FilesystemAdapterTest::rmdir(sys_get_temp_dir().'/symfony-cache'); - } - } - - public function createSimpleCache() - { - return new PhpArrayCacheWrapper(self::$file, new NullCache()); - } - - public function testStore() - { - $arrayWithRefs = []; - $arrayWithRefs[0] = 123; - $arrayWithRefs[1] = &$arrayWithRefs[0]; - - $object = (object) [ - 'foo' => 'bar', - 'foo2' => 'bar2', - ]; - - $expected = [ - 'null' => null, - 'serializedString' => serialize($object), - 'arrayWithRefs' => $arrayWithRefs, - 'object' => $object, - 'arrayWithObject' => ['bar' => $object], - ]; - - $cache = new PhpArrayCache(self::$file, new NullCache()); - $cache->warmUp($expected); - - foreach ($expected as $key => $value) { - $this->assertSame(serialize($value), serialize($cache->get($key)), 'Warm up should create a PHP file that OPCache can load in memory'); - } - } - - public function testStoredFile() - { - $expected = [ - 'integer' => 42, - 'float' => 42.42, - 'boolean' => true, - 'array_simple' => ['foo', 'bar'], - 'array_associative' => ['foo' => 'bar', 'foo2' => 'bar2'], - ]; - - $cache = new PhpArrayCache(self::$file, new NullCache()); - $cache->warmUp($expected); - - $values = eval(substr(file_get_contents(self::$file), 6)); - - $this->assertSame($expected, $values, 'Warm up should create a PHP file that OPCache can load in memory'); - } -} - -class PhpArrayCacheWrapper extends PhpArrayCache -{ - public function set($key, $value, $ttl = null) - { - \call_user_func(\Closure::bind(function () use ($key, $value) { - $this->values[$key] = $value; - $this->warmUp($this->values); - $this->values = eval(substr(file_get_contents($this->file), 6)); - }, $this, PhpArrayCache::class)); - - return true; - } - - public function setMultiple($values, $ttl = null) - { - if (!\is_array($values) && !$values instanceof \Traversable) { - return parent::setMultiple($values, $ttl); - } - \call_user_func(\Closure::bind(function () use ($values) { - foreach ($values as $key => $value) { - $this->values[$key] = $value; - } - $this->warmUp($this->values); - $this->values = eval(substr(file_get_contents($this->file), 6)); - }, $this, PhpArrayCache::class)); - - return true; - } -} diff --git a/lib/symfony/cache/Tests/Simple/PhpArrayCacheWithFallbackTest.php b/lib/symfony/cache/Tests/Simple/PhpArrayCacheWithFallbackTest.php deleted file mode 100644 index eba749cec..000000000 --- a/lib/symfony/cache/Tests/Simple/PhpArrayCacheWithFallbackTest.php +++ /dev/null @@ -1,55 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Simple; - -use Symfony\Component\Cache\Simple\FilesystemCache; -use Symfony\Component\Cache\Simple\PhpArrayCache; -use Symfony\Component\Cache\Tests\Adapter\FilesystemAdapterTest; - -/** - * @group time-sensitive - */ -class PhpArrayCacheWithFallbackTest extends CacheTestCase -{ - protected $skippedTests = [ - 'testGetInvalidKeys' => 'PhpArrayCache does no validation', - 'testGetMultipleInvalidKeys' => 'PhpArrayCache does no validation', - 'testDeleteInvalidKeys' => 'PhpArrayCache does no validation', - 'testDeleteMultipleInvalidKeys' => 'PhpArrayCache does no validation', - //'testSetValidData' => 'PhpArrayCache does no validation', - 'testSetInvalidKeys' => 'PhpArrayCache does no validation', - 'testSetInvalidTtl' => 'PhpArrayCache does no validation', - 'testSetMultipleInvalidKeys' => 'PhpArrayCache does no validation', - 'testSetMultipleInvalidTtl' => 'PhpArrayCache does no validation', - 'testHasInvalidKeys' => 'PhpArrayCache does no validation', - 'testPrune' => 'PhpArrayCache just proxies', - ]; - - protected static $file; - - public static function setUpBeforeClass() - { - self::$file = sys_get_temp_dir().'/symfony-cache/php-array-adapter-test.php'; - } - - protected function tearDown() - { - if (file_exists(sys_get_temp_dir().'/symfony-cache')) { - FilesystemAdapterTest::rmdir(sys_get_temp_dir().'/symfony-cache'); - } - } - - public function createSimpleCache($defaultLifetime = 0) - { - return new PhpArrayCache(self::$file, new FilesystemCache('php-array-fallback', $defaultLifetime)); - } -} diff --git a/lib/symfony/cache/Tests/Simple/PhpFilesCacheTest.php b/lib/symfony/cache/Tests/Simple/PhpFilesCacheTest.php deleted file mode 100644 index 936f29a43..000000000 --- a/lib/symfony/cache/Tests/Simple/PhpFilesCacheTest.php +++ /dev/null @@ -1,42 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Simple; - -use Psr\SimpleCache\CacheInterface; -use Symfony\Component\Cache\Simple\PhpFilesCache; - -/** - * @group time-sensitive - */ -class PhpFilesCacheTest extends CacheTestCase -{ - protected $skippedTests = [ - 'testDefaultLifeTime' => 'PhpFilesCache does not allow configuring a default lifetime.', - ]; - - public function createSimpleCache() - { - if (!PhpFilesCache::isSupported()) { - $this->markTestSkipped('OPcache extension is not enabled.'); - } - - return new PhpFilesCache('sf-cache'); - } - - protected function isPruned(CacheInterface $cache, $name) - { - $getFileMethod = (new \ReflectionObject($cache))->getMethod('getFile'); - $getFileMethod->setAccessible(true); - - return !file_exists($getFileMethod->invoke($cache, $name)); - } -} diff --git a/lib/symfony/cache/Tests/Simple/Psr6CacheTest.php b/lib/symfony/cache/Tests/Simple/Psr6CacheTest.php deleted file mode 100644 index 1bc75c906..000000000 --- a/lib/symfony/cache/Tests/Simple/Psr6CacheTest.php +++ /dev/null @@ -1,30 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Simple; - -use Symfony\Component\Cache\Adapter\FilesystemAdapter; -use Symfony\Component\Cache\Simple\Psr6Cache; - -/** - * @group time-sensitive - */ -class Psr6CacheTest extends CacheTestCase -{ - protected $skippedTests = [ - 'testPrune' => 'Psr6Cache just proxies', - ]; - - public function createSimpleCache($defaultLifetime = 0) - { - return new Psr6Cache(new FilesystemAdapter('', $defaultLifetime)); - } -} diff --git a/lib/symfony/cache/Tests/Simple/RedisArrayCacheTest.php b/lib/symfony/cache/Tests/Simple/RedisArrayCacheTest.php deleted file mode 100644 index ec5e4c06e..000000000 --- a/lib/symfony/cache/Tests/Simple/RedisArrayCacheTest.php +++ /dev/null @@ -1,24 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Simple; - -class RedisArrayCacheTest extends AbstractRedisCacheTest -{ - public static function setUpBeforeClass() - { - parent::setupBeforeClass(); - if (!class_exists('RedisArray')) { - self::markTestSkipped('The RedisArray class is required.'); - } - self::$redis = new \RedisArray([getenv('REDIS_HOST')], ['lazy_connect' => true]); - } -} diff --git a/lib/symfony/cache/Tests/Simple/RedisCacheTest.php b/lib/symfony/cache/Tests/Simple/RedisCacheTest.php deleted file mode 100644 index c2cd31a5b..000000000 --- a/lib/symfony/cache/Tests/Simple/RedisCacheTest.php +++ /dev/null @@ -1,82 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Simple; - -use Symfony\Component\Cache\Simple\RedisCache; - -class RedisCacheTest extends AbstractRedisCacheTest -{ - public static function setUpBeforeClass() - { - parent::setupBeforeClass(); - self::$redis = RedisCache::createConnection('redis://'.getenv('REDIS_HOST')); - } - - public function testCreateConnection() - { - $redisHost = getenv('REDIS_HOST'); - - $redis = RedisCache::createConnection('redis://'.$redisHost); - $this->assertInstanceOf(\Redis::class, $redis); - $this->assertTrue($redis->isConnected()); - $this->assertSame(0, $redis->getDbNum()); - - $redis = RedisCache::createConnection('redis://'.$redisHost.'/2'); - $this->assertSame(2, $redis->getDbNum()); - - $redis = RedisCache::createConnection('redis://'.$redisHost, ['timeout' => 3]); - $this->assertEquals(3, $redis->getTimeout()); - - $redis = RedisCache::createConnection('redis://'.$redisHost.'?timeout=4'); - $this->assertEquals(4, $redis->getTimeout()); - - $redis = RedisCache::createConnection('redis://'.$redisHost, ['read_timeout' => 5]); - $this->assertEquals(5, $redis->getReadTimeout()); - } - - /** - * @dataProvider provideFailedCreateConnection - */ - public function testFailedCreateConnection($dsn) - { - $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); - $this->expectExceptionMessage('Redis connection failed'); - RedisCache::createConnection($dsn); - } - - public function provideFailedCreateConnection() - { - return [ - ['redis://localhost:1234'], - ['redis://foo@localhost'], - ['redis://localhost/123'], - ]; - } - - /** - * @dataProvider provideInvalidCreateConnection - */ - public function testInvalidCreateConnection($dsn) - { - $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); - $this->expectExceptionMessage('Invalid Redis DSN'); - RedisCache::createConnection($dsn); - } - - public function provideInvalidCreateConnection() - { - return [ - ['foo://localhost'], - ['redis://'], - ]; - } -} diff --git a/lib/symfony/cache/Tests/Simple/RedisClusterCacheTest.php b/lib/symfony/cache/Tests/Simple/RedisClusterCacheTest.php deleted file mode 100644 index 6b7f8039d..000000000 --- a/lib/symfony/cache/Tests/Simple/RedisClusterCacheTest.php +++ /dev/null @@ -1,27 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Simple; - -class RedisClusterCacheTest extends AbstractRedisCacheTest -{ - public static function setUpBeforeClass() - { - if (!class_exists('RedisCluster')) { - self::markTestSkipped('The RedisCluster class is required.'); - } - if (!$hosts = getenv('REDIS_CLUSTER_HOSTS')) { - self::markTestSkipped('REDIS_CLUSTER_HOSTS env var is not defined.'); - } - - self::$redis = new \RedisCluster(null, explode(' ', $hosts)); - } -} diff --git a/lib/symfony/cache/Tests/Simple/TraceableCacheTest.php b/lib/symfony/cache/Tests/Simple/TraceableCacheTest.php deleted file mode 100644 index e684caf36..000000000 --- a/lib/symfony/cache/Tests/Simple/TraceableCacheTest.php +++ /dev/null @@ -1,171 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Simple; - -use Symfony\Component\Cache\Simple\FilesystemCache; -use Symfony\Component\Cache\Simple\TraceableCache; - -/** - * @group time-sensitive - */ -class TraceableCacheTest extends CacheTestCase -{ - protected $skippedTests = [ - 'testPrune' => 'TraceableCache just proxies', - ]; - - public function createSimpleCache($defaultLifetime = 0) - { - return new TraceableCache(new FilesystemCache('', $defaultLifetime)); - } - - public function testGetMissTrace() - { - $pool = $this->createSimpleCache(); - $pool->get('k'); - $calls = $pool->getCalls(); - $this->assertCount(1, $calls); - - $call = $calls[0]; - $this->assertSame('get', $call->name); - $this->assertSame(['k' => false], $call->result); - $this->assertSame(0, $call->hits); - $this->assertSame(1, $call->misses); - $this->assertNotEmpty($call->start); - $this->assertNotEmpty($call->end); - } - - public function testGetHitTrace() - { - $pool = $this->createSimpleCache(); - $pool->set('k', 'foo'); - $pool->get('k'); - $calls = $pool->getCalls(); - $this->assertCount(2, $calls); - - $call = $calls[1]; - $this->assertSame(1, $call->hits); - $this->assertSame(0, $call->misses); - } - - public function testGetMultipleMissTrace() - { - $pool = $this->createSimpleCache(); - $pool->set('k1', 123); - $values = $pool->getMultiple(['k0', 'k1']); - foreach ($values as $value) { - } - $calls = $pool->getCalls(); - $this->assertCount(2, $calls); - - $call = $calls[1]; - $this->assertSame('getMultiple', $call->name); - $this->assertSame(['k1' => true, 'k0' => false], $call->result); - $this->assertSame(1, $call->misses); - $this->assertNotEmpty($call->start); - $this->assertNotEmpty($call->end); - } - - public function testHasMissTrace() - { - $pool = $this->createSimpleCache(); - $pool->has('k'); - $calls = $pool->getCalls(); - $this->assertCount(1, $calls); - - $call = $calls[0]; - $this->assertSame('has', $call->name); - $this->assertSame(['k' => false], $call->result); - $this->assertNotEmpty($call->start); - $this->assertNotEmpty($call->end); - } - - public function testHasHitTrace() - { - $pool = $this->createSimpleCache(); - $pool->set('k', 'foo'); - $pool->has('k'); - $calls = $pool->getCalls(); - $this->assertCount(2, $calls); - - $call = $calls[1]; - $this->assertSame('has', $call->name); - $this->assertSame(['k' => true], $call->result); - $this->assertNotEmpty($call->start); - $this->assertNotEmpty($call->end); - } - - public function testDeleteTrace() - { - $pool = $this->createSimpleCache(); - $pool->delete('k'); - $calls = $pool->getCalls(); - $this->assertCount(1, $calls); - - $call = $calls[0]; - $this->assertSame('delete', $call->name); - $this->assertSame(['k' => true], $call->result); - $this->assertSame(0, $call->hits); - $this->assertSame(0, $call->misses); - $this->assertNotEmpty($call->start); - $this->assertNotEmpty($call->end); - } - - public function testDeleteMultipleTrace() - { - $pool = $this->createSimpleCache(); - $arg = ['k0', 'k1']; - $pool->deleteMultiple($arg); - $calls = $pool->getCalls(); - $this->assertCount(1, $calls); - - $call = $calls[0]; - $this->assertSame('deleteMultiple', $call->name); - $this->assertSame(['keys' => $arg, 'result' => true], $call->result); - $this->assertSame(0, $call->hits); - $this->assertSame(0, $call->misses); - $this->assertNotEmpty($call->start); - $this->assertNotEmpty($call->end); - } - - public function testTraceSetTrace() - { - $pool = $this->createSimpleCache(); - $pool->set('k', 'foo'); - $calls = $pool->getCalls(); - $this->assertCount(1, $calls); - - $call = $calls[0]; - $this->assertSame('set', $call->name); - $this->assertSame(['k' => true], $call->result); - $this->assertSame(0, $call->hits); - $this->assertSame(0, $call->misses); - $this->assertNotEmpty($call->start); - $this->assertNotEmpty($call->end); - } - - public function testSetMultipleTrace() - { - $pool = $this->createSimpleCache(); - $pool->setMultiple(['k' => 'foo']); - $calls = $pool->getCalls(); - $this->assertCount(1, $calls); - - $call = $calls[0]; - $this->assertSame('setMultiple', $call->name); - $this->assertSame(['keys' => ['k'], 'result' => true], $call->result); - $this->assertSame(0, $call->hits); - $this->assertSame(0, $call->misses); - $this->assertNotEmpty($call->start); - $this->assertNotEmpty($call->end); - } -} diff --git a/lib/symfony/cache/Tests/Traits/PdoPruneableTrait.php b/lib/symfony/cache/Tests/Traits/PdoPruneableTrait.php deleted file mode 100644 index 3b1e1128b..000000000 --- a/lib/symfony/cache/Tests/Traits/PdoPruneableTrait.php +++ /dev/null @@ -1,34 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Cache\Tests\Traits; - -trait PdoPruneableTrait -{ - protected function isPruned($cache, $name) - { - $o = new \ReflectionObject($cache); - - if (!$o->hasMethod('getConnection')) { - self::fail('Cache does not have "getConnection()" method.'); - } - - $getPdoConn = $o->getMethod('getConnection'); - $getPdoConn->setAccessible(true); - - /** @var \Doctrine\DBAL\Statement $select */ - $select = $getPdoConn->invoke($cache)->prepare('SELECT 1 FROM cache_items WHERE item_id LIKE :id'); - $select->bindValue(':id', sprintf('%%%s', $name)); - $select->execute(); - - return 0 === \count($select->fetchAll(\PDO::FETCH_COLUMN)); - } -} diff --git a/lib/symfony/class-loader/Tests/ApcClassLoaderTest.php b/lib/symfony/class-loader/Tests/ApcClassLoaderTest.php deleted file mode 100644 index 6706acbd3..000000000 --- a/lib/symfony/class-loader/Tests/ApcClassLoaderTest.php +++ /dev/null @@ -1,200 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\ClassLoader\Tests; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\ClassLoader\ApcClassLoader; -use Symfony\Component\ClassLoader\ClassLoader; - -/** - * @group legacy - */ -class ApcClassLoaderTest extends TestCase -{ - protected function setUp() - { - if (!(filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) && filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOLEAN))) { - $this->markTestSkipped('The apc extension is not enabled.'); - } else { - apcu_clear_cache(); - } - } - - protected function tearDown() - { - if (filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) && filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOLEAN)) { - apcu_clear_cache(); - } - } - - public function testConstructor() - { - $loader = new ClassLoader(); - $loader->addPrefix('Apc\Namespaced', __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'); - - $loader = new ApcClassLoader('test.prefix.', $loader); - - $this->assertEquals($loader->findFile('\Apc\Namespaced\FooBar'), apcu_fetch('test.prefix.\Apc\Namespaced\FooBar'), '__construct() takes a prefix as its first argument'); - } - - /** - * @dataProvider getLoadClassTests - */ - public function testLoadClass($className, $testClassName, $message) - { - $loader = new ClassLoader(); - $loader->addPrefix('Apc\Namespaced', __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'); - $loader->addPrefix('Apc_Pearlike_', __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'); - - $loader = new ApcClassLoader('test.prefix.', $loader); - $loader->loadClass($testClassName); - $this->assertTrue(class_exists($className), $message); - } - - public function getLoadClassTests() - { - return [ - ['\\Apc\\Namespaced\\Foo', 'Apc\\Namespaced\\Foo', '->loadClass() loads Apc\Namespaced\Foo class'], - ['Apc_Pearlike_Foo', 'Apc_Pearlike_Foo', '->loadClass() loads Apc_Pearlike_Foo class'], - ]; - } - - /** - * @dataProvider getLoadClassFromFallbackTests - */ - public function testLoadClassFromFallback($className, $testClassName, $message) - { - $loader = new ClassLoader(); - $loader->addPrefix('Apc\Namespaced', __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'); - $loader->addPrefix('Apc_Pearlike_', __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'); - $loader->addPrefix('', [__DIR__.\DIRECTORY_SEPARATOR.'Fixtures/Apc/fallback']); - - $loader = new ApcClassLoader('test.prefix.fallback', $loader); - $loader->loadClass($testClassName); - - $this->assertTrue(class_exists($className), $message); - } - - public function getLoadClassFromFallbackTests() - { - return [ - ['\\Apc\\Namespaced\\Baz', 'Apc\\Namespaced\\Baz', '->loadClass() loads Apc\Namespaced\Baz class'], - ['Apc_Pearlike_Baz', 'Apc_Pearlike_Baz', '->loadClass() loads Apc_Pearlike_Baz class'], - ['\\Apc\\Namespaced\\FooBar', 'Apc\\Namespaced\\FooBar', '->loadClass() loads Apc\Namespaced\Baz class from fallback dir'], - ['Apc_Pearlike_FooBar', 'Apc_Pearlike_FooBar', '->loadClass() loads Apc_Pearlike_Baz class from fallback dir'], - ]; - } - - /** - * @dataProvider getLoadClassNamespaceCollisionTests - */ - public function testLoadClassNamespaceCollision($namespaces, $className, $message) - { - $loader = new ClassLoader(); - $loader->addPrefixes($namespaces); - - $loader = new ApcClassLoader('test.prefix.collision.', $loader); - $loader->loadClass($className); - - $this->assertTrue(class_exists($className), $message); - } - - public function getLoadClassNamespaceCollisionTests() - { - return [ - [ - [ - 'Apc\\NamespaceCollision\\A' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha', - 'Apc\\NamespaceCollision\\A\\B' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/Apc/beta', - ], - 'Apc\NamespaceCollision\A\Foo', - '->loadClass() loads NamespaceCollision\A\Foo from alpha.', - ], - [ - [ - 'Apc\\NamespaceCollision\\A\\B' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/Apc/beta', - 'Apc\\NamespaceCollision\\A' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha', - ], - 'Apc\NamespaceCollision\A\Bar', - '->loadClass() loads NamespaceCollision\A\Bar from alpha.', - ], - [ - [ - 'Apc\\NamespaceCollision\\A' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha', - 'Apc\\NamespaceCollision\\A\\B' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/Apc/beta', - ], - 'Apc\NamespaceCollision\A\B\Foo', - '->loadClass() loads NamespaceCollision\A\B\Foo from beta.', - ], - [ - [ - 'Apc\\NamespaceCollision\\A\\B' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/Apc/beta', - 'Apc\\NamespaceCollision\\A' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha', - ], - 'Apc\NamespaceCollision\A\B\Bar', - '->loadClass() loads NamespaceCollision\A\B\Bar from beta.', - ], - ]; - } - - /** - * @dataProvider getLoadClassPrefixCollisionTests - */ - public function testLoadClassPrefixCollision($prefixes, $className, $message) - { - $loader = new ClassLoader(); - $loader->addPrefixes($prefixes); - - $loader = new ApcClassLoader('test.prefix.collision.', $loader); - $loader->loadClass($className); - - $this->assertTrue(class_exists($className), $message); - } - - public function getLoadClassPrefixCollisionTests() - { - return [ - [ - [ - 'ApcPrefixCollision_A_' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha/Apc', - 'ApcPrefixCollision_A_B_' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/Apc/beta/Apc', - ], - 'ApcPrefixCollision_A_Foo', - '->loadClass() loads ApcPrefixCollision_A_Foo from alpha.', - ], - [ - [ - 'ApcPrefixCollision_A_B_' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/Apc/beta/Apc', - 'ApcPrefixCollision_A_' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha/Apc', - ], - 'ApcPrefixCollision_A_Bar', - '->loadClass() loads ApcPrefixCollision_A_Bar from alpha.', - ], - [ - [ - 'ApcPrefixCollision_A_' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha/Apc', - 'ApcPrefixCollision_A_B_' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/Apc/beta/Apc', - ], - 'ApcPrefixCollision_A_B_Foo', - '->loadClass() loads ApcPrefixCollision_A_B_Foo from beta.', - ], - [ - [ - 'ApcPrefixCollision_A_B_' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/Apc/beta/Apc', - 'ApcPrefixCollision_A_' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha/Apc', - ], - 'ApcPrefixCollision_A_B_Bar', - '->loadClass() loads ApcPrefixCollision_A_B_Bar from beta.', - ], - ]; - } -} diff --git a/lib/symfony/class-loader/Tests/ClassCollectionLoaderTest.php b/lib/symfony/class-loader/Tests/ClassCollectionLoaderTest.php deleted file mode 100644 index e1d5f56de..000000000 --- a/lib/symfony/class-loader/Tests/ClassCollectionLoaderTest.php +++ /dev/null @@ -1,317 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\ClassLoader\Tests; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\ClassLoader\ClassCollectionLoader; -use Symfony\Component\ClassLoader\Tests\Fixtures\DeclaredClass; -use Symfony\Component\ClassLoader\Tests\Fixtures\WarmedClass; - -require_once __DIR__.'/Fixtures/ClassesWithParents/GInterface.php'; -require_once __DIR__.'/Fixtures/ClassesWithParents/CInterface.php'; -require_once __DIR__.'/Fixtures/ClassesWithParents/B.php'; -require_once __DIR__.'/Fixtures/ClassesWithParents/A.php'; - -/** - * @group legacy - */ -class ClassCollectionLoaderTest extends TestCase -{ - public function testTraitDependencies() - { - require_once __DIR__.'/Fixtures/deps/traits.php'; - - $r = new \ReflectionClass('Symfony\Component\ClassLoader\ClassCollectionLoader'); - $m = $r->getMethod('getOrderedClasses'); - $m->setAccessible(true); - - $ordered = $m->invoke(null, ['CTFoo']); - - $this->assertEquals( - ['TD', 'TC', 'TB', 'TA', 'TZ', 'CTFoo'], - array_map(function ($class) { return $class->getName(); }, $ordered) - ); - - $ordered = $m->invoke(null, ['CTBar']); - - $this->assertEquals( - ['TD', 'TZ', 'TC', 'TB', 'TA', 'CTBar'], - array_map(function ($class) { return $class->getName(); }, $ordered) - ); - } - - /** - * @dataProvider getDifferentOrders - */ - public function testClassReordering(array $classes) - { - $expected = [ - 'ClassesWithParents\\GInterface', - 'ClassesWithParents\\CInterface', - 'ClassesWithParents\\B', - 'ClassesWithParents\\A', - ]; - - $r = new \ReflectionClass('Symfony\Component\ClassLoader\ClassCollectionLoader'); - $m = $r->getMethod('getOrderedClasses'); - $m->setAccessible(true); - - $ordered = $m->invoke(null, $classes); - - $this->assertEquals($expected, array_map(function ($class) { return $class->getName(); }, $ordered)); - } - - public function getDifferentOrders() - { - return [ - [[ - 'ClassesWithParents\\A', - 'ClassesWithParents\\CInterface', - 'ClassesWithParents\\GInterface', - 'ClassesWithParents\\B', - ]], - [[ - 'ClassesWithParents\\B', - 'ClassesWithParents\\A', - 'ClassesWithParents\\CInterface', - ]], - [[ - 'ClassesWithParents\\CInterface', - 'ClassesWithParents\\B', - 'ClassesWithParents\\A', - ]], - [[ - 'ClassesWithParents\\A', - ]], - ]; - } - - /** - * @dataProvider getDifferentOrdersForTraits - */ - public function testClassWithTraitsReordering(array $classes) - { - require_once __DIR__.'/Fixtures/ClassesWithParents/ATrait.php'; - require_once __DIR__.'/Fixtures/ClassesWithParents/BTrait.php'; - require_once __DIR__.'/Fixtures/ClassesWithParents/CTrait.php'; - require_once __DIR__.'/Fixtures/ClassesWithParents/D.php'; - require_once __DIR__.'/Fixtures/ClassesWithParents/E.php'; - - $expected = [ - 'ClassesWithParents\\GInterface', - 'ClassesWithParents\\CInterface', - 'ClassesWithParents\\ATrait', - 'ClassesWithParents\\BTrait', - 'ClassesWithParents\\CTrait', - 'ClassesWithParents\\B', - 'ClassesWithParents\\A', - 'ClassesWithParents\\D', - 'ClassesWithParents\\E', - ]; - - $r = new \ReflectionClass('Symfony\Component\ClassLoader\ClassCollectionLoader'); - $m = $r->getMethod('getOrderedClasses'); - $m->setAccessible(true); - - $ordered = $m->invoke(null, $classes); - - $this->assertEquals($expected, array_map(function ($class) { return $class->getName(); }, $ordered)); - } - - public function getDifferentOrdersForTraits() - { - return [ - [[ - 'ClassesWithParents\\E', - 'ClassesWithParents\\ATrait', - ]], - [[ - 'ClassesWithParents\\E', - ]], - ]; - } - - public function testFixClassWithTraitsOrdering() - { - require_once __DIR__.'/Fixtures/ClassesWithParents/CTrait.php'; - require_once __DIR__.'/Fixtures/ClassesWithParents/F.php'; - require_once __DIR__.'/Fixtures/ClassesWithParents/G.php'; - - $classes = [ - 'ClassesWithParents\\F', - 'ClassesWithParents\\G', - ]; - - $expected = [ - 'ClassesWithParents\\CTrait', - 'ClassesWithParents\\F', - 'ClassesWithParents\\G', - ]; - - $r = new \ReflectionClass('Symfony\Component\ClassLoader\ClassCollectionLoader'); - $m = $r->getMethod('getOrderedClasses'); - $m->setAccessible(true); - - $ordered = $m->invoke(null, $classes); - - $this->assertEquals($expected, array_map(function ($class) { return $class->getName(); }, $ordered)); - } - - /** - * @dataProvider getFixNamespaceDeclarationsData - */ - public function testFixNamespaceDeclarations($source, $expected) - { - $this->assertEquals('assertEquals('expectException('InvalidArgumentException'); - if (is_file($file = sys_get_temp_dir().'/foo.php')) { - unlink($file); - } - - ClassCollectionLoader::load(['SomeNotExistingClass'], sys_get_temp_dir(), 'foo', false); - } - - public function testCommentStripping() - { - if (is_file($file = __DIR__.'/bar.php')) { - unlink($file); - } - spl_autoload_register($r = function ($class) { - if (0 === strpos($class, 'Namespaced') || 0 === strpos($class, 'Pearlike_')) { - @require_once __DIR__.'/Fixtures/'.str_replace(['\\', '_'], '/', $class).'.php'; - } - }); - - $strictTypes = \defined('HHVM_VERSION') ? '' : "\nnamespace {require __DIR__.'/Fixtures/Namespaced/WithStrictTypes.php';}"; - - ClassCollectionLoader::load( - ['Namespaced\\WithComments', 'Pearlike_WithComments', 'Namespaced\\WithDirMagic', 'Namespaced\\WithFileMagic', 'Namespaced\\WithHaltCompiler', $strictTypes ? 'Namespaced\\WithStrictTypes' : 'Namespaced\\WithComments'], - __DIR__, - 'bar', - false - ); - - spl_autoload_unregister($r); - - $this->assertEquals(<<<'EOF' -namespace Namespaced -{ -class WithComments -{ -public static $loaded = true; -} -$string ='string should not be modified {$string}'; -$heredoc = (<<assertTrue(class_exists(WarmedClass::class, true)); - - @unlink($cache = sys_get_temp_dir().'/inline.php'); - - $classes = [WarmedClass::class]; - $excluded = [DeclaredClass::class]; - - ClassCollectionLoader::inline($classes, $cache, $excluded); - - $this->assertSame(<<<'EOTXT' - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\ClassLoader\Tests; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\ClassLoader\ClassLoader; - -/** - * @group legacy - */ -class ClassLoaderTest extends TestCase -{ - public function testGetPrefixes() - { - $loader = new ClassLoader(); - $loader->addPrefix('Foo', __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'); - $loader->addPrefix('Bar', __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'); - $loader->addPrefix('Bas', __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'); - $prefixes = $loader->getPrefixes(); - $this->assertArrayHasKey('Foo', $prefixes); - $this->assertArrayNotHasKey('Foo1', $prefixes); - $this->assertArrayHasKey('Bar', $prefixes); - $this->assertArrayHasKey('Bas', $prefixes); - } - - public function testGetFallbackDirs() - { - $loader = new ClassLoader(); - $loader->addPrefix(null, __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'); - $loader->addPrefix(null, __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'); - $fallback_dirs = $loader->getFallbackDirs(); - $this->assertCount(2, $fallback_dirs); - } - - /** - * @dataProvider getLoadClassTests - */ - public function testLoadClass($className, $testClassName, $message) - { - $loader = new ClassLoader(); - $loader->addPrefix('Namespaced2\\', __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'); - $loader->addPrefix('Pearlike2_', __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'); - $loader->loadClass($testClassName); - $this->assertTrue(class_exists($className), $message); - } - - public function getLoadClassTests() - { - return [ - ['\\Namespaced2\\Foo', 'Namespaced2\\Foo', '->loadClass() loads Namespaced2\Foo class'], - ['\\Pearlike2_Foo', 'Pearlike2_Foo', '->loadClass() loads Pearlike2_Foo class'], - ]; - } - - /** - * @dataProvider getLoadNonexistentClassTests - */ - public function testLoadNonexistentClass($className, $testClassName, $message) - { - $loader = new ClassLoader(); - $loader->addPrefix('Namespaced2\\', __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'); - $loader->addPrefix('Pearlike2_', __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'); - $loader->loadClass($testClassName); - $this->assertFalse(class_exists($className), $message); - } - - public function getLoadNonexistentClassTests() - { - return [ - ['\\Pearlike3_Bar', '\\Pearlike3_Bar', '->loadClass() loads non existing Pearlike3_Bar class with a leading slash'], - ]; - } - - public function testAddPrefixSingle() - { - $loader = new ClassLoader(); - $loader->addPrefix('Foo', __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'); - $loader->addPrefix('Foo', __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'); - $prefixes = $loader->getPrefixes(); - $this->assertArrayHasKey('Foo', $prefixes); - $this->assertCount(1, $prefixes['Foo']); - } - - public function testAddPrefixesSingle() - { - $loader = new ClassLoader(); - $loader->addPrefixes(['Foo' => ['foo', 'foo']]); - $loader->addPrefixes(['Foo' => ['foo']]); - $prefixes = $loader->getPrefixes(); - $this->assertArrayHasKey('Foo', $prefixes); - $this->assertCount(1, $prefixes['Foo'], print_r($prefixes, true)); - } - - public function testAddPrefixMulti() - { - $loader = new ClassLoader(); - $loader->addPrefix('Foo', 'foo'); - $loader->addPrefix('Foo', 'bar'); - $prefixes = $loader->getPrefixes(); - $this->assertArrayHasKey('Foo', $prefixes); - $this->assertCount(2, $prefixes['Foo']); - $this->assertContains('foo', $prefixes['Foo']); - $this->assertContains('bar', $prefixes['Foo']); - } - - public function testUseIncludePath() - { - $loader = new ClassLoader(); - $this->assertFalse($loader->getUseIncludePath()); - - $this->assertNull($loader->findFile('Foo')); - - $includePath = get_include_path(); - - $loader->setUseIncludePath(true); - $this->assertTrue($loader->getUseIncludePath()); - - set_include_path(__DIR__.'/Fixtures/includepath'.PATH_SEPARATOR.$includePath); - - $this->assertEquals(__DIR__.\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR.'includepath'.\DIRECTORY_SEPARATOR.'Foo.php', $loader->findFile('Foo')); - - set_include_path($includePath); - } - - /** - * @dataProvider getLoadClassFromFallbackTests - */ - public function testLoadClassFromFallback($className, $testClassName, $message) - { - $loader = new ClassLoader(); - $loader->addPrefix('Namespaced2\\', __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'); - $loader->addPrefix('Pearlike2_', __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'); - $loader->addPrefix('', [__DIR__.\DIRECTORY_SEPARATOR.'Fixtures/fallback']); - $loader->loadClass($testClassName); - $this->assertTrue(class_exists($className), $message); - } - - public function getLoadClassFromFallbackTests() - { - return [ - ['\\Namespaced2\\Baz', 'Namespaced2\\Baz', '->loadClass() loads Namespaced2\Baz class'], - ['\\Pearlike2_Baz', 'Pearlike2_Baz', '->loadClass() loads Pearlike2_Baz class'], - ['\\Namespaced2\\FooBar', 'Namespaced2\\FooBar', '->loadClass() loads Namespaced2\Baz class from fallback dir'], - ['\\Pearlike2_FooBar', 'Pearlike2_FooBar', '->loadClass() loads Pearlike2_Baz class from fallback dir'], - ]; - } - - /** - * @dataProvider getLoadClassNamespaceCollisionTests - */ - public function testLoadClassNamespaceCollision($namespaces, $className, $message) - { - $loader = new ClassLoader(); - $loader->addPrefixes($namespaces); - - $loader->loadClass($className); - $this->assertTrue(class_exists($className), $message); - } - - public function getLoadClassNamespaceCollisionTests() - { - return [ - [ - [ - 'NamespaceCollision\\C' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/alpha', - 'NamespaceCollision\\C\\B' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/beta', - ], - 'NamespaceCollision\C\Foo', - '->loadClass() loads NamespaceCollision\C\Foo from alpha.', - ], - [ - [ - 'NamespaceCollision\\C\\B' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/beta', - 'NamespaceCollision\\C' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/alpha', - ], - 'NamespaceCollision\C\Bar', - '->loadClass() loads NamespaceCollision\C\Bar from alpha.', - ], - [ - [ - 'NamespaceCollision\\C' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/alpha', - 'NamespaceCollision\\C\\B' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/beta', - ], - 'NamespaceCollision\C\B\Foo', - '->loadClass() loads NamespaceCollision\C\B\Foo from beta.', - ], - [ - [ - 'NamespaceCollision\\C\\B' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/beta', - 'NamespaceCollision\\C' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/alpha', - ], - 'NamespaceCollision\C\B\Bar', - '->loadClass() loads NamespaceCollision\C\B\Bar from beta.', - ], - [ - [ - 'PrefixCollision_C_' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/alpha', - 'PrefixCollision_C_B_' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/beta', - ], - 'PrefixCollision_C_Foo', - '->loadClass() loads PrefixCollision_C_Foo from alpha.', - ], - [ - [ - 'PrefixCollision_C_B_' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/beta', - 'PrefixCollision_C_' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/alpha', - ], - 'PrefixCollision_C_Bar', - '->loadClass() loads PrefixCollision_C_Bar from alpha.', - ], - [ - [ - 'PrefixCollision_C_' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/alpha', - 'PrefixCollision_C_B_' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/beta', - ], - 'PrefixCollision_C_B_Foo', - '->loadClass() loads PrefixCollision_C_B_Foo from beta.', - ], - [ - [ - 'PrefixCollision_C_B_' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/beta', - 'PrefixCollision_C_' => __DIR__.\DIRECTORY_SEPARATOR.'Fixtures/alpha', - ], - 'PrefixCollision_C_B_Bar', - '->loadClass() loads PrefixCollision_C_B_Bar from beta.', - ], - ]; - } -} diff --git a/lib/symfony/class-loader/Tests/ClassMapGeneratorTest.php b/lib/symfony/class-loader/Tests/ClassMapGeneratorTest.php deleted file mode 100644 index 911066018..000000000 --- a/lib/symfony/class-loader/Tests/ClassMapGeneratorTest.php +++ /dev/null @@ -1,151 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\ClassLoader\Tests; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\ClassLoader\ClassMapGenerator; - -/** - * @group legacy - */ -class ClassMapGeneratorTest extends TestCase -{ - /** - * @var string|null - */ - private $workspace = null; - - public function prepare_workspace() - { - $this->workspace = sys_get_temp_dir().'/'.microtime(true).'.'.mt_rand(); - mkdir($this->workspace, 0777, true); - $this->workspace = realpath($this->workspace); - } - - /** - * @param string $file - */ - private function clean($file) - { - if (is_dir($file) && !is_link($file)) { - $dir = new \FilesystemIterator($file); - foreach ($dir as $childFile) { - $this->clean($childFile); - } - - rmdir($file); - } else { - unlink($file); - } - } - - /** - * @dataProvider getTestCreateMapTests - */ - public function testDump($directory) - { - $this->prepare_workspace(); - - $file = $this->workspace.'/file'; - - $generator = new ClassMapGenerator(); - $generator->dump($directory, $file); - $this->assertFileExists($file); - - $this->clean($this->workspace); - } - - /** - * @dataProvider getTestCreateMapTests - */ - public function testCreateMap($directory, $expected) - { - $this->assertEqualsNormalized($expected, ClassMapGenerator::createMap($directory)); - } - - public function getTestCreateMapTests() - { - $data = [ - [__DIR__.'/Fixtures/Namespaced', [ - 'Namespaced\\Bar' => realpath(__DIR__).'/Fixtures/Namespaced/Bar.php', - 'Namespaced\\Foo' => realpath(__DIR__).'/Fixtures/Namespaced/Foo.php', - 'Namespaced\\Baz' => realpath(__DIR__).'/Fixtures/Namespaced/Baz.php', - 'Namespaced\\WithComments' => realpath(__DIR__).'/Fixtures/Namespaced/WithComments.php', - 'Namespaced\\WithStrictTypes' => realpath(__DIR__).'/Fixtures/Namespaced/WithStrictTypes.php', - 'Namespaced\\WithHaltCompiler' => realpath(__DIR__).'/Fixtures/Namespaced/WithHaltCompiler.php', - 'Namespaced\\WithDirMagic' => realpath(__DIR__).'/Fixtures/Namespaced/WithDirMagic.php', - 'Namespaced\\WithFileMagic' => realpath(__DIR__).'/Fixtures/Namespaced/WithFileMagic.php', - ]], - [__DIR__.'/Fixtures/beta/NamespaceCollision', [ - 'NamespaceCollision\\A\\B\\Bar' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/A/B/Bar.php', - 'NamespaceCollision\\A\\B\\Foo' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/A/B/Foo.php', - 'NamespaceCollision\\C\\B\\Bar' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/C/B/Bar.php', - 'NamespaceCollision\\C\\B\\Foo' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/C/B/Foo.php', - ]], - [__DIR__.'/Fixtures/Pearlike', [ - 'Pearlike_Foo' => realpath(__DIR__).'/Fixtures/Pearlike/Foo.php', - 'Pearlike_Bar' => realpath(__DIR__).'/Fixtures/Pearlike/Bar.php', - 'Pearlike_Baz' => realpath(__DIR__).'/Fixtures/Pearlike/Baz.php', - 'Pearlike_WithComments' => realpath(__DIR__).'/Fixtures/Pearlike/WithComments.php', - ]], - [__DIR__.'/Fixtures/classmap', [ - 'Foo\\Bar\\A' => realpath(__DIR__).'/Fixtures/classmap/sameNsMultipleClasses.php', - 'Foo\\Bar\\B' => realpath(__DIR__).'/Fixtures/classmap/sameNsMultipleClasses.php', - 'A' => realpath(__DIR__).'/Fixtures/classmap/multipleNs.php', - 'Alpha\\A' => realpath(__DIR__).'/Fixtures/classmap/multipleNs.php', - 'Alpha\\B' => realpath(__DIR__).'/Fixtures/classmap/multipleNs.php', - 'Beta\\A' => realpath(__DIR__).'/Fixtures/classmap/multipleNs.php', - 'Beta\\B' => realpath(__DIR__).'/Fixtures/classmap/multipleNs.php', - 'ClassMap\\SomeInterface' => realpath(__DIR__).'/Fixtures/classmap/SomeInterface.php', - 'ClassMap\\SomeParent' => realpath(__DIR__).'/Fixtures/classmap/SomeParent.php', - 'ClassMap\\SomeClass' => realpath(__DIR__).'/Fixtures/classmap/SomeClass.php', - ]], - [__DIR__.'/Fixtures/php5.4', [ - 'TFoo' => __DIR__.'/Fixtures/php5.4/traits.php', - 'CFoo' => __DIR__.'/Fixtures/php5.4/traits.php', - 'Foo\\TBar' => __DIR__.'/Fixtures/php5.4/traits.php', - 'Foo\\IBar' => __DIR__.'/Fixtures/php5.4/traits.php', - 'Foo\\TFooBar' => __DIR__.'/Fixtures/php5.4/traits.php', - 'Foo\\CBar' => __DIR__.'/Fixtures/php5.4/traits.php', - ]], - [__DIR__.'/Fixtures/php5.5', [ - 'ClassCons\\Foo' => __DIR__.'/Fixtures/php5.5/class_cons.php', - ]], - ]; - - return $data; - } - - public function testCreateMapFinderSupport() - { - $finder = new \Symfony\Component\Finder\Finder(); - $finder->files()->in(__DIR__.'/Fixtures/beta/NamespaceCollision'); - - $this->assertEqualsNormalized([ - 'NamespaceCollision\\A\\B\\Bar' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/A/B/Bar.php', - 'NamespaceCollision\\A\\B\\Foo' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/A/B/Foo.php', - 'NamespaceCollision\\C\\B\\Bar' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/C/B/Bar.php', - 'NamespaceCollision\\C\\B\\Foo' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/C/B/Foo.php', - ], ClassMapGenerator::createMap($finder)); - } - - protected function assertEqualsNormalized($expected, $actual, $message = '') - { - foreach ($expected as $ns => $path) { - $expected[$ns] = str_replace('\\', '/', $path); - } - foreach ($actual as $ns => $path) { - $actual[$ns] = str_replace('\\', '/', $path); - } - $this->assertEquals($expected, $actual, $message); - } -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/Apc/Namespaced/Bar.php b/lib/symfony/class-loader/Tests/Fixtures/Apc/Namespaced/Bar.php deleted file mode 100644 index 4259f1451..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/Apc/Namespaced/Bar.php +++ /dev/null @@ -1,17 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Apc\Namespaced; - -class Bar -{ - public static $loaded = true; -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/Apc/Namespaced/Baz.php b/lib/symfony/class-loader/Tests/Fixtures/Apc/Namespaced/Baz.php deleted file mode 100644 index 3ddb595e2..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/Apc/Namespaced/Baz.php +++ /dev/null @@ -1,17 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Apc\Namespaced; - -class Baz -{ - public static $loaded = true; -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/Apc/Namespaced/Foo.php b/lib/symfony/class-loader/Tests/Fixtures/Apc/Namespaced/Foo.php deleted file mode 100644 index cf0a4b741..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/Apc/Namespaced/Foo.php +++ /dev/null @@ -1,17 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Apc\Namespaced; - -class Foo -{ - public static $loaded = true; -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/Apc/Namespaced/FooBar.php b/lib/symfony/class-loader/Tests/Fixtures/Apc/Namespaced/FooBar.php deleted file mode 100644 index bbbc81515..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/Apc/Namespaced/FooBar.php +++ /dev/null @@ -1,17 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Apc\Namespaced; - -class FooBar -{ - public static $loaded = true; -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/Apc/Pearlike/Bar.php b/lib/symfony/class-loader/Tests/Fixtures/Apc/Pearlike/Bar.php deleted file mode 100644 index e774cb9bf..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/Apc/Pearlike/Bar.php +++ /dev/null @@ -1,6 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Apc\NamespaceCollision\A; - -class Bar -{ - public static $loaded = true; -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/Apc/alpha/Apc/NamespaceCollision/A/Foo.php b/lib/symfony/class-loader/Tests/Fixtures/Apc/alpha/Apc/NamespaceCollision/A/Foo.php deleted file mode 100644 index 184a1b1da..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/Apc/alpha/Apc/NamespaceCollision/A/Foo.php +++ /dev/null @@ -1,17 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Apc\NamespaceCollision\A; - -class Foo -{ - public static $loaded = true; -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/Apc/beta/Apc/ApcPrefixCollision/A/B/Bar.php b/lib/symfony/class-loader/Tests/Fixtures/Apc/beta/Apc/ApcPrefixCollision/A/B/Bar.php deleted file mode 100644 index 3892f7068..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/Apc/beta/Apc/ApcPrefixCollision/A/B/Bar.php +++ /dev/null @@ -1,6 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Apc\NamespaceCollision\A\B; - -class Bar -{ - public static $loaded = true; -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/Apc/beta/Apc/NamespaceCollision/A/B/Foo.php b/lib/symfony/class-loader/Tests/Fixtures/Apc/beta/Apc/NamespaceCollision/A/B/Foo.php deleted file mode 100644 index 450eeb50b..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/Apc/beta/Apc/NamespaceCollision/A/B/Foo.php +++ /dev/null @@ -1,17 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Apc\NamespaceCollision\A\B; - -class Foo -{ - public static $loaded = true; -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/Apc/fallback/Apc/Pearlike/FooBar.php b/lib/symfony/class-loader/Tests/Fixtures/Apc/fallback/Apc/Pearlike/FooBar.php deleted file mode 100644 index 96f2f76c6..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/Apc/fallback/Apc/Pearlike/FooBar.php +++ /dev/null @@ -1,6 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Apc\Namespaced; - -class FooBar -{ - public static $loaded = true; -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/ClassesWithParents/A.php b/lib/symfony/class-loader/Tests/Fixtures/ClassesWithParents/A.php deleted file mode 100644 index b0f942595..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/ClassesWithParents/A.php +++ /dev/null @@ -1,7 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Namespaced; - -class Bar -{ - public static $loaded = true; -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/Namespaced/Baz.php b/lib/symfony/class-loader/Tests/Fixtures/Namespaced/Baz.php deleted file mode 100644 index 0b0bbd057..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/Namespaced/Baz.php +++ /dev/null @@ -1,17 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Namespaced; - -class Baz -{ - public static $loaded = true; -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/Namespaced/Foo.php b/lib/symfony/class-loader/Tests/Fixtures/Namespaced/Foo.php deleted file mode 100644 index df5e1f4ce..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/Namespaced/Foo.php +++ /dev/null @@ -1,17 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Namespaced; - -class Foo -{ - public static $loaded = true; -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/Namespaced/WithComments.php b/lib/symfony/class-loader/Tests/Fixtures/Namespaced/WithComments.php deleted file mode 100644 index 361e53de1..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/Namespaced/WithComments.php +++ /dev/null @@ -1,37 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Namespaced; - -class WithComments -{ - /** @Boolean */ - public static $loaded = true; -} - -$string = 'string should not be modified {$string}'; - -$heredoc = (<< - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -class Pearlike_WithComments -{ - /** @Boolean */ - public static $loaded = true; -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/Pearlike2/Bar.php b/lib/symfony/class-loader/Tests/Fixtures/Pearlike2/Bar.php deleted file mode 100644 index 7f5f79773..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/Pearlike2/Bar.php +++ /dev/null @@ -1,6 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace NamespaceCollision\A; - -class Bar -{ - public static $loaded = true; -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/alpha/NamespaceCollision/A/Foo.php b/lib/symfony/class-loader/Tests/Fixtures/alpha/NamespaceCollision/A/Foo.php deleted file mode 100644 index aee6a080d..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/alpha/NamespaceCollision/A/Foo.php +++ /dev/null @@ -1,17 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace NamespaceCollision\A; - -class Foo -{ - public static $loaded = true; -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/alpha/NamespaceCollision/C/Bar.php b/lib/symfony/class-loader/Tests/Fixtures/alpha/NamespaceCollision/C/Bar.php deleted file mode 100644 index c1b8dd65d..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/alpha/NamespaceCollision/C/Bar.php +++ /dev/null @@ -1,8 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace NamespaceCollision\A\B; - -class Bar -{ - public static $loaded = true; -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/beta/NamespaceCollision/A/B/Foo.php b/lib/symfony/class-loader/Tests/Fixtures/beta/NamespaceCollision/A/B/Foo.php deleted file mode 100644 index f5f2d727e..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/beta/NamespaceCollision/A/B/Foo.php +++ /dev/null @@ -1,17 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace NamespaceCollision\A\B; - -class Foo -{ - public static $loaded = true; -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/beta/NamespaceCollision/C/B/Bar.php b/lib/symfony/class-loader/Tests/Fixtures/beta/NamespaceCollision/C/B/Bar.php deleted file mode 100644 index 4bb03dc7f..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/beta/NamespaceCollision/C/B/Bar.php +++ /dev/null @@ -1,8 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace ClassMap; - -class SomeClass extends SomeParent implements SomeInterface -{ -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/classmap/SomeInterface.php b/lib/symfony/class-loader/Tests/Fixtures/classmap/SomeInterface.php deleted file mode 100644 index 1fe5e09aa..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/classmap/SomeInterface.php +++ /dev/null @@ -1,16 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace ClassMap; - -interface SomeInterface -{ -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/classmap/SomeParent.php b/lib/symfony/class-loader/Tests/Fixtures/classmap/SomeParent.php deleted file mode 100644 index ce2f9fc6c..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/classmap/SomeParent.php +++ /dev/null @@ -1,16 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace ClassMap; - -abstract class SomeParent -{ -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/classmap/multipleNs.php b/lib/symfony/class-loader/Tests/Fixtures/classmap/multipleNs.php deleted file mode 100644 index c7cec646f..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/classmap/multipleNs.php +++ /dev/null @@ -1,25 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Foo\Bar; - -class A -{ -} -class B -{ -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/deps/traits.php b/lib/symfony/class-loader/Tests/Fixtures/deps/traits.php deleted file mode 100644 index 82b30a6f9..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/deps/traits.php +++ /dev/null @@ -1,37 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Namespaced; - -class FooBar -{ - public static $loaded = true; -} diff --git a/lib/symfony/class-loader/Tests/Fixtures/fallback/Namespaced2/FooBar.php b/lib/symfony/class-loader/Tests/Fixtures/fallback/Namespaced2/FooBar.php deleted file mode 100644 index 1036d4359..000000000 --- a/lib/symfony/class-loader/Tests/Fixtures/fallback/Namespaced2/FooBar.php +++ /dev/null @@ -1,8 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\ClassLoader\Tests; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\ClassLoader\Psr4ClassLoader; - -/** - * @group legacy - */ -class Psr4ClassLoaderTest extends TestCase -{ - /** - * @param string $className - * @dataProvider getLoadClassTests - */ - public function testLoadClass($className) - { - $loader = new Psr4ClassLoader(); - $loader->addPrefix( - 'Acme\\DemoLib', - __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR.'psr-4' - ); - $loader->loadClass($className); - $this->assertTrue(class_exists($className), sprintf('loadClass() should load %s', $className)); - } - - /** - * @return array - */ - public function getLoadClassTests() - { - return [ - ['Acme\\DemoLib\\Foo'], - ['Acme\\DemoLib\\Class_With_Underscores'], - ['Acme\\DemoLib\\Lets\\Go\\Deeper\\Foo'], - ['Acme\\DemoLib\\Lets\\Go\\Deeper\\Class_With_Underscores'], - ]; - } - - /** - * @param string $className - * @dataProvider getLoadNonexistentClassTests - */ - public function testLoadNonexistentClass($className) - { - $loader = new Psr4ClassLoader(); - $loader->addPrefix( - 'Acme\\DemoLib', - __DIR__.\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR.'psr-4' - ); - $loader->loadClass($className); - $this->assertFalse(class_exists($className), sprintf('loadClass() should not load %s', $className)); - } - - /** - * @return array - */ - public function getLoadNonexistentClassTests() - { - return [ - ['Acme\\DemoLib\\I_Do_Not_Exist'], - ['UnknownVendor\\SomeLib\\I_Do_Not_Exist'], - ]; - } -} diff --git a/lib/symfony/config/Tests/ConfigCacheFactoryTest.php b/lib/symfony/config/Tests/ConfigCacheFactoryTest.php deleted file mode 100644 index 6190b9b45..000000000 --- a/lib/symfony/config/Tests/ConfigCacheFactoryTest.php +++ /dev/null @@ -1,27 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\ConfigCacheFactory; - -class ConfigCacheFactoryTest extends TestCase -{ - public function testCacheWithInvalidCallback() - { - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessage('Invalid type for callback argument. Expected callable, but got "object".'); - $cacheFactory = new ConfigCacheFactory(true); - - $cacheFactory->cache('file', new \stdClass()); - } -} diff --git a/lib/symfony/config/Tests/ConfigCacheTest.php b/lib/symfony/config/Tests/ConfigCacheTest.php deleted file mode 100644 index d0b70899b..000000000 --- a/lib/symfony/config/Tests/ConfigCacheTest.php +++ /dev/null @@ -1,99 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\ConfigCache; -use Symfony\Component\Config\Tests\Resource\ResourceStub; - -class ConfigCacheTest extends TestCase -{ - private $cacheFile = null; - - protected function setUp() - { - $this->cacheFile = tempnam(sys_get_temp_dir(), 'config_'); - } - - protected function tearDown() - { - $files = [$this->cacheFile, $this->cacheFile.'.meta']; - - foreach ($files as $file) { - if (file_exists($file)) { - unlink($file); - } - } - } - - /** - * @dataProvider debugModes - */ - public function testCacheIsNotValidIfNothingHasBeenCached($debug) - { - unlink($this->cacheFile); // remove tempnam() side effect - $cache = new ConfigCache($this->cacheFile, $debug); - - $this->assertFalse($cache->isFresh()); - } - - public function testIsAlwaysFreshInProduction() - { - $staleResource = new ResourceStub(); - $staleResource->setFresh(false); - - $cache = new ConfigCache($this->cacheFile, false); - $cache->write('', [$staleResource]); - - $this->assertTrue($cache->isFresh()); - } - - /** - * @dataProvider debugModes - */ - public function testIsFreshWhenNoResourceProvided($debug) - { - $cache = new ConfigCache($this->cacheFile, $debug); - $cache->write('', []); - $this->assertTrue($cache->isFresh()); - } - - public function testFreshResourceInDebug() - { - $freshResource = new ResourceStub(); - $freshResource->setFresh(true); - - $cache = new ConfigCache($this->cacheFile, true); - $cache->write('', [$freshResource]); - - $this->assertTrue($cache->isFresh()); - } - - public function testStaleResourceInDebug() - { - $staleResource = new ResourceStub(); - $staleResource->setFresh(false); - - $cache = new ConfigCache($this->cacheFile, true); - $cache->write('', [$staleResource]); - - $this->assertFalse($cache->isFresh()); - } - - public function debugModes() - { - return [ - [true], - [false], - ]; - } -} diff --git a/lib/symfony/config/Tests/Definition/ArrayNodeTest.php b/lib/symfony/config/Tests/Definition/ArrayNodeTest.php deleted file mode 100644 index 25c2cfc69..000000000 --- a/lib/symfony/config/Tests/Definition/ArrayNodeTest.php +++ /dev/null @@ -1,237 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Definition; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Definition\ArrayNode; -use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; -use Symfony\Component\Config\Definition\ScalarNode; - -class ArrayNodeTest extends TestCase -{ - public function testNormalizeThrowsExceptionWhenFalseIsNotAllowed() - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); - $node = new ArrayNode('root'); - $node->normalize(false); - } - - public function testExceptionThrownOnUnrecognizedChild() - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); - $this->expectExceptionMessage('Unrecognized option "foo" under "root"'); - $node = new ArrayNode('root'); - $node->normalize(['foo' => 'bar']); - } - - public function ignoreAndRemoveMatrixProvider() - { - $unrecognizedOptionException = new InvalidConfigurationException('Unrecognized option "foo" under "root"'); - - return [ - [true, true, [], 'no exception is thrown for an unrecognized child if the ignoreExtraKeys option is set to true'], - [true, false, ['foo' => 'bar'], 'extra keys are not removed when ignoreExtraKeys second option is set to false'], - [false, true, $unrecognizedOptionException], - [false, false, $unrecognizedOptionException], - ]; - } - - /** - * @dataProvider ignoreAndRemoveMatrixProvider - */ - public function testIgnoreAndRemoveBehaviors($ignore, $remove, $expected, $message = '') - { - if ($expected instanceof \Exception) { - $this->expectException(\get_class($expected)); - $this->expectExceptionMessage($expected->getMessage()); - } - $node = new ArrayNode('root'); - $node->setIgnoreExtraKeys($ignore, $remove); - $result = $node->normalize(['foo' => 'bar']); - $this->assertSame($expected, $result, $message); - } - - /** - * @dataProvider getPreNormalizationTests - */ - public function testPreNormalize($denormalized, $normalized) - { - $node = new ArrayNode('foo'); - - $r = new \ReflectionMethod($node, 'preNormalize'); - $r->setAccessible(true); - - $this->assertSame($normalized, $r->invoke($node, $denormalized)); - } - - public function getPreNormalizationTests() - { - return [ - [ - ['foo-bar' => 'foo'], - ['foo_bar' => 'foo'], - ], - [ - ['foo-bar_moo' => 'foo'], - ['foo-bar_moo' => 'foo'], - ], - [ - ['anything-with-dash-and-no-underscore' => 'first', 'no_dash' => 'second'], - ['anything_with_dash_and_no_underscore' => 'first', 'no_dash' => 'second'], - ], - [ - ['foo-bar' => null, 'foo_bar' => 'foo'], - ['foo-bar' => null, 'foo_bar' => 'foo'], - ], - ]; - } - - /** - * @dataProvider getZeroNamedNodeExamplesData - */ - public function testNodeNameCanBeZero($denormalized, $normalized) - { - $zeroNode = new ArrayNode(0); - $zeroNode->addChild(new ScalarNode('name')); - $fiveNode = new ArrayNode(5); - $fiveNode->addChild(new ScalarNode(0)); - $fiveNode->addChild(new ScalarNode('new_key')); - $rootNode = new ArrayNode('root'); - $rootNode->addChild($zeroNode); - $rootNode->addChild($fiveNode); - $rootNode->addChild(new ScalarNode('string_key')); - $r = new \ReflectionMethod($rootNode, 'normalizeValue'); - $r->setAccessible(true); - - $this->assertSame($normalized, $r->invoke($rootNode, $denormalized)); - } - - public function getZeroNamedNodeExamplesData() - { - return [ - [ - [ - 0 => [ - 'name' => 'something', - ], - 5 => [ - 0 => 'this won\'t work too', - 'new_key' => 'some other value', - ], - 'string_key' => 'just value', - ], - [ - 0 => [ - 'name' => 'something', - ], - 5 => [ - 0 => 'this won\'t work too', - 'new_key' => 'some other value', - ], - 'string_key' => 'just value', - ], - ], - ]; - } - - /** - * @dataProvider getPreNormalizedNormalizedOrderedData - */ - public function testChildrenOrderIsMaintainedOnNormalizeValue($prenormalized, $normalized) - { - $scalar1 = new ScalarNode('1'); - $scalar2 = new ScalarNode('2'); - $scalar3 = new ScalarNode('3'); - $node = new ArrayNode('foo'); - $node->addChild($scalar1); - $node->addChild($scalar3); - $node->addChild($scalar2); - - $r = new \ReflectionMethod($node, 'normalizeValue'); - $r->setAccessible(true); - - $this->assertSame($normalized, $r->invoke($node, $prenormalized)); - } - - public function getPreNormalizedNormalizedOrderedData() - { - return [ - [ - ['2' => 'two', '1' => 'one', '3' => 'three'], - ['2' => 'two', '1' => 'one', '3' => 'three'], - ], - ]; - } - - public function testAddChildEmptyName() - { - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessage('Child nodes must be named.'); - $node = new ArrayNode('root'); - - $childNode = new ArrayNode(''); - $node->addChild($childNode); - } - - public function testAddChildNameAlreadyExists() - { - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessage('A child node named "foo" already exists.'); - $node = new ArrayNode('root'); - - $childNode = new ArrayNode('foo'); - $node->addChild($childNode); - - $childNodeWithSameName = new ArrayNode('foo'); - $node->addChild($childNodeWithSameName); - } - - public function testGetDefaultValueWithoutDefaultValue() - { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage('The node at path "foo" has no default value.'); - $node = new ArrayNode('foo'); - $node->getDefaultValue(); - } - - public function testSetDeprecated() - { - $childNode = new ArrayNode('foo'); - $childNode->setDeprecated('"%node%" is deprecated'); - - $this->assertTrue($childNode->isDeprecated()); - $this->assertSame('"foo" is deprecated', $childNode->getDeprecationMessage($childNode->getName(), $childNode->getPath())); - - $node = new ArrayNode('root'); - $node->addChild($childNode); - - $deprecationTriggered = false; - $deprecationHandler = function ($level, $message, $file, $line) use (&$prevErrorHandler, &$deprecationTriggered) { - if (E_USER_DEPRECATED === $level) { - return $deprecationTriggered = true; - } - - return $prevErrorHandler ? $prevErrorHandler($level, $message, $file, $line) : false; - }; - - $prevErrorHandler = set_error_handler($deprecationHandler); - $node->finalize([]); - restore_error_handler(); - - $this->assertFalse($deprecationTriggered, '->finalize() should not trigger if the deprecated node is not set'); - - $prevErrorHandler = set_error_handler($deprecationHandler); - $node->finalize(['foo' => []]); - restore_error_handler(); - $this->assertTrue($deprecationTriggered, '->finalize() should trigger if the deprecated node is set'); - } -} diff --git a/lib/symfony/config/Tests/Definition/BooleanNodeTest.php b/lib/symfony/config/Tests/Definition/BooleanNodeTest.php deleted file mode 100644 index 8552eeba3..000000000 --- a/lib/symfony/config/Tests/Definition/BooleanNodeTest.php +++ /dev/null @@ -1,74 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Definition; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Definition\BooleanNode; - -class BooleanNodeTest extends TestCase -{ - /** - * @dataProvider getValidValues - */ - public function testNormalize($value) - { - $node = new BooleanNode('test'); - $this->assertSame($value, $node->normalize($value)); - } - - /** - * @dataProvider getValidValues - * - * @param bool $value - */ - public function testValidNonEmptyValues($value) - { - $node = new BooleanNode('test'); - $node->setAllowEmptyValue(false); - - $this->assertSame($value, $node->finalize($value)); - } - - public function getValidValues() - { - return [ - [false], - [true], - ]; - } - - /** - * @dataProvider getInvalidValues - */ - public function testNormalizeThrowsExceptionOnInvalidValues($value) - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); - $node = new BooleanNode('test'); - $node->normalize($value); - } - - public function getInvalidValues() - { - return [ - [null], - [''], - ['foo'], - [0], - [1], - [0.0], - [0.1], - [[]], - [['foo' => 'bar']], - [new \stdClass()], - ]; - } -} diff --git a/lib/symfony/config/Tests/Definition/Builder/ArrayNodeDefinitionTest.php b/lib/symfony/config/Tests/Definition/Builder/ArrayNodeDefinitionTest.php deleted file mode 100644 index 1123b4159..000000000 --- a/lib/symfony/config/Tests/Definition/Builder/ArrayNodeDefinitionTest.php +++ /dev/null @@ -1,362 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Definition\Builder; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; -use Symfony\Component\Config\Definition\Builder\ScalarNodeDefinition; -use Symfony\Component\Config\Definition\Exception\InvalidDefinitionException; -use Symfony\Component\Config\Definition\Processor; - -class ArrayNodeDefinitionTest extends TestCase -{ - public function testAppendingSomeNode() - { - $parent = new ArrayNodeDefinition('root'); - $child = new ScalarNodeDefinition('child'); - - $parent - ->children() - ->scalarNode('foo')->end() - ->scalarNode('bar')->end() - ->end() - ->append($child); - - $this->assertCount(3, $this->getField($parent, 'children')); - $this->assertContains($child, $this->getField($parent, 'children')); - } - - /** - * @dataProvider providePrototypeNodeSpecificCalls - */ - public function testPrototypeNodeSpecificOption($method, $args) - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidDefinitionException'); - $node = new ArrayNodeDefinition('root'); - - \call_user_func_array([$node, $method], $args); - - $node->getNode(); - } - - public function providePrototypeNodeSpecificCalls() - { - return [ - ['defaultValue', [[]]], - ['addDefaultChildrenIfNoneSet', []], - ['requiresAtLeastOneElement', []], - ['useAttributeAsKey', ['foo']], - ]; - } - - public function testConcreteNodeSpecificOption() - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidDefinitionException'); - $node = new ArrayNodeDefinition('root'); - $node - ->addDefaultsIfNotSet() - ->prototype('array') - ; - $node->getNode(); - } - - public function testPrototypeNodesCantHaveADefaultValueWhenUsingDefaultChildren() - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidDefinitionException'); - $node = new ArrayNodeDefinition('root'); - $node - ->defaultValue([]) - ->addDefaultChildrenIfNoneSet('foo') - ->prototype('array') - ; - $node->getNode(); - } - - public function testPrototypedArrayNodeDefaultWhenUsingDefaultChildren() - { - $node = new ArrayNodeDefinition('root'); - $node - ->addDefaultChildrenIfNoneSet() - ->prototype('array') - ; - $tree = $node->getNode(); - $this->assertEquals([[]], $tree->getDefaultValue()); - } - - /** - * @dataProvider providePrototypedArrayNodeDefaults - */ - public function testPrototypedArrayNodeDefault($args, $shouldThrowWhenUsingAttrAsKey, $shouldThrowWhenNotUsingAttrAsKey, $defaults) - { - $node = new ArrayNodeDefinition('root'); - $node - ->addDefaultChildrenIfNoneSet($args) - ->prototype('array') - ; - - try { - $tree = $node->getNode(); - $this->assertFalse($shouldThrowWhenNotUsingAttrAsKey); - $this->assertEquals($defaults, $tree->getDefaultValue()); - } catch (InvalidDefinitionException $e) { - $this->assertTrue($shouldThrowWhenNotUsingAttrAsKey); - } - - $node = new ArrayNodeDefinition('root'); - $node - ->useAttributeAsKey('attr') - ->addDefaultChildrenIfNoneSet($args) - ->prototype('array') - ; - - try { - $tree = $node->getNode(); - $this->assertFalse($shouldThrowWhenUsingAttrAsKey); - $this->assertEquals($defaults, $tree->getDefaultValue()); - } catch (InvalidDefinitionException $e) { - $this->assertTrue($shouldThrowWhenUsingAttrAsKey); - } - } - - public function providePrototypedArrayNodeDefaults() - { - return [ - [null, true, false, [[]]], - [2, true, false, [[], []]], - ['2', false, true, ['2' => []]], - ['foo', false, true, ['foo' => []]], - [['foo'], false, true, ['foo' => []]], - [['foo', 'bar'], false, true, ['foo' => [], 'bar' => []]], - ]; - } - - public function testNestedPrototypedArrayNodes() - { - $nodeDefinition = new ArrayNodeDefinition('root'); - $nodeDefinition - ->addDefaultChildrenIfNoneSet() - ->prototype('array') - ->prototype('array') - ; - $node = $nodeDefinition->getNode(); - - $this->assertInstanceOf('Symfony\Component\Config\Definition\PrototypedArrayNode', $node); - $this->assertInstanceOf('Symfony\Component\Config\Definition\PrototypedArrayNode', $node->getPrototype()); - } - - public function testEnabledNodeDefaults() - { - $node = new ArrayNodeDefinition('root'); - $node - ->canBeEnabled() - ->children() - ->scalarNode('foo')->defaultValue('bar')->end() - ; - - $this->assertEquals(['enabled' => false, 'foo' => 'bar'], $node->getNode()->getDefaultValue()); - } - - /** - * @dataProvider getEnableableNodeFixtures - */ - public function testTrueEnableEnabledNode($expected, $config, $message) - { - $processor = new Processor(); - $node = new ArrayNodeDefinition('root'); - $node - ->canBeEnabled() - ->children() - ->scalarNode('foo')->defaultValue('bar')->end() - ; - - $this->assertEquals( - $expected, - $processor->process($node->getNode(), $config), - $message - ); - } - - public function testCanBeDisabled() - { - $node = new ArrayNodeDefinition('root'); - $node->canBeDisabled(); - - $this->assertTrue($this->getField($node, 'addDefaults')); - $this->assertEquals(['enabled' => false], $this->getField($node, 'falseEquivalent')); - $this->assertEquals(['enabled' => true], $this->getField($node, 'trueEquivalent')); - $this->assertEquals(['enabled' => true], $this->getField($node, 'nullEquivalent')); - - $nodeChildren = $this->getField($node, 'children'); - $this->assertArrayHasKey('enabled', $nodeChildren); - - $enabledNode = $nodeChildren['enabled']; - $this->assertTrue($this->getField($enabledNode, 'default')); - $this->assertTrue($this->getField($enabledNode, 'defaultValue')); - } - - public function testIgnoreExtraKeys() - { - $node = new ArrayNodeDefinition('root'); - - $this->assertFalse($this->getField($node, 'ignoreExtraKeys')); - - $result = $node->ignoreExtraKeys(); - - $this->assertEquals($node, $result); - $this->assertTrue($this->getField($node, 'ignoreExtraKeys')); - } - - public function testNormalizeKeys() - { - $node = new ArrayNodeDefinition('root'); - - $this->assertTrue($this->getField($node, 'normalizeKeys')); - - $result = $node->normalizeKeys(false); - - $this->assertEquals($node, $result); - $this->assertFalse($this->getField($node, 'normalizeKeys')); - } - - public function testUnsetChild() - { - $node = new ArrayNodeDefinition('root'); - $node - ->children() - ->scalarNode('value') - ->beforeNormalization() - ->ifTrue(function ($value) { - return empty($value); - }) - ->thenUnset() - ->end() - ->end() - ->end() - ; - - $this->assertSame([], $node->getNode()->normalize(['value' => null])); - } - - public function testPrototypeVariable() - { - $node = new ArrayNodeDefinition('root'); - $this->assertEquals($node->prototype('variable'), $node->variablePrototype()); - } - - public function testPrototypeScalar() - { - $node = new ArrayNodeDefinition('root'); - $this->assertEquals($node->prototype('scalar'), $node->scalarPrototype()); - } - - public function testPrototypeBoolean() - { - $node = new ArrayNodeDefinition('root'); - $this->assertEquals($node->prototype('boolean'), $node->booleanPrototype()); - } - - public function testPrototypeInteger() - { - $node = new ArrayNodeDefinition('root'); - $this->assertEquals($node->prototype('integer'), $node->integerPrototype()); - } - - public function testPrototypeFloat() - { - $node = new ArrayNodeDefinition('root'); - $this->assertEquals($node->prototype('float'), $node->floatPrototype()); - } - - public function testPrototypeArray() - { - $node = new ArrayNodeDefinition('root'); - $this->assertEquals($node->prototype('array'), $node->arrayPrototype()); - } - - public function testPrototypeEnum() - { - $node = new ArrayNodeDefinition('root'); - $this->assertEquals($node->prototype('enum'), $node->enumPrototype()); - } - - public function getEnableableNodeFixtures() - { - return [ - [['enabled' => true, 'foo' => 'bar'], [true], 'true enables an enableable node'], - [['enabled' => true, 'foo' => 'bar'], [null], 'null enables an enableable node'], - [['enabled' => true, 'foo' => 'bar'], [['enabled' => true]], 'An enableable node can be enabled'], - [['enabled' => true, 'foo' => 'baz'], [['foo' => 'baz']], 'any configuration enables an enableable node'], - [['enabled' => false, 'foo' => 'baz'], [['foo' => 'baz', 'enabled' => false]], 'An enableable node can be disabled'], - [['enabled' => false, 'foo' => 'bar'], [false], 'false disables an enableable node'], - ]; - } - - public function testRequiresAtLeastOneElement() - { - $node = new ArrayNodeDefinition('root'); - $node - ->requiresAtLeastOneElement() - ->integerPrototype(); - - $node->getNode()->finalize([1]); - - $this->addToAssertionCount(1); - } - - /** - * @group legacy - * @expectedDeprecation Using Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition::cannotBeEmpty() at path "root" has no effect, consider requiresAtLeastOneElement() instead. In 4.0 both methods will behave the same. - */ - public function testCannotBeEmpty() - { - $node = new ArrayNodeDefinition('root'); - $node - ->cannotBeEmpty() - ->integerPrototype(); - - $node->getNode()->finalize([]); - } - - public function testSetDeprecated() - { - $node = new ArrayNodeDefinition('root'); - $node - ->children() - ->arrayNode('foo')->setDeprecated('The "%path%" node is deprecated.')->end() - ->end() - ; - $deprecatedNode = $node->getNode()->getChildren()['foo']; - - $this->assertTrue($deprecatedNode->isDeprecated()); - $this->assertSame('The "root.foo" node is deprecated.', $deprecatedNode->getDeprecationMessage($deprecatedNode->getName(), $deprecatedNode->getPath())); - } - - /** - * @group legacy - * @expectedDeprecation ->cannotBeEmpty() is not applicable to concrete nodes at path "root". In 4.0 it will throw an exception. - */ - public function testCannotBeEmptyOnConcreteNode() - { - $node = new ArrayNodeDefinition('root'); - $node->cannotBeEmpty(); - - $node->getNode()->finalize([]); - } - - protected function getField($object, $field) - { - $reflection = new \ReflectionProperty($object, $field); - $reflection->setAccessible(true); - - return $reflection->getValue($object); - } -} diff --git a/lib/symfony/config/Tests/Definition/Builder/BooleanNodeDefinitionTest.php b/lib/symfony/config/Tests/Definition/Builder/BooleanNodeDefinitionTest.php deleted file mode 100644 index 6f568a2df..000000000 --- a/lib/symfony/config/Tests/Definition/Builder/BooleanNodeDefinitionTest.php +++ /dev/null @@ -1,37 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Definition\Builder; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Definition\Builder\BooleanNodeDefinition; - -class BooleanNodeDefinitionTest extends TestCase -{ - public function testCannotBeEmptyThrowsAnException() - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidDefinitionException'); - $this->expectExceptionMessage('->cannotBeEmpty() is not applicable to BooleanNodeDefinition.'); - $def = new BooleanNodeDefinition('foo'); - $def->cannotBeEmpty(); - } - - public function testSetDeprecated() - { - $def = new BooleanNodeDefinition('foo'); - $def->setDeprecated('The "%path%" node is deprecated.'); - - $node = $def->getNode(); - - $this->assertTrue($node->isDeprecated()); - $this->assertSame('The "foo" node is deprecated.', $node->getDeprecationMessage($node->getName(), $node->getPath())); - } -} diff --git a/lib/symfony/config/Tests/Definition/Builder/EnumNodeDefinitionTest.php b/lib/symfony/config/Tests/Definition/Builder/EnumNodeDefinitionTest.php deleted file mode 100644 index 2e43a1354..000000000 --- a/lib/symfony/config/Tests/Definition/Builder/EnumNodeDefinitionTest.php +++ /dev/null @@ -1,73 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Definition\Builder; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Definition\Builder\EnumNodeDefinition; - -class EnumNodeDefinitionTest extends TestCase -{ - public function testWithOneValue() - { - $def = new EnumNodeDefinition('foo'); - $def->values(['foo']); - - $node = $def->getNode(); - $this->assertEquals(['foo'], $node->getValues()); - } - - public function testWithOneDistinctValue() - { - $def = new EnumNodeDefinition('foo'); - $def->values(['foo', 'foo']); - - $node = $def->getNode(); - $this->assertEquals(['foo'], $node->getValues()); - } - - public function testNoValuesPassed() - { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage('You must call ->values() on enum nodes.'); - $def = new EnumNodeDefinition('foo'); - $def->getNode(); - } - - public function testWithNoValues() - { - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessage('->values() must be called with at least one value.'); - $def = new EnumNodeDefinition('foo'); - $def->values([]); - } - - public function testGetNode() - { - $def = new EnumNodeDefinition('foo'); - $def->values(['foo', 'bar']); - - $node = $def->getNode(); - $this->assertEquals(['foo', 'bar'], $node->getValues()); - } - - public function testSetDeprecated() - { - $def = new EnumNodeDefinition('foo'); - $def->values(['foo', 'bar']); - $def->setDeprecated('The "%path%" node is deprecated.'); - - $node = $def->getNode(); - - $this->assertTrue($node->isDeprecated()); - $this->assertSame('The "foo" node is deprecated.', $def->getNode()->getDeprecationMessage($node->getName(), $node->getPath())); - } -} diff --git a/lib/symfony/config/Tests/Definition/Builder/ExprBuilderTest.php b/lib/symfony/config/Tests/Definition/Builder/ExprBuilderTest.php deleted file mode 100644 index 85d0d3631..000000000 --- a/lib/symfony/config/Tests/Definition/Builder/ExprBuilderTest.php +++ /dev/null @@ -1,264 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Definition\Builder; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Definition\Builder\TreeBuilder; - -class ExprBuilderTest extends TestCase -{ - public function testAlwaysExpression() - { - $test = $this->getTestBuilder() - ->always($this->returnClosure('new_value')) - ->end(); - - $this->assertFinalizedValueIs('new_value', $test); - } - - public function testIfTrueExpression() - { - $test = $this->getTestBuilder() - ->ifTrue() - ->then($this->returnClosure('new_value')) - ->end(); - $this->assertFinalizedValueIs('new_value', $test, ['key' => true]); - - $test = $this->getTestBuilder() - ->ifTrue(function ($v) { return true; }) - ->then($this->returnClosure('new_value')) - ->end(); - $this->assertFinalizedValueIs('new_value', $test); - - $test = $this->getTestBuilder() - ->ifTrue(function ($v) { return false; }) - ->then($this->returnClosure('new_value')) - ->end(); - $this->assertFinalizedValueIs('value', $test); - } - - public function testIfStringExpression() - { - $test = $this->getTestBuilder() - ->ifString() - ->then($this->returnClosure('new_value')) - ->end(); - $this->assertFinalizedValueIs('new_value', $test); - - $test = $this->getTestBuilder() - ->ifString() - ->then($this->returnClosure('new_value')) - ->end(); - $this->assertFinalizedValueIs(45, $test, ['key' => 45]); - } - - public function testIfNullExpression() - { - $test = $this->getTestBuilder() - ->ifNull() - ->then($this->returnClosure('new_value')) - ->end(); - $this->assertFinalizedValueIs('new_value', $test, ['key' => null]); - - $test = $this->getTestBuilder() - ->ifNull() - ->then($this->returnClosure('new_value')) - ->end(); - $this->assertFinalizedValueIs('value', $test); - } - - public function testIfEmptyExpression() - { - $test = $this->getTestBuilder() - ->ifEmpty() - ->then($this->returnClosure('new_value')) - ->end(); - $this->assertFinalizedValueIs('new_value', $test, ['key' => []]); - - $test = $this->getTestBuilder() - ->ifEmpty() - ->then($this->returnClosure('new_value')) - ->end(); - $this->assertFinalizedValueIs('value', $test); - } - - public function testIfArrayExpression() - { - $test = $this->getTestBuilder() - ->ifArray() - ->then($this->returnClosure('new_value')) - ->end(); - $this->assertFinalizedValueIs('new_value', $test, ['key' => []]); - - $test = $this->getTestBuilder() - ->ifArray() - ->then($this->returnClosure('new_value')) - ->end(); - $this->assertFinalizedValueIs('value', $test); - } - - public function testIfInArrayExpression() - { - $test = $this->getTestBuilder() - ->ifInArray(['foo', 'bar', 'value']) - ->then($this->returnClosure('new_value')) - ->end(); - $this->assertFinalizedValueIs('new_value', $test); - - $test = $this->getTestBuilder() - ->ifInArray(['foo', 'bar']) - ->then($this->returnClosure('new_value')) - ->end(); - $this->assertFinalizedValueIs('value', $test); - } - - public function testIfNotInArrayExpression() - { - $test = $this->getTestBuilder() - ->ifNotInArray(['foo', 'bar']) - ->then($this->returnClosure('new_value')) - ->end(); - $this->assertFinalizedValueIs('new_value', $test); - - $test = $this->getTestBuilder() - ->ifNotInArray(['foo', 'bar', 'value_from_config']) - ->then($this->returnClosure('new_value')) - ->end(); - $this->assertFinalizedValueIs('new_value', $test); - } - - public function testThenEmptyArrayExpression() - { - $test = $this->getTestBuilder() - ->ifString() - ->thenEmptyArray() - ->end(); - $this->assertFinalizedValueIs([], $test); - } - - /** - * @dataProvider castToArrayValues - */ - public function testcastToArrayExpression($configValue, $expectedValue) - { - $test = $this->getTestBuilder() - ->castToArray() - ->end(); - $this->assertFinalizedValueIs($expectedValue, $test, ['key' => $configValue]); - } - - public function castToArrayValues() - { - yield ['value', ['value']]; - yield [-3.14, [-3.14]]; - yield [null, [null]]; - yield [['value'], ['value']]; - } - - public function testThenInvalid() - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); - $test = $this->getTestBuilder() - ->ifString() - ->thenInvalid('Invalid value') - ->end(); - $this->finalizeTestBuilder($test); - } - - public function testThenUnsetExpression() - { - $test = $this->getTestBuilder() - ->ifString() - ->thenUnset() - ->end(); - $this->assertEquals([], $this->finalizeTestBuilder($test)); - } - - public function testEndIfPartNotSpecified() - { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage('You must specify an if part.'); - $this->getTestBuilder()->end(); - } - - public function testEndThenPartNotSpecified() - { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage('You must specify a then part.'); - $builder = $this->getTestBuilder(); - $builder->ifPart = 'test'; - $builder->end(); - } - - /** - * Create a test treebuilder with a variable node, and init the validation. - * - * @return TreeBuilder - */ - protected function getTestBuilder() - { - $builder = new TreeBuilder(); - - return $builder - ->root('test') - ->children() - ->variableNode('key') - ->validate() - ; - } - - /** - * Close the validation process and finalize with the given config. - * - * @param TreeBuilder $testBuilder The tree builder to finalize - * @param array $config The config you want to use for the finalization, if nothing provided - * a simple ['key'=>'value'] will be used - * - * @return array The finalized config values - */ - protected function finalizeTestBuilder($testBuilder, $config = null) - { - return $testBuilder - ->end() - ->end() - ->end() - ->buildTree() - ->finalize(null === $config ? ['key' => 'value'] : $config) - ; - } - - /** - * Return a closure that will return the given value. - * - * @param mixed $val The value that the closure must return - * - * @return \Closure - */ - protected function returnClosure($val) - { - return function ($v) use ($val) { - return $val; - }; - } - - /** - * Assert that the given test builder, will return the given value. - * - * @param mixed $value The value to test - * @param TreeBuilder $treeBuilder The tree builder to finalize - * @param mixed $config The config values that new to be finalized - */ - protected function assertFinalizedValueIs($value, $treeBuilder, $config = null) - { - $this->assertEquals(['key' => $value], $this->finalizeTestBuilder($treeBuilder, $config)); - } -} diff --git a/lib/symfony/config/Tests/Definition/Builder/NodeBuilderTest.php b/lib/symfony/config/Tests/Definition/Builder/NodeBuilderTest.php deleted file mode 100644 index 5cc7cfea4..000000000 --- a/lib/symfony/config/Tests/Definition/Builder/NodeBuilderTest.php +++ /dev/null @@ -1,91 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Definition\Builder; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Definition\Builder\NodeBuilder as BaseNodeBuilder; -use Symfony\Component\Config\Definition\Builder\VariableNodeDefinition as BaseVariableNodeDefinition; - -class NodeBuilderTest extends TestCase -{ - public function testThrowsAnExceptionWhenTryingToCreateANonRegisteredNodeType() - { - $this->expectException('RuntimeException'); - $builder = new BaseNodeBuilder(); - $builder->node('', 'foobar'); - } - - public function testThrowsAnExceptionWhenTheNodeClassIsNotFound() - { - $this->expectException('RuntimeException'); - $builder = new BaseNodeBuilder(); - $builder - ->setNodeClass('noclasstype', '\\foo\\bar\\noclass') - ->node('', 'noclasstype'); - } - - public function testAddingANewNodeType() - { - $class = __NAMESPACE__.'\\SomeNodeDefinition'; - - $builder = new BaseNodeBuilder(); - $node = $builder - ->setNodeClass('newtype', $class) - ->node('', 'newtype'); - - $this->assertInstanceOf($class, $node); - } - - public function testOverridingAnExistingNodeType() - { - $class = __NAMESPACE__.'\\SomeNodeDefinition'; - - $builder = new BaseNodeBuilder(); - $node = $builder - ->setNodeClass('variable', $class) - ->node('', 'variable'); - - $this->assertInstanceOf($class, $node); - } - - public function testNodeTypesAreNotCaseSensitive() - { - $builder = new BaseNodeBuilder(); - - $node1 = $builder->node('', 'VaRiAbLe'); - $node2 = $builder->node('', 'variable'); - - $this->assertInstanceOf(\get_class($node1), $node2); - - $builder->setNodeClass('CuStOm', __NAMESPACE__.'\\SomeNodeDefinition'); - - $node1 = $builder->node('', 'CUSTOM'); - $node2 = $builder->node('', 'custom'); - - $this->assertInstanceOf(\get_class($node1), $node2); - } - - public function testNumericNodeCreation() - { - $builder = new BaseNodeBuilder(); - - $node = $builder->integerNode('foo')->min(3)->max(5); - $this->assertInstanceOf('Symfony\Component\Config\Definition\Builder\IntegerNodeDefinition', $node); - - $node = $builder->floatNode('bar')->min(3.0)->max(5.0); - $this->assertInstanceOf('Symfony\Component\Config\Definition\Builder\FloatNodeDefinition', $node); - } -} - -class SomeNodeDefinition extends BaseVariableNodeDefinition -{ -} diff --git a/lib/symfony/config/Tests/Definition/Builder/NumericNodeDefinitionTest.php b/lib/symfony/config/Tests/Definition/Builder/NumericNodeDefinitionTest.php deleted file mode 100644 index aa938bbaa..000000000 --- a/lib/symfony/config/Tests/Definition/Builder/NumericNodeDefinitionTest.php +++ /dev/null @@ -1,89 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Definition\Builder; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Definition\Builder\FloatNodeDefinition; -use Symfony\Component\Config\Definition\Builder\IntegerNodeDefinition; - -class NumericNodeDefinitionTest extends TestCase -{ - public function testIncoherentMinAssertion() - { - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessage('You cannot define a min(4) as you already have a max(3)'); - $def = new IntegerNodeDefinition('foo'); - $def->max(3)->min(4); - } - - public function testIncoherentMaxAssertion() - { - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessage('You cannot define a max(2) as you already have a min(3)'); - $node = new IntegerNodeDefinition('foo'); - $node->min(3)->max(2); - } - - public function testIntegerMinAssertion() - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); - $this->expectExceptionMessage('The value 4 is too small for path "foo". Should be greater than or equal to 5'); - $def = new IntegerNodeDefinition('foo'); - $def->min(5)->getNode()->finalize(4); - } - - public function testIntegerMaxAssertion() - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); - $this->expectExceptionMessage('The value 4 is too big for path "foo". Should be less than or equal to 3'); - $def = new IntegerNodeDefinition('foo'); - $def->max(3)->getNode()->finalize(4); - } - - public function testIntegerValidMinMaxAssertion() - { - $def = new IntegerNodeDefinition('foo'); - $node = $def->min(3)->max(7)->getNode(); - $this->assertEquals(4, $node->finalize(4)); - } - - public function testFloatMinAssertion() - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); - $this->expectExceptionMessage('The value 400 is too small for path "foo". Should be greater than or equal to 500'); - $def = new FloatNodeDefinition('foo'); - $def->min(5E2)->getNode()->finalize(4e2); - } - - public function testFloatMaxAssertion() - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); - $this->expectExceptionMessage('The value 4.3 is too big for path "foo". Should be less than or equal to 0.3'); - $def = new FloatNodeDefinition('foo'); - $def->max(0.3)->getNode()->finalize(4.3); - } - - public function testFloatValidMinMaxAssertion() - { - $def = new FloatNodeDefinition('foo'); - $node = $def->min(3.0)->max(7e2)->getNode(); - $this->assertEquals(4.5, $node->finalize(4.5)); - } - - public function testCannotBeEmptyThrowsAnException() - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidDefinitionException'); - $this->expectExceptionMessage('->cannotBeEmpty() is not applicable to NumericNodeDefinition.'); - $def = new IntegerNodeDefinition('foo'); - $def->cannotBeEmpty(); - } -} diff --git a/lib/symfony/config/Tests/Definition/Builder/TreeBuilderTest.php b/lib/symfony/config/Tests/Definition/Builder/TreeBuilderTest.php deleted file mode 100644 index 53c9c256b..000000000 --- a/lib/symfony/config/Tests/Definition/Builder/TreeBuilderTest.php +++ /dev/null @@ -1,134 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Definition\Builder; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Definition\Builder\TreeBuilder; -use Symfony\Component\Config\Tests\Fixtures\Builder\NodeBuilder as CustomNodeBuilder; - -class TreeBuilderTest extends TestCase -{ - public function testUsingACustomNodeBuilder() - { - $builder = new TreeBuilder(); - $root = $builder->root('custom', 'array', new CustomNodeBuilder()); - - $nodeBuilder = $root->children(); - - $this->assertInstanceOf('Symfony\Component\Config\Tests\Fixtures\Builder\NodeBuilder', $nodeBuilder); - - $nodeBuilder = $nodeBuilder->arrayNode('deeper')->children(); - - $this->assertInstanceOf('Symfony\Component\Config\Tests\Fixtures\Builder\NodeBuilder', $nodeBuilder); - } - - public function testOverrideABuiltInNodeType() - { - $builder = new TreeBuilder(); - $root = $builder->root('override', 'array', new CustomNodeBuilder()); - - $definition = $root->children()->variableNode('variable'); - - $this->assertInstanceOf('Symfony\Component\Config\Tests\Fixtures\Builder\VariableNodeDefinition', $definition); - } - - public function testAddANodeType() - { - $builder = new TreeBuilder(); - $root = $builder->root('override', 'array', new CustomNodeBuilder()); - - $definition = $root->children()->barNode('variable'); - - $this->assertInstanceOf('Symfony\Component\Config\Tests\Fixtures\Builder\BarNodeDefinition', $definition); - } - - public function testCreateABuiltInNodeTypeWithACustomNodeBuilder() - { - $builder = new TreeBuilder(); - $root = $builder->root('builtin', 'array', new CustomNodeBuilder()); - - $definition = $root->children()->booleanNode('boolean'); - - $this->assertInstanceOf('Symfony\Component\Config\Definition\Builder\BooleanNodeDefinition', $definition); - } - - public function testPrototypedArrayNodeUseTheCustomNodeBuilder() - { - $builder = new TreeBuilder(); - $root = $builder->root('override', 'array', new CustomNodeBuilder()); - - $root->prototype('bar')->end(); - - $this->assertInstanceOf('Symfony\Component\Config\Tests\Fixtures\BarNode', $root->getNode(true)->getPrototype()); - } - - public function testAnExtendedNodeBuilderGetsPropagatedToTheChildren() - { - $builder = new TreeBuilder(); - - $builder->root('propagation') - ->children() - ->setNodeClass('extended', 'Symfony\Component\Config\Definition\Builder\BooleanNodeDefinition') - ->node('foo', 'extended')->end() - ->arrayNode('child') - ->children() - ->node('foo', 'extended') - ->end() - ->end() - ->end() - ->end(); - - $node = $builder->buildTree(); - $children = $node->getChildren(); - - $this->assertInstanceOf('Symfony\Component\Config\Definition\BooleanNode', $children['foo']); - - $childChildren = $children['child']->getChildren(); - - $this->assertInstanceOf('Symfony\Component\Config\Definition\BooleanNode', $childChildren['foo']); - } - - public function testDefinitionInfoGetsTransferredToNode() - { - $builder = new TreeBuilder(); - - $builder->root('test')->info('root info') - ->children() - ->node('child', 'variable')->info('child info')->defaultValue('default') - ->end() - ->end(); - - $tree = $builder->buildTree(); - $children = $tree->getChildren(); - - $this->assertEquals('root info', $tree->getInfo()); - $this->assertEquals('child info', $children['child']->getInfo()); - } - - public function testDefinitionExampleGetsTransferredToNode() - { - $builder = new TreeBuilder(); - - $builder->root('test') - ->example(['key' => 'value']) - ->children() - ->node('child', 'variable')->info('child info')->defaultValue('default')->example('example') - ->end() - ->end(); - - $tree = $builder->buildTree(); - $children = $tree->getChildren(); - - $this->assertIsArray($tree->getExample()); - $this->assertEquals('example', $children['child']->getExample()); - } -} diff --git a/lib/symfony/config/Tests/Definition/Dumper/XmlReferenceDumperTest.php b/lib/symfony/config/Tests/Definition/Dumper/XmlReferenceDumperTest.php deleted file mode 100644 index 5bc961bab..000000000 --- a/lib/symfony/config/Tests/Definition/Dumper/XmlReferenceDumperTest.php +++ /dev/null @@ -1,114 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Definition\Dumper; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Definition\Dumper\XmlReferenceDumper; -use Symfony\Component\Config\Tests\Fixtures\Configuration\ExampleConfiguration; - -class XmlReferenceDumperTest extends TestCase -{ - public function testDumper() - { - $configuration = new ExampleConfiguration(); - - $dumper = new XmlReferenceDumper(); - $this->assertEquals($this->getConfigurationAsString(), $dumper->dump($configuration)); - } - - public function testNamespaceDumper() - { - $configuration = new ExampleConfiguration(); - - $dumper = new XmlReferenceDumper(); - $this->assertEquals(str_replace('http://example.org/schema/dic/acme_root', 'http://symfony.com/schema/dic/symfony', $this->getConfigurationAsString()), $dumper->dump($configuration, 'http://symfony.com/schema/dic/symfony')); - } - - private function getConfigurationAsString() - { - return str_replace("\n", PHP_EOL, <<<'EOL' - - - - - - - - - - - - - - scalar value - - - scalar value - - - - - - - - - - - - - - - - - - - - - - - - -EOL - ); - } -} diff --git a/lib/symfony/config/Tests/Definition/Dumper/YamlReferenceDumperTest.php b/lib/symfony/config/Tests/Definition/Dumper/YamlReferenceDumperTest.php deleted file mode 100644 index 3cb9121ba..000000000 --- a/lib/symfony/config/Tests/Definition/Dumper/YamlReferenceDumperTest.php +++ /dev/null @@ -1,143 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Definition\Dumper; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Definition\Dumper\YamlReferenceDumper; -use Symfony\Component\Config\Tests\Fixtures\Configuration\ExampleConfiguration; - -class YamlReferenceDumperTest extends TestCase -{ - public function testDumper() - { - $configuration = new ExampleConfiguration(); - - $dumper = new YamlReferenceDumper(); - - $this->assertEquals($this->getConfigurationAsString(), $dumper->dump($configuration)); - } - - public function provideDumpAtPath() - { - return [ - 'Regular node' => ['scalar_true', << ['array', << ['array.child2', << ['cms_pages.page', << ['cms_pages.page.locale', <<assertSame(trim($expected), trim($dumper->dumpAtPath($configuration, $path))); - } - - private function getConfigurationAsString() - { - return <<<'EOL' -acme_root: - boolean: true - scalar_empty: ~ - scalar_null: null - scalar_true: true - scalar_false: false - scalar_default: default - scalar_array_empty: [] - scalar_array_defaults: - - # Defaults: - - elem1 - - elem2 - scalar_required: ~ # Required - scalar_deprecated: ~ # Deprecated (The child node "scalar_deprecated" at path "acme_root" is deprecated.) - scalar_deprecated_with_message: ~ # Deprecated (Deprecation custom message for "scalar_deprecated_with_message" at "acme_root") - node_with_a_looong_name: ~ - enum_with_default: this # One of "this"; "that" - enum: ~ # One of "this"; "that" - - # some info - array: - child1: ~ - child2: ~ - - # this is a long - # multi-line info text - # which should be indented - child3: ~ # Example: example setting - scalar_prototyped: [] - parameters: - - # Prototype: Parameter name - name: ~ - connections: - - # Prototype - - - user: ~ - pass: ~ - cms_pages: - - # Prototype - page: - - # Prototype - locale: - title: ~ # Required - path: ~ # Required - pipou: - - # Prototype - name: [] - -EOL; - } -} diff --git a/lib/symfony/config/Tests/Definition/EnumNodeTest.php b/lib/symfony/config/Tests/Definition/EnumNodeTest.php deleted file mode 100644 index fa89eea23..000000000 --- a/lib/symfony/config/Tests/Definition/EnumNodeTest.php +++ /dev/null @@ -1,51 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Definition; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Definition\EnumNode; - -class EnumNodeTest extends TestCase -{ - public function testFinalizeValue() - { - $node = new EnumNode('foo', null, ['foo', 'bar']); - $this->assertSame('foo', $node->finalize('foo')); - } - - public function testConstructionWithNoValues() - { - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessage('$values must contain at least one element.'); - new EnumNode('foo', null, []); - } - - public function testConstructionWithOneValue() - { - $node = new EnumNode('foo', null, ['foo']); - $this->assertSame('foo', $node->finalize('foo')); - } - - public function testConstructionWithOneDistinctValue() - { - $node = new EnumNode('foo', null, ['foo', 'foo']); - $this->assertSame('foo', $node->finalize('foo')); - } - - public function testFinalizeWithInvalidValue() - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); - $this->expectExceptionMessage('The value "foobar" is not allowed for path "foo". Permissible values: "foo", "bar"'); - $node = new EnumNode('foo', null, ['foo', 'bar']); - $node->finalize('foobar'); - } -} diff --git a/lib/symfony/config/Tests/Definition/FinalizationTest.php b/lib/symfony/config/Tests/Definition/FinalizationTest.php deleted file mode 100644 index be68a27c6..000000000 --- a/lib/symfony/config/Tests/Definition/FinalizationTest.php +++ /dev/null @@ -1,74 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Definition; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Definition\Builder\TreeBuilder; -use Symfony\Component\Config\Definition\NodeInterface; -use Symfony\Component\Config\Definition\Processor; - -class FinalizationTest extends TestCase -{ - public function testUnsetKeyWithDeepHierarchy() - { - $tb = new TreeBuilder(); - $tree = $tb - ->root('config', 'array') - ->children() - ->node('level1', 'array') - ->canBeUnset() - ->children() - ->node('level2', 'array') - ->canBeUnset() - ->children() - ->node('somevalue', 'scalar')->end() - ->node('anothervalue', 'scalar')->end() - ->end() - ->end() - ->node('level1_scalar', 'scalar')->end() - ->end() - ->end() - ->end() - ->end() - ->buildTree() - ; - - $a = [ - 'level1' => [ - 'level2' => [ - 'somevalue' => 'foo', - 'anothervalue' => 'bar', - ], - 'level1_scalar' => 'foo', - ], - ]; - - $b = [ - 'level1' => [ - 'level2' => false, - ], - ]; - - $this->assertEquals([ - 'level1' => [ - 'level1_scalar' => 'foo', - ], - ], $this->process($tree, [$a, $b])); - } - - protected function process(NodeInterface $tree, array $configs) - { - $processor = new Processor(); - - return $processor->process($tree, $configs); - } -} diff --git a/lib/symfony/config/Tests/Definition/FloatNodeTest.php b/lib/symfony/config/Tests/Definition/FloatNodeTest.php deleted file mode 100644 index fed9f013d..000000000 --- a/lib/symfony/config/Tests/Definition/FloatNodeTest.php +++ /dev/null @@ -1,78 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Definition; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Definition\FloatNode; - -class FloatNodeTest extends TestCase -{ - /** - * @dataProvider getValidValues - */ - public function testNormalize($value) - { - $node = new FloatNode('test'); - $this->assertSame($value, $node->normalize($value)); - } - - /** - * @dataProvider getValidValues - * - * @param int $value - */ - public function testValidNonEmptyValues($value) - { - $node = new FloatNode('test'); - $node->setAllowEmptyValue(false); - - $this->assertSame($value, $node->finalize($value)); - } - - public function getValidValues() - { - return [ - [1798.0], - [-678.987], - [12.56E45], - [0.0], - // Integer are accepted too, they will be cast - [17], - [-10], - [0], - ]; - } - - /** - * @dataProvider getInvalidValues - */ - public function testNormalizeThrowsExceptionOnInvalidValues($value) - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); - $node = new FloatNode('test'); - $node->normalize($value); - } - - public function getInvalidValues() - { - return [ - [null], - [''], - ['foo'], - [true], - [false], - [[]], - [['foo' => 'bar']], - [new \stdClass()], - ]; - } -} diff --git a/lib/symfony/config/Tests/Definition/IntegerNodeTest.php b/lib/symfony/config/Tests/Definition/IntegerNodeTest.php deleted file mode 100644 index 3fb1b771e..000000000 --- a/lib/symfony/config/Tests/Definition/IntegerNodeTest.php +++ /dev/null @@ -1,75 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Definition; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Definition\IntegerNode; - -class IntegerNodeTest extends TestCase -{ - /** - * @dataProvider getValidValues - */ - public function testNormalize($value) - { - $node = new IntegerNode('test'); - $this->assertSame($value, $node->normalize($value)); - } - - /** - * @dataProvider getValidValues - * - * @param int $value - */ - public function testValidNonEmptyValues($value) - { - $node = new IntegerNode('test'); - $node->setAllowEmptyValue(false); - - $this->assertSame($value, $node->finalize($value)); - } - - public function getValidValues() - { - return [ - [1798], - [-678], - [0], - ]; - } - - /** - * @dataProvider getInvalidValues - */ - public function testNormalizeThrowsExceptionOnInvalidValues($value) - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); - $node = new IntegerNode('test'); - $node->normalize($value); - } - - public function getInvalidValues() - { - return [ - [null], - [''], - ['foo'], - [true], - [false], - [0.0], - [0.1], - [[]], - [['foo' => 'bar']], - [new \stdClass()], - ]; - } -} diff --git a/lib/symfony/config/Tests/Definition/MergeTest.php b/lib/symfony/config/Tests/Definition/MergeTest.php deleted file mode 100644 index 8fee2635c..000000000 --- a/lib/symfony/config/Tests/Definition/MergeTest.php +++ /dev/null @@ -1,192 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Definition; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Definition\Builder\TreeBuilder; - -class MergeTest extends TestCase -{ - public function testForbiddenOverwrite() - { - $this->expectException('Symfony\Component\Config\Definition\Exception\ForbiddenOverwriteException'); - $tb = new TreeBuilder(); - $tree = $tb - ->root('root', 'array') - ->children() - ->node('foo', 'scalar') - ->cannotBeOverwritten() - ->end() - ->end() - ->end() - ->buildTree() - ; - - $a = [ - 'foo' => 'bar', - ]; - - $b = [ - 'foo' => 'moo', - ]; - - $tree->merge($a, $b); - } - - public function testUnsetKey() - { - $tb = new TreeBuilder(); - $tree = $tb - ->root('root', 'array') - ->children() - ->node('foo', 'scalar')->end() - ->node('bar', 'scalar')->end() - ->node('unsettable', 'array') - ->canBeUnset() - ->children() - ->node('foo', 'scalar')->end() - ->node('bar', 'scalar')->end() - ->end() - ->end() - ->node('unsetted', 'array') - ->canBeUnset() - ->prototype('scalar')->end() - ->end() - ->end() - ->end() - ->buildTree() - ; - - $a = [ - 'foo' => 'bar', - 'unsettable' => [ - 'foo' => 'a', - 'bar' => 'b', - ], - 'unsetted' => false, - ]; - - $b = [ - 'foo' => 'moo', - 'bar' => 'b', - 'unsettable' => false, - 'unsetted' => ['a', 'b'], - ]; - - $this->assertEquals([ - 'foo' => 'moo', - 'bar' => 'b', - 'unsettable' => false, - 'unsetted' => ['a', 'b'], - ], $tree->merge($a, $b)); - } - - public function testDoesNotAllowNewKeysInSubsequentConfigs() - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); - $tb = new TreeBuilder(); - $tree = $tb - ->root('config', 'array') - ->children() - ->node('test', 'array') - ->disallowNewKeysInSubsequentConfigs() - ->useAttributeAsKey('key') - ->prototype('array') - ->children() - ->node('value', 'scalar')->end() - ->end() - ->end() - ->end() - ->end() - ->end() - ->buildTree(); - - $a = [ - 'test' => [ - 'a' => ['value' => 'foo'], - ], - ]; - - $b = [ - 'test' => [ - 'b' => ['value' => 'foo'], - ], - ]; - - $tree->merge($a, $b); - } - - public function testPerformsNoDeepMerging() - { - $tb = new TreeBuilder(); - - $tree = $tb - ->root('config', 'array') - ->children() - ->node('no_deep_merging', 'array') - ->performNoDeepMerging() - ->children() - ->node('foo', 'scalar')->end() - ->node('bar', 'scalar')->end() - ->end() - ->end() - ->end() - ->end() - ->buildTree() - ; - - $a = [ - 'no_deep_merging' => [ - 'foo' => 'a', - 'bar' => 'b', - ], - ]; - - $b = [ - 'no_deep_merging' => [ - 'c' => 'd', - ], - ]; - - $this->assertEquals([ - 'no_deep_merging' => [ - 'c' => 'd', - ], - ], $tree->merge($a, $b)); - } - - public function testPrototypeWithoutAKeyAttribute() - { - $tb = new TreeBuilder(); - - $tree = $tb - ->root('config', 'array') - ->children() - ->arrayNode('append_elements') - ->prototype('scalar')->end() - ->end() - ->end() - ->end() - ->buildTree() - ; - - $a = [ - 'append_elements' => ['a', 'b'], - ]; - - $b = [ - 'append_elements' => ['c', 'd'], - ]; - - $this->assertEquals(['append_elements' => ['a', 'b', 'c', 'd']], $tree->merge($a, $b)); - } -} diff --git a/lib/symfony/config/Tests/Definition/NormalizationTest.php b/lib/symfony/config/Tests/Definition/NormalizationTest.php deleted file mode 100644 index 200a98594..000000000 --- a/lib/symfony/config/Tests/Definition/NormalizationTest.php +++ /dev/null @@ -1,228 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Definition; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Definition\Builder\TreeBuilder; -use Symfony\Component\Config\Definition\NodeInterface; - -class NormalizationTest extends TestCase -{ - /** - * @dataProvider getEncoderTests - */ - public function testNormalizeEncoders($denormalized) - { - $tb = new TreeBuilder(); - $tree = $tb - ->root('root_name', 'array') - ->fixXmlConfig('encoder') - ->children() - ->node('encoders', 'array') - ->useAttributeAsKey('class') - ->prototype('array') - ->beforeNormalization()->ifString()->then(function ($v) { return ['algorithm' => $v]; })->end() - ->children() - ->node('algorithm', 'scalar')->end() - ->end() - ->end() - ->end() - ->end() - ->end() - ->buildTree() - ; - - $normalized = [ - 'encoders' => [ - 'foo' => ['algorithm' => 'plaintext'], - ], - ]; - - $this->assertNormalized($tree, $denormalized, $normalized); - } - - public function getEncoderTests() - { - $configs = []; - - // XML - $configs[] = [ - 'encoder' => [ - ['class' => 'foo', 'algorithm' => 'plaintext'], - ], - ]; - - // XML when only one element of this type - $configs[] = [ - 'encoder' => ['class' => 'foo', 'algorithm' => 'plaintext'], - ]; - - // YAML/PHP - $configs[] = [ - 'encoders' => [ - ['class' => 'foo', 'algorithm' => 'plaintext'], - ], - ]; - - // YAML/PHP - $configs[] = [ - 'encoders' => [ - 'foo' => 'plaintext', - ], - ]; - - // YAML/PHP - $configs[] = [ - 'encoders' => [ - 'foo' => ['algorithm' => 'plaintext'], - ], - ]; - - return array_map(function ($v) { - return [$v]; - }, $configs); - } - - /** - * @dataProvider getAnonymousKeysTests - */ - public function testAnonymousKeysArray($denormalized) - { - $tb = new TreeBuilder(); - $tree = $tb - ->root('root', 'array') - ->children() - ->node('logout', 'array') - ->fixXmlConfig('handler') - ->children() - ->node('handlers', 'array') - ->prototype('scalar')->end() - ->end() - ->end() - ->end() - ->end() - ->end() - ->buildTree() - ; - - $normalized = ['logout' => ['handlers' => ['a', 'b', 'c']]]; - - $this->assertNormalized($tree, $denormalized, $normalized); - } - - public function getAnonymousKeysTests() - { - $configs = []; - - $configs[] = [ - 'logout' => [ - 'handlers' => ['a', 'b', 'c'], - ], - ]; - - $configs[] = [ - 'logout' => [ - 'handler' => ['a', 'b', 'c'], - ], - ]; - - return array_map(function ($v) { return [$v]; }, $configs); - } - - /** - * @dataProvider getNumericKeysTests - */ - public function testNumericKeysAsAttributes($denormalized) - { - $normalized = [ - 'thing' => [42 => ['foo', 'bar'], 1337 => ['baz', 'qux']], - ]; - - $this->assertNormalized($this->getNumericKeysTestTree(), $denormalized, $normalized); - } - - public function getNumericKeysTests() - { - $configs = []; - - $configs[] = [ - 'thing' => [ - 42 => ['foo', 'bar'], 1337 => ['baz', 'qux'], - ], - ]; - - $configs[] = [ - 'thing' => [ - ['foo', 'bar', 'id' => 42], ['baz', 'qux', 'id' => 1337], - ], - ]; - - return array_map(function ($v) { return [$v]; }, $configs); - } - - public function testNonAssociativeArrayThrowsExceptionIfAttributeNotSet() - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); - $this->expectExceptionMessage('The attribute "id" must be set for path "root.thing".'); - $denormalized = [ - 'thing' => [ - ['foo', 'bar'], ['baz', 'qux'], - ], - ]; - - $this->assertNormalized($this->getNumericKeysTestTree(), $denormalized, []); - } - - public function testAssociativeArrayPreserveKeys() - { - $tb = new TreeBuilder(); - $tree = $tb - ->root('root', 'array') - ->prototype('array') - ->children() - ->node('foo', 'scalar')->end() - ->end() - ->end() - ->end() - ->buildTree() - ; - - $data = ['first' => ['foo' => 'bar']]; - - $this->assertNormalized($tree, $data, $data); - } - - public static function assertNormalized(NodeInterface $tree, $denormalized, $normalized) - { - self::assertSame($normalized, $tree->normalize($denormalized)); - } - - private function getNumericKeysTestTree() - { - $tb = new TreeBuilder(); - $tree = $tb - ->root('root', 'array') - ->children() - ->node('thing', 'array') - ->useAttributeAsKey('id') - ->prototype('array') - ->prototype('scalar')->end() - ->end() - ->end() - ->end() - ->end() - ->buildTree() - ; - - return $tree; - } -} diff --git a/lib/symfony/config/Tests/Definition/PrototypedArrayNodeTest.php b/lib/symfony/config/Tests/Definition/PrototypedArrayNodeTest.php deleted file mode 100644 index 7a58ead8d..000000000 --- a/lib/symfony/config/Tests/Definition/PrototypedArrayNodeTest.php +++ /dev/null @@ -1,341 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Definition; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Definition\ArrayNode; -use Symfony\Component\Config\Definition\PrototypedArrayNode; -use Symfony\Component\Config\Definition\ScalarNode; -use Symfony\Component\Config\Definition\VariableNode; - -class PrototypedArrayNodeTest extends TestCase -{ - public function testGetDefaultValueReturnsAnEmptyArrayForPrototypes() - { - $node = new PrototypedArrayNode('root'); - $prototype = new ArrayNode(null, $node); - $node->setPrototype($prototype); - $this->assertEmpty($node->getDefaultValue()); - } - - public function testGetDefaultValueReturnsDefaultValueForPrototypes() - { - $node = new PrototypedArrayNode('root'); - $prototype = new ArrayNode(null, $node); - $node->setPrototype($prototype); - $node->setDefaultValue(['test']); - $this->assertEquals(['test'], $node->getDefaultValue()); - } - - // a remapped key (e.g. "mapping" -> "mappings") should be unset after being used - public function testRemappedKeysAreUnset() - { - $node = new ArrayNode('root'); - $mappingsNode = new PrototypedArrayNode('mappings'); - $node->addChild($mappingsNode); - - // each item under mappings is just a scalar - $prototype = new ScalarNode(null, $mappingsNode); - $mappingsNode->setPrototype($prototype); - - $remappings = []; - $remappings[] = ['mapping', 'mappings']; - $node->setXmlRemappings($remappings); - - $normalized = $node->normalize(['mapping' => ['foo', 'bar']]); - $this->assertEquals(['mappings' => ['foo', 'bar']], $normalized); - } - - /** - * Tests that when a key attribute is mapped, that key is removed from the array. - * - * - * - * - * The above should finally be mapped to an array that looks like this - * (because "id" is the key attribute). - * - * [ - * 'things' => [ - * 'option1' => 'foo', - * 'option2' => 'bar', - * ] - * ] - */ - public function testMappedAttributeKeyIsRemoved() - { - $node = new PrototypedArrayNode('root'); - $node->setKeyAttribute('id', true); - - // each item under the root is an array, with one scalar item - $prototype = new ArrayNode(null, $node); - $prototype->addChild(new ScalarNode('foo')); - $node->setPrototype($prototype); - - $children = []; - $children[] = ['id' => 'item_name', 'foo' => 'bar']; - $normalized = $node->normalize($children); - - $expected = []; - $expected['item_name'] = ['foo' => 'bar']; - $this->assertEquals($expected, $normalized); - } - - /** - * Tests the opposite of the testMappedAttributeKeyIsRemoved because - * the removal can be toggled with an option. - */ - public function testMappedAttributeKeyNotRemoved() - { - $node = new PrototypedArrayNode('root'); - $node->setKeyAttribute('id', false); - - // each item under the root is an array, with two scalar items - $prototype = new ArrayNode(null, $node); - $prototype->addChild(new ScalarNode('foo')); - $prototype->addChild(new ScalarNode('id')); // the key attribute will remain - $node->setPrototype($prototype); - - $children = []; - $children[] = ['id' => 'item_name', 'foo' => 'bar']; - $normalized = $node->normalize($children); - - $expected = []; - $expected['item_name'] = ['id' => 'item_name', 'foo' => 'bar']; - $this->assertEquals($expected, $normalized); - } - - public function testAddDefaultChildren() - { - $node = $this->getPrototypeNodeWithDefaultChildren(); - $node->setAddChildrenIfNoneSet(); - $this->assertTrue($node->hasDefaultValue()); - $this->assertEquals([['foo' => 'bar']], $node->getDefaultValue()); - - $node = $this->getPrototypeNodeWithDefaultChildren(); - $node->setKeyAttribute('foobar'); - $node->setAddChildrenIfNoneSet(); - $this->assertTrue($node->hasDefaultValue()); - $this->assertEquals(['defaults' => ['foo' => 'bar']], $node->getDefaultValue()); - - $node = $this->getPrototypeNodeWithDefaultChildren(); - $node->setKeyAttribute('foobar'); - $node->setAddChildrenIfNoneSet('defaultkey'); - $this->assertTrue($node->hasDefaultValue()); - $this->assertEquals(['defaultkey' => ['foo' => 'bar']], $node->getDefaultValue()); - - $node = $this->getPrototypeNodeWithDefaultChildren(); - $node->setKeyAttribute('foobar'); - $node->setAddChildrenIfNoneSet(['defaultkey']); - $this->assertTrue($node->hasDefaultValue()); - $this->assertEquals(['defaultkey' => ['foo' => 'bar']], $node->getDefaultValue()); - - $node = $this->getPrototypeNodeWithDefaultChildren(); - $node->setKeyAttribute('foobar'); - $node->setAddChildrenIfNoneSet(['dk1', 'dk2']); - $this->assertTrue($node->hasDefaultValue()); - $this->assertEquals(['dk1' => ['foo' => 'bar'], 'dk2' => ['foo' => 'bar']], $node->getDefaultValue()); - - $node = $this->getPrototypeNodeWithDefaultChildren(); - $node->setAddChildrenIfNoneSet([5, 6]); - $this->assertTrue($node->hasDefaultValue()); - $this->assertEquals([0 => ['foo' => 'bar'], 1 => ['foo' => 'bar']], $node->getDefaultValue()); - - $node = $this->getPrototypeNodeWithDefaultChildren(); - $node->setAddChildrenIfNoneSet(2); - $this->assertTrue($node->hasDefaultValue()); - $this->assertEquals([['foo' => 'bar'], ['foo' => 'bar']], $node->getDefaultValue()); - } - - public function testDefaultChildrenWinsOverDefaultValue() - { - $node = $this->getPrototypeNodeWithDefaultChildren(); - $node->setAddChildrenIfNoneSet(); - $node->setDefaultValue(['bar' => 'foo']); - $this->assertTrue($node->hasDefaultValue()); - $this->assertEquals([['foo' => 'bar']], $node->getDefaultValue()); - } - - protected function getPrototypeNodeWithDefaultChildren() - { - $node = new PrototypedArrayNode('root'); - $prototype = new ArrayNode(null, $node); - $child = new ScalarNode('foo'); - $child->setDefaultValue('bar'); - $prototype->addChild($child); - $prototype->setAddIfNotSet(true); - $node->setPrototype($prototype); - - return $node; - } - - /** - * Tests that when a key attribute is mapped, that key is removed from the array. - * And if only 'value' element is left in the array, it will replace its wrapper array. - * - * - * - * - * The above should finally be mapped to an array that looks like this - * (because "id" is the key attribute). - * - * [ - * 'things' => [ - * 'option1' => 'value1' - * ] - * ] - * - * It's also possible to mix 'value-only' and 'non-value-only' elements in the array. - * - * - * - * - * The above should finally be mapped to an array as follows - * - * [ - * 'things' => [ - * 'option1' => 'value1', - * 'option2' => [ - * 'value' => 'value2', - * 'foo' => 'foo2' - * ] - * ] - * ] - * - * The 'value' element can also be ArrayNode: - * - * - * - * - * - * The above should be finally be mapped to an array as follows - * - * [ - * 'things' => [ - * 'option1' => [ - * 'foo' => 'foo1', - * 'bar' => 'bar1' - * ] - * ] - * ] - * - * If using VariableNode for value node, it's also possible to mix different types of value nodes: - * - * - * - * - * - * The above should be finally mapped to an array as follows - * - * [ - * 'things' => [ - * 'option1' => [ - * 'foo' => 'foo1', - * 'bar' => 'bar1' - * ], - * 'option2' => 'value2' - * ] - * ] - * - * @dataProvider getDataForKeyRemovedLeftValueOnly - */ - public function testMappedAttributeKeyIsRemovedLeftValueOnly($value, $children, $expected) - { - $node = new PrototypedArrayNode('root'); - $node->setKeyAttribute('id', true); - - // each item under the root is an array, with one scalar item - $prototype = new ArrayNode(null, $node); - $prototype->addChild(new ScalarNode('id')); - $prototype->addChild(new ScalarNode('foo')); - $prototype->addChild($value); - $node->setPrototype($prototype); - - $normalized = $node->normalize($children); - $this->assertEquals($expected, $normalized); - } - - public function getDataForKeyRemovedLeftValueOnly() - { - $scalarValue = new ScalarNode('value'); - - $arrayValue = new ArrayNode('value'); - $arrayValue->addChild(new ScalarNode('foo')); - $arrayValue->addChild(new ScalarNode('bar')); - - $variableValue = new VariableNode('value'); - - return [ - [ - $scalarValue, - [ - ['id' => 'option1', 'value' => 'value1'], - ], - ['option1' => 'value1'], - ], - - [ - $scalarValue, - [ - ['id' => 'option1', 'value' => 'value1'], - ['id' => 'option2', 'value' => 'value2', 'foo' => 'foo2'], - ], - [ - 'option1' => 'value1', - 'option2' => ['value' => 'value2', 'foo' => 'foo2'], - ], - ], - - [ - $arrayValue, - [ - [ - 'id' => 'option1', - 'value' => ['foo' => 'foo1', 'bar' => 'bar1'], - ], - ], - [ - 'option1' => ['foo' => 'foo1', 'bar' => 'bar1'], - ], - ], - - [$variableValue, - [ - [ - 'id' => 'option1', 'value' => ['foo' => 'foo1', 'bar' => 'bar1'], - ], - ['id' => 'option2', 'value' => 'value2'], - ], - [ - 'option1' => ['foo' => 'foo1', 'bar' => 'bar1'], - 'option2' => 'value2', - ], - ], - ]; - } -} diff --git a/lib/symfony/config/Tests/Definition/ScalarNodeTest.php b/lib/symfony/config/Tests/Definition/ScalarNodeTest.php deleted file mode 100644 index 4413baf3c..000000000 --- a/lib/symfony/config/Tests/Definition/ScalarNodeTest.php +++ /dev/null @@ -1,161 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Definition; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Definition\ArrayNode; -use Symfony\Component\Config\Definition\ScalarNode; - -class ScalarNodeTest extends TestCase -{ - /** - * @dataProvider getValidValues - */ - public function testNormalize($value) - { - $node = new ScalarNode('test'); - $this->assertSame($value, $node->normalize($value)); - } - - public function getValidValues() - { - return [ - [false], - [true], - [null], - [''], - ['foo'], - [0], - [1], - [0.0], - [0.1], - ]; - } - - public function testSetDeprecated() - { - $childNode = new ScalarNode('foo'); - $childNode->setDeprecated('"%node%" is deprecated'); - - $this->assertTrue($childNode->isDeprecated()); - $this->assertSame('"foo" is deprecated', $childNode->getDeprecationMessage($childNode->getName(), $childNode->getPath())); - - $node = new ArrayNode('root'); - $node->addChild($childNode); - - $deprecationTriggered = 0; - $deprecationHandler = function ($level, $message, $file, $line) use (&$prevErrorHandler, &$deprecationTriggered) { - if (E_USER_DEPRECATED === $level) { - return ++$deprecationTriggered; - } - - return $prevErrorHandler ? $prevErrorHandler($level, $message, $file, $line) : false; - }; - - $prevErrorHandler = set_error_handler($deprecationHandler); - $node->finalize([]); - restore_error_handler(); - $this->assertSame(0, $deprecationTriggered, '->finalize() should not trigger if the deprecated node is not set'); - - $prevErrorHandler = set_error_handler($deprecationHandler); - $node->finalize(['foo' => '']); - restore_error_handler(); - $this->assertSame(1, $deprecationTriggered, '->finalize() should trigger if the deprecated node is set'); - } - - /** - * @dataProvider getInvalidValues - */ - public function testNormalizeThrowsExceptionOnInvalidValues($value) - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); - $node = new ScalarNode('test'); - $node->normalize($value); - } - - public function getInvalidValues() - { - return [ - [[]], - [['foo' => 'bar']], - [new \stdClass()], - ]; - } - - public function testNormalizeThrowsExceptionWithoutHint() - { - $node = new ScalarNode('test'); - - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); - $this->expectExceptionMessage('Invalid type for path "test". Expected scalar, but got array.'); - - $node->normalize([]); - } - - public function testNormalizeThrowsExceptionWithErrorMessage() - { - $node = new ScalarNode('test'); - $node->setInfo('"the test value"'); - - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); - $this->expectExceptionMessage("Invalid type for path \"test\". Expected scalar, but got array.\nHint: \"the test value\""); - - $node->normalize([]); - } - - /** - * @dataProvider getValidNonEmptyValues - * - * @param mixed $value - */ - public function testValidNonEmptyValues($value) - { - $node = new ScalarNode('test'); - $node->setAllowEmptyValue(false); - - $this->assertSame($value, $node->finalize($value)); - } - - public function getValidNonEmptyValues() - { - return [ - [false], - [true], - ['foo'], - [0], - [1], - [0.0], - [0.1], - ]; - } - - /** - * @dataProvider getEmptyValues - * - * @param mixed $value - */ - public function testNotAllowedEmptyValuesThrowException($value) - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); - $node = new ScalarNode('test'); - $node->setAllowEmptyValue(false); - $node->finalize($value); - } - - public function getEmptyValues() - { - return [ - [null], - [''], - ]; - } -} diff --git a/lib/symfony/config/Tests/DependencyInjection/ConfigCachePassTest.php b/lib/symfony/config/Tests/DependencyInjection/ConfigCachePassTest.php deleted file mode 100644 index c2b95195d..000000000 --- a/lib/symfony/config/Tests/DependencyInjection/ConfigCachePassTest.php +++ /dev/null @@ -1,59 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\DependencyInjection; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\DependencyInjection\ConfigCachePass; -use Symfony\Component\DependencyInjection\Argument\IteratorArgument; -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Reference; - -/** - * @group legacy - */ -class ConfigCachePassTest extends TestCase -{ - public function testThatCheckersAreProcessedInPriorityOrder() - { - $container = new ContainerBuilder(); - - $definition = $container->register('config_cache_factory')->addArgument(null); - $container->register('checker_2')->addTag('config_cache.resource_checker', ['priority' => 100]); - $container->register('checker_1')->addTag('config_cache.resource_checker', ['priority' => 200]); - $container->register('checker_3')->addTag('config_cache.resource_checker'); - - $pass = new ConfigCachePass(); - $pass->process($container); - - $expected = new IteratorArgument([ - new Reference('checker_1'), - new Reference('checker_2'), - new Reference('checker_3'), - ]); - $this->assertEquals($expected, $definition->getArgument(0)); - } - - public function testThatCheckersCanBeMissing() - { - $container = new ContainerBuilder(); - - $definitionsBefore = \count($container->getDefinitions()); - $aliasesBefore = \count($container->getAliases()); - - $pass = new ConfigCachePass(); - $pass->process($container); - - // the container is untouched (i.e. no new definitions or aliases) - $this->assertCount($definitionsBefore, $container->getDefinitions()); - $this->assertCount($aliasesBefore, $container->getAliases()); - } -} diff --git a/lib/symfony/config/Tests/Exception/FileLoaderLoadExceptionTest.php b/lib/symfony/config/Tests/Exception/FileLoaderLoadExceptionTest.php deleted file mode 100644 index 8363084c1..000000000 --- a/lib/symfony/config/Tests/Exception/FileLoaderLoadExceptionTest.php +++ /dev/null @@ -1,98 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Exception; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Exception\FileLoaderLoadException; - -class FileLoaderLoadExceptionTest extends TestCase -{ - public function testMessageCannotLoadResource() - { - $exception = new FileLoaderLoadException('resource', null); - $this->assertEquals('Cannot load resource "resource".', $exception->getMessage()); - } - - public function testMessageCannotLoadResourceWithType() - { - $exception = new FileLoaderLoadException('resource', null, null, null, 'foobar'); - $this->assertEquals('Cannot load resource "resource". Make sure there is a loader supporting the "foobar" type.', $exception->getMessage()); - } - - public function testMessageCannotLoadResourceWithAnnotationType() - { - $exception = new FileLoaderLoadException('resource', null, null, null, 'annotation'); - $this->assertEquals('Cannot load resource "resource". Make sure annotations are installed and enabled.', $exception->getMessage()); - } - - public function testMessageCannotImportResourceFromSource() - { - $exception = new FileLoaderLoadException('resource', 'sourceResource'); - $this->assertEquals('Cannot import resource "resource" from "sourceResource".', $exception->getMessage()); - } - - public function testMessageCannotImportBundleResource() - { - $exception = new FileLoaderLoadException('@resource', 'sourceResource'); - $this->assertEquals( - 'Cannot import resource "@resource" from "sourceResource". '. - 'Make sure the "resource" bundle is correctly registered and loaded in the application kernel class. '. - 'If the bundle is registered, make sure the bundle path "@resource" is not empty.', - $exception->getMessage() - ); - } - - public function testMessageHasPreviousErrorWithDotAndUnableToLoad() - { - $exception = new FileLoaderLoadException( - 'resource', - null, - null, - new \Exception('There was a previous error with an ending dot.') - ); - $this->assertEquals( - 'There was a previous error with an ending dot in resource (which is loaded in resource "resource").', - $exception->getMessage() - ); - } - - public function testMessageHasPreviousErrorWithoutDotAndUnableToLoad() - { - $exception = new FileLoaderLoadException( - 'resource', - null, - null, - new \Exception('There was a previous error with no ending dot') - ); - $this->assertEquals( - 'There was a previous error with no ending dot in resource (which is loaded in resource "resource").', - $exception->getMessage() - ); - } - - public function testMessageHasPreviousErrorAndUnableToLoadBundle() - { - $exception = new FileLoaderLoadException( - '@resource', - null, - null, - new \Exception('There was a previous error with an ending dot.') - ); - $this->assertEquals( - 'There was a previous error with an ending dot in @resource '. - '(which is loaded in resource "@resource"). '. - 'Make sure the "resource" bundle is correctly registered and loaded in the application kernel class. '. - 'If the bundle is registered, make sure the bundle path "@resource" is not empty.', - $exception->getMessage() - ); - } -} diff --git a/lib/symfony/config/Tests/FileLocatorTest.php b/lib/symfony/config/Tests/FileLocatorTest.php deleted file mode 100644 index e931916af..000000000 --- a/lib/symfony/config/Tests/FileLocatorTest.php +++ /dev/null @@ -1,114 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\FileLocator; - -class FileLocatorTest extends TestCase -{ - /** - * @dataProvider getIsAbsolutePathTests - */ - public function testIsAbsolutePath($path) - { - $loader = new FileLocator([]); - $r = new \ReflectionObject($loader); - $m = $r->getMethod('isAbsolutePath'); - $m->setAccessible(true); - - $this->assertTrue($m->invoke($loader, $path), '->isAbsolutePath() returns true for an absolute path'); - } - - public function getIsAbsolutePathTests() - { - return [ - ['/foo.xml'], - ['c:\\\\foo.xml'], - ['c:/foo.xml'], - ['\\server\\foo.xml'], - ['https://server/foo.xml'], - ['phar://server/foo.xml'], - ]; - } - - public function testLocate() - { - $loader = new FileLocator(__DIR__.'/Fixtures'); - - $this->assertEquals( - __DIR__.\DIRECTORY_SEPARATOR.'FileLocatorTest.php', - $loader->locate('FileLocatorTest.php', __DIR__), - '->locate() returns the absolute filename if the file exists in the given path' - ); - - $this->assertEquals( - __DIR__.'/Fixtures'.\DIRECTORY_SEPARATOR.'foo.xml', - $loader->locate('foo.xml', __DIR__), - '->locate() returns the absolute filename if the file exists in one of the paths given in the constructor' - ); - - $this->assertEquals( - __DIR__.'/Fixtures'.\DIRECTORY_SEPARATOR.'foo.xml', - $loader->locate(__DIR__.'/Fixtures'.\DIRECTORY_SEPARATOR.'foo.xml', __DIR__), - '->locate() returns the absolute filename if the file exists in one of the paths given in the constructor' - ); - - $loader = new FileLocator([__DIR__.'/Fixtures', __DIR__.'/Fixtures/Again']); - - $this->assertEquals( - [__DIR__.'/Fixtures'.\DIRECTORY_SEPARATOR.'foo.xml', __DIR__.'/Fixtures/Again'.\DIRECTORY_SEPARATOR.'foo.xml'], - $loader->locate('foo.xml', __DIR__, false), - '->locate() returns an array of absolute filenames' - ); - - $this->assertEquals( - [__DIR__.'/Fixtures'.\DIRECTORY_SEPARATOR.'foo.xml', __DIR__.'/Fixtures/Again'.\DIRECTORY_SEPARATOR.'foo.xml'], - $loader->locate('foo.xml', __DIR__.'/Fixtures', false), - '->locate() returns an array of absolute filenames' - ); - - $loader = new FileLocator(__DIR__.'/Fixtures/Again'); - - $this->assertEquals( - [__DIR__.'/Fixtures'.\DIRECTORY_SEPARATOR.'foo.xml', __DIR__.'/Fixtures/Again'.\DIRECTORY_SEPARATOR.'foo.xml'], - $loader->locate('foo.xml', __DIR__.'/Fixtures', false), - '->locate() returns an array of absolute filenames' - ); - } - - public function testLocateThrowsAnExceptionIfTheFileDoesNotExists() - { - $this->expectException('Symfony\Component\Config\Exception\FileLocatorFileNotFoundException'); - $this->expectExceptionMessage('The file "foobar.xml" does not exist'); - $loader = new FileLocator([__DIR__.'/Fixtures']); - - $loader->locate('foobar.xml', __DIR__); - } - - public function testLocateThrowsAnExceptionIfTheFileDoesNotExistsInAbsolutePath() - { - $this->expectException('Symfony\Component\Config\Exception\FileLocatorFileNotFoundException'); - $loader = new FileLocator([__DIR__.'/Fixtures']); - - $loader->locate(__DIR__.'/Fixtures/foobar.xml', __DIR__); - } - - public function testLocateEmpty() - { - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessage('An empty file name is not valid to be located.'); - $loader = new FileLocator([__DIR__.'/Fixtures']); - - $loader->locate(null, __DIR__); - } -} diff --git a/lib/symfony/config/Tests/Fixtures/Again/foo.xml b/lib/symfony/config/Tests/Fixtures/Again/foo.xml deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/symfony/config/Tests/Fixtures/BadParent.php b/lib/symfony/config/Tests/Fixtures/BadParent.php deleted file mode 100644 index 68d7296ed..000000000 --- a/lib/symfony/config/Tests/Fixtures/BadParent.php +++ /dev/null @@ -1,7 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Fixtures; - -use Symfony\Component\Config\Definition\ArrayNode; - -class BarNode extends ArrayNode -{ -} diff --git a/lib/symfony/config/Tests/Fixtures/Builder/BarNodeDefinition.php b/lib/symfony/config/Tests/Fixtures/Builder/BarNodeDefinition.php deleted file mode 100644 index b9c62e537..000000000 --- a/lib/symfony/config/Tests/Fixtures/Builder/BarNodeDefinition.php +++ /dev/null @@ -1,23 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Fixtures\Builder; - -use Symfony\Component\Config\Definition\Builder\NodeDefinition; -use Symfony\Component\Config\Tests\Fixtures\BarNode; - -class BarNodeDefinition extends NodeDefinition -{ - protected function createNode() - { - return new BarNode($this->name); - } -} diff --git a/lib/symfony/config/Tests/Fixtures/Builder/NodeBuilder.php b/lib/symfony/config/Tests/Fixtures/Builder/NodeBuilder.php deleted file mode 100644 index 22b8b32fb..000000000 --- a/lib/symfony/config/Tests/Fixtures/Builder/NodeBuilder.php +++ /dev/null @@ -1,34 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Fixtures\Builder; - -use Symfony\Component\Config\Definition\Builder\NodeBuilder as BaseNodeBuilder; - -class NodeBuilder extends BaseNodeBuilder -{ - public function barNode($name) - { - return $this->node($name, 'bar'); - } - - protected function getNodeClass($type) - { - switch ($type) { - case 'variable': - return __NAMESPACE__.'\\'.ucfirst($type).'NodeDefinition'; - case 'bar': - return __NAMESPACE__.'\\'.ucfirst($type).'NodeDefinition'; - default: - return parent::getNodeClass($type); - } - } -} diff --git a/lib/symfony/config/Tests/Fixtures/Builder/VariableNodeDefinition.php b/lib/symfony/config/Tests/Fixtures/Builder/VariableNodeDefinition.php deleted file mode 100644 index 6126ed434..000000000 --- a/lib/symfony/config/Tests/Fixtures/Builder/VariableNodeDefinition.php +++ /dev/null @@ -1,18 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Fixtures\Builder; - -use Symfony\Component\Config\Definition\Builder\VariableNodeDefinition as BaseVariableNodeDefinition; - -class VariableNodeDefinition extends BaseVariableNodeDefinition -{ -} diff --git a/lib/symfony/config/Tests/Fixtures/Configuration/ExampleConfiguration.php b/lib/symfony/config/Tests/Fixtures/Configuration/ExampleConfiguration.php deleted file mode 100644 index 3f02700a1..000000000 --- a/lib/symfony/config/Tests/Fixtures/Configuration/ExampleConfiguration.php +++ /dev/null @@ -1,102 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Fixtures\Configuration; - -use Symfony\Component\Config\Definition\Builder\TreeBuilder; -use Symfony\Component\Config\Definition\ConfigurationInterface; - -class ExampleConfiguration implements ConfigurationInterface -{ - public function getConfigTreeBuilder() - { - $treeBuilder = new TreeBuilder(); - $rootNode = $treeBuilder->root('acme_root'); - - $rootNode - ->fixXmlConfig('parameter') - ->fixXmlConfig('connection') - ->fixXmlConfig('cms_page') - ->children() - ->booleanNode('boolean')->defaultTrue()->end() - ->scalarNode('scalar_empty')->end() - ->scalarNode('scalar_null')->defaultNull()->end() - ->scalarNode('scalar_true')->defaultTrue()->end() - ->scalarNode('scalar_false')->defaultFalse()->end() - ->scalarNode('scalar_default')->defaultValue('default')->end() - ->scalarNode('scalar_array_empty')->defaultValue([])->end() - ->scalarNode('scalar_array_defaults')->defaultValue(['elem1', 'elem2'])->end() - ->scalarNode('scalar_required')->isRequired()->end() - ->scalarNode('scalar_deprecated')->setDeprecated()->end() - ->scalarNode('scalar_deprecated_with_message')->setDeprecated('Deprecation custom message for "%node%" at "%path%"')->end() - ->scalarNode('node_with_a_looong_name')->end() - ->enumNode('enum_with_default')->values(['this', 'that'])->defaultValue('this')->end() - ->enumNode('enum')->values(['this', 'that'])->end() - ->arrayNode('array') - ->info('some info') - ->canBeUnset() - ->children() - ->scalarNode('child1')->end() - ->scalarNode('child2')->end() - ->scalarNode('child3') - ->info( - "this is a long\n". - "multi-line info text\n". - 'which should be indented' - ) - ->example('example setting') - ->end() - ->end() - ->end() - ->arrayNode('scalar_prototyped') - ->prototype('scalar')->end() - ->end() - ->arrayNode('parameters') - ->useAttributeAsKey('name') - ->prototype('scalar')->info('Parameter name')->end() - ->end() - ->arrayNode('connections') - ->prototype('array') - ->children() - ->scalarNode('user')->end() - ->scalarNode('pass')->end() - ->end() - ->end() - ->end() - ->arrayNode('cms_pages') - ->useAttributeAsKey('page') - ->prototype('array') - ->useAttributeAsKey('locale') - ->prototype('array') - ->children() - ->scalarNode('title')->isRequired()->end() - ->scalarNode('path')->isRequired()->end() - ->end() - ->end() - ->end() - ->end() - ->arrayNode('pipou') - ->useAttributeAsKey('name') - ->prototype('array') - ->prototype('array') - ->children() - ->scalarNode('didou') - ->end() - ->end() - ->end() - ->end() - ->end() - ->end() - ; - - return $treeBuilder; - } -} diff --git a/lib/symfony/config/Tests/Fixtures/Resource/.hiddenFile b/lib/symfony/config/Tests/Fixtures/Resource/.hiddenFile deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/symfony/config/Tests/Fixtures/Resource/ConditionalClass.php b/lib/symfony/config/Tests/Fixtures/Resource/ConditionalClass.php deleted file mode 100644 index 2ba48c5b0..000000000 --- a/lib/symfony/config/Tests/Fixtures/Resource/ConditionalClass.php +++ /dev/null @@ -1,9 +0,0 @@ - -]> - diff --git a/lib/symfony/config/Tests/Fixtures/Util/invalid.xml b/lib/symfony/config/Tests/Fixtures/Util/invalid.xml deleted file mode 100644 index a07af9fd8..000000000 --- a/lib/symfony/config/Tests/Fixtures/Util/invalid.xml +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/lib/symfony/config/Tests/Fixtures/Util/invalid_schema.xml b/lib/symfony/config/Tests/Fixtures/Util/invalid_schema.xml deleted file mode 100644 index e2725a2c2..000000000 --- a/lib/symfony/config/Tests/Fixtures/Util/invalid_schema.xml +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/lib/symfony/config/Tests/Fixtures/Util/schema.xsd b/lib/symfony/config/Tests/Fixtures/Util/schema.xsd deleted file mode 100644 index e56820f69..000000000 --- a/lib/symfony/config/Tests/Fixtures/Util/schema.xsd +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - diff --git a/lib/symfony/config/Tests/Fixtures/Util/valid.xml b/lib/symfony/config/Tests/Fixtures/Util/valid.xml deleted file mode 100644 index a96bb3826..000000000 --- a/lib/symfony/config/Tests/Fixtures/Util/valid.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/lib/symfony/config/Tests/Fixtures/foo.xml b/lib/symfony/config/Tests/Fixtures/foo.xml deleted file mode 100644 index e69de29bb..000000000 diff --git a/lib/symfony/config/Tests/Loader/DelegatingLoaderTest.php b/lib/symfony/config/Tests/Loader/DelegatingLoaderTest.php deleted file mode 100644 index 38ae6ff7b..000000000 --- a/lib/symfony/config/Tests/Loader/DelegatingLoaderTest.php +++ /dev/null @@ -1,69 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Loader; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Loader\DelegatingLoader; -use Symfony\Component\Config\Loader\LoaderResolver; - -class DelegatingLoaderTest extends TestCase -{ - public function testConstructor() - { - new DelegatingLoader($resolver = new LoaderResolver()); - $this->assertTrue(true, '__construct() takes a loader resolver as its first argument'); - } - - public function testGetSetResolver() - { - $resolver = new LoaderResolver(); - $loader = new DelegatingLoader($resolver); - $this->assertSame($resolver, $loader->getResolver(), '->getResolver() gets the resolver loader'); - $loader->setResolver($resolver = new LoaderResolver()); - $this->assertSame($resolver, $loader->getResolver(), '->setResolver() sets the resolver loader'); - } - - public function testSupports() - { - $loader1 = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderInterface')->getMock(); - $loader1->expects($this->once())->method('supports')->willReturn(true); - $loader = new DelegatingLoader(new LoaderResolver([$loader1])); - $this->assertTrue($loader->supports('foo.xml'), '->supports() returns true if the resource is loadable'); - - $loader1 = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderInterface')->getMock(); - $loader1->expects($this->once())->method('supports')->willReturn(false); - $loader = new DelegatingLoader(new LoaderResolver([$loader1])); - $this->assertFalse($loader->supports('foo.foo'), '->supports() returns false if the resource is not loadable'); - } - - public function testLoad() - { - $loader = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderInterface')->getMock(); - $loader->expects($this->once())->method('supports')->willReturn(true); - $loader->expects($this->once())->method('load'); - $resolver = new LoaderResolver([$loader]); - $loader = new DelegatingLoader($resolver); - - $loader->load('foo'); - } - - public function testLoadThrowsAnExceptionIfTheResourceCannotBeLoaded() - { - $this->expectException('Symfony\Component\Config\Exception\FileLoaderLoadException'); - $loader = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderInterface')->getMock(); - $loader->expects($this->once())->method('supports')->willReturn(false); - $resolver = new LoaderResolver([$loader]); - $loader = new DelegatingLoader($resolver); - - $loader->load('foo'); - } -} diff --git a/lib/symfony/config/Tests/Loader/FileLoaderTest.php b/lib/symfony/config/Tests/Loader/FileLoaderTest.php deleted file mode 100644 index b59ace46f..000000000 --- a/lib/symfony/config/Tests/Loader/FileLoaderTest.php +++ /dev/null @@ -1,128 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Loader; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\FileLocator; -use Symfony\Component\Config\Loader\FileLoader; -use Symfony\Component\Config\Loader\LoaderResolver; - -class FileLoaderTest extends TestCase -{ - public function testImportWithFileLocatorDelegation() - { - $locatorMock = $this->getMockBuilder('Symfony\Component\Config\FileLocatorInterface')->getMock(); - - $locatorMockForAdditionalLoader = $this->getMockBuilder('Symfony\Component\Config\FileLocatorInterface')->getMock(); - $locatorMockForAdditionalLoader->expects($this->any())->method('locate')->will($this->onConsecutiveCalls( - ['path/to/file1'], // Default - ['path/to/file1', 'path/to/file2'], // First is imported - ['path/to/file1', 'path/to/file2'], // Second is imported - ['path/to/file1'], // Exception - ['path/to/file1', 'path/to/file2'] // Exception - )); - - $fileLoader = new TestFileLoader($locatorMock); - $fileLoader->setSupports(false); - $fileLoader->setCurrentDir('.'); - - $additionalLoader = new TestFileLoader($locatorMockForAdditionalLoader); - $additionalLoader->setCurrentDir('.'); - - $fileLoader->setResolver($loaderResolver = new LoaderResolver([$fileLoader, $additionalLoader])); - - // Default case - $this->assertSame('path/to/file1', $fileLoader->import('my_resource')); - - // Check first file is imported if not already loading - $this->assertSame('path/to/file1', $fileLoader->import('my_resource')); - - // Check second file is imported if first is already loading - $fileLoader->addLoading('path/to/file1'); - $this->assertSame('path/to/file2', $fileLoader->import('my_resource')); - - // Check exception throws if first (and only available) file is already loading - try { - $fileLoader->import('my_resource'); - $this->fail('->import() throws a FileLoaderImportCircularReferenceException if the resource is already loading'); - } catch (\Exception $e) { - $this->assertInstanceOf('Symfony\Component\Config\Exception\FileLoaderImportCircularReferenceException', $e, '->import() throws a FileLoaderImportCircularReferenceException if the resource is already loading'); - } - - // Check exception throws if all files are already loading - try { - $fileLoader->addLoading('path/to/file2'); - $fileLoader->import('my_resource'); - $this->fail('->import() throws a FileLoaderImportCircularReferenceException if the resource is already loading'); - } catch (\Exception $e) { - $this->assertInstanceOf('Symfony\Component\Config\Exception\FileLoaderImportCircularReferenceException', $e, '->import() throws a FileLoaderImportCircularReferenceException if the resource is already loading'); - } - } - - public function testImportWithGlobLikeResource() - { - $locatorMock = $this->getMockBuilder('Symfony\Component\Config\FileLocatorInterface')->getMock(); - $loader = new TestFileLoader($locatorMock); - - $this->assertSame('[foo]', $loader->import('[foo]')); - } - - public function testImportWithNoGlobMatch() - { - $locatorMock = $this->getMockBuilder('Symfony\Component\Config\FileLocatorInterface')->getMock(); - $loader = new TestFileLoader($locatorMock); - - $this->assertNull($loader->import('./*.abc')); - } - - public function testImportWithSimpleGlob() - { - $loader = new TestFileLoader(new FileLocator(__DIR__)); - - $this->assertSame(__FILE__, strtr($loader->import('FileLoaderTest.*'), '/', \DIRECTORY_SEPARATOR)); - } -} - -class TestFileLoader extends FileLoader -{ - private $supports = true; - - public function load($resource, $type = null) - { - return $resource; - } - - public function supports($resource, $type = null) - { - return $this->supports; - } - - public function addLoading($resource) - { - self::$loading[$resource] = true; - } - - public function removeLoading($resource) - { - unset(self::$loading[$resource]); - } - - public function clearLoading() - { - self::$loading = []; - } - - public function setSupports($supports) - { - $this->supports = $supports; - } -} diff --git a/lib/symfony/config/Tests/Loader/LoaderResolverTest.php b/lib/symfony/config/Tests/Loader/LoaderResolverTest.php deleted file mode 100644 index aabc2a600..000000000 --- a/lib/symfony/config/Tests/Loader/LoaderResolverTest.php +++ /dev/null @@ -1,47 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Loader; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Loader\LoaderResolver; - -class LoaderResolverTest extends TestCase -{ - public function testConstructor() - { - $resolver = new LoaderResolver([ - $loader = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderInterface')->getMock(), - ]); - - $this->assertEquals([$loader], $resolver->getLoaders(), '__construct() takes an array of loaders as its first argument'); - } - - public function testResolve() - { - $loader = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderInterface')->getMock(); - $resolver = new LoaderResolver([$loader]); - $this->assertFalse($resolver->resolve('foo.foo'), '->resolve() returns false if no loader is able to load the resource'); - - $loader = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderInterface')->getMock(); - $loader->expects($this->once())->method('supports')->willReturn(true); - $resolver = new LoaderResolver([$loader]); - $this->assertEquals($loader, $resolver->resolve(function () {}), '->resolve() returns the loader for the given resource'); - } - - public function testLoaders() - { - $resolver = new LoaderResolver(); - $resolver->addLoader($loader = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderInterface')->getMock()); - - $this->assertEquals([$loader], $resolver->getLoaders(), 'addLoader() adds a loader'); - } -} diff --git a/lib/symfony/config/Tests/Loader/LoaderTest.php b/lib/symfony/config/Tests/Loader/LoaderTest.php deleted file mode 100644 index 35a911ef3..000000000 --- a/lib/symfony/config/Tests/Loader/LoaderTest.php +++ /dev/null @@ -1,116 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Loader; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Loader\Loader; - -class LoaderTest extends TestCase -{ - public function testGetSetResolver() - { - $resolver = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderResolverInterface')->getMock(); - - $loader = new ProjectLoader1(); - $loader->setResolver($resolver); - - $this->assertSame($resolver, $loader->getResolver(), '->setResolver() sets the resolver loader'); - } - - public function testResolve() - { - $resolvedLoader = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderInterface')->getMock(); - - $resolver = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderResolverInterface')->getMock(); - $resolver->expects($this->once()) - ->method('resolve') - ->with('foo.xml') - ->willReturn($resolvedLoader); - - $loader = new ProjectLoader1(); - $loader->setResolver($resolver); - - $this->assertSame($loader, $loader->resolve('foo.foo'), '->resolve() finds a loader'); - $this->assertSame($resolvedLoader, $loader->resolve('foo.xml'), '->resolve() finds a loader'); - } - - public function testResolveWhenResolverCannotFindLoader() - { - $this->expectException('Symfony\Component\Config\Exception\FileLoaderLoadException'); - $resolver = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderResolverInterface')->getMock(); - $resolver->expects($this->once()) - ->method('resolve') - ->with('FOOBAR') - ->willReturn(false); - - $loader = new ProjectLoader1(); - $loader->setResolver($resolver); - - $loader->resolve('FOOBAR'); - } - - public function testImport() - { - $resolvedLoader = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderInterface')->getMock(); - $resolvedLoader->expects($this->once()) - ->method('load') - ->with('foo') - ->willReturn('yes'); - - $resolver = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderResolverInterface')->getMock(); - $resolver->expects($this->once()) - ->method('resolve') - ->with('foo') - ->willReturn($resolvedLoader); - - $loader = new ProjectLoader1(); - $loader->setResolver($resolver); - - $this->assertEquals('yes', $loader->import('foo')); - } - - public function testImportWithType() - { - $resolvedLoader = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderInterface')->getMock(); - $resolvedLoader->expects($this->once()) - ->method('load') - ->with('foo', 'bar') - ->willReturn('yes'); - - $resolver = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderResolverInterface')->getMock(); - $resolver->expects($this->once()) - ->method('resolve') - ->with('foo', 'bar') - ->willReturn($resolvedLoader); - - $loader = new ProjectLoader1(); - $loader->setResolver($resolver); - - $this->assertEquals('yes', $loader->import('foo', 'bar')); - } -} - -class ProjectLoader1 extends Loader -{ - public function load($resource, $type = null) - { - } - - public function supports($resource, $type = null) - { - return \is_string($resource) && 'foo' === pathinfo($resource, PATHINFO_EXTENSION); - } - - public function getType() - { - } -} diff --git a/lib/symfony/config/Tests/Resource/ClassExistenceResourceTest.php b/lib/symfony/config/Tests/Resource/ClassExistenceResourceTest.php deleted file mode 100644 index b7ae81eaa..000000000 --- a/lib/symfony/config/Tests/Resource/ClassExistenceResourceTest.php +++ /dev/null @@ -1,99 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Resource; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Resource\ClassExistenceResource; -use Symfony\Component\Config\Tests\Fixtures\BadParent; -use Symfony\Component\Config\Tests\Fixtures\Resource\ConditionalClass; - -class ClassExistenceResourceTest extends TestCase -{ - public function testToString() - { - $res = new ClassExistenceResource('BarClass'); - $this->assertSame('BarClass', (string) $res); - } - - public function testGetResource() - { - $res = new ClassExistenceResource('BarClass'); - $this->assertSame('BarClass', $res->getResource()); - } - - public function testIsFreshWhenClassDoesNotExist() - { - $res = new ClassExistenceResource('Symfony\Component\Config\Tests\Fixtures\BarClass'); - - $this->assertTrue($res->isFresh(time())); - - eval(<<assertFalse($res->isFresh(time())); - } - - public function testIsFreshWhenClassExists() - { - $res = new ClassExistenceResource('Symfony\Component\Config\Tests\Resource\ClassExistenceResourceTest'); - - $this->assertTrue($res->isFresh(time())); - } - - public function testExistsKo() - { - spl_autoload_register($autoloader = function ($class) use (&$loadedClass) { $loadedClass = $class; }); - - try { - $res = new ClassExistenceResource('MissingFooClass'); - $this->assertTrue($res->isFresh(0)); - - $this->assertSame('MissingFooClass', $loadedClass); - - $loadedClass = 123; - - new ClassExistenceResource('MissingFooClass', false); - - $this->assertSame(123, $loadedClass); - } finally { - spl_autoload_unregister($autoloader); - } - } - - public function testBadParentWithTimestamp() - { - $res = new ClassExistenceResource(BadParent::class, false); - $this->assertTrue($res->isFresh(time())); - } - - public function testBadParentWithNoTimestamp() - { - $this->expectException('ReflectionException'); - $this->expectExceptionMessage('Class "Symfony\Component\Config\Tests\Fixtures\MissingParent" not found while loading "Symfony\Component\Config\Tests\Fixtures\BadParent".'); - - $res = new ClassExistenceResource(BadParent::class, false); - $res->isFresh(0); - } - - public function testConditionalClass() - { - $res = new ClassExistenceResource(ConditionalClass::class, false); - - $this->assertFalse($res->isFresh(0)); - } -} diff --git a/lib/symfony/config/Tests/Resource/ComposerResourceTest.php b/lib/symfony/config/Tests/Resource/ComposerResourceTest.php deleted file mode 100644 index 6857c766d..000000000 --- a/lib/symfony/config/Tests/Resource/ComposerResourceTest.php +++ /dev/null @@ -1,47 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Resource; - -use Composer\Autoload\ClassLoader; -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Resource\ComposerResource; - -class ComposerResourceTest extends TestCase -{ - public function testGetVendor() - { - $res = new ComposerResource(); - - $r = new \ReflectionClass(ClassLoader::class); - $found = false; - - foreach ($res->getVendors() as $vendor) { - if ($vendor && 0 === strpos($r->getFileName(), $vendor)) { - $found = true; - break; - } - } - - $this->assertTrue($found); - } - - public function testSerializeUnserialize() - { - $res = new ComposerResource(); - $ser = unserialize(serialize($res)); - - $this->assertTrue($res->isFresh(0)); - $this->assertTrue($ser->isFresh(0)); - - $this->assertEquals($res, $ser); - } -} diff --git a/lib/symfony/config/Tests/Resource/DirectoryResourceTest.php b/lib/symfony/config/Tests/Resource/DirectoryResourceTest.php deleted file mode 100644 index 40b179010..000000000 --- a/lib/symfony/config/Tests/Resource/DirectoryResourceTest.php +++ /dev/null @@ -1,181 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Resource; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Resource\DirectoryResource; - -class DirectoryResourceTest extends TestCase -{ - protected $directory; - - protected function setUp() - { - $this->directory = sys_get_temp_dir().\DIRECTORY_SEPARATOR.'symfonyDirectoryIterator'; - if (!file_exists($this->directory)) { - mkdir($this->directory); - } - touch($this->directory.'/tmp.xml'); - } - - protected function tearDown() - { - if (!is_dir($this->directory)) { - return; - } - $this->removeDirectory($this->directory); - } - - protected function removeDirectory($directory) - { - $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory), \RecursiveIteratorIterator::CHILD_FIRST); - foreach ($iterator as $path) { - if (preg_match('#[/\\\\]\.\.?$#', $path->__toString())) { - continue; - } - if ($path->isDir()) { - rmdir($path->__toString()); - } else { - unlink($path->__toString()); - } - } - rmdir($directory); - } - - public function testGetResource() - { - $resource = new DirectoryResource($this->directory); - $this->assertSame(realpath($this->directory), $resource->getResource(), '->getResource() returns the path to the resource'); - } - - public function testGetPattern() - { - $resource = new DirectoryResource($this->directory, 'bar'); - $this->assertEquals('bar', $resource->getPattern()); - } - - public function testResourceDoesNotExist() - { - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessageRegExp('/The directory ".*" does not exist./'); - new DirectoryResource('/____foo/foobar'.mt_rand(1, 999999)); - } - - public function testIsFresh() - { - $resource = new DirectoryResource($this->directory); - $this->assertTrue($resource->isFresh(time() + 10), '->isFresh() returns true if the resource has not changed'); - $this->assertFalse($resource->isFresh(time() - 86400), '->isFresh() returns false if the resource has been updated'); - } - - public function testIsFreshForDeletedResources() - { - $resource = new DirectoryResource($this->directory); - $this->removeDirectory($this->directory); - - $this->assertFalse($resource->isFresh(time()), '->isFresh() returns false if the resource does not exist'); - } - - public function testIsFreshUpdateFile() - { - $resource = new DirectoryResource($this->directory); - touch($this->directory.'/tmp.xml', time() + 20); - $this->assertFalse($resource->isFresh(time() + 10), '->isFresh() returns false if an existing file is modified'); - } - - public function testIsFreshNewFile() - { - $resource = new DirectoryResource($this->directory); - touch($this->directory.'/new.xml', time() + 20); - $this->assertFalse($resource->isFresh(time() + 10), '->isFresh() returns false if a new file is added'); - } - - public function testIsFreshNewFileWithDifferentPattern() - { - $resource = new DirectoryResource($this->directory, '/.xml$/'); - touch($this->directory.'/new.yaml', time() + 20); - $this->assertTrue($resource->isFresh(time() + 10), '->isFresh() returns true if a new file with a non-matching pattern is added'); - } - - public function testIsFreshDeleteFile() - { - $resource = new DirectoryResource($this->directory); - $time = time(); - sleep(1); - unlink($this->directory.'/tmp.xml'); - $this->assertFalse($resource->isFresh($time), '->isFresh() returns false if an existing file is removed'); - } - - public function testIsFreshDeleteDirectory() - { - $resource = new DirectoryResource($this->directory); - $this->removeDirectory($this->directory); - $this->assertFalse($resource->isFresh(time()), '->isFresh() returns false if the whole resource is removed'); - } - - public function testIsFreshCreateFileInSubdirectory() - { - $subdirectory = $this->directory.'/subdirectory'; - mkdir($subdirectory); - - $resource = new DirectoryResource($this->directory); - $this->assertTrue($resource->isFresh(time() + 10), '->isFresh() returns true if an unmodified subdirectory exists'); - - touch($subdirectory.'/newfile.xml', time() + 20); - $this->assertFalse($resource->isFresh(time() + 10), '->isFresh() returns false if a new file in a subdirectory is added'); - } - - public function testIsFreshModifySubdirectory() - { - $resource = new DirectoryResource($this->directory); - - $subdirectory = $this->directory.'/subdirectory'; - mkdir($subdirectory); - touch($subdirectory, time() + 20); - - $this->assertFalse($resource->isFresh(time() + 10), '->isFresh() returns false if a subdirectory is modified (e.g. a file gets deleted)'); - } - - public function testFilterRegexListNoMatch() - { - $resource = new DirectoryResource($this->directory, '/\.(foo|xml)$/'); - - touch($this->directory.'/new.bar', time() + 20); - $this->assertTrue($resource->isFresh(time() + 10), '->isFresh() returns true if a new file not matching the filter regex is created'); - } - - public function testFilterRegexListMatch() - { - $resource = new DirectoryResource($this->directory, '/\.(foo|xml)$/'); - - touch($this->directory.'/new.xml', time() + 20); - $this->assertFalse($resource->isFresh(time() + 10), '->isFresh() returns false if an new file matching the filter regex is created '); - } - - public function testSerializeUnserialize() - { - $resource = new DirectoryResource($this->directory, '/\.(foo|xml)$/'); - - unserialize(serialize($resource)); - - $this->assertSame(realpath($this->directory), $resource->getResource()); - $this->assertSame('/\.(foo|xml)$/', $resource->getPattern()); - } - - public function testResourcesWithDifferentPatternsAreDifferent() - { - $resourceA = new DirectoryResource($this->directory, '/.xml$/'); - $resourceB = new DirectoryResource($this->directory, '/.yaml$/'); - - $this->assertCount(2, array_unique([$resourceA, $resourceB])); - } -} diff --git a/lib/symfony/config/Tests/Resource/FileExistenceResourceTest.php b/lib/symfony/config/Tests/Resource/FileExistenceResourceTest.php deleted file mode 100644 index 433f65e82..000000000 --- a/lib/symfony/config/Tests/Resource/FileExistenceResourceTest.php +++ /dev/null @@ -1,71 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Resource; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Resource\FileExistenceResource; - -class FileExistenceResourceTest extends TestCase -{ - protected $resource; - protected $file; - protected $time; - - protected function setUp() - { - $this->file = realpath(sys_get_temp_dir()).'/tmp.xml'; - $this->time = time(); - $this->resource = new FileExistenceResource($this->file); - } - - protected function tearDown() - { - if (file_exists($this->file)) { - unlink($this->file); - } - } - - public function testToString() - { - $this->assertSame($this->file, (string) $this->resource); - } - - public function testGetResource() - { - $this->assertSame($this->file, $this->resource->getResource(), '->getResource() returns the path to the resource'); - } - - public function testIsFreshWithExistingResource() - { - touch($this->file, $this->time); - $serialized = serialize(new FileExistenceResource($this->file)); - - $resource = unserialize($serialized); - $this->assertTrue($resource->isFresh($this->time), '->isFresh() returns true if the resource is still present'); - - unlink($this->file); - $resource = unserialize($serialized); - $this->assertFalse($resource->isFresh($this->time), '->isFresh() returns false if the resource has been deleted'); - } - - public function testIsFreshWithAbsentResource() - { - $serialized = serialize(new FileExistenceResource($this->file)); - - $resource = unserialize($serialized); - $this->assertTrue($resource->isFresh($this->time), '->isFresh() returns true if the resource is still absent'); - - touch($this->file, $this->time); - $resource = unserialize($serialized); - $this->assertFalse($resource->isFresh($this->time), '->isFresh() returns false if the resource has been created'); - } -} diff --git a/lib/symfony/config/Tests/Resource/FileResourceTest.php b/lib/symfony/config/Tests/Resource/FileResourceTest.php deleted file mode 100644 index 968c7e926..000000000 --- a/lib/symfony/config/Tests/Resource/FileResourceTest.php +++ /dev/null @@ -1,83 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Resource; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Resource\FileResource; - -class FileResourceTest extends TestCase -{ - protected $resource; - protected $file; - protected $time; - - protected function setUp() - { - $this->file = sys_get_temp_dir().'/tmp.xml'; - $this->time = time(); - touch($this->file, $this->time); - $this->resource = new FileResource($this->file); - } - - protected function tearDown() - { - if (!file_exists($this->file)) { - return; - } - - unlink($this->file); - } - - public function testGetResource() - { - $this->assertSame(realpath($this->file), $this->resource->getResource(), '->getResource() returns the path to the resource'); - } - - public function testGetResourceWithScheme() - { - $resource = new FileResource('file://'.$this->file); - $this->assertSame('file://'.$this->file, $resource->getResource(), '->getResource() returns the path to the schemed resource'); - } - - public function testToString() - { - $this->assertSame(realpath($this->file), (string) $this->resource); - } - - public function testResourceDoesNotExist() - { - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessageRegExp('/The file ".*" does not exist./'); - new FileResource('/____foo/foobar'.mt_rand(1, 999999)); - } - - public function testIsFresh() - { - $this->assertTrue($this->resource->isFresh($this->time), '->isFresh() returns true if the resource has not changed in same second'); - $this->assertTrue($this->resource->isFresh($this->time + 10), '->isFresh() returns true if the resource has not changed'); - $this->assertFalse($this->resource->isFresh($this->time - 86400), '->isFresh() returns false if the resource has been updated'); - } - - public function testIsFreshForDeletedResources() - { - unlink($this->file); - - $this->assertFalse($this->resource->isFresh($this->time), '->isFresh() returns false if the resource does not exist'); - } - - public function testSerializeUnserialize() - { - unserialize(serialize($this->resource)); - - $this->assertSame(realpath($this->file), $this->resource->getResource()); - } -} diff --git a/lib/symfony/config/Tests/Resource/GlobResourceTest.php b/lib/symfony/config/Tests/Resource/GlobResourceTest.php deleted file mode 100644 index cfbfd2b45..000000000 --- a/lib/symfony/config/Tests/Resource/GlobResourceTest.php +++ /dev/null @@ -1,114 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Resource; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Resource\GlobResource; - -class GlobResourceTest extends TestCase -{ - protected function tearDown() - { - $dir = \dirname(__DIR__).'/Fixtures'; - @rmdir($dir.'/TmpGlob'); - @unlink($dir.'/TmpGlob'); - @unlink($dir.'/Resource/TmpGlob'); - touch($dir.'/Resource/.hiddenFile'); - } - - public function testIterator() - { - $dir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'; - $resource = new GlobResource($dir, '/Resource', true); - - $paths = iterator_to_array($resource); - - $file = $dir.'/Resource'.\DIRECTORY_SEPARATOR.'ConditionalClass.php'; - $this->assertEquals([$file => new \SplFileInfo($file)], $paths); - $this->assertInstanceOf('SplFileInfo', current($paths)); - $this->assertSame($dir, $resource->getPrefix()); - - $resource = new GlobResource($dir, '/**/Resource', true); - - $paths = iterator_to_array($resource); - - $file = $dir.\DIRECTORY_SEPARATOR.'Resource'.\DIRECTORY_SEPARATOR.'ConditionalClass.php'; - $this->assertEquals([$file => $file], $paths); - $this->assertInstanceOf('SplFileInfo', current($paths)); - $this->assertSame($dir, $resource->getPrefix()); - } - - public function testIsFreshNonRecursiveDetectsNewFile() - { - $dir = \dirname(__DIR__).'/Fixtures'; - $resource = new GlobResource($dir, '/*', false); - - $this->assertTrue($resource->isFresh(0)); - - mkdir($dir.'/TmpGlob'); - $this->assertTrue($resource->isFresh(0)); - - rmdir($dir.'/TmpGlob'); - $this->assertTrue($resource->isFresh(0)); - - touch($dir.'/TmpGlob'); - $this->assertFalse($resource->isFresh(0)); - - unlink($dir.'/TmpGlob'); - $this->assertTrue($resource->isFresh(0)); - } - - public function testIsFreshNonRecursiveDetectsRemovedFile() - { - $dir = \dirname(__DIR__).'/Fixtures'; - $resource = new GlobResource($dir, '/*', false); - - touch($dir.'/TmpGlob'); - touch($dir.'/.TmpGlob'); - $this->assertTrue($resource->isFresh(0)); - - unlink($dir.'/.TmpGlob'); - $this->assertTrue($resource->isFresh(0)); - - unlink($dir.'/TmpGlob'); - $this->assertFalse($resource->isFresh(0)); - } - - public function testIsFreshRecursiveDetectsRemovedFile() - { - $dir = \dirname(__DIR__).'/Fixtures'; - $resource = new GlobResource($dir, '/*', true); - - touch($dir.'/Resource/TmpGlob'); - $this->assertTrue($resource->isFresh(0)); - - unlink($dir.'/Resource/TmpGlob'); - $this->assertFalse($resource->isFresh(0)); - - touch($dir.'/Resource/TmpGlob'); - $this->assertTrue($resource->isFresh(0)); - - unlink($dir.'/Resource/.hiddenFile'); - $this->assertTrue($resource->isFresh(0)); - } - - public function testIsFreshRecursiveDetectsNewFile() - { - $dir = \dirname(__DIR__).'/Fixtures'; - $resource = new GlobResource($dir, '/*', true); - - $this->assertTrue($resource->isFresh(0)); - - touch($dir.'/Resource/TmpGlob'); - $this->assertFalse($resource->isFresh(0)); - } -} diff --git a/lib/symfony/config/Tests/Resource/ReflectionClassResourceTest.php b/lib/symfony/config/Tests/Resource/ReflectionClassResourceTest.php deleted file mode 100644 index 74ed6b3ed..000000000 --- a/lib/symfony/config/Tests/Resource/ReflectionClassResourceTest.php +++ /dev/null @@ -1,223 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Resource; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Resource\ReflectionClassResource; -use Symfony\Component\DependencyInjection\ServiceSubscriberInterface; -use Symfony\Component\EventDispatcher\EventSubscriberInterface; - -class ReflectionClassResourceTest extends TestCase -{ - public function testToString() - { - $res = new ReflectionClassResource(new \ReflectionClass('ErrorException')); - - $this->assertSame('reflection.ErrorException', (string) $res); - } - - public function testSerializeUnserialize() - { - $res = new ReflectionClassResource(new \ReflectionClass(DummyInterface::class)); - $ser = unserialize(serialize($res)); - - $this->assertTrue($res->isFresh(0)); - $this->assertTrue($ser->isFresh(0)); - - $this->assertSame((string) $res, (string) $ser); - } - - public function testIsFresh() - { - $res = new ReflectionClassResource(new \ReflectionClass(__CLASS__)); - $mtime = filemtime(__FILE__); - - $this->assertTrue($res->isFresh($mtime), '->isFresh() returns true if the resource has not changed in same second'); - $this->assertTrue($res->isFresh($mtime + 10), '->isFresh() returns true if the resource has not changed'); - $this->assertTrue($res->isFresh($mtime - 86400), '->isFresh() returns true if the resource has not changed'); - } - - public function testIsFreshForDeletedResources() - { - $now = time(); - $tmp = sys_get_temp_dir().'/tmp.php'; - file_put_contents($tmp, 'assertTrue($res->isFresh($now)); - - unlink($tmp); - $this->assertFalse($res->isFresh($now), '->isFresh() returns false if the resource does not exist'); - } - - /** - * @dataProvider provideHashedSignature - */ - public function testHashedSignature($changeExpected, $changedLine, $changedCode, $setContext = null) - { - if ($setContext) { - $setContext(); - } - - $code = <<<'EOPHP' -/* 0*/ -/* 1*/ class %s extends ErrorException -/* 2*/ { -/* 3*/ const FOO = 123; -/* 4*/ -/* 5*/ public $pub = []; -/* 6*/ -/* 7*/ protected $prot; -/* 8*/ -/* 9*/ private $priv; -/*10*/ -/*11*/ public function pub($arg = null) {} -/*12*/ -/*13*/ protected function prot($a = []) {} -/*14*/ -/*15*/ private function priv() {} -/*16*/ -/*17*/ public function ccc($bar = A_CONSTANT_THAT_FOR_SURE_WILL_NEVER_BE_DEFINED_CCCCCC) {} -/*18*/ } -EOPHP; - - static $expectedSignature, $generateSignature; - - if (null === $expectedSignature) { - eval(sprintf($code, $class = 'Foo'.str_replace('.', '_', uniqid('', true)))); - $r = new \ReflectionClass(ReflectionClassResource::class); - $generateSignature = $r->getMethod('generateSignature'); - $generateSignature->setAccessible(true); - $generateSignature = $generateSignature->getClosure($r->newInstanceWithoutConstructor()); - $expectedSignature = implode("\n", iterator_to_array($generateSignature(new \ReflectionClass($class)))); - } - - $code = explode("\n", $code); - if (null !== $changedCode) { - $code[$changedLine] = $changedCode; - } - eval(sprintf(implode("\n", $code), $class = 'Foo'.str_replace('.', '_', uniqid('', true)))); - $signature = implode("\n", iterator_to_array($generateSignature(new \ReflectionClass($class)))); - - if ($changeExpected) { - $this->assertNotSame($expectedSignature, $signature); - } else { - $this->assertSame($expectedSignature, $signature); - } - } - - public function provideHashedSignature() - { - yield [0, 0, "// line change\n\n"]; - yield [1, 0, '/** class docblock */']; - yield [1, 1, 'abstract class %s']; - yield [1, 1, 'final class %s']; - yield [1, 1, 'class %s extends Exception']; - yield [1, 1, 'class %s implements '.DummyInterface::class]; - yield [1, 3, 'const FOO = 456;']; - yield [1, 3, 'const BAR = 123;']; - yield [1, 4, '/** pub docblock */']; - yield [1, 5, 'protected $pub = [];']; - yield [1, 5, 'public $pub = [123];']; - yield [1, 6, '/** prot docblock */']; - yield [1, 7, 'private $prot;']; - yield [0, 8, '/** priv docblock */']; - yield [0, 9, 'private $priv = 123;']; - yield [1, 10, '/** pub docblock */']; - if (\PHP_VERSION_ID >= 50600) { - yield [1, 11, 'public function pub(...$arg) {}']; - } - if (\PHP_VERSION_ID >= 70000) { - yield [1, 11, 'public function pub($arg = null): Foo {}']; - } - yield [0, 11, "public function pub(\$arg = null) {\nreturn 123;\n}"]; - yield [1, 12, '/** prot docblock */']; - yield [1, 13, 'protected function prot($a = [123]) {}']; - yield [0, 14, '/** priv docblock */']; - yield [0, 15, '']; - - if (\PHP_VERSION_ID >= 70400) { - // PHP7.4 typed properties without default value are - // undefined, make sure this doesn't throw an error - yield [1, 5, 'public array $pub;']; - yield [0, 7, 'protected int $prot;']; - yield [0, 9, 'private string $priv;']; - } - - yield [1, 17, 'public function ccc($bar = 187) {}']; - yield [1, 17, 'public function ccc($bar = ANOTHER_ONE_THAT_WILL_NEVER_BE_DEFINED_CCCCCCCCC) {}']; - yield [1, 17, null, static function () { \define('A_CONSTANT_THAT_FOR_SURE_WILL_NEVER_BE_DEFINED_CCCCCC', 'foo'); }]; - } - - public function testEventSubscriber() - { - $res = new ReflectionClassResource(new \ReflectionClass(TestEventSubscriber::class)); - $this->assertTrue($res->isFresh(0)); - - TestEventSubscriber::$subscribedEvents = [123]; - $this->assertFalse($res->isFresh(0)); - - $res = new ReflectionClassResource(new \ReflectionClass(TestEventSubscriber::class)); - $this->assertTrue($res->isFresh(0)); - } - - public function testServiceSubscriber() - { - $res = new ReflectionClassResource(new \ReflectionClass(TestServiceSubscriber::class)); - $this->assertTrue($res->isFresh(0)); - - TestServiceSubscriber::$subscribedServices = [123]; - $this->assertFalse($res->isFresh(0)); - - $res = new ReflectionClassResource(new \ReflectionClass(TestServiceSubscriber::class)); - $this->assertTrue($res->isFresh(0)); - } - - public function testIgnoresObjectsInSignature() - { - $res = new ReflectionClassResource(new \ReflectionClass(TestServiceWithStaticProperty::class)); - $this->assertTrue($res->isFresh(0)); - - TestServiceWithStaticProperty::$initializedObject = new TestServiceWithStaticProperty(); - $this->assertTrue($res->isFresh(0)); - } -} - -interface DummyInterface -{ -} - -class TestEventSubscriber implements EventSubscriberInterface -{ - public static $subscribedEvents = []; - - public static function getSubscribedEvents() - { - return self::$subscribedEvents; - } -} - -class TestServiceSubscriber implements ServiceSubscriberInterface -{ - public static $subscribedServices = []; - - public static function getSubscribedServices() - { - return self::$subscribedServices; - } -} - -class TestServiceWithStaticProperty -{ - public static $initializedObject; -} diff --git a/lib/symfony/config/Tests/Resource/ResourceStub.php b/lib/symfony/config/Tests/Resource/ResourceStub.php deleted file mode 100644 index b01729cbf..000000000 --- a/lib/symfony/config/Tests/Resource/ResourceStub.php +++ /dev/null @@ -1,34 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Resource; - -use Symfony\Component\Config\Resource\SelfCheckingResourceInterface; - -class ResourceStub implements SelfCheckingResourceInterface -{ - private $fresh = true; - - public function setFresh($isFresh) - { - $this->fresh = $isFresh; - } - - public function __toString() - { - return 'stub'; - } - - public function isFresh($timestamp) - { - return $this->fresh; - } -} diff --git a/lib/symfony/config/Tests/ResourceCheckerConfigCacheTest.php b/lib/symfony/config/Tests/ResourceCheckerConfigCacheTest.php deleted file mode 100644 index a2c2eeb81..000000000 --- a/lib/symfony/config/Tests/ResourceCheckerConfigCacheTest.php +++ /dev/null @@ -1,150 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Resource\FileResource; -use Symfony\Component\Config\ResourceCheckerConfigCache; -use Symfony\Component\Config\Tests\Resource\ResourceStub; - -class ResourceCheckerConfigCacheTest extends TestCase -{ - private $cacheFile = null; - - protected function setUp() - { - $this->cacheFile = tempnam(sys_get_temp_dir(), 'config_'); - } - - protected function tearDown() - { - $files = [$this->cacheFile, "{$this->cacheFile}.meta"]; - - foreach ($files as $file) { - if (file_exists($file)) { - unlink($file); - } - } - } - - public function testGetPath() - { - $cache = new ResourceCheckerConfigCache($this->cacheFile); - - $this->assertSame($this->cacheFile, $cache->getPath()); - } - - public function testCacheIsNotFreshIfEmpty() - { - $checker = $this->getMockBuilder('\Symfony\Component\Config\ResourceCheckerInterface')->getMock() - ->expects($this->never())->method('supports'); - - /* If there is nothing in the cache, it needs to be filled (and thus it's not fresh). - It does not matter if you provide checkers or not. */ - - unlink($this->cacheFile); // remove tempnam() side effect - $cache = new ResourceCheckerConfigCache($this->cacheFile, [$checker]); - - $this->assertFalse($cache->isFresh()); - } - - public function testCacheIsFreshIfNoCheckerProvided() - { - /* For example in prod mode, you may choose not to run any checkers - at all. In that case, the cache should always be considered fresh. */ - $cache = new ResourceCheckerConfigCache($this->cacheFile); - $this->assertTrue($cache->isFresh()); - } - - public function testCacheIsFreshIfEmptyCheckerIteratorProvided() - { - $cache = new ResourceCheckerConfigCache($this->cacheFile, new \ArrayIterator([])); - $this->assertTrue($cache->isFresh()); - } - - public function testResourcesWithoutcheckersAreIgnoredAndConsideredFresh() - { - /* As in the previous test, but this time we have a resource. */ - $cache = new ResourceCheckerConfigCache($this->cacheFile); - $cache->write('', [new ResourceStub()]); - - $this->assertTrue($cache->isFresh()); // no (matching) ResourceChecker passed - } - - public function testIsFreshWithchecker() - { - $checker = $this->getMockBuilder('\Symfony\Component\Config\ResourceCheckerInterface')->getMock(); - - $checker->expects($this->once()) - ->method('supports') - ->willReturn(true); - - $checker->expects($this->once()) - ->method('isFresh') - ->willReturn(true); - - $cache = new ResourceCheckerConfigCache($this->cacheFile, [$checker]); - $cache->write('', [new ResourceStub()]); - - $this->assertTrue($cache->isFresh()); - } - - public function testIsNotFreshWithchecker() - { - $checker = $this->getMockBuilder('\Symfony\Component\Config\ResourceCheckerInterface')->getMock(); - - $checker->expects($this->once()) - ->method('supports') - ->willReturn(true); - - $checker->expects($this->once()) - ->method('isFresh') - ->willReturn(false); - - $cache = new ResourceCheckerConfigCache($this->cacheFile, [$checker]); - $cache->write('', [new ResourceStub()]); - - $this->assertFalse($cache->isFresh()); - } - - public function testCacheIsNotFreshWhenUnserializeFails() - { - $checker = $this->getMockBuilder('\Symfony\Component\Config\ResourceCheckerInterface')->getMock(); - $cache = new ResourceCheckerConfigCache($this->cacheFile, [$checker]); - $cache->write('foo', [new FileResource(__FILE__)]); - - $metaFile = "{$this->cacheFile}.meta"; - file_put_contents($metaFile, str_replace('FileResource', 'ClassNotHere', file_get_contents($metaFile))); - - $this->assertFalse($cache->isFresh()); - } - - public function testCacheKeepsContent() - { - $cache = new ResourceCheckerConfigCache($this->cacheFile); - $cache->write('FOOBAR'); - - $this->assertSame('FOOBAR', file_get_contents($cache->getPath())); - } - - public function testCacheIsNotFreshIfNotExistsMetaFile() - { - $checker = $this->getMockBuilder('\Symfony\Component\Config\ResourceCheckerInterface')->getMock(); - $cache = new ResourceCheckerConfigCache($this->cacheFile, [$checker]); - $cache->write('foo', [new FileResource(__FILE__)]); - - $metaFile = "{$this->cacheFile}.meta"; - unlink($metaFile); - - $this->assertFalse($cache->isFresh()); - } -} diff --git a/lib/symfony/config/Tests/Util/XmlUtilsTest.php b/lib/symfony/config/Tests/Util/XmlUtilsTest.php deleted file mode 100644 index 4653c8d7c..000000000 --- a/lib/symfony/config/Tests/Util/XmlUtilsTest.php +++ /dev/null @@ -1,211 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Config\Tests\Util; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Config\Util\XmlUtils; - -class XmlUtilsTest extends TestCase -{ - public function testLoadFile() - { - $fixtures = __DIR__.'/../Fixtures/Util/'; - - try { - XmlUtils::loadFile($fixtures.'invalid.xml'); - $this->fail(); - } catch (\InvalidArgumentException $e) { - $this->assertStringContainsString('ERROR 77', $e->getMessage()); - } - - try { - XmlUtils::loadFile($fixtures.'document_type.xml'); - $this->fail(); - } catch (\InvalidArgumentException $e) { - $this->assertStringContainsString('Document types are not allowed', $e->getMessage()); - } - - try { - XmlUtils::loadFile($fixtures.'invalid_schema.xml', $fixtures.'schema.xsd'); - $this->fail(); - } catch (\InvalidArgumentException $e) { - $this->assertStringContainsString('ERROR 1845', $e->getMessage()); - } - - try { - XmlUtils::loadFile($fixtures.'invalid_schema.xml', 'invalid_callback_or_file'); - $this->fail(); - } catch (\InvalidArgumentException $e) { - $this->assertStringContainsString('XSD file or callable', $e->getMessage()); - } - - $mock = $this->getMockBuilder(__NAMESPACE__.'\Validator')->getMock(); - $mock->expects($this->exactly(2))->method('validate')->will($this->onConsecutiveCalls(false, true)); - - try { - XmlUtils::loadFile($fixtures.'valid.xml', [$mock, 'validate']); - $this->fail(); - } catch (\InvalidArgumentException $e) { - $this->assertRegExp('/The XML file ".+" is not valid\./', $e->getMessage()); - } - - $this->assertInstanceOf('DOMDocument', XmlUtils::loadFile($fixtures.'valid.xml', [$mock, 'validate'])); - $this->assertSame([], libxml_get_errors()); - } - - public function testParseWithInvalidValidatorCallable() - { - $this->expectException('Symfony\Component\Config\Util\Exception\InvalidXmlException'); - $this->expectExceptionMessage('The XML is not valid'); - $fixtures = __DIR__.'/../Fixtures/Util/'; - - $mock = $this->getMockBuilder(__NAMESPACE__.'\Validator')->getMock(); - $mock->expects($this->once())->method('validate')->willReturn(false); - - XmlUtils::parse(file_get_contents($fixtures.'valid.xml'), [$mock, 'validate']); - } - - public function testLoadFileWithInternalErrorsEnabled() - { - $internalErrors = libxml_use_internal_errors(true); - - $this->assertSame([], libxml_get_errors()); - $this->assertInstanceOf('DOMDocument', XmlUtils::loadFile(__DIR__.'/../Fixtures/Util/invalid_schema.xml')); - $this->assertSame([], libxml_get_errors()); - - libxml_clear_errors(); - libxml_use_internal_errors($internalErrors); - } - - /** - * @dataProvider getDataForConvertDomToArray - */ - public function testConvertDomToArray($expected, $xml, $root = false, $checkPrefix = true) - { - $dom = new \DOMDocument(); - $dom->loadXML($root ? $xml : ''.$xml.''); - - $this->assertSame($expected, XmlUtils::convertDomElementToArray($dom->documentElement, $checkPrefix)); - } - - public function getDataForConvertDomToArray() - { - return [ - [null, ''], - ['bar', 'bar'], - [['bar' => 'foobar'], '', true], - [['foo' => null], ''], - [['foo' => 'bar'], 'bar'], - [['foo' => ['foo' => 'bar']], ''], - [['foo' => ['foo' => 0]], '0'], - [['foo' => ['foo' => 'bar']], 'bar'], - [['foo' => ['foo' => 'bar', 'value' => 'text']], 'text'], - [['foo' => ['attr' => 'bar', 'foo' => 'text']], 'text'], - [['foo' => ['bar', 'text']], 'bartext'], - [['foo' => [['foo' => 'bar'], ['foo' => 'text']]], ''], - [['foo' => ['foo' => ['bar', 'text']]], 'text'], - [['foo' => 'bar'], 'bar'], - [['foo' => 'text'], 'text'], - [['foo' => ['bar' => 'bar', 'value' => 'text']], 'text', false, false], - [['attr' => 1, 'b' => 'hello'], 'hello2', true], - ]; - } - - /** - * @dataProvider getDataForPhpize - */ - public function testPhpize($expected, $value) - { - $this->assertSame($expected, XmlUtils::phpize($value)); - } - - public function getDataForPhpize() - { - return [ - ['', ''], - [null, 'null'], - [true, 'true'], - [false, 'false'], - [null, 'Null'], - [true, 'True'], - [false, 'False'], - [0, '0'], - [1, '1'], - [-1, '-1'], - [0777, '0777'], - [255, '0xFF'], - [100.0, '1e2'], - [-120.0, '-1.2E2'], - [-10100.1, '-10100.1'], - ['-10,100.1', '-10,100.1'], - ['1234 5678 9101 1121 3141', '1234 5678 9101 1121 3141'], - ['1,2,3,4', '1,2,3,4'], - ['11,22,33,44', '11,22,33,44'], - ['11,222,333,4', '11,222,333,4'], - ['1,222,333,444', '1,222,333,444'], - ['11,222,333,444', '11,222,333,444'], - ['111,222,333,444', '111,222,333,444'], - ['1111,2222,3333,4444,5555', '1111,2222,3333,4444,5555'], - ['foo', 'foo'], - [6, '0b0110'], - ]; - } - - public function testLoadEmptyXmlFile() - { - $file = __DIR__.'/../Fixtures/foo.xml'; - - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessage(sprintf('File %s does not contain valid XML, it is empty.', $file)); - - XmlUtils::loadFile($file); - } - - // test for issue https://github.com/symfony/symfony/issues/9731 - public function testLoadWrongEmptyXMLWithErrorHandler() - { - $originalDisableEntities = libxml_disable_entity_loader(false); - $errorReporting = error_reporting(-1); - - set_error_handler(function ($errno, $errstr) { - throw new \Exception($errstr, $errno); - }); - - $file = __DIR__.'/../Fixtures/foo.xml'; - try { - try { - XmlUtils::loadFile($file); - $this->fail('An exception should have been raised'); - } catch (\InvalidArgumentException $e) { - $this->assertEquals(sprintf('File %s does not contain valid XML, it is empty.', $file), $e->getMessage()); - } - } finally { - restore_error_handler(); - error_reporting($errorReporting); - } - - $disableEntities = libxml_disable_entity_loader(true); - libxml_disable_entity_loader($disableEntities); - - libxml_disable_entity_loader($originalDisableEntities); - - $this->assertFalse($disableEntities); - - // should not throw an exception - XmlUtils::loadFile(__DIR__.'/../Fixtures/Util/valid.xml', __DIR__.'/../Fixtures/Util/schema.xsd'); - } -} - -interface Validator -{ - public function validate(); -} diff --git a/lib/symfony/console/Tests/ApplicationTest.php b/lib/symfony/console/Tests/ApplicationTest.php deleted file mode 100644 index 1ef2ed3d7..000000000 --- a/lib/symfony/console/Tests/ApplicationTest.php +++ /dev/null @@ -1,1744 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Console\Tests; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Application; -use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\CommandLoader\FactoryCommandLoader; -use Symfony\Component\Console\DependencyInjection\AddConsoleCommandPass; -use Symfony\Component\Console\Event\ConsoleCommandEvent; -use Symfony\Component\Console\Event\ConsoleErrorEvent; -use Symfony\Component\Console\Event\ConsoleExceptionEvent; -use Symfony\Component\Console\Event\ConsoleTerminateEvent; -use Symfony\Component\Console\Exception\CommandNotFoundException; -use Symfony\Component\Console\Helper\FormatterHelper; -use Symfony\Component\Console\Helper\HelperSet; -use Symfony\Component\Console\Input\ArgvInput; -use Symfony\Component\Console\Input\ArrayInput; -use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputDefinition; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Input\InputOption; -use Symfony\Component\Console\Output\NullOutput; -use Symfony\Component\Console\Output\Output; -use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Output\StreamOutput; -use Symfony\Component\Console\Tester\ApplicationTester; -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\EventDispatcher\EventDispatcher; - -class ApplicationTest extends TestCase -{ - protected static $fixturesPath; - - private $colSize; - - protected function setUp() - { - $this->colSize = getenv('COLUMNS'); - } - - protected function tearDown() - { - putenv($this->colSize ? 'COLUMNS='.$this->colSize : 'COLUMNS'); - putenv('SHELL_VERBOSITY'); - unset($_ENV['SHELL_VERBOSITY']); - unset($_SERVER['SHELL_VERBOSITY']); - } - - public static function setUpBeforeClass() - { - self::$fixturesPath = realpath(__DIR__.'/Fixtures/'); - require_once self::$fixturesPath.'/FooCommand.php'; - require_once self::$fixturesPath.'/FooOptCommand.php'; - require_once self::$fixturesPath.'/Foo1Command.php'; - require_once self::$fixturesPath.'/Foo2Command.php'; - require_once self::$fixturesPath.'/Foo3Command.php'; - require_once self::$fixturesPath.'/Foo4Command.php'; - require_once self::$fixturesPath.'/Foo5Command.php'; - require_once self::$fixturesPath.'/FooSameCaseUppercaseCommand.php'; - require_once self::$fixturesPath.'/FooSameCaseLowercaseCommand.php'; - require_once self::$fixturesPath.'/FoobarCommand.php'; - require_once self::$fixturesPath.'/BarBucCommand.php'; - require_once self::$fixturesPath.'/FooSubnamespaced1Command.php'; - require_once self::$fixturesPath.'/FooSubnamespaced2Command.php'; - require_once self::$fixturesPath.'/TestAmbiguousCommandRegistering.php'; - require_once self::$fixturesPath.'/TestAmbiguousCommandRegistering2.php'; - require_once self::$fixturesPath.'/FooHiddenCommand.php'; - } - - protected function normalizeLineBreaks($text) - { - return str_replace(PHP_EOL, "\n", $text); - } - - /** - * Replaces the dynamic placeholders of the command help text with a static version. - * The placeholder %command.full_name% includes the script path that is not predictable - * and can not be tested against. - */ - protected function ensureStaticCommandHelp(Application $application) - { - foreach ($application->all() as $command) { - $command->setHelp(str_replace('%command.full_name%', 'app/console %command.name%', $command->getHelp())); - } - } - - public function testConstructor() - { - $application = new Application('foo', 'bar'); - $this->assertEquals('foo', $application->getName(), '__construct() takes the application name as its first argument'); - $this->assertEquals('bar', $application->getVersion(), '__construct() takes the application version as its second argument'); - $this->assertEquals(['help', 'list'], array_keys($application->all()), '__construct() registered the help and list commands by default'); - } - - public function testSetGetName() - { - $application = new Application(); - $application->setName('foo'); - $this->assertEquals('foo', $application->getName(), '->setName() sets the name of the application'); - } - - public function testSetGetVersion() - { - $application = new Application(); - $application->setVersion('bar'); - $this->assertEquals('bar', $application->getVersion(), '->setVersion() sets the version of the application'); - } - - public function testGetLongVersion() - { - $application = new Application('foo', 'bar'); - $this->assertEquals('foo bar', $application->getLongVersion(), '->getLongVersion() returns the long version of the application'); - } - - public function testHelp() - { - $application = new Application(); - $this->assertStringEqualsFile(self::$fixturesPath.'/application_gethelp.txt', $this->normalizeLineBreaks($application->getHelp()), '->getHelp() returns a help message'); - } - - public function testAll() - { - $application = new Application(); - $commands = $application->all(); - $this->assertInstanceOf('Symfony\\Component\\Console\\Command\\HelpCommand', $commands['help'], '->all() returns the registered commands'); - - $application->add(new \FooCommand()); - $commands = $application->all('foo'); - $this->assertCount(1, $commands, '->all() takes a namespace as its first argument'); - } - - public function testAllWithCommandLoader() - { - $application = new Application(); - $commands = $application->all(); - $this->assertInstanceOf('Symfony\\Component\\Console\\Command\\HelpCommand', $commands['help'], '->all() returns the registered commands'); - - $application->add(new \FooCommand()); - $commands = $application->all('foo'); - $this->assertCount(1, $commands, '->all() takes a namespace as its first argument'); - - $application->setCommandLoader(new FactoryCommandLoader([ - 'foo:bar1' => function () { return new \Foo1Command(); }, - ])); - $commands = $application->all('foo'); - $this->assertCount(2, $commands, '->all() takes a namespace as its first argument'); - $this->assertInstanceOf(\FooCommand::class, $commands['foo:bar'], '->all() returns the registered commands'); - $this->assertInstanceOf(\Foo1Command::class, $commands['foo:bar1'], '->all() returns the registered commands'); - } - - public function testRegister() - { - $application = new Application(); - $command = $application->register('foo'); - $this->assertEquals('foo', $command->getName(), '->register() registers a new command'); - } - - public function testRegisterAmbiguous() - { - $code = function (InputInterface $input, OutputInterface $output) { - $output->writeln('It works!'); - }; - - $application = new Application(); - $application->setAutoExit(false); - $application - ->register('test-foo') - ->setAliases(['test']) - ->setCode($code); - - $application - ->register('test-bar') - ->setCode($code); - - $tester = new ApplicationTester($application); - $tester->run(['test']); - $this->assertStringContainsString('It works!', $tester->getDisplay(true)); - } - - public function testAdd() - { - $application = new Application(); - $application->add($foo = new \FooCommand()); - $commands = $application->all(); - $this->assertEquals($foo, $commands['foo:bar'], '->add() registers a command'); - - $application = new Application(); - $application->addCommands([$foo = new \FooCommand(), $foo1 = new \Foo1Command()]); - $commands = $application->all(); - $this->assertEquals([$foo, $foo1], [$commands['foo:bar'], $commands['foo:bar1']], '->addCommands() registers an array of commands'); - } - - public function testAddCommandWithEmptyConstructor() - { - $this->expectException('LogicException'); - $this->expectExceptionMessage('Command class "Foo5Command" is not correctly initialized. You probably forgot to call the parent constructor.'); - $application = new Application(); - $application->add(new \Foo5Command()); - } - - public function testHasGet() - { - $application = new Application(); - $this->assertTrue($application->has('list'), '->has() returns true if a named command is registered'); - $this->assertFalse($application->has('afoobar'), '->has() returns false if a named command is not registered'); - - $application->add($foo = new \FooCommand()); - $this->assertTrue($application->has('afoobar'), '->has() returns true if an alias is registered'); - $this->assertEquals($foo, $application->get('foo:bar'), '->get() returns a command by name'); - $this->assertEquals($foo, $application->get('afoobar'), '->get() returns a command by alias'); - - $application = new Application(); - $application->add($foo = new \FooCommand()); - // simulate --help - $r = new \ReflectionObject($application); - $p = $r->getProperty('wantHelps'); - $p->setAccessible(true); - $p->setValue($application, true); - $command = $application->get('foo:bar'); - $this->assertInstanceOf('Symfony\Component\Console\Command\HelpCommand', $command, '->get() returns the help command if --help is provided as the input'); - } - - public function testHasGetWithCommandLoader() - { - $application = new Application(); - $this->assertTrue($application->has('list'), '->has() returns true if a named command is registered'); - $this->assertFalse($application->has('afoobar'), '->has() returns false if a named command is not registered'); - - $application->add($foo = new \FooCommand()); - $this->assertTrue($application->has('afoobar'), '->has() returns true if an alias is registered'); - $this->assertEquals($foo, $application->get('foo:bar'), '->get() returns a command by name'); - $this->assertEquals($foo, $application->get('afoobar'), '->get() returns a command by alias'); - - $application->setCommandLoader(new FactoryCommandLoader([ - 'foo:bar1' => function () { return new \Foo1Command(); }, - ])); - - $this->assertTrue($application->has('afoobar'), '->has() returns true if an instance is registered for an alias even with command loader'); - $this->assertEquals($foo, $application->get('foo:bar'), '->get() returns an instance by name even with command loader'); - $this->assertEquals($foo, $application->get('afoobar'), '->get() returns an instance by alias even with command loader'); - $this->assertTrue($application->has('foo:bar1'), '->has() returns true for commands registered in the loader'); - $this->assertInstanceOf(\Foo1Command::class, $foo1 = $application->get('foo:bar1'), '->get() returns a command by name from the command loader'); - $this->assertTrue($application->has('afoobar1'), '->has() returns true for commands registered in the loader'); - $this->assertEquals($foo1, $application->get('afoobar1'), '->get() returns a command by name from the command loader'); - } - - public function testSilentHelp() - { - $application = new Application(); - $application->setAutoExit(false); - $application->setCatchExceptions(false); - - $tester = new ApplicationTester($application); - $tester->run(['-h' => true, '-q' => true], ['decorated' => false]); - - $this->assertEmpty($tester->getDisplay(true)); - } - - public function testGetInvalidCommand() - { - $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); - $this->expectExceptionMessage('The command "foofoo" does not exist.'); - $application = new Application(); - $application->get('foofoo'); - } - - public function testGetNamespaces() - { - $application = new Application(); - $application->add(new \FooCommand()); - $application->add(new \Foo1Command()); - $this->assertEquals(['foo'], $application->getNamespaces(), '->getNamespaces() returns an array of unique used namespaces'); - } - - public function testFindNamespace() - { - $application = new Application(); - $application->add(new \FooCommand()); - $this->assertEquals('foo', $application->findNamespace('foo'), '->findNamespace() returns the given namespace if it exists'); - $this->assertEquals('foo', $application->findNamespace('f'), '->findNamespace() finds a namespace given an abbreviation'); - $application->add(new \Foo2Command()); - $this->assertEquals('foo', $application->findNamespace('foo'), '->findNamespace() returns the given namespace if it exists'); - } - - public function testFindNamespaceWithSubnamespaces() - { - $application = new Application(); - $application->add(new \FooSubnamespaced1Command()); - $application->add(new \FooSubnamespaced2Command()); - $this->assertEquals('foo', $application->findNamespace('foo'), '->findNamespace() returns commands even if the commands are only contained in subnamespaces'); - } - - public function testFindAmbiguousNamespace() - { - $application = new Application(); - $application->add(new \BarBucCommand()); - $application->add(new \FooCommand()); - $application->add(new \Foo2Command()); - - $expectedMsg = "The namespace \"f\" is ambiguous.\nDid you mean one of these?\n foo\n foo1"; - - $this->expectException(CommandNotFoundException::class); - $this->expectExceptionMessage($expectedMsg); - - $application->findNamespace('f'); - } - - public function testFindNonAmbiguous() - { - $application = new Application(); - $application->add(new \TestAmbiguousCommandRegistering()); - $application->add(new \TestAmbiguousCommandRegistering2()); - $this->assertEquals('test-ambiguous', $application->find('test')->getName()); - } - - public function testFindInvalidNamespace() - { - $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); - $this->expectExceptionMessage('There are no commands defined in the "bar" namespace.'); - $application = new Application(); - $application->findNamespace('bar'); - } - - public function testFindUniqueNameButNamespaceName() - { - $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); - $this->expectExceptionMessage('Command "foo1" is not defined'); - $application = new Application(); - $application->add(new \FooCommand()); - $application->add(new \Foo1Command()); - $application->add(new \Foo2Command()); - - $application->find($commandName = 'foo1'); - } - - public function testFind() - { - $application = new Application(); - $application->add(new \FooCommand()); - - $this->assertInstanceOf('FooCommand', $application->find('foo:bar'), '->find() returns a command if its name exists'); - $this->assertInstanceOf('Symfony\Component\Console\Command\HelpCommand', $application->find('h'), '->find() returns a command if its name exists'); - $this->assertInstanceOf('FooCommand', $application->find('f:bar'), '->find() returns a command if the abbreviation for the namespace exists'); - $this->assertInstanceOf('FooCommand', $application->find('f:b'), '->find() returns a command if the abbreviation for the namespace and the command name exist'); - $this->assertInstanceOf('FooCommand', $application->find('a'), '->find() returns a command if the abbreviation exists for an alias'); - } - - public function testFindCaseSensitiveFirst() - { - $application = new Application(); - $application->add(new \FooSameCaseUppercaseCommand()); - $application->add(new \FooSameCaseLowercaseCommand()); - - $this->assertInstanceOf('FooSameCaseUppercaseCommand', $application->find('f:B'), '->find() returns a command if the abbreviation is the correct case'); - $this->assertInstanceOf('FooSameCaseUppercaseCommand', $application->find('f:BAR'), '->find() returns a command if the abbreviation is the correct case'); - $this->assertInstanceOf('FooSameCaseLowercaseCommand', $application->find('f:b'), '->find() returns a command if the abbreviation is the correct case'); - $this->assertInstanceOf('FooSameCaseLowercaseCommand', $application->find('f:bar'), '->find() returns a command if the abbreviation is the correct case'); - } - - public function testFindCaseInsensitiveAsFallback() - { - $application = new Application(); - $application->add(new \FooSameCaseLowercaseCommand()); - - $this->assertInstanceOf('FooSameCaseLowercaseCommand', $application->find('f:b'), '->find() returns a command if the abbreviation is the correct case'); - $this->assertInstanceOf('FooSameCaseLowercaseCommand', $application->find('f:B'), '->find() will fallback to case insensitivity'); - $this->assertInstanceOf('FooSameCaseLowercaseCommand', $application->find('FoO:BaR'), '->find() will fallback to case insensitivity'); - } - - public function testFindCaseInsensitiveSuggestions() - { - $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); - $this->expectExceptionMessage('Command "FoO:BaR" is ambiguous'); - $application = new Application(); - $application->add(new \FooSameCaseLowercaseCommand()); - $application->add(new \FooSameCaseUppercaseCommand()); - - $this->assertInstanceOf('FooSameCaseLowercaseCommand', $application->find('FoO:BaR'), '->find() will find two suggestions with case insensitivity'); - } - - public function testFindWithCommandLoader() - { - $application = new Application(); - $application->setCommandLoader(new FactoryCommandLoader([ - 'foo:bar' => $f = function () { return new \FooCommand(); }, - ])); - - $this->assertInstanceOf('FooCommand', $application->find('foo:bar'), '->find() returns a command if its name exists'); - $this->assertInstanceOf('Symfony\Component\Console\Command\HelpCommand', $application->find('h'), '->find() returns a command if its name exists'); - $this->assertInstanceOf('FooCommand', $application->find('f:bar'), '->find() returns a command if the abbreviation for the namespace exists'); - $this->assertInstanceOf('FooCommand', $application->find('f:b'), '->find() returns a command if the abbreviation for the namespace and the command name exist'); - $this->assertInstanceOf('FooCommand', $application->find('a'), '->find() returns a command if the abbreviation exists for an alias'); - } - - /** - * @dataProvider provideAmbiguousAbbreviations - */ - public function testFindWithAmbiguousAbbreviations($abbreviation, $expectedExceptionMessage) - { - putenv('COLUMNS=120'); - $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); - $this->expectExceptionMessage($expectedExceptionMessage); - - $application = new Application(); - $application->add(new \FooCommand()); - $application->add(new \Foo1Command()); - $application->add(new \Foo2Command()); - - $application->find($abbreviation); - } - - public function provideAmbiguousAbbreviations() - { - return [ - ['f', 'Command "f" is not defined.'], - [ - 'a', - "Command \"a\" is ambiguous.\nDid you mean one of these?\n". - " afoobar The foo:bar command\n". - " afoobar1 The foo:bar1 command\n". - ' afoobar2 The foo1:bar command', - ], - [ - 'foo:b', - "Command \"foo:b\" is ambiguous.\nDid you mean one of these?\n". - " foo:bar The foo:bar command\n". - " foo:bar1 The foo:bar1 command\n". - ' foo1:bar The foo1:bar command', - ], - ]; - } - - public function testFindCommandEqualNamespace() - { - $application = new Application(); - $application->add(new \Foo3Command()); - $application->add(new \Foo4Command()); - - $this->assertInstanceOf('Foo3Command', $application->find('foo3:bar'), '->find() returns the good command even if a namespace has same name'); - $this->assertInstanceOf('Foo4Command', $application->find('foo3:bar:toh'), '->find() returns a command even if its namespace equals another command name'); - } - - public function testFindCommandWithAmbiguousNamespacesButUniqueName() - { - $application = new Application(); - $application->add(new \FooCommand()); - $application->add(new \FoobarCommand()); - - $this->assertInstanceOf('FoobarCommand', $application->find('f:f')); - } - - public function testFindCommandWithMissingNamespace() - { - $application = new Application(); - $application->add(new \Foo4Command()); - - $this->assertInstanceOf('Foo4Command', $application->find('f::t')); - } - - /** - * @dataProvider provideInvalidCommandNamesSingle - */ - public function testFindAlternativeExceptionMessageSingle($name) - { - $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); - $this->expectExceptionMessage('Did you mean this'); - $application = new Application(); - $application->add(new \Foo3Command()); - $application->find($name); - } - - public function provideInvalidCommandNamesSingle() - { - return [ - ['foo3:barr'], - ['fooo3:bar'], - ]; - } - - public function testFindAlternativeExceptionMessageMultiple() - { - putenv('COLUMNS=120'); - $application = new Application(); - $application->add(new \FooCommand()); - $application->add(new \Foo1Command()); - $application->add(new \Foo2Command()); - - // Command + plural - try { - $application->find('foo:baR'); - $this->fail('->find() throws a CommandNotFoundException if command does not exist, with alternatives'); - } catch (\Exception $e) { - $this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e, '->find() throws a CommandNotFoundException if command does not exist, with alternatives'); - $this->assertRegExp('/Did you mean one of these/', $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternatives'); - $this->assertRegExp('/foo1:bar/', $e->getMessage()); - $this->assertRegExp('/foo:bar/', $e->getMessage()); - } - - // Namespace + plural - try { - $application->find('foo2:bar'); - $this->fail('->find() throws a CommandNotFoundException if command does not exist, with alternatives'); - } catch (\Exception $e) { - $this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e, '->find() throws a CommandNotFoundException if command does not exist, with alternatives'); - $this->assertRegExp('/Did you mean one of these/', $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternatives'); - $this->assertRegExp('/foo1/', $e->getMessage()); - } - - $application->add(new \Foo3Command()); - $application->add(new \Foo4Command()); - - // Subnamespace + plural - try { - $application->find('foo3:'); - $this->fail('->find() should throw an Symfony\Component\Console\Exception\CommandNotFoundException if a command is ambiguous because of a subnamespace, with alternatives'); - } catch (\Exception $e) { - $this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e); - $this->assertRegExp('/foo3:bar/', $e->getMessage()); - $this->assertRegExp('/foo3:bar:toh/', $e->getMessage()); - } - } - - public function testFindAlternativeCommands() - { - $application = new Application(); - - $application->add(new \FooCommand()); - $application->add(new \Foo1Command()); - $application->add(new \Foo2Command()); - - try { - $application->find($commandName = 'Unknown command'); - $this->fail('->find() throws a CommandNotFoundException if command does not exist'); - } catch (\Exception $e) { - $this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e, '->find() throws a CommandNotFoundException if command does not exist'); - $this->assertSame([], $e->getAlternatives()); - $this->assertEquals(sprintf('Command "%s" is not defined.', $commandName), $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, without alternatives'); - } - - // Test if "bar1" command throw a "CommandNotFoundException" and does not contain - // "foo:bar" as alternative because "bar1" is too far from "foo:bar" - try { - $application->find($commandName = 'bar1'); - $this->fail('->find() throws a CommandNotFoundException if command does not exist'); - } catch (\Exception $e) { - $this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e, '->find() throws a CommandNotFoundException if command does not exist'); - $this->assertSame(['afoobar1', 'foo:bar1'], $e->getAlternatives()); - $this->assertRegExp(sprintf('/Command "%s" is not defined./', $commandName), $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternatives'); - $this->assertRegExp('/afoobar1/', $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternative : "afoobar1"'); - $this->assertRegExp('/foo:bar1/', $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternative : "foo:bar1"'); - $this->assertNotRegExp('/foo:bar(?>!1)/', $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, without "foo:bar" alternative'); - } - } - - public function testFindAlternativeCommandsWithAnAlias() - { - $fooCommand = new \FooCommand(); - $fooCommand->setAliases(['foo2']); - - $application = new Application(); - $application->add($fooCommand); - - $result = $application->find('foo'); - - $this->assertSame($fooCommand, $result); - } - - public function testFindAlternativeNamespace() - { - $application = new Application(); - - $application->add(new \FooCommand()); - $application->add(new \Foo1Command()); - $application->add(new \Foo2Command()); - $application->add(new \Foo3Command()); - - try { - $application->find('Unknown-namespace:Unknown-command'); - $this->fail('->find() throws a CommandNotFoundException if namespace does not exist'); - } catch (\Exception $e) { - $this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e, '->find() throws a CommandNotFoundException if namespace does not exist'); - $this->assertSame([], $e->getAlternatives()); - $this->assertEquals('There are no commands defined in the "Unknown-namespace" namespace.', $e->getMessage(), '->find() throws a CommandNotFoundException if namespace does not exist, without alternatives'); - } - - try { - $application->find('foo2:command'); - $this->fail('->find() throws a CommandNotFoundException if namespace does not exist'); - } catch (\Exception $e) { - $this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e, '->find() throws a CommandNotFoundException if namespace does not exist'); - $this->assertCount(3, $e->getAlternatives()); - $this->assertContains('foo', $e->getAlternatives()); - $this->assertContains('foo1', $e->getAlternatives()); - $this->assertContains('foo3', $e->getAlternatives()); - $this->assertRegExp('/There are no commands defined in the "foo2" namespace./', $e->getMessage(), '->find() throws a CommandNotFoundException if namespace does not exist, with alternative'); - $this->assertRegExp('/foo/', $e->getMessage(), '->find() throws a CommandNotFoundException if namespace does not exist, with alternative : "foo"'); - $this->assertRegExp('/foo1/', $e->getMessage(), '->find() throws a CommandNotFoundException if namespace does not exist, with alternative : "foo1"'); - $this->assertRegExp('/foo3/', $e->getMessage(), '->find() throws a CommandNotFoundException if namespace does not exist, with alternative : "foo3"'); - } - } - - public function testFindAlternativesOutput() - { - $application = new Application(); - - $application->add(new \FooCommand()); - $application->add(new \Foo1Command()); - $application->add(new \Foo2Command()); - $application->add(new \Foo3Command()); - $application->add(new \FooHiddenCommand()); - - $expectedAlternatives = [ - 'afoobar', - 'afoobar1', - 'afoobar2', - 'foo1:bar', - 'foo3:bar', - 'foo:bar', - 'foo:bar1', - ]; - - try { - $application->find('foo'); - $this->fail('->find() throws a CommandNotFoundException if command is not defined'); - } catch (\Exception $e) { - $this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e, '->find() throws a CommandNotFoundException if command is not defined'); - $this->assertSame($expectedAlternatives, $e->getAlternatives()); - - $this->assertRegExp('/Command "foo" is not defined\..*Did you mean one of these\?.*/Ums', $e->getMessage()); - } - } - - public function testFindNamespaceDoesNotFailOnDeepSimilarNamespaces() - { - $application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(['getNamespaces'])->getMock(); - $application->expects($this->once()) - ->method('getNamespaces') - ->willReturn(['foo:sublong', 'bar:sub']); - - $this->assertEquals('foo:sublong', $application->findNamespace('f:sub')); - } - - public function testFindWithDoubleColonInNameThrowsException() - { - $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); - $this->expectExceptionMessage('Command "foo::bar" is not defined.'); - $application = new Application(); - $application->add(new \FooCommand()); - $application->add(new \Foo4Command()); - $application->find('foo::bar'); - } - - public function testSetCatchExceptions() - { - $application = new Application(); - $application->setAutoExit(false); - putenv('COLUMNS=120'); - $tester = new ApplicationTester($application); - - $application->setCatchExceptions(true); - $this->assertTrue($application->areExceptionsCaught()); - - $tester->run(['command' => 'foo'], ['decorated' => false]); - $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getDisplay(true), '->setCatchExceptions() sets the catch exception flag'); - - $tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]); - $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getErrorOutput(true), '->setCatchExceptions() sets the catch exception flag'); - $this->assertSame('', $tester->getDisplay(true)); - - $application->setCatchExceptions(false); - try { - $tester->run(['command' => 'foo'], ['decorated' => false]); - $this->fail('->setCatchExceptions() sets the catch exception flag'); - } catch (\Exception $e) { - $this->assertInstanceOf('\Exception', $e, '->setCatchExceptions() sets the catch exception flag'); - $this->assertEquals('Command "foo" is not defined.', $e->getMessage(), '->setCatchExceptions() sets the catch exception flag'); - } - } - - public function testAutoExitSetting() - { - $application = new Application(); - $this->assertTrue($application->isAutoExitEnabled()); - - $application->setAutoExit(false); - $this->assertFalse($application->isAutoExitEnabled()); - } - - public function testRenderException() - { - $application = new Application(); - $application->setAutoExit(false); - putenv('COLUMNS=120'); - $tester = new ApplicationTester($application); - - $tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]); - $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exception'); - - $tester->run(['command' => 'foo'], ['decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE, 'capture_stderr_separately' => true]); - $this->assertStringContainsString('Exception trace', $tester->getErrorOutput(), '->renderException() renders a pretty exception with a stack trace when verbosity is verbose'); - - $tester->run(['command' => 'list', '--foo' => true], ['decorated' => false, 'capture_stderr_separately' => true]); - $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception2.txt', $tester->getErrorOutput(true), '->renderException() renders the command synopsis when an exception occurs in the context of a command'); - - $application->add(new \Foo3Command()); - $tester = new ApplicationTester($application); - $tester->run(['command' => 'foo3:bar'], ['decorated' => false, 'capture_stderr_separately' => true]); - $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exceptions with previous exceptions'); - - $tester->run(['command' => 'foo3:bar'], ['decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE]); - $this->assertRegExp('/\[Exception\]\s*First exception/', $tester->getDisplay(), '->renderException() renders a pretty exception without code exception when code exception is default and verbosity is verbose'); - $this->assertRegExp('/\[Exception\]\s*Second exception/', $tester->getDisplay(), '->renderException() renders a pretty exception without code exception when code exception is 0 and verbosity is verbose'); - $this->assertRegExp('/\[Exception \(404\)\]\s*Third exception/', $tester->getDisplay(), '->renderException() renders a pretty exception with code exception when code exception is 404 and verbosity is verbose'); - - $tester->run(['command' => 'foo3:bar'], ['decorated' => true]); - $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3decorated.txt', $tester->getDisplay(true), '->renderException() renders a pretty exceptions with previous exceptions'); - - $tester->run(['command' => 'foo3:bar'], ['decorated' => true, 'capture_stderr_separately' => true]); - $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3decorated.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exceptions with previous exceptions'); - - $application = new Application(); - $application->setAutoExit(false); - putenv('COLUMNS=32'); - $tester = new ApplicationTester($application); - - $tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]); - $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception4.txt', $tester->getErrorOutput(true), '->renderException() wraps messages when they are bigger than the terminal'); - putenv('COLUMNS=120'); - } - - public function testRenderExceptionWithDoubleWidthCharacters() - { - $application = new Application(); - $application->setAutoExit(false); - putenv('COLUMNS=120'); - $application->register('foo')->setCode(function () { - throw new \Exception('エラーメッセージ'); - }); - $tester = new ApplicationTester($application); - - $tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]); - $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_doublewidth1.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exceptions with previous exceptions'); - - $tester->run(['command' => 'foo'], ['decorated' => true, 'capture_stderr_separately' => true]); - $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_doublewidth1decorated.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exceptions with previous exceptions'); - - $application = new Application(); - $application->setAutoExit(false); - putenv('COLUMNS=32'); - $application->register('foo')->setCode(function () { - throw new \Exception('コマンドの実行中にエラーが発生しました。'); - }); - $tester = new ApplicationTester($application); - $tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]); - $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_doublewidth2.txt', $tester->getErrorOutput(true), '->renderException() wraps messages when they are bigger than the terminal'); - putenv('COLUMNS=120'); - } - - public function testRenderExceptionEscapesLines() - { - $application = new Application(); - $application->setAutoExit(false); - putenv('COLUMNS=22'); - $application->register('foo')->setCode(function () { - throw new \Exception('dont break here !'); - }); - $tester = new ApplicationTester($application); - - $tester->run(['command' => 'foo'], ['decorated' => false]); - $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_escapeslines.txt', $tester->getDisplay(true), '->renderException() escapes lines containing formatting'); - putenv('COLUMNS=120'); - } - - public function testRenderExceptionLineBreaks() - { - $application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(['getTerminalWidth'])->getMock(); - $application->setAutoExit(false); - $application->expects($this->any()) - ->method('getTerminalWidth') - ->willReturn(120); - $application->register('foo')->setCode(function () { - throw new \InvalidArgumentException("\n\nline 1 with extra spaces \nline 2\n\nline 4\n"); - }); - $tester = new ApplicationTester($application); - - $tester->run(['command' => 'foo'], ['decorated' => false]); - $this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_linebreaks.txt', $tester->getDisplay(true), '->renderException() keep multiple line breaks'); - } - - public function testRenderExceptionStackTraceContainsRootException() - { - $application = new Application(); - $application->setAutoExit(false); - $application->register('foo')->setCode(function () { - throw new \Exception('Verbose exception'); - }); - - $tester = new ApplicationTester($application); - $tester->run(['command' => 'foo'], ['decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE]); - - $this->assertStringContainsString(sprintf('() at %s:', __FILE__), $tester->getDisplay()); - } - - public function testRun() - { - $application = new Application(); - $application->setAutoExit(false); - $application->setCatchExceptions(false); - $application->add($command = new \Foo1Command()); - $_SERVER['argv'] = ['cli.php', 'foo:bar1']; - - ob_start(); - $application->run(); - ob_end_clean(); - - $this->assertInstanceOf('Symfony\Component\Console\Input\ArgvInput', $command->input, '->run() creates an ArgvInput by default if none is given'); - $this->assertInstanceOf('Symfony\Component\Console\Output\ConsoleOutput', $command->output, '->run() creates a ConsoleOutput by default if none is given'); - - $application = new Application(); - $application->setAutoExit(false); - $application->setCatchExceptions(false); - - $this->ensureStaticCommandHelp($application); - $tester = new ApplicationTester($application); - - $tester->run([], ['decorated' => false]); - $this->assertStringEqualsFile(self::$fixturesPath.'/application_run1.txt', $tester->getDisplay(true), '->run() runs the list command if no argument is passed'); - - $tester->run(['--help' => true], ['decorated' => false]); - $this->assertStringEqualsFile(self::$fixturesPath.'/application_run2.txt', $tester->getDisplay(true), '->run() runs the help command if --help is passed'); - - $tester->run(['-h' => true], ['decorated' => false]); - $this->assertStringEqualsFile(self::$fixturesPath.'/application_run2.txt', $tester->getDisplay(true), '->run() runs the help command if -h is passed'); - - $tester->run(['command' => 'list', '--help' => true], ['decorated' => false]); - $this->assertStringEqualsFile(self::$fixturesPath.'/application_run3.txt', $tester->getDisplay(true), '->run() displays the help if --help is passed'); - - $tester->run(['command' => 'list', '-h' => true], ['decorated' => false]); - $this->assertStringEqualsFile(self::$fixturesPath.'/application_run3.txt', $tester->getDisplay(true), '->run() displays the help if -h is passed'); - - $tester->run(['--ansi' => true]); - $this->assertTrue($tester->getOutput()->isDecorated(), '->run() forces color output if --ansi is passed'); - - $tester->run(['--no-ansi' => true]); - $this->assertFalse($tester->getOutput()->isDecorated(), '->run() forces color output to be disabled if --no-ansi is passed'); - - $tester->run(['--version' => true], ['decorated' => false]); - $this->assertStringEqualsFile(self::$fixturesPath.'/application_run4.txt', $tester->getDisplay(true), '->run() displays the program version if --version is passed'); - - $tester->run(['-V' => true], ['decorated' => false]); - $this->assertStringEqualsFile(self::$fixturesPath.'/application_run4.txt', $tester->getDisplay(true), '->run() displays the program version if -v is passed'); - - $tester->run(['command' => 'list', '--quiet' => true]); - $this->assertSame('', $tester->getDisplay(), '->run() removes all output if --quiet is passed'); - $this->assertFalse($tester->getInput()->isInteractive(), '->run() sets off the interactive mode if --quiet is passed'); - - $tester->run(['command' => 'list', '-q' => true]); - $this->assertSame('', $tester->getDisplay(), '->run() removes all output if -q is passed'); - $this->assertFalse($tester->getInput()->isInteractive(), '->run() sets off the interactive mode if -q is passed'); - - $tester->run(['command' => 'list', '--verbose' => true]); - $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if --verbose is passed'); - - $tester->run(['command' => 'list', '--verbose' => 1]); - $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if --verbose=1 is passed'); - - $tester->run(['command' => 'list', '--verbose' => 2]); - $this->assertSame(Output::VERBOSITY_VERY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to very verbose if --verbose=2 is passed'); - - $tester->run(['command' => 'list', '--verbose' => 3]); - $this->assertSame(Output::VERBOSITY_DEBUG, $tester->getOutput()->getVerbosity(), '->run() sets the output to debug if --verbose=3 is passed'); - - $tester->run(['command' => 'list', '--verbose' => 4]); - $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if unknown --verbose level is passed'); - - $tester->run(['command' => 'list', '-v' => true]); - $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed'); - - $tester->run(['command' => 'list', '-vv' => true]); - $this->assertSame(Output::VERBOSITY_VERY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed'); - - $tester->run(['command' => 'list', '-vvv' => true]); - $this->assertSame(Output::VERBOSITY_DEBUG, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed'); - - $application = new Application(); - $application->setAutoExit(false); - $application->setCatchExceptions(false); - $application->add(new \FooCommand()); - $tester = new ApplicationTester($application); - - $tester->run(['command' => 'foo:bar', '--no-interaction' => true], ['decorated' => false]); - $this->assertSame('called'.PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if --no-interaction is passed'); - - $tester->run(['command' => 'foo:bar', '-n' => true], ['decorated' => false]); - $this->assertSame('called'.PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if -n is passed'); - } - - public function testRunWithGlobalOptionAndNoCommand() - { - $application = new Application(); - $application->setAutoExit(false); - $application->setCatchExceptions(false); - $application->getDefinition()->addOption(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL)); - - $output = new StreamOutput(fopen('php://memory', 'w', false)); - $input = new ArgvInput(['cli.php', '--foo', 'bar']); - - $this->assertSame(0, $application->run($input, $output)); - } - - /** - * Issue #9285. - * - * If the "verbose" option is just before an argument in ArgvInput, - * an argument value should not be treated as verbosity value. - * This test will fail with "Not enough arguments." if broken - */ - public function testVerboseValueNotBreakArguments() - { - $application = new Application(); - $application->setAutoExit(false); - $application->setCatchExceptions(false); - $application->add(new \FooCommand()); - - $output = new StreamOutput(fopen('php://memory', 'w', false)); - - $input = new ArgvInput(['cli.php', '-v', 'foo:bar']); - $application->run($input, $output); - - $this->addToAssertionCount(1); - - $input = new ArgvInput(['cli.php', '--verbose', 'foo:bar']); - $application->run($input, $output); - - $this->addToAssertionCount(1); - } - - public function testRunReturnsIntegerExitCode() - { - $exception = new \Exception('', 4); - - $application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(['doRun'])->getMock(); - $application->setAutoExit(false); - $application->expects($this->once()) - ->method('doRun') - ->willThrowException($exception); - - $exitCode = $application->run(new ArrayInput([]), new NullOutput()); - - $this->assertSame(4, $exitCode, '->run() returns integer exit code extracted from raised exception'); - } - - public function testRunDispatchesIntegerExitCode() - { - $passedRightValue = false; - - // We can assume here that some other test asserts that the event is dispatched at all - $dispatcher = new EventDispatcher(); - $dispatcher->addListener('console.terminate', function (ConsoleTerminateEvent $event) use (&$passedRightValue) { - $passedRightValue = (4 === $event->getExitCode()); - }); - - $application = new Application(); - $application->setDispatcher($dispatcher); - $application->setAutoExit(false); - - $application->register('test')->setCode(function (InputInterface $input, OutputInterface $output) { - throw new \Exception('', 4); - }); - - $tester = new ApplicationTester($application); - $tester->run(['command' => 'test']); - - $this->assertTrue($passedRightValue, '-> exit code 4 was passed in the console.terminate event'); - } - - public function testRunReturnsExitCodeOneForExceptionCodeZero() - { - $exception = new \Exception('', 0); - - $application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(['doRun'])->getMock(); - $application->setAutoExit(false); - $application->expects($this->once()) - ->method('doRun') - ->willThrowException($exception); - - $exitCode = $application->run(new ArrayInput([]), new NullOutput()); - - $this->assertSame(1, $exitCode, '->run() returns exit code 1 when exception code is 0'); - } - - public function testRunDispatchesExitCodeOneForExceptionCodeZero() - { - $passedRightValue = false; - - // We can assume here that some other test asserts that the event is dispatched at all - $dispatcher = new EventDispatcher(); - $dispatcher->addListener('console.terminate', function (ConsoleTerminateEvent $event) use (&$passedRightValue) { - $passedRightValue = (1 === $event->getExitCode()); - }); - - $application = new Application(); - $application->setDispatcher($dispatcher); - $application->setAutoExit(false); - - $application->register('test')->setCode(function (InputInterface $input, OutputInterface $output) { - throw new \Exception(); - }); - - $tester = new ApplicationTester($application); - $tester->run(['command' => 'test']); - - $this->assertTrue($passedRightValue, '-> exit code 1 was passed in the console.terminate event'); - } - - public function testAddingOptionWithDuplicateShortcut() - { - $this->expectException('LogicException'); - $this->expectExceptionMessage('An option with shortcut "e" already exists.'); - $dispatcher = new EventDispatcher(); - $application = new Application(); - $application->setAutoExit(false); - $application->setCatchExceptions(false); - $application->setDispatcher($dispatcher); - - $application->getDefinition()->addOption(new InputOption('--env', '-e', InputOption::VALUE_REQUIRED, 'Environment')); - - $application - ->register('foo') - ->setAliases(['f']) - ->setDefinition([new InputOption('survey', 'e', InputOption::VALUE_REQUIRED, 'My option with a shortcut.')]) - ->setCode(function (InputInterface $input, OutputInterface $output) {}) - ; - - $input = new ArrayInput(['command' => 'foo']); - $output = new NullOutput(); - - $application->run($input, $output); - } - - /** - * @dataProvider getAddingAlreadySetDefinitionElementData - */ - public function testAddingAlreadySetDefinitionElementData($def) - { - $this->expectException('LogicException'); - $application = new Application(); - $application->setAutoExit(false); - $application->setCatchExceptions(false); - $application - ->register('foo') - ->setDefinition([$def]) - ->setCode(function (InputInterface $input, OutputInterface $output) {}) - ; - - $input = new ArrayInput(['command' => 'foo']); - $output = new NullOutput(); - $application->run($input, $output); - } - - public function getAddingAlreadySetDefinitionElementData() - { - return [ - [new InputArgument('command', InputArgument::REQUIRED)], - [new InputOption('quiet', '', InputOption::VALUE_NONE)], - [new InputOption('query', 'q', InputOption::VALUE_NONE)], - ]; - } - - public function testGetDefaultHelperSetReturnsDefaultValues() - { - $application = new Application(); - $application->setAutoExit(false); - $application->setCatchExceptions(false); - - $helperSet = $application->getHelperSet(); - - $this->assertTrue($helperSet->has('formatter')); - } - - public function testAddingSingleHelperSetOverwritesDefaultValues() - { - $application = new Application(); - $application->setAutoExit(false); - $application->setCatchExceptions(false); - - $application->setHelperSet(new HelperSet([new FormatterHelper()])); - - $helperSet = $application->getHelperSet(); - - $this->assertTrue($helperSet->has('formatter')); - - // no other default helper set should be returned - $this->assertFalse($helperSet->has('dialog')); - $this->assertFalse($helperSet->has('progress')); - } - - public function testOverwritingDefaultHelperSetOverwritesDefaultValues() - { - $application = new CustomApplication(); - $application->setAutoExit(false); - $application->setCatchExceptions(false); - - $application->setHelperSet(new HelperSet([new FormatterHelper()])); - - $helperSet = $application->getHelperSet(); - - $this->assertTrue($helperSet->has('formatter')); - - // no other default helper set should be returned - $this->assertFalse($helperSet->has('dialog')); - $this->assertFalse($helperSet->has('progress')); - } - - public function testGetDefaultInputDefinitionReturnsDefaultValues() - { - $application = new Application(); - $application->setAutoExit(false); - $application->setCatchExceptions(false); - - $inputDefinition = $application->getDefinition(); - - $this->assertTrue($inputDefinition->hasArgument('command')); - - $this->assertTrue($inputDefinition->hasOption('help')); - $this->assertTrue($inputDefinition->hasOption('quiet')); - $this->assertTrue($inputDefinition->hasOption('verbose')); - $this->assertTrue($inputDefinition->hasOption('version')); - $this->assertTrue($inputDefinition->hasOption('ansi')); - $this->assertTrue($inputDefinition->hasOption('no-ansi')); - $this->assertTrue($inputDefinition->hasOption('no-interaction')); - } - - public function testOverwritingDefaultInputDefinitionOverwritesDefaultValues() - { - $application = new CustomApplication(); - $application->setAutoExit(false); - $application->setCatchExceptions(false); - - $inputDefinition = $application->getDefinition(); - - // check whether the default arguments and options are not returned any more - $this->assertFalse($inputDefinition->hasArgument('command')); - - $this->assertFalse($inputDefinition->hasOption('help')); - $this->assertFalse($inputDefinition->hasOption('quiet')); - $this->assertFalse($inputDefinition->hasOption('verbose')); - $this->assertFalse($inputDefinition->hasOption('version')); - $this->assertFalse($inputDefinition->hasOption('ansi')); - $this->assertFalse($inputDefinition->hasOption('no-ansi')); - $this->assertFalse($inputDefinition->hasOption('no-interaction')); - - $this->assertTrue($inputDefinition->hasOption('custom')); - } - - public function testSettingCustomInputDefinitionOverwritesDefaultValues() - { - $application = new Application(); - $application->setAutoExit(false); - $application->setCatchExceptions(false); - - $application->setDefinition(new InputDefinition([new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.')])); - - $inputDefinition = $application->getDefinition(); - - // check whether the default arguments and options are not returned any more - $this->assertFalse($inputDefinition->hasArgument('command')); - - $this->assertFalse($inputDefinition->hasOption('help')); - $this->assertFalse($inputDefinition->hasOption('quiet')); - $this->assertFalse($inputDefinition->hasOption('verbose')); - $this->assertFalse($inputDefinition->hasOption('version')); - $this->assertFalse($inputDefinition->hasOption('ansi')); - $this->assertFalse($inputDefinition->hasOption('no-ansi')); - $this->assertFalse($inputDefinition->hasOption('no-interaction')); - - $this->assertTrue($inputDefinition->hasOption('custom')); - } - - public function testRunWithDispatcher() - { - $application = new Application(); - $application->setAutoExit(false); - $application->setDispatcher($this->getDispatcher()); - - $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) { - $output->write('foo.'); - }); - - $tester = new ApplicationTester($application); - $tester->run(['command' => 'foo']); - $this->assertEquals('before.foo.after.'.PHP_EOL, $tester->getDisplay()); - } - - public function testRunWithExceptionAndDispatcher() - { - $this->expectException('LogicException'); - $this->expectExceptionMessage('error'); - $application = new Application(); - $application->setDispatcher($this->getDispatcher()); - $application->setAutoExit(false); - $application->setCatchExceptions(false); - - $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) { - throw new \RuntimeException('foo'); - }); - - $tester = new ApplicationTester($application); - $tester->run(['command' => 'foo']); - } - - public function testRunDispatchesAllEventsWithException() - { - $application = new Application(); - $application->setDispatcher($this->getDispatcher()); - $application->setAutoExit(false); - - $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) { - $output->write('foo.'); - - throw new \RuntimeException('foo'); - }); - - $tester = new ApplicationTester($application); - $tester->run(['command' => 'foo']); - $this->assertStringContainsString('before.foo.error.after.', $tester->getDisplay()); - } - - public function testRunDispatchesAllEventsWithExceptionInListener() - { - $dispatcher = $this->getDispatcher(); - $dispatcher->addListener('console.command', function () { - throw new \RuntimeException('foo'); - }); - - $application = new Application(); - $application->setDispatcher($dispatcher); - $application->setAutoExit(false); - - $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) { - $output->write('foo.'); - }); - - $tester = new ApplicationTester($application); - $tester->run(['command' => 'foo']); - $this->assertStringContainsString('before.error.after.', $tester->getDisplay()); - } - - /** - * @requires PHP 7 - */ - public function testRunWithError() - { - $application = new Application(); - $application->setAutoExit(false); - $application->setCatchExceptions(false); - - $application->register('dym')->setCode(function (InputInterface $input, OutputInterface $output) { - $output->write('dym.'); - - throw new \Error('dymerr'); - }); - - $tester = new ApplicationTester($application); - - try { - $tester->run(['command' => 'dym']); - $this->fail('Error expected.'); - } catch (\Error $e) { - $this->assertSame('dymerr', $e->getMessage()); - } - } - - public function testRunAllowsErrorListenersToSilenceTheException() - { - $dispatcher = $this->getDispatcher(); - $dispatcher->addListener('console.error', function (ConsoleErrorEvent $event) { - $event->getOutput()->write('silenced.'); - - $event->setExitCode(0); - }); - - $dispatcher->addListener('console.command', function () { - throw new \RuntimeException('foo'); - }); - - $application = new Application(); - $application->setDispatcher($dispatcher); - $application->setAutoExit(false); - - $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) { - $output->write('foo.'); - }); - - $tester = new ApplicationTester($application); - $tester->run(['command' => 'foo']); - $this->assertStringContainsString('before.error.silenced.after.', $tester->getDisplay()); - $this->assertEquals(ConsoleCommandEvent::RETURN_CODE_DISABLED, $tester->getStatusCode()); - } - - public function testConsoleErrorEventIsTriggeredOnCommandNotFound() - { - $dispatcher = new EventDispatcher(); - $dispatcher->addListener('console.error', function (ConsoleErrorEvent $event) { - $this->assertNull($event->getCommand()); - $this->assertInstanceOf(CommandNotFoundException::class, $event->getError()); - $event->getOutput()->write('silenced command not found'); - }); - - $application = new Application(); - $application->setDispatcher($dispatcher); - $application->setAutoExit(false); - - $tester = new ApplicationTester($application); - $tester->run(['command' => 'unknown']); - $this->assertStringContainsString('silenced command not found', $tester->getDisplay()); - $this->assertEquals(1, $tester->getStatusCode()); - } - - /** - * @group legacy - * @expectedDeprecation The "ConsoleEvents::EXCEPTION" event is deprecated since Symfony 3.3 and will be removed in 4.0. Listen to the "ConsoleEvents::ERROR" event instead. - */ - public function testLegacyExceptionListenersAreStillTriggered() - { - $dispatcher = $this->getDispatcher(); - $dispatcher->addListener('console.exception', function (ConsoleExceptionEvent $event) { - $event->getOutput()->write('caught.'); - - $event->setException(new \RuntimeException('replaced in caught.')); - }); - - $application = new Application(); - $application->setDispatcher($dispatcher); - $application->setAutoExit(false); - - $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) { - throw new \RuntimeException('foo'); - }); - - $tester = new ApplicationTester($application); - $tester->run(['command' => 'foo']); - $this->assertStringContainsString('before.caught.error.after.', $tester->getDisplay()); - $this->assertStringContainsString('replaced in caught.', $tester->getDisplay()); - } - - /** - * @requires PHP 7 - */ - public function testErrorIsRethrownIfNotHandledByConsoleErrorEvent() - { - $application = new Application(); - $application->setAutoExit(false); - $application->setCatchExceptions(false); - $application->setDispatcher(new EventDispatcher()); - - $application->register('dym')->setCode(function (InputInterface $input, OutputInterface $output) { - new \UnknownClass(); - }); - - $tester = new ApplicationTester($application); - - try { - $tester->run(['command' => 'dym']); - $this->fail('->run() should rethrow PHP errors if not handled via ConsoleErrorEvent.'); - } catch (\Error $e) { - $this->assertSame($e->getMessage(), 'Class \'UnknownClass\' not found'); - } - } - - /** - * @requires PHP 7 - */ - public function testRunWithErrorAndDispatcher() - { - $this->expectException('LogicException'); - $this->expectExceptionMessage('error'); - $application = new Application(); - $application->setDispatcher($this->getDispatcher()); - $application->setAutoExit(false); - $application->setCatchExceptions(false); - - $application->register('dym')->setCode(function (InputInterface $input, OutputInterface $output) { - $output->write('dym.'); - - throw new \Error('dymerr'); - }); - - $tester = new ApplicationTester($application); - $tester->run(['command' => 'dym']); - $this->assertStringContainsString('before.dym.error.after.', $tester->getDisplay(), 'The PHP Error did not dispached events'); - } - - /** - * @requires PHP 7 - */ - public function testRunDispatchesAllEventsWithError() - { - $application = new Application(); - $application->setDispatcher($this->getDispatcher()); - $application->setAutoExit(false); - - $application->register('dym')->setCode(function (InputInterface $input, OutputInterface $output) { - $output->write('dym.'); - - throw new \Error('dymerr'); - }); - - $tester = new ApplicationTester($application); - $tester->run(['command' => 'dym']); - $this->assertStringContainsString('before.dym.error.after.', $tester->getDisplay(), 'The PHP Error did not dispached events'); - } - - /** - * @requires PHP 7 - */ - public function testRunWithErrorFailingStatusCode() - { - $application = new Application(); - $application->setDispatcher($this->getDispatcher()); - $application->setAutoExit(false); - - $application->register('dus')->setCode(function (InputInterface $input, OutputInterface $output) { - $output->write('dus.'); - - throw new \Error('duserr'); - }); - - $tester = new ApplicationTester($application); - $tester->run(['command' => 'dus']); - $this->assertSame(1, $tester->getStatusCode(), 'Status code should be 1'); - } - - public function testRunWithDispatcherSkippingCommand() - { - $application = new Application(); - $application->setDispatcher($this->getDispatcher(true)); - $application->setAutoExit(false); - - $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) { - $output->write('foo.'); - }); - - $tester = new ApplicationTester($application); - $exitCode = $tester->run(['command' => 'foo']); - $this->assertStringContainsString('before.after.', $tester->getDisplay()); - $this->assertEquals(ConsoleCommandEvent::RETURN_CODE_DISABLED, $exitCode); - } - - public function testRunWithDispatcherAccessingInputOptions() - { - $noInteractionValue = null; - $quietValue = null; - - $dispatcher = $this->getDispatcher(); - $dispatcher->addListener('console.command', function (ConsoleCommandEvent $event) use (&$noInteractionValue, &$quietValue) { - $input = $event->getInput(); - - $noInteractionValue = $input->getOption('no-interaction'); - $quietValue = $input->getOption('quiet'); - }); - - $application = new Application(); - $application->setDispatcher($dispatcher); - $application->setAutoExit(false); - - $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) { - $output->write('foo.'); - }); - - $tester = new ApplicationTester($application); - $tester->run(['command' => 'foo', '--no-interaction' => true]); - - $this->assertTrue($noInteractionValue); - $this->assertFalse($quietValue); - } - - public function testRunWithDispatcherAddingInputOptions() - { - $extraValue = null; - - $dispatcher = $this->getDispatcher(); - $dispatcher->addListener('console.command', function (ConsoleCommandEvent $event) use (&$extraValue) { - $definition = $event->getCommand()->getDefinition(); - $input = $event->getInput(); - - $definition->addOption(new InputOption('extra', null, InputOption::VALUE_REQUIRED)); - $input->bind($definition); - - $extraValue = $input->getOption('extra'); - }); - - $application = new Application(); - $application->setDispatcher($dispatcher); - $application->setAutoExit(false); - - $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) { - $output->write('foo.'); - }); - - $tester = new ApplicationTester($application); - $tester->run(['command' => 'foo', '--extra' => 'some test value']); - - $this->assertEquals('some test value', $extraValue); - } - - /** - * @group legacy - */ - public function testTerminalDimensions() - { - $application = new Application(); - $originalDimensions = $application->getTerminalDimensions(); - $this->assertCount(2, $originalDimensions); - - $width = 80; - if ($originalDimensions[0] == $width) { - $width = 100; - } - - $application->setTerminalDimensions($width, 80); - $this->assertSame([$width, 80], $application->getTerminalDimensions()); - } - - public function testSetRunCustomDefaultCommand() - { - $command = new \FooCommand(); - - $application = new Application(); - $application->setAutoExit(false); - $application->add($command); - $application->setDefaultCommand($command->getName()); - - $tester = new ApplicationTester($application); - $tester->run([], ['interactive' => false]); - $this->assertEquals('called'.PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command'); - - $application = new CustomDefaultCommandApplication(); - $application->setAutoExit(false); - - $tester = new ApplicationTester($application); - $tester->run([], ['interactive' => false]); - - $this->assertEquals('called'.PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command'); - } - - public function testSetRunCustomDefaultCommandWithOption() - { - $command = new \FooOptCommand(); - - $application = new Application(); - $application->setAutoExit(false); - $application->add($command); - $application->setDefaultCommand($command->getName()); - - $tester = new ApplicationTester($application); - $tester->run(['--fooopt' => 'opt'], ['interactive' => false]); - - $this->assertEquals('called'.PHP_EOL.'opt'.PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command'); - } - - public function testSetRunCustomSingleCommand() - { - $command = new \FooCommand(); - - $application = new Application(); - $application->setAutoExit(false); - $application->add($command); - $application->setDefaultCommand($command->getName(), true); - - $tester = new ApplicationTester($application); - - $tester->run([]); - $this->assertStringContainsString('called', $tester->getDisplay()); - - $tester->run(['--help' => true]); - $this->assertStringContainsString('The foo:bar command', $tester->getDisplay()); - } - - public function testRunLazyCommandService() - { - $container = new ContainerBuilder(); - $container->addCompilerPass(new AddConsoleCommandPass()); - $container - ->register('lazy-command', LazyCommand::class) - ->addTag('console.command', ['command' => 'lazy:command']) - ->addTag('console.command', ['command' => 'lazy:alias']) - ->addTag('console.command', ['command' => 'lazy:alias2']); - $container->compile(); - - $application = new Application(); - $application->setCommandLoader($container->get('console.command_loader')); - $application->setAutoExit(false); - - $tester = new ApplicationTester($application); - - $tester->run(['command' => 'lazy:command']); - $this->assertSame("lazy-command called\n", $tester->getDisplay(true)); - - $tester->run(['command' => 'lazy:alias']); - $this->assertSame("lazy-command called\n", $tester->getDisplay(true)); - - $tester->run(['command' => 'lazy:alias2']); - $this->assertSame("lazy-command called\n", $tester->getDisplay(true)); - - $command = $application->get('lazy:command'); - $this->assertSame(['lazy:alias', 'lazy:alias2'], $command->getAliases()); - } - - public function testGetDisabledLazyCommand() - { - $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); - $application = new Application(); - $application->setCommandLoader(new FactoryCommandLoader(['disabled' => function () { return new DisabledCommand(); }])); - $application->get('disabled'); - } - - public function testHasReturnsFalseForDisabledLazyCommand() - { - $application = new Application(); - $application->setCommandLoader(new FactoryCommandLoader(['disabled' => function () { return new DisabledCommand(); }])); - $this->assertFalse($application->has('disabled')); - } - - public function testAllExcludesDisabledLazyCommand() - { - $application = new Application(); - $application->setCommandLoader(new FactoryCommandLoader(['disabled' => function () { return new DisabledCommand(); }])); - $this->assertArrayNotHasKey('disabled', $application->all()); - } - - protected function getDispatcher($skipCommand = false) - { - $dispatcher = new EventDispatcher(); - $dispatcher->addListener('console.command', function (ConsoleCommandEvent $event) use ($skipCommand) { - $event->getOutput()->write('before.'); - - if ($skipCommand) { - $event->disableCommand(); - } - }); - $dispatcher->addListener('console.terminate', function (ConsoleTerminateEvent $event) use ($skipCommand) { - $event->getOutput()->writeln('after.'); - - if (!$skipCommand) { - $event->setExitCode(ConsoleCommandEvent::RETURN_CODE_DISABLED); - } - }); - $dispatcher->addListener('console.error', function (ConsoleErrorEvent $event) { - $event->getOutput()->write('error.'); - - $event->setError(new \LogicException('error.', $event->getExitCode(), $event->getError())); - }); - - return $dispatcher; - } - - /** - * @requires PHP 7 - */ - public function testErrorIsRethrownIfNotHandledByConsoleErrorEventWithCatchingEnabled() - { - $application = new Application(); - $application->setAutoExit(false); - $application->setDispatcher(new EventDispatcher()); - - $application->register('dym')->setCode(function (InputInterface $input, OutputInterface $output) { - new \UnknownClass(); - }); - - $tester = new ApplicationTester($application); - - try { - $tester->run(['command' => 'dym']); - $this->fail('->run() should rethrow PHP errors if not handled via ConsoleErrorEvent.'); - } catch (\Error $e) { - $this->assertSame($e->getMessage(), 'Class \'UnknownClass\' not found'); - } - } -} - -class CustomApplication extends Application -{ - /** - * Overwrites the default input definition. - * - * @return InputDefinition An InputDefinition instance - */ - protected function getDefaultInputDefinition() - { - return new InputDefinition([new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.')]); - } - - /** - * Gets the default helper set with the helpers that should always be available. - * - * @return HelperSet A HelperSet instance - */ - protected function getDefaultHelperSet() - { - return new HelperSet([new FormatterHelper()]); - } -} - -class CustomDefaultCommandApplication extends Application -{ - /** - * Overwrites the constructor in order to set a different default command. - */ - public function __construct() - { - parent::__construct(); - - $command = new \FooCommand(); - $this->add($command); - $this->setDefaultCommand($command->getName()); - } -} - -class LazyCommand extends Command -{ - public function execute(InputInterface $input, OutputInterface $output) - { - $output->writeln('lazy-command called'); - } -} - -class DisabledCommand extends Command -{ - public function isEnabled() - { - return false; - } -} diff --git a/lib/symfony/console/Tests/Command/CommandTest.php b/lib/symfony/console/Tests/Command/CommandTest.php deleted file mode 100644 index 207302fdf..000000000 --- a/lib/symfony/console/Tests/Command/CommandTest.php +++ /dev/null @@ -1,430 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Console\Tests\Command; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Application; -use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Helper\FormatterHelper; -use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputDefinition; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Input\InputOption; -use Symfony\Component\Console\Input\StringInput; -use Symfony\Component\Console\Output\NullOutput; -use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Tester\CommandTester; - -class CommandTest extends TestCase -{ - protected static $fixturesPath; - - public static function setUpBeforeClass() - { - self::$fixturesPath = __DIR__.'/../Fixtures/'; - require_once self::$fixturesPath.'/TestCommand.php'; - } - - public function testConstructor() - { - $command = new Command('foo:bar'); - $this->assertEquals('foo:bar', $command->getName(), '__construct() takes the command name as its first argument'); - } - - public function testCommandNameCannotBeEmpty() - { - $this->expectException('LogicException'); - $this->expectExceptionMessage('The command defined in "Symfony\Component\Console\Command\Command" cannot have an empty name.'); - (new Application())->add(new Command()); - } - - public function testSetApplication() - { - $application = new Application(); - $command = new \TestCommand(); - $command->setApplication($application); - $this->assertEquals($application, $command->getApplication(), '->setApplication() sets the current application'); - $this->assertEquals($application->getHelperSet(), $command->getHelperSet()); - } - - public function testSetApplicationNull() - { - $command = new \TestCommand(); - $command->setApplication(null); - $this->assertNull($command->getHelperSet()); - } - - public function testSetGetDefinition() - { - $command = new \TestCommand(); - $ret = $command->setDefinition($definition = new InputDefinition()); - $this->assertEquals($command, $ret, '->setDefinition() implements a fluent interface'); - $this->assertEquals($definition, $command->getDefinition(), '->setDefinition() sets the current InputDefinition instance'); - $command->setDefinition([new InputArgument('foo'), new InputOption('bar')]); - $this->assertTrue($command->getDefinition()->hasArgument('foo'), '->setDefinition() also takes an array of InputArguments and InputOptions as an argument'); - $this->assertTrue($command->getDefinition()->hasOption('bar'), '->setDefinition() also takes an array of InputArguments and InputOptions as an argument'); - $command->setDefinition(new InputDefinition()); - } - - public function testAddArgument() - { - $command = new \TestCommand(); - $ret = $command->addArgument('foo'); - $this->assertEquals($command, $ret, '->addArgument() implements a fluent interface'); - $this->assertTrue($command->getDefinition()->hasArgument('foo'), '->addArgument() adds an argument to the command'); - } - - public function testAddOption() - { - $command = new \TestCommand(); - $ret = $command->addOption('foo'); - $this->assertEquals($command, $ret, '->addOption() implements a fluent interface'); - $this->assertTrue($command->getDefinition()->hasOption('foo'), '->addOption() adds an option to the command'); - } - - public function testSetHidden() - { - $command = new \TestCommand(); - $command->setHidden(true); - $this->assertTrue($command->isHidden()); - } - - public function testGetNamespaceGetNameSetName() - { - $command = new \TestCommand(); - $this->assertEquals('namespace:name', $command->getName(), '->getName() returns the command name'); - $command->setName('foo'); - $this->assertEquals('foo', $command->getName(), '->setName() sets the command name'); - - $ret = $command->setName('foobar:bar'); - $this->assertEquals($command, $ret, '->setName() implements a fluent interface'); - $this->assertEquals('foobar:bar', $command->getName(), '->setName() sets the command name'); - } - - /** - * @dataProvider provideInvalidCommandNames - */ - public function testInvalidCommandNames($name) - { - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessage(sprintf('Command name "%s" is invalid.', $name)); - - $command = new \TestCommand(); - $command->setName($name); - } - - public function provideInvalidCommandNames() - { - return [ - [''], - ['foo:'], - ]; - } - - public function testGetSetDescription() - { - $command = new \TestCommand(); - $this->assertEquals('description', $command->getDescription(), '->getDescription() returns the description'); - $ret = $command->setDescription('description1'); - $this->assertEquals($command, $ret, '->setDescription() implements a fluent interface'); - $this->assertEquals('description1', $command->getDescription(), '->setDescription() sets the description'); - } - - public function testGetSetHelp() - { - $command = new \TestCommand(); - $this->assertEquals('help', $command->getHelp(), '->getHelp() returns the help'); - $ret = $command->setHelp('help1'); - $this->assertEquals($command, $ret, '->setHelp() implements a fluent interface'); - $this->assertEquals('help1', $command->getHelp(), '->setHelp() sets the help'); - $command->setHelp(''); - $this->assertEquals('', $command->getHelp(), '->getHelp() does not fall back to the description'); - } - - public function testGetProcessedHelp() - { - $command = new \TestCommand(); - $command->setHelp('The %command.name% command does... Example: php %command.full_name%.'); - $this->assertStringContainsString('The namespace:name command does...', $command->getProcessedHelp(), '->getProcessedHelp() replaces %command.name% correctly'); - $this->assertStringNotContainsString('%command.full_name%', $command->getProcessedHelp(), '->getProcessedHelp() replaces %command.full_name%'); - - $command = new \TestCommand(); - $command->setHelp(''); - $this->assertStringContainsString('description', $command->getProcessedHelp(), '->getProcessedHelp() falls back to the description'); - - $command = new \TestCommand(); - $command->setHelp('The %command.name% command does... Example: php %command.full_name%.'); - $application = new Application(); - $application->add($command); - $application->setDefaultCommand('namespace:name', true); - $this->assertStringContainsString('The namespace:name command does...', $command->getProcessedHelp(), '->getProcessedHelp() replaces %command.name% correctly in single command applications'); - $this->assertStringNotContainsString('%command.full_name%', $command->getProcessedHelp(), '->getProcessedHelp() replaces %command.full_name% in single command applications'); - } - - public function testGetSetAliases() - { - $command = new \TestCommand(); - $this->assertEquals(['name'], $command->getAliases(), '->getAliases() returns the aliases'); - $ret = $command->setAliases(['name1']); - $this->assertEquals($command, $ret, '->setAliases() implements a fluent interface'); - $this->assertEquals(['name1'], $command->getAliases(), '->setAliases() sets the aliases'); - } - - public function testSetAliasesNull() - { - $command = new \TestCommand(); - $this->expectException('InvalidArgumentException'); - $command->setAliases(null); - } - - public function testGetSynopsis() - { - $command = new \TestCommand(); - $command->addOption('foo'); - $command->addArgument('bar'); - $this->assertEquals('namespace:name [--foo] [--] []', $command->getSynopsis(), '->getSynopsis() returns the synopsis'); - } - - public function testAddGetUsages() - { - $command = new \TestCommand(); - $command->addUsage('foo1'); - $command->addUsage('foo2'); - $this->assertContains('namespace:name foo1', $command->getUsages()); - $this->assertContains('namespace:name foo2', $command->getUsages()); - } - - public function testGetHelper() - { - $application = new Application(); - $command = new \TestCommand(); - $command->setApplication($application); - $formatterHelper = new FormatterHelper(); - $this->assertEquals($formatterHelper->getName(), $command->getHelper('formatter')->getName(), '->getHelper() returns the correct helper'); - } - - public function testGetHelperWithoutHelperSet() - { - $this->expectException('LogicException'); - $this->expectExceptionMessage('Cannot retrieve helper "formatter" because there is no HelperSet defined.'); - $command = new \TestCommand(); - $command->getHelper('formatter'); - } - - public function testMergeApplicationDefinition() - { - $application1 = new Application(); - $application1->getDefinition()->addArguments([new InputArgument('foo')]); - $application1->getDefinition()->addOptions([new InputOption('bar')]); - $command = new \TestCommand(); - $command->setApplication($application1); - $command->setDefinition($definition = new InputDefinition([new InputArgument('bar'), new InputOption('foo')])); - - $r = new \ReflectionObject($command); - $m = $r->getMethod('mergeApplicationDefinition'); - $m->setAccessible(true); - $m->invoke($command); - $this->assertTrue($command->getDefinition()->hasArgument('foo'), '->mergeApplicationDefinition() merges the application arguments and the command arguments'); - $this->assertTrue($command->getDefinition()->hasArgument('bar'), '->mergeApplicationDefinition() merges the application arguments and the command arguments'); - $this->assertTrue($command->getDefinition()->hasOption('foo'), '->mergeApplicationDefinition() merges the application options and the command options'); - $this->assertTrue($command->getDefinition()->hasOption('bar'), '->mergeApplicationDefinition() merges the application options and the command options'); - - $m->invoke($command); - $this->assertEquals(3, $command->getDefinition()->getArgumentCount(), '->mergeApplicationDefinition() does not try to merge twice the application arguments and options'); - } - - public function testMergeApplicationDefinitionWithoutArgsThenWithArgsAddsArgs() - { - $application1 = new Application(); - $application1->getDefinition()->addArguments([new InputArgument('foo')]); - $application1->getDefinition()->addOptions([new InputOption('bar')]); - $command = new \TestCommand(); - $command->setApplication($application1); - $command->setDefinition($definition = new InputDefinition([])); - - $r = new \ReflectionObject($command); - $m = $r->getMethod('mergeApplicationDefinition'); - $m->setAccessible(true); - $m->invoke($command, false); - $this->assertTrue($command->getDefinition()->hasOption('bar'), '->mergeApplicationDefinition(false) merges the application and the command options'); - $this->assertFalse($command->getDefinition()->hasArgument('foo'), '->mergeApplicationDefinition(false) does not merge the application arguments'); - - $m->invoke($command, true); - $this->assertTrue($command->getDefinition()->hasArgument('foo'), '->mergeApplicationDefinition(true) merges the application arguments and the command arguments'); - - $m->invoke($command); - $this->assertEquals(2, $command->getDefinition()->getArgumentCount(), '->mergeApplicationDefinition() does not try to merge twice the application arguments'); - } - - public function testRunInteractive() - { - $tester = new CommandTester(new \TestCommand()); - - $tester->execute([], ['interactive' => true]); - - $this->assertEquals('interact called'.PHP_EOL.'execute called'.PHP_EOL, $tester->getDisplay(), '->run() calls the interact() method if the input is interactive'); - } - - public function testRunNonInteractive() - { - $tester = new CommandTester(new \TestCommand()); - - $tester->execute([], ['interactive' => false]); - - $this->assertEquals('execute called'.PHP_EOL, $tester->getDisplay(), '->run() does not call the interact() method if the input is not interactive'); - } - - public function testExecuteMethodNeedsToBeOverridden() - { - $this->expectException('LogicException'); - $this->expectExceptionMessage('You must override the execute() method in the concrete command class.'); - $command = new Command('foo'); - $command->run(new StringInput(''), new NullOutput()); - } - - public function testRunWithInvalidOption() - { - $this->expectException('Symfony\Component\Console\Exception\InvalidOptionException'); - $this->expectExceptionMessage('The "--bar" option does not exist.'); - $command = new \TestCommand(); - $tester = new CommandTester($command); - $tester->execute(['--bar' => true]); - } - - public function testRunReturnsIntegerExitCode() - { - $command = new \TestCommand(); - $exitCode = $command->run(new StringInput(''), new NullOutput()); - $this->assertSame(0, $exitCode, '->run() returns integer exit code (treats null as 0)'); - - $command = $this->getMockBuilder('TestCommand')->setMethods(['execute'])->getMock(); - $command->expects($this->once()) - ->method('execute') - ->willReturn('2.3'); - $exitCode = $command->run(new StringInput(''), new NullOutput()); - $this->assertSame(2, $exitCode, '->run() returns integer exit code (casts numeric to int)'); - } - - public function testRunWithApplication() - { - $command = new \TestCommand(); - $command->setApplication(new Application()); - $exitCode = $command->run(new StringInput(''), new NullOutput()); - - $this->assertSame(0, $exitCode, '->run() returns an integer exit code'); - } - - public function testRunReturnsAlwaysInteger() - { - $command = new \TestCommand(); - - $this->assertSame(0, $command->run(new StringInput(''), new NullOutput())); - } - - public function testRunWithProcessTitle() - { - $command = new \TestCommand(); - $command->setApplication(new Application()); - $command->setProcessTitle('foo'); - $this->assertSame(0, $command->run(new StringInput(''), new NullOutput())); - if (\function_exists('cli_set_process_title')) { - if (null === @cli_get_process_title() && 'Darwin' === PHP_OS) { - $this->markTestSkipped('Running "cli_get_process_title" as an unprivileged user is not supported on MacOS.'); - } - $this->assertEquals('foo', cli_get_process_title()); - } - } - - public function testSetCode() - { - $command = new \TestCommand(); - $ret = $command->setCode(function (InputInterface $input, OutputInterface $output) { - $output->writeln('from the code...'); - }); - $this->assertEquals($command, $ret, '->setCode() implements a fluent interface'); - $tester = new CommandTester($command); - $tester->execute([]); - $this->assertEquals('interact called'.PHP_EOL.'from the code...'.PHP_EOL, $tester->getDisplay()); - } - - public function getSetCodeBindToClosureTests() - { - return [ - [true, 'not bound to the command'], - [false, 'bound to the command'], - ]; - } - - /** - * @dataProvider getSetCodeBindToClosureTests - */ - public function testSetCodeBindToClosure($previouslyBound, $expected) - { - $code = createClosure(); - if ($previouslyBound) { - $code = $code->bindTo($this); - } - - $command = new \TestCommand(); - $command->setCode($code); - $tester = new CommandTester($command); - $tester->execute([]); - $this->assertEquals('interact called'.PHP_EOL.$expected.PHP_EOL, $tester->getDisplay()); - } - - public function testSetCodeWithStaticClosure() - { - $command = new \TestCommand(); - $command->setCode(self::createClosure()); - $tester = new CommandTester($command); - $tester->execute([]); - - if (\PHP_VERSION_ID < 70000) { - // Cannot bind static closures in PHP 5 - $this->assertEquals('interact called'.PHP_EOL.'not bound'.PHP_EOL, $tester->getDisplay()); - } else { - // Can bind static closures in PHP 7 - $this->assertEquals('interact called'.PHP_EOL.'bound'.PHP_EOL, $tester->getDisplay()); - } - } - - private static function createClosure() - { - return function (InputInterface $input, OutputInterface $output) { - $output->writeln(isset($this) ? 'bound' : 'not bound'); - }; - } - - public function testSetCodeWithNonClosureCallable() - { - $command = new \TestCommand(); - $ret = $command->setCode([$this, 'callableMethodCommand']); - $this->assertEquals($command, $ret, '->setCode() implements a fluent interface'); - $tester = new CommandTester($command); - $tester->execute([]); - $this->assertEquals('interact called'.PHP_EOL.'from the code...'.PHP_EOL, $tester->getDisplay()); - } - - public function callableMethodCommand(InputInterface $input, OutputInterface $output) - { - $output->writeln('from the code...'); - } -} - -// In order to get an unbound closure, we should create it outside a class -// scope. -function createClosure() -{ - return function (InputInterface $input, OutputInterface $output) { - $output->writeln($this instanceof Command ? 'bound to the command' : 'not bound to the command'); - }; -} diff --git a/lib/symfony/console/Tests/Command/HelpCommandTest.php b/lib/symfony/console/Tests/Command/HelpCommandTest.php deleted file mode 100644 index 5b25550a6..000000000 --- a/lib/symfony/console/Tests/Command/HelpCommandTest.php +++ /dev/null @@ -1,71 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Console\Tests\Command; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Application; -use Symfony\Component\Console\Command\HelpCommand; -use Symfony\Component\Console\Command\ListCommand; -use Symfony\Component\Console\Tester\CommandTester; - -class HelpCommandTest extends TestCase -{ - public function testExecuteForCommandAlias() - { - $command = new HelpCommand(); - $command->setApplication(new Application()); - $commandTester = new CommandTester($command); - $commandTester->execute(['command_name' => 'li'], ['decorated' => false]); - $this->assertStringContainsString('list [options] [--] []', $commandTester->getDisplay(), '->execute() returns a text help for the given command alias'); - $this->assertStringContainsString('format=FORMAT', $commandTester->getDisplay(), '->execute() returns a text help for the given command alias'); - $this->assertStringContainsString('raw', $commandTester->getDisplay(), '->execute() returns a text help for the given command alias'); - } - - public function testExecuteForCommand() - { - $command = new HelpCommand(); - $commandTester = new CommandTester($command); - $command->setCommand(new ListCommand()); - $commandTester->execute([], ['decorated' => false]); - $this->assertStringContainsString('list [options] [--] []', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); - $this->assertStringContainsString('format=FORMAT', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); - $this->assertStringContainsString('raw', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); - } - - public function testExecuteForCommandWithXmlOption() - { - $command = new HelpCommand(); - $commandTester = new CommandTester($command); - $command->setCommand(new ListCommand()); - $commandTester->execute(['--format' => 'xml']); - $this->assertStringContainsString('getDisplay(), '->execute() returns an XML help text if --xml is passed'); - } - - public function testExecuteForApplicationCommand() - { - $application = new Application(); - $commandTester = new CommandTester($application->get('help')); - $commandTester->execute(['command_name' => 'list']); - $this->assertStringContainsString('list [options] [--] []', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); - $this->assertStringContainsString('format=FORMAT', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); - $this->assertStringContainsString('raw', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); - } - - public function testExecuteForApplicationCommandWithXmlOption() - { - $application = new Application(); - $commandTester = new CommandTester($application->get('help')); - $commandTester->execute(['command_name' => 'list', '--format' => 'xml']); - $this->assertStringContainsString('list [--raw] [--format FORMAT] [--] [<namespace>]', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); - $this->assertStringContainsString('getDisplay(), '->execute() returns an XML help text if --format=xml is passed'); - } -} diff --git a/lib/symfony/console/Tests/Command/ListCommandTest.php b/lib/symfony/console/Tests/Command/ListCommandTest.php deleted file mode 100644 index 57687d4c6..000000000 --- a/lib/symfony/console/Tests/Command/ListCommandTest.php +++ /dev/null @@ -1,113 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Console\Tests\Command; - -use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Application; -use Symfony\Component\Console\Tester\CommandTester; - -class ListCommandTest extends TestCase -{ - public function testExecuteListsCommands() - { - $application = new Application(); - $commandTester = new CommandTester($command = $application->get('list')); - $commandTester->execute(['command' => $command->getName()], ['decorated' => false]); - - $this->assertRegExp('/help\s{2,}Displays help for a command/', $commandTester->getDisplay(), '->execute() returns a list of available commands'); - } - - public function testExecuteListsCommandsWithXmlOption() - { - $application = new Application(); - $commandTester = new CommandTester($command = $application->get('list')); - $commandTester->execute(['command' => $command->getName(), '--format' => 'xml']); - $this->assertRegExp('/