repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Plugin/Fixtures/plugin-v9/Installer/Plugin.php | tests/Composer/Test/Plugin/Fixtures/plugin-v9/Installer/Plugin.php | <?php
declare(strict_types = 1);
namespace Installer;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
class Plugin implements PluginInterface
{
public $version = 'installer-v9';
public function activate(Composer $composer, IOInterface $io)
{
$io->write('activate v9');
}
public function deactivate(Composer $composer, IOInterface $io)
{
$io->write('deactivate v9');
}
public function uninstall(Composer $composer, IOInterface $io)
{
$io->write('uninstall v9');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Plugin/Fixtures/plugin-v7/Installer/Plugin7.php | tests/Composer/Test/Plugin/Fixtures/plugin-v7/Installer/Plugin7.php | <?php
namespace Installer;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
class Plugin7 implements PluginInterface
{
public function activate(Composer $composer, IOInterface $io)
{
$io->write('activate v7');
}
public function deactivate(Composer $composer, IOInterface $io)
{
$io->write('deactivate v7');
}
public function uninstall(Composer $composer, IOInterface $io)
{
$io->write('uninstall v7');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Plugin/Fixtures/plugin-v2/Installer/Plugin2.php | tests/Composer/Test/Plugin/Fixtures/plugin-v2/Installer/Plugin2.php | <?php
namespace Installer;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
class Plugin2 implements PluginInterface
{
public $version = 'installer-v2';
public function activate(Composer $composer, IOInterface $io)
{
$io->write('activate v2');
}
public function deactivate(Composer $composer, IOInterface $io)
{
$io->write('deactivate v2');
}
public function uninstall(Composer $composer, IOInterface $io)
{
$io->write('uninstall v2');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Plugin/Fixtures/plugin-v1/Installer/Plugin.php | tests/Composer/Test/Plugin/Fixtures/plugin-v1/Installer/Plugin.php | <?php
namespace Installer;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
class Plugin implements PluginInterface
{
public $version = 'installer-v1';
public function activate(Composer $composer, IOInterface $io)
{
$io->write('activate v1');
}
public function deactivate(Composer $composer, IOInterface $io)
{
$io->write('deactivate v1');
}
public function uninstall(Composer $composer, IOInterface $io)
{
$io->write('uninstall v1');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Plugin/Fixtures/plugin-v8/Installer/Plugin8.php | tests/Composer/Test/Plugin/Fixtures/plugin-v8/Installer/Plugin8.php | <?php
namespace Installer;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
use Composer\Plugin\Capable;
class Plugin8 implements PluginInterface, Capable
{
public $version = 'installer-v8';
public function activate(Composer $composer, IOInterface $io)
{
$io->write('activate v8');
}
public function deactivate(Composer $composer, IOInterface $io)
{
$io->write('deactivate v8');
}
public function uninstall(Composer $composer, IOInterface $io)
{
$io->write('uninstall v8');
}
public function getCapabilities()
{
return array(
'Composer\Plugin\Capability\CommandProvider' => 'Installer\CommandProvider',
);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Plugin/Fixtures/plugin-v8/Installer/CommandProvider.php | tests/Composer/Test/Plugin/Fixtures/plugin-v8/Installer/CommandProvider.php | <?php
namespace Installer;
use Composer\Plugin\Capability\CommandProvider as CommandProviderCapability;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Composer\Command\BaseCommand;
class CommandProvider implements CommandProviderCapability
{
public function __construct(array $args)
{
if (!$args['composer'] instanceof \Composer\Composer) {
throw new \RuntimeException('Expected a "composer" key');
}
if (!$args['io'] instanceof \Composer\IO\IOInterface) {
throw new \RuntimeException('Expected an "io" key');
}
if (!$args['plugin'] instanceof Plugin8) {
throw new \RuntimeException('Expected a "plugin" key with my own plugin');
}
}
public function getCommands()
{
return array(new Command);
}
}
class Command extends BaseCommand
{
protected function configure(): void
{
$this->setName('custom-plugin-command');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$output->writeln('Executing');
return 5;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Plugin/Fixtures/plugin-v4/Installer/Plugin1.php | tests/Composer/Test/Plugin/Fixtures/plugin-v4/Installer/Plugin1.php | <?php
namespace Installer;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
class Plugin1 implements PluginInterface
{
public $name = 'plugin1';
public $version = 'installer-v4';
public function activate(Composer $composer, IOInterface $io)
{
$io->write('activate v4-plugin1');
}
public function deactivate(Composer $composer, IOInterface $io)
{
$io->write('deactivate v4-plugin1');
}
public function uninstall(Composer $composer, IOInterface $io)
{
$io->write('uninstall v4-plugin1');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Plugin/Fixtures/plugin-v4/Installer/Plugin2.php | tests/Composer/Test/Plugin/Fixtures/plugin-v4/Installer/Plugin2.php | <?php
namespace Installer;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
class Plugin2 implements PluginInterface
{
public $name = 'plugin2';
public $version = 'installer-v4';
public function activate(Composer $composer, IOInterface $io)
{
$io->write('activate v4-plugin2');
}
public function deactivate(Composer $composer, IOInterface $io)
{
$io->write('deactivate v4-plugin2');
}
public function uninstall(Composer $composer, IOInterface $io)
{
$io->write('uninstall v4-plugin2');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Plugin/Fixtures/plugin-v5/Installer/Plugin5.php | tests/Composer/Test/Plugin/Fixtures/plugin-v5/Installer/Plugin5.php | <?php
namespace Installer;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
class Plugin5 implements PluginInterface
{
public function activate(Composer $composer, IOInterface $io)
{
$io->write('activate v5');
}
public function deactivate(Composer $composer, IOInterface $io)
{
$io->write('deactivate v5');
}
public function uninstall(Composer $composer, IOInterface $io)
{
$io->write('uninstall v5');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Plugin/Fixtures/plugin-v6/Installer/Plugin6.php | tests/Composer/Test/Plugin/Fixtures/plugin-v6/Installer/Plugin6.php | <?php
namespace Installer;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
class Plugin6 implements PluginInterface
{
public function activate(Composer $composer, IOInterface $io)
{
$io->write('activate v6');
}
public function deactivate(Composer $composer, IOInterface $io)
{
$io->write('deactivate v6');
}
public function uninstall(Composer $composer, IOInterface $io)
{
$io->write('uninstall v6');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Plugin/Fixtures/plugin-v3/Installer/Plugin2.php | tests/Composer/Test/Plugin/Fixtures/plugin-v3/Installer/Plugin2.php | <?php
namespace Installer;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Plugin\PluginInterface;
class Plugin2 implements PluginInterface
{
public $version = 'installer-v3';
public function activate(Composer $composer, IOInterface $io)
{
$io->write('activate v3');
}
public function deactivate(Composer $composer, IOInterface $io)
{
$io->write('deactivate v3');
}
public function uninstall(Composer $composer, IOInterface $io)
{
$io->write('uninstall v3');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Plugin/Mock/Capability.php | tests/Composer/Test/Plugin/Mock/Capability.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Plugin\Mock;
class Capability implements \Composer\Plugin\Capability\Capability
{
/**
* @var mixed[]
*/
public $args;
/**
* @param mixed[] $args
*/
public function __construct(array $args)
{
$this->args = $args;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Plugin/Mock/CapablePluginInterface.php | tests/Composer/Test/Plugin/Mock/CapablePluginInterface.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Plugin\Mock;
use Composer\Plugin\Capable;
use Composer\Plugin\PluginInterface;
interface CapablePluginInterface extends PluginInterface, Capable
{
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/EventDispatcher/EventDispatcherTest.php | tests/Composer/Test/EventDispatcher/EventDispatcherTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\EventDispatcher;
use Composer\Autoload\AutoloadGenerator;
use Composer\EventDispatcher\Event;
use Composer\EventDispatcher\EventDispatcher;
use Composer\EventDispatcher\ScriptExecutionException;
use Composer\Installer\InstallerEvents;
use Composer\Config;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\IO\NullIO;
use Composer\Repository\ArrayRepository;
use Composer\Repository\InstalledArrayRepository;
use Composer\Repository\RepositoryManager;
use Composer\Test\Mock\HttpDownloaderMock;
use Composer\Test\Mock\InstallationManagerMock;
use Composer\Test\TestCase;
use Composer\IO\BufferIO;
use Composer\Script\ScriptEvents;
use Composer\Script\Event as ScriptEvent;
use Composer\Util\ProcessExecutor;
use Composer\Util\Platform;
use Symfony\Component\Console\Output\OutputInterface;
class EventDispatcherTest extends TestCase
{
public function tearDown(): void
{
parent::tearDown();
Platform::clearEnv('COMPOSER_SKIP_SCRIPTS');
}
public function testListenerExceptionsAreCaught(): void
{
self::expectException('RuntimeException');
$io = $this->getIOMock(IOInterface::NORMAL);
$dispatcher = $this->getDispatcherStubForListenersTest([
'Composer\Test\EventDispatcher\EventDispatcherTest::call',
], $io);
$io->expects([
['text' => '> Composer\Test\EventDispatcher\EventDispatcherTest::call'],
['text' => 'Script Composer\Test\EventDispatcher\EventDispatcherTest::call handling the post-install-cmd event terminated with an exception'],
], true);
$dispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, false);
}
/**
* @dataProvider provideValidCommands
*/
public function testDispatcherCanExecuteSingleCommandLineScript(string $command): void
{
$process = $this->getProcessExecutorMock();
$process->expects([
$command,
], true);
$dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')
->setConstructorArgs([
$this->createComposerInstance(),
$this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
$process,
])
->onlyMethods(['getListeners'])
->getMock();
$listener = [$command];
$dispatcher->expects($this->atLeastOnce())
->method('getListeners')
->will($this->returnValue($listener));
$dispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, false);
}
/**
* @dataProvider provideDevModes
*/
public function testDispatcherPassDevModeToAutoloadGeneratorForScriptEvents(bool $devMode): void
{
$composer = $this->createComposerInstance();
$generator = $this->getGeneratorMockForDevModePassingTest();
$generator->expects($this->atLeastOnce())
->method('setDevMode')
->with($devMode);
$composer->setAutoloadGenerator($generator);
$package = $this->getMockBuilder('Composer\Package\RootPackageInterface')->getMock();
$package->method('getScripts')->will($this->returnValue(['scriptName' => ['ClassName::testMethod']]));
$composer->setPackage($package);
$composer->setRepositoryManager($this->getRepositoryManagerMockForDevModePassingTest());
$composer->setInstallationManager($this->getMockBuilder('Composer\Installer\InstallationManager')->disableOriginalConstructor()->getMock());
$dispatcher = new EventDispatcher(
$composer,
$this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
$this->getProcessExecutorMock()
);
$event = $this->getMockBuilder('Composer\Script\Event')
->disableOriginalConstructor()
->getMock();
$event->method('getName')->will($this->returnValue('scriptName'));
$event->expects($this->atLeastOnce())
->method('isDevMode')
->will($this->returnValue($devMode));
$dispatcher->dispatch('scriptName', $event);
}
public static function provideDevModes(): array
{
return [
[true],
[false],
];
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Autoload\AutoloadGenerator
*/
private function getGeneratorMockForDevModePassingTest()
{
$generator = $this->getMockBuilder('Composer\Autoload\AutoloadGenerator')
->disableOriginalConstructor()
->onlyMethods([
'buildPackageMap',
'parseAutoloads',
'createLoader',
'setDevMode',
])
->getMock();
$generator
->method('buildPackageMap')
->will($this->returnValue([]));
$generator
->method('parseAutoloads')
->will($this->returnValue(['psr-0' => [], 'psr-4' => [], 'classmap' => [], 'files' => [], 'exclude-from-classmap' => []]));
$generator
->method('createLoader')
->will($this->returnValue($this->getMockBuilder('Composer\Autoload\ClassLoader')->getMock()));
return $generator;
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Repository\RepositoryManager
*/
private function getRepositoryManagerMockForDevModePassingTest()
{
$rm = $this->getMockBuilder('Composer\Repository\RepositoryManager')
->disableOriginalConstructor()
->onlyMethods(['getLocalRepository'])
->getMock();
$repo = $this->getMockBuilder('Composer\Repository\InstalledRepositoryInterface')->getMock();
$repo
->method('getCanonicalPackages')
->will($this->returnValue([]));
$rm
->method('getLocalRepository')
->will($this->returnValue($repo));
return $rm;
}
public function testDispatcherRemoveListener(): void
{
$composer = $this->createComposerInstance();
$composer->setRepositoryManager($this->getRepositoryManagerMockForDevModePassingTest());
$composer->setInstallationManager($this->getMockBuilder('Composer\Installer\InstallationManager')->disableOriginalConstructor()->getMock());
$dispatcher = new EventDispatcher(
$composer,
$io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE),
$this->getProcessExecutorMock()
);
$listener = [$this, 'someMethod'];
$listener2 = [$this, 'someMethod2'];
$listener3 = 'Composer\\Test\\EventDispatcher\\EventDispatcherTest::someMethod';
$dispatcher->addListener('ev1', $listener, 0);
$dispatcher->addListener('ev1', $listener, 1);
$dispatcher->addListener('ev1', $listener2, 1);
$dispatcher->addListener('ev1', $listener3);
$dispatcher->addListener('ev2', $listener3);
$dispatcher->addListener('ev2', $listener);
$dispatcher->dispatch('ev1');
$dispatcher->dispatch('ev2');
$expected = '> ev1: Composer\Test\EventDispatcher\EventDispatcherTest->someMethod'.PHP_EOL
.'> ev1: Composer\Test\EventDispatcher\EventDispatcherTest->someMethod2'.PHP_EOL
.'> ev1: Composer\Test\EventDispatcher\EventDispatcherTest->someMethod'.PHP_EOL
.'> ev1: Composer\Test\EventDispatcher\EventDispatcherTest::someMethod'.PHP_EOL
.'> ev2: Composer\Test\EventDispatcher\EventDispatcherTest::someMethod'.PHP_EOL
.'> ev2: Composer\Test\EventDispatcher\EventDispatcherTest->someMethod'.PHP_EOL;
self::assertEquals($expected, $io->getOutput());
$dispatcher->removeListener($this);
$dispatcher->dispatch('ev1');
$dispatcher->dispatch('ev2');
$expected .= '> ev1: Composer\Test\EventDispatcher\EventDispatcherTest::someMethod'.PHP_EOL
.'> ev2: Composer\Test\EventDispatcher\EventDispatcherTest::someMethod'.PHP_EOL;
self::assertEquals($expected, $io->getOutput());
}
public function testDispatcherCanExecuteCliAndPhpInSameEventScriptStack(): void
{
$process = $this->getProcessExecutorMock();
$process->expects([
'echo -n foo',
'echo -n bar',
], true);
$dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')
->setConstructorArgs([
$this->createComposerInstance(),
$io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE),
$process,
])
->onlyMethods([
'getListeners',
])
->getMock();
$listeners = [
'echo -n foo',
'Composer\\Test\\EventDispatcher\\EventDispatcherTest::someMethod',
'echo -n bar',
];
$dispatcher->expects($this->atLeastOnce())
->method('getListeners')
->will($this->returnValue($listeners));
$dispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, false);
$expected = '> post-install-cmd: echo -n foo'.PHP_EOL.
'> post-install-cmd: Composer\Test\EventDispatcher\EventDispatcherTest::someMethod'.PHP_EOL.
'> post-install-cmd: echo -n bar'.PHP_EOL;
self::assertEquals($expected, $io->getOutput());
}
public function testDispatcherCanPutEnv(): void
{
$dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')
->setConstructorArgs([
$this->createComposerInstance(),
$io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE),
$this->getProcessExecutorMock(),
])
->onlyMethods([
'getListeners',
])
->getMock();
$listeners = [
'@putenv ABC=123',
'Composer\\Test\\EventDispatcher\\EventDispatcherTest::getTestEnv',
];
$dispatcher->expects($this->atLeastOnce())
->method('getListeners')
->will($this->returnValue($listeners));
$dispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, false);
$expected = '> post-install-cmd: @putenv ABC=123'.PHP_EOL.
'> post-install-cmd: Composer\Test\EventDispatcher\EventDispatcherTest::getTestEnv'.PHP_EOL;
self::assertEquals($expected, $io->getOutput());
}
public function testDispatcherAppendsDirBinOnPathForEveryListener(): void
{
$currentDirectoryBkp = Platform::getCwd();
$composerBinDirBkp = Platform::getEnv('COMPOSER_BIN_DIR');
chdir(__DIR__);
Platform::putEnv('COMPOSER_BIN_DIR', __DIR__ . '/vendor/bin');
$dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->setConstructorArgs([
$this->createComposerInstance(),
$io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE),
$this->getProcessExecutorMock(),
])->onlyMethods([
'getListeners',
])->getMock();
$listeners = [
'Composer\\Test\\EventDispatcher\\EventDispatcherTest::createsVendorBinFolderChecksEnvDoesNotContainsBin',
'Composer\\Test\\EventDispatcher\\EventDispatcherTest::createsVendorBinFolderChecksEnvContainsBin',
];
$dispatcher->expects($this->atLeastOnce())->method('getListeners')->will($this->returnValue($listeners));
$dispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, false);
rmdir(__DIR__ . '/vendor/bin');
rmdir(__DIR__ . '/vendor');
chdir($currentDirectoryBkp);
if ($composerBinDirBkp) {
Platform::putEnv('COMPOSER_BIN_DIR', $composerBinDirBkp);
} else {
Platform::clearEnv('COMPOSER_BIN_DIR');
}
}
public function testDispatcherSupportForAdditionalArgs(): void
{
$process = $this->getProcessExecutorMock();
$dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')
->setConstructorArgs([
$this->createComposerInstance(),
$io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE),
$process,
])
->onlyMethods([
'getListeners',
])
->getMock();
$reflMethod = new \ReflectionMethod($dispatcher, 'getPhpExecCommand');
if (PHP_VERSION_ID < 80100) {
$reflMethod->setAccessible(true);
}
$phpCmd = $reflMethod->invoke($dispatcher);
$args = ProcessExecutor::escape('ARG').' '.ProcessExecutor::escape('ARG2').' '.ProcessExecutor::escape('--arg');
$process->expects([
'echo -n foo',
$phpCmd.' foo.php '.$args.' then the rest',
'echo -n bar '.$args,
], true);
$listeners = [
'echo -n foo @no_additional_args',
'@php foo.php @additional_args then the rest',
'echo -n bar',
];
$dispatcher->expects($this->atLeastOnce())
->method('getListeners')
->will($this->returnValue($listeners));
$dispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, false, ['ARG', 'ARG2', '--arg']);
$expected = '> post-install-cmd: echo -n foo'.PHP_EOL.
'> post-install-cmd: @php foo.php '.$args.' then the rest'.PHP_EOL.
'> post-install-cmd: echo -n bar '.$args.PHP_EOL;
self::assertEquals($expected, $io->getOutput());
}
public static function createsVendorBinFolderChecksEnvDoesNotContainsBin(): void
{
mkdir(__DIR__ . '/vendor/bin', 0700, true);
$val = getenv('PATH');
if (!$val) {
$val = getenv('Path');
}
self::assertStringNotContainsString(__DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'bin', $val);
}
public static function createsVendorBinFolderChecksEnvContainsBin(): void
{
$val = getenv('PATH');
if (!$val) {
$val = getenv('Path');
}
self::assertStringContainsString(__DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'bin', $val);
}
public static function getTestEnv(): void
{
$val = getenv('ABC');
if ($val !== '123') {
throw new \Exception('getenv() did not return the expected value. expected 123 got '. var_export($val, true));
}
}
public function testDispatcherCanExecuteComposerScriptGroups(): void
{
$process = $this->getProcessExecutorMock();
$process->expects([
'echo -n foo',
'echo -n baz',
'echo -n bar',
], true);
$dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')
->setConstructorArgs([
$composer = $this->createComposerInstance(),
$io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE),
$process,
])
->onlyMethods([
'getListeners',
])
->getMock();
$dispatcher->expects($this->atLeastOnce())
->method('getListeners')
->will($this->returnCallback(static function (Event $event): array {
if ($event->getName() === 'root') {
return ['@group'];
}
if ($event->getName() === 'group') {
return ['echo -n foo', '@subgroup', 'echo -n bar'];
}
if ($event->getName() === 'subgroup') {
return ['echo -n baz'];
}
return [];
}));
$dispatcher->dispatch('root', new ScriptEvent('root', $composer, $io));
$expected = '> root: @group'.PHP_EOL.
'> group: echo -n foo'.PHP_EOL.
'> group: @subgroup'.PHP_EOL.
'> subgroup: echo -n baz'.PHP_EOL.
'> group: echo -n bar'.PHP_EOL;
self::assertEquals($expected, $io->getOutput());
}
public function testRecursionInScriptsNames(): void
{
$process = $this->getProcessExecutorMock();
$process->expects([
'echo Hello '.ProcessExecutor::escape('World'),
], true);
$dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')
->setConstructorArgs([
$composer = $this->createComposerInstance(),
$io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE),
$process,
])
->onlyMethods([
'getListeners',
])
->getMock();
$dispatcher->expects($this->atLeastOnce())
->method('getListeners')
->will($this->returnCallback(static function (Event $event): array {
if ($event->getName() === 'hello') {
return ['echo Hello'];
}
if ($event->getName() === 'helloWorld') {
return ['@hello World'];
}
return [];
}));
$dispatcher->dispatch('helloWorld', new ScriptEvent('helloWorld', $composer, $io));
$expected = "> helloWorld: @hello World".PHP_EOL.
"> hello: echo Hello " .self::getCmd("'World'").PHP_EOL;
self::assertEquals($expected, $io->getOutput());
}
public function testDispatcherDetectInfiniteRecursion(): void
{
self::expectException('RuntimeException');
$dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')
->setConstructorArgs([
$composer = $this->createComposerInstance(),
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
$this->getProcessExecutorMock(),
])
->onlyMethods([
'getListeners',
])
->getMock();
$dispatcher->expects($this->atLeastOnce())
->method('getListeners')
->will($this->returnCallback(static function (Event $event): array {
if ($event->getName() === 'root') {
return ['@recurse'];
}
if ($event->getName() === 'recurse') {
return ['@root'];
}
return [];
}));
$dispatcher->dispatch('root', new ScriptEvent('root', $composer, $io));
}
/**
* @param array<callable|string> $listeners
*
* @return \PHPUnit\Framework\MockObject\MockObject&EventDispatcher
*/
private function getDispatcherStubForListenersTest(array $listeners, IOInterface $io)
{
$dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')
->setConstructorArgs([
$this->createComposerInstance(),
$io,
])
->onlyMethods(['getListeners'])
->getMock();
$dispatcher->expects($this->atLeastOnce())
->method('getListeners')
->will($this->returnValue($listeners));
return $dispatcher;
}
public static function provideValidCommands(): array
{
return [
['phpunit'],
['echo foo'],
['echo -n foo'],
];
}
public function testDispatcherOutputsCommand(): void
{
$dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')
->setConstructorArgs([
$this->createComposerInstance(),
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
new ProcessExecutor($io),
])
->onlyMethods(['getListeners'])
->getMock();
$listener = ['echo foo'];
$dispatcher->expects($this->atLeastOnce())
->method('getListeners')
->will($this->returnValue($listener));
$io->expects($this->once())
->method('writeError')
->with($this->equalTo('> echo foo'));
$io->expects($this->once())
->method('writeRaw')
->with($this->equalTo('foo'.PHP_EOL), false);
$dispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, false);
}
public function testDispatcherOutputsErrorOnFailedCommand(): void
{
$dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')
->setConstructorArgs([
$this->createComposerInstance(),
$io = $this->getIOMock(IOInterface::NORMAL),
new ProcessExecutor,
])
->onlyMethods(['getListeners'])
->getMock();
$code = 'exit 1';
$listener = [$code];
$dispatcher->expects($this->atLeastOnce())
->method('getListeners')
->will($this->returnValue($listener));
$io->expects([
['text' => '> exit 1'],
['text' => 'Script '.$code.' handling the post-install-cmd event returned with error code 1'],
], true);
self::expectException(ScriptExecutionException::class);
self::expectExceptionMessage('Error Output: ');
$dispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, false);
}
public function testDispatcherInstallerEvents(): void
{
$dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')
->setConstructorArgs([
$this->createComposerInstance(),
$this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
$this->getProcessExecutorMock(),
])
->onlyMethods(['getListeners'])
->getMock();
$dispatcher->expects($this->atLeastOnce())
->method('getListeners')
->will($this->returnValue([]));
$transaction = $this->getMockBuilder('Composer\DependencyResolver\LockTransaction')->disableOriginalConstructor()->getMock();
$dispatcher->dispatchInstallerEvent(InstallerEvents::PRE_OPERATIONS_EXEC, true, true, $transaction);
}
public function testDispatcherDoesntReturnSkippedScripts(): void
{
Platform::putEnv('COMPOSER_SKIP_SCRIPTS', 'scriptName');
$composer = $this->createComposerInstance();
$package = $this->getMockBuilder('Composer\Package\RootPackageInterface')->getMock();
$package->method('getScripts')->will($this->returnValue(['scriptName' => ['scriptName']]));
$composer->setPackage($package);
$dispatcher = new EventDispatcher(
$composer,
$this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
$this->getProcessExecutorMock()
);
$event = $this->getMockBuilder('Composer\Script\Event')
->disableOriginalConstructor()
->getMock();
$event->method('getName')->will($this->returnValue('scriptName'));
$this->assertFalse($dispatcher->hasEventListeners($event));
}
public static function call(): void
{
throw new \RuntimeException();
}
/**
* @return true
*/
public static function someMethod(): bool
{
return true;
}
/**
* @return true
*/
public static function someMethod2(): bool
{
return true;
}
private function createComposerInstance(): Composer
{
$composer = new Composer;
$config = new Config();
$composer->setConfig($config);
$package = $this->getMockBuilder('Composer\Package\RootPackageInterface')->getMock();
$composer->setPackage($package);
$composer->setRepositoryManager($rm = new RepositoryManager(new NullIO(), $config, new HttpDownloaderMock()));
$rm->setLocalRepository(new InstalledArrayRepository([]));
$composer->setAutoloadGenerator(new AutoloadGenerator(new EventDispatcher($composer, new NullIO())));
$composer->setInstallationManager(new InstallationManagerMock());
return $composer;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Console/HtmlOutputFormatterTest.php | tests/Composer/Test/Console/HtmlOutputFormatterTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Console;
use Composer\Console\HtmlOutputFormatter;
use Composer\Test\TestCase;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
class HtmlOutputFormatterTest extends TestCase
{
public function testFormatting(): void
{
$formatter = new HtmlOutputFormatter([
'warning' => new OutputFormatterStyle('black', 'yellow'),
]);
self::assertEquals(
'text <span style="color:green;">green</span> <span style="color:yellow;">yellow</span> <span style="color:black;background-color:yellow;">black w/ yellow bg</span>',
$formatter->format('text <info>green</info> <comment>yellow</comment> <warning>black w/ yellow bg</warning>')
);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/StreamContextFactoryTest.php | tests/Composer/Test/Util/StreamContextFactoryTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Util\Http\ProxyManager;
use Composer\Util\StreamContextFactory;
use Composer\Test\TestCase;
class StreamContextFactoryTest extends TestCase
{
protected function setUp(): void
{
unset($_SERVER['HTTP_PROXY'], $_SERVER['http_proxy'], $_SERVER['HTTPS_PROXY'], $_SERVER['https_proxy'], $_SERVER['NO_PROXY'], $_SERVER['no_proxy']);
ProxyManager::reset();
}
protected function tearDown(): void
{
parent::tearDown();
unset($_SERVER['HTTP_PROXY'], $_SERVER['http_proxy'], $_SERVER['HTTPS_PROXY'], $_SERVER['https_proxy'], $_SERVER['NO_PROXY'], $_SERVER['no_proxy']);
ProxyManager::reset();
}
/**
* @dataProvider dataGetContext
*
* @param mixed[] $expectedOptions
* @param mixed[] $defaultOptions
* @param mixed[] $expectedParams
* @param mixed[] $defaultParams
*/
public function testGetContext(array $expectedOptions, array $defaultOptions, array $expectedParams, array $defaultParams): void
{
$context = StreamContextFactory::getContext('http://example.org', $defaultOptions, $defaultParams);
$options = stream_context_get_options($context);
$params = stream_context_get_params($context);
self::assertEquals($expectedOptions, $options);
self::assertEquals($expectedParams, $params);
}
public static function dataGetContext(): array
{
return [
[
$a = ['http' => ['follow_location' => 1, 'max_redirects' => 20, 'header' => ['User-Agent: foo']]], ['http' => ['header' => 'User-Agent: foo']],
['options' => $a], [],
],
[
$a = ['http' => ['method' => 'GET', 'max_redirects' => 20, 'follow_location' => 1, 'header' => ['User-Agent: foo']]], ['http' => ['method' => 'GET', 'header' => 'User-Agent: foo']],
['options' => $a, 'notification' => $f = static function (): void {
}], ['notification' => $f],
],
];
}
public function testHttpProxy(): void
{
$_SERVER['http_proxy'] = 'http://username:p%40ssword@proxyserver.net:3128/';
$_SERVER['HTTP_PROXY'] = 'http://proxyserver/';
$context = StreamContextFactory::getContext('http://example.org', ['http' => ['method' => 'GET', 'header' => 'User-Agent: foo']]);
$options = stream_context_get_options($context);
self::assertEquals(['http' => [
'proxy' => 'tcp://proxyserver.net:3128',
'request_fulluri' => true,
'method' => 'GET',
'header' => ['User-Agent: foo', "Proxy-Authorization: Basic " . base64_encode('username:p@ssword')],
'max_redirects' => 20,
'follow_location' => 1,
]], $options);
}
public function testHttpProxyWithNoProxy(): void
{
$_SERVER['http_proxy'] = 'http://username:password@proxyserver.net:3128/';
$_SERVER['no_proxy'] = 'foo,example.org';
$context = StreamContextFactory::getContext('http://example.org', ['http' => ['method' => 'GET', 'header' => 'User-Agent: foo']]);
$options = stream_context_get_options($context);
self::assertEquals(['http' => [
'method' => 'GET',
'max_redirects' => 20,
'follow_location' => 1,
'header' => ['User-Agent: foo'],
]], $options);
}
public function testHttpProxyWithNoProxyWildcard(): void
{
$_SERVER['http_proxy'] = 'http://username:password@proxyserver.net:3128/';
$_SERVER['no_proxy'] = '*';
$context = StreamContextFactory::getContext('http://example.org', ['http' => ['method' => 'GET', 'header' => 'User-Agent: foo']]);
$options = stream_context_get_options($context);
self::assertEquals(['http' => [
'method' => 'GET',
'max_redirects' => 20,
'follow_location' => 1,
'header' => ['User-Agent: foo'],
]], $options);
}
public function testOptionsArePreserved(): void
{
$_SERVER['http_proxy'] = 'http://username:password@proxyserver.net:3128/';
$context = StreamContextFactory::getContext('http://example.org', ['http' => ['method' => 'GET', 'header' => ['User-Agent: foo', "X-Foo: bar"], 'request_fulluri' => false]]);
$options = stream_context_get_options($context);
self::assertEquals(['http' => [
'proxy' => 'tcp://proxyserver.net:3128',
'request_fulluri' => false,
'method' => 'GET',
'header' => ['User-Agent: foo', "X-Foo: bar", "Proxy-Authorization: Basic " . base64_encode('username:password')],
'max_redirects' => 20,
'follow_location' => 1,
]], $options);
}
public function testHttpProxyWithoutPort(): void
{
$_SERVER['https_proxy'] = 'http://username:password@proxyserver.net';
$context = StreamContextFactory::getContext('https://example.org', ['http' => ['method' => 'GET', 'header' => 'User-Agent: foo']]);
$options = stream_context_get_options($context);
self::assertEquals(['http' => [
'proxy' => 'tcp://proxyserver.net:80',
'method' => 'GET',
'header' => ['User-Agent: foo', "Proxy-Authorization: Basic " . base64_encode('username:password')],
'max_redirects' => 20,
'follow_location' => 1,
]], $options);
}
public function testHttpsProxyOverride(): void
{
if (!extension_loaded('openssl')) {
$this->markTestSkipped('Requires openssl');
}
$_SERVER['http_proxy'] = 'http://username:password@proxyserver.net';
$_SERVER['https_proxy'] = 'https://woopproxy.net';
// Pointless test replaced by ProxyHelperTest.php
self::expectException('Composer\Downloader\TransportException');
$context = StreamContextFactory::getContext('https://example.org', ['http' => ['method' => 'GET', 'header' => 'User-Agent: foo']]);
}
/**
* @dataProvider dataSSLProxy
*/
public function testSSLProxy(string $expected, string $proxy): void
{
$_SERVER['http_proxy'] = $proxy;
if (extension_loaded('openssl')) {
$context = StreamContextFactory::getContext('http://example.org', ['http' => ['header' => 'User-Agent: foo']]);
$options = stream_context_get_options($context);
self::assertEquals(['http' => [
'proxy' => $expected,
'request_fulluri' => true,
'max_redirects' => 20,
'follow_location' => 1,
'header' => ['User-Agent: foo'],
]], $options);
} else {
try {
StreamContextFactory::getContext('http://example.org');
$this->fail();
} catch (\RuntimeException $e) {
self::assertInstanceOf('Composer\Downloader\TransportException', $e);
}
}
}
public static function dataSSLProxy(): array
{
return [
['ssl://proxyserver:443', 'https://proxyserver/'],
['ssl://proxyserver:8443', 'https://proxyserver:8443'],
];
}
public function testEnsureThatfixHttpHeaderFieldMovesContentTypeToEndOfOptions(): void
{
$options = [
'http' => [
'header' => "User-agent: foo\r\nX-Foo: bar\r\nContent-Type: application/json\r\nAuthorization: Basic aW52YWxpZA==",
],
];
$expectedOptions = [
'http' => [
'header' => [
"User-agent: foo",
"X-Foo: bar",
"Authorization: Basic aW52YWxpZA==",
"Content-Type: application/json",
],
],
];
$context = StreamContextFactory::getContext('http://example.org', $options);
$ctxoptions = stream_context_get_options($context);
self::assertEquals(end($expectedOptions['http']['header']), end($ctxoptions['http']['header']));
}
public function testInitOptionsDoesIncludeProxyAuthHeaders(): void
{
$_SERVER['https_proxy'] = 'http://username:password@proxyserver.net:3128/';
$options = [];
$options = StreamContextFactory::initOptions('https://example.org', $options);
$headers = implode(' ', $options['http']['header']);
self::assertTrue(false !== stripos($headers, 'Proxy-Authorization'));
}
public function testInitOptionsForCurlDoesNotIncludeProxyAuthHeaders(): void
{
if (!extension_loaded('curl')) {
$this->markTestSkipped('The curl is not available.');
}
$_SERVER['http_proxy'] = 'http://username:password@proxyserver.net:3128/';
$options = [];
$options = StreamContextFactory::initOptions('https://example.org', $options, true);
$headers = implode(' ', $options['http']['header']);
self::assertFalse(stripos($headers, 'Proxy-Authorization'));
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/ProcessExecutorTest.php | tests/Composer/Test/Util/ProcessExecutorTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\IO\ConsoleIO;
use Composer\Util\ProcessExecutor;
use Composer\Test\TestCase;
use Composer\IO\BufferIO;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\StreamOutput;
class ProcessExecutorTest extends TestCase
{
public function testExecuteCapturesOutput(): void
{
$process = new ProcessExecutor;
$process->execute('echo foo', $output);
self::assertEquals("foo".PHP_EOL, $output);
}
public function testExecuteOutputsIfNotCaptured(): void
{
$process = new ProcessExecutor;
ob_start();
$process->execute('echo foo');
$output = ob_get_clean();
self::assertEquals("foo".PHP_EOL, $output);
}
public function testUseIOIsNotNullAndIfNotCaptured(): void
{
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$io->expects($this->once())
->method('writeRaw')
->with($this->equalTo('foo'.PHP_EOL), false);
$process = new ProcessExecutor($io);
$process->execute('echo foo');
}
public function testExecuteCapturesStderr(): void
{
$process = new ProcessExecutor;
$process->execute('cat foo', $output);
self::assertStringContainsString('foo: No such file or directory', $process->getErrorOutput());
}
public function testTimeout(): void
{
ProcessExecutor::setTimeout(1);
$process = new ProcessExecutor;
self::assertEquals(1, $process->getTimeout());
ProcessExecutor::setTimeout(60);
}
/**
* @dataProvider hidePasswordProvider
*/
public function testHidePasswords(string $command, string $expectedCommandOutput): void
{
$process = new ProcessExecutor($buffer = new BufferIO('', StreamOutput::VERBOSITY_DEBUG));
$process->execute($command, $output);
self::assertEquals('Executing command (CWD): ' . $expectedCommandOutput, trim($buffer->getOutput()));
}
public static function hidePasswordProvider(): array
{
return [
['echo https://foo:bar@example.org/', 'echo https://foo:***@example.org/'],
['echo http://foo@example.org', 'echo http://foo@example.org'],
['echo http://abcdef1234567890234578:x-oauth-token@github.com/', 'echo http://***:***@github.com/'],
['echo http://github_pat_1234567890abcdefghijkl_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW:x-oauth-token@github.com/', 'echo http://***:***@github.com/'],
["svn ls --verbose --non-interactive --username 'foo' --password 'bar' 'https://foo.example.org/svn/'", "svn ls --verbose --non-interactive --username 'foo' --password '***' 'https://foo.example.org/svn/'"],
["svn ls --verbose --non-interactive --username 'foo' --password 'bar \'bar' 'https://foo.example.org/svn/'", "svn ls --verbose --non-interactive --username 'foo' --password '***' 'https://foo.example.org/svn/'"],
];
}
public function testDoesntHidePorts(): void
{
$process = new ProcessExecutor($buffer = new BufferIO('', StreamOutput::VERBOSITY_DEBUG));
$process->execute('echo https://localhost:1234/', $output);
self::assertEquals('Executing command (CWD): echo https://localhost:1234/', trim($buffer->getOutput()));
}
public function testSplitLines(): void
{
$process = new ProcessExecutor;
self::assertEquals([], $process->splitLines(''));
self::assertEquals([], $process->splitLines(null));
self::assertEquals(['foo'], $process->splitLines('foo'));
self::assertEquals(['foo', 'bar'], $process->splitLines("foo\nbar"));
self::assertEquals(['foo', 'bar'], $process->splitLines("foo\r\nbar"));
self::assertEquals(['foo', 'bar'], $process->splitLines("foo\r\nbar\n"));
}
public function testConsoleIODoesNotFormatSymfonyConsoleStyle(): void
{
$output = new BufferedOutput(OutputInterface::VERBOSITY_NORMAL, true);
$process = new ProcessExecutor(new ConsoleIO(new ArrayInput([]), $output, new HelperSet([])));
$process->execute('php -ddisplay_errors=0 -derror_reporting=0 -r "echo \'<error>foo</error>\'.PHP_EOL;"');
self::assertSame('<error>foo</error>'.PHP_EOL, $output->fetch());
}
public function testExecuteAsyncCancel(): void
{
$process = new ProcessExecutor($buffer = new BufferIO('', StreamOutput::VERBOSITY_DEBUG));
$process->enableAsync();
$start = microtime(true);
$promise = $process->executeAsync('sleep 2');
self::assertEquals(1, $process->countActiveJobs());
$promise->cancel();
self::assertEquals(0, $process->countActiveJobs());
$process->wait();
$end = microtime(true);
self::assertTrue($end - $start < 2, 'Canceling took longer than it should, lasted '.($end - $start));
}
/**
* Test various arguments are escaped as expected
*
* @dataProvider dataEscapeArguments
*
* @param string|false|null $argument
*/
public function testEscapeArgument($argument, string $win, string $unix): void
{
$expected = defined('PHP_WINDOWS_VERSION_BUILD') ? $win : $unix;
self::assertSame($expected, ProcessExecutor::escape($argument));
}
/**
* Each named test is an array of:
* argument, win-expected, unix-expected
*/
public static function dataEscapeArguments(): array
{
return [
// empty argument - must be quoted
'empty' => ['', '""', "''"],
// null argument - must be quoted
'empty null' => [null, '""', "''"],
// false argument - must be quoted
'empty false' => [false, '""', "''"],
// unix single-quote must be escaped
'unix-sq' => ["a'bc", "a'bc", "'a'\\''bc'"],
// new lines must be replaced
'new lines' => ["a\nb\nc", '"a b c"', "'a\nb\nc'"],
// whitespace <space> must be quoted
'ws space' => ['a b c', '"a b c"', "'a b c'"],
// whitespace <tab> must be quoted
'ws tab' => ["a\tb\tc", "\"a\tb\tc\"", "'a\tb\tc'"],
// no whitespace must not be quoted
'no-ws' => ['abc', 'abc', "'abc'"],
// commas must be quoted
'comma' => ['a,bc', '"a,bc"', "'a,bc'"],
// double-quotes must be backslash-escaped
'dq' => ['a"bc', 'a\^"bc', "'a\"bc'"],
// double-quotes must be backslash-escaped with preceding backslashes doubled
'dq-bslash' => ['a\\"bc', 'a\\\\\^"bc', "'a\\\"bc'"],
// backslashes not preceding a double-quote are treated as literal
'bslash' => ['ab\\\\c\\', 'ab\\\\c\\', "'ab\\\\c\\'"],
// trailing backslashes must be doubled up when the argument is quoted
'bslash dq' => ['a b c\\\\', '"a b c\\\\\\\\"', "'a b c\\\\'"],
// meta: outer double-quotes must be caret-escaped as well
'meta dq' => ['a "b" c', '^"a \^"b\^" c^"', "'a \"b\" c'"],
// meta: percent expansion must be caret-escaped
'meta-pc1' => ['%path%', '^%path^%', "'%path%'"],
// meta: expansion must have two percent characters
'meta-pc2' => ['%path', '%path', "'%path'"],
// meta: expansion must have have two surrounding percent characters
'meta-pc3' => ['%%path', '%%path', "'%%path'"],
// meta: bang expansion must be double caret-escaped
'meta-bang1' => ['!path!', '^^!path^^!', "'!path!'"],
// meta: bang expansion must have two bang characters
'meta-bang2' => ['!path', '!path', "'!path'"],
// meta: bang expansion must have two surrounding ang characters
'meta-bang3' => ['!!path', '!!path', "'!!path'"],
// meta: caret-escaping must escape all other meta chars (triggered by double-quote)
'meta-all-dq' => ['<>"&|()^', '^<^>\^"^&^|^(^)^^', "'<>\"&|()^'"],
// other meta: no caret-escaping when whitespace in argument
'other meta' => ['<> &| ()^', '"<> &| ()^"', "'<> &| ()^'"],
// other meta: quote escape chars when no whitespace in argument
'other-meta' => ['<>&|()^', '"<>&|()^"', "'<>&|()^'"],
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/ConfigValidatorTest.php | tests/Composer/Test/Util/ConfigValidatorTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\IO\NullIO;
use Composer\Util\ConfigValidator;
use Composer\Test\TestCase;
/**
* ConfigValidator test case
*/
class ConfigValidatorTest extends TestCase
{
/**
* Test ConfigValidator warns on commit reference
*/
public function testConfigValidatorCommitRefWarning(): void
{
$configValidator = new ConfigValidator(new NullIO());
[, , $warnings] = $configValidator->validate(__DIR__ . '/Fixtures/composer_commit-ref.json');
self::assertContains(
'The package "some/package" is pointing to a commit-ref, this is bad practice and can cause unforeseen issues.',
$warnings
);
}
public function testConfigValidatorWarnsOnScriptDescriptionForNonexistentScript(): void
{
$configValidator = new ConfigValidator(new NullIO());
[, , $warnings] = $configValidator->validate(__DIR__ . '/Fixtures/composer_scripts-descriptions.json');
self::assertContains(
'Description for non-existent script "phpcsxxx" found in "scripts-descriptions"',
$warnings
);
}
public function testConfigValidatorWarnsOnScriptAliasForNonexistentScript(): void
{
$configValidator = new ConfigValidator(new NullIO());
[, , $warnings] = $configValidator->validate(__DIR__ . '/Fixtures/composer_scripts-aliases.json');
self::assertContains(
'Aliases for non-existent script "phpcsxxx" found in "scripts-aliases"',
$warnings
);
}
public function testConfigValidatorWarnsOnUnnecessaryProvideReplace(): void
{
$configValidator = new ConfigValidator(new NullIO());
[, , $warnings] = $configValidator->validate(__DIR__ . '/Fixtures/composer_provide-replace-requirements.json');
self::assertContains(
'The package a/a in require is also listed in provide which satisfies the requirement. Remove it from provide if you wish to install it.',
$warnings
);
self::assertContains(
'The package b/b in require is also listed in replace which satisfies the requirement. Remove it from replace if you wish to install it.',
$warnings
);
self::assertContains(
'The package c/c in require-dev is also listed in provide which satisfies the requirement. Remove it from provide if you wish to install it.',
$warnings
);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/ForgejoTest.php | tests/Composer/Test/Util/ForgejoTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Test\TestCase;
use Composer\Util\Forgejo;
class ForgejoTest extends TestCase
{
/** @var string */
private $username = 'username';
/** @var string */
private $accessToken = 'access-token';
/** @var string */
private $message = 'mymessage';
/** @var string */
private $origin = 'codeberg.org';
public function testUsernamePasswordAuthenticationFlow(): void
{
$io = $this->getIOMock();
$io->expects([
['text' => $this->message],
['ask' => 'Username: ', 'reply' => $this->username],
['ask' => 'Token (hidden): ', 'reply' => $this->accessToken],
]);
$httpDownloader = $this->getHttpDownloaderMock();
$httpDownloader->expects(
[['url' => sprintf('https://%s/api/v1/version', $this->origin), 'body' => '{}']],
true
);
$config = $this->getConfigMock();
$config
->expects($this->exactly(2))
->method('getAuthConfigSource')
->willReturn($this->getAuthJsonMock())
;
$config
->expects($this->once())
->method('getConfigSource')
->willReturn($this->getConfJsonMock())
;
$forgejo = new Forgejo($io, $config, $httpDownloader);
self::assertTrue($forgejo->authorizeOAuthInteractively($this->origin, $this->message));
}
public function testUsernamePasswordFailure(): void
{
$io = $this->getIOMock();
$io->expects([
['ask' => 'Username: ', 'reply' => $this->username],
['ask' => 'Token (hidden): ', 'reply' => $this->accessToken],
]);
$httpDownloader = $this->getHttpDownloaderMock();
$httpDownloader->expects(
[['url' => sprintf('https://%s/api/v1/version', $this->origin), 'status' => 404]],
true
);
$config = $this->getConfigMock();
$config
->expects($this->exactly(1))
->method('getAuthConfigSource')
->willReturn($this->getAuthJsonMock())
;
$forgejo = new Forgejo($io, $config, $httpDownloader);
self::assertFalse($forgejo->authorizeOAuthInteractively($this->origin));
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Config
*/
private function getConfigMock()
{
return $this->getMockBuilder('Composer\Config')->getMock();
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Config\JsonConfigSource
*/
private function getAuthJsonMock()
{
$authjson = $this
->getMockBuilder('Composer\Config\JsonConfigSource')
->disableOriginalConstructor()
->getMock()
;
$authjson
->expects($this->atLeastOnce())
->method('getName')
->willReturn('auth.json')
;
return $authjson;
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Config\JsonConfigSource
*/
private function getConfJsonMock()
{
$confjson = $this
->getMockBuilder('Composer\Config\JsonConfigSource')
->disableOriginalConstructor()
->getMock()
;
$confjson
->expects($this->atLeastOnce())
->method('removeConfigSetting')
->with('forgejo-token.'.$this->origin)
;
return $confjson;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/TarTest.php | tests/Composer/Test/Util/TarTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Util\Tar;
use Composer\Test\TestCase;
/**
* @author Wissem Riahi <wissemr@gmail.com>
*/
class TarTest extends TestCase
{
public function testReturnsNullifTheTarIsNotFound(): void
{
$result = Tar::getComposerJson(__DIR__.'/Fixtures/Tar/invalid.zip');
self::assertNull($result);
}
public function testReturnsNullIfTheTarIsEmpty(): void
{
$result = Tar::getComposerJson(__DIR__.'/Fixtures/Tar/empty.tar.gz');
self::assertNull($result);
}
public function testThrowsExceptionIfTheTarHasNoComposerJson(): void
{
self::expectException('RuntimeException');
Tar::getComposerJson(__DIR__.'/Fixtures/Tar/nojson.tar.gz');
}
public function testThrowsExceptionIfTheComposerJsonIsInASubSubfolder(): void
{
self::expectException('RuntimeException');
Tar::getComposerJson(__DIR__.'/Fixtures/Tar/subfolders.tar.gz');
}
public function testReturnsComposerJsonInTarRoot(): void
{
$result = Tar::getComposerJson(__DIR__.'/Fixtures/Tar/root.tar.gz');
self::assertEquals("{\n \"name\": \"foo/bar\"\n}\n", $result);
}
public function testReturnsComposerJsonInFirstFolder(): void
{
$result = Tar::getComposerJson(__DIR__.'/Fixtures/Tar/folder.tar.gz');
self::assertEquals("{\n \"name\": \"foo/bar\"\n}\n", $result);
}
public function testMultipleTopLevelDirsIsInvalid(): void
{
self::expectException('RuntimeException');
Tar::getComposerJson(__DIR__.'/Fixtures/Tar/multiple.tar.gz');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/SvnTest.php | tests/Composer/Test/Util/SvnTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Config;
use Composer\IO\NullIO;
use Composer\Util\Svn;
use Composer\Test\TestCase;
class SvnTest extends TestCase
{
/**
* Test the credential string.
*
* @param string $url The SVN url.
* @param non-empty-list<string> $expect The expectation for the test.
*
* @dataProvider urlProvider
*/
public function testCredentials(string $url, array $expect): void
{
$svn = new Svn($url, new NullIO, new Config());
$reflMethod = new \ReflectionMethod('Composer\\Util\\Svn', 'getCredentialArgs');
(\PHP_VERSION_ID < 80100) and $reflMethod->setAccessible(true);
self::assertEquals($expect, $reflMethod->invoke($svn));
}
public static function urlProvider(): array
{
return [
['http://till:test@svn.example.org/', ['--username', 'till', '--password', 'test']],
['http://svn.apache.org/', []],
['svn://johndoe@example.org', ['--username', 'johndoe', '--password', '']],
];
}
public function testInteractiveString(): void
{
$url = 'http://svn.example.org';
$svn = new Svn($url, new NullIO(), new Config());
$reflMethod = new \ReflectionMethod('Composer\\Util\\Svn', 'getCommand');
(\PHP_VERSION_ID < 80100) and $reflMethod->setAccessible(true);
self::assertEquals(
['svn', 'ls', '--non-interactive', '--', 'http://svn.example.org'],
$reflMethod->invokeArgs($svn, [['svn', 'ls'], $url])
);
}
public function testCredentialsFromConfig(): void
{
$url = 'http://svn.apache.org';
$config = new Config();
$config->merge([
'config' => [
'http-basic' => [
'svn.apache.org' => ['username' => 'foo', 'password' => 'bar'],
],
],
]);
$svn = new Svn($url, new NullIO, $config);
$reflMethod = new \ReflectionMethod('Composer\\Util\\Svn', 'getCredentialArgs');
(\PHP_VERSION_ID < 80100) and $reflMethod->setAccessible(true);
self::assertEquals(['--username', 'foo', '--password', 'bar'], $reflMethod->invoke($svn));
}
public function testCredentialsFromConfigWithCacheCredentialsTrue(): void
{
$url = 'http://svn.apache.org';
$config = new Config();
$config->merge(
[
'config' => [
'http-basic' => [
'svn.apache.org' => ['username' => 'foo', 'password' => 'bar'],
],
],
]
);
$svn = new Svn($url, new NullIO, $config);
$svn->setCacheCredentials(true);
$reflMethod = new \ReflectionMethod('Composer\\Util\\Svn', 'getCredentialArgs');
(\PHP_VERSION_ID < 80100) and $reflMethod->setAccessible(true);
self::assertEquals(['--username', 'foo', '--password', 'bar'], $reflMethod->invoke($svn));
}
public function testCredentialsFromConfigWithCacheCredentialsFalse(): void
{
$url = 'http://svn.apache.org';
$config = new Config();
$config->merge(
[
'config' => [
'http-basic' => [
'svn.apache.org' => ['username' => 'foo', 'password' => 'bar'],
],
],
]
);
$svn = new Svn($url, new NullIO, $config);
$svn->setCacheCredentials(false);
$reflMethod = new \ReflectionMethod('Composer\\Util\\Svn', 'getCredentialArgs');
(\PHP_VERSION_ID < 80100) and $reflMethod->setAccessible(true);
self::assertEquals(['--no-auth-cache', '--username', 'foo', '--password', 'bar'], $reflMethod->invoke($svn));
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/RemoteFilesystemTest.php | tests/Composer/Test/Util/RemoteFilesystemTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Config;
use Composer\IO\IOInterface;
use Composer\Util\AuthHelper;
use Composer\Util\RemoteFilesystem;
use Composer\Test\TestCase;
use PHPUnit\Framework\MockObject\MockObject;
use ReflectionMethod;
use ReflectionProperty;
class RemoteFilesystemTest extends TestCase
{
public function testGetOptionsForUrl(): void
{
$io = $this->getIOInterfaceMock();
$io
->expects($this->once())
->method('hasAuthentication')
->willReturn(false)
;
$res = $this->callGetOptionsForUrl($io, ['http://example.org', []]);
self::assertTrue(isset($res['http']['header']) && is_array($res['http']['header']), 'getOptions must return an array with headers');
}
public function testGetOptionsForUrlWithAuthorization(): void
{
$io = $this->getIOInterfaceMock();
$io
->expects($this->once())
->method('hasAuthentication')
->willReturn(true)
;
$io
->expects($this->once())
->method('getAuthentication')
->willReturn(['username' => 'login', 'password' => 'password'])
;
$options = $this->callGetOptionsForUrl($io, ['http://example.org', []]);
$found = false;
foreach ($options['http']['header'] as $header) {
if (0 === strpos($header, 'Authorization: Basic')) {
$found = true;
}
}
self::assertTrue($found, 'getOptions must have an Authorization header');
}
public function testGetOptionsForUrlWithStreamOptions(): void
{
$io = $this->getIOInterfaceMock();
$io
->expects($this->once())
->method('hasAuthentication')
->willReturn(true)
;
$io
->expects($this->once())
->method('getAuthentication')
->willReturn(['username' => null, 'password' => null])
;
$streamOptions = ['ssl' => [
'allow_self_signed' => true,
]];
$res = $this->callGetOptionsForUrl($io, ['https://example.org', []], $streamOptions);
self::assertTrue(
isset($res['ssl'], $res['ssl']['allow_self_signed']) && true === $res['ssl']['allow_self_signed'],
'getOptions must return an array with a allow_self_signed set to true'
);
}
public function testGetOptionsForUrlWithCallOptionsKeepsHeader(): void
{
$io = $this->getIOInterfaceMock();
$io
->expects($this->once())
->method('hasAuthentication')
->willReturn(true)
;
$io
->expects($this->once())
->method('getAuthentication')
->willReturn(['username' => null, 'password' => null])
;
$streamOptions = ['http' => [
'header' => 'Foo: bar',
]];
$res = $this->callGetOptionsForUrl($io, ['https://example.org', $streamOptions]);
self::assertTrue(isset($res['http']['header']), 'getOptions must return an array with a http.header key');
$found = false;
foreach ($res['http']['header'] as $header) {
if ($header === 'Foo: bar') {
$found = true;
}
}
self::assertTrue($found, 'getOptions must have a Foo: bar header');
self::assertGreaterThan(1, count($res['http']['header']));
}
public function testCallbackGetFileSize(): void
{
$fs = new RemoteFilesystem($this->getIOInterfaceMock(), $this->getConfigMock());
$this->callCallbackGet($fs, STREAM_NOTIFY_FILE_SIZE_IS, 0, '', 0, 0, 20);
self::assertAttributeEqualsCustom(20, 'bytesMax', $fs);
}
public function testCallbackGetNotifyProgress(): void
{
$io = $this->getIOInterfaceMock();
$io
->expects($this->once())
->method('overwriteError')
;
$fs = new RemoteFilesystem($io, $this->getConfigMock());
$this->setAttribute($fs, 'bytesMax', 20);
$this->setAttribute($fs, 'progress', true);
$this->callCallbackGet($fs, STREAM_NOTIFY_PROGRESS, 0, '', 0, 10, 20);
self::assertAttributeEqualsCustom(50, 'lastProgress', $fs);
}
/**
* @doesNotPerformAssertions
*/
public function testCallbackGetPassesThrough404(): void
{
$fs = new RemoteFilesystem($this->getIOInterfaceMock(), $this->getConfigMock());
$this->callCallbackGet($fs, STREAM_NOTIFY_FAILURE, 0, 'HTTP/1.1 404 Not Found', 404, 0, 0);
}
public function testGetContents(): void
{
$fs = new RemoteFilesystem($this->getIOInterfaceMock(), $this->getConfigMock());
self::assertStringContainsString('testGetContents', (string) $fs->getContents('http://example.org', 'file://'.__FILE__));
}
public function testCopy(): void
{
$fs = new RemoteFilesystem($this->getIOInterfaceMock(), $this->getConfigMock());
$file = $this->createTempFile();
self::assertTrue($fs->copy('http://example.org', 'file://'.__FILE__, $file));
self::assertFileExists($file);
self::assertStringContainsString('testCopy', (string) file_get_contents($file));
unlink($file);
}
public function testCopyWithNoRetryOnFailure(): void
{
self::expectException('Composer\Downloader\TransportException');
$fs = $this->getRemoteFilesystemWithMockedMethods(['getRemoteContents']);
$fs->expects($this->once())->method('getRemoteContents')
->willReturnCallback(static function ($originUrl, $fileUrl, $ctx, &$http_response_header): string {
$http_response_header = ['http/1.1 401 unauthorized'];
return '';
});
$file = $this->createTempFile();
unlink($file);
$fs->copy(
'http://example.org',
'file://' . __FILE__,
$file,
true,
['retry-auth-failure' => false]
);
}
public function testCopyWithSuccessOnRetry(): void
{
$authHelper = $this->getAuthHelperWithMockedMethods(['promptAuthIfNeeded']);
$fs = $this->getRemoteFilesystemWithMockedMethods(['getRemoteContents'], $authHelper);
$authHelper->expects($this->once())
->method('promptAuthIfNeeded')
->willReturn([
'storeAuth' => true,
'retry' => true,
]);
$counter = 0;
$fs->expects($this->exactly(2))
->method('getRemoteContents')
->willReturnCallback(static function ($originUrl, $fileUrl, $ctx, &$http_response_header) use (&$counter) {
if ($counter++ === 0) {
$http_response_header = ['http/1.1 401 unauthorized'];
return '';
} else {
$http_response_header = ['http/1.1 200 OK'];
return '<?php $copied = "Copied"; ';
}
});
$file = $this->createTempFile();
$copyResult = $fs->copy(
'http://example.org',
'file://' . __FILE__,
$file,
true,
['retry-auth-failure' => true]
);
self::assertTrue($copyResult);
self::assertFileExists($file);
self::assertStringContainsString('Copied', (string) file_get_contents($file));
unlink($file);
}
/**
* @group TLS
*/
public function testGetOptionsForUrlCreatesSecureTlsDefaults(): void
{
$io = $this->getIOInterfaceMock();
$res = $this->callGetOptionsForUrl($io, ['example.org', ['ssl' => ['cafile' => '/some/path/file.crt']]], [], 'http://www.example.org');
self::assertTrue(isset($res['ssl']['ciphers']));
self::assertMatchesRegularExpression('|!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA|', $res['ssl']['ciphers']);
self::assertTrue($res['ssl']['verify_peer']);
self::assertTrue($res['ssl']['SNI_enabled']);
self::assertEquals(7, $res['ssl']['verify_depth']);
self::assertEquals('/some/path/file.crt', $res['ssl']['cafile']);
if (version_compare(PHP_VERSION, '5.4.13') >= 0) {
self::assertTrue($res['ssl']['disable_compression']);
} else {
self::assertFalse(isset($res['ssl']['disable_compression']));
}
}
/**
* Provides URLs to public downloads at BitBucket.
*
* @return string[][]
*/
public static function provideBitbucketPublicDownloadUrls(): array
{
return [
['https://bitbucket.org/seldaek/composer-live-test-repo/raw/master/composer-unit-test-download-me.txt', '1234'],
];
}
/**
* Tests that a BitBucket public download is correctly retrieved.
*
* @dataProvider provideBitbucketPublicDownloadUrls
* @param non-empty-string $url
* @requires PHP 7.4.17
*/
public function testBitBucketPublicDownload(string $url, string $contents): void
{
$io = $this
->getMockBuilder('Composer\IO\ConsoleIO')
->disableOriginalConstructor()
->getMock();
$rfs = new RemoteFilesystem($io, $this->getConfigMock());
$hostname = parse_url($url, PHP_URL_HOST);
$result = $rfs->getContents($hostname, $url, false);
self::assertEquals($contents, $result);
}
/**
* @param mixed[] $args
* @param mixed[] $options
*
* @return mixed[]
*/
private function callGetOptionsForUrl(IOInterface $io, array $args = [], array $options = [], string $fileUrl = ''): array
{
$fs = new RemoteFilesystem($io, $this->getConfigMock(), $options);
$ref = new ReflectionMethod($fs, 'getOptionsForUrl');
$prop = new ReflectionProperty($fs, 'fileUrl');
(\PHP_VERSION_ID < 80100) and $ref->setAccessible(true);
(\PHP_VERSION_ID < 80100) and $prop->setAccessible(true);
$prop->setValue($fs, $fileUrl);
return $ref->invokeArgs($fs, $args);
}
/**
* @return MockObject|Config
*/
private function getConfigMock()
{
$config = $this->getMockBuilder('Composer\Config')->getMock();
$config
->method('get')
->willReturnCallback(static function ($key) {
if ($key === 'github-domains' || $key === 'gitlab-domains') {
return [];
}
return null;
});
return $config;
}
private function callCallbackGet(RemoteFilesystem $fs, int $notificationCode, int $severity, string $message, int $messageCode, int $bytesTransferred, int $bytesMax): void
{
$ref = new ReflectionMethod($fs, 'callbackGet');
(\PHP_VERSION_ID < 80100) and $ref->setAccessible(true);
$ref->invoke($fs, $notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax);
}
/**
* @param object|string $object
* @param mixed $value
*/
private function setAttribute($object, string $attribute, $value): void
{
$attr = new ReflectionProperty($object, $attribute);
(\PHP_VERSION_ID < 80100) and $attr->setAccessible(true);
$attr->setValue($object, $value);
}
/**
* @param mixed $value
* @param object|string $object
*/
private function assertAttributeEqualsCustom($value, string $attribute, $object): void
{
$attr = new ReflectionProperty($object, $attribute);
(\PHP_VERSION_ID < 80100) and $attr->setAccessible(true);
self::assertSame($value, $attr->getValue($object));
}
/**
* @return MockObject|IOInterface
*/
private function getIOInterfaceMock()
{
return $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
}
/**
* @param string[] $mockedMethods
*
* @return RemoteFilesystem|MockObject
*/
private function getRemoteFilesystemWithMockedMethods(array $mockedMethods, ?AuthHelper $authHelper = null)
{
return $this->getMockBuilder('Composer\Util\RemoteFilesystem')
->setConstructorArgs([
$this->getIOInterfaceMock(),
$this->getConfigMock(),
[],
false,
$authHelper,
])
->onlyMethods($mockedMethods)
->getMock();
}
/**
* @param string[] $mockedMethods
*
* @return AuthHelper|MockObject
*/
private function getAuthHelperWithMockedMethods(array $mockedMethods)
{
return $this->getMockBuilder('Composer\Util\AuthHelper')
->setConstructorArgs([
$this->getIOInterfaceMock(),
$this->getConfigMock(),
])
->onlyMethods($mockedMethods)
->getMock();
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/ErrorHandlerTest.php | tests/Composer/Test/Util/ErrorHandlerTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Util\ErrorHandler;
use Composer\Test\TestCase;
/**
* ErrorHandler test case
*/
class ErrorHandlerTest extends TestCase
{
public function setUp(): void
{
ErrorHandler::register();
}
protected function tearDown(): void
{
parent::tearDown();
restore_error_handler();
}
/**
* Test ErrorHandler handles notices
*/
public function testErrorHandlerCaptureNotice(): void
{
if (\PHP_VERSION_ID >= 80000) {
self::expectException('\ErrorException');
self::expectExceptionMessage('Undefined array key "baz"');
} else {
self::expectException('\ErrorException');
self::expectExceptionMessage('Undefined index: baz');
}
$array = ['foo' => 'bar'];
// @phpstan-ignore offsetAccess.notFound, expr.resultUnused
$array['baz'];
}
/**
* Test ErrorHandler handles warnings
*/
public function testErrorHandlerCaptureWarning(): void
{
if (\PHP_VERSION_ID >= 80000) {
self::expectException('TypeError');
self::expectExceptionMessage('array_merge');
} else {
self::expectException('ErrorException');
self::expectExceptionMessage('array_merge');
}
// @phpstan-ignore function.resultUnused, argument.type
array_merge([], 'string');
}
/**
* Test ErrorHandler handles warnings
* @doesNotPerformAssertions
*/
public function testErrorHandlerRespectsAtOperator(): void
{
@trigger_error('test', E_USER_NOTICE);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/ZipTest.php | tests/Composer/Test/Util/ZipTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Util\Zip;
use Composer\Test\TestCase;
/**
* @author Andreas Schempp <andreas.schempp@terminal42.ch>
*/
class ZipTest extends TestCase
{
public function testThrowsExceptionIfZipExtensionIsNotLoaded(): void
{
if (extension_loaded('zip')) {
$this->markTestSkipped('The PHP zip extension is loaded.');
}
self::expectException('RuntimeException');
self::expectExceptionMessage('The Zip Util requires PHP\'s zip extension');
Zip::getComposerJson('');
}
public function testReturnsNullifTheZipIsNotFound(): void
{
if (!extension_loaded('zip')) {
$this->markTestSkipped('The PHP zip extension is not loaded.');
}
$result = Zip::getComposerJson(__DIR__.'/Fixtures/Zip/invalid.zip');
self::assertNull($result);
}
public function testReturnsNullIfTheZipIsEmpty(): void
{
if (!extension_loaded('zip')) {
$this->markTestSkipped('The PHP zip extension is not loaded.');
}
$result = Zip::getComposerJson(__DIR__.'/Fixtures/Zip/empty.zip');
self::assertNull($result);
}
public function testThrowsExceptionIfTheZipHasNoComposerJson(): void
{
if (!extension_loaded('zip')) {
$this->markTestSkipped('The PHP zip extension is not loaded.');
}
self::expectException('RuntimeException');
self::expectExceptionMessage('No composer.json found either at the top level or within the topmost directory');
Zip::getComposerJson(__DIR__.'/Fixtures/Zip/nojson.zip');
}
public function testThrowsExceptionIfTheComposerJsonIsInASubSubfolder(): void
{
if (!extension_loaded('zip')) {
$this->markTestSkipped('The PHP zip extension is not loaded.');
}
self::expectException('RuntimeException');
self::expectExceptionMessage('No composer.json found either at the top level or within the topmost directory');
Zip::getComposerJson(__DIR__.'/Fixtures/Zip/subfolders.zip');
}
public function testReturnsComposerJsonInZipRoot(): void
{
if (!extension_loaded('zip')) {
$this->markTestSkipped('The PHP zip extension is not loaded.');
}
$result = Zip::getComposerJson(__DIR__.'/Fixtures/Zip/root.zip');
self::assertEquals("{\n \"name\": \"foo/bar\"\n}\n", $result);
}
public function testReturnsComposerJsonInFirstFolder(): void
{
if (!extension_loaded('zip')) {
$this->markTestSkipped('The PHP zip extension is not loaded.');
}
$result = Zip::getComposerJson(__DIR__.'/Fixtures/Zip/folder.zip');
self::assertEquals("{\n \"name\": \"foo/bar\"\n}\n", $result);
}
public function testMultipleTopLevelDirsIsInvalid(): void
{
if (!extension_loaded('zip')) {
$this->markTestSkipped('The PHP zip extension is not loaded.');
}
self::expectException('RuntimeException');
self::expectExceptionMessage('Archive has more than one top level directories, and no composer.json was found on the top level, so it\'s an invalid archive. Top level paths found were: folder1/,folder2/');
Zip::getComposerJson(__DIR__.'/Fixtures/Zip/multiple.zip');
}
public function testReturnsComposerJsonFromFirstSubfolder(): void
{
if (!extension_loaded('zip')) {
$this->markTestSkipped('The PHP zip extension is not loaded.');
}
$result = Zip::getComposerJson(__DIR__.'/Fixtures/Zip/single-sub.zip');
self::assertEquals("{\n \"name\": \"foo/bar\"\n}\n", $result);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/PackageSorterTest.php | tests/Composer/Test/Util/PackageSorterTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Package\Link;
use Composer\Package\Package;
use Composer\Test\TestCase;
use Composer\Util\PackageSorter;
use Composer\Semver\Constraint\MatchAllConstraint;
class PackageSorterTest extends TestCase
{
public function testSortingDoesNothingWithNoDependencies(): void
{
$packages[] = self::createPackage('foo/bar1', []);
$packages[] = self::createPackage('foo/bar2', []);
$packages[] = self::createPackage('foo/bar3', []);
$packages[] = self::createPackage('foo/bar4', []);
$sortedPackages = PackageSorter::sortPackages($packages);
self::assertSame($packages, $sortedPackages);
}
public static function sortingOrdersDependenciesHigherThanPackageDataProvider(): array
{
return [
'one package is dep' => [
[
self::createPackage('foo/bar1', ['foo/bar4']),
self::createPackage('foo/bar2', ['foo/bar4']),
self::createPackage('foo/bar3', ['foo/bar4']),
self::createPackage('foo/bar4', []),
],
[
'foo/bar4',
'foo/bar1',
'foo/bar2',
'foo/bar3',
],
],
'one package has more deps' => [
[
self::createPackage('foo/bar1', ['foo/bar2']),
self::createPackage('foo/bar2', ['foo/bar4']),
self::createPackage('foo/bar3', ['foo/bar4']),
self::createPackage('foo/bar4', []),
],
[
'foo/bar4',
'foo/bar2',
'foo/bar1',
'foo/bar3',
],
],
'package is required by many, but requires one other' => [
[
self::createPackage('foo/bar1', ['foo/bar3']),
self::createPackage('foo/bar2', ['foo/bar3']),
self::createPackage('foo/bar3', ['foo/bar4']),
self::createPackage('foo/bar4', []),
self::createPackage('foo/bar5', ['foo/bar3']),
self::createPackage('foo/bar6', ['foo/bar3']),
],
[
'foo/bar4',
'foo/bar3',
'foo/bar1',
'foo/bar2',
'foo/bar5',
'foo/bar6',
],
],
'one package has many requires' => [
[
self::createPackage('foo/bar1', ['foo/bar2']),
self::createPackage('foo/bar2', []),
self::createPackage('foo/bar3', ['foo/bar4']),
self::createPackage('foo/bar4', []),
self::createPackage('foo/bar5', ['foo/bar2']),
self::createPackage('foo/bar6', ['foo/bar2']),
],
[
'foo/bar2',
'foo/bar4',
'foo/bar1',
'foo/bar3',
'foo/bar5',
'foo/bar6',
],
],
'circular deps sorted alphabetically if weighted equally' => [
[
self::createPackage('foo/bar1', ['circular/part1']),
self::createPackage('foo/bar2', ['circular/part2']),
self::createPackage('circular/part1', ['circular/part2']),
self::createPackage('circular/part2', ['circular/part1']),
],
[
'circular/part1',
'circular/part2',
'foo/bar1',
'foo/bar2',
],
],
'equal weight sorted alphabetically' => [
[
self::createPackage('foo/bar10', ['foo/dep']),
self::createPackage('foo/bar2', ['foo/dep']),
self::createPackage('foo/baz', ['foo/dep']),
self::createPackage('foo/dep', []),
],
[
'foo/dep',
'foo/bar2',
'foo/bar10',
'foo/baz',
],
],
'pre-weighted packages bumped to top incl their deps' => [
[
self::createPackage('foo/bar', ['foo/dep']),
self::createPackage('foo/bar2', ['foo/dep2']),
self::createPackage('foo/dep', []),
self::createPackage('foo/dep2', []),
],
[
'foo/dep',
'foo/bar',
'foo/dep2',
'foo/bar2',
],
[
'foo/bar' => -1000,
],
],
];
}
/**
* @dataProvider sortingOrdersDependenciesHigherThanPackageDataProvider
*
* @param Package[] $packages
* @param string[] $expectedOrderedList
* @param array<string, int> $weights
*/
public function testSortingOrdersDependenciesHigherThanPackage(array $packages, array $expectedOrderedList, array $weights = []): void
{
$sortedPackages = PackageSorter::sortPackages($packages, $weights);
$sortedPackageNames = array_map(static function ($package): string {
return $package->getName();
}, $sortedPackages);
self::assertSame($expectedOrderedList, $sortedPackageNames);
}
/**
* @param string[] $requires
*/
private static function createPackage(string $name, array $requires): Package
{
$package = new Package($name, '1.0.0.0', '1.0.0');
$links = [];
foreach ($requires as $requireName) {
$links[$requireName] = new Link($package->getName(), $requireName, new MatchAllConstraint);
}
$package->setRequires($links);
return $package;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/TlsHelperTest.php | tests/Composer/Test/Util/TlsHelperTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Util\TlsHelper;
use Composer\Test\TestCase;
class TlsHelperTest extends TestCase
{
/**
* @dataProvider dataCheckCertificateHost
*
* @param string[] $certNames
*/
public function testCheckCertificateHost(bool $expectedResult, string $hostname, array $certNames): void
{
$certificate['subject']['commonName'] = $expectedCn = array_shift($certNames);
$certificate['extensions']['subjectAltName'] = $certNames ? 'DNS:'.implode(',DNS:', $certNames) : '';
// @phpstan-ignore staticMethod.deprecatedClass
$result = TlsHelper::checkCertificateHost($certificate, $hostname, $foundCn);
if (true === $expectedResult) {
self::assertTrue($result);
self::assertSame($expectedCn, $foundCn);
} else {
self::assertFalse($result);
self::assertNull($foundCn);
}
}
public static function dataCheckCertificateHost(): array
{
return [
[true, 'getcomposer.org', ['getcomposer.org']],
[true, 'getcomposer.org', ['getcomposer.org', 'packagist.org']],
[true, 'getcomposer.org', ['packagist.org', 'getcomposer.org']],
[true, 'foo.getcomposer.org', ['*.getcomposer.org']],
[false, 'xyz.foo.getcomposer.org', ['*.getcomposer.org']],
[true, 'foo.getcomposer.org', ['getcomposer.org', '*.getcomposer.org']],
[true, 'foo.getcomposer.org', ['foo.getcomposer.org', 'foo*.getcomposer.org']],
[true, 'foo1.getcomposer.org', ['foo.getcomposer.org', 'foo*.getcomposer.org']],
[true, 'foo2.getcomposer.org', ['foo.getcomposer.org', 'foo*.getcomposer.org']],
[false, 'foo2.another.getcomposer.org', ['foo.getcomposer.org', 'foo*.getcomposer.org']],
[false, 'test.example.net', ['**.example.net', '**.example.net']],
[false, 'test.example.net', ['t*t.example.net', 't*t.example.net']],
[false, 'xyz.example.org', ['*z.example.org', '*z.example.org']],
[false, 'foo.bar.example.com', ['foo.*.example.com', 'foo.*.example.com']],
[false, 'example.com', ['example.*', 'example.*']],
[true, 'localhost', ['localhost']],
[false, 'localhost', ['*']],
[false, 'localhost', ['local*']],
[false, 'example.net', ['*.net', '*.org', 'ex*.net']],
[true, 'example.net', ['*.net', '*.org', 'example.net']],
];
}
public function testGetCertificateNames(): void
{
$certificate['subject']['commonName'] = 'example.net';
$certificate['extensions']['subjectAltName'] = 'DNS: example.com, IP: 127.0.0.1, DNS: getcomposer.org, Junk: blah, DNS: composer.example.org';
// @phpstan-ignore staticMethod.deprecatedClass
$names = TlsHelper::getCertificateNames($certificate);
self::assertIsArray($names);
self::assertSame('example.net', $names['cn']);
self::assertSame([
'example.com',
'getcomposer.org',
'composer.example.org',
], $names['san']);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/ForgejoUrlTest.php | tests/Composer/Test/Util/ForgejoUrlTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Test\TestCase;
use Composer\Util\ForgejoUrl;
class ForgejoUrlTest extends TestCase
{
/**
* @dataProvider createProvider
*/
public function testCreate(?string $repoUrl): void
{
$forgejoUrl = ForgejoUrl::tryFrom($repoUrl);
$this->assertNotNull($forgejoUrl);
$this->assertSame('codeberg.org', $forgejoUrl->originUrl);
$this->assertSame('acme', $forgejoUrl->owner);
$this->assertSame('repo', $forgejoUrl->repository);
$this->assertSame('https://codeberg.org/api/v1/repos/acme/repo', $forgejoUrl->apiUrl);
}
public static function createProvider(): array
{
return [
['git@codeberg.org:acme/repo.git'],
['https://codeberg.org/acme/repo'],
['https://codeberg.org/acme/repo.git'],
];
}
public function testCreateInvalid(): void
{
$this->expectException(\InvalidArgumentException::class);
ForgejoUrl::create('https://example.org');
}
public function testGenerateSshUrl(): void
{
$forgejoUrl = ForgejoUrl::create('git@codeberg.org:acme/repo.git');
$this->assertSame('git@codeberg.org:acme/repo.git', $forgejoUrl->generateSshUrl());
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/AuthHelperTest.php | tests/Composer/Test/Util/AuthHelperTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\IO\IOInterface;
use Composer\Test\TestCase;
use Composer\Util\AuthHelper;
use Composer\Util\Bitbucket;
/**
* @author Michael Chekin <mchekin@gmail.com>
*/
class AuthHelperTest extends TestCase
{
/** @var IOInterface&\PHPUnit\Framework\MockObject\MockObject */
private $io;
/** @var \Composer\Config&\PHPUnit\Framework\MockObject\MockObject */
private $config;
/** @var AuthHelper */
private $authHelper;
protected function setUp(): void
{
$this->io = $this
->getMockBuilder('Composer\IO\IOInterface')
->disableOriginalConstructor()
->getMock();
$this->config = $this->getMockBuilder('Composer\Config')->getMock();
$this->authHelper = new AuthHelper($this->io, $this->config);
}
public function testAddAuthenticationHeaderWithoutAuthCredentials(): void
{
$headers = [
'Accept-Encoding: gzip',
'Connection: close',
];
$options = ['http' => ['header' => $headers]];
$origin = 'http://example.org';
$url = 'file://' . __FILE__;
$this->io->expects($this->once())
->method('hasAuthentication')
->with($origin)
->willReturn(false);
$options = $this->authHelper->addAuthenticationOptions($options, $origin, $url);
self::assertSame($headers, $options['http']['header']);
}
public function testAddAuthenticationHeaderWithBearerPassword(): void
{
$headers = [
'Accept-Encoding: gzip',
'Connection: close',
];
$options = ['http' => ['header' => $headers]];
$origin = 'http://example.org';
$url = 'file://' . __FILE__;
$auth = [
'username' => 'my_username',
'password' => 'bearer',
];
$this->expectsAuthentication($origin, $auth);
$expectedHeaders = array_merge($headers, ['Authorization: Bearer ' . $auth['username']]);
$options = $this->authHelper->addAuthenticationOptions($options, $origin, $url);
self::assertSame($expectedHeaders, $options['http']['header']);
}
public function testAddAuthenticationHeaderWithGithubToken(): void
{
$headers = [
'Accept-Encoding: gzip',
'Connection: close',
];
$options = ['http' => ['header' => $headers]];
$origin = 'github.com';
$url = 'https://api.github.com/';
$auth = [
'username' => 'my_username',
'password' => 'x-oauth-basic',
];
$this->expectsAuthentication($origin, $auth);
$this->io->expects($this->once())
->method('writeError')
->with('Using GitHub token authentication', true, IOInterface::DEBUG);
$expectedHeaders = array_merge($headers, ['Authorization: token ' . $auth['username']]);
$options = $this->authHelper->addAuthenticationOptions($options, $origin, $url);
self::assertSame($expectedHeaders, $options['http']['header']);
}
public function testAddAuthenticationHeaderWithGitlabOathToken(): void
{
$headers = [
'Accept-Encoding: gzip',
'Connection: close',
];
$options = ['http' => ['header' => $headers]];
$origin = 'gitlab.com';
$url = 'https://api.gitlab.com/';
$auth = [
'username' => 'my_username',
'password' => 'oauth2',
];
$this->expectsAuthentication($origin, $auth);
$this->config->expects($this->once())
->method('get')
->with('gitlab-domains')
->willReturn([$origin]);
$this->io->expects($this->once())
->method('writeError')
->with('Using GitLab OAuth token authentication', true, IOInterface::DEBUG);
$expectedHeaders = array_merge($headers, ['Authorization: Bearer ' . $auth['username']]);
$options = $this->authHelper->addAuthenticationOptions($options, $origin, $url);
self::assertSame($expectedHeaders, $options['http']['header']);
}
public function testAddAuthenticationOptionsForClientCertificate(): void
{
$options = [];
$origin = 'example.org';
$url = 'file://' . __FILE__;
$certificateConfiguration = [
'local_cert' => 'certificate value',
'local_pk' => 'key value',
'passphrase' => 'passphrase value',
];
$auth = [
'username' => 'client-certificate',
'password' => (string) json_encode($certificateConfiguration),
];
$this->expectsAuthentication($origin, $auth);
$options = $this->authHelper->addAuthenticationOptions($options, $origin, $url);
self::assertSame($certificateConfiguration, $options['ssl']);
}
public static function gitlabPrivateTokenProvider(): array
{
return [
['private-token'],
['gitlab-ci-token'],
];
}
/**
* @dataProvider gitlabPrivateTokenProvider
*/
public function testAddAuthenticationHeaderWithGitlabPrivateToken(string $password): void
{
$headers = [
'Accept-Encoding: gzip',
'Connection: close',
];
$options = ['http' => ['header' => $headers]];
$origin = 'gitlab.com';
$url = 'https://api.gitlab.com/';
$auth = [
'username' => 'my_username',
'password' => $password,
];
$this->expectsAuthentication($origin, $auth);
$this->config->expects($this->once())
->method('get')
->with('gitlab-domains')
->willReturn([$origin]);
$this->io->expects($this->once())
->method('writeError')
->with('Using GitLab private token authentication', true, IOInterface::DEBUG);
$expectedHeaders = array_merge($headers, ['PRIVATE-TOKEN: ' . $auth['username']]);
$options = $this->authHelper->addAuthenticationOptions($options, $origin, $url);
self::assertSame($expectedHeaders, $options['http']['header']);
}
public function testAddAuthenticationHeaderWithBitbucketOathToken(): void
{
$headers = [
'Accept-Encoding: gzip',
'Connection: close',
];
$options = ['http' => ['header' => $headers]];
$origin = 'bitbucket.org';
$url = 'https://bitbucket.org/site/oauth2/authorize';
$auth = [
'username' => 'x-token-auth',
'password' => 'my_password',
];
$this->expectsAuthentication($origin, $auth);
$this->io->expects($this->once())
->method('writeError')
->with('Using Bitbucket OAuth token authentication', true, IOInterface::DEBUG);
$expectedHeaders = array_merge($headers, ['Authorization: Bearer ' . $auth['password']]);
$options = $this->authHelper->addAuthenticationOptions($options, $origin, $url);
self::assertSame($expectedHeaders, $options['http']['header']);
}
public static function bitbucketPublicUrlProvider(): array
{
return [
['https://bitbucket.org/user/repo/downloads/whatever'],
['https://bbuseruploads.s3.amazonaws.com/9421ee72-638e-43a9-82ea-39cfaae2bfaa/downloads/b87c59d9-54f3-4922-b711-d89059ec3bcf'],
];
}
/**
* @dataProvider bitbucketPublicUrlProvider
*/
public function testAddAuthenticationHeaderWithBitbucketPublicUrl(string $url): void
{
$headers = [
'Accept-Encoding: gzip',
'Connection: close',
];
$options = ['http' => ['header' => $headers]];
$origin = 'bitbucket.org';
$auth = [
'username' => 'x-token-auth',
'password' => 'my_password',
];
$this->expectsAuthentication($origin, $auth);
$options = $this->authHelper->addAuthenticationOptions($options, $origin, $url);
self::assertSame($headers, $options['http']['header']);
}
public static function basicHttpAuthenticationProvider(): array
{
return [
[
Bitbucket::OAUTH2_ACCESS_TOKEN_URL,
'bitbucket.org',
[
'username' => 'x-token-auth',
'password' => 'my_password',
],
],
[
'https://some-api.url.com',
'some-api.url.com',
[
'username' => 'my_username',
'password' => 'my_password',
],
],
[
'https://gitlab.com',
'gitlab.com',
[
'username' => 'my_username',
'password' => 'my_password',
],
],
];
}
/**
* @dataProvider basicHttpAuthenticationProvider
*
* @param array<string, string|null> $auth
*
* @phpstan-param array{username: string|null, password: string|null} $auth
*/
public function testAddAuthenticationHeaderWithBasicHttpAuthentication(string $url, string $origin, array $auth): void
{
$headers = [
'Accept-Encoding: gzip',
'Connection: close',
];
$options = ['http' => ['header' => $headers]];
$this->expectsAuthentication($origin, $auth);
$this->io->expects($this->once())
->method('writeError')
->with(
'Using HTTP basic authentication with username "' . $auth['username'] . '"',
true,
IOInterface::DEBUG
);
$expectedHeaders = array_merge(
$headers,
['Authorization: Basic ' . base64_encode($auth['username'] . ':' . $auth['password'])]
);
$options = $this->authHelper->addAuthenticationOptions($options, $origin, $url);
self::assertSame($expectedHeaders, $options['http']['header']);
}
/**
* Tests that custom HTTP headers are correctly added to the request when using
* the 'custom-headers' authentication type.
*/
public function testAddAuthenticationHeaderWithCustomHeaders(): void
{
$headers = [
'Accept-Encoding: gzip',
'Connection: close',
];
$origin = 'example.org';
$url = 'https://example.org/packages.json';
$customHeaders = [
'API-TOKEN: abc123',
'X-CUSTOM-HEADER: value',
];
$headersJson = json_encode($customHeaders);
// Ensure we have a string, not false from json_encode failure
$auth = [
'username' => $headersJson !== false ? $headersJson : null,
'password' => 'custom-headers',
];
$this->expectsAuthentication($origin, $auth);
$this->io->expects($this->once())
->method('writeError')
->with('Using custom HTTP headers for authentication', true, IOInterface::DEBUG);
$expectedHeaders = array_merge($headers, $customHeaders);
self::assertSame(
$expectedHeaders,
$this->authHelper->addAuthenticationHeader($headers, $origin, $url)
);
}
/**
* @dataProvider bitbucketPublicUrlProvider
*/
public function testIsPublicBitBucketDownloadWithBitbucketPublicUrl(string $url): void
{
self::assertTrue($this->authHelper->isPublicBitBucketDownload($url));
}
public function testIsPublicBitBucketDownloadWithNonBitbucketPublicUrl(): void
{
self::assertFalse(
$this->authHelper->isPublicBitBucketDownload(
'https://bitbucket.org/site/oauth2/authorize'
)
);
}
public function testStoreAuthAutomatically(): void
{
$origin = 'github.com';
$storeAuth = true;
$auth = [
'username' => 'my_username',
'password' => 'my_password',
];
/** @var \Composer\Config\ConfigSourceInterface&\PHPUnit\Framework\MockObject\MockObject $configSource */
$configSource = $this
->getMockBuilder('Composer\Config\ConfigSourceInterface')
->disableOriginalConstructor()
->getMock();
$this->config->expects($this->once())
->method('getAuthConfigSource')
->willReturn($configSource);
$this->io->expects($this->once())
->method('getAuthentication')
->with($origin)
->willReturn($auth);
$configSource->expects($this->once())
->method('addConfigSetting')
->with('http-basic.'.$origin, $auth);
$this->authHelper->storeAuth($origin, $storeAuth);
}
public function testStoreAuthWithPromptYesAnswer(): void
{
$origin = 'github.com';
$storeAuth = 'prompt';
$auth = [
'username' => 'my_username',
'password' => 'my_password',
];
$answer = 'y';
$configSourceName = 'https://api.gitlab.com/source';
/** @var \Composer\Config\ConfigSourceInterface&\PHPUnit\Framework\MockObject\MockObject $configSource */
$configSource = $this
->getMockBuilder('Composer\Config\ConfigSourceInterface')
->disableOriginalConstructor()
->getMock();
$this->config->expects($this->once())
->method('getAuthConfigSource')
->willReturn($configSource);
$configSource->expects($this->once())
->method('getName')
->willReturn($configSourceName);
$this->io->expects($this->once())
->method('askAndValidate')
->with(
'Do you want to store credentials for '.$origin.' in '.$configSourceName.' ? [Yn] ',
$this->anything(),
null,
'y'
)
->willReturnCallback(static function ($question, $validator, $attempts, $default) use ($answer): string {
$validator($answer);
return $answer;
});
$this->io->expects($this->once())
->method('getAuthentication')
->with($origin)
->willReturn($auth);
$configSource->expects($this->once())
->method('addConfigSetting')
->with('http-basic.'.$origin, $auth);
$this->authHelper->storeAuth($origin, $storeAuth);
}
public function testStoreAuthWithPromptNoAnswer(): void
{
$origin = 'github.com';
$storeAuth = 'prompt';
$answer = 'n';
$configSourceName = 'https://api.gitlab.com/source';
/** @var \Composer\Config\ConfigSourceInterface&\PHPUnit\Framework\MockObject\MockObject $configSource */
$configSource = $this
->getMockBuilder('Composer\Config\ConfigSourceInterface')
->disableOriginalConstructor()
->getMock();
$this->config->expects($this->once())
->method('getAuthConfigSource')
->willReturn($configSource);
$configSource->expects($this->once())
->method('getName')
->willReturn($configSourceName);
$this->io->expects($this->once())
->method('askAndValidate')
->with(
'Do you want to store credentials for '.$origin.' in '.$configSourceName.' ? [Yn] ',
$this->anything(),
null,
'y'
)
->willReturnCallback(static function ($question, $validator, $attempts, $default) use ($answer): string {
$validator($answer);
return $answer;
});
$this->authHelper->storeAuth($origin, $storeAuth);
}
public function testStoreAuthWithPromptInvalidAnswer(): void
{
self::expectException('RuntimeException');
$origin = 'github.com';
$storeAuth = 'prompt';
$answer = 'invalid';
$configSourceName = 'https://api.gitlab.com/source';
/** @var \Composer\Config\ConfigSourceInterface&\PHPUnit\Framework\MockObject\MockObject $configSource */
$configSource = $this
->getMockBuilder('Composer\Config\ConfigSourceInterface')
->disableOriginalConstructor()
->getMock();
$this->config->expects($this->once())
->method('getAuthConfigSource')
->willReturn($configSource);
$configSource->expects($this->once())
->method('getName')
->willReturn($configSourceName);
$this->io->expects($this->once())
->method('askAndValidate')
->with(
'Do you want to store credentials for '.$origin.' in '.$configSourceName.' ? [Yn] ',
$this->anything(),
null,
'y'
)
->willReturnCallback(static function ($question, $validator, $attempts, $default) use ($answer): string {
$validator($answer);
return $answer;
});
$this->authHelper->storeAuth($origin, $storeAuth);
}
public function testPromptAuthIfNeededGitLabNoAuthChange(): void
{
self::expectException('Composer\Downloader\TransportException');
$origin = 'gitlab.com';
$this->io
->method('hasAuthentication')
->with($origin)
->willReturn(true);
$this->io
->method('getAuthentication')
->with($origin)
->willReturn([
'username' => 'gitlab-user',
'password' => 'gitlab-password',
]);
$this->io
->expects($this->once())
->method('setAuthentication')
->with('gitlab.com', 'gitlab-user', 'gitlab-password');
$this->config
->method('get')
->willReturnMap([
['github-domains', 0, []],
['gitlab-domains', 0, ['gitlab.com']],
['gitlab-token', 0, ['gitlab.com' => ['username' => 'gitlab-user', 'token' => 'gitlab-password']]],
]);
$this->authHelper->promptAuthIfNeeded('https://gitlab.com/acme/archive.zip', $origin, 404, 'GitLab requires authentication and it was not provided');
}
public function testPromptAuthIfNeededMultipleBitbucketDownloads(): void
{
$origin = 'bitbucket.org';
$expectedResult = [
'retry' => true,
'storeAuth' => false,
];
$authConfig = [
'bitbucket.org' => [
'access-token' => 'bitbucket_access_token',
'access-token-expiration' => time() + 1800,
],
];
$this->config
->method('get')
->willReturnMap([
['github-domains', 0, []],
['gitlab-domains', 0, []],
['bitbucket-oauth', 0, $authConfig],
['github-domains', 0, []],
['gitlab-domains', 0, []],
]);
$this->io
->expects($this->exactly(2))
->method('hasAuthentication')
->with($origin)
->willReturn(true);
$getAuthenticationReturnValues = [
['username' => 'bitbucket_client_id', 'password' => 'bitbucket_client_secret'],
['username' => 'x-token-auth', 'password' => 'bitbucket_access_token'],
];
$this->io
->expects($this->exactly(2))
->method('getAuthentication')
->willReturnCallback(
static function ($repositoryName) use (&$getAuthenticationReturnValues) {
return array_shift($getAuthenticationReturnValues);
}
);
$this->io
->expects($this->once())
->method('setAuthentication')
->with($origin, 'x-token-auth', 'bitbucket_access_token');
$result1 = $this->authHelper->promptAuthIfNeeded('https://bitbucket.org/workspace/repo1/get/hash1.zip', $origin, 401, 'HTTP/2 401 ');
$result2 = $this->authHelper->promptAuthIfNeeded('https://bitbucket.org/workspace/repo2/get/hash2.zip', $origin, 401, 'HTTP/2 401 ');
self::assertSame(
$expectedResult,
$result1
);
self::assertSame(
$expectedResult,
$result2
);
}
/**
* @dataProvider basicHttpAuthenticationProvider
* @param array<string, string|null> $auth
* @phpstan-param array{username: string|null, password: string|null} $auth
*/
public function testAddAuthenticationHeaderIsWorking(string $url, string $origin, array $auth): void
{
set_error_handler(
static function (): bool {
return true;
},
E_USER_DEPRECATED
);
$this->expectsAuthentication($origin, $auth);
$headers = [
'Accept-Encoding: gzip',
'Connection: close',
];
$this->expectsAuthentication($origin, $auth);
try {
$updatedHeaders = $this->authHelper->addAuthenticationHeader($headers, $origin, $url);
} finally {
restore_error_handler();
}
$this->assertIsArray($updatedHeaders);
}
public function testAddAuthenticationHeaderDeprecation(): void
{
set_error_handler(
static function (int $errno, string $errstr) {
throw new \RuntimeException($errstr);
},
E_USER_DEPRECATED
);
$headers = [];
$origin = 'example.org';
$url = 'file://' . __FILE__;
$expectedException = new \RuntimeException('AuthHelper::addAuthenticationHeader is deprecated since Composer 2.9 use addAuthenticationOptions instead.');
$this->expectExceptionObject($expectedException);
try {
$this->authHelper->addAuthenticationHeader($headers, $origin, $url);
} finally {
restore_error_handler();
}
}
/**
* @param array<string, string|null> $auth
*
* @phpstan-param array{username: string|null, password: string|null} $auth
*/
private function expectsAuthentication(string $origin, array $auth): void
{
$this->io->expects($this->once())
->method('hasAuthentication')
->with($origin)
->willReturn(true);
$this->io->expects($this->once())
->method('getAuthentication')
->with($origin)
->willReturn($auth);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/GitHubTest.php | tests/Composer/Test/Util/GitHubTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Util\GitHub;
use Composer\Test\TestCase;
/**
* @author Rob Bast <rob.bast@gmail.com>
*/
class GitHubTest extends TestCase
{
/** @var string */
private $password = 'password';
/** @var string */
private $message = 'mymessage';
/** @var string */
private $origin = 'github.com';
public function testUsernamePasswordAuthenticationFlow(): void
{
$io = $this->getIOMock();
$io->expects([
['text' => $this->message],
['ask' => 'Token (hidden): ', 'reply' => $this->password],
]);
$httpDownloader = $this->getHttpDownloaderMock();
$httpDownloader->expects(
[['url' => sprintf('https://api.%s/', $this->origin), 'body' => '{}']],
true
);
$config = $this->getConfigMock();
$config
->expects($this->exactly(2))
->method('getAuthConfigSource')
->willReturn($this->getAuthJsonMock())
;
$config
->expects($this->once())
->method('getConfigSource')
->willReturn($this->getConfJsonMock())
;
$github = new GitHub($io, $config, null, $httpDownloader);
self::assertTrue($github->authorizeOAuthInteractively($this->origin, $this->message));
}
public function testUsernamePasswordFailure(): void
{
$io = $this->getIOMock();
$io->expects([
['ask' => 'Token (hidden): ', 'reply' => $this->password],
]);
$httpDownloader = $this->getHttpDownloaderMock();
$httpDownloader->expects(
[['url' => sprintf('https://api.%s/', $this->origin), 'status' => 401]],
true
);
$config = $this->getConfigMock();
$config
->expects($this->exactly(1))
->method('getAuthConfigSource')
->willReturn($this->getAuthJsonMock())
;
$github = new GitHub($io, $config, null, $httpDownloader);
self::assertFalse($github->authorizeOAuthInteractively($this->origin));
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Config
*/
private function getConfigMock()
{
return $this->getMockBuilder('Composer\Config')->getMock();
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Config\JsonConfigSource
*/
private function getAuthJsonMock()
{
$authjson = $this
->getMockBuilder('Composer\Config\JsonConfigSource')
->disableOriginalConstructor()
->getMock()
;
$authjson
->expects($this->atLeastOnce())
->method('getName')
->willReturn('auth.json')
;
return $authjson;
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Config\JsonConfigSource
*/
private function getConfJsonMock()
{
$confjson = $this
->getMockBuilder('Composer\Config\JsonConfigSource')
->disableOriginalConstructor()
->getMock()
;
$confjson
->expects($this->atLeastOnce())
->method('removeConfigSetting')
->with('github-oauth.'.$this->origin)
;
return $confjson;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/BitbucketTest.php | tests/Composer/Test/Util/BitbucketTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Test\Mock\IOMock;
use Composer\Util\Bitbucket;
use Composer\Util\Http\Response;
use Composer\Test\TestCase;
/**
* @author Paul Wenke <wenke.paul@gmail.com>
*/
class BitbucketTest extends TestCase
{
/** @var string */
private $username = 'username';
/** @var string */
private $password = 'password';
/** @var string */
private $consumer_key = 'consumer_key';
/** @var string */
private $consumer_secret = 'consumer_secret';
/** @var string */
private $message = 'mymessage';
/** @var string */
private $origin = 'bitbucket.org';
/** @var string */
private $token = 'bitbuckettoken';
/** @var IOMock */
private $io;
/** @var \Composer\Util\HttpDownloader&\PHPUnit\Framework\MockObject\MockObject */
private $httpDownloader;
/** @var \Composer\Config&\PHPUnit\Framework\MockObject\MockObject */
private $config;
/** @var Bitbucket */
private $bitbucket;
/** @var int */
private $time;
protected function setUp(): void
{
$this->io = $this->getIOMock();
$this->httpDownloader = $this
->getMockBuilder('Composer\Util\HttpDownloader')
->disableOriginalConstructor()
->getMock()
;
$this->config = $this->getMockBuilder('Composer\Config')->getMock();
$this->time = time();
$this->bitbucket = new Bitbucket($this->io, $this->config, null, $this->httpDownloader, $this->time);
}
public function testRequestAccessTokenWithValidOAuthConsumer(): void
{
$this->io->expects([
['auth' => [$this->origin, $this->consumer_key, $this->consumer_secret]],
]);
$this->httpDownloader->expects($this->once())
->method('get')
->with(
Bitbucket::OAUTH2_ACCESS_TOKEN_URL,
[
'retry-auth-failure' => false,
'http' => [
'method' => 'POST',
'content' => 'grant_type=client_credentials',
],
]
)
->willReturn(
new Response(
['url' => Bitbucket::OAUTH2_ACCESS_TOKEN_URL],
200,
[],
sprintf(
'{"access_token": "%s", "scopes": "repository", "expires_in": 3600, "refresh_token": "refreshtoken", "token_type": "bearer"}',
$this->token
)
)
);
$this->config->expects($this->once())
->method('get')
->with('bitbucket-oauth')
->willReturn(null);
$this->setExpectationsForStoringAccessToken();
self::assertEquals(
$this->token,
$this->bitbucket->requestToken($this->origin, $this->consumer_key, $this->consumer_secret)
);
}
public function testRequestAccessTokenWithValidOAuthConsumerAndValidStoredAccessToken(): Bitbucket
{
$this->config->expects($this->once())
->method('get')
->with('bitbucket-oauth')
->willReturn(
[
$this->origin => [
'access-token' => $this->token,
'access-token-expiration' => $this->time + 1800,
'consumer-key' => $this->consumer_key,
'consumer-secret' => $this->consumer_secret,
],
]
);
self::assertEquals(
$this->token,
$this->bitbucket->requestToken($this->origin, $this->consumer_key, $this->consumer_secret)
);
return $this->bitbucket;
}
public function testRequestAccessTokenWithValidOAuthConsumerAndExpiredAccessToken(): void
{
$this->config->expects($this->once())
->method('get')
->with('bitbucket-oauth')
->willReturn(
[
$this->origin => [
'access-token' => 'randomExpiredToken',
'access-token-expiration' => $this->time - 400,
'consumer-key' => $this->consumer_key,
'consumer-secret' => $this->consumer_secret,
],
]
);
$this->io->expects([
['auth' => [$this->origin, $this->consumer_key, $this->consumer_secret]],
]);
$this->httpDownloader->expects($this->once())
->method('get')
->with(
Bitbucket::OAUTH2_ACCESS_TOKEN_URL,
[
'retry-auth-failure' => false,
'http' => [
'method' => 'POST',
'content' => 'grant_type=client_credentials',
],
]
)
->willReturn(
new Response(
['url' => Bitbucket::OAUTH2_ACCESS_TOKEN_URL],
200,
[],
sprintf(
'{"access_token": "%s", "scopes": "repository", "expires_in": 3600, "refresh_token": "refreshtoken", "token_type": "bearer"}',
$this->token
)
)
);
$this->setExpectationsForStoringAccessToken();
self::assertEquals(
$this->token,
$this->bitbucket->requestToken($this->origin, $this->consumer_key, $this->consumer_secret)
);
}
public function testRequestAccessTokenWithUsernameAndPassword(): void
{
$this->io->expects([
['auth' => [$this->origin, $this->username, $this->password]],
['text' => 'Invalid OAuth consumer provided.'],
['text' => 'This can have three reasons:'],
['text' => '1. You are authenticating with a bitbucket username/password combination'],
['text' => '2. You are using an OAuth consumer, but didn\'t configure a (dummy) callback url'],
['text' => '3. You are using an OAuth consumer, but didn\'t configure it as private consumer'],
], true);
$this->httpDownloader->expects($this->once())
->method('get')
->with(
Bitbucket::OAUTH2_ACCESS_TOKEN_URL,
[
'retry-auth-failure' => false,
'http' => [
'method' => 'POST',
'content' => 'grant_type=client_credentials',
],
]
)
->willThrowException(
new \Composer\Downloader\TransportException(
sprintf(
'The \'%s\' URL could not be accessed: HTTP/1.1 400 BAD REQUEST',
Bitbucket::OAUTH2_ACCESS_TOKEN_URL
),
400
)
);
$this->config->expects($this->once())
->method('get')
->with('bitbucket-oauth')
->willReturn(null);
self::assertEquals('', $this->bitbucket->requestToken($this->origin, $this->username, $this->password));
}
public function testRequestAccessTokenWithUsernameAndPasswordWithUnauthorizedResponse(): void
{
$this->config->expects($this->once())
->method('get')
->with('bitbucket-oauth')
->willReturn(null);
$this->io->expects([
['auth' => [$this->origin, $this->username, $this->password]],
['text' => 'Invalid OAuth consumer provided.'],
['text' => 'You can also add it manually later by using "composer config --global --auth bitbucket-oauth.bitbucket.org <consumer-key> <consumer-secret>"'],
], true);
$this->httpDownloader->expects($this->once())
->method('get')
->with(
Bitbucket::OAUTH2_ACCESS_TOKEN_URL,
[
'retry-auth-failure' => false,
'http' => [
'method' => 'POST',
'content' => 'grant_type=client_credentials',
],
]
)
->willThrowException(new \Composer\Downloader\TransportException('HTTP/1.1 401 UNAUTHORIZED', 401));
self::assertEquals('', $this->bitbucket->requestToken($this->origin, $this->username, $this->password));
}
public function testRequestAccessTokenWithUsernameAndPasswordWithNotFoundResponse(): void
{
self::expectException('Composer\Downloader\TransportException');
$this->config->expects($this->once())
->method('get')
->with('bitbucket-oauth')
->willReturn(null);
$this->io->expects([
['auth' => [$this->origin, $this->username, $this->password]],
]);
$exception = new \Composer\Downloader\TransportException('HTTP/1.1 404 NOT FOUND', 404);
$this->httpDownloader->expects($this->once())
->method('get')
->with(
Bitbucket::OAUTH2_ACCESS_TOKEN_URL,
[
'retry-auth-failure' => false,
'http' => [
'method' => 'POST',
'content' => 'grant_type=client_credentials',
],
]
)
->willThrowException($exception);
$this->bitbucket->requestToken($this->origin, $this->username, $this->password);
}
public function testUsernamePasswordAuthenticationFlow(): void
{
$this->io->expects([
['text' => $this->message],
['ask' => 'Consumer Key (hidden): ', 'reply' => $this->consumer_key],
['ask' => 'Consumer Secret (hidden): ', 'reply' => $this->consumer_secret],
]);
$this->httpDownloader
->expects($this->once())
->method('get')
->with(
$this->equalTo($url = sprintf('https://%s/site/oauth2/access_token', $this->origin)),
$this->anything()
)
->willReturn(
new Response(
['url' => $url],
200,
[],
sprintf(
'{"access_token": "%s", "scopes": "repository", "expires_in": 3600, "refresh_token": "refresh_token", "token_type": "bearer"}',
$this->token
)
)
)
;
$this->setExpectationsForStoringAccessToken(true);
self::assertTrue($this->bitbucket->authorizeOAuthInteractively($this->origin, $this->message));
}
public function testAuthorizeOAuthInteractivelyWithEmptyUsername(): void
{
$authConfigSourceMock = $this->getMockBuilder('Composer\Config\ConfigSourceInterface')->getMock();
$this->config->expects($this->atLeastOnce())
->method('getAuthConfigSource')
->willReturn($authConfigSourceMock);
$this->io->expects([
['ask' => 'Consumer Key (hidden): ', 'reply' => ''],
]);
self::assertFalse($this->bitbucket->authorizeOAuthInteractively($this->origin, $this->message));
}
public function testAuthorizeOAuthInteractivelyWithEmptyPassword(): void
{
$authConfigSourceMock = $this->getMockBuilder('Composer\Config\ConfigSourceInterface')->getMock();
$this->config->expects($this->atLeastOnce())
->method('getAuthConfigSource')
->willReturn($authConfigSourceMock);
$this->io->expects([
['text' => $this->message],
['ask' => 'Consumer Key (hidden): ', 'reply' => $this->consumer_key],
['ask' => 'Consumer Secret (hidden): ', 'reply' => ''],
]);
self::assertFalse($this->bitbucket->authorizeOAuthInteractively($this->origin, $this->message));
}
public function testAuthorizeOAuthInteractivelyWithRequestAccessTokenFailure(): void
{
$authConfigSourceMock = $this->getMockBuilder('Composer\Config\ConfigSourceInterface')->getMock();
$this->config->expects($this->atLeastOnce())
->method('getAuthConfigSource')
->willReturn($authConfigSourceMock);
$this->io->expects([
['text' => $this->message],
['ask' => 'Consumer Key (hidden): ', 'reply' => $this->consumer_key],
['ask' => 'Consumer Secret (hidden): ', 'reply' => $this->consumer_secret],
]);
$this->httpDownloader
->expects($this->once())
->method('get')
->with(
$this->equalTo($url = sprintf('https://%s/site/oauth2/access_token', $this->origin)),
$this->anything()
)
->willThrowException(
new \Composer\Downloader\TransportException(
sprintf(
'The \'%s\' URL could not be accessed: HTTP/1.1 400 BAD REQUEST',
Bitbucket::OAUTH2_ACCESS_TOKEN_URL
),
400
)
);
self::assertFalse($this->bitbucket->authorizeOAuthInteractively($this->origin, $this->message));
}
private function setExpectationsForStoringAccessToken(bool $removeBasicAuth = false): void
{
$configSourceMock = $this->getMockBuilder('Composer\Config\ConfigSourceInterface')->getMock();
$this->config->expects($this->once())
->method('getConfigSource')
->willReturn($configSourceMock);
$configSourceMock->expects($this->once())
->method('removeConfigSetting')
->with('bitbucket-oauth.' . $this->origin);
$authConfigSourceMock = $this->getMockBuilder('Composer\Config\ConfigSourceInterface')->getMock();
$this->config->expects($this->atLeastOnce())
->method('getAuthConfigSource')
->willReturn($authConfigSourceMock);
$authConfigSourceMock->expects($this->once())
->method('addConfigSetting')
->with(
'bitbucket-oauth.' . $this->origin,
[
"consumer-key" => $this->consumer_key,
"consumer-secret" => $this->consumer_secret,
"access-token" => $this->token,
"access-token-expiration" => $this->time + 3600,
]
);
if ($removeBasicAuth) {
$authConfigSourceMock->expects($this->once())
->method('removeConfigSetting')
->with('http-basic.' . $this->origin);
}
}
public function testGetTokenWithoutAccessToken(): void
{
self::assertSame('', $this->bitbucket->getToken());
}
/**
* @depends testRequestAccessTokenWithValidOAuthConsumerAndValidStoredAccessToken
*/
public function testGetTokenWithAccessToken(Bitbucket $bitbucket): void
{
self::assertSame($this->token, $bitbucket->getToken());
}
public function testAuthorizeOAuthWithWrongOriginUrl(): void
{
self::assertFalse($this->bitbucket->authorizeOAuth('non-' . $this->origin));
}
public function testAuthorizeOAuthWithoutAvailableGitConfigToken(): void
{
$process = $this->getProcessExecutorMock();
$process->expects([], false, ['return' => -1]);
$bitbucket = new Bitbucket($this->io, $this->config, $process, $this->httpDownloader, $this->time);
self::assertFalse($bitbucket->authorizeOAuth($this->origin));
}
public function testAuthorizeOAuthWithAvailableGitConfigToken(): void
{
$process = $this->getProcessExecutorMock();
$bitbucket = new Bitbucket($this->io, $this->config, $process, $this->httpDownloader, $this->time);
self::assertTrue($bitbucket->authorizeOAuth($this->origin));
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/MetadataMinifierTest.php | tests/Composer/Test/Util/MetadataMinifierTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\MetadataMinifier\MetadataMinifier;
use Composer\Package\CompletePackage;
use Composer\Package\Dumper\ArrayDumper;
use PHPUnit\Framework\TestCase;
class MetadataMinifierTest extends TestCase
{
public function testMinifyExpand(): void
{
$package1 = new CompletePackage('foo/bar', '2.0.0.0', '2.0.0');
$package1->setScripts(['foo' => ['bar']]);
$package1->setLicense(['MIT']);
$package2 = new CompletePackage('foo/bar', '1.2.0.0', '1.2.0');
$package2->setLicense(['GPL']);
$package2->setHomepage('https://example.org');
$package3 = new CompletePackage('foo/bar', '1.0.0.0', '1.0.0');
$package3->setLicense(['GPL']);
$dumper = new ArrayDumper();
$minified = [
['name' => 'foo/bar', 'version' => '2.0.0', 'version_normalized' => '2.0.0.0', 'type' => 'library', 'scripts' => ['foo' => ['bar']], 'license' => ['MIT']],
['version' => '1.2.0', 'version_normalized' => '1.2.0.0', 'license' => ['GPL'], 'homepage' => 'https://example.org', 'scripts' => '__unset'],
['version' => '1.0.0', 'version_normalized' => '1.0.0.0', 'homepage' => '__unset'],
];
$source = [$dumper->dump($package1), $dumper->dump($package2), $dumper->dump($package3)];
self::assertSame($minified, MetadataMinifier::minify($source));
self::assertSame($source, MetadataMinifier::expand($minified));
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/PlatformTest.php | tests/Composer/Test/Util/PlatformTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Util\Platform;
use Composer\Test\TestCase;
/**
* PlatformTest
*
* @author Niels Keurentjes <niels.keurentjes@omines.com>
*/
class PlatformTest extends TestCase
{
public function testExpandPath(): void
{
putenv('TESTENV=/home/test');
self::assertEquals('/home/test/myPath', Platform::expandPath('%TESTENV%/myPath'));
self::assertEquals('/home/test/myPath', Platform::expandPath('$TESTENV/myPath'));
self::assertEquals((getenv('HOME') ?: getenv('USERPROFILE')) . '/test', Platform::expandPath('~/test'));
}
public function testIsWindows(): void
{
// Compare 2 common tests for Windows to the built-in Windows test
self::assertEquals(('\\' === DIRECTORY_SEPARATOR), Platform::isWindows());
self::assertEquals(defined('PHP_WINDOWS_VERSION_MAJOR'), Platform::isWindows());
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/GitTest.php | tests/Composer/Test/Util/GitTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Config;
use Composer\IO\IOInterface;
use Composer\Util\Filesystem;
use Composer\Util\Git;
use Composer\Test\Mock\ProcessExecutorMock;
use Composer\Test\TestCase;
class GitTest extends TestCase
{
/** @var Git */
private $git;
/** @var IOInterface&\PHPUnit\Framework\MockObject\MockObject */
private $io;
/** @var Config&\PHPUnit\Framework\MockObject\MockObject */
private $config;
/** @var ProcessExecutorMock */
private $process;
/** @var Filesystem&\PHPUnit\Framework\MockObject\MockObject */
private $fs;
protected function setUp(): void
{
$this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$this->config = $this->getMockBuilder('Composer\Config')->disableOriginalConstructor()->getMock();
$this->process = $this->getProcessExecutorMock();
$this->fs = $this->getMockBuilder('Composer\Util\Filesystem')->disableOriginalConstructor()->getMock();
$this->git = new Git($this->io, $this->config, $this->process, $this->fs);
}
/**
* @dataProvider publicGithubNoCredentialsProvider
*/
public function testRunCommandPublicGitHubRepositoryNotInitialClone(string $protocol, string $expectedUrl): void
{
$commandCallable = static function ($url) use ($expectedUrl): string {
self::assertSame($expectedUrl, $url);
return 'git command';
};
$this->mockConfig($protocol);
$this->process->expects(['git command'], true);
// @phpstan-ignore method.deprecated
$this->git->runCommand($commandCallable, 'https://github.com/acme/repo', null, true);
}
public static function publicGithubNoCredentialsProvider(): array
{
return [
['ssh', 'git@github.com:acme/repo'],
['https', 'https://github.com/acme/repo'],
];
}
public function testRunCommandPrivateGitHubRepositoryNotInitialCloneNotInteractiveWithoutAuthentication(): void
{
self::expectException('RuntimeException');
$commandCallable = static function ($url): string {
self::assertSame('https://github.com/acme/repo', $url);
return 'git command';
};
$this->mockConfig('https');
$this->process->expects([
['cmd' => 'git command', 'return' => 1],
['cmd' => ['git', '--version'], 'return' => 0],
], true);
// @phpstan-ignore method.deprecated
$this->git->runCommand($commandCallable, 'https://github.com/acme/repo', null, true);
}
/**
* @dataProvider privateGithubWithCredentialsProvider
*/
public function testRunCommandPrivateGitHubRepositoryNotInitialCloneNotInteractiveWithAuthentication(string $gitUrl, string $protocol, string $gitHubToken, string $expectedUrl, int $expectedFailuresBeforeSuccess): void
{
$commandCallable = static function ($url) use ($expectedUrl): string {
if ($url !== $expectedUrl) {
return 'git command failing';
}
return 'git command ok';
};
$this->mockConfig($protocol);
$expectedCalls = array_fill(0, $expectedFailuresBeforeSuccess, ['cmd' => 'git command failing', 'return' => 1]);
$expectedCalls[] = ['cmd' => 'git command ok', 'return' => 0];
$this->process->expects($expectedCalls, true);
$this->io
->method('isInteractive')
->willReturn(false);
$this->io
->expects($this->atLeastOnce())
->method('hasAuthentication')
->with($this->equalTo('github.com'))
->willReturn(true);
$this->io
->expects($this->atLeastOnce())
->method('getAuthentication')
->with($this->equalTo('github.com'))
->willReturn(['username' => 'token', 'password' => $gitHubToken]);
// @phpstan-ignore method.deprecated
$this->git->runCommand($commandCallable, $gitUrl, null, true);
}
/**
* @dataProvider privateBitbucketWithCredentialsProvider
*/
public function testRunCommandPrivateBitbucketRepositoryNotInitialCloneNotInteractiveWithAuthentication(string $gitUrl, ?string $bitbucketToken, string $expectedUrl, int $expectedFailuresBeforeSuccess, int $bitbucket_git_auth_calls = 0): void
{
$commandCallable = static function ($url) use ($expectedUrl): string {
if ($url !== $expectedUrl) {
return 'git command failing';
}
return 'git command ok';
};
$this->config
->method('get')
->willReturnMap([
['gitlab-domains', 0, ['gitlab.com']],
['github-domains', 0, ['github.com']],
]);
$expectedCalls = array_fill(0, $expectedFailuresBeforeSuccess, ['cmd' => 'git command failing', 'return' => 1]);
if ($bitbucket_git_auth_calls > 0) {
// When we are testing what happens without auth saved, and URLs
// with https, there will also be an attempt to find the token in
// the git config for the folder and repo, locally.
$additional_calls = array_fill(0, $bitbucket_git_auth_calls, ['cmd' => ['git', 'config', 'bitbucket.accesstoken'], 'return' => 1]);
foreach ($additional_calls as $call) {
$expectedCalls[] = $call;
}
}
$expectedCalls[] = ['cmd' => 'git command ok', 'return' => 0];
$this->process->expects($expectedCalls, true);
$this->io
->method('isInteractive')
->willReturn(false);
if (null !== $bitbucketToken) {
$this->io
->expects($this->atLeastOnce())
->method('hasAuthentication')
->with($this->equalTo('bitbucket.org'))
->willReturn(true);
$this->io
->expects($this->atLeastOnce())
->method('getAuthentication')
->with($this->equalTo('bitbucket.org'))
->willReturn(['username' => 'token', 'password' => $bitbucketToken]);
}
// @phpstan-ignore method.deprecated
$this->git->runCommand($commandCallable, $gitUrl, null, true);
}
/**
* @dataProvider privateBitbucketWithOauthProvider
*
* @param array{'username': string, 'password': string}[] $initial_config
*/
public function testRunCommandPrivateBitbucketRepositoryNotInitialCloneInteractiveWithOauth(string $gitUrl, string $expectedUrl, array $initial_config = []): void
{
$commandCallable = static function ($url) use ($expectedUrl): string {
if ($url !== $expectedUrl) {
return 'git command failing';
}
return 'git command ok';
};
$expectedCalls = [];
$expectedCalls[] = ['cmd' => 'git command failing', 'return' => 1];
if (count($initial_config) > 0) {
$expectedCalls[] = ['cmd' => 'git command failing', 'return' => 1];
} else {
$expectedCalls[] = ['cmd' => ['git', 'config', 'bitbucket.accesstoken'], 'return' => 1];
}
$expectedCalls[] = ['cmd' => 'git command ok', 'return' => 0];
$this->process->expects($expectedCalls, true);
$this->config
->method('get')
->willReturnMap([
['gitlab-domains', 0, ['gitlab.com']],
['github-domains', 0, ['github.com']],
]);
$this->io
->method('isInteractive')
->willReturn(true);
$this->io
->method('askConfirmation')
->willReturnCallback(static function () {
return true;
});
$this->io->method('askAndHideAnswer')
->willReturnCallback(static function ($question) {
switch ($question) {
case 'Consumer Key (hidden): ':
return 'my-consumer-key';
case 'Consumer Secret (hidden): ':
return 'my-consumer-secret';
}
return '';
});
$this->io
->method('hasAuthentication')
->with($this->equalTo('bitbucket.org'))
->willReturnCallback(static function ($repositoryName) use (&$initial_config) {
return isset($initial_config[$repositoryName]);
});
$this->io
->method('setAuthentication')
->willReturnCallback(static function (string $repositoryName, string $username, ?string $password = null) use (&$initial_config) {
$initial_config[$repositoryName] = ['username' => $username, 'password' => $password];
});
$this->io
->method('getAuthentication')
->willReturnCallback(static function (string $repositoryName) use (&$initial_config) {
if (isset($initial_config[$repositoryName])) {
return $initial_config[$repositoryName];
}
return ['username' => null, 'password' => null];
});
$downloader_mock = $this->getHttpDownloaderMock();
$downloader_mock->expects([
['url' => 'https://bitbucket.org/site/oauth2/access_token', 'status' => 200, 'body' => '{"expires_in": 600, "access_token": "my-access-token"}'],
]);
$this->git->setHttpDownloader($downloader_mock);
// @phpstan-ignore method.deprecated
$this->git->runCommand($commandCallable, $gitUrl, null, true);
}
public static function privateBitbucketWithOauthProvider(): array
{
return [
['git@bitbucket.org:acme/repo.git', 'https://x-token-auth:my-access-token@bitbucket.org/acme/repo.git'],
['https://bitbucket.org/acme/repo.git', 'https://x-token-auth:my-access-token@bitbucket.org/acme/repo.git'],
['https://bitbucket.org/acme/repo', 'https://x-token-auth:my-access-token@bitbucket.org/acme/repo.git'],
['git@bitbucket.org:acme/repo.git', 'https://x-token-auth:my-access-token@bitbucket.org/acme/repo.git', ['bitbucket.org' => ['username' => 'someuseralsoswappedfortoken', 'password' => 'little green men']]],
];
}
public static function privateBitbucketWithCredentialsProvider(): array
{
return [
['git@bitbucket.org:acme/repo.git', 'MY_BITBUCKET_TOKEN', 'https://token:MY_BITBUCKET_TOKEN@bitbucket.org/acme/repo.git', 1],
['https://bitbucket.org/acme/repo', 'MY_BITBUCKET_TOKEN', 'https://token:MY_BITBUCKET_TOKEN@bitbucket.org/acme/repo.git', 1],
['https://bitbucket.org/acme/repo.git', 'MY_BITBUCKET_TOKEN', 'https://token:MY_BITBUCKET_TOKEN@bitbucket.org/acme/repo.git', 1],
['git@bitbucket.org:acme/repo.git', null, 'git@bitbucket.org:acme/repo.git', 0],
['https://bitbucket.org/acme/repo', null, 'git@bitbucket.org:acme/repo.git', 1, 1],
['https://bitbucket.org/acme/repo.git', null, 'git@bitbucket.org:acme/repo.git', 1, 1],
['https://bitbucket.org/acme/repo.git', 'ATAT_BITBUCKET_API_TOKEN', 'https://x-bitbucket-api-token-auth:ATAT_BITBUCKET_API_TOKEN@bitbucket.org/acme/repo.git', 1],
];
}
public static function privateGithubWithCredentialsProvider(): array
{
return [
['git@github.com:acme/repo.git', 'ssh', 'MY_GITHUB_TOKEN', 'https://token:MY_GITHUB_TOKEN@github.com/acme/repo.git', 1],
['https://github.com/acme/repo', 'https', 'MY_GITHUB_TOKEN', 'https://token:MY_GITHUB_TOKEN@github.com/acme/repo.git', 2],
];
}
private function mockConfig(string $protocol): void
{
$this->config
->method('get')
->willReturnMap([
['github-domains', 0, ['github.com']],
['github-protocols', 0, [$protocol]],
]);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/HttpDownloaderTest.php | tests/Composer/Test/Util/HttpDownloaderTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\IO\BufferIO;
use Composer\Util\HttpDownloader;
use PHPUnit\Framework\TestCase;
class HttpDownloaderTest extends TestCase
{
/**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Config
*/
private function getConfigMock()
{
$config = $this->getMockBuilder('Composer\Config')->getMock();
$config->expects($this->any())
->method('get')
->will($this->returnCallback(static function ($key) {
if ($key === 'github-domains' || $key === 'gitlab-domains') {
return [];
}
}));
return $config;
}
/**
* @group slow
*/
public function testCaptureAuthenticationParamsFromUrl(): void
{
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$io->expects($this->once())
->method('setAuthentication')
->with($this->equalTo('github.com'), $this->equalTo('user'), $this->equalTo('pass'));
$fs = new HttpDownloader($io, $this->getConfigMock());
try {
$fs->get('https://user:pass@github.com/composer/composer/404');
} catch (\Composer\Downloader\TransportException $e) {
self::assertNotEquals(200, $e->getCode());
}
}
public function testOutputWarnings(): void
{
$io = new BufferIO();
HttpDownloader::outputWarnings($io, '$URL', []);
self::assertSame('', $io->getOutput());
HttpDownloader::outputWarnings($io, '$URL', [
'warning' => 'old warning msg',
'warning-versions' => '>=2.0',
'info' => 'old info msg',
'info-versions' => '>=2.0',
'warnings' => [
['message' => 'should not appear', 'versions' => '<2.2'],
['message' => 'visible warning', 'versions' => '>=2.2-dev'],
],
'infos' => [
['message' => 'should not appear', 'versions' => '<2.2'],
['message' => 'visible info', 'versions' => '>=2.2-dev'],
],
]);
// the <info> tag are consumed by the OutputFormatter, but not <warning> as that is not a default output format
self::assertSame(
'<warning>Warning from $URL: old warning msg</warning>'.PHP_EOL.
'Info from $URL: old info msg'.PHP_EOL.
'<warning>Warning from $URL: visible warning</warning>'.PHP_EOL.
'Info from $URL: visible info'.PHP_EOL,
$io->getOutput()
);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/SilencerTest.php | tests/Composer/Test/Util/SilencerTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Util\Silencer;
use Composer\Test\TestCase;
/**
* SilencerTest
*
* @author Niels Keurentjes <niels.keurentjes@omines.com>
*/
class SilencerTest extends TestCase
{
/**
* Test succeeds when no warnings are emitted externally, and original level is restored.
*/
public function testSilencer(): void
{
$before = error_reporting();
// Check warnings are suppressed correctly
Silencer::suppress();
@trigger_error('Test', E_USER_WARNING);
Silencer::restore();
// Check all parameters and return values are passed correctly in a silenced call.
$result = Silencer::call(static function ($a, $b, $c) {
@trigger_error('Test', E_USER_WARNING);
return $a * $b * $c;
}, 2, 3, 4);
self::assertEquals(24, $result);
// Check the error reporting setting was restored correctly
self::assertEquals($before, error_reporting());
}
/**
* Test whether exception from silent callbacks are correctly forwarded.
*/
public function testSilencedException(): void
{
$verification = microtime();
self::expectException('RuntimeException');
self::expectExceptionMessage($verification);
Silencer::call(static function () use ($verification): void {
throw new \RuntimeException($verification);
});
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/GitLabTest.php | tests/Composer/Test/Util/GitLabTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Util\GitLab;
use Composer\Test\TestCase;
/**
* @author Jérôme Tamarelle <jerome@tamarelle.net>
*/
class GitLabTest extends TestCase
{
/** @var string */
private $username = 'username';
/** @var string */
private $password = 'password';
/** @var string */
private $message = 'mymessage';
/** @var string */
private $origin = 'gitlab.com';
/** @var string */
private $token = 'gitlabtoken';
/** @var string */
private $refreshtoken = 'gitlabrefreshtoken';
public function testUsernamePasswordAuthenticationFlow(): void
{
$io = $this->getIOMock();
$io->expects([
['text' => $this->message],
['ask' => 'Username: ', 'reply' => $this->username],
['ask' => 'Password: ', 'reply' => $this->password],
]);
$httpDownloader = $this->getHttpDownloaderMock();
$httpDownloader->expects(
[['url' => sprintf('http://%s/oauth/token', $this->origin), 'body' => sprintf('{"access_token": "%s", "refresh_token": "%s", "token_type": "bearer", "expires_in": 7200, "created_at": 0}', $this->token, $this->refreshtoken)]],
true
);
$config = $this->getConfigMock();
$config
->expects($this->exactly(2))
->method('getAuthConfigSource')
->willReturn($this->getAuthJsonMock())
;
$gitLab = new GitLab($io, $config, null, $httpDownloader);
self::assertTrue($gitLab->authorizeOAuthInteractively('http', $this->origin, $this->message));
}
public function testUsernamePasswordFailure(): void
{
self::expectException('RuntimeException');
self::expectExceptionMessage('Invalid GitLab credentials 5 times in a row, aborting.');
$io = $this->getIOMock();
$io->expects([
['ask' => 'Username: ', 'reply' => $this->username],
['ask' => 'Password: ', 'reply' => $this->password],
['ask' => 'Username: ', 'reply' => $this->username],
['ask' => 'Password: ', 'reply' => $this->password],
['ask' => 'Username: ', 'reply' => $this->username],
['ask' => 'Password: ', 'reply' => $this->password],
['ask' => 'Username: ', 'reply' => $this->username],
['ask' => 'Password: ', 'reply' => $this->password],
['ask' => 'Username: ', 'reply' => $this->username],
['ask' => 'Password: ', 'reply' => $this->password],
]);
$httpDownloader = $this->getHttpDownloaderMock();
$httpDownloader->expects(
[
['url' => 'https://gitlab.com/oauth/token', 'status' => 401, 'body' => '{}'],
['url' => 'https://gitlab.com/oauth/token', 'status' => 401, 'body' => '{}'],
['url' => 'https://gitlab.com/oauth/token', 'status' => 401, 'body' => '{}'],
['url' => 'https://gitlab.com/oauth/token', 'status' => 401, 'body' => '{}'],
['url' => 'https://gitlab.com/oauth/token', 'status' => 401, 'body' => '{}'],
],
true
);
$config = $this->getConfigMock();
$config
->expects($this->exactly(1))
->method('getAuthConfigSource')
->willReturn($this->getAuthJsonMock())
;
$gitLab = new GitLab($io, $config, null, $httpDownloader);
$gitLab->authorizeOAuthInteractively('https', $this->origin);
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Config
*/
private function getConfigMock()
{
return $this->getMockBuilder('Composer\Config')->getMock();
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Config\JsonConfigSource
*/
private function getAuthJsonMock()
{
$authjson = $this
->getMockBuilder('Composer\Config\JsonConfigSource')
->disableOriginalConstructor()
->getMock()
;
$authjson
->expects($this->atLeastOnce())
->method('getName')
->willReturn('auth.json')
;
return $authjson;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/PerforceTest.php | tests/Composer/Test/Util/PerforceTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Json\JsonFile;
use Composer\Test\Mock\ProcessExecutorMock;
use Composer\Util\Perforce;
use Composer\Test\TestCase;
use Composer\Util\ProcessExecutor;
/**
* @author Matt Whittom <Matt.Whittom@veteransunited.com>
*/
class PerforceTest extends TestCase
{
/** @var Perforce */
protected $perforce;
/** @var ProcessExecutorMock */
protected $processExecutor;
/** @var array<string, string> */
protected $repoConfig;
/** @var \PHPUnit\Framework\MockObject\MockObject&\Composer\IO\IOInterface */
protected $io;
private const TEST_DEPOT = 'depot';
private const TEST_BRANCH = 'branch';
private const TEST_P4USER = 'user';
private const TEST_CLIENT_NAME = 'TEST';
private const TEST_PORT = 'port';
private const TEST_PATH = 'path';
protected function setUp(): void
{
$this->processExecutor = $this->getProcessExecutorMock();
$this->repoConfig = $this->getTestRepoConfig();
$this->io = $this->getMockIOInterface();
$this->createNewPerforceWithWindowsFlag(true);
}
/**
* @return array<string, string>
*/
public function getTestRepoConfig(): array
{
return [
'depot' => self::TEST_DEPOT,
'branch' => self::TEST_BRANCH,
'p4user' => self::TEST_P4USER,
'unique_perforce_client_name' => self::TEST_CLIENT_NAME,
];
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\IO\IOInterface
*/
public function getMockIOInterface()
{
return $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
}
protected function createNewPerforceWithWindowsFlag(bool $flag): void
{
$this->perforce = new Perforce($this->repoConfig, self::TEST_PORT, self::TEST_PATH, $this->processExecutor, $flag, $this->io);
}
public function testGetClientWithoutStream(): void
{
$client = $this->perforce->getClient();
$expected = 'composer_perforce_TEST_depot';
self::assertEquals($expected, $client);
}
public function testGetClientFromStream(): void
{
$this->setPerforceToStream();
$client = $this->perforce->getClient();
$expected = 'composer_perforce_TEST_depot_branch';
self::assertEquals($expected, $client);
}
public function testGetStreamWithoutStream(): void
{
$stream = $this->perforce->getStream();
self::assertEquals("//depot", $stream);
}
public function testGetStreamWithStream(): void
{
$this->setPerforceToStream();
$stream = $this->perforce->getStream();
self::assertEquals('//depot/branch', $stream);
}
public function testGetStreamWithoutLabelWithStreamWithoutLabel(): void
{
$stream = $this->perforce->getStreamWithoutLabel('//depot/branch');
self::assertEquals('//depot/branch', $stream);
}
public function testGetStreamWithoutLabelWithStreamWithLabel(): void
{
$stream = $this->perforce->getStreamWithoutLabel('//depot/branching@label');
self::assertEquals('//depot/branching', $stream);
}
public function testGetClientSpec(): void
{
$clientSpec = $this->perforce->getP4ClientSpec();
$expected = 'path/composer_perforce_TEST_depot.p4.spec';
self::assertEquals($expected, $clientSpec);
}
public function testGenerateP4Command(): void
{
$command = 'do something';
$p4Command = $this->perforce->generateP4Command($command);
$expected = 'p4 -u user -c composer_perforce_TEST_depot -p port do something';
self::assertEquals($expected, $p4Command);
}
public function testQueryP4UserWithUserAlreadySet(): void
{
$this->perforce->queryP4user();
self::assertEquals(self::TEST_P4USER, $this->perforce->getUser());
}
public function testQueryP4UserWithUserSetInP4VariablesWithWindowsOS(): void
{
$this->createNewPerforceWithWindowsFlag(true);
$this->perforce->setUser(null);
$this->processExecutor->expects(
[['cmd' => 'p4 set', 'stdout' => 'P4USER=TEST_P4VARIABLE_USER' . PHP_EOL, 'return' => 0]],
true
);
$this->perforce->queryP4user();
self::assertEquals('TEST_P4VARIABLE_USER', $this->perforce->getUser());
}
public function testQueryP4UserWithUserSetInP4VariablesNotWindowsOS(): void
{
$this->createNewPerforceWithWindowsFlag(false);
$this->perforce->setUser(null);
$this->processExecutor->expects(
[['cmd' => 'echo $P4USER', 'stdout' => 'TEST_P4VARIABLE_USER' . PHP_EOL, 'return' => 0]],
true
);
$this->perforce->queryP4user();
self::assertEquals('TEST_P4VARIABLE_USER', $this->perforce->getUser());
}
public function testQueryP4UserQueriesForUser(): void
{
$this->perforce->setUser(null);
$expectedQuestion = 'Enter P4 User:';
$this->io->method('ask')
->with($this->equalTo($expectedQuestion))
->willReturn('TEST_QUERY_USER');
$this->perforce->queryP4user();
self::assertEquals('TEST_QUERY_USER', $this->perforce->getUser());
}
public function testQueryP4UserStoresResponseToQueryForUserWithWindows(): void
{
$this->createNewPerforceWithWindowsFlag(true);
$this->perforce->setUser(null);
$expectedQuestion = 'Enter P4 User:';
$expectedCommand = 'p4 set P4USER=TEST_QUERY_USER';
$this->io->expects($this->once())
->method('ask')
->with($this->equalTo($expectedQuestion))
->willReturn('TEST_QUERY_USER');
$this->processExecutor->expects(
[
'p4 set',
$expectedCommand,
],
true
);
$this->perforce->queryP4user();
}
public function testQueryP4UserStoresResponseToQueryForUserWithoutWindows(): void
{
$this->createNewPerforceWithWindowsFlag(false);
$this->perforce->setUser(null);
$expectedQuestion = 'Enter P4 User:';
$expectedCommand = 'export P4USER=TEST_QUERY_USER';
$this->io->expects($this->once())
->method('ask')
->with($this->equalTo($expectedQuestion))
->willReturn('TEST_QUERY_USER');
$this->processExecutor->expects(
[
'echo $P4USER',
$expectedCommand,
],
true
);
$this->perforce->queryP4user();
}
public function testQueryP4PasswordWithPasswordAlreadySet(): void
{
$repoConfig = [
'depot' => 'depot',
'branch' => 'branch',
'p4user' => 'user',
'p4password' => 'TEST_PASSWORD',
];
$this->perforce = new Perforce($repoConfig, 'port', 'path', $this->processExecutor, false, $this->getMockIOInterface());
$password = $this->perforce->queryP4Password();
self::assertEquals('TEST_PASSWORD', $password);
}
public function testQueryP4PasswordWithPasswordSetInP4VariablesWithWindowsOS(): void
{
$this->createNewPerforceWithWindowsFlag(true);
$this->processExecutor->expects(
[['cmd' => 'p4 set', 'stdout' => 'P4PASSWD=TEST_P4VARIABLE_PASSWORD' . PHP_EOL, 'return' => 0]],
true
);
$password = $this->perforce->queryP4Password();
self::assertEquals('TEST_P4VARIABLE_PASSWORD', $password);
}
public function testQueryP4PasswordWithPasswordSetInP4VariablesNotWindowsOS(): void
{
$this->createNewPerforceWithWindowsFlag(false);
$this->processExecutor->expects(
[['cmd' => 'echo $P4PASSWD', 'stdout' => 'TEST_P4VARIABLE_PASSWORD' . PHP_EOL, 'return' => 0]],
true
);
$password = $this->perforce->queryP4Password();
self::assertEquals('TEST_P4VARIABLE_PASSWORD', $password);
}
public function testQueryP4PasswordQueriesForPassword(): void
{
$expectedQuestion = 'Enter password for Perforce user user: ';
$this->io->expects($this->once())
->method('askAndHideAnswer')
->with($this->equalTo($expectedQuestion))
->willReturn('TEST_QUERY_PASSWORD');
$password = $this->perforce->queryP4Password();
self::assertEquals('TEST_QUERY_PASSWORD', $password);
}
public function testWriteP4ClientSpecWithoutStream(): void
{
$stream = fopen('php://memory', 'w+');
if (false === $stream) {
self::fail('Could not open memory stream');
}
$this->perforce->writeClientSpecToFile($stream);
rewind($stream);
$expectedArray = $this->getExpectedClientSpec(false);
try {
foreach ($expectedArray as $expected) {
self::assertStringStartsWith($expected, (string) fgets($stream));
}
self::assertFalse(fgets($stream));
} catch (\Exception $e) {
fclose($stream);
throw $e;
}
fclose($stream);
}
public function testWriteP4ClientSpecWithStream(): void
{
$this->setPerforceToStream();
$stream = fopen('php://memory', 'w+');
if (false === $stream) {
self::fail('Could not open memory stream');
}
$this->perforce->writeClientSpecToFile($stream);
rewind($stream);
$expectedArray = $this->getExpectedClientSpec(true);
try {
foreach ($expectedArray as $expected) {
self::assertStringStartsWith($expected, (string) fgets($stream));
}
self::assertFalse(fgets($stream));
} catch (\Exception $e) {
fclose($stream);
throw $e;
}
fclose($stream);
}
public function testIsLoggedIn(): void
{
$this->processExecutor->expects(
[['cmd' => 'p4 -u user -p port login -s']],
true
);
$this->perforce->isLoggedIn();
}
public function testConnectClient(): void
{
$this->processExecutor->expects(
['p4 -u user -c composer_perforce_TEST_depot -p port client -i < '.ProcessExecutor::escape('path/composer_perforce_TEST_depot.p4.spec')],
true
);
$this->perforce->connectClient();
}
public function testGetBranchesWithStream(): void
{
$this->setPerforceToStream();
$this->processExecutor->expects(
[
[
'cmd' => 'p4 -u user -c composer_perforce_TEST_depot_branch -p port streams '.ProcessExecutor::escape('//depot/...'),
'stdout' => 'Stream //depot/branch mainline none \'branch\'' . PHP_EOL,
],
[
'cmd' => 'p4 -u user -p port changes '.ProcessExecutor::escape('//depot/branch/...'),
'stdout' => 'Change 1234 on 2014/03/19 by Clark.Stuth@Clark.Stuth_test_client \'test changelist\'',
],
],
true
);
$branches = $this->perforce->getBranches();
self::assertEquals('//depot/branch@1234', $branches['master']);
}
public function testGetBranchesWithoutStream(): void
{
$this->processExecutor->expects(
[
[
'cmd' => 'p4 -u user -p port changes '.ProcessExecutor::escape('//depot/...'),
'stdout' => 'Change 5678 on 2014/03/19 by Clark.Stuth@Clark.Stuth_test_client \'test changelist\'',
],
],
true
);
$branches = $this->perforce->getBranches();
self::assertEquals('//depot@5678', $branches['master']);
}
public function testGetTagsWithoutStream(): void
{
$this->processExecutor->expects(
[
[
'cmd' => 'p4 -u user -c composer_perforce_TEST_depot -p port labels',
'stdout' => 'Label 0.0.1 2013/07/31 \'First Label!\'' . PHP_EOL . 'Label 0.0.2 2013/08/01 \'Second Label!\'' . PHP_EOL,
],
],
true
);
$tags = $this->perforce->getTags();
self::assertEquals('//depot@0.0.1', $tags['0.0.1']);
self::assertEquals('//depot@0.0.2', $tags['0.0.2']);
}
public function testGetTagsWithStream(): void
{
$this->setPerforceToStream();
$this->processExecutor->expects(
[
[
'cmd' => 'p4 -u user -c composer_perforce_TEST_depot_branch -p port labels',
'stdout' => 'Label 0.0.1 2013/07/31 \'First Label!\'' . PHP_EOL . 'Label 0.0.2 2013/08/01 \'Second Label!\'' . PHP_EOL,
],
],
true
);
$tags = $this->perforce->getTags();
self::assertEquals('//depot/branch@0.0.1', $tags['0.0.1']);
self::assertEquals('//depot/branch@0.0.2', $tags['0.0.2']);
}
public function testCheckStreamWithoutStream(): void
{
$result = $this->perforce->checkStream();
self::assertFalse($result);
self::assertFalse($this->perforce->isStream());
}
public function testCheckStreamWithStream(): void
{
$this->processExecutor->expects(
[
[
'cmd' => 'p4 -u user -p port depots',
'stdout' => 'Depot depot 2013/06/25 stream /p4/1/depots/depot/... \'Created by Me\'',
],
],
true
);
$result = $this->perforce->checkStream();
self::assertTrue($result);
self::assertTrue($this->perforce->isStream());
}
public function testGetComposerInformationWithoutLabelWithoutStream(): void
{
$this->processExecutor->expects(
[
[
'cmd' => 'p4 -u user -c composer_perforce_TEST_depot -p port print '.ProcessExecutor::escape('//depot/composer.json'),
'stdout' => PerforceTest::getComposerJson(),
],
],
true
);
$result = $this->perforce->getComposerInformation('//depot');
$expected = [
'name' => 'test/perforce',
'description' => 'Basic project for testing',
'minimum-stability' => 'dev',
'autoload' => ['psr-0' => []],
];
self::assertEquals($expected, $result);
}
public function testGetComposerInformationWithLabelWithoutStream(): void
{
$this->processExecutor->expects(
[
[
'cmd' => 'p4 -u user -p port files '.ProcessExecutor::escape('//depot/composer.json@0.0.1'),
'stdout' => '//depot/composer.json#1 - branch change 10001 (text)',
],
[
'cmd' => 'p4 -u user -c composer_perforce_TEST_depot -p port print '.ProcessExecutor::escape('//depot/composer.json@10001'),
'stdout' => PerforceTest::getComposerJson(),
],
],
true
);
$result = $this->perforce->getComposerInformation('//depot@0.0.1');
$expected = [
'name' => 'test/perforce',
'description' => 'Basic project for testing',
'minimum-stability' => 'dev',
'autoload' => ['psr-0' => []],
];
self::assertEquals($expected, $result);
}
public function testGetComposerInformationWithoutLabelWithStream(): void
{
$this->setPerforceToStream();
$this->processExecutor->expects(
[
[
'cmd' => 'p4 -u user -c composer_perforce_TEST_depot_branch -p port print '.ProcessExecutor::escape('//depot/branch/composer.json'),
'stdout' => PerforceTest::getComposerJson(),
],
],
true
);
$result = $this->perforce->getComposerInformation('//depot/branch');
$expected = [
'name' => 'test/perforce',
'description' => 'Basic project for testing',
'minimum-stability' => 'dev',
'autoload' => ['psr-0' => []],
];
self::assertEquals($expected, $result);
}
public function testGetComposerInformationWithLabelWithStream(): void
{
$this->processExecutor->expects(
[
[
'cmd' => 'p4 -u user -p port files '.ProcessExecutor::escape('//depot/branch/composer.json@0.0.1'),
'stdout' => '//depot/composer.json#1 - branch change 10001 (text)',
],
[
'cmd' => 'p4 -u user -c composer_perforce_TEST_depot_branch -p port print '.ProcessExecutor::escape('//depot/branch/composer.json@10001'),
'stdout' => PerforceTest::getComposerJson(),
],
],
true
);
$this->setPerforceToStream();
$result = $this->perforce->getComposerInformation('//depot/branch@0.0.1');
$expected = [
'name' => 'test/perforce',
'description' => 'Basic project for testing',
'minimum-stability' => 'dev',
'autoload' => ['psr-0' => []],
];
self::assertEquals($expected, $result);
}
public function testSyncCodeBaseWithoutStream(): void
{
$this->processExecutor->expects(
['p4 -u user -c composer_perforce_TEST_depot -p port sync -f @label'],
true
);
$this->perforce->syncCodeBase('label');
}
public function testSyncCodeBaseWithStream(): void
{
$this->setPerforceToStream();
$this->processExecutor->expects(
['p4 -u user -c composer_perforce_TEST_depot_branch -p port sync -f @label'],
true
);
$this->perforce->syncCodeBase('label');
}
public function testCheckServerExists(): void
{
$this->processExecutor->expects(
[
['p4', '-p', 'perforce.does.exist:port', 'info', '-s'],
],
true
);
$result = $this->perforce->checkServerExists('perforce.does.exist:port', $this->processExecutor);
self::assertTrue($result);
}
/**
* Test if "p4" command is missing.
*
* @covers \Composer\Util\Perforce::checkServerExists
*/
public function testCheckServerClientError(): void
{
$processExecutor = $this->getMockBuilder('Composer\Util\ProcessExecutor')->getMock();
$expectedCommand = ['p4', '-p', 'perforce.does.exist:port', 'info', '-s'];
$processExecutor->expects($this->once())
->method('execute')
->with($this->equalTo($expectedCommand), $this->equalTo(null))
->willReturn(127);
$result = $this->perforce->checkServerExists('perforce.does.exist:port', $processExecutor);
self::assertFalse($result);
}
public static function getComposerJson(): string
{
return JsonFile::encode([
'name' => 'test/perforce',
'description' => 'Basic project for testing',
'minimum-stability' => 'dev',
'autoload' => [
'psr-0' => [],
],
], JSON_FORCE_OBJECT);
}
/**
* @return string[]
*/
private function getExpectedClientSpec(bool $withStream): array
{
$expectedArray = [
'Client: composer_perforce_TEST_depot',
PHP_EOL,
'Update:',
PHP_EOL,
'Access:',
'Owner: user',
PHP_EOL,
'Description:',
' Created by user from composer.',
PHP_EOL,
'Root: path',
PHP_EOL,
'Options: noallwrite noclobber nocompress unlocked modtime rmdir',
PHP_EOL,
'SubmitOptions: revertunchanged',
PHP_EOL,
'LineEnd: local',
PHP_EOL,
];
if ($withStream) {
$expectedArray[] = 'Stream:';
$expectedArray[] = ' //depot/branch';
} else {
$expectedArray[] = 'View: //depot/... //composer_perforce_TEST_depot/...';
}
return $expectedArray;
}
private function setPerforceToStream(): void
{
$this->perforce->setStream('//depot/branch');
}
public function testCleanupClientSpecShouldDeleteClient(): void
{
$fs = $this->getMockBuilder('Composer\Util\Filesystem')->getMock();
$this->perforce->setFilesystem($fs);
$testClient = $this->perforce->getClient();
$this->processExecutor->expects(
['p4 -u ' . self::TEST_P4USER . ' -p ' . self::TEST_PORT . ' client -d ' . ProcessExecutor::escape($testClient)],
true
);
$fs->expects($this->once())->method('remove')->with($this->perforce->getP4ClientSpec());
$this->perforce->cleanupClientSpec();
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/NoProxyPatternTest.php | tests/Composer/Test/Util/NoProxyPatternTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Util\NoProxyPattern;
use Composer\Test\TestCase;
class NoProxyPatternTest extends TestCase
{
/**
* @dataProvider dataHostName
*/
public function testHostName(string $noproxy, string $url, bool $expected): void
{
$matcher = new NoProxyPattern($noproxy);
$url = $this->getUrl($url);
self::assertEquals($expected, $matcher->test($url));
}
public static function dataHostName(): array
{
$noproxy = 'foobar.com, .barbaz.net';
// noproxy, url, expected
return [
'match as foobar.com' => [$noproxy, 'foobar.com', true],
'match foobar.com' => [$noproxy, 'www.foobar.com', true],
'no match foobar.com' => [$noproxy, 'foofoobar.com', false],
'match .barbaz.net 1' => [$noproxy, 'barbaz.net', true],
'match .barbaz.net 2' => [$noproxy, 'www.barbaz.net', true],
'no match .barbaz.net' => [$noproxy, 'barbarbaz.net', false],
'no match wrong domain' => [$noproxy, 'barbaz.com', false],
'no match FQDN' => [$noproxy, 'foobar.com.', false],
];
}
/**
* @dataProvider dataIpAddress
*/
public function testIpAddress(string $noproxy, string $url, bool $expected): void
{
$matcher = new NoProxyPattern($noproxy);
$url = $this->getUrl($url);
self::assertEquals($expected, $matcher->test($url));
}
public static function dataIpAddress(): array
{
$noproxy = '192.168.1.1, 2001:db8::52:0:1';
// noproxy, url, expected
return [
'match exact IPv4' => [$noproxy, '192.168.1.1', true],
'no match IPv4' => [$noproxy, '192.168.1.4', false],
'match exact IPv6' => [$noproxy, '[2001:db8:0:0:0:52:0:1]', true],
'no match IPv6' => [$noproxy, '[2001:db8:0:0:0:52:0:2]', false],
'match mapped IPv4' => [$noproxy, '[::FFFF:C0A8:0101]', true],
'no match mapped IPv4' => [$noproxy, '[::FFFF:C0A8:0104]', false],
];
}
/**
* @dataProvider dataIpRange
*/
public function testIpRange(string $noproxy, string $url, bool $expected): void
{
$matcher = new NoProxyPattern($noproxy);
$url = $this->getUrl($url);
self::assertEquals($expected, $matcher->test($url));
}
public static function dataIpRange(): array
{
$noproxy = '10.0.0.0/30, 2002:db8:a::45/121';
// noproxy, url, expected
return [
'match IPv4/CIDR' => [$noproxy, '10.0.0.2', true],
'no match IPv4/CIDR' => [$noproxy, '10.0.0.4', false],
'match IPv6/CIDR' => [$noproxy, '[2002:db8:a:0:0:0:0:7f]', true],
'no match IPv6' => [$noproxy, '[2002:db8:a:0:0:0:0:ff]', false],
'match mapped IPv4' => [$noproxy, '[::FFFF:0A00:0002]', true],
'no match mapped IPv4' => [$noproxy, '[::FFFF:0A00:0004]', false],
];
}
/**
* @dataProvider dataPort
*/
public function testPort(string $noproxy, string $url, bool $expected): void
{
$matcher = new NoProxyPattern($noproxy);
$url = $this->getUrl($url);
self::assertEquals($expected, $matcher->test($url));
}
public static function dataPort(): array
{
$noproxy = '192.168.1.2:81, 192.168.1.3:80, [2001:db8::52:0:2]:443, [2001:db8::52:0:3]:80';
// noproxy, url, expected
return [
'match IPv4 port' => [$noproxy, '192.168.1.3', true],
'no match IPv4 port' => [$noproxy, '192.168.1.2', false],
'match IPv6 port' => [$noproxy, '[2001:db8::52:0:3]', true],
'no match IPv6 port' => [$noproxy, '[2001:db8::52:0:2]', false],
];
}
/**
* Appends a scheme to the test url if it is missing
*/
private function getUrl(string $url): string
{
if (parse_url($url, PHP_URL_SCHEME)) {
return $url;
}
$scheme = 'http';
if (strpos($url, '[') !== 0 && strrpos($url, ':') !== false) {
[, $port] = explode(':', $url);
if ($port === '443') {
$scheme = 'https';
}
}
return sprintf('%s://%s', $scheme, $url);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/UrlTest.php | tests/Composer/Test/Util/UrlTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Util\Url;
use Composer\Test\TestCase;
use Composer\Config;
class UrlTest extends TestCase
{
/**
* @dataProvider distRefsProvider
*
* @param array<string, mixed> $conf
* @param non-empty-string $url
*/
public function testUpdateDistReference(string $url, string $expectedUrl, array $conf = [], string $ref = 'newref'): void
{
$config = new Config();
$config->merge(['config' => $conf]);
self::assertSame($expectedUrl, Url::updateDistReference($config, $url, $ref));
}
public static function distRefsProvider(): array
{
return [
// github
['https://github.com/foo/bar/zipball/abcd', 'https://api.github.com/repos/foo/bar/zipball/newref'],
['https://www.github.com/foo/bar/zipball/abcd', 'https://api.github.com/repos/foo/bar/zipball/newref'],
['https://github.com/foo/bar/archive/abcd.zip', 'https://api.github.com/repos/foo/bar/zipball/newref'],
['https://github.com/foo/bar/archive/abcd.tar.gz', 'https://api.github.com/repos/foo/bar/tarball/newref'],
['https://api.github.com/repos/foo/bar/tarball', 'https://api.github.com/repos/foo/bar/tarball/newref'],
['https://api.github.com/repos/foo/bar/tarball/abcd', 'https://api.github.com/repos/foo/bar/tarball/newref'],
// github enterprise
['https://mygithub.com/api/v3/repos/foo/bar/tarball/abcd', 'https://mygithub.com/api/v3/repos/foo/bar/tarball/newref', ['github-domains' => ['mygithub.com']]],
// bitbucket
['https://bitbucket.org/foo/bar/get/abcd.zip', 'https://bitbucket.org/foo/bar/get/newref.zip'],
['https://www.bitbucket.org/foo/bar/get/abcd.tar.bz2', 'https://bitbucket.org/foo/bar/get/newref.tar.bz2'],
// gitlab
['https://gitlab.com/api/v4/projects/foo%2Fbar/repository/archive.zip?sha=abcd', 'https://gitlab.com/api/v4/projects/foo%2Fbar/repository/archive.zip?sha=newref'],
['https://www.gitlab.com/api/v4/projects/foo%2Fbar/repository/archive.zip?sha=abcd', 'https://gitlab.com/api/v4/projects/foo%2Fbar/repository/archive.zip?sha=newref'],
['https://gitlab.com/api/v3/projects/foo%2Fbar/repository/archive.tar.gz?sha=abcd', 'https://gitlab.com/api/v4/projects/foo%2Fbar/repository/archive.tar.gz?sha=newref'],
// gitlab enterprise
['https://mygitlab.com/api/v4/projects/foo%2Fbar/repository/archive.tar.gz?sha=abcd', 'https://mygitlab.com/api/v4/projects/foo%2Fbar/repository/archive.tar.gz?sha=newref', ['gitlab-domains' => ['mygitlab.com']]],
['https://mygitlab.com/api/v3/projects/foo%2Fbar/repository/archive.tar.bz2?sha=abcd', 'https://mygitlab.com/api/v3/projects/foo%2Fbar/repository/archive.tar.bz2?sha=newref', ['gitlab-domains' => ['mygitlab.com']]],
['https://mygitlab.com/api/v3/projects/foo%2Fbar/repository/archive.tar.bz2?sha=abcd', 'https://mygitlab.com/api/v3/projects/foo%2Fbar/repository/archive.tar.bz2?sha=65', ['gitlab-domains' => ['mygitlab.com']], '65'],
];
}
/**
* @dataProvider sanitizeProvider
*/
public function testSanitize(string $expected, string $url): void
{
self::assertSame($expected, Url::sanitize($url));
}
public static function sanitizeProvider(): array
{
return [
// with scheme
['https://foo:***@example.org/', 'https://foo:bar@example.org/'],
['https://foo@example.org/', 'https://foo@example.org/'],
['https://example.org/', 'https://example.org/'],
['http://***:***@example.org', 'http://10a8f08e8d7b7b9:foo@example.org'],
['https://foo:***@example.org:123/', 'https://foo:bar@example.org:123/'],
['https://example.org/foo/bar?access_token=***', 'https://example.org/foo/bar?access_token=abcdef'],
['https://example.org/foo/bar?foo=bar&access_token=***', 'https://example.org/foo/bar?foo=bar&access_token=abcdef'],
['https://***:***@github.com/acme/repo', 'https://ghp_1234567890abcdefghijklmnopqrstuvwxyzAB:x-oauth-basic@github.com/acme/repo'],
['https://***:***@github.com/acme/repo', 'https://github_pat_1234567890abcdefghijkl_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW:x-oauth-basic@github.com/acme/repo'],
// without scheme
['foo:***@example.org/', 'foo:bar@example.org/'],
['foo@example.org/', 'foo@example.org/'],
['example.org/', 'example.org/'],
['***:***@example.org', '10a8f08e8d7b7b9:foo@example.org'],
['foo:***@example.org:123/', 'foo:bar@example.org:123/'],
['example.org/foo/bar?access_token=***', 'example.org/foo/bar?access_token=abcdef'],
['example.org/foo/bar?foo=bar&access_token=***', 'example.org/foo/bar?foo=bar&access_token=abcdef'],
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/FilesystemTest.php | tests/Composer/Test/Util/FilesystemTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Util\Platform;
use Composer\Util\Filesystem;
use Composer\Test\TestCase;
class FilesystemTest extends TestCase
{
/**
* @var Filesystem
*/
private $fs;
/**
* @var string
*/
private $workingDir;
/**
* @var string
*/
private $testFile;
public function setUp(): void
{
$this->fs = new Filesystem;
$this->workingDir = self::getUniqueTmpDirectory();
$this->testFile = self::getUniqueTmpDirectory() . '/composer_test_file';
}
protected function tearDown(): void
{
parent::tearDown();
if (is_dir($this->workingDir)) {
$this->fs->removeDirectory($this->workingDir);
}
if (is_file($this->testFile)) {
$this->fs->removeDirectory(dirname($this->testFile));
}
}
/**
* @dataProvider providePathCouplesAsCode
*/
public function testFindShortestPathCode(string $a, string $b, bool $directory, string $expected, bool $static = false, bool $preferRelative = false): void
{
$fs = new Filesystem;
self::assertEquals($expected, $fs->findShortestPathCode($a, $b, $directory, $static, $preferRelative));
}
public static function providePathCouplesAsCode(): array
{
return [
['/foo/bar', '/foo/bar', false, "__FILE__"],
['/foo/bar', '/foo/baz', false, "__DIR__.'/baz'"],
['/foo/bin/run', '/foo/vendor/acme/bin/run', false, "dirname(__DIR__).'/vendor/acme/bin/run'"],
['/foo/bin/run', '/bar/bin/run', false, "'/bar/bin/run'"],
['c:/bin/run', 'c:/vendor/acme/bin/run', false, "dirname(__DIR__).'/vendor/acme/bin/run'"],
['c:\\bin\\run', 'c:/vendor/acme/bin/run', false, "dirname(__DIR__).'/vendor/acme/bin/run'"],
['c:/bin/run', 'D:/vendor/acme/bin/run', false, "'D:/vendor/acme/bin/run'"],
['c:\\bin\\run', 'd:/vendor/acme/bin/run', false, "'D:/vendor/acme/bin/run'"],
['/foo/bar', '/foo/bar', true, "__DIR__"],
['/foo/bar/', '/foo/bar', true, "__DIR__"],
['/foo', '/baz', true, "dirname(__DIR__).'/baz'"],
['/foo/bar', '/foo/baz', true, "dirname(__DIR__).'/baz'"],
['/foo/bin/run', '/foo/vendor/acme/bin/run', true, "dirname(dirname(__DIR__)).'/vendor/acme/bin/run'"],
['/foo/bin/run', '/bar/bin/run', true, "'/bar/bin/run'"],
['/app/vendor/foo/bar', '/lib', true, "dirname(dirname(dirname(dirname(__DIR__)))).'/lib'", false, true],
['/bin/run', '/bin/run', true, "__DIR__"],
['c:/bin/run', 'C:\\bin/run', true, "__DIR__"],
['c:/bin/run', 'c:/vendor/acme/bin/run', true, "dirname(dirname(__DIR__)).'/vendor/acme/bin/run'"],
['c:\\bin\\run', 'c:/vendor/acme/bin/run', true, "dirname(dirname(__DIR__)).'/vendor/acme/bin/run'"],
['c:/bin/run', 'd:/vendor/acme/bin/run', true, "'D:/vendor/acme/bin/run'"],
['c:\\bin\\run', 'd:/vendor/acme/bin/run', true, "'D:/vendor/acme/bin/run'"],
['C:/Temp/test', 'C:\Temp', true, "dirname(__DIR__)"],
['C:/Temp', 'C:\Temp\test', true, "__DIR__ . '/test'"],
['/tmp/test', '/tmp', true, "dirname(__DIR__)"],
['/tmp', '/tmp/test', true, "__DIR__ . '/test'"],
['C:/Temp', 'c:\Temp\test', true, "__DIR__ . '/test'"],
['/tmp/test/./', '/tmp/test/', true, '__DIR__'],
['/tmp/test/../vendor', '/tmp/test', true, "dirname(__DIR__).'/test'"],
['/tmp/test/.././vendor', '/tmp/test', true, "dirname(__DIR__).'/test'"],
['C:/Temp', 'c:\Temp\..\..\test', true, "dirname(__DIR__).'/test'"],
['C:/Temp/../..', 'd:\Temp\..\..\test', true, "'D:/test'"],
['/foo/bar', '/foo/bar_vendor', true, "dirname(__DIR__).'/bar_vendor'"],
['/foo/bar_vendor', '/foo/bar', true, "dirname(__DIR__).'/bar'"],
['/foo/bar_vendor', '/foo/bar/src', true, "dirname(__DIR__).'/bar/src'"],
['/foo/bar_vendor/src2', '/foo/bar/src/lib', true, "dirname(dirname(__DIR__)).'/bar/src/lib'"],
// static use case
['/tmp/test/../vendor', '/tmp/test', true, "__DIR__ . '/..'.'/test'", true],
['/tmp/test/.././vendor', '/tmp/test', true, "__DIR__ . '/..'.'/test'", true],
['C:/Temp', 'c:\Temp\..\..\test', true, "__DIR__ . '/..'.'/test'", true],
['C:/Temp/../..', 'd:\Temp\..\..\test', true, "'D:/test'", true],
['/foo/bar', '/foo/bar_vendor', true, "__DIR__ . '/..'.'/bar_vendor'", true],
['/foo/bar_vendor', '/foo/bar', true, "__DIR__ . '/..'.'/bar'", true],
['/foo/bar_vendor', '/foo/bar/src', true, "__DIR__ . '/..'.'/bar/src'", true],
['/foo/bar_vendor/src2', '/foo/bar/src/lib', true, "__DIR__ . '/../..'.'/bar/src/lib'", true],
];
}
/**
* @dataProvider providePathCouples
*/
public function testFindShortestPath(string $a, string $b, string $expected, bool $directory = false, bool $preferRelative = false): void
{
$fs = new Filesystem;
self::assertEquals($expected, $fs->findShortestPath($a, $b, $directory, $preferRelative));
}
public static function providePathCouples(): array
{
return [
['/foo/bar', '/foo/bar', "./bar"],
['/foo/bar', '/foo/baz', "./baz"],
['/foo/bar/', '/foo/baz', "./baz"],
['/foo/bar', '/foo/bar', "./", true],
['/foo/bar', '/foo/baz', "../baz", true],
['/foo/bar/', '/foo/baz', "../baz", true],
['C:/foo/bar/', 'c:/foo/baz', "../baz", true],
['/foo/bin/run', '/foo/vendor/acme/bin/run', "../vendor/acme/bin/run"],
['/foo/bin/run', '/bar/bin/run', "/bar/bin/run"],
['/foo/bin/run', '/bar/bin/run', "/bar/bin/run", true],
['c:/foo/bin/run', 'd:/bar/bin/run', "D:/bar/bin/run", true],
['c:/bin/run', 'c:/vendor/acme/bin/run', "../vendor/acme/bin/run"],
['c:\\bin\\run', 'c:/vendor/acme/bin/run', "../vendor/acme/bin/run"],
['c:/bin/run', 'd:/vendor/acme/bin/run', "D:/vendor/acme/bin/run"],
['c:\\bin\\run', 'd:/vendor/acme/bin/run', "D:/vendor/acme/bin/run"],
['C:/Temp/test', 'C:\Temp', "./"],
['/tmp/test', '/tmp', "./"],
['C:/Temp/test/sub', 'C:\Temp', "../"],
['/tmp/test/sub', '/tmp', "../"],
['/tmp/test/sub', '/tmp', "../../", true],
['c:/tmp/test/sub', 'c:/tmp', "../../", true],
['/tmp', '/tmp/test', "test"],
['C:/Temp', 'C:\Temp\test', "test"],
['C:/Temp', 'c:\Temp\test', "test"],
['/tmp/test/./', '/tmp/test', './', true],
['/tmp/test/../vendor', '/tmp/test', '../test', true],
['/tmp/test/.././vendor', '/tmp/test', '../test', true],
['C:/Temp', 'c:\Temp\..\..\test', "../test", true],
['C:/Temp/../..', 'c:\Temp\..\..\test', "./test", true],
['C:/Temp/../..', 'D:\Temp\..\..\test', "D:/test", true],
['/app/vendor/foo/bar', '/lib', '../../../../lib', true, true],
['/tmp', '/tmp/../../test', '../test', true],
['/tmp', '/test', '../test', true],
['/foo/bar', '/foo/bar_vendor', '../bar_vendor', true],
['/foo/bar_vendor', '/foo/bar', '../bar', true],
['/foo/bar_vendor', '/foo/bar/src', '../bar/src', true],
['/foo/bar_vendor/src2', '/foo/bar/src/lib', '../../bar/src/lib', true],
['C:/', 'C:/foo/bar/', "foo/bar", true],
];
}
/**
* @group GH-1339
*/
public function testRemoveDirectoryPhp(): void
{
@mkdir($this->workingDir . "/level1/level2", 0777, true);
file_put_contents($this->workingDir . "/level1/level2/hello.txt", "hello world");
$fs = new Filesystem;
self::assertTrue($fs->removeDirectoryPhp($this->workingDir));
self::assertFileDoesNotExist($this->workingDir . "/level1/level2/hello.txt");
}
public function testFileSize(): void
{
file_put_contents($this->testFile, 'Hello');
$fs = new Filesystem;
self::assertGreaterThanOrEqual(5, $fs->size($this->testFile));
}
public function testDirectorySize(): void
{
@mkdir($this->workingDir, 0777, true);
file_put_contents($this->workingDir."/file1.txt", 'Hello');
file_put_contents($this->workingDir."/file2.txt", 'World');
$fs = new Filesystem;
self::assertGreaterThanOrEqual(10, $fs->size($this->workingDir));
}
/**
* @dataProvider provideNormalizedPaths
*/
public function testNormalizePath(string $expected, string $actual): void
{
$fs = new Filesystem;
self::assertEquals($expected, $fs->normalizePath($actual));
}
public static function provideNormalizedPaths(): array
{
return [
['../foo', '../foo'],
['C:/foo/bar', 'c:/foo//bar'],
['C:/foo/bar', 'C:/foo/./bar'],
['C:/foo/bar', 'C://foo//bar'],
['C:/foo/bar', 'C:///foo//bar'],
['C:/bar', 'C:/foo/../bar'],
['/bar', '/foo/../bar/'],
['phar://C:/Foo', 'phar://c:/Foo/Bar/..'],
['phar://C:/Foo', 'phar://c:///Foo/Bar/..'],
['phar://C:/', 'phar://c:/Foo/Bar/../../../..'],
['/', '/Foo/Bar/../../../..'],
['/', '/'],
['/', '//'],
['/', '///'],
['/Foo', '///Foo'],
['C:/', 'c:\\'],
['../src', 'Foo/Bar/../../../src'],
['C:../b', 'c:.\\..\\a\\..\\b'],
['phar://C:../Foo', 'phar://c:../Foo'],
['//foo/bar', '\\\\foo\\bar'],
];
}
/**
* @link https://github.com/composer/composer/issues/3157
* @requires function symlink
*/
public function testUnlinkSymlinkedDirectory(): void
{
$basepath = $this->workingDir;
$symlinked = $basepath . "/linked";
@mkdir($basepath . "/real", 0777, true);
touch($basepath . "/real/FILE");
$result = @symlink($basepath . "/real", $symlinked);
if (!$result) {
$this->markTestSkipped('Symbolic links for directories not supported on this platform');
}
if (!is_dir($symlinked)) {
$this->fail('Precondition assertion failed (is_dir is false on symbolic link to directory).');
}
$fs = new Filesystem();
$result = $fs->unlink($symlinked);
self::assertTrue($result);
self::assertFileDoesNotExist($symlinked);
}
/**
* @link https://github.com/composer/composer/issues/3144
* @requires function symlink
*/
public function testRemoveSymlinkedDirectoryWithTrailingSlash(): void
{
@mkdir($this->workingDir . "/real", 0777, true);
touch($this->workingDir . "/real/FILE");
$symlinked = $this->workingDir . "/linked";
$symlinkedTrailingSlash = $symlinked . "/";
$result = @symlink($this->workingDir . "/real", $symlinked);
if (!$result) {
$this->markTestSkipped('Symbolic links for directories not supported on this platform');
}
if (!is_dir($symlinked)) {
$this->fail('Precondition assertion failed (is_dir is false on symbolic link to directory).');
}
if (!is_dir($symlinkedTrailingSlash)) {
$this->fail('Precondition assertion failed (is_dir false w trailing slash).');
}
$fs = new Filesystem();
$result = $fs->removeDirectory($symlinkedTrailingSlash);
self::assertTrue($result);
self::assertFileDoesNotExist($symlinkedTrailingSlash);
self::assertFileDoesNotExist($symlinked);
}
public function testJunctions(): void
{
@mkdir($this->workingDir . '/real/nesting/testing', 0777, true);
$fs = new Filesystem();
// Non-Windows systems do not support this and will return false on all tests, and an exception on creation
if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
self::assertFalse($fs->isJunction($this->workingDir));
self::assertFalse($fs->removeJunction($this->workingDir));
self::expectException('LogicException');
self::expectExceptionMessage('not available on non-Windows platform');
}
$target = $this->workingDir . '/real/../real/nesting';
$junction = $this->workingDir . '/junction';
// Create and detect junction
$fs->junction($target, $junction);
self::assertTrue($fs->isJunction($junction), $junction . ': is a junction');
self::assertFalse($fs->isJunction($target), $target . ': is not a junction');
self::assertTrue($fs->isJunction($target . '/../../junction'), $target . '/../../junction: is a junction');
self::assertFalse($fs->isJunction($junction . '/../real'), $junction . '/../real: is not a junction');
self::assertTrue($fs->isJunction($junction . '/../junction'), $junction . '/../junction: is a junction');
// Remove junction
self::assertDirectoryExists($junction, $junction . ' is a directory');
self::assertTrue($fs->removeJunction($junction), $junction . ' has been removed');
self::assertDirectoryDoesNotExist($junction, $junction . ' is not a directory');
}
public function testOverrideJunctions(): void
{
if (!Platform::isWindows()) {
$this->markTestSkipped('Only runs on windows');
}
@mkdir($this->workingDir.'/real/nesting/testing', 0777, true);
$fs = new Filesystem();
$old_target = $this->workingDir.'/real/nesting/testing';
$target = $this->workingDir.'/real/../real/nesting';
$junction = $this->workingDir.'/junction';
// Override non-broken junction
$fs->junction($old_target, $junction);
$fs->junction($target, $junction);
self::assertTrue($fs->isJunction($junction), $junction.': is a junction');
self::assertTrue($fs->isJunction($target.'/../../junction'), $target.'/../../junction: is a junction');
//Remove junction
self::assertTrue($fs->removeJunction($junction), $junction . ' has been removed');
// Override broken junction
$fs->junction($old_target, $junction);
$fs->removeDirectory($old_target);
$fs->junction($target, $junction);
self::assertTrue($fs->isJunction($junction), $junction.': is a junction');
self::assertTrue($fs->isJunction($target.'/../../junction'), $target.'/../../junction: is a junction');
}
public function testCopy(): void
{
@mkdir($this->workingDir . '/foo/bar', 0777, true);
@mkdir($this->workingDir . '/foo/baz', 0777, true);
file_put_contents($this->workingDir . '/foo/foo.file', 'foo');
file_put_contents($this->workingDir . '/foo/bar/foobar.file', 'foobar');
file_put_contents($this->workingDir . '/foo/baz/foobaz.file', 'foobaz');
file_put_contents($this->testFile, 'testfile');
$fs = new Filesystem();
$result1 = $fs->copy($this->workingDir . '/foo', $this->workingDir . '/foop');
self::assertTrue($result1, 'Copying directory failed.');
self::assertDirectoryExists($this->workingDir . '/foop', 'Not a directory: ' . $this->workingDir . '/foop');
self::assertDirectoryExists($this->workingDir . '/foop/bar', 'Not a directory: ' . $this->workingDir . '/foop/bar');
self::assertDirectoryExists($this->workingDir . '/foop/baz', 'Not a directory: ' . $this->workingDir . '/foop/baz');
self::assertFileExists($this->workingDir . '/foop/foo.file', 'Not a file: ' . $this->workingDir . '/foop/foo.file');
self::assertFileExists($this->workingDir . '/foop/bar/foobar.file', 'Not a file: ' . $this->workingDir . '/foop/bar/foobar.file');
self::assertFileExists($this->workingDir . '/foop/baz/foobaz.file', 'Not a file: ' . $this->workingDir . '/foop/baz/foobaz.file');
$result2 = $fs->copy($this->testFile, $this->workingDir . '/testfile.file');
self::assertTrue($result2);
self::assertFileExists($this->workingDir . '/testfile.file');
}
public function testCopyThenRemove(): void
{
@mkdir($this->workingDir . '/foo/bar', 0777, true);
@mkdir($this->workingDir . '/foo/baz', 0777, true);
file_put_contents($this->workingDir . '/foo/foo.file', 'foo');
file_put_contents($this->workingDir . '/foo/bar/foobar.file', 'foobar');
file_put_contents($this->workingDir . '/foo/baz/foobaz.file', 'foobaz');
file_put_contents($this->testFile, 'testfile');
$fs = new Filesystem();
$fs->copyThenRemove($this->testFile, $this->workingDir . '/testfile.file');
self::assertFileDoesNotExist($this->testFile, 'Still a file: ' . $this->testFile);
$fs->copyThenRemove($this->workingDir . '/foo', $this->workingDir . '/foop');
self::assertFileDoesNotExist($this->workingDir . '/foo/baz/foobaz.file', 'Still a file: ' . $this->workingDir . '/foo/baz/foobaz.file');
self::assertFileDoesNotExist($this->workingDir . '/foo/bar/foobar.file', 'Still a file: ' . $this->workingDir . '/foo/bar/foobar.file');
self::assertFileDoesNotExist($this->workingDir . '/foo/foo.file', 'Still a file: ' . $this->workingDir . '/foo/foo.file');
self::assertDirectoryDoesNotExist($this->workingDir . '/foo/baz', 'Still a directory: ' . $this->workingDir . '/foo/baz');
self::assertDirectoryDoesNotExist($this->workingDir . '/foo/bar', 'Still a directory: ' . $this->workingDir . '/foo/bar');
self::assertDirectoryDoesNotExist($this->workingDir . '/foo', 'Still a directory: ' . $this->workingDir . '/foo');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/IniHelperTest.php | tests/Composer/Test/Util/IniHelperTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util;
use Composer\Util\IniHelper;
use Composer\XdebugHandler\XdebugHandler;
use Composer\Test\TestCase;
/**
* @author John Stevenson <john-stevenson@blueyonder.co.uk>
*/
class IniHelperTest extends TestCase
{
/**
* @var string|false
*/
public static $envOriginal;
public function testWithNoIni(): void
{
$paths = [
'',
];
$this->setEnv($paths);
self::assertStringContainsString('does not exist', IniHelper::getMessage());
self::assertEquals($paths, IniHelper::getAll());
}
public function testWithLoadedIniOnly(): void
{
$paths = [
'loaded.ini',
];
$this->setEnv($paths);
self::assertStringContainsString('loaded.ini', IniHelper::getMessage());
}
public function testWithLoadedIniAndAdditional(): void
{
$paths = [
'loaded.ini',
'one.ini',
'two.ini',
];
$this->setEnv($paths);
self::assertStringContainsString('multiple ini files', IniHelper::getMessage());
self::assertEquals($paths, IniHelper::getAll());
}
public function testWithoutLoadedIniAndAdditional(): void
{
$paths = [
'',
'one.ini',
'two.ini',
];
$this->setEnv($paths);
self::assertStringContainsString('multiple ini files', IniHelper::getMessage());
self::assertEquals($paths, IniHelper::getAll());
}
public static function setUpBeforeClass(): void
{
// Register our name with XdebugHandler
$xdebug = new XdebugHandler('composer');
// Save current state
self::$envOriginal = getenv('COMPOSER_ORIGINAL_INIS');
}
public static function tearDownAfterClass(): void
{
// Restore original state
if (false !== self::$envOriginal) {
putenv('COMPOSER_ORIGINAL_INIS='.self::$envOriginal);
} else {
putenv('COMPOSER_ORIGINAL_INIS');
}
}
/**
* @param string[] $paths
*/
protected function setEnv(array $paths): void
{
putenv('COMPOSER_ORIGINAL_INIS='.implode(PATH_SEPARATOR, $paths));
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/Http/ProxyItemTest.php | tests/Composer/Test/Util/Http/ProxyItemTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util\Http;
use Composer\Util\Http\ProxyItem;
use Composer\Test\TestCase;
class ProxyItemTest extends TestCase
{
/**
* @dataProvider dataMalformed
*/
public function testThrowsOnMalformedUrl(string $url): void
{
self::expectException('RuntimeException');
$proxyItem = new ProxyItem($url, 'http_proxy');
}
/**
* @return array<string, array<string>>
*/
public static function dataMalformed(): array
{
return [
'ws-r' => ["http://user\rname@localhost:80"],
'ws-n' => ["http://user\nname@localhost:80"],
'ws-t' => ["http://user\tname@localhost:80"],
'no-host' => ['localhost'],
'no-port' => ['scheme://localhost'],
'port-0' => ['http://localhost:0'],
'port-big' => ['http://localhost:65536'],
];
}
/**
* @dataProvider dataFormatting
*/
public function testUrlFormatting(string $url, string $expected): void
{
$proxyItem = new ProxyItem($url, 'http_proxy');
$proxy = $proxyItem->toRequestProxy('http');
self::assertSame($expected, $proxy->getStatus());
}
/**
* @return array<string, array<string>>
*/
public static function dataFormatting(): array
{
// url, expected
return [
'none' => ['http://proxy.com:8888', 'http://proxy.com:8888'],
'lowercases-scheme' => ['HTTP://proxy.com:8888', 'http://proxy.com:8888'],
'adds-http-scheme' => ['proxy.com:80', 'http://proxy.com:80'],
'adds-http-port' => ['http://proxy.com', 'http://proxy.com:80'],
'adds-https-port' => ['https://proxy.com', 'https://proxy.com:443'],
'removes-user' => ['http://user@proxy.com:6180', 'http://***@proxy.com:6180'],
'removes-user-pass' => ['http://user:p%40ss@proxy.com:6180', 'http://***:***@proxy.com:6180'],
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/Http/RequestProxyTest.php | tests/Composer/Test/Util/Http/RequestProxyTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util\Http;
use Composer\Util\Http\RequestProxy;
use Composer\Test\TestCase;
class RequestProxyTest extends TestCase
{
public function testFactoryNone(): void
{
$proxy = RequestProxy::none();
$options = extension_loaded('curl') ? [CURLOPT_PROXY => ''] : [];
self::assertSame($options, $proxy->getCurlOptions([]));
self::assertNull($proxy->getContextOptions());
self::assertSame('', $proxy->getStatus());
}
public function testFactoryNoProxy(): void
{
$proxy = RequestProxy::noProxy();
$options = extension_loaded('curl') ? [CURLOPT_PROXY => ''] : [];
self::assertSame($options, $proxy->getCurlOptions([]));
self::assertNull($proxy->getContextOptions());
self::assertSame('excluded by no_proxy', $proxy->getStatus());
}
/**
* @dataProvider dataSecure
*
* @param ?non-empty-string $url
*/
public function testIsSecure(?string $url, bool $expected): void
{
$proxy = new RequestProxy($url, null, null, null);
self::assertSame($expected, $proxy->isSecure());
}
/**
* @return array<string, array{0: ?non-empty-string, 1: bool}>
*/
public static function dataSecure(): array
{
// url, expected
return [
'basic' => ['http://proxy.com:80', false],
'secure' => ['https://proxy.com:443', true],
'none' => [null, false],
];
}
public function testGetStatusThrowsOnBadFormatSpecifier(): void
{
$proxy = new RequestProxy('http://proxy.com:80', null, null, 'http://proxy.com:80');
self::expectException('InvalidArgumentException');
$proxy->getStatus('using proxy');
}
/**
* @dataProvider dataStatus
*
* @param ?non-empty-string $url
*/
public function testGetStatus(?string $url, ?string $format, string $expected): void
{
$proxy = new RequestProxy($url, null, null, $url);
if ($format === null) {
// try with and without optional param
self::assertSame($expected, $proxy->getStatus());
self::assertSame($expected, $proxy->getStatus($format));
} else {
self::assertSame($expected, $proxy->getStatus($format));
}
}
/**
* @return array<string, array{0: ?non-empty-string, 1: ?string, 2: string}>
*/
public static function dataStatus(): array
{
$format = 'proxy (%s)';
// url, format, expected
return [
'no-proxy' => [null, $format, ''],
'null-format' => ['http://proxy.com:80', null, 'http://proxy.com:80'],
'with-format' => ['http://proxy.com:80', $format, 'proxy (http://proxy.com:80)'],
];
}
/**
* This test avoids HTTPS proxies so that it can be run on PHP < 7.3
*
* @requires extension curl
* @dataProvider dataCurlOptions
*
* @param ?non-empty-string $url
* @param ?non-empty-string $auth
* @param array<int, string|int> $expected
*/
public function testGetCurlOptions(?string $url, ?string $auth, array $expected): void
{
$proxy = new RequestProxy($url, $auth, null, null);
self::assertSame($expected, $proxy->getCurlOptions([]));
}
/**
* @return list<array{0: ?string, 1: ?string, 2: array<int, string|int>}>
*/
public static function dataCurlOptions(): array
{
// url, auth, expected
return [
[null, null, [CURLOPT_PROXY => '']],
['http://proxy.com:80', null,
[
CURLOPT_PROXY => 'http://proxy.com:80',
CURLOPT_NOPROXY => '',
],
],
['http://proxy.com:80', 'user:p%40ss',
[
CURLOPT_PROXY => 'http://proxy.com:80',
CURLOPT_NOPROXY => '',
CURLOPT_PROXYAUTH => CURLAUTH_BASIC,
CURLOPT_PROXYUSERPWD => 'user:p%40ss',
],
],
];
}
/**
* @requires PHP >= 7.3.0
* @requires extension curl >= 7.52.0
* @dataProvider dataCurlSSLOptions
*
* @param non-empty-string $url
* @param ?non-empty-string $auth
* @param array<string, string> $sslOptions
* @param array<int, string|int> $expected
*/
public function testGetCurlOptionsWithSSL(string $url, ?string $auth, array $sslOptions, array $expected): void
{
$proxy = new RequestProxy($url, $auth, null, null);
self::assertSame($expected, $proxy->getCurlOptions($sslOptions));
}
/**
* @return list<array{0: string, 1: ?string, 2: array<string, string>, 3: array<int, string|int>}>
*/
public static function dataCurlSSLOptions(): array
{
// for PHPStan on PHP < 7.3
$caInfo = 10246; // CURLOPT_PROXY_CAINFO
$caPath = 10247; // CURLOPT_PROXY_CAPATH
// url, auth, sslOptions, expected
return [
['https://proxy.com:443', null, ['cafile' => '/certs/bundle.pem'],
[
CURLOPT_PROXY => 'https://proxy.com:443',
CURLOPT_NOPROXY => '',
$caInfo => '/certs/bundle.pem',
],
],
['https://proxy.com:443', 'user:p%40ss', ['capath' => '/certs'],
[
CURLOPT_PROXY => 'https://proxy.com:443',
CURLOPT_NOPROXY => '',
CURLOPT_PROXYAUTH => CURLAUTH_BASIC,
CURLOPT_PROXYUSERPWD => 'user:p%40ss',
$caPath => '/certs',
],
],
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Util/Http/ProxyManagerTest.php | tests/Composer/Test/Util/Http/ProxyManagerTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Util\Http;
use Composer\Util\Http\ProxyManager;
use Composer\Test\TestCase;
/**
* @phpstan-import-type contextOptions from \Composer\Util\Http\RequestProxy
*/
class ProxyManagerTest extends TestCase
{
protected function setUp(): void
{
unset(
$_SERVER['HTTP_PROXY'],
$_SERVER['http_proxy'],
$_SERVER['HTTPS_PROXY'],
$_SERVER['https_proxy'],
$_SERVER['NO_PROXY'],
$_SERVER['no_proxy'],
$_SERVER['CGI_HTTP_PROXY'],
$_SERVER['cgi_http_proxy']
);
ProxyManager::reset();
}
protected function tearDown(): void
{
parent::tearDown();
unset(
$_SERVER['HTTP_PROXY'],
$_SERVER['http_proxy'],
$_SERVER['HTTPS_PROXY'],
$_SERVER['https_proxy'],
$_SERVER['NO_PROXY'],
$_SERVER['no_proxy'],
$_SERVER['CGI_HTTP_PROXY'],
$_SERVER['cgi_http_proxy']
);
ProxyManager::reset();
}
public function testInstantiation(): void
{
$originalInstance = ProxyManager::getInstance();
$sameInstance = ProxyManager::getInstance();
self::assertTrue($originalInstance === $sameInstance);
ProxyManager::reset();
$newInstance = ProxyManager::getInstance();
self::assertFalse($sameInstance === $newInstance);
}
public function testGetProxyForRequestThrowsOnBadProxyUrl(): void
{
$_SERVER['http_proxy'] = 'localhost';
$proxyManager = ProxyManager::getInstance();
self::expectException('Composer\Downloader\TransportException');
$proxyManager->getProxyForRequest('http://example.com');
}
/**
* @dataProvider dataCaseOverrides
*
* @param array<string, string> $server
* @param non-empty-string $url
*/
public function testLowercaseOverridesUppercase(array $server, string $url, string $expectedUrl): void
{
$_SERVER = array_merge($_SERVER, $server);
$proxyManager = ProxyManager::getInstance();
$proxy = $proxyManager->getProxyForRequest($url);
self::assertSame($expectedUrl, $proxy->getStatus());
}
/**
* @return list<array{0: array<string, string>, 1: string, 2: string}>
*/
public static function dataCaseOverrides(): array
{
// server, url, expectedUrl
return [
[['HTTP_PROXY' => 'http://upper.com', 'http_proxy' => 'http://lower.com'], 'http://repo.org', 'http://lower.com:80'],
[['CGI_HTTP_PROXY' => 'http://upper.com', 'cgi_http_proxy' => 'http://lower.com'], 'http://repo.org', 'http://lower.com:80'],
[['HTTPS_PROXY' => 'http://upper.com', 'https_proxy' => 'http://lower.com'], 'https://repo.org', 'http://lower.com:80'],
];
}
/**
* @dataProvider dataCGIProxy
*
* @param array<string, string> $server
*/
public function testCGIProxyIsOnlyUsedWhenNoHttpProxy(array $server, string $expectedUrl): void
{
$_SERVER = array_merge($_SERVER, $server);
$proxyManager = ProxyManager::getInstance();
$proxy = $proxyManager->getProxyForRequest('http://repo.org');
self::assertSame($expectedUrl, $proxy->getStatus());
}
/**
* @return list<array{0: array<string, string>, 1: string}>
*/
public static function dataCGIProxy(): array
{
// server, expectedUrl
return [
[['CGI_HTTP_PROXY' => 'http://cgi.com:80'], 'http://cgi.com:80'],
[['http_proxy' => 'http://http.com:80', 'CGI_HTTP_PROXY' => 'http://cgi.com:80'], 'http://http.com:80'],
];
}
public function testNoHttpProxyDoesNotUseHttpsProxy(): void
{
$_SERVER['https_proxy'] = 'https://proxy.com:443';
$proxyManager = ProxyManager::getInstance();
$proxy = $proxyManager->getProxyForRequest('http://repo.org');
self::assertSame('', $proxy->getStatus());
}
public function testNoHttpsProxyDoesNotUseHttpProxy(): void
{
$_SERVER['http_proxy'] = 'http://proxy.com:80';
$proxyManager = ProxyManager::getInstance();
$proxy = $proxyManager->getProxyForRequest('https://repo.org');
self::assertSame('', $proxy->getStatus());
}
/**
* @dataProvider dataRequest
*
* @param array<string, string> $server
* @param non-empty-string $url
* @param ?contextOptions $options
*/
public function testGetProxyForRequest(array $server, string $url, ?array $options, string $status, bool $excluded): void
{
$_SERVER = array_merge($_SERVER, $server);
$proxyManager = ProxyManager::getInstance();
$proxy = $proxyManager->getProxyForRequest($url);
self::assertSame($options, $proxy->getContextOptions());
self::assertSame($status, $proxy->getStatus());
self::assertSame($excluded, $proxy->isExcludedByNoProxy());
}
/**
* Tests context options. curl options are tested in RequestProxyTest.php
*
* @return list<array{0: array<string, string>, 1: string, 2: ?contextOptions, 3: string, 4: bool}>
*/
public static function dataRequest(): array
{
$server = [
'http_proxy' => 'http://user:p%40ss@proxy.com',
'https_proxy' => 'https://proxy.com:443',
'no_proxy' => 'other.repo.org',
];
// server, url, options, status, excluded
return [
[[], 'http://repo.org', null, '', false],
[$server, 'http://repo.org',
['http' => [
'proxy' => 'tcp://proxy.com:80',
'header' => 'Proxy-Authorization: Basic dXNlcjpwQHNz',
'request_fulluri' => true,
]],
'http://***:***@proxy.com:80',
false,
],
[$server, 'https://repo.org',
['http' => [
'proxy' => 'ssl://proxy.com:443',
]],
'https://proxy.com:443',
false,
],
[$server, 'https://other.repo.org', null, 'excluded by no_proxy', true],
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Config/JsonConfigSourceTest.php | tests/Composer/Test/Config/JsonConfigSourceTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Config;
use Composer\Config\JsonConfigSource;
use Composer\Json\JsonFile;
use Composer\Test\TestCase;
use Composer\Util\Filesystem;
class JsonConfigSourceTest extends TestCase
{
/** @var Filesystem */
private $fs;
/** @var string */
private $workingDir;
protected static function fixturePath(string $name): string
{
return __DIR__.'/Fixtures/'.$name;
}
protected function setUp(): void
{
$this->fs = new Filesystem;
$this->workingDir = self::getUniqueTmpDirectory();
}
protected function tearDown(): void
{
parent::tearDown();
if (is_dir($this->workingDir)) {
$this->fs->removeDirectory($this->workingDir);
}
}
public function testAddRepository(): void
{
$config = $this->workingDir.'/composer.json';
copy(self::fixturePath('composer-repositories.json'), $config);
$jsonConfigSource = new JsonConfigSource(new JsonFile($config));
$jsonConfigSource->addRepository('example_tld', ['type' => 'git', 'url' => 'example.tld']);
self::assertFileEquals(self::fixturePath('config/config-with-exampletld-repository.json'), $config);
}
public function testAddRepositoryAsList(): void
{
$config = $this->workingDir.'/composer.json';
copy(self::fixturePath('composer-repositories.json'), $config);
$jsonConfigSource = new JsonConfigSource(new JsonFile($config));
$jsonConfigSource->addRepository('', ['type' => 'git', 'url' => 'example.tld']);
self::assertFileEquals(self::fixturePath('config/config-with-exampletld-repository-as-list.json'), $config);
}
public function testAddRepositoryWithOptions(): void
{
$config = $this->workingDir.'/composer.json';
copy(self::fixturePath('composer-repositories.json'), $config);
$jsonConfigSource = new JsonConfigSource(new JsonFile($config));
$jsonConfigSource->addRepository('example_tld', [
'type' => 'composer',
'url' => 'https://example.tld',
'options' => [
'ssl' => [
'local_cert' => '/home/composer/.ssl/composer.pem',
],
],
]);
self::assertFileEquals(self::fixturePath('config/config-with-exampletld-repository-and-options.json'), $config);
}
public function testRemoveRepository(): void
{
$config = $this->workingDir.'/composer.json';
copy(self::fixturePath('config/config-with-exampletld-repository.json'), $config);
$jsonConfigSource = new JsonConfigSource(new JsonFile($config));
$jsonConfigSource->removeRepository('example_tld');
self::assertFileEquals(self::fixturePath('composer-empty.json'), $config);
}
public function testAddPackagistRepositoryWithFalseValue(): void
{
$config = $this->workingDir.'/composer.json';
copy(self::fixturePath('composer-repositories.json'), $config);
$jsonConfigSource = new JsonConfigSource(new JsonFile($config));
$jsonConfigSource->addRepository('packagist', false);
self::assertFileEquals(self::fixturePath('config/config-with-packagist-false.json'), $config);
}
public function testRemovePackagist(): void
{
$config = $this->workingDir.'/composer.json';
copy(self::fixturePath('config/config-with-packagist-false.json'), $config);
$jsonConfigSource = new JsonConfigSource(new JsonFile($config));
$jsonConfigSource->removeRepository('packagist');
self::assertFileEquals(self::fixturePath('composer-empty.json'), $config);
}
/**
* Test addLink()
*
* @param string $sourceFile Source file
* @param string $type Type (require, require-dev, provide, suggest, replace, conflict)
* @param string $name Name
* @param string $value Value
* @param string $compareAgainst File to compare against after making changes
*
* @dataProvider provideAddLinkData
*/
public function testAddLink(string $sourceFile, string $type, string $name, string $value, string $compareAgainst): void
{
$composerJson = $this->workingDir.'/composer.json';
copy($sourceFile, $composerJson);
$jsonConfigSource = new JsonConfigSource(new JsonFile($composerJson));
$jsonConfigSource->addLink($type, $name, $value);
self::assertFileEquals($compareAgainst, $composerJson);
}
/**
* Test removeLink()
*
* @param string $sourceFile Source file
* @param string $type Type (require, require-dev, provide, suggest, replace, conflict)
* @param string $name Name
* @param string $compareAgainst File to compare against after making changes
*
* @dataProvider provideRemoveLinkData
*/
public function testRemoveLink(string $sourceFile, string $type, string $name, string $compareAgainst): void
{
$composerJson = $this->workingDir.'/composer.json';
copy($sourceFile, $composerJson);
$jsonConfigSource = new JsonConfigSource(new JsonFile($composerJson));
$jsonConfigSource->removeLink($type, $name);
self::assertFileEquals($compareAgainst, $composerJson);
}
/**
* @return string[]
*
* @phpstan-return array{string, string, string, string, string}
*/
protected static function addLinkDataArguments(string $type, string $name, string $value, string $fixtureBasename, string $before): array
{
return [
$before,
$type,
$name,
$value,
self::fixturePath('addLink/'.$fixtureBasename.'.json'),
];
}
/**
* Provide data for testAddLink
*/
public static function provideAddLinkData(): array
{
$empty = self::fixturePath('composer-empty.json');
$oneOfEverything = self::fixturePath('composer-one-of-everything.json');
$twoOfEverything = self::fixturePath('composer-two-of-everything.json');
return [
self::addLinkDataArguments('require', 'my-vend/my-lib', '1.*', 'require-from-empty', $empty),
self::addLinkDataArguments('require', 'my-vend/my-lib', '1.*', 'require-from-oneOfEverything', $oneOfEverything),
self::addLinkDataArguments('require', 'my-vend/my-lib', '1.*', 'require-from-twoOfEverything', $twoOfEverything),
self::addLinkDataArguments('require-dev', 'my-vend/my-lib-tests', '1.*', 'require-dev-from-empty', $empty),
self::addLinkDataArguments('require-dev', 'my-vend/my-lib-tests', '1.*', 'require-dev-from-oneOfEverything', $oneOfEverything),
self::addLinkDataArguments('require-dev', 'my-vend/my-lib-tests', '1.*', 'require-dev-from-twoOfEverything', $twoOfEverything),
self::addLinkDataArguments('provide', 'my-vend/my-lib-interface', '1.*', 'provide-from-empty', $empty),
self::addLinkDataArguments('provide', 'my-vend/my-lib-interface', '1.*', 'provide-from-oneOfEverything', $oneOfEverything),
self::addLinkDataArguments('provide', 'my-vend/my-lib-interface', '1.*', 'provide-from-twoOfEverything', $twoOfEverything),
self::addLinkDataArguments('suggest', 'my-vend/my-optional-extension', '1.*', 'suggest-from-empty', $empty),
self::addLinkDataArguments('suggest', 'my-vend/my-optional-extension', '1.*', 'suggest-from-oneOfEverything', $oneOfEverything),
self::addLinkDataArguments('suggest', 'my-vend/my-optional-extension', '1.*', 'suggest-from-twoOfEverything', $twoOfEverything),
self::addLinkDataArguments('replace', 'my-vend/other-app', '1.*', 'replace-from-empty', $empty),
self::addLinkDataArguments('replace', 'my-vend/other-app', '1.*', 'replace-from-oneOfEverything', $oneOfEverything),
self::addLinkDataArguments('replace', 'my-vend/other-app', '1.*', 'replace-from-twoOfEverything', $twoOfEverything),
self::addLinkDataArguments('conflict', 'my-vend/my-old-app', '1.*', 'conflict-from-empty', $empty),
self::addLinkDataArguments('conflict', 'my-vend/my-old-app', '1.*', 'conflict-from-oneOfEverything', $oneOfEverything),
self::addLinkDataArguments('conflict', 'my-vend/my-old-app', '1.*', 'conflict-from-twoOfEverything', $twoOfEverything),
];
}
/**
* @return string[]
*
* @phpstan-return array{string, string, string, string}
*/
protected static function removeLinkDataArguments(string $type, string $name, string $fixtureBasename, ?string $after = null): array
{
return [
self::fixturePath('removeLink/'.$fixtureBasename.'.json'),
$type,
$name,
$after ?: self::fixturePath('removeLink/'.$fixtureBasename.'-after.json'),
];
}
/**
* Provide data for testRemoveLink
*/
public static function provideRemoveLinkData(): array
{
$oneOfEverything = self::fixturePath('composer-one-of-everything.json');
$twoOfEverything = self::fixturePath('composer-two-of-everything.json');
return [
self::removeLinkDataArguments('require', 'my-vend/my-lib', 'require-to-empty'),
self::removeLinkDataArguments('require', 'my-vend/my-lib', 'require-to-oneOfEverything', $oneOfEverything),
self::removeLinkDataArguments('require', 'my-vend/my-lib', 'require-to-twoOfEverything', $twoOfEverything),
self::removeLinkDataArguments('require-dev', 'my-vend/my-lib-tests', 'require-dev-to-empty'),
self::removeLinkDataArguments('require-dev', 'my-vend/my-lib-tests', 'require-dev-to-oneOfEverything', $oneOfEverything),
self::removeLinkDataArguments('require-dev', 'my-vend/my-lib-tests', 'require-dev-to-twoOfEverything', $twoOfEverything),
self::removeLinkDataArguments('provide', 'my-vend/my-lib-interface', 'provide-to-empty'),
self::removeLinkDataArguments('provide', 'my-vend/my-lib-interface', 'provide-to-oneOfEverything', $oneOfEverything),
self::removeLinkDataArguments('provide', 'my-vend/my-lib-interface', 'provide-to-twoOfEverything', $twoOfEverything),
self::removeLinkDataArguments('suggest', 'my-vend/my-optional-extension', 'suggest-to-empty'),
self::removeLinkDataArguments('suggest', 'my-vend/my-optional-extension', 'suggest-to-oneOfEverything', $oneOfEverything),
self::removeLinkDataArguments('suggest', 'my-vend/my-optional-extension', 'suggest-to-twoOfEverything', $twoOfEverything),
self::removeLinkDataArguments('replace', 'my-vend/other-app', 'replace-to-empty'),
self::removeLinkDataArguments('replace', 'my-vend/other-app', 'replace-to-oneOfEverything', $oneOfEverything),
self::removeLinkDataArguments('replace', 'my-vend/other-app', 'replace-to-twoOfEverything', $twoOfEverything),
self::removeLinkDataArguments('conflict', 'my-vend/my-old-app', 'conflict-to-empty'),
self::removeLinkDataArguments('conflict', 'my-vend/my-old-app', 'conflict-to-oneOfEverything', $oneOfEverything),
self::removeLinkDataArguments('conflict', 'my-vend/my-old-app', 'conflict-to-twoOfEverything', $twoOfEverything),
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Package/BasePackageTest.php | tests/Composer/Test/Package/BasePackageTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Package;
use Composer\Package\BasePackage;
use Composer\Test\TestCase;
class BasePackageTest extends TestCase
{
/**
* @doesNotPerformAssertions
*/
public function testSetSameRepository(): void
{
$package = $this->getMockForAbstractClass('Composer\Package\BasePackage', ['foo']);
$repository = $this->getMockBuilder('Composer\Repository\RepositoryInterface')->getMock();
$package->setRepository($repository);
try {
$package->setRepository($repository);
} catch (\Exception $e) {
$this->fail('Set against the same repository is allowed.');
}
}
public function testSetAnotherRepository(): void
{
self::expectException('LogicException');
$package = $this->getMockForAbstractClass('Composer\Package\BasePackage', ['foo']);
$package->setRepository($this->getMockBuilder('Composer\Repository\RepositoryInterface')->getMock());
$package->setRepository($this->getMockBuilder('Composer\Repository\RepositoryInterface')->getMock());
}
/**
* @dataProvider provideFormattedVersions
*/
public function testFormatVersionForDevPackage(string $sourceReference, bool $truncate, string $expected): void
{
$package = $this->getMockForAbstractClass('\Composer\Package\BasePackage', [], '', false);
$package->expects($this->once())->method('isDev')->will($this->returnValue(true));
$package->expects($this->any())->method('getSourceType')->will($this->returnValue('git'));
$package->expects($this->once())->method('getPrettyVersion')->will($this->returnValue('PrettyVersion'));
$package->expects($this->any())->method('getSourceReference')->will($this->returnValue($sourceReference));
self::assertSame($expected, $package->getFullPrettyVersion($truncate));
}
public static function provideFormattedVersions(): array
{
return [
[
'sourceReference' => 'v2.1.0-RC2',
'truncate' => true,
'expected' => 'PrettyVersion v2.1.0-RC2',
],
[
'sourceReference' => 'bbf527a27356414bfa9bf520f018c5cb7af67c77',
'truncate' => true,
'expected' => 'PrettyVersion bbf527a',
],
[
'sourceReference' => 'v1.0.0',
'truncate' => false,
'expected' => 'PrettyVersion v1.0.0',
],
[
'sourceReference' => 'bbf527a27356414bfa9bf520f018c5cb7af67c77',
'truncate' => false,
'expected' => 'PrettyVersion bbf527a27356414bfa9bf520f018c5cb7af67c77',
],
];
}
/**
* @param string[] $packageNames
* @param non-empty-string $wrap
*
* @dataProvider dataPackageNamesToRegexp
*/
public function testPackageNamesToRegexp(array $packageNames, $wrap, string $expectedRegexp): void
{
$regexp = BasePackage::packageNamesToRegexp($packageNames, $wrap);
self::assertSame($expectedRegexp, $regexp);
}
/**
* @return mixed[][]
*/
public static function dataPackageNamesToRegexp(): array
{
return [
[
['ext-*', 'monolog/monolog'], '{^%s$}i', '{^ext\-.*|monolog/monolog$}i',
['php'], '{^%s$}i', '{^php$}i',
['*'], '{^%s$}i', '{^.*$}i',
['foo', 'bar'], '§%s§', '§foo|bar§',
],
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Package/RootAliasPackageTest.php | tests/Composer/Test/Package/RootAliasPackageTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Package;
use Composer\Package\Link;
use Composer\Package\RootAliasPackage;
use Composer\Package\RootPackage;
use Composer\Semver\Constraint\MatchAllConstraint;
use Composer\Test\TestCase;
use PHPUnit\Framework\MockObject\MockObject;
class RootAliasPackageTest extends TestCase
{
public function testUpdateRequires(): void
{
$links = [new Link('a', 'b', new MatchAllConstraint(), Link::TYPE_REQUIRE, 'self.version')];
$root = $this->getMockRootPackage();
$root->expects($this->once())
->method('setRequires')
->with($this->equalTo($links));
$alias = new RootAliasPackage($root, '1.0', '1.0.0.0');
self::assertEmpty($alias->getRequires());
$alias->setRequires($links);
self::assertNotEmpty($alias->getRequires());
}
public function testUpdateDevRequires(): void
{
$links = [new Link('a', 'b', new MatchAllConstraint(), Link::TYPE_DEV_REQUIRE, 'self.version')];
$root = $this->getMockRootPackage();
$root->expects($this->once())
->method('setDevRequires')
->with($this->equalTo($links));
$alias = new RootAliasPackage($root, '1.0', '1.0.0.0');
self::assertEmpty($alias->getDevRequires());
$alias->setDevRequires($links);
self::assertNotEmpty($alias->getDevRequires());
}
public function testUpdateConflicts(): void
{
$links = [new Link('a', 'b', new MatchAllConstraint(), Link::TYPE_CONFLICT, 'self.version')];
$root = $this->getMockRootPackage();
$root->expects($this->once())
->method('setConflicts')
->with($this->equalTo($links));
$alias = new RootAliasPackage($root, '1.0', '1.0.0.0');
self::assertEmpty($alias->getConflicts());
$alias->setConflicts($links);
self::assertNotEmpty($alias->getConflicts());
}
public function testUpdateProvides(): void
{
$links = [new Link('a', 'b', new MatchAllConstraint(), Link::TYPE_PROVIDE, 'self.version')];
$root = $this->getMockRootPackage();
$root->expects($this->once())
->method('setProvides')
->with($this->equalTo($links));
$alias = new RootAliasPackage($root, '1.0', '1.0.0.0');
self::assertEmpty($alias->getProvides());
$alias->setProvides($links);
self::assertNotEmpty($alias->getProvides());
}
public function testUpdateReplaces(): void
{
$links = [new Link('a', 'b', new MatchAllConstraint(), Link::TYPE_REPLACE, 'self.version')];
$root = $this->getMockRootPackage();
$root->expects($this->once())
->method('setReplaces')
->with($this->equalTo($links));
$alias = new RootAliasPackage($root, '1.0', '1.0.0.0');
self::assertEmpty($alias->getReplaces());
$alias->setReplaces($links);
self::assertNotEmpty($alias->getReplaces());
}
/**
* @return RootPackage&MockObject
*/
protected function getMockRootPackage()
{
$root = $this->getMockBuilder(RootPackage::class)->disableOriginalConstructor()->getMock();
$root->expects($this->atLeastOnce())
->method('getName')
->willReturn('something/something');
$root->expects($this->atLeastOnce())
->method('getRequires')
->willReturn([]);
$root->expects($this->atLeastOnce())
->method('getDevRequires')
->willReturn([]);
$root->expects($this->atLeastOnce())
->method('getConflicts')
->willReturn([]);
$root->expects($this->atLeastOnce())
->method('getProvides')
->willReturn([]);
$root->expects($this->atLeastOnce())
->method('getReplaces')
->willReturn([]);
return $root;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Package/LockerTest.php | tests/Composer/Test/Package/LockerTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Package;
use Composer\Json\JsonFile;
use Composer\Package\Locker;
use Composer\Plugin\PluginInterface;
use Composer\IO\NullIO;
use Composer\Test\TestCase;
class LockerTest extends TestCase
{
public function testIsLocked(): void
{
$json = $this->createJsonFileMock();
$locker = new Locker(
new NullIO,
$json,
$this->createInstallationManagerMock(),
$this->getJsonContent()
);
$json
->expects($this->any())
->method('exists')
->will($this->returnValue(true));
$json
->expects($this->any())
->method('read')
->will($this->returnValue(['packages' => []]));
self::assertTrue($locker->isLocked());
}
public function testGetNotLockedPackages(): void
{
$json = $this->createJsonFileMock();
$inst = $this->createInstallationManagerMock();
$locker = new Locker(new NullIO, $json, $inst, $this->getJsonContent());
$json
->expects($this->once())
->method('exists')
->will($this->returnValue(false));
self::expectException('LogicException');
$locker->getLockedRepository();
}
public function testGetLockedPackages(): void
{
$json = $this->createJsonFileMock();
$inst = $this->createInstallationManagerMock();
$locker = new Locker(new NullIO, $json, $inst, $this->getJsonContent());
$json
->expects($this->once())
->method('exists')
->will($this->returnValue(true));
$json
->expects($this->once())
->method('read')
->will($this->returnValue([
'packages' => [
['name' => 'pkg1', 'version' => '1.0.0-beta'],
['name' => 'pkg2', 'version' => '0.1.10'],
],
]));
$repo = $locker->getLockedRepository();
self::assertNotNull($repo->findPackage('pkg1', '1.0.0-beta'));
self::assertNotNull($repo->findPackage('pkg2', '0.1.10'));
}
public function testSetLockData(): void
{
$json = $this->createJsonFileMock();
$inst = $this->createInstallationManagerMock();
$jsonContent = $this->getJsonContent() . ' ';
$locker = new Locker(new NullIO, $json, $inst, $jsonContent);
$package1 = self::getPackage('pkg1', '1.0.0-beta');
$package2 = self::getPackage('pkg2', '0.1.10');
$contentHash = hash('md5', trim($jsonContent));
$json
->expects($this->once())
->method('write')
->with([
'_readme' => ['This file locks the dependencies of your project to a known state',
'Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies',
'This file is @gener'.'ated automatically', ],
'content-hash' => $contentHash,
'packages' => [
['name' => 'pkg1', 'version' => '1.0.0-beta', 'type' => 'library'],
['name' => 'pkg2', 'version' => '0.1.10', 'type' => 'library'],
],
'packages-dev' => [],
'aliases' => [],
'minimum-stability' => 'dev',
'stability-flags' => new \stdClass,
'platform' => new \stdClass,
'platform-dev' => new \stdClass,
'platform-overrides' => ['foo/bar' => '1.0'],
'prefer-stable' => false,
'prefer-lowest' => false,
'plugin-api-version' => PluginInterface::PLUGIN_API_VERSION,
]);
$locker->setLockData([$package1, $package2], [], [], [], [], 'dev', [], false, false, ['foo/bar' => '1.0']);
}
public function testLockBadPackages(): void
{
$json = $this->createJsonFileMock();
$inst = $this->createInstallationManagerMock();
$locker = new Locker(new NullIO, $json, $inst, $this->getJsonContent());
$package1 = $this->createPackageMock();
$package1
->expects($this->once())
->method('getPrettyName')
->will($this->returnValue('pkg1'));
self::expectException('LogicException');
$locker->setLockData([$package1], [], [], [], [], 'dev', [], false, false, []);
}
public function testIsFresh(): void
{
$json = $this->createJsonFileMock();
$inst = $this->createInstallationManagerMock();
$jsonContent = $this->getJsonContent();
$locker = new Locker(new NullIO, $json, $inst, $jsonContent);
$json
->expects($this->once())
->method('read')
->will($this->returnValue(['hash' => hash('md5', $jsonContent)]));
self::assertTrue($locker->isFresh());
}
public function testIsFreshFalse(): void
{
$json = $this->createJsonFileMock();
$inst = $this->createInstallationManagerMock();
$locker = new Locker(new NullIO, $json, $inst, $this->getJsonContent());
$json
->expects($this->once())
->method('read')
->will($this->returnValue(['hash' => $this->getJsonContent(['name' => 'test2'])]));
self::assertFalse($locker->isFresh());
}
public function testIsFreshWithContentHash(): void
{
$json = $this->createJsonFileMock();
$inst = $this->createInstallationManagerMock();
$jsonContent = $this->getJsonContent();
$locker = new Locker(new NullIO, $json, $inst, $jsonContent);
$json
->expects($this->once())
->method('read')
->will($this->returnValue(['hash' => hash('md5', $jsonContent . ' '), 'content-hash' => hash('md5', $jsonContent)]));
self::assertTrue($locker->isFresh());
}
public function testIsFreshWithContentHashAndNoHash(): void
{
$json = $this->createJsonFileMock();
$inst = $this->createInstallationManagerMock();
$jsonContent = $this->getJsonContent();
$locker = new Locker(new NullIO, $json, $inst, $jsonContent);
$json
->expects($this->once())
->method('read')
->will($this->returnValue(['content-hash' => hash('md5', $jsonContent)]));
self::assertTrue($locker->isFresh());
}
public function testIsFreshFalseWithContentHash(): void
{
$json = $this->createJsonFileMock();
$inst = $this->createInstallationManagerMock();
$locker = new Locker(new NullIO, $json, $inst, $this->getJsonContent());
$differentHash = hash('md5', $this->getJsonContent(['name' => 'test2']));
$json
->expects($this->once())
->method('read')
->will($this->returnValue(['hash' => $differentHash, 'content-hash' => $differentHash]));
self::assertFalse($locker->isFresh());
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject&JsonFile
*/
private function createJsonFileMock()
{
return $this->getMockBuilder('Composer\Json\JsonFile')
->disableOriginalConstructor()
->getMock();
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Installer\InstallationManager
*/
private function createInstallationManagerMock()
{
$mock = $this->getMockBuilder('Composer\Installer\InstallationManager')
->disableOriginalConstructor()
->getMock();
return $mock;
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Package\PackageInterface
*/
private function createPackageMock()
{
return $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
}
/**
* @param array<string, string> $customData
*/
private function getJsonContent(array $customData = []): string
{
$data = array_merge([
'minimum-stability' => 'beta',
'name' => 'test',
], $customData);
ksort($data);
return JsonFile::encode($data, 0);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Package/CompletePackageTest.php | tests/Composer/Test/Package/CompletePackageTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Package;
use Composer\Package\Package;
use Composer\Semver\VersionParser;
use Composer\Test\TestCase;
class CompletePackageTest extends TestCase
{
/**
* Memory package naming, versioning, and marshalling semantics provider
*
* demonstrates several versioning schemes
*/
public static function providerVersioningSchemes(): array
{
$provider[] = ['foo', '1-beta'];
$provider[] = ['node', '0.5.6'];
$provider[] = ['li3', '0.10'];
$provider[] = ['mongodb_odm', '1.0.0BETA3'];
$provider[] = ['DoctrineCommon', '2.2.0-DEV'];
return $provider;
}
/**
* @dataProvider providerVersioningSchemes
*/
public function testPackageHasExpectedNamingSemantics(string $name, string $version): void
{
$versionParser = new VersionParser();
$normVersion = $versionParser->normalize($version);
$package = new Package($name, $normVersion, $version);
self::assertEquals(strtolower($name), $package->getName());
}
/**
* @dataProvider providerVersioningSchemes
*/
public function testPackageHasExpectedVersioningSemantics(string $name, string $version): void
{
$versionParser = new VersionParser();
$normVersion = $versionParser->normalize($version);
$package = new Package($name, $normVersion, $version);
self::assertEquals($version, $package->getPrettyVersion());
self::assertEquals($normVersion, $package->getVersion());
}
/**
* @dataProvider providerVersioningSchemes
*/
public function testPackageHasExpectedMarshallingSemantics(string $name, string $version): void
{
$versionParser = new VersionParser();
$normVersion = $versionParser->normalize($version);
$package = new Package($name, $normVersion, $version);
self::assertEquals(strtolower($name).'-'.$normVersion, (string) $package);
}
public function testGetTargetDir(): void
{
$package = new Package('a', '1.0.0.0', '1.0');
self::assertNull($package->getTargetDir());
$package->setTargetDir('./../foo/');
self::assertEquals('foo/', $package->getTargetDir());
$package->setTargetDir('foo/../../../bar/');
self::assertEquals('foo/bar/', $package->getTargetDir());
$package->setTargetDir('../..');
self::assertEquals('', $package->getTargetDir());
$package->setTargetDir('..');
self::assertEquals('', $package->getTargetDir());
$package->setTargetDir('/..');
self::assertEquals('', $package->getTargetDir());
$package->setTargetDir('/foo/..');
self::assertEquals('foo/', $package->getTargetDir());
$package->setTargetDir('/foo/..//bar');
self::assertEquals('foo/bar', $package->getTargetDir());
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Package/Archiver/ArchiveManagerTest.php | tests/Composer/Test/Package/Archiver/ArchiveManagerTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Package\Archiver;
use Composer\IO\NullIO;
use Composer\Factory;
use Composer\Package\Archiver\ArchiveManager;
use Composer\Package\CompletePackage;
use Composer\Util\Loop;
use Composer\Test\Mock\FactoryMock;
use Composer\Util\Platform;
use Composer\Util\ProcessExecutor;
class ArchiveManagerTest extends ArchiverTestCase
{
/**
* @var ArchiveManager
*/
protected $manager;
/**
* @var string
*/
protected $targetDir;
public function setUp(): void
{
parent::setUp();
$factory = new Factory();
$dm = $factory->createDownloadManager(
$io = new NullIO,
$config = FactoryMock::createConfig(),
$httpDownloader = $factory->createHttpDownloader($io, $config),
new ProcessExecutor($io)
);
$loop = new Loop($httpDownloader);
$this->manager = $factory->createArchiveManager($factory->createConfig(), $dm, $loop);
$this->targetDir = $this->testDir.'/composer_archiver_tests';
}
public function testUnknownFormat(): void
{
self::expectException('RuntimeException');
$package = $this->setupPackage();
$this->manager->archive($package, '__unknown_format__', $this->targetDir);
}
public function testArchiveTar(): void
{
$this->skipIfNotExecutable('git');
$this->setupGitRepo();
$package = $this->setupPackage();
$this->manager->archive($package, 'tar', $this->targetDir);
$target = $this->getTargetName($package, 'tar');
self::assertFileExists($target);
$tmppath = sys_get_temp_dir().'/composer_archiver/'.$this->manager->getPackageFilename($package);
self::assertFileDoesNotExist($tmppath);
unlink($target);
}
public function testArchiveCustomFileName(): void
{
$this->skipIfNotExecutable('git');
$this->setupGitRepo();
$package = $this->setupPackage();
$fileName = 'testArchiveName';
$this->manager->archive($package, 'tar', $this->targetDir, $fileName);
$target = $this->targetDir . '/' . $fileName . '.tar';
self::assertFileExists($target);
$tmppath = sys_get_temp_dir().'/composer_archiver/'.$this->manager->getPackageFilename($package);
self::assertFileDoesNotExist($tmppath);
unlink($target);
}
public function testGetPackageFilenameParts(): void
{
$expected = [
'base' => 'archivertest-archivertest',
'version' => 'master',
'source_reference' => '4f26ae',
];
$package = $this->setupPackage();
self::assertSame(
$expected,
$this->manager->getPackageFilenameParts($package)
);
}
public function testGetPackageFilename(): void
{
$package = $this->setupPackage();
self::assertSame(
'archivertest-archivertest-master-4f26ae',
$this->manager->getPackageFilename($package)
);
}
protected function getTargetName(CompletePackage $package, string $format, ?string $fileName = null): string
{
if (null === $fileName) {
$packageName = $this->manager->getPackageFilename($package);
} else {
$packageName = $fileName;
}
return $this->targetDir.'/'.$packageName.'.'.$format;
}
/**
* Create local git repository to run tests against!
*/
protected function setupGitRepo(): void
{
$currentWorkDir = Platform::getCwd();
chdir($this->testDir);
$output = null;
$result = $this->process->execute('git init -q', $output, $this->testDir);
if ($result > 0) {
chdir($currentWorkDir);
throw new \RuntimeException('Could not init: '.$this->process->getErrorOutput());
}
$result = $this->process->execute('git checkout -b master', $output, $this->testDir);
if ($result > 0) {
chdir($currentWorkDir);
throw new \RuntimeException('Could not checkout master branch: '.$this->process->getErrorOutput());
}
$result = $this->process->execute('git config user.email "you@example.com"', $output, $this->testDir);
if ($result > 0) {
chdir($currentWorkDir);
throw new \RuntimeException('Could not config: '.$this->process->getErrorOutput());
}
$result = $this->process->execute('git config commit.gpgsign false', $output, $this->testDir);
if ($result > 0) {
chdir($currentWorkDir);
throw new \RuntimeException('Could not config: '.$this->process->getErrorOutput());
}
$result = $this->process->execute('git config user.name "Your Name"', $output, $this->testDir);
if ($result > 0) {
chdir($currentWorkDir);
throw new \RuntimeException('Could not config: '.$this->process->getErrorOutput());
}
$result = file_put_contents('composer.json', '{"name":"faker/faker", "description": "description", "license": "MIT"}');
if (false === $result) {
chdir($currentWorkDir);
throw new \RuntimeException('Could not save file.');
}
$result = $this->process->execute('git add composer.json && git commit -m "commit composer.json" -q', $output, $this->testDir);
if ($result > 0) {
chdir($currentWorkDir);
throw new \RuntimeException('Could not commit: '.$this->process->getErrorOutput());
}
chdir($currentWorkDir);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Package/Archiver/PharArchiverTest.php | tests/Composer/Test/Package/Archiver/PharArchiverTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Package\Archiver;
use Composer\Package\Archiver\PharArchiver;
use Composer\Util\Platform;
class PharArchiverTest extends ArchiverTestCase
{
public function testTarArchive(): void
{
// Set up repository
$this->setupDummyRepo();
$package = $this->setupPackage();
$target = self::getUniqueTmpDirectory().'/composer_archiver_test.tar';
// Test archive
$archiver = new PharArchiver();
$archiver->archive($package->getSourceUrl(), $target, 'tar', ['foo/bar', 'baz', '!/foo/bar/baz']);
self::assertFileExists($target);
$this->filesystem->removeDirectory(dirname($target));
}
public function testZipArchive(): void
{
// Set up repository
$this->setupDummyRepo();
$package = $this->setupPackage();
$target = self::getUniqueTmpDirectory().'/composer_archiver_test.zip';
// Test archive
$archiver = new PharArchiver();
$archiver->archive($package->getSourceUrl(), $target, 'zip');
self::assertFileExists($target);
$this->filesystem->removeDirectory(dirname($target));
}
/**
* Create a local dummy repository to run tests against!
*/
protected function setupDummyRepo(): void
{
$currentWorkDir = Platform::getCwd();
chdir($this->testDir);
$this->writeFile('file.txt', 'content', $currentWorkDir);
$this->writeFile('foo/bar/baz', 'content', $currentWorkDir);
$this->writeFile('foo/bar/ignoreme', 'content', $currentWorkDir);
$this->writeFile('x/baz', 'content', $currentWorkDir);
$this->writeFile('x/includeme', 'content', $currentWorkDir);
chdir($currentWorkDir);
}
protected function writeFile(string $path, string $content, string $currentWorkDir): void
{
if (!file_exists(dirname($path))) {
mkdir(dirname($path), 0777, true);
}
$result = file_put_contents($path, $content);
if (false === $result) {
chdir($currentWorkDir);
throw new \RuntimeException('Could not save file.');
}
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Package/Archiver/ArchiverTestCase.php | tests/Composer/Test/Package/Archiver/ArchiverTestCase.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Package\Archiver;
use Composer\Test\TestCase;
use Composer\Util\Filesystem;
use Composer\Util\ProcessExecutor;
use Composer\Package\CompletePackage;
abstract class ArchiverTestCase extends TestCase
{
/**
* @var Filesystem
*/
protected $filesystem;
/**
* @var ProcessExecutor
*/
protected $process;
/**
* @var string
*/
protected $testDir;
public function setUp(): void
{
$this->filesystem = new Filesystem();
$this->process = new ProcessExecutor();
$this->testDir = self::getUniqueTmpDirectory();
}
protected function tearDown(): void
{
parent::tearDown();
$this->filesystem->removeDirectory($this->testDir);
}
/**
* Util method to quickly setup a package using the source path built.
*/
protected function setupPackage(): CompletePackage
{
$package = new CompletePackage('archivertest/archivertest', 'master', 'master');
$package->setSourceUrl((string) realpath($this->testDir));
$package->setSourceReference('master');
$package->setSourceType('git');
return $package;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Package/Archiver/GitExcludeFilterTest.php | tests/Composer/Test/Package/Archiver/GitExcludeFilterTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Package\Archiver;
use Composer\Package\Archiver\GitExcludeFilter;
use Composer\Test\TestCase;
class GitExcludeFilterTest extends TestCase
{
/**
* @dataProvider providePatterns
*
* @param mixed[] $expected
*/
public function testPatternEscape(string $ignore, array $expected): void
{
$filter = new GitExcludeFilter('/');
self::assertEquals($expected, $filter->parseGitAttributesLine($ignore));
}
public static function providePatterns(): array
{
return [
['app/config/parameters.yml export-ignore', ['{(?=[^\.])app/(?=[^\.])config/(?=[^\.])parameters\.yml(?=$|/)}', false, false]],
['app/config/parameters.yml -export-ignore', ['{(?=[^\.])app/(?=[^\.])config/(?=[^\.])parameters\.yml(?=$|/)}', true, false]],
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Package/Archiver/ZipArchiverTest.php | tests/Composer/Test/Package/Archiver/ZipArchiverTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Package\Archiver;
use Composer\Util\Platform;
use ZipArchive;
use Composer\Package\Archiver\ZipArchiver;
class ZipArchiverTest extends ArchiverTestCase
{
/** @var list<string> */
private $filesToCleanup = [];
public function testSimpleFiles(): void
{
$files = [
'file.txt' => null,
'foo/bar/baz' => null,
'x/baz' => null,
'x/includeme' => null,
];
if (!Platform::isWindows()) {
$files['zfoo' . Platform::getCwd() . '/file.txt'] = null;
}
$this->assertZipArchive($files);
}
/**
* @dataProvider provideGitignoreExcludeNegationTestCases
*/
public function testGitignoreExcludeNegation(string $include): void
{
$this->assertZipArchive([
'.gitignore' => "/*\n.*\n!.git*\n$include",
'docs/README.md' => '# The doc',
]);
}
public static function provideGitignoreExcludeNegationTestCases(): array
{
return [
['!/docs'],
['!/docs/'],
];
}
public function testFolderWithBackslashes(): void
{
if (Platform::isWindows()) {
$this->markTestSkipped('Folder names cannot contain backslashes on Windows.');
}
$this->assertZipArchive([
'folder\with\backslashes/README.md' => '# doc',
]);
}
/**
* @param array<string, string|null> $files
*/
protected function assertZipArchive(array $files): void
{
if (!class_exists('ZipArchive')) {
$this->markTestSkipped('Cannot run ZipArchiverTest, missing class "ZipArchive".');
}
// Set up repository
$this->setupDummyRepo($files);
$package = $this->setupPackage();
$target = $this->filesToCleanup[] = sys_get_temp_dir().'/composer_archiver_test.zip';
// Test archive
$archiver = new ZipArchiver();
$archiver->archive($package->getSourceUrl(), $target, 'zip');
static::assertFileExists($target);
$zip = new ZipArchive();
$res = $zip->open($target);
static::assertTrue($res, 'Failed asserting that Zip file can be opened');
$zipContents = [];
for ($i = 0; $i < $zip->numFiles; $i++) {
$path = $zip->getNameIndex($i);
static::assertIsString($path);
$zipContents[$path] = $zip->getFromName($path);
}
$zip->close();
static::assertSame(
$files,
$zipContents,
'Failed asserting that Zip created with the ZipArchiver contains all files from the repository.'
);
}
/**
* Create a local dummy repository to run tests against!
*
* @param array<string, string|null> $files
*/
protected function setupDummyRepo(array &$files): void
{
$currentWorkDir = Platform::getCwd();
chdir($this->testDir);
foreach ($files as $path => $content) {
if ($files[$path] === null) {
$files[$path] = 'content';
}
$this->writeFile($path, $files[$path], $currentWorkDir);
}
chdir($currentWorkDir);
}
protected function writeFile(string $path, string $content, string $currentWorkDir): void
{
if (!file_exists(dirname($path))) {
mkdir(dirname($path), 0777, true);
}
$result = file_put_contents($path, $content);
if (false === $result) {
chdir($currentWorkDir);
throw new \RuntimeException('Could not save file.');
}
}
protected function tearDown(): void
{
foreach ($this->filesToCleanup as $file) {
unlink($file);
}
parent::tearDown();
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Package/Archiver/ArchivableFilesFinderTest.php | tests/Composer/Test/Package/Archiver/ArchivableFilesFinderTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Package\Archiver;
use Composer\Package\Archiver\ArchivableFilesFinder;
use Composer\Pcre\Preg;
use Composer\Test\TestCase;
use Composer\Util\Filesystem;
use Symfony\Component\Process\Process;
class ArchivableFilesFinderTest extends TestCase
{
/**
* @var string
*/
protected $sources;
/**
* @var ArchivableFilesFinder
*/
protected $finder;
/**
* @var Filesystem
*/
protected $fs;
protected function setUp(): void
{
$fs = new Filesystem;
$this->fs = $fs;
$this->sources = $fs->normalizePath(
self::getUniqueTmpDirectory()
);
$fileTree = [
'.foo',
'A/prefixA.foo',
'A/prefixB.foo',
'A/prefixC.foo',
'A/prefixD.foo',
'A/prefixE.foo',
'A/prefixF.foo',
'B/sub/prefixA.foo',
'B/sub/prefixB.foo',
'B/sub/prefixC.foo',
'B/sub/prefixD.foo',
'B/sub/prefixE.foo',
'B/sub/prefixF.foo',
'C/prefixA.foo',
'C/prefixB.foo',
'C/prefixC.foo',
'C/prefixD.foo',
'C/prefixE.foo',
'C/prefixF.foo',
'D/prefixA',
'D/prefixB',
'D/prefixC',
'D/prefixD',
'D/prefixE',
'D/prefixF',
'E/subtestA.foo',
'F/subtestA.foo',
'G/subtestA.foo',
'H/subtestA.foo',
'I/J/subtestA.foo',
'K/dirJ/subtestA.foo',
'toplevelA.foo',
'toplevelB.foo',
'prefixA.foo',
'prefixB.foo',
'prefixC.foo',
'prefixD.foo',
'prefixE.foo',
'prefixF.foo',
'parameters.yml',
'parameters.yml.dist',
'!important!.txt',
'!important_too!.txt',
'#weirdfile',
];
foreach ($fileTree as $relativePath) {
$path = $this->sources.'/'.$relativePath;
$fs->ensureDirectoryExists(dirname($path));
file_put_contents($path, '');
}
}
protected function tearDown(): void
{
parent::tearDown();
$fs = new Filesystem;
$fs->removeDirectory($this->sources);
}
public function testManualExcludes(): void
{
$excludes = [
'prefixB.foo',
'!/prefixB.foo',
'/prefixA.foo',
'prefixC.*',
'!*/*/*/prefixC.foo',
'.*',
];
$this->finder = new ArchivableFilesFinder($this->sources, $excludes);
self::assertArchivableFiles([
'/!important!.txt',
'/!important_too!.txt',
'/#weirdfile',
'/A/prefixA.foo',
'/A/prefixD.foo',
'/A/prefixE.foo',
'/A/prefixF.foo',
'/B/sub/prefixA.foo',
'/B/sub/prefixC.foo',
'/B/sub/prefixD.foo',
'/B/sub/prefixE.foo',
'/B/sub/prefixF.foo',
'/C/prefixA.foo',
'/C/prefixD.foo',
'/C/prefixE.foo',
'/C/prefixF.foo',
'/D/prefixA',
'/D/prefixB',
'/D/prefixC',
'/D/prefixD',
'/D/prefixE',
'/D/prefixF',
'/E/subtestA.foo',
'/F/subtestA.foo',
'/G/subtestA.foo',
'/H/subtestA.foo',
'/I/J/subtestA.foo',
'/K/dirJ/subtestA.foo',
'/parameters.yml',
'/parameters.yml.dist',
'/prefixB.foo',
'/prefixD.foo',
'/prefixE.foo',
'/prefixF.foo',
'/toplevelA.foo',
'/toplevelB.foo',
]);
}
public function testGitExcludes(): void
{
$this->skipIfNotExecutable('git');
file_put_contents($this->sources.'/.gitattributes', implode("\n", [
'',
'# gitattributes rules with comments and blank lines',
'prefixB.foo export-ignore',
'/prefixA.foo export-ignore',
'prefixC.* export-ignore',
'',
'prefixE.foo export-ignore',
'# and more',
'# comments',
'',
'/prefixE.foo -export-ignore',
'/prefixD.foo export-ignore',
'prefixF.* export-ignore',
'/*/*/prefixF.foo -export-ignore',
'',
'refixD.foo export-ignore',
'/C export-ignore',
'D/prefixA export-ignore',
'E export-ignore',
'F/ export-ignore',
'G/* export-ignore',
'H/** export-ignore',
'J/ export-ignore',
'parameters.yml export-ignore',
'\!important!.txt export-ignore',
'\#* export-ignore',
]));
$this->finder = new ArchivableFilesFinder($this->sources, []);
self::assertArchivableFiles($this->getArchivedFiles(
'git init && '.
'git config user.email "you@example.com" && '.
'git config user.name "Your Name" && '.
'git config commit.gpgsign false && '.
'git add .git* && '.
'git commit -m "ignore rules" && '.
'git add . && '.
'git commit -m "init" && '.
'git archive --format=zip --prefix=archive/ -o archive.zip HEAD'
));
}
public function testSkipExcludes(): void
{
$excludes = [
'prefixB.foo',
];
$this->finder = new ArchivableFilesFinder($this->sources, $excludes, true);
self::assertArchivableFiles([
'/!important!.txt',
'/!important_too!.txt',
'/#weirdfile',
'/.foo',
'/A/prefixA.foo',
'/A/prefixB.foo',
'/A/prefixC.foo',
'/A/prefixD.foo',
'/A/prefixE.foo',
'/A/prefixF.foo',
'/B/sub/prefixA.foo',
'/B/sub/prefixB.foo',
'/B/sub/prefixC.foo',
'/B/sub/prefixD.foo',
'/B/sub/prefixE.foo',
'/B/sub/prefixF.foo',
'/C/prefixA.foo',
'/C/prefixB.foo',
'/C/prefixC.foo',
'/C/prefixD.foo',
'/C/prefixE.foo',
'/C/prefixF.foo',
'/D/prefixA',
'/D/prefixB',
'/D/prefixC',
'/D/prefixD',
'/D/prefixE',
'/D/prefixF',
'/E/subtestA.foo',
'/F/subtestA.foo',
'/G/subtestA.foo',
'/H/subtestA.foo',
'/I/J/subtestA.foo',
'/K/dirJ/subtestA.foo',
'/parameters.yml',
'/parameters.yml.dist',
'/prefixA.foo',
'/prefixB.foo',
'/prefixC.foo',
'/prefixD.foo',
'/prefixE.foo',
'/prefixF.foo',
'/toplevelA.foo',
'/toplevelB.foo',
]);
}
/**
* @return string[]
*/
protected function getArchivableFiles(): array
{
$files = [];
foreach ($this->finder as $file) {
if (!$file->isDir()) {
$files[] = Preg::replace('#^'.preg_quote($this->sources, '#').'#', '', $this->fs->normalizePath($file->getRealPath()));
}
}
sort($files);
return $files;
}
/**
* @return string[]
*/
protected function getArchivedFiles(string $command): array
{
$process = Process::fromShellCommandline($command, $this->sources);
$process->run();
$archive = new \PharData($this->sources.'/archive.zip');
$iterator = new \RecursiveIteratorIterator($archive);
$files = [];
foreach ($iterator as $file) {
$files[] = Preg::replace('#^phar://'.preg_quote($this->sources, '#').'/archive\.zip/archive#', '', $this->fs->normalizePath((string) $file));
}
unset($archive, $iterator, $file);
unlink($this->sources.'/archive.zip');
return $files;
}
/**
* @param string[] $expectedFiles
*/
protected function assertArchivableFiles(array $expectedFiles): void
{
$actualFiles = $this->getArchivableFiles();
self::assertEquals($expectedFiles, $actualFiles);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Package/Dumper/ArrayDumperTest.php | tests/Composer/Test/Package/Dumper/ArrayDumperTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Package\Dumper;
use Composer\Package\Dumper\ArrayDumper;
use Composer\Package\Link;
use Composer\Semver\Constraint\Constraint;
use Composer\Test\TestCase;
class ArrayDumperTest extends TestCase
{
/**
* @var ArrayDumper
*/
private $dumper;
public function setUp(): void
{
$this->dumper = new ArrayDumper();
}
public function testRequiredInformation(): void
{
$config = $this->dumper->dump(self::getPackage());
self::assertEquals(
[
'name' => 'dummy/pkg',
'version' => '1.0.0',
'version_normalized' => '1.0.0.0',
'type' => 'library',
],
$config
);
}
public function testRootPackage(): void
{
$package = self::getRootPackage();
$package->setMinimumStability('dev');
$config = $this->dumper->dump($package);
self::assertSame('dev', $config['minimum-stability']);
}
public function testDumpAbandoned(): void
{
$package = self::getPackage();
$package->setAbandoned(true);
$config = $this->dumper->dump($package);
self::assertTrue($config['abandoned']);
}
public function testDumpAbandonedReplacement(): void
{
$package = self::getPackage();
$package->setAbandoned('foo/bar');
$config = $this->dumper->dump($package);
self::assertSame('foo/bar', $config['abandoned']);
}
/**
* @dataProvider provideKeys
*
* @param mixed $value
* @param mixed $expectedValue
*/
public function testKeys(string $key, $value, ?string $method = null, $expectedValue = null): void
{
$package = self::getRootPackage();
// @phpstan-ignore method.dynamicName
$package->{'set'.ucfirst($method ?? $key)}($value);
$config = $this->dumper->dump($package);
self::assertSame($expectedValue ?: $value, $config[$key]);
}
public static function provideKeys(): array
{
return [
[
'type',
'library',
],
[
'time',
$datetime = new \DateTime('2012-02-01'),
'ReleaseDate',
$datetime->format(DATE_RFC3339),
],
[
'authors',
['Nils Adermann <naderman@naderman.de>', 'Jordi Boggiano <j.boggiano@seld.be>'],
],
[
'homepage',
'https://getcomposer.org',
],
[
'description',
'Dependency Manager',
],
[
'keywords',
['package', 'dependency', 'autoload'],
null,
['autoload', 'dependency', 'package'],
],
[
'bin',
['bin/composer'],
'binaries',
],
[
'license',
['MIT'],
],
[
'autoload',
['psr-0' => ['Composer' => 'src/']],
],
[
'repositories',
['packagist' => false],
],
[
'scripts',
['post-update-cmd' => 'MyVendor\\MyClass::postUpdate'],
],
[
'extra',
['class' => 'MyVendor\\Installer'],
],
[
'archive',
['/foo/bar', 'baz', '!/foo/bar/baz'],
'archiveExcludes',
[
'exclude' => ['/foo/bar', 'baz', '!/foo/bar/baz'],
],
],
[
'require',
['foo/bar' => new Link('dummy/pkg', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0')],
'requires',
['foo/bar' => '1.0.0'],
],
[
'require-dev',
['foo/bar' => new Link('dummy/pkg', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_DEV_REQUIRE, '1.0.0')],
'devRequires',
['foo/bar' => '1.0.0'],
],
[
'suggest',
['foo/bar' => 'very useful package'],
'suggests',
],
[
'support',
['foo' => 'bar'],
],
[
'funding',
['type' => 'foo', 'url' => 'https://example.com'],
],
[
'require',
[
'foo/bar' => new Link('dummy/pkg', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'),
'bar/baz' => new Link('dummy/pkg', 'bar/baz', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'),
],
'requires',
['bar/baz' => '1.0.0', 'foo/bar' => '1.0.0'],
],
[
'require-dev',
[
'foo/bar' => new Link('dummy/pkg', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'),
'bar/baz' => new Link('dummy/pkg', 'bar/baz', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'),
],
'devRequires',
['bar/baz' => '1.0.0', 'foo/bar' => '1.0.0'],
],
[
'suggest',
['foo/bar' => 'very useful package', 'bar/baz' => 'another useful package'],
'suggests',
['bar/baz' => 'another useful package', 'foo/bar' => 'very useful package'],
],
[
'provide',
[
'foo/bar' => new Link('dummy/pkg', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'),
'bar/baz' => new Link('dummy/pkg', 'bar/baz', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'),
],
'provides',
['bar/baz' => '1.0.0', 'foo/bar' => '1.0.0'],
],
[
'replace',
[
'foo/bar' => new Link('dummy/pkg', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'),
'bar/baz' => new Link('dummy/pkg', 'bar/baz', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'),
],
'replaces',
['bar/baz' => '1.0.0', 'foo/bar' => '1.0.0'],
],
[
'conflict',
[
'foo/bar' => new Link('dummy/pkg', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'),
'bar/baz' => new Link('dummy/pkg', 'bar/baz', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'),
],
'conflicts',
['bar/baz' => '1.0.0', 'foo/bar' => '1.0.0'],
],
[
'transport-options',
['ssl' => ['local_cert' => '/opt/certs/test.pem']],
'transportOptions',
],
[
'php-ext',
['extension-name' => 'test'],
'phpExt',
],
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Package/Loader/RootPackageLoaderTest.php | tests/Composer/Test/Package/Loader/RootPackageLoaderTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Package\Loader;
use Composer\Config;
use Composer\Package\Loader\RootPackageLoader;
use Composer\Package\BasePackage;
use Composer\Package\RootAliasPackage;
use Composer\Package\RootPackage;
use Composer\Package\Version\VersionGuesser;
use Composer\Semver\VersionParser;
use Composer\Test\TestCase;
use Composer\Util\ProcessExecutor;
class RootPackageLoaderTest extends TestCase
{
/**
* @param array<string, mixed> $data
*
* @return RootPackage|RootAliasPackage
*/
protected function loadPackage(array $data): \Composer\Package\PackageInterface
{
$manager = $this->getMockBuilder('Composer\\Repository\\RepositoryManager')
->disableOriginalConstructor()
->getMock();
$config = new Config;
$config->merge(['repositories' => ['packagist' => false]]);
$processExecutor = new ProcessExecutor();
$processExecutor->enableAsync();
$guesser = new VersionGuesser($config, $processExecutor, new VersionParser());
$loader = new RootPackageLoader($manager, $config, null, $guesser);
return $loader->load($data);
}
public function testStabilityFlagsParsing(): void
{
$package = $this->loadPackage([
'require' => [
'foo/bar' => '~2.1.0-beta2',
'bar/baz' => '1.0.x-dev as 1.2.0',
'qux/quux' => '1.0.*@rc',
'zux/complex' => '~1.0,>=1.0.2@dev',
'or/op' => '^2.0@dev || ^2.0@dev',
'multi/lowest-wins' => '^2.0@rc || >=3.0@dev , ~3.5@alpha',
'or/op-without-flags' => 'dev-master || 2.0 , ~3.5-alpha',
'or/op-without-flags2' => '3.0-beta || 2.0 , ~3.5-alpha',
],
'minimum-stability' => 'alpha',
]);
self::assertEquals('alpha', $package->getMinimumStability());
self::assertEquals([
'bar/baz' => BasePackage::STABILITY_DEV,
'qux/quux' => BasePackage::STABILITY_RC,
'zux/complex' => BasePackage::STABILITY_DEV,
'or/op' => BasePackage::STABILITY_DEV,
'multi/lowest-wins' => BasePackage::STABILITY_DEV,
'or/op-without-flags' => BasePackage::STABILITY_DEV,
'or/op-without-flags2' => BasePackage::STABILITY_ALPHA,
], $package->getStabilityFlags());
}
public function testNoVersionIsVisibleInPrettyVersion(): void
{
$manager = $this->getMockBuilder('Composer\\Repository\\RepositoryManager')
->disableOriginalConstructor()
->getMock()
;
$config = new Config;
$config->merge(['repositories' => ['packagist' => false]]);
$loader = new RootPackageLoader($manager, $config, null, new VersionGuesser($config, $process = $this->getProcessExecutorMock(), new VersionParser()));
$process->expects([], false, ['return' => 1]);
$package = $loader->load([]);
self::assertEquals("1.0.0.0", $package->getVersion());
self::assertEquals(RootPackage::DEFAULT_PRETTY_VERSION, $package->getPrettyVersion());
}
public function testPrettyVersionForRootPackageInVersionBranch(): void
{
// see #6845
$manager = $this->getMockBuilder('Composer\\Repository\\RepositoryManager')->disableOriginalConstructor()->getMock();
$versionGuesser = $this->getMockBuilder('Composer\\Package\\Version\\VersionGuesser')->disableOriginalConstructor()->getMock();
$versionGuesser->expects($this->atLeastOnce())
->method('guessVersion')
->willReturn([
'name' => 'A',
'version' => '3.0.9999999.9999999-dev',
'pretty_version' => '3.0-dev',
'commit' => 'aabbccddee',
]);
$config = new Config;
$config->merge(['repositories' => ['packagist' => false]]);
$loader = new RootPackageLoader($manager, $config, null, $versionGuesser);
$package = $loader->load([]);
self::assertEquals('3.0-dev', $package->getPrettyVersion());
}
public function testFeatureBranchPrettyVersion(): void
{
if (!function_exists('proc_open')) {
$this->markTestSkipped('proc_open() is not available');
}
$manager = $this->getMockBuilder('Composer\\Repository\\RepositoryManager')
->disableOriginalConstructor()
->getMock()
;
$process = $this->getProcessExecutorMock();
$process->expects([
[
'cmd' => ['git', 'branch', '-a', '--no-color', '--no-abbrev', '-v'],
'stdout' => "* latest-production 38137d2f6c70e775e137b2d8a7a7d3eaebf7c7e5 Commit message\n master 4f6ed96b0bc363d2aa4404c3412de1c011f67c66 Commit message\n",
],
['cmd' => ['git', 'rev-list', 'master..latest-production']],
], true);
$config = new Config;
$config->merge(['repositories' => ['packagist' => false]]);
$loader = new RootPackageLoader($manager, $config, null, new VersionGuesser($config, $process, new VersionParser()));
$package = $loader->load(['require' => ['foo/bar' => 'self.version']]);
self::assertEquals("dev-master", $package->getPrettyVersion());
}
public function testNonFeatureBranchPrettyVersion(): void
{
if (!function_exists('proc_open')) {
$this->markTestSkipped('proc_open() is not available');
}
$manager = $this->getMockBuilder('Composer\\Repository\\RepositoryManager')
->disableOriginalConstructor()
->getMock()
;
$process = $this->getProcessExecutorMock();
$process->expects([
[
'cmd' => ['git', 'branch', '-a', '--no-color', '--no-abbrev', '-v'],
'stdout' => "* latest-production 38137d2f6c70e775e137b2d8a7a7d3eaebf7c7e5 Commit message\n master 4f6ed96b0bc363d2aa4404c3412de1c011f67c66 Commit message\n",
],
], true);
$config = new Config;
$config->merge(['repositories' => ['packagist' => false]]);
$loader = new RootPackageLoader($manager, $config, null, new VersionGuesser($config, $process, new VersionParser()));
$package = $loader->load(['require' => ['foo/bar' => 'self.version'], "non-feature-branches" => ["latest-.*"]]);
self::assertEquals("dev-latest-production", $package->getPrettyVersion());
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Package/Loader/ValidatingArrayLoaderTest.php | tests/Composer/Test/Package/Loader/ValidatingArrayLoaderTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Package\Loader;
use Composer\Package\Loader\ValidatingArrayLoader;
use Composer\Package\Loader\InvalidPackageException;
use Composer\Test\TestCase;
class ValidatingArrayLoaderTest extends TestCase
{
/**
* @dataProvider successProvider
*
* @param array<string, mixed> $config
*/
public function testLoadSuccess(array $config): void
{
$internalLoader = $this->getMockBuilder('Composer\Package\Loader\LoaderInterface')->getMock();
$internalLoader
->expects($this->once())
->method('load')
->with($config);
$loader = new ValidatingArrayLoader($internalLoader, true, null, ValidatingArrayLoader::CHECK_ALL);
$loader->load($config);
}
public static function successProvider(): array
{
return [
[ // minimal
[
'name' => 'foo/bar',
],
],
[ // complete
[
'name' => 'foo/bar',
'description' => 'Foo bar',
'version' => '1.0.0',
'type' => 'library',
'keywords' => ['a', 'b_c', 'D E', 'éîüø', '微信'],
'homepage' => 'https://foo.com',
'time' => '2010-10-10T10:10:10+00:00',
'license' => ['MIT', 'WTFPL'],
'authors' => [
[
'name' => 'Alice',
'email' => 'alice@example.org',
'role' => 'Lead',
'homepage' => 'http://example.org',
],
[
'name' => 'Bob',
'homepage' => '',
],
],
'support' => [
'email' => 'mail@example.org',
'issues' => 'http://example.org/',
'forum' => 'http://example.org/',
'wiki' => 'http://example.org/',
'source' => 'http://example.org/',
'irc' => 'irc://example.org/example',
'rss' => 'http://example.org/rss',
'chat' => 'http://example.org/chat',
'security' => 'https://example.org/security',
],
'funding' => [
[
'type' => 'example',
'url' => 'https://example.org/fund',
],
[
'url' => 'https://example.org/fund',
],
],
'require' => [
'a/b' => '1.*',
'b/c' => '~2',
'example/pkg' => '>2.0-dev,<2.4-dev',
'composer-runtime-api' => '*',
],
'require-dev' => [
'a/b' => '1.*',
'b/c' => '*',
'example/pkg' => '>2.0-dev,<2.4-dev',
],
'conflict' => [
'a/bx' => '1.*',
'b/cx' => '>2.7',
'example/pkgx' => '>2.0-dev,<2.4-dev',
],
'replace' => [
'a/b' => '1.*',
'example/pkg' => '>2.0-dev,<2.4-dev',
],
'provide' => [
'a/b' => '1.*',
'example/pkg' => '>2.0-dev,<2.4-dev',
],
'suggest' => [
'foo/bar' => 'Foo bar is very useful',
],
'autoload' => [
'psr-0' => [
'Foo\\Bar' => 'src/',
'' => 'fallback/libs/',
],
'classmap' => [
'dir/',
'dir2/file.php',
],
'files' => [
'functions.php',
],
],
'include-path' => [
'lib/',
],
'target-dir' => 'Foo/Bar',
'minimum-stability' => 'dev',
'repositories' => [
[
'type' => 'composer',
'url' => 'https://repo.packagist.org/',
],
],
'config' => [
'bin-dir' => 'bin',
'vendor-dir' => 'vendor',
'process-timeout' => 10000,
],
'archive' => [
'exclude' => ['/foo/bar', 'baz', '!/foo/bar/baz'],
],
'scripts' => [
'post-update-cmd' => 'Foo\\Bar\\Baz::doSomething',
'post-install-cmd' => [
'Foo\\Bar\\Baz::doSomething',
],
],
'extra' => [
'random' => ['stuff' => ['deeply' => 'nested']],
'branch-alias' => [
'dev-master' => '2.0-dev',
'dev-old' => '1.0.x-dev',
'3.x-dev' => '3.1.x-dev',
],
],
'bin' => [
'bin/foo',
'bin/bar',
],
'transport-options' => ['ssl' => ['local_cert' => '/opt/certs/test.pem']],
],
],
[ // test bin as string
[
'name' => 'foo/bar',
'bin' => 'bin1',
],
],
[ // package name with dashes
[
'name' => 'foo/bar-baz',
],
],
[ // package name with dashes
[
'name' => 'foo/bar--baz',
],
],
[ // package name with dashes
[
'name' => 'foo/b-ar--ba-z',
],
],
[ // package name with dashes
[
'name' => 'npm-asset/angular--core',
],
],
[ // refs as int or string
[
'name' => 'foo/bar',
'source' => ['url' => 'https://example.org', 'reference' => 1234, 'type' => 'baz'],
'dist' => ['url' => 'https://example.org', 'reference' => 'foobar', 'type' => 'baz'],
],
],
[ // valid php-ext configuration
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'extension-name' => 'ext-xdebug',
'priority' => 80,
'support-zts' => true,
'support-nts' => false,
'build-path' => 'my-extension-source',
'download-url-method' => 'composer-default',
'os-families' => ['linux', 'darwin'],
'configure-options' => [
[
'name' => 'enable-xdebug',
'needs-value' => false,
'description' => 'Enable xdebug support',
],
[
'name' => 'with-xdebug-path',
'needs-value' => true,
],
],
],
],
],
[ // valid php-ext with os-families-exclude
[
'name' => 'foo/bar',
'type' => 'php-ext-zend',
'php-ext' => [
'os-families-exclude' => ['windows'],
],
],
],
[ // valid php-ext with null build-path
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'build-path' => null,
],
],
],
];
}
/**
* @dataProvider errorProvider
*
* @param array<string, mixed> $config
* @param string[] $expectedErrors
*/
public function testLoadFailureThrowsException(array $config, array $expectedErrors): void
{
$internalLoader = $this->getMockBuilder('Composer\Package\Loader\LoaderInterface')->getMock();
$loader = new ValidatingArrayLoader($internalLoader, true, null, ValidatingArrayLoader::CHECK_ALL);
try {
$loader->load($config);
$this->fail('Expected exception to be thrown');
} catch (InvalidPackageException $e) {
$errors = $e->getErrors();
sort($expectedErrors);
sort($errors);
self::assertEquals($expectedErrors, $errors);
}
}
/**
* @dataProvider warningProvider
*
* @param array<string, mixed> $config
* @param string[] $expectedWarnings
*/
public function testLoadWarnings(array $config, array $expectedWarnings): void
{
$internalLoader = $this->getMockBuilder('Composer\Package\Loader\LoaderInterface')->getMock();
$loader = new ValidatingArrayLoader($internalLoader, true, null, ValidatingArrayLoader::CHECK_ALL);
$loader->load($config);
$warnings = $loader->getWarnings();
sort($expectedWarnings);
sort($warnings);
self::assertEquals($expectedWarnings, $warnings);
}
/**
* @dataProvider warningProvider
*
* @param array<string, mixed> $config
* @param string[] $expectedWarnings
* @param array<string, mixed>|null $expectedArray
*/
public function testLoadSkipsWarningDataWhenIgnoringErrors(array $config, array $expectedWarnings, bool $mustCheck = true, ?array $expectedArray = null): void
{
if (!$mustCheck) {
self::assertTrue(true); // @phpstan-ignore staticMethod.alreadyNarrowedType
return;
}
$internalLoader = $this->getMockBuilder('Composer\Package\Loader\LoaderInterface')->getMock();
$internalLoader
->expects($this->once())
->method('load')
->with($expectedArray ?? ['name' => 'a/b']);
$loader = new ValidatingArrayLoader($internalLoader, true, null, ValidatingArrayLoader::CHECK_ALL);
$config['name'] = 'a/b';
$loader->load($config);
}
public static function errorProvider(): array
{
$invalidNames = [
'foo',
'foo/-bar-',
'foo/-bar',
];
$invalidNaming = [];
foreach ($invalidNames as $invalidName) {
$invalidNaming[] = [
[
'name' => $invalidName,
],
[
"name : $invalidName is invalid, it should have a vendor name, a forward slash, and a package name. The vendor and package name can be words separated by -, . or _. The complete name should match \"^[a-z0-9]([_.-]?[a-z0-9]+)*/[a-z0-9](([_.]?|-{0,2})[a-z0-9]+)*$\".",
],
];
}
$invalidNames = [
'fo--oo/bar',
'fo-oo/bar__baz',
'fo-oo/bar_.baz',
'foo/bar---baz',
];
foreach ($invalidNames as $invalidName) {
$invalidNaming[] = [
[
'name' => $invalidName,
],
[
"name : $invalidName is invalid, it should have a vendor name, a forward slash, and a package name. The vendor and package name can be words separated by -, . or _. The complete name should match \"^[a-z0-9]([_.-]?[a-z0-9]+)*/[a-z0-9](([_.]?|-{0,2})[a-z0-9]+)*$\".",
],
false,
];
}
return array_merge($invalidNaming, [
[
[
'name' => 'foo/bar',
'homepage' => 43,
],
[
'homepage : should be a string, int given',
],
],
[
[
'name' => 'foo/bar',
'support' => [
'source' => [],
],
],
[
'support.source : invalid value, must be a string',
],
],
[
[
'name' => 'foo/bar.json',
],
[
'name : foo/bar.json is invalid, package names can not end in .json, consider renaming it or perhaps using a -json suffix instead.',
],
],
[
[
'name' => 'com1/foo',
],
[
'name : com1/foo is reserved, package and vendor names can not match any of: nul, con, prn, aux, com1, com2, com3, com4, com5, com6, com7, com8, com9, lpt1, lpt2, lpt3, lpt4, lpt5, lpt6, lpt7, lpt8, lpt9.',
],
],
[
[
'name' => 'Foo/Bar',
],
[
'name : Foo/Bar is invalid, it should not contain uppercase characters. We suggest using foo/bar instead.',
],
],
[
[
'name' => 'foo/bar',
'autoload' => 'strings',
],
[
'autoload : should be an array, string given',
],
],
[
[
'name' => 'foo/bar',
'autoload' => [
'psr0' => [
'foo' => 'src',
],
],
],
[
'autoload : invalid value (psr0), must be one of psr-0, psr-4, classmap, files, exclude-from-classmap',
],
],
[
[
'name' => 'foo/bar',
'transport-options' => 'test',
],
[
'transport-options : should be an array, string given',
],
],
[
[
'name' => 'foo/bar',
'source' => ['url' => '--foo', 'reference' => ' --bar', 'type' => 'baz'],
'dist' => ['url' => ' --foox', 'reference' => '--barx', 'type' => 'baz'],
],
[
'dist.reference : must not start with a "-", "--barx" given',
'dist.url : must not start with a "-", " --foox" given',
'source.reference : must not start with a "-", " --bar" given',
'source.url : must not start with a "-", "--foo" given',
],
],
[
[
'name' => 'foo/bar',
'require' => ['foo/Bar' => '1.*'],
],
[
'require.foo/Bar : a package cannot set a require on itself',
],
],
[
[
'name' => 'foo/bar',
'source' => ['url' => 1],
'dist' => ['url' => null],
],
[
'source.type : must be present',
'source.url : should be a string, int given',
'source.reference : must be present',
'dist.type : must be present',
'dist.url : must be present',
],
],
[
[
'name' => 'foo/bar',
'replace' => ['acme/bar'],
],
['replace.0 : invalid version constraint (Could not parse version constraint acme/bar: Invalid version string "acme/bar")'],
],
[
[
'require' => ['acme/bar' => '^1.0'],
],
['name : must be present'],
],
[
[
'name' => 'foo/bar',
'type' => 'library',
'php-ext' => ['extension-name' => 'ext-foobar'],
],
['php-ext can only be set by packages of type "php-ext" or "php-ext-zend" which must be C extensions'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'extension-name' => 123,
],
],
['php-ext.extension-name : should be a string, int given'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'priority' => 'invalid',
],
],
['php-ext.priority : should be an integer, string given'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'support-zts' => 'yes',
],
],
['php-ext.support-zts : should be a boolean, string given'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'support-nts' => 1,
],
],
['php-ext.support-nts : should be a boolean, int given'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'build-path' => 123,
],
],
['php-ext.build-path : should be a string or null, int given'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'download-url-method' => 123,
],
],
['php-ext.download-url-method : should be a string, int given'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'download-url-method' => 'invalid-method',
],
],
['php-ext.download-url-method : invalid value (invalid-method), must be one of composer-default, pre-packaged-source'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'os-families' => ['linux'],
'os-families-exclude' => ['windows'],
],
],
['php-ext : os-families and os-families-exclude cannot both be specified'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'os-families' => 'linux',
],
],
['php-ext.os-families : should be an array, string given'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'os-families' => [],
],
],
['php-ext.os-families : must contain at least one element'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'os-families' => ['invalid-os', 'linux'],
],
],
['php-ext.os-families.0 : invalid value (invalid-os), must be one of windows, bsd, darwin, solaris, linux, unknown'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'os-families' => [123],
],
],
['php-ext.os-families.0 : should be a string, int given'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'os-families-exclude' => 'windows',
],
],
['php-ext.os-families-exclude : should be an array, string given'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'os-families-exclude' => [],
],
],
['php-ext.os-families-exclude : must contain at least one element'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'os-families-exclude' => ['invalid'],
],
],
['php-ext.os-families-exclude.0 : invalid value (invalid), must be one of windows, bsd, darwin, solaris, linux, unknown'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'configure-options' => 'invalid',
],
],
['php-ext.configure-options : should be an array, string given'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'configure-options' => ['invalid'],
],
],
['php-ext.configure-options.0 : should be an array, string given'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'configure-options' => [
['description' => 'test'],
],
],
],
['php-ext.configure-options.0.name : must be present'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'configure-options' => [
['name' => 123],
],
],
],
['php-ext.configure-options.0.name : should be a string, int given'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'configure-options' => [
[
'name' => 'valid-name',
'needs-value' => 'yes',
],
],
],
],
['php-ext.configure-options.0.needs-value : should be a boolean, string given'],
],
[
[
'name' => 'foo/bar',
'type' => 'php-ext',
'php-ext' => [
'configure-options' => [
[
'name' => 'valid-name',
'description' => 123,
],
],
],
],
['php-ext.configure-options.0.description : should be a string, int given'],
],
]);
}
public static function warningProvider(): array
{
return [
[
[
'name' => 'foo/bar',
'homepage' => 'foo:bar',
],
[
'homepage : invalid value (foo:bar), must be an http/https URL',
],
],
[
[
'name' => 'foo/bar',
'support' => [
'source' => 'foo:bar',
'forum' => 'foo:bar',
'issues' => 'foo:bar',
'wiki' => 'foo:bar',
'chat' => 'foo:bar',
'security' => 'foo:bar',
],
],
[
'support.source : invalid value (foo:bar), must be an http/https URL',
'support.forum : invalid value (foo:bar), must be an http/https URL',
'support.issues : invalid value (foo:bar), must be an http/https URL',
'support.wiki : invalid value (foo:bar), must be an http/https URL',
'support.chat : invalid value (foo:bar), must be an http/https URL',
'support.security : invalid value (foo:bar), must be an http/https URL',
],
],
[
[
'name' => 'foo/bar',
'require' => [
'foo/baz' => '*',
'bar/baz' => '>=1.0',
'bar/hacked' => '@stable',
'bar/woo' => '1.0.0',
],
],
[
'require.foo/baz : unbound version constraints (*) should be avoided',
'require.bar/baz : unbound version constraints (>=1.0) should be avoided',
'require.bar/hacked : unbound version constraints (@stable) should be avoided',
'require.bar/woo : exact version constraints (1.0.0) should be avoided if the package follows semantic versioning',
],
false,
],
[
[
'name' => 'foo/bar',
'require' => [
'foo/baz' => '>1, <0.5',
'bar/baz' => 'dev-main, >0.5',
],
],
[
'require.foo/baz : this version constraint cannot possibly match anything (>1, <0.5)',
'require.bar/baz : this version constraint cannot possibly match anything (dev-main, >0.5)',
],
false,
],
[
[
'name' => 'foo/bar',
'require' => [
'bar/unstable' => '0.3.0',
],
],
[
// using an exact version constraint for an unstable version should not trigger a warning
],
false,
],
[
[
'name' => 'foo/bar',
'extra' => [
'branch-alias' => [
'5.x-dev' => '3.1.x-dev',
],
],
],
[
'extra.branch-alias.5.x-dev : the target branch (3.1.x-dev) is not a valid numeric alias for this version',
],
false,
],
[
[
'name' => 'foo/bar',
'extra' => [
'branch-alias' => [
'5.x-dev' => '3.1-dev',
],
],
],
[
'extra.branch-alias.5.x-dev : the target branch (3.1-dev) is not a valid numeric alias for this version',
],
false,
],
[
[
'name' => 'foo/bar',
'require' => [
'Foo/Baz' => '^1.0',
],
],
[
'require.Foo/Baz is invalid, it should not contain uppercase characters. Please use foo/baz instead.',
],
false,
],
[
[
'name' => 'a/b',
'license' => 'XXXXX',
],
[
'License "XXXXX" is not a valid SPDX license identifier, see https://spdx.org/licenses/ if you use an open license.'.PHP_EOL.
'If the software is closed-source, you may use "proprietary" as license.',
],
true,
[
'name' => 'a/b',
'license' => ['XXXXX'],
],
],
[
[
'name' => 'a/b',
'license' => [['author' => 'bar'], 'MIT'],
],
[
'License {"author":"bar"} should be a string.',
],
true,
[
'name' => 'a/b',
'license' => ['MIT'],
],
],
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Package/Loader/ArrayLoaderTest.php | tests/Composer/Test/Package/Loader/ArrayLoaderTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Package\Loader;
use Composer\Package\Loader\ArrayLoader;
use Composer\Package\Dumper\ArrayDumper;
use Composer\Package\Link;
use Composer\Package\Version\VersionParser;
use Composer\Test\TestCase;
class ArrayLoaderTest extends TestCase
{
/**
* @var ArrayLoader
*/
private $loader;
public function setUp(): void
{
$this->loader = new ArrayLoader(null);
}
public function testSelfVersion(): void
{
$config = [
'name' => 'A',
'version' => '1.2.3.4',
'replace' => [
'foo' => 'self.version',
],
];
$package = $this->loader->load($config);
$replaces = $package->getReplaces();
self::assertEquals('== 1.2.3.4', (string) $replaces['foo']->getConstraint());
}
public function testTypeDefault(): void
{
$config = [
'name' => 'A',
'version' => '1.0',
];
$package = $this->loader->load($config);
self::assertEquals('library', $package->getType());
$config = [
'name' => 'A',
'version' => '1.0',
'type' => 'foo',
];
$package = $this->loader->load($config);
self::assertEquals('foo', $package->getType());
}
public function testNormalizedVersionOptimization(): void
{
$config = [
'name' => 'A',
'version' => '1.2.3',
];
$package = $this->loader->load($config);
self::assertEquals('1.2.3.0', $package->getVersion());
$config = [
'name' => 'A',
'version' => '1.2.3',
'version_normalized' => '1.2.3.4',
];
$package = $this->loader->load($config);
self::assertEquals('1.2.3.4', $package->getVersion());
}
public static function parseDumpProvider(): array
{
$validConfig = [
'name' => 'A/B',
'version' => '1.2.3',
'version_normalized' => '1.2.3.0',
'description' => 'Foo bar',
'type' => 'library',
'keywords' => ['a', 'b', 'c'],
'homepage' => 'http://example.com',
'license' => ['MIT', 'GPLv3'],
'authors' => [
['name' => 'Bob', 'email' => 'bob@example.org', 'homepage' => 'example.org', 'role' => 'Developer'],
],
'funding' => [
['type' => 'example', 'url' => 'https://example.org/fund'],
],
'require' => [
'foo/bar' => '1.0',
],
'require-dev' => [
'foo/baz' => '1.0',
],
'replace' => [
'foo/qux' => '1.0',
],
'conflict' => [
'foo/quux' => '1.0',
],
'provide' => [
'foo/quuux' => '1.0',
],
'autoload' => [
'psr-0' => ['Ns\Prefix' => 'path'],
'classmap' => ['path', 'path2'],
],
'include-path' => ['path3', 'path4'],
'target-dir' => 'some/prefix',
'extra' => ['random' => ['things' => 'of', 'any' => 'shape']],
'bin' => ['bin1', 'bin/foo'],
'archive' => [
'exclude' => ['/foo/bar', 'baz', '!/foo/bar/baz'],
],
'transport-options' => ['ssl' => ['local_cert' => '/opt/certs/test.pem']],
'abandoned' => 'foo/bar',
];
return [[$validConfig]];
}
/**
* @param array<string, mixed> $config
*
* @return array<string, mixed>
*/
protected function fixConfigWhenLoadConfigIsFalse(array $config): array
{
$expectedConfig = $config;
unset($expectedConfig['transport-options']);
return $expectedConfig;
}
/**
* The default parser should default to loading the config as this
* allows require-dev libraries to have transport options included.
*
* @dataProvider parseDumpProvider
*
* @param array<string, mixed> $config
*/
public function testParseDumpDefaultLoadConfig(array $config): void
{
$package = $this->loader->load($config);
$dumper = new ArrayDumper;
$expectedConfig = $this->fixConfigWhenLoadConfigIsFalse($config);
self::assertEquals($expectedConfig, $dumper->dump($package));
}
/**
* @dataProvider parseDumpProvider
*
* @param array<string, mixed> $config
*/
public function testParseDumpTrueLoadConfig(array $config): void
{
$loader = new ArrayLoader(null, true);
$package = $loader->load($config);
$dumper = new ArrayDumper;
$expectedConfig = $config;
self::assertEquals($expectedConfig, $dumper->dump($package));
}
/**
* @dataProvider parseDumpProvider
*
* @param array<string, mixed> $config
*/
public function testParseDumpFalseLoadConfig(array $config): void
{
$loader = new ArrayLoader(null, false);
$package = $loader->load($config);
$dumper = new ArrayDumper;
$expectedConfig = $this->fixConfigWhenLoadConfigIsFalse($config);
self::assertEquals($expectedConfig, $dumper->dump($package));
}
public function testPackageWithBranchAlias(): void
{
$config = [
'name' => 'A',
'version' => 'dev-master',
'extra' => ['branch-alias' => ['dev-master' => '1.0.x-dev']],
];
$package = $this->loader->load($config);
self::assertInstanceOf('Composer\Package\AliasPackage', $package);
self::assertEquals('1.0.x-dev', $package->getPrettyVersion());
$config = [
'name' => 'A',
'version' => 'dev-master',
'extra' => ['branch-alias' => ['dev-master' => '1.0-dev']],
];
$package = $this->loader->load($config);
self::assertInstanceOf('Composer\Package\AliasPackage', $package);
self::assertEquals('1.0.x-dev', $package->getPrettyVersion());
$config = [
'name' => 'B',
'version' => '4.x-dev',
'extra' => ['branch-alias' => ['4.x-dev' => '4.0.x-dev']],
];
$package = $this->loader->load($config);
self::assertInstanceOf('Composer\Package\AliasPackage', $package);
self::assertEquals('4.0.x-dev', $package->getPrettyVersion());
$config = [
'name' => 'B',
'version' => '4.x-dev',
'extra' => ['branch-alias' => ['4.x-dev' => '4.0-dev']],
];
$package = $this->loader->load($config);
self::assertInstanceOf('Composer\Package\AliasPackage', $package);
self::assertEquals('4.0.x-dev', $package->getPrettyVersion());
$config = [
'name' => 'C',
'version' => '4.x-dev',
'extra' => ['branch-alias' => ['4.x-dev' => '3.4.x-dev']],
];
$package = $this->loader->load($config);
self::assertInstanceOf('Composer\Package\CompletePackage', $package);
self::assertEquals('4.x-dev', $package->getPrettyVersion());
}
public function testPackageAliasingWithoutBranchAlias(): void
{
// non-numeric gets a default alias
$config = [
'name' => 'A',
'version' => 'dev-main',
'default-branch' => true,
];
$package = $this->loader->load($config);
self::assertInstanceOf('Composer\Package\AliasPackage', $package);
self::assertEquals(VersionParser::DEFAULT_BRANCH_ALIAS, $package->getPrettyVersion());
// non-default branch gets no alias even if non-numeric
$config = [
'name' => 'A',
'version' => 'dev-main',
'default-branch' => false,
];
$package = $this->loader->load($config);
self::assertInstanceOf('Composer\Package\CompletePackage', $package);
self::assertEquals('dev-main', $package->getPrettyVersion());
// default branch gets no alias if already numeric
$config = [
'name' => 'A',
'version' => '2.x-dev',
'default-branch' => true,
];
$package = $this->loader->load($config);
self::assertInstanceOf('Composer\Package\CompletePackage', $package);
self::assertEquals('2.9999999.9999999.9999999-dev', $package->getVersion());
// default branch gets no alias if already numeric, with v prefix
$config = [
'name' => 'A',
'version' => 'v2.x-dev',
'default-branch' => true,
];
$package = $this->loader->load($config);
self::assertInstanceOf('Composer\Package\CompletePackage', $package);
self::assertEquals('2.9999999.9999999.9999999-dev', $package->getVersion());
}
public function testAbandoned(): void
{
$config = [
'name' => 'A',
'version' => '1.2.3.4',
'abandoned' => 'foo/bar',
];
$package = $this->loader->load($config);
self::assertTrue($package->isAbandoned());
self::assertEquals('foo/bar', $package->getReplacementPackage());
}
public function testNotAbandoned(): void
{
$config = [
'name' => 'A',
'version' => '1.2.3.4',
];
$package = $this->loader->load($config);
self::assertFalse($package->isAbandoned());
}
public static function providePluginApiVersions(): array
{
return [
['1.0'],
['1.0.0'],
['1.0.0.0'],
['1'],
['=1.0.0'],
['==1.0'],
['~1.0.0'],
['*'],
['3.0.*'],
['@stable'],
['1.0.0@stable'],
['^5.1'],
['>=1.0.0 <2.5'],
['x'],
['1.0.0-dev'],
];
}
/**
* @dataProvider providePluginApiVersions
*/
public function testPluginApiVersionAreKeptAsDeclared(string $apiVersion): void
{
$links = $this->loader->parseLinks('Plugin', '9.9.9', Link::TYPE_REQUIRE, ['composer-plugin-api' => $apiVersion]);
self::assertArrayHasKey('composer-plugin-api', $links);
self::assertSame($apiVersion, $links['composer-plugin-api']->getConstraint()->getPrettyString());
}
public function testPluginApiVersionDoesSupportSelfVersion(): void
{
$links = $this->loader->parseLinks('Plugin', '6.6.6', Link::TYPE_REQUIRE, ['composer-plugin-api' => 'self.version']);
self::assertArrayHasKey('composer-plugin-api', $links);
self::assertSame('6.6.6', $links['composer-plugin-api']->getConstraint()->getPrettyString());
}
public function testParseLinksIntegerTarget(): void
{
$links = $this->loader->parseLinks('Plugin', '9.9.9', Link::TYPE_REQUIRE, ['1' => 'dev-main']);
self::assertArrayHasKey('1', $links);
}
public function testNoneStringVersion(): void
{
$config = [
'name' => 'acme/package',
'version' => 1,
];
$package = $this->loader->load($config);
self::assertSame('1', $package->getPrettyVersion());
}
public function testNoneStringSourceDistReference(): void
{
$config = [
'name' => 'acme/package',
'version' => 'dev-main',
'source' => [
'type' => 'svn',
'url' => 'https://example.org/',
'reference' => 2019,
],
'dist' => [
'type' => 'zip',
'url' => 'https://example.org/',
'reference' => 2019,
],
];
$package = $this->loader->load($config);
self::assertSame('2019', $package->getSourceReference());
self::assertSame('2019', $package->getDistReference());
}
public function testBranchAliasIntegerIndex(): void
{
$config = [
'name' => 'acme/package',
'version' => 'dev-1',
'extra' => [
'branch-alias' => [
'1' => '1.3-dev',
],
],
'dist' => [
'type' => 'zip',
'url' => 'https://example.org/',
],
];
self::assertNull($this->loader->getBranchAlias($config));
}
public function testPackageLinksRequire(): void
{
$config = [
'name' => 'acme/package',
'version' => 'dev-1',
'require' => [
'foo/bar' => '1.0',
],
];
$package = $this->loader->load($config);
self::assertArrayHasKey('foo/bar', $package->getRequires());
self::assertSame('1.0', $package->getRequires()['foo/bar']->getConstraint()->getPrettyString());
}
public function testPackageLinksRequireInvalid(): void
{
$config = [
'name' => 'acme/package',
'version' => 'dev-1',
'require' => [
'foo/bar' => [
'random-string' => '1.0',
],
],
];
$package = $this->loader->load($config);
self::assertCount(0, $package->getRequires());
}
public function testPackageLinksReplace(): void
{
$config = [
'name' => 'acme/package',
'version' => 'dev-1',
'replace' => [
'coyote/package' => 'self.version',
],
];
$package = $this->loader->load($config);
self::assertArrayHasKey('coyote/package', $package->getReplaces());
self::assertSame('dev-1', $package->getReplaces()['coyote/package']->getConstraint()->getPrettyString());
}
public function testPackageLinksReplaceInvalid(): void
{
$config = [
'name' => 'acme/package',
'version' => 'dev-1',
'replace' => 'coyote/package',
];
$package = $this->loader->load($config);
self::assertCount(0, $package->getReplaces());
}
public function testSupportStringValue(): void
{
$config = [
'name' => 'acme/package',
'version' => 'dev-1',
'support' => 'https://example.org',
];
$package = $this->loader->load($config);
self::assertSame([], $package->getSupport());
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Package/Version/VersionBumperTest.php | tests/Composer/Test/Package/Version/VersionBumperTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Package\Version;
use Composer\Package\Version\VersionBumper;
use Composer\Package\Package;
use Composer\Package\Version\VersionParser;
use Composer\Test\TestCase;
use Generator;
class VersionBumperTest extends TestCase
{
/**
* @dataProvider provideBumpRequirementTests
*/
public function testBumpRequirement(string $requirement, string $prettyVersion, string $expectedRequirement, ?string $branchAlias = null): void
{
$versionBumper = new VersionBumper();
$versionParser = new VersionParser();
$package = new Package('foo/bar', $versionParser->normalize($prettyVersion), $prettyVersion);
if ($branchAlias !== null) {
$package->setExtra(['branch-alias' => [$prettyVersion => $branchAlias]]);
}
$newConstraint = $versionBumper->bumpRequirement($versionParser->parseConstraints($requirement), $package);
// assert that the recommended version is what we expect
self::assertSame($expectedRequirement, $newConstraint);
}
public static function provideBumpRequirementTests(): Generator
{
// constraint, version, expected recommendation, [branch-alias]
yield 'upgrade caret' => ['^1.0', '1.2.1', '^1.2.1'];
yield 'upgrade caret with v' => ['^v1.0', '1.2.1', '^1.2.1'];
yield 'skip trailing .0s' => ['^1.0', '1.0.0', '^1.0'];
yield 'skip trailing .0s/2' => ['^1.2', '1.2.0', '^1.2'];
yield 'preserve major.minor.patch format when installed minor is 0' => ['^1.0.0', '1.2.0', '^1.2.0'];
yield 'preserve major.minor.patch format when installed minor is 1' => ['^1.0.0', '1.2.1', '^1.2.1'];
yield 'preserve multi constraints' => ['^1.2 || ^2.3', '1.3.2', '^1.3.2 || ^2.3'];
yield 'preserve multi constraints/2' => ['^1.2 || ^2.3', '2.4.0', '^1.2 || ^2.4'];
yield 'preserve multi constraints/3' => ['^1.2 || ^2.3 || ^2', '2.4.0', '^1.2 || ^2.4 || ^2.4'];
yield 'preserve multi constraints/4' => ['^1.2 || ^2.3.3 || ^2', '2.4.0', '^1.2 || ^2.4.0 || ^2.4'];
yield '@dev is preserved' => ['^3@dev', '3.2.x-dev', '^3.2@dev'];
yield 'non-stable versions abort upgrades' => ['~2', '2.1-beta.1', '~2'];
yield 'dev reqs are skipped' => ['dev-main', 'dev-foo', 'dev-main'];
yield 'dev version does not upgrade' => ['^3.2', 'dev-main', '^3.2'];
yield 'upgrade dev version if aliased' => ['^3.2', 'dev-main', '^3.3', '3.3.x-dev'];
yield 'upgrade major wildcard to caret' => ['2.*', '2.4.0', '^2.4'];
yield 'upgrade major wildcard to caret with v' => ['v2.*', '2.4.0', '^2.4'];
yield 'upgrade major wildcard as x to caret' => ['2.x', '2.4.0', '^2.4'];
yield 'upgrade major wildcard as x to caret/2' => ['2.x.x', '2.4.0', '^2.4.0'];
yield 'leave minor wildcard alone' => ['2.4.*', '2.4.3', '2.4.*'];
yield 'leave patch wildcard alone' => ['2.4.3.*', '2.4.3.2', '2.4.3.*'];
yield 'leave single tilde alone' => ['~2', '2.4.3', '~2'];
yield 'upgrade tilde to caret when compatible' => ['~2.2', '2.4.3', '^2.4.3'];
yield 'upgrade patch-only-tilde, longer version' => ['~2.2.3', '2.2.6.2', '~2.2.6'];
yield 'upgrade patch-only-tilde' => ['~2.2.3', '2.2.6', '~2.2.6'];
yield 'upgrade patch-only-tilde, also .0s' => ['~2.0.0', '2.0.0', '~2.0.0'];
yield 'upgrade patch-only-tilde - with year based versions' => ['~2025.1.561', '2025.1.583', '~2025.1.583'];
yield 'upgrade 4 bits tilde' => ['~2.2.3.1', '2.2.4', '~2.2.4.0'];
yield 'upgrade 4 bits tilde/2' => ['~2.2.3.1', '2.2.4.0', '~2.2.4.0'];
yield 'upgrade 4 bits tilde/3' => ['~2.2.3.1', '2.2.4.5', '~2.2.4.5'];
yield 'upgrade bigger-or-eq to latest' => ['>=3.0', '3.4.5', '>=3.4.5'];
yield 'upgrade bigger-or-eq to latest with v' => ['>=v3.0', '3.4.5', '>=3.4.5'];
yield 'leave bigger-than untouched' => ['>2.2.3', '2.2.6', '>2.2.3'];
yield 'skip pre-stable releases' => ['^0.3 || ^0.4', '0.4.3', '^0.3 || ^0.4.3'];
yield 'upgrade full wildcard to bigger-or-eq' => ['*', '1.2.3', '>=1.2.3'];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Package/Version/VersionGuesserTest.php | tests/Composer/Test/Package/Version/VersionGuesserTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Package\Version;
use Composer\Config;
use Composer\Package\Version\VersionGuesser;
use Composer\Semver\VersionParser;
use Composer\Test\TestCase;
use Composer\Util\Git as GitUtil;
use Composer\Util\Platform;
use Composer\Util\ProcessExecutor;
class VersionGuesserTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
if (!function_exists('proc_open')) {
$this->markTestSkipped('proc_open() is not available');
}
$reflProp = new \ReflectionProperty(GitUtil::class, 'version');
(\PHP_VERSION_ID < 80100) and $reflProp->setAccessible(true);
$reflProp->setValue(null, false);
}
public function tearDown(): void
{
parent::tearDown();
$reflProp = new \ReflectionProperty(GitUtil::class, 'version');
(\PHP_VERSION_ID < 80100) and $reflProp->setAccessible(true);
$reflProp->setValue(null, false);
}
public function testHgGuessVersionReturnsData(): void
{
$branch = 'default';
$process = $this->getProcessExecutorMock();
$process->expects([
['cmd' => ['git', '--version'], 'return' => 0, 'stdout' => 'git version 2.33.0'],
['cmd' => ['git', 'branch', '-a', '--no-color', '--no-abbrev', '-v'], 'return' => 128],
['cmd' => ['git', 'describe', '--exact-match', '--tags'], 'return' => 128],
['cmd' => ['git', 'rev-list', '--no-commit-header', '--format=%H', '-n1', 'HEAD', '--no-show-signature'], 'return' => 128],
['cmd' => ['hg', 'branch'], 'return' => 0, 'stdout' => $branch],
['cmd' => ['hg', 'branches'], 'return' => 0],
['cmd' => ['hg', 'bookmarks'], 'return' => 0],
], true);
$config = new Config;
$config->merge(['repositories' => ['packagist' => false]]);
$guesser = new VersionGuesser($config, $process, new VersionParser());
$versionArray = $guesser->guessVersion([], 'dummy/path');
self::assertIsArray($versionArray);
self::assertEquals("dev-".$branch, $versionArray['version']);
self::assertEquals("dev-".$branch, $versionArray['pretty_version']);
self::assertEmpty($versionArray['commit']);
}
public function testGuessVersionReturnsData(): void
{
$commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea';
$anotherCommitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea';
$process = $this->getProcessExecutorMock();
$process->expects([
['cmd' => ['git', '--version'], 'return' => 0, 'stdout' => 'git version 2.52.0'],
[
'cmd' => ['git', 'branch', '-a', '--no-color', '--no-abbrev', '-v'],
'stdout' => "* master $commitHash Commit message\n(no branch) $anotherCommitHash Commit message\n",
],
], true);
$config = new Config;
$config->merge(['repositories' => ['packagist' => false]]);
$guesser = new VersionGuesser($config, $process, new VersionParser());
$versionArray = $guesser->guessVersion([], 'dummy/path');
self::assertIsArray($versionArray);
self::assertEquals("dev-master", $versionArray['version']);
self::assertEquals("dev-master", $versionArray['pretty_version']);
self::assertArrayNotHasKey('feature_version', $versionArray);
self::assertArrayNotHasKey('feature_pretty_version', $versionArray);
self::assertEquals($commitHash, $versionArray['commit']);
}
public function testGuessVersionDoesNotSeeCustomDefaultBranchAsNonFeatureBranch(): void
{
$commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea';
$anotherCommitHash = '13a15d220da53c52eddd5f32ffca64a7b3801bea';
$process = $this->getProcessExecutorMock();
$process->expects([
['cmd' => ['git', '--version'], 'return' => 0, 'stdout' => 'git version 2.52.0'],
[
'cmd' => ['git', 'branch', '-a', '--no-color', '--no-abbrev', '-v'],
// Assumption here is that arbitrary would be the default branch
'stdout' => " arbitrary $commitHash Commit message\n* current $anotherCommitHash Another message\n",
],
], true);
$config = new Config;
$config->merge(['repositories' => ['packagist' => false]]);
$guesser = new VersionGuesser($config, $process, new VersionParser());
$versionArray = $guesser->guessVersion(['version' => 'self.version'], 'dummy/path');
self::assertIsArray($versionArray);
self::assertEquals("dev-current", $versionArray['version']);
self::assertEquals($anotherCommitHash, $versionArray['commit']);
}
public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationForArbitraryNaming(): void
{
$commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea';
$anotherCommitHash = '13a15d220da53c52eddd5f32ffca64a7b3801bea';
$process = $this->getProcessExecutorMock();
$process->expects([
['cmd' => ['git', '--version'], 'return' => 0, 'stdout' => 'git version 2.52.0'],
[
'cmd' => ['git', 'branch', '-a', '--no-color', '--no-abbrev', '-v'],
'stdout' => " arbitrary $commitHash Commit message\n* feature $anotherCommitHash Another message\n",
],
[
'cmd' => ['git', 'rev-list', 'arbitrary..feature'],
'stdout' => "$anotherCommitHash\n",
],
], true);
$config = new Config;
$config->merge(['repositories' => ['packagist' => false]]);
$guesser = new VersionGuesser($config, $process, new VersionParser());
$versionArray = $guesser->guessVersion(['version' => 'self.version', 'non-feature-branches' => ['arbitrary']], 'dummy/path');
self::assertIsArray($versionArray);
self::assertEquals("dev-arbitrary", $versionArray['version']);
self::assertEquals($anotherCommitHash, $versionArray['commit']);
self::assertArrayHasKey('feature_version', $versionArray);
self::assertEquals("dev-feature", $versionArray['feature_version']);
self::assertEquals("dev-feature", $versionArray['feature_pretty_version']);
}
public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationForArbitraryNamingRegex(): void
{
$commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea';
$anotherCommitHash = '13a15d220da53c52eddd5f32ffca64a7b3801bea';
$process = $this->getProcessExecutorMock();
$process->expects([
['cmd' => ['git', '--version'], 'return' => 0, 'stdout' => 'git version 2.52.0'],
[
'cmd' => ['git', 'branch', '-a', '--no-color', '--no-abbrev', '-v'],
'stdout' => " latest-testing $commitHash Commit message\n* feature $anotherCommitHash Another message\n",
],
[
'cmd' => ['git', 'rev-list', 'latest-testing..feature'],
'stdout' => "$anotherCommitHash\n",
],
], true);
$config = new Config;
$config->merge(['repositories' => ['packagist' => false]]);
$guesser = new VersionGuesser($config, $process, new VersionParser());
$versionArray = $guesser->guessVersion(['version' => 'self.version', 'non-feature-branches' => ['latest-.*']], 'dummy/path');
self::assertIsArray($versionArray);
self::assertEquals("dev-latest-testing", $versionArray['version']);
self::assertEquals($anotherCommitHash, $versionArray['commit']);
self::assertArrayHasKey('feature_version', $versionArray);
self::assertEquals("dev-feature", $versionArray['feature_version']);
self::assertEquals("dev-feature", $versionArray['feature_pretty_version']);
}
public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationForArbitraryNamingWhenOnNonFeatureBranch(): void
{
$commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea';
$anotherCommitHash = '13a15d220da53c52eddd5f32ffca64a7b3801bea';
$process = $this->getProcessExecutorMock();
$process->expects([
['cmd' => ['git', '--version'], 'return' => 0, 'stdout' => 'git version 2.52.0'],
[
'cmd' => ['git', 'branch', '-a', '--no-color', '--no-abbrev', '-v'],
'stdout' => "* latest-testing $commitHash Commit message\n current $anotherCommitHash Another message\n master $anotherCommitHash Another message\n",
],
], true);
$config = new Config;
$config->merge(['repositories' => ['packagist' => false]]);
$guesser = new VersionGuesser($config, $process, new VersionParser());
$versionArray = $guesser->guessVersion(['version' => 'self.version', 'non-feature-branches' => ['latest-.*']], 'dummy/path');
self::assertIsArray($versionArray);
self::assertEquals("dev-latest-testing", $versionArray['version']);
self::assertEquals($commitHash, $versionArray['commit']);
self::assertArrayNotHasKey('feature_version', $versionArray);
self::assertArrayNotHasKey('feature_pretty_version', $versionArray);
}
public function testDetachedHeadBecomesDevHash(): void
{
$commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea';
$process = $this->getProcessExecutorMock();
$process->expects([
['cmd' => ['git', '--version'], 'return' => 0, 'stdout' => 'git version 2.52.0'],
[
'cmd' => ['git', 'branch', '-a', '--no-color', '--no-abbrev', '-v'],
'stdout' => "* (no branch) $commitHash Commit message\n",
],
['git', 'describe', '--exact-match', '--tags'],
], true);
$config = new Config;
$config->merge(['repositories' => ['packagist' => false]]);
$guesser = new VersionGuesser($config, $process, new VersionParser());
$versionData = $guesser->guessVersion([], 'dummy/path');
self::assertIsArray($versionData);
self::assertEquals("dev-$commitHash", $versionData['version']);
}
public function testDetachedFetchHeadBecomesDevHashGit2(): void
{
$commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea';
$process = $this->getProcessExecutorMock();
$process->expects([
['cmd' => ['git', '--version'], 'return' => 0, 'stdout' => 'git version 2.52.0'],
[
'cmd' => ['git', 'branch', '-a', '--no-color', '--no-abbrev', '-v'],
'stdout' => "* (HEAD detached at FETCH_HEAD) $commitHash Commit message\n",
],
['git', 'describe', '--exact-match', '--tags'],
], true);
$config = new Config;
$config->merge(['repositories' => ['packagist' => false]]);
$guesser = new VersionGuesser($config, $process, new VersionParser());
$versionData = $guesser->guessVersion([], 'dummy/path');
self::assertIsArray($versionData);
self::assertEquals("dev-$commitHash", $versionData['version']);
}
public function testDetachedCommitHeadBecomesDevHashGit2(): void
{
$commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea';
$process = $this->getProcessExecutorMock();
$process->expects([
['cmd' => ['git', '--version'], 'return' => 0, 'stdout' => 'git version 2.52.0'],
[
'cmd' => ['git', 'branch', '-a', '--no-color', '--no-abbrev', '-v'],
'stdout' => "* (HEAD detached at 03a15d220) $commitHash Commit message\n",
],
['git', 'describe', '--exact-match', '--tags'],
], true);
$config = new Config;
$config->merge(['repositories' => ['packagist' => false]]);
$guesser = new VersionGuesser($config, $process, new VersionParser());
$versionData = $guesser->guessVersion([], 'dummy/path');
self::assertIsArray($versionData);
self::assertEquals("dev-$commitHash", $versionData['version']);
}
public function testTagBecomesVersion(): void
{
$process = $this->getProcessExecutorMock();
$process->expects([
['cmd' => ['git', '--version'], 'return' => 0, 'stdout' => 'git version 2.52.0'],
[
'cmd' => ['git', 'branch', '-a', '--no-color', '--no-abbrev', '-v'],
'stdout' => "* (HEAD detached at v2.0.5-alpha2) 433b98d4218c181bae01865901aac045585e8a1a Commit message\n",
],
[
'cmd' => ['git', 'describe', '--exact-match', '--tags'],
'stdout' => "v2.0.5-alpha2",
],
], true);
$config = new Config;
$config->merge(['repositories' => ['packagist' => false]]);
$guesser = new VersionGuesser($config, $process, new VersionParser());
$versionData = $guesser->guessVersion([], 'dummy/path');
self::assertIsArray($versionData);
self::assertEquals("2.0.5.0-alpha2", $versionData['version']);
}
public function testTagBecomesPrettyVersion(): void
{
$process = $this->getProcessExecutorMock();
$process->expects([
['cmd' => ['git', '--version'], 'return' => 0, 'stdout' => 'git version 2.52.0'],
[
'cmd' => ['git', 'branch', '-a', '--no-color', '--no-abbrev', '-v'],
'stdout' => "* (HEAD detached at 1.0.0) c006f0c12bbbf197b5c071ffb1c0e9812bb14a4d Commit message\n",
],
[
'cmd' => ['git', 'describe', '--exact-match', '--tags'],
'stdout' => '1.0.0',
],
], true);
$config = new Config;
$config->merge(['repositories' => ['packagist' => false]]);
$guesser = new VersionGuesser($config, $process, new VersionParser());
$versionData = $guesser->guessVersion([], 'dummy/path');
self::assertIsArray($versionData);
self::assertEquals('1.0.0.0', $versionData['version']);
self::assertEquals('1.0.0', $versionData['pretty_version']);
}
public function testInvalidTagBecomesVersion(): void
{
$process = $this->getProcessExecutorMock();
$process->expects([
['cmd' => ['git', '--version'], 'return' => 0, 'stdout' => 'git version 2.52.0'],
[
'cmd' => ['git', 'branch', '-a', '--no-color', '--no-abbrev', '-v'],
'stdout' => "* foo 03a15d220da53c52eddd5f32ffca64a7b3801bea Commit message\n",
],
], true);
$config = new Config;
$config->merge(['repositories' => ['packagist' => false]]);
$guesser = new VersionGuesser($config, $process, new VersionParser());
$versionData = $guesser->guessVersion([], 'dummy/path');
self::assertIsArray($versionData);
self::assertEquals("dev-foo", $versionData['version']);
}
public function testNumericBranchesShowNicely(): void
{
$process = $this->getProcessExecutorMock();
$process->expects([
['cmd' => ['git', '--version'], 'return' => 0, 'stdout' => 'git version 2.52.0'],
[
'cmd' => ['git', 'branch', '-a', '--no-color', '--no-abbrev', '-v'],
'stdout' => "* 1.5 03a15d220da53c52eddd5f32ffca64a7b3801bea Commit message\n",
],
], true);
$config = new Config;
$config->merge(['repositories' => ['packagist' => false]]);
$guesser = new VersionGuesser($config, $process, new VersionParser());
$versionData = $guesser->guessVersion([], 'dummy/path');
self::assertIsArray($versionData);
self::assertEquals("1.5.x-dev", $versionData['pretty_version']);
self::assertEquals("1.5.9999999.9999999-dev", $versionData['version']);
}
public function testRemoteBranchesAreSelected(): void
{
$process = $this->getProcessExecutorMock();
$process->expects([
['cmd' => ['git', '--version'], 'return' => 0, 'stdout' => 'git version 2.52.0'],
[
'cmd' => ['git', 'branch', '-a', '--no-color', '--no-abbrev', '-v'],
'stdout' => "* feature-branch 03a15d220da53c52eddd5f32ffca64a7b3801bea Commit message\n".
"remotes/origin/1.5 03a15d220da53c52eddd5f32ffca64a7b3801bea Commit message\n",
],
[
'cmd' => ['git', 'rev-list', 'remotes/origin/1.5..feature-branch'],
'stdout' => "\n",
],
], true);
$config = new Config;
$config->merge(['repositories' => ['packagist' => false]]);
$guesser = new VersionGuesser($config, $process, new VersionParser());
$versionData = $guesser->guessVersion(['version' => 'self.version'], 'dummy/path');
self::assertIsArray($versionData);
self::assertEquals("1.5.x-dev", $versionData['pretty_version']);
self::assertEquals("1.5.9999999.9999999-dev", $versionData['version']);
}
/**
* @dataProvider rootEnvVersionsProvider
*/
public function testGetRootVersionFromEnv(string $env, string $expectedVersion): void
{
Platform::putEnv('COMPOSER_ROOT_VERSION', $env);
$guesser = new VersionGuesser(new Config, $this->getProcessExecutorMock(), new VersionParser());
self::assertSame($expectedVersion, $guesser->getRootVersionFromEnv());
Platform::clearEnv('COMPOSER_ROOT_VERSION');
}
/**
* @return array<array{string, string}>
*/
public function rootEnvVersionsProvider(): array
{
return [
['1.0-dev', '1.0.x-dev'],
['1.0.x-dev', '1.0.x-dev'],
['1-dev', '1.x-dev'],
['1.x-dev', '1.x-dev'],
['1.0.0', '1.0.0'],
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Package/Version/VersionParserTest.php | tests/Composer/Test/Package/Version/VersionParserTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Package\Version;
use Composer\Package\Version\VersionParser;
use Composer\Test\TestCase;
class VersionParserTest extends TestCase
{
/**
* @dataProvider provideParseNameVersionPairsData
*
* @param string[] $pairs
* @param array<array<string, string>> $result
*/
public function testParseNameVersionPairs(array $pairs, array $result): void
{
$versionParser = new VersionParser();
self::assertSame($result, $versionParser->parseNameVersionPairs($pairs));
}
public static function provideParseNameVersionPairsData(): array
{
return [
[['php:^7.0'], [['name' => 'php', 'version' => '^7.0']]],
[['php', '^7.0'], [['name' => 'php', 'version' => '^7.0']]],
[['php', 'ext-apcu'], [['name' => 'php'], ['name' => 'ext-apcu']]],
[['foo/*', 'bar*', 'acme/baz', '*@dev'], [['name' => 'foo/*'], ['name' => 'bar*'], ['name' => 'acme/baz', 'version' => '*@dev']]],
[['php', '*'], [['name' => 'php', 'version' => '*']]],
];
}
/**
* @dataProvider provideIsUpgradeTests
*/
public function testIsUpgrade(string $from, string $to, bool $expected): void
{
self::assertSame($expected, VersionParser::isUpgrade($from, $to));
}
public static function provideIsUpgradeTests(): array
{
return [
['0.9.0.0', '1.0.0.0', true],
['1.0.0.0', '0.9.0.0', false],
['1.0.0.0', VersionParser::DEFAULT_BRANCH_ALIAS, true],
[VersionParser::DEFAULT_BRANCH_ALIAS, VersionParser::DEFAULT_BRANCH_ALIAS, true],
[VersionParser::DEFAULT_BRANCH_ALIAS, '1.0.0.0', false],
['1.0.0.0', 'dev-foo', true],
['dev-foo', 'dev-foo', true],
['dev-foo', '1.0.0.0', true],
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Package/Version/VersionSelectorTest.php | tests/Composer/Test/Package/Version/VersionSelectorTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Package\Version;
use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterFactory;
use Composer\IO\BufferIO;
use Composer\Package\Version\VersionSelector;
use Composer\Package\Package;
use Composer\Package\Link;
use Composer\Package\AliasPackage;
use Composer\Repository\PlatformRepository;
use Composer\Package\Version\VersionParser;
use Composer\Test\TestCase;
use Symfony\Component\Console\Output\StreamOutput;
class VersionSelectorTest extends TestCase
{
// A) multiple versions, get the latest one
// B) targetPackageVersion will pass to repo set
// C) No results, throw exception
public function testLatestVersionIsReturned(): void
{
$packageName = 'foo/bar';
$package1 = self::getPackage('foo/bar', '1.2.1');
$package2 = self::getPackage('foo/bar', '1.2.2');
$package3 = self::getPackage('foo/bar', '1.2.0');
$packages = [$package1, $package2, $package3];
$repositorySet = $this->createMockRepositorySet();
$repositorySet->expects($this->once())
->method('findPackages')
->with($packageName, null)
->will($this->returnValue($packages));
$versionSelector = new VersionSelector($repositorySet);
$best = $versionSelector->findBestCandidate($packageName);
// 1.2.2 should be returned because it's the latest of the returned versions
self::assertSame($package2, $best, 'Latest version should be 1.2.2');
}
public function testLatestVersionIsReturnedThatMatchesPhpRequirements(): void
{
$packageName = 'foo/bar';
$platform = new PlatformRepository([], ['php' => '5.5.0']);
$repositorySet = $this->createMockRepositorySet();
$versionSelector = new VersionSelector($repositorySet, $platform);
$parser = new VersionParser;
$package0 = self::getPackage('foo/bar', '0.9.0');
$package0->setRequires(['php' => new Link($packageName, 'php', $parser->parseConstraints('>=5.6'), Link::TYPE_REQUIRE, '>=5.6')]);
$package1 = self::getPackage('foo/bar', '1.0.0');
$package1->setRequires(['php' => new Link($packageName, 'php', $parser->parseConstraints('>=5.4'), Link::TYPE_REQUIRE, '>=5.4')]);
$package2 = self::getPackage('foo/bar', '2.0.0');
$package2->setRequires(['php' => new Link($packageName, 'php', $parser->parseConstraints('>=5.6'), Link::TYPE_REQUIRE, '>=5.6')]);
$package3 = self::getPackage('foo/bar', '2.1.0');
$package3->setRequires(['php' => new Link($packageName, 'php', $parser->parseConstraints('>=5.6'), Link::TYPE_REQUIRE, '>=5.6')]);
$packages = [$package0, $package1, $package2, $package3];
$repositorySet->expects($this->any())
->method('findPackages')
->with($packageName, null)
->will($this->returnValue($packages));
$io = new BufferIO();
$best = $versionSelector->findBestCandidate($packageName, null, 'stable', null, 0, $io);
self::assertSame((string) $package1, (string) $best, 'Latest version supporting php 5.5 should be returned (1.0.0)');
self::assertSame("<warning>Cannot use foo/bar's latest version 2.1.0 as it requires php >=5.6 which is not satisfied by your platform.".PHP_EOL, $io->getOutput());
$io = new BufferIO('', StreamOutput::VERBOSITY_VERBOSE);
$best = $versionSelector->findBestCandidate($packageName, null, 'stable', null, 0, $io);
self::assertSame((string) $package1, (string) $best, 'Latest version supporting php 5.5 should be returned (1.0.0)');
self::assertSame(
"<warning>Cannot use foo/bar's latest version 2.1.0 as it requires php >=5.6 which is not satisfied by your platform.".PHP_EOL
."<warning>Cannot use foo/bar 2.0.0 as it requires php >=5.6 which is not satisfied by your platform.".PHP_EOL,
$io->getOutput()
);
$best = $versionSelector->findBestCandidate($packageName, null, 'stable', PlatformRequirementFilterFactory::ignoreAll());
self::assertSame((string) $package3, (string) $best, 'Latest version should be returned when ignoring platform reqs (2.1.0)');
}
public function testLatestVersionIsReturnedThatMatchesExtRequirements(): void
{
$packageName = 'foo/bar';
$platform = new PlatformRepository([], ['ext-zip' => '5.3.0']);
$repositorySet = $this->createMockRepositorySet();
$versionSelector = new VersionSelector($repositorySet, $platform);
$parser = new VersionParser;
$package1 = self::getPackage('foo/bar', '1.0.0');
$package1->setRequires(['ext-zip' => new Link($packageName, 'ext-zip', $parser->parseConstraints('^5.2'), Link::TYPE_REQUIRE, '^5.2')]);
$package2 = self::getPackage('foo/bar', '2.0.0');
$package2->setRequires(['ext-zip' => new Link($packageName, 'ext-zip', $parser->parseConstraints('^5.4'), Link::TYPE_REQUIRE, '^5.4')]);
$packages = [$package1, $package2];
$repositorySet->expects($this->any())
->method('findPackages')
->with($packageName, null)
->will($this->returnValue($packages));
$best = $versionSelector->findBestCandidate($packageName);
self::assertSame($package1, $best, 'Latest version supporting ext-zip 5.3.0 should be returned (1.0.0)');
$best = $versionSelector->findBestCandidate($packageName, null, 'stable', PlatformRequirementFilterFactory::ignoreAll());
self::assertSame($package2, $best, 'Latest version should be returned when ignoring platform reqs (2.0.0)');
}
public function testLatestVersionIsReturnedThatMatchesPlatformExt(): void
{
$packageName = 'foo/bar';
$platform = new PlatformRepository();
$repositorySet = $this->createMockRepositorySet();
$versionSelector = new VersionSelector($repositorySet, $platform);
$parser = new VersionParser;
$package1 = self::getPackage('foo/bar', '1.0.0');
$package2 = self::getPackage('foo/bar', '2.0.0');
$package2->setRequires(['ext-barfoo' => new Link($packageName, 'ext-barfoo', $parser->parseConstraints('*'), Link::TYPE_REQUIRE, '*')]);
$packages = [$package1, $package2];
$repositorySet->expects($this->any())
->method('findPackages')
->with($packageName, null)
->will($this->returnValue($packages));
$best = $versionSelector->findBestCandidate($packageName);
self::assertSame($package1, $best, 'Latest version not requiring ext-barfoo should be returned (1.0.0)');
$best = $versionSelector->findBestCandidate($packageName, null, 'stable', PlatformRequirementFilterFactory::ignoreAll());
self::assertSame($package2, $best, 'Latest version should be returned when ignoring platform reqs (2.0.0)');
}
public function testLatestVersionIsReturnedThatMatchesComposerRequirements(): void
{
$packageName = 'foo/bar';
$platform = new PlatformRepository([], ['composer-runtime-api' => '1.0.0']);
$repositorySet = $this->createMockRepositorySet();
$versionSelector = new VersionSelector($repositorySet, $platform);
$parser = new VersionParser;
$package1 = self::getPackage('foo/bar', '1.0.0');
$package1->setRequires(['composer-runtime-api' => new Link($packageName, 'composer-runtime-api', $parser->parseConstraints('^1.0'), Link::TYPE_REQUIRE, '^1.0')]);
$package2 = self::getPackage('foo/bar', '1.1.0');
$package2->setRequires(['composer-runtime-api' => new Link($packageName, 'composer-runtime-api', $parser->parseConstraints('^2.0'), Link::TYPE_REQUIRE, '^2.0')]);
$packages = [$package1, $package2];
$repositorySet->expects($this->any())
->method('findPackages')
->with($packageName, null)
->will($this->returnValue($packages));
$best = $versionSelector->findBestCandidate($packageName);
self::assertSame($package1, $best, 'Latest version supporting composer 1 should be returned (1.0.0)');
$best = $versionSelector->findBestCandidate($packageName, null, 'stable', PlatformRequirementFilterFactory::ignoreAll());
self::assertSame($package2, $best, 'Latest version should be returned when ignoring platform reqs (1.1.0)');
}
public function testMostStableVersionIsReturned(): void
{
$packageName = 'foo/bar';
$package1 = self::getPackage('foo/bar', '1.0.0');
$package2 = self::getPackage('foo/bar', '1.1.0-beta');
$packages = [$package1, $package2];
$repositorySet = $this->createMockRepositorySet();
$repositorySet->expects($this->once())
->method('findPackages')
->with($packageName, null)
->will($this->returnValue($packages));
$versionSelector = new VersionSelector($repositorySet);
$best = $versionSelector->findBestCandidate($packageName);
self::assertSame($package1, $best, 'Latest most stable version should be returned (1.0.0)');
}
public function testMostStableVersionIsReturnedRegardlessOfOrder(): void
{
$packageName = 'foo/bar';
$package1 = self::getPackage('foo/bar', '2.x-dev');
$package2 = self::getPackage('foo/bar', '2.0.0-beta3');
$packages = [$package1, $package2];
$repositorySet = $this->createMockRepositorySet();
$repositorySet->expects($this->exactly(2))
->method('findPackages')
->with($packageName, null)
->willReturnOnConsecutiveCalls(
$packages,
array_reverse($packages)
);
$versionSelector = new VersionSelector($repositorySet);
$best = $versionSelector->findBestCandidate($packageName);
self::assertSame($package2, $best, 'Expecting 2.0.0-beta3, cause beta is more stable than dev');
$best = $versionSelector->findBestCandidate($packageName);
self::assertSame($package2, $best, 'Expecting 2.0.0-beta3, cause beta is more stable than dev');
}
public function testHighestVersionIsReturned(): void
{
$packageName = 'foo/bar';
$package1 = self::getPackage('foo/bar', '1.0.0');
$package2 = self::getPackage('foo/bar', '1.1.0-beta');
$packages = [$package1, $package2];
$repositorySet = $this->createMockRepositorySet();
$repositorySet->expects($this->once())
->method('findPackages')
->with($packageName, null)
->will($this->returnValue($packages));
$versionSelector = new VersionSelector($repositorySet);
$best = $versionSelector->findBestCandidate($packageName, null, 'dev');
self::assertSame($package2, $best, 'Latest version should be returned (1.1.0-beta)');
}
public function testHighestVersionMatchingStabilityIsReturned(): void
{
$packageName = 'foo/bar';
$package1 = self::getPackage('foo/bar', '1.0.0');
$package2 = self::getPackage('foo/bar', '1.1.0-beta');
$package3 = self::getPackage('foo/bar', '1.2.0-alpha');
$packages = [$package1, $package2, $package3];
$repositorySet = $this->createMockRepositorySet();
$repositorySet->expects($this->once())
->method('findPackages')
->with($packageName, null)
->will($this->returnValue($packages));
$versionSelector = new VersionSelector($repositorySet);
$best = $versionSelector->findBestCandidate($packageName, null, 'beta');
self::assertSame($package2, $best, 'Latest version should be returned (1.1.0-beta)');
}
public function testMostStableUnstableVersionIsReturned(): void
{
$packageName = 'foo/bar';
$package2 = self::getPackage('foo/bar', '1.1.0-beta');
$package3 = self::getPackage('foo/bar', '1.2.0-alpha');
$packages = [$package2, $package3];
$repositorySet = $this->createMockRepositorySet();
$repositorySet->expects($this->once())
->method('findPackages')
->with($packageName, null)
->will($this->returnValue($packages));
$versionSelector = new VersionSelector($repositorySet);
$best = $versionSelector->findBestCandidate($packageName, null, 'stable');
self::assertSame($package2, $best, 'Latest version should be returned (1.1.0-beta)');
}
public function testDefaultBranchAliasIsNeverReturned(): void
{
$packageName = 'foo/bar';
$package = self::getPackage('foo/bar', '1.1.0-beta');
$package2 = self::getPackage('foo/bar', 'dev-main');
$package2Alias = new AliasPackage($package2, VersionParser::DEFAULT_BRANCH_ALIAS, VersionParser::DEFAULT_BRANCH_ALIAS);
$packages = [$package, $package2Alias];
$repositorySet = $this->createMockRepositorySet();
$repositorySet->expects($this->once())
->method('findPackages')
->with($packageName, null)
->will($this->returnValue($packages));
$versionSelector = new VersionSelector($repositorySet);
$best = $versionSelector->findBestCandidate($packageName, null, 'dev');
self::assertSame($package2, $best, 'Latest version should be returned (dev-main)');
}
public function testFalseReturnedOnNoPackages(): void
{
$repositorySet = $this->createMockRepositorySet();
$repositorySet->expects($this->once())
->method('findPackages')
->will($this->returnValue([]));
$versionSelector = new VersionSelector($repositorySet);
$best = $versionSelector->findBestCandidate('foobaz');
self::assertFalse($best, 'No versions are available returns false');
}
/**
* @dataProvider provideRecommendedRequireVersionPackages
*/
public function testFindRecommendedRequireVersion(string $prettyVersion, string $expectedVersion, ?string $branchAlias = null, string $packageName = 'foo/bar'): void
{
$repositorySet = $this->createMockRepositorySet();
$versionSelector = new VersionSelector($repositorySet);
$versionParser = new VersionParser();
$package = new Package($packageName, $versionParser->normalize($prettyVersion), $prettyVersion);
if ($branchAlias) {
$package->setExtra(['branch-alias' => [$prettyVersion => $branchAlias]]);
}
$recommended = $versionSelector->findRecommendedRequireVersion($package);
// assert that the recommended version is what we expect
self::assertSame($expectedVersion, $recommended);
}
public static function provideRecommendedRequireVersionPackages(): array
{
return [
// real version, expected recommendation, [branch-alias], [pkg name]
['1.2.1', '^1.2'],
['1.2', '^1.2'],
['v1.2.1', '^1.2'],
['3.1.2-pl2', '^3.1'],
['3.1.2-patch', '^3.1'],
['2.0-beta.1', '^2.0@beta'],
['3.1.2-alpha5', '^3.1@alpha'],
['3.0-RC2', '^3.0@RC'],
['0.1.0', '^0.1.0'],
['0.1.3', '^0.1.3'],
['0.0.3', '^0.0.3'],
['0.0.3-alpha', '^0.0.3@alpha'],
['0.0.3.4-alpha', '^0.0.3@alpha'],
['3.0.0.2-RC2', '^3.0@RC'],
['1.2.1.1020402', '^1.2'],
// date-based versions are not touched at all
['v20121020', 'v20121020'],
['v20121020.2', 'v20121020.2'],
// dev packages without alias are not touched at all
['dev-master', 'dev-master'],
['3.1.2-dev', '3.1.2-dev'],
// dev packages with alias inherit the alias
['dev-master', '^2.1@dev', '2.1.x-dev'],
['dev-master', '^2.1@dev', '2.1-dev'],
['dev-master', '^2.1@dev', '2.1.3.x-dev'],
['dev-master', '^2.0@dev', '2.x-dev'],
['dev-master', '^0.3.0@dev', '0.3.x-dev'],
['dev-master', '^0.0.3@dev', '0.0.3.x-dev'],
['dev-master', 'dev-master', VersionParser::DEFAULT_BRANCH_ALIAS],
// numeric alias
['3.x-dev', '^3.0@dev', '3.0.x-dev'],
['3.x-dev', '^3.0@dev', '3.0-dev'],
// ext in sync with php
[PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION, '*', null, 'ext-filter'],
// ext versioned individually
['3.0.5', '^3.0', null, 'ext-xdebug'],
];
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Repository\RepositorySet
*/
private function createMockRepositorySet()
{
return $this->getMockBuilder('Composer\Repository\RepositorySet')
->disableOriginalConstructor()
->getMock();
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Downloader/GitDownloaderTest.php | tests/Composer/Test/Downloader/GitDownloaderTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Downloader;
use Composer\Downloader\GitDownloader;
use Composer\Config;
use Composer\Pcre\Preg;
use Composer\Test\TestCase;
use Composer\Util\Filesystem;
use Composer\Util\Platform;
class GitDownloaderTest extends TestCase
{
/** @var Filesystem */
private $fs;
/** @var string */
private $workingDir;
protected function setUp(): void
{
$this->skipIfNotExecutable('git');
$this->initGitVersion('1.0.0');
$this->fs = new Filesystem;
$this->workingDir = self::getUniqueTmpDirectory();
}
protected function tearDown(): void
{
parent::tearDown();
if (is_dir($this->workingDir)) {
$this->fs->removeDirectory($this->workingDir);
}
$this->initGitVersion(false);
}
/**
* @param string|bool $version
*/
private function initGitVersion($version): void
{
// reset the static version cache
$refl = new \ReflectionProperty('Composer\Util\Git', 'version');
(\PHP_VERSION_ID < 80100) and $refl->setAccessible(true);
$refl->setValue(null, $version);
}
/**
* @param ?Config $config
*/
protected function setupConfig($config = null): Config
{
if (!$config) {
$config = new Config();
}
if (!$config->has('home')) {
$tmpDir = realpath(sys_get_temp_dir()).DIRECTORY_SEPARATOR.'cmptest-'.bin2hex(random_bytes(5));
$config->merge(['config' => ['home' => $tmpDir]]);
}
return $config;
}
protected function getDownloaderMock(?\Composer\IO\IOInterface $io = null, ?Config $config = null, ?\Composer\Test\Mock\ProcessExecutorMock $executor = null, ?Filesystem $filesystem = null): GitDownloader
{
$io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$executor = $executor ?: $this->getProcessExecutorMock();
$filesystem = $filesystem ?: $this->getMockBuilder('Composer\Util\Filesystem')->getMock();
$config = $this->setupConfig($config);
return new GitDownloader($io, $config, $executor, $filesystem);
}
public function testDownloadForPackageWithoutSourceReference(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->once())
->method('getSourceReference')
->will($this->returnValue(null));
self::expectException('InvalidArgumentException');
$downloader = $this->getDownloaderMock();
$downloader->download($packageMock, '/path');
$downloader->prepare('install', $packageMock, '/path');
$downloader->install($packageMock, '/path');
$downloader->cleanup('install', $packageMock, '/path');
}
public function testDownload(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('1234567890123456789012345678901234567890'));
$packageMock->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://example.com/composer/composer']));
$packageMock->expects($this->any())
->method('getSourceUrl')
->will($this->returnValue('https://example.com/composer/composer'));
$packageMock->expects($this->any())
->method('getPrettyVersion')
->will($this->returnValue('dev-master'));
$process = $this->getProcessExecutorMock();
$expectedPath = Platform::isWindows() ? Platform::getCwd().'/composerPath' : 'composerPath';
$process->expects([
['git', 'clone', '--no-checkout', '--', 'https://example.com/composer/composer', $expectedPath],
['git', 'remote', 'add', 'composer', '--', 'https://example.com/composer/composer'],
['git', 'fetch', 'composer'],
['git', 'remote', 'set-url', 'origin', '--', 'https://example.com/composer/composer'],
['git', 'remote', 'set-url', 'composer', '--', 'https://example.com/composer/composer'],
['git', 'branch', '-r'],
['git', 'checkout', 'master', '--'],
['git', 'reset', '--hard', '1234567890123456789012345678901234567890', '--'],
], true);
$downloader = $this->getDownloaderMock(null, null, $process);
$downloader->download($packageMock, 'composerPath');
$downloader->prepare('install', $packageMock, 'composerPath');
$downloader->install($packageMock, 'composerPath');
$downloader->cleanup('install', $packageMock, 'composerPath');
}
public function testDownloadWithCache(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('1234567890123456789012345678901234567890'));
$packageMock->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://example.com/composer/composer']));
$packageMock->expects($this->any())
->method('getSourceUrl')
->will($this->returnValue('https://example.com/composer/composer'));
$packageMock->expects($this->any())
->method('getPrettyVersion')
->will($this->returnValue('dev-master'));
$this->initGitVersion('2.17.0');
$config = new Config;
$this->setupConfig($config);
$cachePath = $config->get('cache-vcs-dir').'/'.Preg::replace('{[^a-z0-9.]}i', '-', 'https://example.com/composer/composer').'/';
$filesystem = new Filesystem;
$filesystem->removeDirectory($cachePath);
$expectedPath = Platform::isWindows() ? Platform::getCwd().'/composerPath' : 'composerPath';
$process = $this->getProcessExecutorMock();
$process->expects([
[
'cmd' => ['git', 'clone', '--mirror', '--', 'https://example.com/composer/composer', $cachePath],
'callback' => static function () use ($cachePath): void {
@mkdir($cachePath, 0777, true);
},
],
['cmd' => ['git', 'rev-parse', '--git-dir'], 'stdout' => '.'],
['git', 'rev-parse', '--quiet', '--verify', '1234567890123456789012345678901234567890^{commit}'],
['git', 'clone', '--no-checkout', $cachePath, $expectedPath, '--dissociate', '--reference', $cachePath],
['git', 'remote', 'set-url', 'origin', '--', 'https://example.com/composer/composer'],
['git', 'remote', 'add', 'composer', '--', 'https://example.com/composer/composer'],
['git', 'branch', '-r'],
['cmd' => ['git', 'checkout', 'master', '--'], 'return' => 1],
['git', 'checkout', '-B', 'master', 'composer/master', '--'],
['git', 'reset', '--hard', '1234567890123456789012345678901234567890', '--'],
], true);
$downloader = $this->getDownloaderMock(null, $config, $process);
$downloader->download($packageMock, 'composerPath');
$downloader->prepare('install', $packageMock, 'composerPath');
$downloader->install($packageMock, 'composerPath');
$downloader->cleanup('install', $packageMock, 'composerPath');
@rmdir($cachePath);
}
public function testDownloadUsesVariousProtocolsAndSetsPushUrlForGithub(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$packageMock->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://github.com/mirrors/composer', 'https://github.com/composer/composer']));
$packageMock->expects($this->any())
->method('getSourceUrl')
->will($this->returnValue('https://github.com/composer/composer'));
$packageMock->expects($this->any())
->method('getPrettyVersion')
->will($this->returnValue('1.0.0'));
$process = $this->getProcessExecutorMock();
$expectedPath = Platform::isWindows() ? Platform::getCwd().'/composerPath' : 'composerPath';
$process->expects([
['cmd' => ['git', 'clone', '--no-checkout', '--', 'https://github.com/mirrors/composer', $expectedPath], 'return' => 1, 'stderr' => 'Error1'],
['git', 'clone', '--no-checkout', '--', 'git@github.com:mirrors/composer', $expectedPath],
['git', 'remote', 'add', 'composer', '--', 'git@github.com:mirrors/composer'],
['git', 'fetch', 'composer'],
['git', 'remote', 'set-url', 'origin', '--', 'git@github.com:mirrors/composer'],
['git', 'remote', 'set-url', 'composer', '--', 'git@github.com:mirrors/composer'],
['git', 'remote', 'set-url', 'origin', '--', 'https://github.com/composer/composer'],
['git', 'remote', 'set-url', '--push', 'origin', '--', 'git@github.com:composer/composer.git'],
['git', 'branch', '-r'],
['git', 'checkout', 'ref', '--'],
['git', 'reset', '--hard', 'ref', '--'],
], true);
$downloader = $this->getDownloaderMock(null, new Config(), $process);
$downloader->download($packageMock, 'composerPath');
$downloader->prepare('install', $packageMock, 'composerPath');
$downloader->install($packageMock, 'composerPath');
$downloader->cleanup('install', $packageMock, 'composerPath');
}
public static function pushUrlProvider(): array
{
return [
// ssh proto should use git@ all along
[['ssh'], 'git@github.com:composer/composer', 'git@github.com:composer/composer.git'],
// auto-proto uses git@ by default for push url, but not fetch
[['https', 'ssh', 'git'], 'https://github.com/composer/composer', 'git@github.com:composer/composer.git'],
// if restricted to https then push url is not overwritten to git@
[['https'], 'https://github.com/composer/composer', 'https://github.com/composer/composer.git'],
];
}
/**
* @dataProvider pushUrlProvider
* @param string[] $protocols
*/
public function testDownloadAndSetPushUrlUseCustomVariousProtocolsForGithub(array $protocols, string $url, string $pushUrl): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$packageMock->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://github.com/composer/composer']));
$packageMock->expects($this->any())
->method('getSourceUrl')
->will($this->returnValue('https://github.com/composer/composer'));
$packageMock->expects($this->any())
->method('getPrettyVersion')
->will($this->returnValue('1.0.0'));
$process = $this->getProcessExecutorMock();
$expectedPath = Platform::isWindows() ? Platform::getCwd().'/composerPath' : 'composerPath';
$process->expects([
['git', 'clone', '--no-checkout', '--', $url, $expectedPath],
['git', 'remote', 'add', 'composer', '--', $url],
['git', 'fetch', 'composer'],
['git', 'remote', 'set-url', 'origin', '--', $url],
['git', 'remote', 'set-url', 'composer', '--', $url],
['git', 'remote', 'set-url', '--push', 'origin', '--', $pushUrl],
['git', 'branch', '-r'],
['git', 'checkout', 'ref', '--'],
['git', 'reset', '--hard', 'ref', '--'],
], true);
$config = new Config();
$config->merge(['config' => ['github-protocols' => $protocols]]);
$downloader = $this->getDownloaderMock(null, $config, $process);
$downloader->download($packageMock, 'composerPath');
$downloader->prepare('install', $packageMock, 'composerPath');
$downloader->install($packageMock, 'composerPath');
$downloader->cleanup('install', $packageMock, 'composerPath');
}
public function testDownloadThrowsRuntimeExceptionIfGitCommandFails(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$packageMock->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://example.com/composer/composer']));
$packageMock->expects($this->any())
->method('getSourceUrl')
->will($this->returnValue('https://example.com/composer/composer'));
$packageMock->expects($this->any())
->method('getPrettyVersion')
->will($this->returnValue('1.0.0'));
$process = $this->getProcessExecutorMock();
$expectedPath = Platform::isWindows() ? Platform::getCwd().'/composerPath' : 'composerPath';
$process->expects([
[
'cmd' => ['git', 'clone', '--no-checkout', '--', 'https://example.com/composer/composer', $expectedPath],
'return' => 1,
],
]);
self::expectException('RuntimeException');
self::expectExceptionMessage('Failed to execute git clone --no-checkout -- https://example.com/composer/composer '.$expectedPath);
$downloader = $this->getDownloaderMock(null, null, $process);
$downloader->download($packageMock, 'composerPath');
$downloader->prepare('install', $packageMock, 'composerPath');
$downloader->install($packageMock, 'composerPath');
$downloader->cleanup('install', $packageMock, 'composerPath');
}
public function testUpdateforPackageWithoutSourceReference(): void
{
$initialPackageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$sourcePackageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$sourcePackageMock->expects($this->once())
->method('getSourceReference')
->will($this->returnValue(null));
self::expectException('InvalidArgumentException');
$downloader = $this->getDownloaderMock();
$downloader->download($sourcePackageMock, '/path', $initialPackageMock);
$downloader->prepare('update', $sourcePackageMock, '/path', $initialPackageMock);
$downloader->update($initialPackageMock, $sourcePackageMock, '/path');
$downloader->cleanup('update', $sourcePackageMock, '/path', $initialPackageMock);
}
public function testUpdate(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$packageMock->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://github.com/composer/composer']));
$packageMock->expects($this->any())
->method('getVersion')
->will($this->returnValue('1.0.0.0'));
$packageMock->expects($this->any())
->method('getPrettyVersion')
->will($this->returnValue('1.0.0'));
$process = $this->getProcessExecutorMock();
$process->expects([
['git', 'show-ref', '--head', '-d'],
['git', 'status', '--porcelain', '--untracked-files=no'],
['cmd' => ['git', 'rev-parse', '--quiet', '--verify', 'ref^{commit}'], 'return' => 1],
// fallback commands for the above failing
['git', 'remote', '-v'],
['git', 'remote', 'set-url', 'composer', '--', 'https://github.com/composer/composer'],
['git', 'fetch', 'composer'],
['git', 'fetch', '--tags', 'composer'],
['git', 'remote', '-v'],
['git', 'remote', 'set-url', 'composer', '--', 'https://github.com/composer/composer'],
['git', 'branch', '-r'],
['git', 'checkout', 'ref', '--'],
['git', 'reset', '--hard', 'ref', '--'],
['git', 'remote', '-v'],
], true);
$this->fs->ensureDirectoryExists($this->workingDir.'/.git');
$downloader = $this->getDownloaderMock(null, new Config(), $process);
$downloader->download($packageMock, $this->workingDir, $packageMock);
$downloader->prepare('update', $packageMock, $this->workingDir, $packageMock);
$downloader->update($packageMock, $packageMock, $this->workingDir);
$downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock);
}
public function testUpdateWithNewRepoUrl(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$packageMock->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://github.com/composer/composer']));
$packageMock->expects($this->any())
->method('getSourceUrl')
->will($this->returnValue('https://github.com/composer/composer'));
$packageMock->expects($this->any())
->method('getVersion')
->will($this->returnValue('1.0.0.0'));
$packageMock->expects($this->any())
->method('getPrettyVersion')
->will($this->returnValue('1.0.0'));
$process = $this->getProcessExecutorMock();
$process->expects([
['git', 'show-ref', '--head', '-d'],
['git', 'status', '--porcelain', '--untracked-files=no'],
['cmd' => ['git', 'rev-parse', '--quiet', '--verify', 'ref^{commit}'], 'return' => 0],
['git', 'remote', '-v'],
['git', 'remote', 'set-url', 'composer', '--', 'https://github.com/composer/composer'],
['git', 'branch', '-r'],
['git', 'checkout', 'ref', '--'],
['git', 'reset', '--hard', 'ref', '--'],
[
'cmd' => ['git', 'remote', '-v'],
'stdout' => 'origin https://github.com/old/url (fetch)
origin https://github.com/old/url (push)
composer https://github.com/old/url (fetch)
composer https://github.com/old/url (push)
',
],
['git', 'remote', 'set-url', 'origin', '--', 'https://github.com/composer/composer'],
['git', 'remote', 'set-url', '--push', 'origin', '--', 'git@github.com:composer/composer.git'],
], true);
$this->fs->ensureDirectoryExists($this->workingDir.'/.git');
$downloader = $this->getDownloaderMock(null, new Config(), $process);
$downloader->download($packageMock, $this->workingDir, $packageMock);
$downloader->prepare('update', $packageMock, $this->workingDir, $packageMock);
$downloader->update($packageMock, $packageMock, $this->workingDir);
$downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock);
}
/**
* @group failing
*/
public function testUpdateThrowsRuntimeExceptionIfGitCommandFails(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$packageMock->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://github.com/composer/composer']));
$packageMock->expects($this->any())
->method('getVersion')
->will($this->returnValue('1.0.0.0'));
$process = $this->getProcessExecutorMock();
$process->expects([
['git', 'show-ref', '--head', '-d'],
['git', 'status', '--porcelain', '--untracked-files=no'],
// commit not yet in so we try to fetch
['cmd' => ['git', 'rev-parse', '--quiet', '--verify', 'ref^{commit}'], 'return' => 1],
// fail first fetch
['git', 'remote', '-v'],
['git', 'remote', 'set-url', 'composer', '--', 'https://github.com/composer/composer'],
['cmd' => ['git', 'fetch', 'composer'], 'return' => 1],
// fail second fetch
['git', 'remote', 'set-url', 'composer', '--', 'git@github.com:composer/composer'],
['cmd' => ['git', 'fetch', 'composer'], 'return' => 1],
['git', '--version'],
], true);
$this->fs->ensureDirectoryExists($this->workingDir.'/.git');
self::expectException('RuntimeException');
self::expectExceptionMessage('Failed to clone https://github.com/composer/composer via https, ssh protocols, aborting.');
self::expectExceptionMessageMatches('{git@github\.com:composer/composer}');
$downloader = $this->getDownloaderMock(null, new Config(), $process);
$downloader->download($packageMock, $this->workingDir, $packageMock);
$downloader->prepare('update', $packageMock, $this->workingDir, $packageMock);
$downloader->update($packageMock, $packageMock, $this->workingDir);
$downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock);
}
public function testUpdateDoesntThrowsRuntimeExceptionIfGitCommandFailsAtFirstButIsAbleToRecover(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$packageMock->expects($this->any())
->method('getVersion')
->will($this->returnValue('1.0.0.0'));
$packageMock->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue([Platform::isWindows() ? 'C:\\' : '/', 'https://github.com/composer/composer']));
$packageMock->expects($this->any())
->method('getPrettyVersion')
->will($this->returnValue('1.0.0'));
$process = $this->getProcessExecutorMock();
$process->expects([
['git', 'show-ref', '--head', '-d'],
['git', 'status', '--porcelain', '--untracked-files=no'],
// commit not yet in so we try to fetch
['cmd' => ['git', 'rev-parse', '--quiet', '--verify', 'ref^{commit}'], 'return' => 1],
// fail first source URL
['git', 'remote', '-v'],
['git', 'remote', 'set-url', 'composer', '--', Platform::isWindows() ? 'C:\\' : '/'],
['cmd' => ['git', 'fetch', 'composer'], 'return' => 1],
['git', '--version'],
// commit not yet in so we try to fetch
['cmd' => ['git', 'rev-parse', '--quiet', '--verify', 'ref^{commit}'], 'return' => 1],
// pass second source URL
['git', 'remote', '-v'],
['git', 'remote', 'set-url', 'composer', '--', 'https://github.com/composer/composer'],
['cmd' => ['git', 'fetch', 'composer'], 'return' => 0],
['git', 'fetch', '--tags', 'composer'],
['git', 'remote', '-v'],
['git', 'remote', 'set-url', 'composer', '--', 'https://github.com/composer/composer'],
['git', 'branch', '-r'],
['git', 'checkout', 'ref', '--'],
['git', 'reset', '--hard', 'ref', '--'],
['git', 'remote', '-v'],
], true);
$this->fs->ensureDirectoryExists($this->workingDir.'/.git');
$downloader = $this->getDownloaderMock(null, new Config(), $process);
$downloader->download($packageMock, $this->workingDir, $packageMock);
$downloader->prepare('update', $packageMock, $this->workingDir, $packageMock);
$downloader->update($packageMock, $packageMock, $this->workingDir);
$downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock);
}
public function testDowngradeShowsAppropriateMessage(): void
{
$oldPackage = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$oldPackage->expects($this->any())
->method('getVersion')
->will($this->returnValue('1.2.0.0'));
$oldPackage->expects($this->any())
->method('getFullPrettyVersion')
->will($this->returnValue('1.2.0'));
$oldPackage->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$oldPackage->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['/foo/bar', 'https://github.com/composer/composer']));
$newPackage = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$newPackage->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$newPackage->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://github.com/composer/composer']));
$newPackage->expects($this->any())
->method('getVersion')
->will($this->returnValue('1.0.0.0'));
$newPackage->expects($this->any())
->method('getPrettyVersion')
->will($this->returnValue('1.0.0'));
$newPackage->expects($this->any())
->method('getFullPrettyVersion')
->will($this->returnValue('1.0.0'));
$process = $this->getProcessExecutorMock();
$ioMock = $this->getIOMock();
$ioMock->expects([
['text' => '{Downgrading .*}', 'regex' => true],
]);
$this->fs->ensureDirectoryExists($this->workingDir.'/.git');
$downloader = $this->getDownloaderMock($ioMock, null, $process);
$downloader->download($newPackage, $this->workingDir, $oldPackage);
$downloader->prepare('update', $newPackage, $this->workingDir, $oldPackage);
$downloader->update($oldPackage, $newPackage, $this->workingDir);
$downloader->cleanup('update', $newPackage, $this->workingDir, $oldPackage);
}
public function testNotUsingDowngradingWithReferences(): void
{
$oldPackage = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$oldPackage->expects($this->any())
->method('getVersion')
->will($this->returnValue('dev-ref'));
$oldPackage->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$oldPackage->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['/foo/bar', 'https://github.com/composer/composer']));
$newPackage = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$newPackage->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$newPackage->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://github.com/composer/composer']));
$newPackage->expects($this->any())
->method('getVersion')
->will($this->returnValue('dev-ref2'));
$newPackage->expects($this->any())
->method('getPrettyVersion')
->will($this->returnValue('dev-ref2'));
$process = $this->getProcessExecutorMock();
$ioMock = $this->getIOMock();
$ioMock->expects([
['text' => '{Upgrading .*}', 'regex' => true],
]);
$this->fs->ensureDirectoryExists($this->workingDir.'/.git');
$downloader = $this->getDownloaderMock($ioMock, null, $process);
$downloader->download($newPackage, $this->workingDir, $oldPackage);
$downloader->prepare('update', $newPackage, $this->workingDir, $oldPackage);
$downloader->update($oldPackage, $newPackage, $this->workingDir);
$downloader->cleanup('update', $newPackage, $this->workingDir, $oldPackage);
}
public function testRemove(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$process = $this->getProcessExecutorMock();
$process->expects([
['git', 'show-ref', '--head', '-d'],
['git', 'status', '--porcelain', '--untracked-files=no'],
], true);
$this->fs->ensureDirectoryExists($this->workingDir.'/.git');
$filesystem = $this->getMockBuilder('Composer\Util\Filesystem')->getMock();
$filesystem->expects($this->once())
->method('removeDirectoryAsync')
->with($this->equalTo($this->workingDir))
->will($this->returnValue(\React\Promise\resolve(true)));
$downloader = $this->getDownloaderMock(null, null, $process, $filesystem);
$downloader->prepare('uninstall', $packageMock, $this->workingDir);
$downloader->remove($packageMock, $this->workingDir);
$downloader->cleanup('uninstall', $packageMock, $this->workingDir);
}
public function testGetInstallationSource(): void
{
$downloader = $this->getDownloaderMock();
self::assertEquals('source', $downloader->getInstallationSource());
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Downloader/FileDownloaderTest.php | tests/Composer/Test/Downloader/FileDownloaderTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Downloader;
use Composer\Downloader\FileDownloader;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Plugin\PluginEvents;
use Composer\Plugin\PreFileDownloadEvent;
use Composer\Test\TestCase;
use Composer\Util\Filesystem;
use Composer\Util\Http\Response;
use Composer\Util\Loop;
use Composer\Config;
use Composer\PartialComposer;
class FileDownloaderTest extends TestCase
{
/** @var \Composer\Util\HttpDownloader&\PHPUnit\Framework\MockObject\MockObject */
private $httpDownloader;
public function setUp(): void
{
$this->httpDownloader = $this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock();
}
/**
* @param \Composer\Util\HttpDownloader&\PHPUnit\Framework\MockObject\MockObject $httpDownloader
*/
protected function getDownloader(?\Composer\IO\IOInterface $io = null, ?Config $config = null, ?EventDispatcher $eventDispatcher = null, ?\Composer\Cache $cache = null, $httpDownloader = null, ?Filesystem $filesystem = null): FileDownloader
{
$io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$config = $config ?: $this->getConfig();
$httpDownloader = $httpDownloader ?: $this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock();
$httpDownloader
->expects($this->any())
->method('addCopy')
->will($this->returnValue(\React\Promise\resolve(new Response(['url' => 'http://example.org/'], 200, [], 'file~'))));
$this->httpDownloader = $httpDownloader;
return new FileDownloader($io, $config, $httpDownloader, $eventDispatcher, $cache, $filesystem);
}
public function testDownloadForPackageWithoutDistReference(): void
{
$package = self::getPackage();
self::expectException('InvalidArgumentException');
$downloader = $this->getDownloader();
$downloader->download($package, '/path');
}
public function testDownloadToExistingFile(): void
{
$package = self::getPackage();
$package->setDistUrl('url');
$path = $this->createTempFile(self::getUniqueTmpDirectory());
$downloader = $this->getDownloader();
try {
$downloader->download($package, $path);
$this->fail();
} catch (\Exception $e) {
if (is_dir($path)) {
$fs = new Filesystem();
$fs->removeDirectory($path);
} elseif (is_file($path)) {
unlink($path);
}
self::assertInstanceOf('RuntimeException', $e);
self::assertStringContainsString('exists and is not a directory', $e->getMessage());
}
}
public function testGetFileName(): void
{
$package = self::getPackage();
$package->setDistUrl('http://example.com/script.js');
$config = $this->getConfig(['vendor-dir' => '/vendor']);
$downloader = $this->getDownloader(null, $config);
$method = new \ReflectionMethod($downloader, 'getFileName');
(\PHP_VERSION_ID < 80100) and $method->setAccessible(true);
self::assertMatchesRegularExpression('#/vendor/composer/tmp-[a-z0-9]+\.js#', $method->invoke($downloader, $package, '/path'));
}
public function testDownloadButFileIsUnsaved(): void
{
$package = self::getPackage();
$package->setDistUrl('http://example.com/script.js');
$path = self::getUniqueTmpDirectory();
$ioMock = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$ioMock->expects($this->any())
->method('write')
->will($this->returnCallback(static function ($messages, $newline = true) use ($path) {
if (is_file($path.'/script.js')) {
unlink($path.'/script.js');
}
return $messages;
}))
;
$config = $this->getConfig(['vendor-dir' => $path.'/vendor']);
$downloader = $this->getDownloader($ioMock, $config);
try {
$loop = new Loop($this->httpDownloader);
$promise = $downloader->download($package, $path);
$loop->wait([$promise]);
$this->fail('Download was expected to throw');
} catch (\Exception $e) {
if (is_dir($path)) {
$fs = new Filesystem();
$fs->removeDirectory($path);
} elseif (is_file($path)) {
unlink($path);
}
self::assertInstanceOf('UnexpectedValueException', $e, $e->getMessage());
self::assertStringContainsString('could not be saved to', $e->getMessage());
}
}
public function testDownloadWithCustomProcessedUrl(): void
{
$path = self::getUniqueTmpDirectory();
$package = self::getPackage();
$package->setDistUrl('url');
$rootPackage = self::getRootPackage();
$config = $this->getConfig([
'vendor-dir' => $path.'/vendor',
'bin-dir' => $path.'/vendor/bin',
]);
$composer = new PartialComposer;
$composer->setPackage($rootPackage);
$composer->setConfig($config);
$expectedUrl = 'foobar';
$expectedCacheKey = 'dummy/pkg/'.hash('sha1', $expectedUrl).'.';
$dispatcher = new EventDispatcher(
$composer,
$this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
$this->getProcessExecutorMock()
);
$dispatcher->addListener(PluginEvents::PRE_FILE_DOWNLOAD, static function (PreFileDownloadEvent $event) use ($expectedUrl): void {
$event->setProcessedUrl($expectedUrl);
});
$cacheMock = $this->getMockBuilder('Composer\Cache')
->disableOriginalConstructor()
->getMock();
$cacheMock
->expects($this->any())
->method('copyTo')
->will($this->returnCallback(static function ($cacheKey) use ($expectedCacheKey): bool {
self::assertEquals($expectedCacheKey, $cacheKey, 'Failed assertion on $cacheKey argument of Cache::copyTo method:');
return false;
}));
$cacheMock
->expects($this->any())
->method('copyFrom')
->will($this->returnCallback(static function ($cacheKey) use ($expectedCacheKey): bool {
self::assertEquals($expectedCacheKey, $cacheKey, 'Failed assertion on $cacheKey argument of Cache::copyFrom method:');
return false;
}));
$httpDownloaderMock = $this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock();
$httpDownloaderMock
->expects($this->any())
->method('addCopy')
->will($this->returnCallback(static function ($url) use ($expectedUrl) {
self::assertEquals($expectedUrl, $url, 'Failed assertion on $url argument of HttpDownloader::addCopy method:');
return \React\Promise\resolve(
new Response(['url' => 'http://example.org/'], 200, [], 'file~')
);
}));
$downloader = $this->getDownloader(null, $config, $dispatcher, $cacheMock, $httpDownloaderMock);
try {
$loop = new Loop($this->httpDownloader);
$promise = $downloader->download($package, $path);
$loop->wait([$promise]);
$this->fail('Download was expected to throw');
} catch (\Exception $e) {
if (is_dir($path)) {
$fs = new Filesystem();
$fs->removeDirectory($path);
} elseif (is_file($path)) {
unlink($path);
}
self::assertInstanceOf('UnexpectedValueException', $e, $e->getMessage());
self::assertStringContainsString('could not be saved to', $e->getMessage());
}
}
public function testDownloadWithCustomCacheKey(): void
{
$path = self::getUniqueTmpDirectory();
$package = self::getPackage();
$package->setDistUrl('url');
$rootPackage = self::getRootPackage();
$config = $this->getConfig([
'vendor-dir' => $path.'/vendor',
'bin-dir' => $path.'/vendor/bin',
]);
$composer = new PartialComposer;
$composer->setPackage($rootPackage);
$composer->setConfig($config);
$expectedUrl = 'url';
$customCacheKey = 'xyzzy';
$expectedCacheKey = 'dummy/pkg/'.hash('sha1', $customCacheKey).'.';
$dispatcher = new EventDispatcher(
$composer,
$this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
$this->getProcessExecutorMock()
);
$dispatcher->addListener(PluginEvents::PRE_FILE_DOWNLOAD, static function (PreFileDownloadEvent $event) use ($customCacheKey): void {
$event->setCustomCacheKey($customCacheKey);
});
$cacheMock = $this->getMockBuilder('Composer\Cache')
->disableOriginalConstructor()
->getMock();
$cacheMock
->expects($this->any())
->method('copyTo')
->will($this->returnCallback(static function ($cacheKey) use ($expectedCacheKey): bool {
self::assertEquals($expectedCacheKey, $cacheKey, 'Failed assertion on $cacheKey argument of Cache::copyTo method:');
return false;
}));
$cacheMock
->expects($this->any())
->method('copyFrom')
->will($this->returnCallback(static function ($cacheKey) use ($expectedCacheKey): bool {
self::assertEquals($expectedCacheKey, $cacheKey, 'Failed assertion on $cacheKey argument of Cache::copyFrom method:');
return false;
}));
$httpDownloaderMock = $this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock();
$httpDownloaderMock
->expects($this->any())
->method('addCopy')
->will($this->returnCallback(static function ($url) use ($expectedUrl) {
self::assertEquals($expectedUrl, $url, 'Failed assertion on $url argument of HttpDownloader::addCopy method:');
return \React\Promise\resolve(
new Response(['url' => 'http://example.org/'], 200, [], 'file~')
);
}));
$downloader = $this->getDownloader(null, $config, $dispatcher, $cacheMock, $httpDownloaderMock);
try {
$loop = new Loop($this->httpDownloader);
$promise = $downloader->download($package, $path);
$loop->wait([$promise]);
$this->fail('Download was expected to throw');
} catch (\Exception $e) {
if (is_dir($path)) {
$fs = new Filesystem();
$fs->removeDirectory($path);
} elseif (is_file($path)) {
unlink($path);
}
self::assertInstanceOf('UnexpectedValueException', $e, $e->getMessage());
self::assertStringContainsString('could not be saved to', $e->getMessage());
}
}
public function testCacheGarbageCollectionIsCalled(): void
{
$expectedTtl = '99999999';
$config = $this->getConfig([
'cache-files-ttl' => $expectedTtl,
'cache-files-maxsize' => '500M',
]);
$cacheMock = $this->getMockBuilder('Composer\Cache')
->disableOriginalConstructor()
->getMock();
$cacheMock
->expects($this->any())
->method('gcIsNecessary')
->will($this->returnValue(true));
$cacheMock
->expects($this->once())
->method('gc')
->with($expectedTtl, $this->anything());
$downloader = $this->getDownloader(null, $config, null, $cacheMock, null, null);
}
public function testDownloadFileWithInvalidChecksum(): void
{
$package = self::getPackage();
$package->setDistUrl($distUrl = 'http://example.com/script.js');
$package->setDistSha1Checksum('invalid');
$filesystem = $this->getMockBuilder('Composer\Util\Filesystem')->getMock();
$path = self::getUniqueTmpDirectory();
$config = $this->getConfig(['vendor-dir' => $path.'/vendor']);
$downloader = $this->getDownloader(null, $config, null, null, null, $filesystem);
// make sure the file expected to be downloaded is on disk already
$method = new \ReflectionMethod($downloader, 'getFileName');
(\PHP_VERSION_ID < 80100) and $method->setAccessible(true);
$dlFile = $method->invoke($downloader, $package, $path);
mkdir(dirname($dlFile), 0777, true);
touch($dlFile);
try {
$loop = new Loop($this->httpDownloader);
$promise = $downloader->download($package, $path);
$loop->wait([$promise]);
$this->fail('Download was expected to throw');
} catch (\Exception $e) {
if (is_dir($path)) {
$fs = new Filesystem();
$fs->removeDirectory($path);
} elseif (is_file($path)) {
unlink($path);
}
self::assertInstanceOf('UnexpectedValueException', $e, $e->getMessage());
self::assertStringContainsString('checksum verification', $e->getMessage());
}
}
public function testDowngradeShowsAppropriateMessage(): void
{
$oldPackage = self::getPackage('dummy/pkg', '1.2.0');
$newPackage = self::getPackage('dummy/pkg', '1.0.0');
$newPackage->setDistUrl($distUrl = 'http://example.com/script.js');
$ioMock = $this->getIOMock();
$ioMock->expects([
['text' => '{Downloading .*}', 'regex' => true],
['text' => '{Downgrading .*}', 'regex' => true],
]);
$path = self::getUniqueTmpDirectory();
$config = $this->getConfig(['vendor-dir' => $path.'/vendor']);
$filesystem = $this->getMockBuilder('Composer\Util\Filesystem')->getMock();
$filesystem->expects($this->once())
->method('removeDirectoryAsync')
->will($this->returnValue(\React\Promise\resolve(true)));
$filesystem->expects($this->any())
->method('normalizePath')
->will(self::returnArgument(0));
$downloader = $this->getDownloader($ioMock, $config, null, null, null, $filesystem);
// make sure the file expected to be downloaded is on disk already
$method = new \ReflectionMethod($downloader, 'getFileName');
(\PHP_VERSION_ID < 80100) and $method->setAccessible(true);
$dlFile = $method->invoke($downloader, $newPackage, $path);
mkdir(dirname($dlFile), 0777, true);
touch($dlFile);
$loop = new Loop($this->httpDownloader);
$promise = $downloader->download($newPackage, $path, $oldPackage);
$loop->wait([$promise]);
$downloader->update($oldPackage, $newPackage, $path);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Downloader/DownloadManagerTest.php | tests/Composer/Test/Downloader/DownloadManagerTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Downloader;
use Composer\Downloader\DownloadManager;
use Composer\Package\PackageInterface;
use Composer\Test\TestCase;
class DownloadManagerTest extends TestCase
{
/** @var \Composer\Util\Filesystem&\PHPUnit\Framework\MockObject\MockObject */
protected $filesystem;
/** @var \Composer\IO\IOInterface&\PHPUnit\Framework\MockObject\MockObject */
protected $io;
public function setUp(): void
{
$this->filesystem = $this->getMockBuilder('Composer\Util\Filesystem')->getMock();
$this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
}
public function testSetGetDownloader(): void
{
$downloader = $this->createDownloaderMock();
$manager = new DownloadManager($this->io, false, $this->filesystem);
$manager->setDownloader('test', $downloader);
self::assertSame($downloader, $manager->getDownloader('test'));
self::expectException('InvalidArgumentException');
$manager->getDownloader('unregistered');
}
public function testGetDownloaderForIncorrectlyInstalledPackage(): void
{
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getInstallationSource')
->will($this->returnValue(null));
$manager = new DownloadManager($this->io, false, $this->filesystem);
self::expectException('InvalidArgumentException');
$manager->getDownloaderForPackage($package);
}
public function testGetDownloaderForCorrectlyInstalledDistPackage(): void
{
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getInstallationSource')
->will($this->returnValue('dist'));
$package
->expects($this->once())
->method('getDistType')
->will($this->returnValue('pear'));
$downloader = $this->createDownloaderMock();
$downloader
->expects($this->once())
->method('getInstallationSource')
->will($this->returnValue('dist'));
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs([$this->io, false, $this->filesystem])
->onlyMethods(['getDownloader'])
->getMock();
$manager
->expects($this->once())
->method('getDownloader')
->with('pear')
->will($this->returnValue($downloader));
self::assertSame($downloader, $manager->getDownloaderForPackage($package));
}
public function testGetDownloaderForIncorrectlyInstalledDistPackage(): void
{
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getInstallationSource')
->will($this->returnValue('dist'));
$package
->expects($this->once())
->method('getDistType')
->will($this->returnValue('git'));
$downloader = $this->createDownloaderMock();
$downloader
->expects($this->exactly(2))
->method('getInstallationSource')
->will($this->returnValue('source'));
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs([$this->io, false, $this->filesystem])
->onlyMethods(['getDownloader'])
->getMock();
$manager
->expects($this->once())
->method('getDownloader')
->with('git')
->will($this->returnValue($downloader));
self::expectException('LogicException');
$manager->getDownloaderForPackage($package);
}
public function testGetDownloaderForCorrectlyInstalledSourcePackage(): void
{
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getInstallationSource')
->will($this->returnValue('source'));
$package
->expects($this->once())
->method('getSourceType')
->will($this->returnValue('git'));
$downloader = $this->createDownloaderMock();
$downloader
->expects($this->once())
->method('getInstallationSource')
->will($this->returnValue('source'));
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs([$this->io, false, $this->filesystem])
->onlyMethods(['getDownloader'])
->getMock();
$manager
->expects($this->once())
->method('getDownloader')
->with('git')
->will($this->returnValue($downloader));
self::assertSame($downloader, $manager->getDownloaderForPackage($package));
}
public function testGetDownloaderForIncorrectlyInstalledSourcePackage(): void
{
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getInstallationSource')
->will($this->returnValue('source'));
$package
->expects($this->once())
->method('getSourceType')
->will($this->returnValue('pear'));
$downloader = $this->createDownloaderMock();
$downloader
->expects($this->exactly(2))
->method('getInstallationSource')
->will($this->returnValue('dist'));
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs([$this->io, false, $this->filesystem])
->onlyMethods(['getDownloader'])
->getMock();
$manager
->expects($this->once())
->method('getDownloader')
->with('pear')
->will($this->returnValue($downloader));
self::expectException('LogicException');
$manager->getDownloaderForPackage($package);
}
public function testGetDownloaderForMetapackage(): void
{
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getType')
->will($this->returnValue('metapackage'));
$manager = new DownloadManager($this->io, false, $this->filesystem);
self::assertNull($manager->getDownloaderForPackage($package));
}
public function testFullPackageDownload(): void
{
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getSourceType')
->will($this->returnValue('git'));
$package
->expects($this->once())
->method('getDistType')
->will($this->returnValue('pear'));
$package
->expects($this->once())
->method('setInstallationSource')
->with('dist');
$downloader = $this->createDownloaderMock();
$downloader
->expects($this->once())
->method('download')
->with($package, 'target_dir')
->will($this->returnValue(\React\Promise\resolve(null)));
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs([$this->io, false, $this->filesystem])
->onlyMethods(['getDownloaderForPackage'])
->getMock();
$manager
->expects($this->once())
->method('getDownloaderForPackage')
->with($package)
->will($this->returnValue($downloader));
$manager->download($package, 'target_dir');
}
public function testFullPackageDownloadFailover(): void
{
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getSourceType')
->will($this->returnValue('git'));
$package
->expects($this->once())
->method('getDistType')
->will($this->returnValue('pear'));
$package
->expects($this->any())
->method('getPrettyString')
->will($this->returnValue('prettyPackage'));
$package
->expects($this->exactly(2))
->method('setInstallationSource')
->willReturnCallback(static function ($type) {
static $series = [
'dist',
'source',
];
self::assertSame(array_shift($series), $type);
});
$downloaderFail = $this->createDownloaderMock();
$downloaderFail
->expects($this->once())
->method('download')
->with($package, 'target_dir')
->will($this->throwException(new \RuntimeException("Foo")));
$downloaderSuccess = $this->createDownloaderMock();
$downloaderSuccess
->expects($this->once())
->method('download')
->with($package, 'target_dir')
->will($this->returnValue(\React\Promise\resolve(null)));
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs([$this->io, false, $this->filesystem])
->onlyMethods(['getDownloaderForPackage'])
->getMock();
$manager
->expects($this->exactly(2))
->method('getDownloaderForPackage')
->with($package)
->willReturnOnConsecutiveCalls(
$downloaderFail,
$downloaderSuccess
);
$manager->download($package, 'target_dir');
}
public function testBadPackageDownload(): void
{
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getSourceType')
->will($this->returnValue(null));
$package
->expects($this->once())
->method('getDistType')
->will($this->returnValue(null));
$manager = new DownloadManager($this->io, false, $this->filesystem);
self::expectException('InvalidArgumentException');
$manager->download($package, 'target_dir');
}
public function testDistOnlyPackageDownload(): void
{
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getSourceType')
->will($this->returnValue(null));
$package
->expects($this->once())
->method('getDistType')
->will($this->returnValue('pear'));
$package
->expects($this->once())
->method('setInstallationSource')
->with('dist');
$downloader = $this->createDownloaderMock();
$downloader
->expects($this->once())
->method('download')
->with($package, 'target_dir')
->will($this->returnValue(\React\Promise\resolve(null)));
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs([$this->io, false, $this->filesystem])
->onlyMethods(['getDownloaderForPackage'])
->getMock();
$manager
->expects($this->once())
->method('getDownloaderForPackage')
->with($package)
->will($this->returnValue($downloader));
$manager->download($package, 'target_dir');
}
public function testSourceOnlyPackageDownload(): void
{
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getSourceType')
->will($this->returnValue('git'));
$package
->expects($this->once())
->method('getDistType')
->will($this->returnValue(null));
$package
->expects($this->once())
->method('setInstallationSource')
->with('source');
$downloader = $this->createDownloaderMock();
$downloader
->expects($this->once())
->method('download')
->with($package, 'target_dir')
->will($this->returnValue(\React\Promise\resolve(null)));
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs([$this->io, false, $this->filesystem])
->onlyMethods(['getDownloaderForPackage'])
->getMock();
$manager
->expects($this->once())
->method('getDownloaderForPackage')
->with($package)
->will($this->returnValue($downloader));
$manager->download($package, 'target_dir');
}
public function testMetapackagePackageDownload(): void
{
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getSourceType')
->will($this->returnValue('git'));
$package
->expects($this->once())
->method('getDistType')
->will($this->returnValue(null));
$package
->expects($this->once())
->method('setInstallationSource')
->with('source');
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs([$this->io, false, $this->filesystem])
->onlyMethods(['getDownloaderForPackage'])
->getMock();
$manager
->expects($this->once())
->method('getDownloaderForPackage')
->with($package)
->will($this->returnValue(null)); // There is no downloader for Metapackages.
$manager->download($package, 'target_dir');
}
public function testFullPackageDownloadWithSourcePreferred(): void
{
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getSourceType')
->will($this->returnValue('git'));
$package
->expects($this->once())
->method('getDistType')
->will($this->returnValue('pear'));
$package
->expects($this->once())
->method('setInstallationSource')
->with('source');
$downloader = $this->createDownloaderMock();
$downloader
->expects($this->once())
->method('download')
->with($package, 'target_dir')
->will($this->returnValue(\React\Promise\resolve(null)));
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs([$this->io, false, $this->filesystem])
->onlyMethods(['getDownloaderForPackage'])
->getMock();
$manager
->expects($this->once())
->method('getDownloaderForPackage')
->with($package)
->will($this->returnValue($downloader));
$manager->setPreferSource(true);
$manager->download($package, 'target_dir');
}
public function testDistOnlyPackageDownloadWithSourcePreferred(): void
{
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getSourceType')
->will($this->returnValue(null));
$package
->expects($this->once())
->method('getDistType')
->will($this->returnValue('pear'));
$package
->expects($this->once())
->method('setInstallationSource')
->with('dist');
$downloader = $this->createDownloaderMock();
$downloader
->expects($this->once())
->method('download')
->with($package, 'target_dir')
->will($this->returnValue(\React\Promise\resolve(null)));
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs([$this->io, false, $this->filesystem])
->onlyMethods(['getDownloaderForPackage'])
->getMock();
$manager
->expects($this->once())
->method('getDownloaderForPackage')
->with($package)
->will($this->returnValue($downloader));
$manager->setPreferSource(true);
$manager->download($package, 'target_dir');
}
public function testSourceOnlyPackageDownloadWithSourcePreferred(): void
{
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getSourceType')
->will($this->returnValue('git'));
$package
->expects($this->once())
->method('getDistType')
->will($this->returnValue(null));
$package
->expects($this->once())
->method('setInstallationSource')
->with('source');
$downloader = $this->createDownloaderMock();
$downloader
->expects($this->once())
->method('download')
->with($package, 'target_dir')
->will($this->returnValue(\React\Promise\resolve(null)));
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs([$this->io, false, $this->filesystem])
->onlyMethods(['getDownloaderForPackage'])
->getMock();
$manager
->expects($this->once())
->method('getDownloaderForPackage')
->with($package)
->will($this->returnValue($downloader));
$manager->setPreferSource(true);
$manager->download($package, 'target_dir');
}
public function testBadPackageDownloadWithSourcePreferred(): void
{
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getSourceType')
->will($this->returnValue(null));
$package
->expects($this->once())
->method('getDistType')
->will($this->returnValue(null));
$manager = new DownloadManager($this->io, false, $this->filesystem);
$manager->setPreferSource(true);
self::expectException('InvalidArgumentException');
$manager->download($package, 'target_dir');
}
public function testUpdateDistWithEqualTypes(): void
{
$initial = $this->createPackageMock();
$initial
->expects($this->once())
->method('getInstallationSource')
->will($this->returnValue('dist'));
$initial
->expects($this->once())
->method('getDistType')
->will($this->returnValue('zip'));
$target = $this->createPackageMock();
$target
->expects($this->once())
->method('getInstallationSource')
->will($this->returnValue('dist'));
$target
->expects($this->once())
->method('getDistType')
->will($this->returnValue('zip'));
$zipDownloader = $this->createDownloaderMock();
$zipDownloader
->expects($this->once())
->method('update')
->with($initial, $target, 'vendor/bundles/FOS/UserBundle')
->will($this->returnValue(\React\Promise\resolve(null)));
$zipDownloader
->expects($this->any())
->method('getInstallationSource')
->will($this->returnValue('dist'));
$manager = new DownloadManager($this->io, false, $this->filesystem);
$manager->setDownloader('zip', $zipDownloader);
$manager->update($initial, $target, 'vendor/bundles/FOS/UserBundle');
}
public function testUpdateDistWithNotEqualTypes(): void
{
$initial = $this->createPackageMock();
$initial
->expects($this->once())
->method('getInstallationSource')
->will($this->returnValue('dist'));
$initial
->expects($this->once())
->method('getDistType')
->will($this->returnValue('xz'));
$target = $this->createPackageMock();
$target
->expects($this->any())
->method('getInstallationSource')
->will($this->returnValue('dist'));
$target
->expects($this->any())
->method('getDistType')
->will($this->returnValue('zip'));
$xzDownloader = $this->createDownloaderMock();
$xzDownloader
->expects($this->once())
->method('remove')
->with($initial, 'vendor/bundles/FOS/UserBundle')
->will($this->returnValue(\React\Promise\resolve(null)));
$xzDownloader
->expects($this->any())
->method('getInstallationSource')
->will($this->returnValue('dist'));
$zipDownloader = $this->createDownloaderMock();
$zipDownloader
->expects($this->once())
->method('install')
->with($target, 'vendor/bundles/FOS/UserBundle')
->will($this->returnValue(\React\Promise\resolve(null)));
$zipDownloader
->expects($this->any())
->method('getInstallationSource')
->will($this->returnValue('dist'));
$manager = new DownloadManager($this->io, false, $this->filesystem);
$manager->setDownloader('xz', $xzDownloader);
$manager->setDownloader('zip', $zipDownloader);
$manager->update($initial, $target, 'vendor/bundles/FOS/UserBundle');
}
/**
* @dataProvider updatesProvider
* @param string[] $targetAvailable
* @param string[] $expected
*/
public function testGetAvailableSourcesUpdateSticksToSameSource(?string $prevPkgSource, ?bool $prevPkgIsDev, array $targetAvailable, bool $targetIsDev, array $expected): void
{
$initial = null;
if ($prevPkgSource) {
$initial = $this->getMockBuilder(PackageInterface::class)->getMock();
$initial->expects($this->atLeastOnce())
->method('getInstallationSource')
->willReturn($prevPkgSource);
$initial->expects($this->any())
->method('isDev')
->willReturn($prevPkgIsDev);
}
$target = $this->getMockBuilder(PackageInterface::class)->getMock();
$target->expects($this->atLeastOnce())
->method('getSourceType')
->willReturn(in_array('source', $targetAvailable, true) ? 'git' : null);
$target->expects($this->atLeastOnce())
->method('getDistType')
->willReturn(in_array('dist', $targetAvailable, true) ? 'zip' : null);
$target->expects($this->any())
->method('isDev')
->willReturn($targetIsDev);
$manager = new DownloadManager($this->io, false, $this->filesystem);
$method = new \ReflectionMethod($manager, 'getAvailableSources');
(\PHP_VERSION_ID < 80100) and $method->setAccessible(true);
self::assertEquals($expected, $method->invoke($manager, $target, $initial ?? null));
}
public static function updatesProvider(): array
{
return [
// prevPkg source, prevPkg isDev, pkg available, pkg isDev, expected
// updates keep previous source as preference
['source', false, ['source', 'dist'], false, ['source', 'dist']],
['dist', false, ['source', 'dist'], false, ['dist', 'source']],
// updates do not keep previous source if target package does not have it
['source', false, ['dist'], false, ['dist']],
['dist', false, ['source'], false, ['source']],
// updates do not keep previous source if target is dev and prev wasn't dev and installed from dist
['source', false, ['source', 'dist'], true, ['source', 'dist']],
['dist', false, ['source', 'dist'], true, ['source', 'dist']],
// install picks the right default
[null, null, ['source', 'dist'], true, ['source', 'dist']],
[null, null, ['dist'], true, ['dist']],
[null, null, ['source'], true, ['source']],
[null, null, ['source', 'dist'], false, ['dist', 'source']],
[null, null, ['dist'], false, ['dist']],
[null, null, ['source'], false, ['source']],
];
}
public function testUpdateMetapackage(): void
{
$initial = $this->createPackageMock();
$target = $this->createPackageMock();
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs([$this->io, false, $this->filesystem])
->onlyMethods(['getDownloaderForPackage'])
->getMock();
$manager
->expects($this->exactly(2))
->method('getDownloaderForPackage')
->with($initial)
->will($this->returnValue(null)); // There is no downloader for metapackages.
$manager->update($initial, $target, 'vendor/pkg');
}
public function testRemove(): void
{
$package = $this->createPackageMock();
$pearDownloader = $this->createDownloaderMock();
$pearDownloader
->expects($this->once())
->method('remove')
->with($package, 'vendor/bundles/FOS/UserBundle');
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs([$this->io, false, $this->filesystem])
->onlyMethods(['getDownloaderForPackage'])
->getMock();
$manager
->expects($this->once())
->method('getDownloaderForPackage')
->with($package)
->will($this->returnValue($pearDownloader));
$manager->remove($package, 'vendor/bundles/FOS/UserBundle');
}
public function testMetapackageRemove(): void
{
$package = $this->createPackageMock();
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs([$this->io, false, $this->filesystem])
->onlyMethods(['getDownloaderForPackage'])
->getMock();
$manager
->expects($this->once())
->method('getDownloaderForPackage')
->with($package)
->will($this->returnValue(null)); // There is no downloader for metapackages.
$manager->remove($package, 'vendor/bundles/FOS/UserBundle');
}
/**
* @covers Composer\Downloader\DownloadManager::resolvePackageInstallPreference
*/
public function testInstallPreferenceWithoutPreferenceDev(): void
{
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getSourceType')
->will($this->returnValue('git'));
$package
->expects($this->once())
->method('getDistType')
->will($this->returnValue('pear'));
$package
->expects($this->once())
->method('isDev')
->will($this->returnValue(true));
$package
->expects($this->once())
->method('setInstallationSource')
->with('source');
$downloader = $this->createDownloaderMock();
$downloader
->expects($this->once())
->method('download')
->with($package, 'target_dir')
->will($this->returnValue(\React\Promise\resolve(null)));
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs([$this->io, false, $this->filesystem])
->onlyMethods(['getDownloaderForPackage'])
->getMock();
$manager
->expects($this->once())
->method('getDownloaderForPackage')
->with($package)
->will($this->returnValue($downloader));
$manager->download($package, 'target_dir');
}
/**
* @covers Composer\Downloader\DownloadManager::resolvePackageInstallPreference
*/
public function testInstallPreferenceWithoutPreferenceNoDev(): void
{
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getSourceType')
->will($this->returnValue('git'));
$package
->expects($this->once())
->method('getDistType')
->will($this->returnValue('pear'));
$package
->expects($this->once())
->method('isDev')
->will($this->returnValue(false));
$package
->expects($this->once())
->method('setInstallationSource')
->with('dist');
$downloader = $this->createDownloaderMock();
$downloader
->expects($this->once())
->method('download')
->with($package, 'target_dir')
->will($this->returnValue(\React\Promise\resolve(null)));
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs([$this->io, false, $this->filesystem])
->onlyMethods(['getDownloaderForPackage'])
->getMock();
$manager
->expects($this->once())
->method('getDownloaderForPackage')
->with($package)
->will($this->returnValue($downloader));
$manager->download($package, 'target_dir');
}
/**
* @covers Composer\Downloader\DownloadManager::resolvePackageInstallPreference
*/
public function testInstallPreferenceWithoutMatchDev(): void
{
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getSourceType')
->will($this->returnValue('git'));
$package
->expects($this->once())
->method('getDistType')
->will($this->returnValue('pear'));
$package
->expects($this->once())
->method('isDev')
->will($this->returnValue(true));
$package
->expects($this->once())
->method('getName')
->will($this->returnValue('bar/package'));
$package
->expects($this->once())
->method('setInstallationSource')
->with('source');
$downloader = $this->createDownloaderMock();
$downloader
->expects($this->once())
->method('download')
->with($package, 'target_dir')
->will($this->returnValue(\React\Promise\resolve(null)));
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs([$this->io, false, $this->filesystem])
->onlyMethods(['getDownloaderForPackage'])
->getMock();
$manager
->expects($this->once())
->method('getDownloaderForPackage')
->with($package)
->will($this->returnValue($downloader));
$manager->setPreferences(['foo/*' => 'source']);
$manager->download($package, 'target_dir');
}
/**
* @covers Composer\Downloader\DownloadManager::resolvePackageInstallPreference
*/
public function testInstallPreferenceWithoutMatchNoDev(): void
{
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getSourceType')
->will($this->returnValue('git'));
$package
->expects($this->once())
->method('getDistType')
->will($this->returnValue('pear'));
$package
->expects($this->once())
->method('isDev')
->will($this->returnValue(false));
$package
->expects($this->once())
->method('getName')
->will($this->returnValue('bar/package'));
$package
->expects($this->once())
->method('setInstallationSource')
->with('dist');
$downloader = $this->createDownloaderMock();
$downloader
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | true |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Downloader/ZipDownloaderTest.php | tests/Composer/Test/Downloader/ZipDownloaderTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Downloader;
use React\Promise\PromiseInterface;
use Composer\Downloader\ZipDownloader;
use Composer\Package\PackageInterface;
use Composer\Test\TestCase;
use Composer\Util\Filesystem;
use Composer\Util\HttpDownloader;
use Composer\Util\Loop;
class ZipDownloaderTest extends TestCase
{
/** @var string */
private $testDir;
/** @var HttpDownloader */
private $httpDownloader;
/** @var \Composer\IO\IOInterface&\PHPUnit\Framework\MockObject\MockObject */
private $io;
/** @var \Composer\Config&\PHPUnit\Framework\MockObject\MockObject */
private $config;
/** @var PackageInterface&\PHPUnit\Framework\MockObject\MockObject */
private $package;
/** @var string */
private $filename;
public function setUp(): void
{
$this->testDir = self::getUniqueTmpDirectory();
$this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$this->config = $this->getMockBuilder('Composer\Config')->getMock();
$dlConfig = $this->getMockBuilder('Composer\Config')->getMock();
$this->httpDownloader = new HttpDownloader($this->io, $dlConfig);
$this->package = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$this->package->expects($this->any())
->method('getName')
->will($this->returnValue('test/pkg'));
$this->filename = $this->testDir.'/composer-test.zip';
file_put_contents($this->filename, 'zip');
}
protected function tearDown(): void
{
parent::tearDown();
$fs = new Filesystem;
$fs->removeDirectory($this->testDir);
$this->setPrivateProperty('hasZipArchive', null);
}
/**
* @param mixed $value
* @param ?MockedZipDownloader $obj
*/
public function setPrivateProperty(string $name, $value, $obj = null): void
{
$reflectionClass = new \ReflectionClass('Composer\Downloader\ZipDownloader');
$reflectedProperty = $reflectionClass->getProperty($name);
(\PHP_VERSION_ID < 80100) and $reflectedProperty->setAccessible(true);
$reflectedProperty->setValue($obj, $value);
}
public function testErrorMessages(): void
{
if (!class_exists('ZipArchive')) {
$this->markTestSkipped('zip extension missing');
}
$this->config->expects($this->any())
->method('get')
->with('vendor-dir')
->will($this->returnValue($this->testDir));
$this->package->expects($this->any())
->method('getDistUrl')
->will($this->returnValue($distUrl = 'file://'.__FILE__))
;
$this->package->expects($this->any())
->method('getDistUrls')
->will($this->returnValue([$distUrl]))
;
$this->package->expects($this->atLeastOnce())
->method('getTransportOptions')
->will($this->returnValue([]))
;
$downloader = new ZipDownloader($this->io, $this->config, $this->httpDownloader);
try {
$loop = new Loop($this->httpDownloader);
$promise = $downloader->download($this->package, $path = sys_get_temp_dir().'/composer-zip-test');
$loop->wait([$promise]);
$downloader->install($this->package, $path);
$this->fail('Download of invalid zip files should throw an exception');
} catch (\Exception $e) {
self::assertStringContainsString('is not a zip archive', $e->getMessage());
}
}
public function testZipArchiveOnlyFailed(): void
{
self::expectException('RuntimeException');
self::expectExceptionMessage('There was an error extracting the ZIP file');
if (!class_exists('ZipArchive')) {
$this->markTestSkipped('zip extension missing');
}
$this->setPrivateProperty('hasZipArchive', true);
$downloader = new MockedZipDownloader($this->io, $this->config, $this->httpDownloader);
$zipArchive = $this->getMockBuilder('ZipArchive')->getMock();
$zipArchive->expects($this->once())
->method('open')
->will($this->returnValue(true));
$zipArchive->expects($this->once())
->method('extractTo')
->will($this->returnValue(false));
$this->setPrivateProperty('zipArchiveObject', $zipArchive, $downloader);
$promise = $downloader->extract($this->package, $this->filename, 'vendor/dir');
$this->wait($promise);
}
public function testZipArchiveExtractOnlyFailed(): void
{
self::expectException('RuntimeException');
self::expectExceptionMessage('The archive for "test/pkg" may contain identical file names with different capitalization (which fails on case insensitive filesystems): Not a directory');
if (!class_exists('ZipArchive')) {
$this->markTestSkipped('zip extension missing');
}
$this->setPrivateProperty('hasZipArchive', true);
$downloader = new MockedZipDownloader($this->io, $this->config, $this->httpDownloader);
$zipArchive = $this->getMockBuilder('ZipArchive')->getMock();
$zipArchive->expects($this->once())
->method('open')
->will($this->returnValue(true));
$zipArchive->expects($this->once())
->method('extractTo')
->will($this->throwException(new \ErrorException('Not a directory')));
$this->setPrivateProperty('zipArchiveObject', $zipArchive, $downloader);
$promise = $downloader->extract($this->package, $this->filename, 'vendor/dir');
$this->wait($promise);
}
public function testZipArchiveOnlyGood(): void
{
if (!class_exists('ZipArchive')) {
$this->markTestSkipped('zip extension missing');
}
$this->setPrivateProperty('hasZipArchive', true);
$downloader = new MockedZipDownloader($this->io, $this->config, $this->httpDownloader);
$zipArchive = $this->getMockBuilder('ZipArchive')->getMock();
$zipArchive->expects($this->once())
->method('open')
->will($this->returnValue(true));
$zipArchive->expects($this->once())
->method('extractTo')
->will($this->returnValue(true));
$zipArchive->expects($this->once())
->method('count')
->will($this->returnValue(0));
$this->setPrivateProperty('zipArchiveObject', $zipArchive, $downloader);
$promise = $downloader->extract($this->package, $this->filename, 'vendor/dir');
$this->wait($promise);
}
public function testSystemUnzipOnlyFailed(): void
{
self::expectException('Exception');
self::expectExceptionMessage('Failed to extract test/pkg: (1) unzip');
$this->setPrivateProperty('isWindows', false);
$this->setPrivateProperty('hasZipArchive', false);
$this->setPrivateProperty('unzipCommands', [['unzip', 'unzip -qq %s -d %s']]);
$procMock = $this->getMockBuilder('Symfony\Component\Process\Process')->disableOriginalConstructor()->getMock();
$procMock->expects($this->any())
->method('getExitCode')
->will($this->returnValue(1));
$procMock->expects($this->any())
->method('isSuccessful')
->will($this->returnValue(false));
$procMock->expects($this->any())
->method('getErrorOutput')
->will($this->returnValue('output'));
$processExecutor = $this->getMockBuilder('Composer\Util\ProcessExecutor')->getMock();
$processExecutor->expects($this->once())
->method('executeAsync')
->will($this->returnValue(\React\Promise\resolve($procMock)));
$downloader = new MockedZipDownloader($this->io, $this->config, $this->httpDownloader, null, null, null, $processExecutor);
$promise = $downloader->extract($this->package, $this->filename, 'vendor/dir');
$this->wait($promise);
}
public function testSystemUnzipOnlyGood(): void
{
$this->setPrivateProperty('isWindows', false);
$this->setPrivateProperty('hasZipArchive', false);
$this->setPrivateProperty('unzipCommands', [['unzip', 'unzip -qq %s -d %s']]);
$procMock = $this->getMockBuilder('Symfony\Component\Process\Process')->disableOriginalConstructor()->getMock();
$procMock->expects($this->any())
->method('getExitCode')
->will($this->returnValue(0));
$procMock->expects($this->any())
->method('isSuccessful')
->will($this->returnValue(true));
$procMock->expects($this->any())
->method('getErrorOutput')
->will($this->returnValue('output'));
$processExecutor = $this->getMockBuilder('Composer\Util\ProcessExecutor')->getMock();
$processExecutor->expects($this->once())
->method('executeAsync')
->will($this->returnValue(\React\Promise\resolve($procMock)));
$downloader = new MockedZipDownloader($this->io, $this->config, $this->httpDownloader, null, null, null, $processExecutor);
$promise = $downloader->extract($this->package, $this->filename, 'vendor/dir');
$this->wait($promise);
}
public function testNonWindowsFallbackGood(): void
{
if (!class_exists('ZipArchive')) {
$this->markTestSkipped('zip extension missing');
}
$this->setPrivateProperty('isWindows', false);
$this->setPrivateProperty('hasZipArchive', true);
$procMock = $this->getMockBuilder('Symfony\Component\Process\Process')->disableOriginalConstructor()->getMock();
$procMock->expects($this->any())
->method('getExitCode')
->will($this->returnValue(1));
$procMock->expects($this->any())
->method('isSuccessful')
->will($this->returnValue(false));
$procMock->expects($this->any())
->method('getErrorOutput')
->will($this->returnValue('output'));
$processExecutor = $this->getMockBuilder('Composer\Util\ProcessExecutor')->getMock();
$processExecutor->expects($this->once())
->method('executeAsync')
->will($this->returnValue(\React\Promise\resolve($procMock)));
$zipArchive = $this->getMockBuilder('ZipArchive')->getMock();
$zipArchive->expects($this->once())
->method('open')
->will($this->returnValue(true));
$zipArchive->expects($this->once())
->method('extractTo')
->will($this->returnValue(true));
$zipArchive->expects($this->once())
->method('count')
->will($this->returnValue(0));
$downloader = new MockedZipDownloader($this->io, $this->config, $this->httpDownloader, null, null, null, $processExecutor);
$this->setPrivateProperty('zipArchiveObject', $zipArchive, $downloader);
$promise = $downloader->extract($this->package, $this->filename, 'vendor/dir');
$this->wait($promise);
}
public function testNonWindowsFallbackFailed(): void
{
self::expectException('Exception');
self::expectExceptionMessage('There was an error extracting the ZIP file');
if (!class_exists('ZipArchive')) {
$this->markTestSkipped('zip extension missing');
}
$this->setPrivateProperty('isWindows', false);
$this->setPrivateProperty('hasZipArchive', true);
$procMock = $this->getMockBuilder('Symfony\Component\Process\Process')->disableOriginalConstructor()->getMock();
$procMock->expects($this->any())
->method('getExitCode')
->will($this->returnValue(1));
$procMock->expects($this->any())
->method('isSuccessful')
->will($this->returnValue(false));
$procMock->expects($this->any())
->method('getErrorOutput')
->will($this->returnValue('output'));
$processExecutor = $this->getMockBuilder('Composer\Util\ProcessExecutor')->getMock();
$processExecutor->expects($this->once())
->method('executeAsync')
->will($this->returnValue(\React\Promise\resolve($procMock)));
$zipArchive = $this->getMockBuilder('ZipArchive')->getMock();
$zipArchive->expects($this->once())
->method('open')
->will($this->returnValue(true));
$zipArchive->expects($this->once())
->method('extractTo')
->will($this->returnValue(false));
$downloader = new MockedZipDownloader($this->io, $this->config, $this->httpDownloader, null, null, null, $processExecutor);
$this->setPrivateProperty('zipArchiveObject', $zipArchive, $downloader);
$promise = $downloader->extract($this->package, $this->filename, 'vendor/dir');
$this->wait($promise);
}
/**
* @param ?PromiseInterface<mixed> $promise
*/
private function wait($promise): void
{
if (null === $promise) {
return;
}
$e = null;
$promise->then(static function (): void {
// noop
}, static function ($ex) use (&$e): void {
$e = $ex;
});
if ($e !== null) {
throw $e;
}
}
}
class MockedZipDownloader extends ZipDownloader
{
public function download(PackageInterface $package, $path, ?PackageInterface $prevPackage = null, bool $output = true): PromiseInterface
{
return \React\Promise\resolve(null);
}
public function install(PackageInterface $package, $path, bool $output = true): PromiseInterface
{
return \React\Promise\resolve(null);
}
public function extract(PackageInterface $package, $file, $path): PromiseInterface
{
return parent::extract($package, $file, $path);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Downloader/FossilDownloaderTest.php | tests/Composer/Test/Downloader/FossilDownloaderTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Downloader;
use Composer\Downloader\FossilDownloader;
use Composer\Test\TestCase;
use Composer\Util\Filesystem;
class FossilDownloaderTest extends TestCase
{
/** @var string */
private $workingDir;
protected function setUp(): void
{
$this->workingDir = self::getUniqueTmpDirectory();
}
protected function tearDown(): void
{
parent::tearDown();
if (is_dir($this->workingDir)) {
$fs = new Filesystem;
$fs->removeDirectory($this->workingDir);
}
}
protected function getDownloaderMock(?\Composer\IO\IOInterface $io = null, ?\Composer\Config $config = null, ?\Composer\Test\Mock\ProcessExecutorMock $executor = null, ?Filesystem $filesystem = null): FossilDownloader
{
$io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$config = $config ?: $this->getConfig(['secure-http' => false]);
$executor = $executor ?: $this->getProcessExecutorMock();
$filesystem = $filesystem ?: $this->getMockBuilder('Composer\Util\Filesystem')->getMock();
return new FossilDownloader($io, $config, $executor, $filesystem);
}
public function testInstallForPackageWithoutSourceReference(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->once())
->method('getSourceReference')
->will($this->returnValue(null));
self::expectException('InvalidArgumentException');
$downloader = $this->getDownloaderMock();
$downloader->install($packageMock, $this->workingDir . '/path');
}
public function testInstall(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('trunk'));
$packageMock->expects($this->once())
->method('getSourceUrls')
->will($this->returnValue(['http://fossil.kd2.org/kd2fw/']));
$process = $this->getProcessExecutorMock();
$process->expects([
['fossil', 'clone', '--', 'http://fossil.kd2.org/kd2fw/', $this->workingDir.'.fossil'],
['fossil', 'open', '--nested', '--', $this->workingDir.'.fossil'],
['fossil', 'update', '--', 'trunk'],
], true);
$downloader = $this->getDownloaderMock(null, null, $process);
$downloader->install($packageMock, $this->workingDir);
}
public function testUpdateforPackageWithoutSourceReference(): void
{
$initialPackageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$sourcePackageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$sourcePackageMock->expects($this->once())
->method('getSourceReference')
->will($this->returnValue(null));
self::expectException('InvalidArgumentException');
$downloader = $this->getDownloaderMock();
$downloader->prepare('update', $sourcePackageMock, '/path', $initialPackageMock);
$downloader->update($initialPackageMock, $sourcePackageMock, '/path');
$downloader->cleanup('update', $sourcePackageMock, '/path', $initialPackageMock);
}
public function testUpdate(): void
{
// Ensure file exists
$file = $this->workingDir . '/.fslckout';
if (!file_exists($file)) {
touch($file);
}
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('trunk'));
$packageMock->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['http://fossil.kd2.org/kd2fw/']));
$packageMock->expects($this->any())
->method('getVersion')
->will($this->returnValue('1.0.0.0'));
$process = $this->getProcessExecutorMock();
$process->expects([
['fossil', 'changes'],
['fossil', 'pull'],
['fossil', 'up', 'trunk'],
], true);
$downloader = $this->getDownloaderMock(null, null, $process);
$downloader->prepare('update', $packageMock, $this->workingDir, $packageMock);
$downloader->update($packageMock, $packageMock, $this->workingDir);
$downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock);
}
public function testRemove(): void
{
// Ensure file exists
$file = $this->workingDir . '/.fslckout';
touch($file);
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$process = $this->getProcessExecutorMock();
$process->expects([
['fossil', 'changes'],
], true);
$filesystem = $this->getMockBuilder('Composer\Util\Filesystem')->getMock();
$filesystem->expects($this->once())
->method('removeDirectoryAsync')
->with($this->equalTo($this->workingDir))
->will($this->returnValue(\React\Promise\resolve(true)));
$downloader = $this->getDownloaderMock(null, null, $process, $filesystem);
$downloader->prepare('uninstall', $packageMock, $this->workingDir);
$downloader->remove($packageMock, $this->workingDir);
$downloader->cleanup('uninstall', $packageMock, $this->workingDir);
}
public function testGetInstallationSource(): void
{
$downloader = $this->getDownloaderMock(null);
self::assertEquals('source', $downloader->getInstallationSource());
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Downloader/ArchiveDownloaderTest.php | tests/Composer/Test/Downloader/ArchiveDownloaderTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Downloader;
use Composer\Test\TestCase;
class ArchiveDownloaderTest extends TestCase
{
/** @var \Composer\Config&\PHPUnit\Framework\MockObject\MockObject */
protected $config;
public function testGetFileName(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getDistUrl')
->will($this->returnValue('http://example.com/script.js'))
;
$downloader = $this->getArchiveDownloaderMock();
$method = new \ReflectionMethod($downloader, 'getFileName');
(\PHP_VERSION_ID < 80100) and $method->setAccessible(true);
$this->config->expects($this->any())
->method('get')
->with('vendor-dir')
->will($this->returnValue('/vendor'));
$first = $method->invoke($downloader, $packageMock, '/path');
self::assertMatchesRegularExpression('#/vendor/composer/tmp-[a-z0-9]+\.js#', $first);
self::assertSame($first, $method->invoke($downloader, $packageMock, '/path'));
}
public function testProcessUrl(): void
{
if (!extension_loaded('openssl')) {
$this->markTestSkipped('Requires openssl');
}
$downloader = $this->getArchiveDownloaderMock();
$method = new \ReflectionMethod($downloader, 'processUrl');
(\PHP_VERSION_ID < 80100) and $method->setAccessible(true);
$expected = 'https://github.com/composer/composer/zipball/master';
$url = $method->invoke($downloader, $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(), $expected);
self::assertEquals($expected, $url);
}
public function testProcessUrl2(): void
{
if (!extension_loaded('openssl')) {
$this->markTestSkipped('Requires openssl');
}
$downloader = $this->getArchiveDownloaderMock();
$method = new \ReflectionMethod($downloader, 'processUrl');
(\PHP_VERSION_ID < 80100) and $method->setAccessible(true);
$expected = 'https://github.com/composer/composer/archive/master.tar.gz';
$url = $method->invoke($downloader, $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(), $expected);
self::assertEquals($expected, $url);
}
public function testProcessUrl3(): void
{
if (!extension_loaded('openssl')) {
$this->markTestSkipped('Requires openssl');
}
$downloader = $this->getArchiveDownloaderMock();
$method = new \ReflectionMethod($downloader, 'processUrl');
(\PHP_VERSION_ID < 80100) and $method->setAccessible(true);
$expected = 'https://api.github.com/repos/composer/composer/zipball/master';
$url = $method->invoke($downloader, $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(), $expected);
self::assertEquals($expected, $url);
}
/**
* @dataProvider provideUrls
*/
public function testProcessUrlRewriteDist(string $url): void
{
if (!extension_loaded('openssl')) {
$this->markTestSkipped('Requires openssl');
}
$downloader = $this->getArchiveDownloaderMock();
$method = new \ReflectionMethod($downloader, 'processUrl');
(\PHP_VERSION_ID < 80100) and $method->setAccessible(true);
$type = strpos($url, 'tar') ? 'tar' : 'zip';
$expected = 'https://api.github.com/repos/composer/composer/'.$type.'ball/ref';
$package = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$package->expects($this->any())
->method('getDistReference')
->will($this->returnValue('ref'));
$url = $method->invoke($downloader, $package, $url);
self::assertEquals($expected, $url);
}
public static function provideUrls(): array
{
return [
['https://api.github.com/repos/composer/composer/zipball/master'],
['https://api.github.com/repos/composer/composer/tarball/master'],
['https://github.com/composer/composer/zipball/master'],
['https://www.github.com/composer/composer/tarball/master'],
['https://github.com/composer/composer/archive/master.zip'],
['https://github.com/composer/composer/archive/master.tar.gz'],
];
}
/**
* @dataProvider provideBitbucketUrls
*/
public function testProcessUrlRewriteBitbucketDist(string $url, string $extension): void
{
if (!extension_loaded('openssl')) {
$this->markTestSkipped('Requires openssl');
}
$downloader = $this->getArchiveDownloaderMock();
$method = new \ReflectionMethod($downloader, 'processUrl');
(\PHP_VERSION_ID < 80100) and $method->setAccessible(true);
$url .= '.' . $extension;
$expected = 'https://bitbucket.org/davereid/drush-virtualhost/get/ref.' . $extension;
$package = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$package->expects($this->any())
->method('getDistReference')
->will($this->returnValue('ref'));
$url = $method->invoke($downloader, $package, $url);
self::assertEquals($expected, $url);
}
public static function provideBitbucketUrls(): array
{
return [
['https://bitbucket.org/davereid/drush-virtualhost/get/77ca490c26ac818e024d1138aa8bd3677d1ef21f', 'zip'],
['https://bitbucket.org/davereid/drush-virtualhost/get/master', 'tar.gz'],
['https://bitbucket.org/davereid/drush-virtualhost/get/v1.0', 'tar.bz2'],
];
}
/**
* @return \Composer\Downloader\ArchiveDownloader&\PHPUnit\Framework\MockObject\MockObject
*/
private function getArchiveDownloaderMock()
{
return $this->getMockForAbstractClass(
'Composer\Downloader\ArchiveDownloader',
[
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
$this->config = $this->getMockBuilder('Composer\Config')->getMock(),
new \Composer\Util\HttpDownloader($io, $this->config),
]
);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Downloader/PerforceDownloaderTest.php | tests/Composer/Test/Downloader/PerforceDownloaderTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Downloader;
use Composer\Downloader\PerforceDownloader;
use Composer\Config;
use Composer\Repository\VcsRepository;
use Composer\IO\IOInterface;
use Composer\Test\TestCase;
use Composer\Factory;
/**
* @author Matt Whittom <Matt.Whittom@veteransunited.com>
*/
class PerforceDownloaderTest extends TestCase
{
/** @var Config */
protected $config;
/** @var PerforceDownloader */
protected $downloader;
/** @var IOInterface&\PHPUnit\Framework\MockObject\MockObject */
protected $io;
/** @var \Composer\Package\PackageInterface&\PHPUnit\Framework\MockObject\MockObject */
protected $package;
/** @var \Composer\Test\Mock\ProcessExecutorMock */
protected $processExecutor;
/** @var string[] */
protected $repoConfig;
/** @var VcsRepository&\PHPUnit\Framework\MockObject\MockObject */
protected $repository;
/** @var string */
protected $testPath;
protected function setUp(): void
{
$this->testPath = self::getUniqueTmpDirectory();
$this->repoConfig = $this->getRepoConfig();
$this->config = $this->getConfig();
$this->io = $this->getMockIoInterface();
$this->processExecutor = $this->getProcessExecutorMock();
$this->repository = $this->getMockRepository($this->repoConfig, $this->io, $this->config);
$this->package = $this->getMockPackageInterface($this->repository);
$this->downloader = new PerforceDownloader($this->io, $this->config, $this->processExecutor);
}
protected function getConfig(array $configOptions = [], bool $useEnvironment = false): Config
{
return parent::getConfig(array_merge(['home' => $this->testPath], $configOptions), $useEnvironment);
}
/**
* @return IOInterface&\PHPUnit\Framework\MockObject\MockObject
*/
protected function getMockIoInterface()
{
return $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
}
/**
* @return \Composer\Package\PackageInterface&\PHPUnit\Framework\MockObject\MockObject
*/
protected function getMockPackageInterface(VcsRepository $repository)
{
$package = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$package->expects($this->any())->method('getRepository')->will($this->returnValue($repository));
return $package;
}
/**
* @return string[]
*/
protected function getRepoConfig(): array
{
return ['url' => 'TEST_URL', 'p4user' => 'TEST_USER'];
}
/**
* @param string[] $repoConfig
* @return VcsRepository&\PHPUnit\Framework\MockObject\MockObject
*/
protected function getMockRepository(array $repoConfig, IOInterface $io, Config $config)
{
$repository = $this->getMockBuilder('Composer\Repository\VcsRepository')
->onlyMethods(['getRepoConfig'])
->setConstructorArgs([$repoConfig, $io, $config, Factory::createHttpDownloader($io, $config)])
->getMock();
$repository->expects($this->any())->method('getRepoConfig')->will($this->returnValue($repoConfig));
return $repository;
}
/**
* @doesNotPerformAssertions
*/
public function testInitPerforceInstantiatesANewPerforceObject(): void
{
$this->downloader->initPerforce($this->package, $this->testPath, 'SOURCE_REF');
}
public function testInitPerforceDoesNothingIfPerforceAlreadySet(): void
{
$perforce = $this->getMockBuilder('Composer\Util\Perforce')->disableOriginalConstructor()->getMock();
$this->downloader->setPerforce($perforce);
$this->repository->expects($this->never())->method('getRepoConfig');
$this->downloader->initPerforce($this->package, $this->testPath, 'SOURCE_REF');
}
/**
* @depends testInitPerforceInstantiatesANewPerforceObject
* @depends testInitPerforceDoesNothingIfPerforceAlreadySet
*/
public function testDoInstallWithTag(): void
{
//I really don't like this test but the logic of each Perforce method is tested in the Perforce class. Really I am just enforcing workflow.
$ref = 'SOURCE_REF@123';
$label = 123;
$this->package->expects($this->once())->method('getSourceReference')->will($this->returnValue($ref));
$this->io->expects($this->once())->method('writeError')->with($this->stringContains('Cloning '.$ref));
$perforceMethods = ['setStream', 'p4Login', 'writeP4ClientSpec', 'connectClient', 'syncCodeBase', 'cleanupClientSpec'];
$perforce = $this->getMockBuilder('Composer\Util\Perforce')->disableOriginalConstructor()->getMock();
$perforce->expects($this->once())->method('initializePath')->with($this->equalTo($this->testPath));
$perforce->expects($this->once())->method('setStream')->with($this->equalTo($ref));
$perforce->expects($this->once())->method('p4Login');
$perforce->expects($this->once())->method('writeP4ClientSpec');
$perforce->expects($this->once())->method('connectClient');
$perforce->expects($this->once())->method('syncCodeBase')->with($label);
$perforce->expects($this->once())->method('cleanupClientSpec');
$this->downloader->setPerforce($perforce);
$this->downloader->doInstall($this->package, $this->testPath, 'url');
}
/**
* @depends testInitPerforceInstantiatesANewPerforceObject
* @depends testInitPerforceDoesNothingIfPerforceAlreadySet
*/
public function testDoInstallWithNoTag(): void
{
$ref = 'SOURCE_REF';
$label = null;
$this->package->expects($this->once())->method('getSourceReference')->will($this->returnValue($ref));
$this->io->expects($this->once())->method('writeError')->with($this->stringContains('Cloning '.$ref));
$perforceMethods = ['setStream', 'p4Login', 'writeP4ClientSpec', 'connectClient', 'syncCodeBase', 'cleanupClientSpec'];
$perforce = $this->getMockBuilder('Composer\Util\Perforce')->disableOriginalConstructor()->getMock();
$perforce->expects($this->once())->method('initializePath')->with($this->equalTo($this->testPath));
$perforce->expects($this->once())->method('setStream')->with($this->equalTo($ref));
$perforce->expects($this->once())->method('p4Login');
$perforce->expects($this->once())->method('writeP4ClientSpec');
$perforce->expects($this->once())->method('connectClient');
$perforce->expects($this->once())->method('syncCodeBase')->with($label);
$perforce->expects($this->once())->method('cleanupClientSpec');
$this->downloader->setPerforce($perforce);
$this->downloader->doInstall($this->package, $this->testPath, 'url');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Downloader/XzDownloaderTest.php | tests/Composer/Test/Downloader/XzDownloaderTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Downloader;
use Composer\Downloader\XzDownloader;
use Composer\Test\TestCase;
use Composer\Util\Filesystem;
use Composer\Util\Platform;
use Composer\Util\Loop;
use Composer\Util\HttpDownloader;
class XzDownloaderTest extends TestCase
{
/**
* @var Filesystem
*/
private $fs;
/**
* @var string
*/
private $testDir;
public function setUp(): void
{
if (Platform::isWindows()) {
$this->markTestSkipped('Skip test on Windows');
}
if (PHP_INT_SIZE === 4) {
$this->markTestSkipped('Skip test on 32bit');
}
$this->testDir = self::getUniqueTmpDirectory();
}
protected function tearDown(): void
{
if (Platform::isWindows()) {
return;
}
parent::tearDown();
$this->fs = new Filesystem;
$this->fs->removeDirectory($this->testDir);
}
public function testErrorMessages(): void
{
$package = self::getPackage();
$package->setDistUrl($distUrl = 'file://'.__FILE__);
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$config = $this->getConfig(['vendor-dir' => $this->testDir]);
$downloader = new XzDownloader($io, $config, $httpDownloader = new HttpDownloader($io, $config), null, null, null);
try {
$loop = new Loop($httpDownloader);
$promise = $downloader->download($package, $this->testDir.'/install-path');
$loop->wait([$promise]);
$downloader->install($package, $this->testDir.'/install-path');
$this->fail('Download of invalid tarball should throw an exception');
} catch (\RuntimeException $e) {
self::assertMatchesRegularExpression('/(File format not recognized|Unrecognized archive format)/i', $e->getMessage());
}
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Downloader/HgDownloaderTest.php | tests/Composer/Test/Downloader/HgDownloaderTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Downloader;
use Composer\Downloader\HgDownloader;
use Composer\Test\TestCase;
use Composer\Util\Filesystem;
class HgDownloaderTest extends TestCase
{
/** @var string */
private $workingDir;
protected function setUp(): void
{
$this->workingDir = self::getUniqueTmpDirectory();
}
protected function tearDown(): void
{
parent::tearDown();
if (is_dir($this->workingDir)) {
$fs = new Filesystem;
$fs->removeDirectory($this->workingDir);
}
}
protected function getDownloaderMock(?\Composer\IO\IOInterface $io = null, ?\Composer\Config $config = null, ?\Composer\Test\Mock\ProcessExecutorMock $executor = null, ?Filesystem $filesystem = null): HgDownloader
{
$io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$config = $config ?: $this->getMockBuilder('Composer\Config')->getMock();
$executor = $executor ?: $this->getProcessExecutorMock();
$filesystem = $filesystem ?: $this->getMockBuilder('Composer\Util\Filesystem')->getMock();
return new HgDownloader($io, $config, $executor, $filesystem);
}
public function testDownloadForPackageWithoutSourceReference(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->once())
->method('getSourceReference')
->will($this->returnValue(null));
self::expectException('InvalidArgumentException');
$downloader = $this->getDownloaderMock();
$downloader->install($packageMock, '/path');
}
public function testDownload(): void
{
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$packageMock->expects($this->once())
->method('getSourceUrls')
->will($this->returnValue(['https://mercurial.dev/l3l0/composer']));
$process = $this->getProcessExecutorMock();
$process->expects([
['hg', 'clone', '--', 'https://mercurial.dev/l3l0/composer', $this->workingDir],
['hg', 'up', '--', 'ref'],
], true);
$downloader = $this->getDownloaderMock(null, null, $process);
$downloader->install($packageMock, $this->workingDir);
}
public function testUpdateforPackageWithoutSourceReference(): void
{
$initialPackageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$sourcePackageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$sourcePackageMock->expects($this->once())
->method('getSourceReference')
->will($this->returnValue(null));
self::expectException('InvalidArgumentException');
$downloader = $this->getDownloaderMock();
$downloader->prepare('update', $sourcePackageMock, '/path', $initialPackageMock);
$downloader->update($initialPackageMock, $sourcePackageMock, '/path');
$downloader->cleanup('update', $sourcePackageMock, '/path', $initialPackageMock);
}
public function testUpdate(): void
{
$fs = new Filesystem;
$fs->ensureDirectoryExists($this->workingDir.'/.hg');
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$packageMock->expects($this->any())
->method('getSourceReference')
->will($this->returnValue('ref'));
$packageMock->expects($this->any())
->method('getVersion')
->will($this->returnValue('1.0.0.0'));
$packageMock->expects($this->any())
->method('getSourceUrls')
->will($this->returnValue(['https://github.com/l3l0/composer']));
$process = $this->getProcessExecutorMock();
$process->expects([
['hg', 'st'],
['hg', 'pull', '--', 'https://github.com/l3l0/composer'],
['hg', 'up', '--', 'ref'],
], true);
$downloader = $this->getDownloaderMock(null, null, $process);
$downloader->prepare('update', $packageMock, $this->workingDir, $packageMock);
$downloader->update($packageMock, $packageMock, $this->workingDir);
$downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock);
}
public function testRemove(): void
{
$fs = new Filesystem;
$fs->ensureDirectoryExists($this->workingDir.'/.hg');
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$process = $this->getProcessExecutorMock();
$process->expects([
['hg', 'st'],
], true);
$filesystem = $this->getMockBuilder('Composer\Util\Filesystem')->getMock();
$filesystem->expects($this->once())
->method('removeDirectoryAsync')
->with($this->equalTo($this->workingDir))
->will($this->returnValue(\React\Promise\resolve(true)));
$downloader = $this->getDownloaderMock(null, null, $process, $filesystem);
$downloader->prepare('uninstall', $packageMock, $this->workingDir);
$downloader->remove($packageMock, $this->workingDir);
$downloader->cleanup('uninstall', $packageMock, $this->workingDir);
}
public function testGetInstallationSource(): void
{
$downloader = $this->getDownloaderMock(null);
self::assertEquals('source', $downloader->getInstallationSource());
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Installer/SuggestedPackagesReporterTest.php | tests/Composer/Test/Installer/SuggestedPackagesReporterTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Installer;
use Composer\Installer\SuggestedPackagesReporter;
use Composer\Test\Mock\IOMock;
use Composer\Test\TestCase;
/**
* @coversDefaultClass Composer\Installer\SuggestedPackagesReporter
*/
class SuggestedPackagesReporterTest extends TestCase
{
/**
* @var IOMock
*/
private $io;
/**
* @var SuggestedPackagesReporter
*/
private $suggestedPackagesReporter;
protected function setUp(): void
{
$this->io = $this->getIOMock();
$this->suggestedPackagesReporter = new SuggestedPackagesReporter($this->io);
}
/**
* @covers ::__construct
*/
public function testConstructor(): void
{
$this->io->expects([['text' => 'b']], true);
$this->suggestedPackagesReporter->addPackage('a', 'b', 'c');
$this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_LIST);
}
/**
* @covers ::getPackages
*/
public function testGetPackagesEmptyByDefault(): void
{
self::assertEmpty($this->suggestedPackagesReporter->getPackages());
}
/**
* @covers ::getPackages
* @covers ::addPackage
*/
public function testGetPackages(): void
{
$suggestedPackage = $this->getSuggestedPackageArray();
$this->suggestedPackagesReporter->addPackage(
$suggestedPackage['source'],
$suggestedPackage['target'],
$suggestedPackage['reason']
);
self::assertSame(
[$suggestedPackage],
$this->suggestedPackagesReporter->getPackages()
);
}
/**
* Test addPackage appends packages.
* Also test targets can be duplicated.
*
* @covers ::addPackage
*/
public function testAddPackageAppends(): void
{
$suggestedPackageA = $this->getSuggestedPackageArray();
$suggestedPackageB = $this->getSuggestedPackageArray();
$suggestedPackageB['source'] = 'different source';
$suggestedPackageB['reason'] = 'different reason';
$this->suggestedPackagesReporter->addPackage(
$suggestedPackageA['source'],
$suggestedPackageA['target'],
$suggestedPackageA['reason']
);
$this->suggestedPackagesReporter->addPackage(
$suggestedPackageB['source'],
$suggestedPackageB['target'],
$suggestedPackageB['reason']
);
self::assertSame(
[$suggestedPackageA, $suggestedPackageB],
$this->suggestedPackagesReporter->getPackages()
);
}
/**
* @covers ::addSuggestionsFromPackage
*/
public function testAddSuggestionsFromPackage(): void
{
$package = $this->createPackageMock();
$package->expects($this->once())
->method('getSuggests')
->will($this->returnValue([
'target-a' => 'reason-a',
'target-b' => 'reason-b',
]));
$package->expects($this->once())
->method('getPrettyName')
->will($this->returnValue('package-pretty-name'));
$this->suggestedPackagesReporter->addSuggestionsFromPackage($package);
self::assertSame([
[
'source' => 'package-pretty-name',
'target' => 'target-a',
'reason' => 'reason-a',
],
[
'source' => 'package-pretty-name',
'target' => 'target-b',
'reason' => 'reason-b',
],
], $this->suggestedPackagesReporter->getPackages());
}
/**
* @covers ::output
*/
public function testOutput(): void
{
$this->suggestedPackagesReporter->addPackage('a', 'b', 'c');
$this->io->expects([
['text' => 'a suggests:'],
['text' => ' - b: c'],
['text' => ''],
], true);
$this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE);
}
/**
* @covers ::output
*/
public function testOutputWithNoSuggestionReason(): void
{
$this->suggestedPackagesReporter->addPackage('a', 'b', '');
$this->io->expects([
['text' => 'a suggests:'],
['text' => ' - b'],
['text' => ''],
], true);
$this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE);
}
/**
* @covers ::output
*/
public function testOutputIgnoresFormatting(): void
{
$this->suggestedPackagesReporter->addPackage('source', 'target1', "\x1b[1;37;42m Like us\r\non Facebook \x1b[0m");
$this->suggestedPackagesReporter->addPackage('source', 'target2', "<bg=green>Like us on Facebook</>");
$this->io->expects([
['text' => 'source suggests:'],
['text' => ' - target1: [1;37;42m Like us on Facebook [0m'],
['text' => ' - target2: <bg=green>Like us on Facebook</>'],
['text' => ''],
], true);
$this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE);
}
/**
* @covers ::output
*/
public function testOutputMultiplePackages(): void
{
$this->suggestedPackagesReporter->addPackage('a', 'b', 'c');
$this->suggestedPackagesReporter->addPackage('source package', 'target', 'because reasons');
$this->io->expects([
['text' => 'a suggests:'],
['text' => ' - b: c'],
['text' => ''],
['text' => 'source package suggests:'],
['text' => ' - target: because reasons'],
['text' => ''],
], true);
$this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE);
}
/**
* @covers ::output
*/
public function testOutputSkipInstalledPackages(): void
{
$repository = $this->getMockBuilder('Composer\Repository\InstalledRepository')->disableOriginalConstructor()->getMock();
$package1 = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$package2 = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$package1->expects($this->once())
->method('getNames')
->will($this->returnValue(['x', 'y']));
$package2->expects($this->once())
->method('getNames')
->will($this->returnValue(['b']));
$repository->expects($this->once())
->method('getPackages')
->will($this->returnValue([
$package1,
$package2,
]));
$this->suggestedPackagesReporter->addPackage('a', 'b', 'c');
$this->suggestedPackagesReporter->addPackage('source package', 'target', 'because reasons');
$this->io->expects([
['text' => 'source package suggests:'],
['text' => ' - target: because reasons'],
['text' => ''],
], true);
$this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE, $repository);
}
/**
* @covers ::output
*/
public function testOutputNotGettingInstalledPackagesWhenNoSuggestions(): void
{
$repository = $this->getMockBuilder('Composer\Repository\InstalledRepository')->disableOriginalConstructor()->getMock();
$repository->expects($this->exactly(0))
->method('getPackages');
$this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE, $repository);
}
/**
* @return array<string, string>
*/
private function getSuggestedPackageArray(): array
{
return [
'source' => 'a',
'target' => 'b',
'reason' => 'c',
];
}
/**
* @return \Composer\Package\PackageInterface&\PHPUnit\Framework\MockObject\MockObject
*/
private function createPackageMock()
{
return $this->getMockBuilder('Composer\Package\Package')
->setConstructorArgs([bin2hex(random_bytes(5)), '1.0.0.0', '1.0.0'])
->getMock();
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Installer/InstallationManagerTest.php | tests/Composer/Test/Installer/InstallationManagerTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Installer;
use Composer\Installer\InstallationManager;
use Composer\Installer\NoopInstaller;
use Composer\DependencyResolver\Operation\InstallOperation;
use Composer\DependencyResolver\Operation\UpdateOperation;
use Composer\DependencyResolver\Operation\UninstallOperation;
use Composer\Test\TestCase;
class InstallationManagerTest extends TestCase
{
/**
* @var \Composer\Repository\InstalledRepositoryInterface&\PHPUnit\Framework\MockObject\MockObject
*/
protected $repository;
/**
* @var \Composer\Util\Loop&\PHPUnit\Framework\MockObject\MockObject
*/
protected $loop;
/**
* @var \Composer\IO\IOInterface&\PHPUnit\Framework\MockObject\MockObject
*/
protected $io;
public function setUp(): void
{
$this->loop = $this->getMockBuilder('Composer\Util\Loop')->disableOriginalConstructor()->getMock();
$this->repository = $this->getMockBuilder('Composer\Repository\InstalledRepositoryInterface')->getMock();
$this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
}
public function testAddGetInstaller(): void
{
$installer = $this->createInstallerMock();
$installer
->expects($this->exactly(2))
->method('supports')
->will($this->returnCallback(static function ($arg): bool {
return $arg === 'vendor';
}));
$manager = new InstallationManager($this->loop, $this->io);
$manager->addInstaller($installer);
self::assertSame($installer, $manager->getInstaller('vendor'));
self::expectException('InvalidArgumentException');
$manager->getInstaller('unregistered');
}
public function testAddRemoveInstaller(): void
{
$installer = $this->createInstallerMock();
$installer
->expects($this->exactly(2))
->method('supports')
->will($this->returnCallback(static function ($arg): bool {
return $arg === 'vendor';
}));
$installer2 = $this->createInstallerMock();
$installer2
->expects($this->exactly(1))
->method('supports')
->will($this->returnCallback(static function ($arg): bool {
return $arg === 'vendor';
}));
$manager = new InstallationManager($this->loop, $this->io);
$manager->addInstaller($installer);
self::assertSame($installer, $manager->getInstaller('vendor'));
$manager->addInstaller($installer2);
self::assertSame($installer2, $manager->getInstaller('vendor'));
$manager->removeInstaller($installer2);
self::assertSame($installer, $manager->getInstaller('vendor'));
}
public function testExecute(): void
{
$manager = $this->getMockBuilder('Composer\Installer\InstallationManager')
->setConstructorArgs([$this->loop, $this->io])
->onlyMethods(['install', 'update', 'uninstall'])
->getMock();
$installOperation = new InstallOperation($package = $this->createPackageMock());
$removeOperation = new UninstallOperation($package);
$updateOperation = new UpdateOperation(
$package,
$package
);
$package->expects($this->any())
->method('getType')
->will($this->returnValue('library'));
$manager
->expects($this->once())
->method('install')
->with($this->repository, $installOperation);
$manager
->expects($this->once())
->method('uninstall')
->with($this->repository, $removeOperation);
$manager
->expects($this->once())
->method('update')
->with($this->repository, $updateOperation);
$manager->addInstaller(new NoopInstaller());
$manager->execute($this->repository, [$installOperation, $removeOperation, $updateOperation]);
}
public function testInstall(): void
{
$installer = $this->createInstallerMock();
$manager = new InstallationManager($this->loop, $this->io);
$manager->addInstaller($installer);
$package = $this->createPackageMock();
$operation = new InstallOperation($package);
$package
->expects($this->once())
->method('getType')
->will($this->returnValue('library'));
$installer
->expects($this->once())
->method('supports')
->with('library')
->will($this->returnValue(true));
$installer
->expects($this->once())
->method('install')
->with($this->repository, $package);
$manager->install($this->repository, $operation);
}
public function testUpdateWithEqualTypes(): void
{
$installer = $this->createInstallerMock();
$manager = new InstallationManager($this->loop, $this->io);
$manager->addInstaller($installer);
$initial = $this->createPackageMock();
$target = $this->createPackageMock();
$operation = new UpdateOperation($initial, $target);
$initial
->expects($this->once())
->method('getType')
->will($this->returnValue('library'));
$target
->expects($this->once())
->method('getType')
->will($this->returnValue('library'));
$installer
->expects($this->once())
->method('supports')
->with('library')
->will($this->returnValue(true));
$installer
->expects($this->once())
->method('update')
->with($this->repository, $initial, $target);
$manager->update($this->repository, $operation);
}
public function testUpdateWithNotEqualTypes(): void
{
$libInstaller = $this->createInstallerMock();
$bundleInstaller = $this->createInstallerMock();
$manager = new InstallationManager($this->loop, $this->io);
$manager->addInstaller($libInstaller);
$manager->addInstaller($bundleInstaller);
$initial = $this->createPackageMock();
$initial
->expects($this->once())
->method('getType')
->will($this->returnValue('library'));
$target = $this->createPackageMock();
$target
->expects($this->once())
->method('getType')
->will($this->returnValue('bundles'));
$bundleInstaller
->expects($this->exactly(2))
->method('supports')
->will($this->returnCallback(static function ($arg): bool {
return $arg === 'bundles';
}));
$libInstaller
->expects($this->once())
->method('supports')
->with('library')
->will($this->returnValue(true));
$libInstaller
->expects($this->once())
->method('uninstall')
->with($this->repository, $initial);
$bundleInstaller
->expects($this->once())
->method('install')
->with($this->repository, $target);
$operation = new UpdateOperation($initial, $target);
$manager->update($this->repository, $operation);
}
public function testUninstall(): void
{
$installer = $this->createInstallerMock();
$manager = new InstallationManager($this->loop, $this->io);
$manager->addInstaller($installer);
$package = $this->createPackageMock();
$operation = new UninstallOperation($package);
$package
->expects($this->once())
->method('getType')
->will($this->returnValue('library'));
$installer
->expects($this->once())
->method('uninstall')
->with($this->repository, $package);
$installer
->expects($this->once())
->method('supports')
->with('library')
->will($this->returnValue(true));
$manager->uninstall($this->repository, $operation);
}
public function testInstallBinary(): void
{
$installer = $this->getMockBuilder('Composer\Installer\LibraryInstaller')
->disableOriginalConstructor()
->getMock();
$manager = new InstallationManager($this->loop, $this->io);
$manager->addInstaller($installer);
$package = $this->createPackageMock();
$package
->expects($this->once())
->method('getType')
->will($this->returnValue('library'));
$installer
->expects($this->once())
->method('supports')
->with('library')
->will($this->returnValue(true));
$installer
->expects($this->once())
->method('ensureBinariesPresence')
->with($package);
$manager->ensureBinariesPresence($package);
}
/**
* @return \Composer\Installer\InstallerInterface&\PHPUnit\Framework\MockObject\MockObject
*/
private function createInstallerMock()
{
return $this->getMockBuilder('Composer\Installer\InstallerInterface')
->getMock();
}
/**
* @return \Composer\Package\PackageInterface&\PHPUnit\Framework\MockObject\MockObject
*/
private function createPackageMock()
{
$mock = $this->getMockBuilder('Composer\Package\PackageInterface')
->getMock();
return $mock;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Installer/BinaryInstallerTest.php | tests/Composer/Test/Installer/BinaryInstallerTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Installer;
use Composer\Installer\BinaryInstaller;
use Composer\Util\Filesystem;
use Composer\Test\TestCase;
use Composer\Util\ProcessExecutor;
class BinaryInstallerTest extends TestCase
{
/**
* @var string
*/
protected $rootDir;
/**
* @var string
*/
protected $vendorDir;
/**
* @var string
*/
protected $binDir;
/**
* @var \Composer\IO\IOInterface&\PHPUnit\Framework\MockObject\MockObject
*/
protected $io;
/**
* @var Filesystem
*/
protected $fs;
protected function setUp(): void
{
$this->fs = new Filesystem;
$this->rootDir = self::getUniqueTmpDirectory();
$this->vendorDir = $this->rootDir.DIRECTORY_SEPARATOR.'vendor';
$this->ensureDirectoryExistsAndClear($this->vendorDir);
$this->binDir = $this->rootDir.DIRECTORY_SEPARATOR.'bin';
$this->ensureDirectoryExistsAndClear($this->binDir);
$this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
}
protected function tearDown(): void
{
parent::tearDown();
$this->fs->removeDirectory($this->rootDir);
}
/**
* @dataProvider executableBinaryProvider
*/
public function testInstallAndExecBinaryWithFullCompat(string $contents): void
{
$package = $this->createPackageMock();
$package->expects($this->any())
->method('getBinaries')
->willReturn(['binary']);
$this->ensureDirectoryExistsAndClear($this->vendorDir.'/foo/bar');
file_put_contents($this->vendorDir.'/foo/bar/binary', $contents);
$installer = new BinaryInstaller($this->io, $this->binDir, 'full', $this->fs);
$installer->installBinaries($package, $this->vendorDir.'/foo/bar');
$proc = new ProcessExecutor();
$proc->execute($this->binDir.'/binary arg', $output);
self::assertEquals('', $proc->getErrorOutput());
self::assertEquals('success arg', $output);
}
public static function executableBinaryProvider(): array
{
return [
'simple php file' => [<<<'EOL'
<?php
echo 'success '.$_SERVER['argv'][1];
EOL
],
'php file with shebang' => [<<<'EOL'
#!/usr/bin/env php
<?php
echo 'success '.$_SERVER['argv'][1];
EOL
],
'phar file' => [
base64_decode('IyEvdXNyL2Jpbi9lbnYgcGhwCjw/cGhwCgpQaGFyOjptYXBQaGFyKCd0ZXN0LnBoYXInKTsKCnJlcXVpcmUgJ3BoYXI6Ly90ZXN0LnBoYXIvcnVuLnBocCc7CgpfX0hBTFRfQ09NUElMRVIoKTsgPz4NCj4AAAABAAAAEQAAAAEACQAAAHRlc3QucGhhcgAAAAAHAAAAcnVuLnBocCoAAADb9n9hKgAAAMUDDWGkAQAAAAAAADw/cGhwIGVjaG8gInN1Y2Nlc3MgIi4kX1NFUlZFUlsiYXJndiJdWzFdO1SOC0IE3+UN0yzrHIwyspp9slhmAgAAAEdCTUI='),
],
'shebang with strict types declare' => [<<<'EOL'
#!/usr/bin/env php
<?php declare(strict_types=1);
echo 'success '.$_SERVER['argv'][1];
EOL
],
];
}
/**
* @return \Composer\Package\PackageInterface&\PHPUnit\Framework\MockObject\MockObject
*/
protected function createPackageMock()
{
return $this->getMockBuilder('Composer\Package\Package')
->setConstructorArgs([bin2hex(random_bytes(5)), '1.0.0.0', '1.0.0'])
->getMock();
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Installer/MetapackageInstallerTest.php | tests/Composer/Test/Installer/MetapackageInstallerTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Installer;
use Composer\Installer\MetapackageInstaller;
use Composer\Test\TestCase;
class MetapackageInstallerTest extends TestCase
{
/**
* @var \Composer\Repository\InstalledRepositoryInterface&\PHPUnit\Framework\MockObject\MockObject
*/
private $repository;
/**
* @var MetapackageInstaller
*/
private $installer;
/**
* @var \Composer\IO\IOInterface&\PHPUnit\Framework\MockObject\MockObject
*/
private $io;
protected function setUp(): void
{
$this->repository = $this->getMockBuilder('Composer\Repository\InstalledRepositoryInterface')->getMock();
$this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$this->installer = new MetapackageInstaller($this->io);
}
public function testInstall(): void
{
$package = $this->createPackageMock();
$this->repository
->expects($this->once())
->method('addPackage')
->with($package);
$this->installer->install($this->repository, $package);
}
public function testUpdate(): void
{
$initial = $this->createPackageMock();
$initial->expects($this->once())
->method('getVersion')
->will($this->returnValue('1.0.0'));
$target = $this->createPackageMock();
$target->expects($this->once())
->method('getVersion')
->will($this->returnValue('1.0.1'));
$this->repository
->expects($this->exactly(2))
->method('hasPackage')
->with($initial)
->will($this->onConsecutiveCalls(true, false));
$this->repository
->expects($this->once())
->method('removePackage')
->with($initial);
$this->repository
->expects($this->once())
->method('addPackage')
->with($target);
$this->installer->update($this->repository, $initial, $target);
self::expectException('InvalidArgumentException');
$this->installer->update($this->repository, $initial, $target);
}
public function testUninstall(): void
{
$package = $this->createPackageMock();
$this->repository
->expects($this->exactly(2))
->method('hasPackage')
->with($package)
->will($this->onConsecutiveCalls(true, false));
$this->repository
->expects($this->once())
->method('removePackage')
->with($package);
$this->installer->uninstall($this->repository, $package);
self::expectException('InvalidArgumentException');
$this->installer->uninstall($this->repository, $package);
}
/**
* @return \Composer\Package\PackageInterface&\PHPUnit\Framework\MockObject\MockObject
*/
private function createPackageMock()
{
return $this->getMockBuilder('Composer\Package\Package')
->setConstructorArgs([bin2hex(random_bytes(5)), '1.0.0.0', '1.0.0'])
->getMock();
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Installer/InstallerEventTest.php | tests/Composer/Test/Installer/InstallerEventTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Installer;
use Composer\Installer\InstallerEvent;
use Composer\Test\TestCase;
class InstallerEventTest extends TestCase
{
public function testGetter(): void
{
$composer = $this->getMockBuilder('Composer\Composer')->getMock();
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$transaction = $this->getMockBuilder('Composer\DependencyResolver\LockTransaction')->disableOriginalConstructor()->getMock();
$event = new InstallerEvent('EVENT_NAME', $composer, $io, true, true, $transaction);
self::assertSame('EVENT_NAME', $event->getName());
self::assertTrue($event->isDevMode());
self::assertTrue($event->isExecutingOperations());
self::assertInstanceOf('Composer\DependencyResolver\Transaction', $event->getTransaction());
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Installer/LibraryInstallerTest.php | tests/Composer/Test/Installer/LibraryInstallerTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Installer;
use Composer\Installer\LibraryInstaller;
use Composer\Repository\InstalledArrayRepository;
use Composer\Util\Filesystem;
use Composer\Test\TestCase;
use Composer\Composer;
use Composer\Config;
class LibraryInstallerTest extends TestCase
{
/**
* @var Composer
*/
protected $composer;
/**
* @var Config
*/
protected $config;
/**
* @var string
*/
protected $rootDir;
/**
* @var string
*/
protected $vendorDir;
/**
* @var string
*/
protected $binDir;
/**
* @var \Composer\Downloader\DownloadManager&\PHPUnit\Framework\MockObject\MockObject
*/
protected $dm;
/**
* @var \Composer\Repository\InstalledRepositoryInterface&\PHPUnit\Framework\MockObject\MockObject
*/
protected $repository;
/**
* @var \Composer\IO\IOInterface&\PHPUnit\Framework\MockObject\MockObject
*/
protected $io;
/**
* @var Filesystem
*/
protected $fs;
protected function setUp(): void
{
$this->fs = new Filesystem;
$this->composer = new Composer();
$this->config = new Config(false);
$this->composer->setConfig($this->config);
$this->rootDir = self::getUniqueTmpDirectory();
$this->vendorDir = $this->rootDir.DIRECTORY_SEPARATOR.'vendor';
self::ensureDirectoryExistsAndClear($this->vendorDir);
$this->binDir = $this->rootDir.DIRECTORY_SEPARATOR.'bin';
self::ensureDirectoryExistsAndClear($this->binDir);
$this->config->merge([
'config' => [
'vendor-dir' => $this->vendorDir,
'bin-dir' => $this->binDir,
],
]);
$this->dm = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->disableOriginalConstructor()
->getMock();
$this->composer->setDownloadManager($this->dm);
$this->repository = $this->getMockBuilder('Composer\Repository\InstalledRepositoryInterface')->getMock();
$this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
}
protected function tearDown(): void
{
parent::tearDown();
$this->fs->removeDirectory($this->rootDir);
}
public function testInstallerCreationShouldNotCreateVendorDirectory(): void
{
$this->fs->removeDirectory($this->vendorDir);
new LibraryInstaller($this->io, $this->composer);
self::assertFileDoesNotExist($this->vendorDir);
}
public function testInstallerCreationShouldNotCreateBinDirectory(): void
{
$this->fs->removeDirectory($this->binDir);
new LibraryInstaller($this->io, $this->composer);
self::assertFileDoesNotExist($this->binDir);
}
public function testIsInstalled(): void
{
$library = new LibraryInstaller($this->io, $this->composer);
$package = self::getPackage('test/pkg', '1.0.0');
$repository = new InstalledArrayRepository();
self::assertFalse($library->isInstalled($repository, $package));
// package being in repo is not enough to be installed
$repository->addPackage($package);
self::assertFalse($library->isInstalled($repository, $package));
// package being in repo and vendor/pkg/foo dir present means it is seen as installed
self::ensureDirectoryExistsAndClear($this->vendorDir.'/'.$package->getPrettyName());
self::assertTrue($library->isInstalled($repository, $package));
$repository->removePackage($package);
self::assertFalse($library->isInstalled($repository, $package));
}
/**
* @depends testInstallerCreationShouldNotCreateVendorDirectory
* @depends testInstallerCreationShouldNotCreateBinDirectory
*/
public function testInstall(): void
{
$library = new LibraryInstaller($this->io, $this->composer);
$package = self::getPackage('some/package', '1.0.0');
$this->dm
->expects($this->once())
->method('install')
->with($package, $this->vendorDir.'/some/package')
->will($this->returnValue(\React\Promise\resolve(null)));
$this->repository
->expects($this->once())
->method('addPackage')
->with($package);
$library->install($this->repository, $package);
self::assertFileExists($this->vendorDir, 'Vendor dir should be created');
self::assertFileExists($this->binDir, 'Bin dir should be created');
}
/**
* @depends testInstallerCreationShouldNotCreateVendorDirectory
* @depends testInstallerCreationShouldNotCreateBinDirectory
*/
public function testUpdate(): void
{
$filesystem = $this->getMockBuilder('Composer\Util\Filesystem')
->getMock();
$filesystem
->expects($this->once())
->method('rename')
->with($this->vendorDir.'/vendor/package1/oldtarget', $this->vendorDir.'/vendor/package1/newtarget');
$initial = self::getPackage('vendor/package1', '1.0.0');
$target = self::getPackage('vendor/package1', '2.0.0');
$initial->setTargetDir('oldtarget');
$target->setTargetDir('newtarget');
$this->repository
->expects($this->exactly(3))
->method('hasPackage')
->will($this->onConsecutiveCalls(true, false, false));
$this->dm
->expects($this->once())
->method('update')
->with($initial, $target, $this->vendorDir.'/vendor/package1/newtarget')
->will($this->returnValue(\React\Promise\resolve(null)));
$this->repository
->expects($this->once())
->method('removePackage')
->with($initial);
$this->repository
->expects($this->once())
->method('addPackage')
->with($target);
$library = new LibraryInstaller($this->io, $this->composer, 'library', $filesystem);
$library->update($this->repository, $initial, $target);
self::assertFileExists($this->vendorDir, 'Vendor dir should be created');
self::assertFileExists($this->binDir, 'Bin dir should be created');
self::expectException('InvalidArgumentException');
$library->update($this->repository, $initial, $target);
}
public function testUninstall(): void
{
$library = new LibraryInstaller($this->io, $this->composer);
$package = self::getPackage('vendor/pkg', '1.0.0');
$this->repository
->expects($this->exactly(2))
->method('hasPackage')
->with($package)
->will($this->onConsecutiveCalls(true, false));
$this->dm
->expects($this->once())
->method('remove')
->with($package, $this->vendorDir.'/vendor/pkg')
->will($this->returnValue(\React\Promise\resolve(null)));
$this->repository
->expects($this->once())
->method('removePackage')
->with($package);
$library->uninstall($this->repository, $package);
self::expectException('InvalidArgumentException');
$library->uninstall($this->repository, $package);
}
public function testGetInstallPathWithoutTargetDir(): void
{
$library = new LibraryInstaller($this->io, $this->composer);
$package = self::getPackage('Vendor/Pkg', '1.0.0');
self::assertEquals($this->vendorDir.'/'.$package->getPrettyName(), $library->getInstallPath($package));
}
public function testGetInstallPathWithTargetDir(): void
{
$library = new LibraryInstaller($this->io, $this->composer);
$package = self::getPackage('Foo/Bar', '1.0.0');
$package->setTargetDir('Some/Namespace');
self::assertEquals($this->vendorDir.'/'.$package->getPrettyName().'/Some/Namespace', $library->getInstallPath($package));
}
/**
* @depends testInstallerCreationShouldNotCreateVendorDirectory
* @depends testInstallerCreationShouldNotCreateBinDirectory
*/
public function testEnsureBinariesInstalled(): void
{
$binaryInstallerMock = $this->getMockBuilder('Composer\Installer\BinaryInstaller')
->disableOriginalConstructor()
->getMock();
$library = new LibraryInstaller($this->io, $this->composer, 'library', null, $binaryInstallerMock);
$package = self::getPackage('foo/bar', '1.0.0');
$binaryInstallerMock
->expects($this->never())
->method('removeBinaries')
->with($package);
$binaryInstallerMock
->expects($this->once())
->method('installBinaries')
->with($package, $library->getInstallPath($package), false);
$library->ensureBinariesPresence($package);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/IO/ConsoleIOTest.php | tests/Composer/Test/IO/ConsoleIOTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\IO;
use Composer\IO\ConsoleIO;
use Composer\Pcre\Preg;
use Composer\Test\TestCase;
use Symfony\Component\Console\Output\OutputInterface;
class ConsoleIOTest extends TestCase
{
public function testIsInteractive(): void
{
$inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock();
$inputMock->expects($this->exactly(2))
->method('isInteractive')
->willReturnOnConsecutiveCalls(
true,
false
);
$outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock();
$helperMock = $this->getMockBuilder('Symfony\Component\Console\Helper\HelperSet')->getMock();
$consoleIO = new ConsoleIO($inputMock, $outputMock, $helperMock);
self::assertTrue($consoleIO->isInteractive());
self::assertFalse($consoleIO->isInteractive());
}
public function testWrite(): void
{
$inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock();
$outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock();
$outputMock->expects($this->once())
->method('getVerbosity')
->willReturn(OutputInterface::VERBOSITY_NORMAL);
$outputMock->expects($this->once())
->method('write')
->with($this->equalTo('some information about something'), $this->equalTo(false));
$helperMock = $this->getMockBuilder('Symfony\Component\Console\Helper\HelperSet')->getMock();
$consoleIO = new ConsoleIO($inputMock, $outputMock, $helperMock);
$consoleIO->write('some information about something', false);
}
public function testWriteError(): void
{
$inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock();
$outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\ConsoleOutputInterface')->getMock();
$outputMock->expects($this->once())
->method('getVerbosity')
->willReturn(OutputInterface::VERBOSITY_NORMAL);
$outputMock->expects($this->once())
->method('getErrorOutput')
->willReturn($outputMock);
$outputMock->expects($this->once())
->method('write')
->with($this->equalTo('some information about something'), $this->equalTo(false));
$helperMock = $this->getMockBuilder('Symfony\Component\Console\Helper\HelperSet')->getMock();
$consoleIO = new ConsoleIO($inputMock, $outputMock, $helperMock);
$consoleIO->writeError('some information about something', false);
}
public function testWriteWithMultipleLineStringWhenDebugging(): void
{
$inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock();
$outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock();
$outputMock->expects($this->once())
->method('getVerbosity')
->willReturn(OutputInterface::VERBOSITY_NORMAL);
$outputMock->expects($this->once())
->method('write')
->with(
$this->callback(static function ($messages): bool {
$result = Preg::isMatch("[(.*)/(.*) First line]", $messages[0]);
$result = $result && Preg::isMatch("[(.*)/(.*) Second line]", $messages[1]);
return $result;
}),
$this->equalTo(false)
);
$helperMock = $this->getMockBuilder('Symfony\Component\Console\Helper\HelperSet')->getMock();
$consoleIO = new ConsoleIO($inputMock, $outputMock, $helperMock);
$startTime = microtime(true);
$consoleIO->enableDebugging($startTime);
$example = explode('\n', 'First line\nSecond lines');
$consoleIO->write($example, false);
}
public function testOverwrite(): void
{
$inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock();
$outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock();
$outputMock->expects($this->any())
->method('getVerbosity')
->willReturn(OutputInterface::VERBOSITY_NORMAL);
$outputMock->expects($this->atLeast(7))
->method('write')
->willReturnCallback(static function (...$args) {
static $series = null;
if ($series === null) {
$series = [
['something (<question>strlen = 23</question>)', true],
[str_repeat("\x08", 23), false],
['shorter (<comment>12</comment>)', false],
[str_repeat(' ', 11), false],
[str_repeat("\x08", 11), false],
[str_repeat("\x08", 12), false],
['something longer than initial (<info>34</info>)', false],
];
}
if (count($series) > 0) {
self::assertSame(array_shift($series), [$args[0], $args[1]]);
}
});
$helperMock = $this->getMockBuilder('Symfony\Component\Console\Helper\HelperSet')->getMock();
$consoleIO = new ConsoleIO($inputMock, $outputMock, $helperMock);
$consoleIO->write('something (<question>strlen = 23</question>)');
$consoleIO->overwrite('shorter (<comment>12</comment>)', false);
$consoleIO->overwrite('something longer than initial (<info>34</info>)');
}
public function testAsk(): void
{
$inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock();
$outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock();
$helperMock = $this->getMockBuilder('Symfony\Component\Console\Helper\QuestionHelper')->getMock();
$setMock = $this->getMockBuilder('Symfony\Component\Console\Helper\HelperSet')->getMock();
$helperMock
->expects($this->once())
->method('ask')
->with(
$this->isInstanceOf('Symfony\Component\Console\Input\InputInterface'),
$this->isInstanceOf('Symfony\Component\Console\Output\OutputInterface'),
$this->isInstanceOf('Symfony\Component\Console\Question\Question')
)
;
$setMock
->expects($this->once())
->method('get')
->with($this->equalTo('question'))
->will($this->returnValue($helperMock))
;
$consoleIO = new ConsoleIO($inputMock, $outputMock, $setMock);
$consoleIO->ask('Why?', 'default');
}
public function testAskConfirmation(): void
{
$inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock();
$outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock();
$helperMock = $this->getMockBuilder('Symfony\Component\Console\Helper\QuestionHelper')->getMock();
$setMock = $this->getMockBuilder('Symfony\Component\Console\Helper\HelperSet')->getMock();
$helperMock
->expects($this->once())
->method('ask')
->with(
$this->isInstanceOf('Symfony\Component\Console\Input\InputInterface'),
$this->isInstanceOf('Symfony\Component\Console\Output\OutputInterface'),
$this->isInstanceOf('Composer\Question\StrictConfirmationQuestion')
)
;
$setMock
->expects($this->once())
->method('get')
->with($this->equalTo('question'))
->will($this->returnValue($helperMock))
;
$consoleIO = new ConsoleIO($inputMock, $outputMock, $setMock);
$consoleIO->askConfirmation('Why?', false);
}
public function testAskAndValidate(): void
{
$inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock();
$outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock();
$helperMock = $this->getMockBuilder('Symfony\Component\Console\Helper\QuestionHelper')->getMock();
$setMock = $this->getMockBuilder('Symfony\Component\Console\Helper\HelperSet')->getMock();
$helperMock
->expects($this->once())
->method('ask')
->with(
$this->isInstanceOf('Symfony\Component\Console\Input\InputInterface'),
$this->isInstanceOf('Symfony\Component\Console\Output\OutputInterface'),
$this->isInstanceOf('Symfony\Component\Console\Question\Question')
)
;
$setMock
->expects($this->once())
->method('get')
->with($this->equalTo('question'))
->will($this->returnValue($helperMock))
;
$validator = static function ($value): bool {
return true;
};
$consoleIO = new ConsoleIO($inputMock, $outputMock, $setMock);
$consoleIO->askAndValidate('Why?', $validator, 10, 'default');
}
public function testSelect(): void
{
$inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock();
$outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock();
$helperMock = $this->getMockBuilder('Symfony\Component\Console\Helper\QuestionHelper')->getMock();
$setMock = $this->getMockBuilder('Symfony\Component\Console\Helper\HelperSet')->getMock();
$helperMock
->expects($this->once())
->method('ask')
->with(
$this->isInstanceOf('Symfony\Component\Console\Input\InputInterface'),
$this->isInstanceOf('Symfony\Component\Console\Output\OutputInterface'),
$this->isInstanceOf('Symfony\Component\Console\Question\Question')
)
->will($this->returnValue(['item2']));
$setMock
->expects($this->once())
->method('get')
->with($this->equalTo('question'))
->will($this->returnValue($helperMock))
;
$consoleIO = new ConsoleIO($inputMock, $outputMock, $setMock);
$result = $consoleIO->select('Select item', ["item1", "item2"], 'item1', false, "Error message", true);
self::assertEquals(['1'], $result);
}
public function testSetAndGetAuthentication(): void
{
$inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock();
$outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock();
$helperMock = $this->getMockBuilder('Symfony\Component\Console\Helper\HelperSet')->getMock();
$consoleIO = new ConsoleIO($inputMock, $outputMock, $helperMock);
$consoleIO->setAuthentication('repoName', 'l3l0', 'passwd');
self::assertEquals(
['username' => 'l3l0', 'password' => 'passwd'],
$consoleIO->getAuthentication('repoName')
);
}
public function testGetAuthenticationWhenDidNotSet(): void
{
$inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock();
$outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock();
$helperMock = $this->getMockBuilder('Symfony\Component\Console\Helper\HelperSet')->getMock();
$consoleIO = new ConsoleIO($inputMock, $outputMock, $helperMock);
self::assertEquals(
['username' => null, 'password' => null],
$consoleIO->getAuthentication('repoName')
);
}
public function testHasAuthentication(): void
{
$inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock();
$outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock();
$helperMock = $this->getMockBuilder('Symfony\Component\Console\Helper\HelperSet')->getMock();
$consoleIO = new ConsoleIO($inputMock, $outputMock, $helperMock);
$consoleIO->setAuthentication('repoName', 'l3l0', 'passwd');
self::assertTrue($consoleIO->hasAuthentication('repoName'));
self::assertFalse($consoleIO->hasAuthentication('repoName2'));
}
/**
* @dataProvider sanitizeProvider
* @param string|string[] $input
* @param string|string[] $expected
*/
public function testSanitize($input, bool $allowNewlines, $expected): void
{
self::assertSame($expected, ConsoleIO::sanitize($input, $allowNewlines));
}
/**
* @return array<string, array{input: string|string[], allowNewlines: bool, expected: string|string[]}>
*/
public static function sanitizeProvider(): array
{
return [
// String input with allowNewlines=true
'string with \n allowed' => [
'input' => "Hello\nWorld",
'allowNewlines' => true,
'expected' => "Hello\nWorld",
],
'string with \r\n allowed' => [
'input' => "Hello\r\nWorld",
'allowNewlines' => true,
'expected' => "Hello\r\nWorld",
],
'string with standalone \r removed' => [
'input' => "Hello\rWorld",
'allowNewlines' => true,
'expected' => "HelloWorld",
],
'string with escape sequence removed' => [
'input' => "Hello\x1B[31mWorld",
'allowNewlines' => true,
'expected' => "HelloWorld",
],
'string with control chars removed' => [
'input' => "Hello\x01\x08\x09World",
'allowNewlines' => true,
'expected' => "HelloWorld",
],
'string with mixed control chars and newlines' => [
'input' => "Line1\n\x1B[32mLine2\x08\rLine3",
'allowNewlines' => true,
'expected' => "Line1\nLine2Line3",
],
'string with null bytes are allowed' => [
'input' => "Hello\x00World",
'allowNewlines' => true,
'expected' => "Hello\x00World",
],
// String input with allowNewlines=false
'string with \n removed' => [
'input' => "Hello\nWorld",
'allowNewlines' => false,
'expected' => "HelloWorld",
],
'string with \r\n removed' => [
'input' => "Hello\r\nWorld",
'allowNewlines' => false,
'expected' => "HelloWorld",
],
'string with escape sequence removed (no newlines)' => [
'input' => "Hello\x1B[31mWorld",
'allowNewlines' => false,
'expected' => "HelloWorld",
],
'string with all control chars removed' => [
'input' => "Hello\x01\x08\x09\x0A\x0DWorld",
'allowNewlines' => false,
'expected' => "HelloWorld",
],
// Array input with allowNewlines=true
'array with newlines allowed' => [
'input' => ["Hello\nWorld", "Foo\r\nBar"],
'allowNewlines' => true,
'expected' => ["Hello\nWorld", "Foo\r\nBar"],
],
'array with control chars removed' => [
'input' => ["Hello\x1B[31mWorld", "Foo\x08Bar\r"],
'allowNewlines' => true,
'expected' => ["HelloWorld", "FooBar"],
],
// Array input with allowNewlines=false
'array with newlines removed' => [
'input' => ["Hello\nWorld", "Foo\r\nBar"],
'allowNewlines' => false,
'expected' => ["HelloWorld", "FooBar"],
],
'array with all control chars removed' => [
'input' => ["Test\x01\x0A", "Data\x1B[m\x0D"],
'allowNewlines' => false,
'expected' => ["Test", "Data"],
],
// Edge cases
'empty string' => [
'input' => '',
'allowNewlines' => true,
'expected' => '',
],
'empty array' => [
'input' => [],
'allowNewlines' => true,
'expected' => [],
],
'string with no control chars' => [
'input' => 'Hello World',
'allowNewlines' => true,
'expected' => 'Hello World',
],
'string with unicode' => [
'input' => "Hello 世界\nTest",
'allowNewlines' => true,
'expected' => "Hello 世界\nTest",
],
// Various ANSI escape sequences
'CSI with multiple parameters' => [
'input' => "Text\x1B[1;31;40mColored\x1B[0mNormal",
'allowNewlines' => true,
'expected' => "TextColoredNormal",
],
'CSI SGR reset' => [
'input' => "Before\x1B[mAfter",
'allowNewlines' => true,
'expected' => "BeforeAfter",
],
'CSI cursor positioning' => [
'input' => "Line\x1B[2J\x1B[H\x1B[10;5HText",
'allowNewlines' => true,
'expected' => "LineText",
],
'OSC with BEL terminator' => [
'input' => "Text\x1B]0;Window Title\x07More",
'allowNewlines' => true,
'expected' => "TextMore",
],
'OSC with ST terminator' => [
'input' => "Text\x1B]2;Title\x1B\\More",
'allowNewlines' => true,
'expected' => "TextMore",
],
'Simple ESC sequences' => [
'input' => "Text\x1B7Saved\x1B8Restored\x1BcReset",
'allowNewlines' => true,
'expected' => "TextSavedRestoredReset",
],
'ESC D (Index)' => [
'input' => "Line1\x1BDLine2",
'allowNewlines' => true,
'expected' => "Line1Line2",
],
'ESC E (Next Line)' => [
'input' => "Line1\x1BELine2",
'allowNewlines' => true,
'expected' => "Line1Line2",
],
'ESC M (Reverse Index)' => [
'input' => "Text\x1BMMore",
'allowNewlines' => true,
'expected' => "TextMore",
],
'ESC N (SS2) and ESC O (SS3)' => [
'input' => "Text\x1BNchar\x1BOanother",
'allowNewlines' => true,
'expected' => "Textcharanother",
],
'Multiple escape sequences in sequence' => [
'input' => "\x1B[1m\x1B[31m\x1B[44mBold Red on Blue\x1B[0m",
'allowNewlines' => true,
'expected' => "Bold Red on Blue",
],
'CSI with question mark (private mode)' => [
'input' => "Text\x1B[?25lHidden\x1B[?25hVisible",
'allowNewlines' => true,
'expected' => "TextHiddenVisible",
],
'CSI erase sequences' => [
'input' => "Clear\x1B[2J\x1B[K\x1B[1KScreen",
'allowNewlines' => true,
'expected' => "ClearScreen",
],
'Hyperlink OSC 8' => [
'input' => "Click \x1B]8;;https://example.com\x1B\\here\x1B]8;;\x1B\\ for link",
'allowNewlines' => true,
'expected' => "Click here for link",
],
'Mixed content with complex sequences' => [
'input' => "\x1B[1;33mWarning:\x1B[0m File\x1B[31m not\x1B[0m found\n\x1B[2KRetrying...",
'allowNewlines' => true,
'expected' => "Warning: File not found\nRetrying...",
],
// Malformed UTF-8 handling
'malformed UTF-8 single byte' => [
'input' => "Hello\xFFWorld",
'allowNewlines' => true,
'expected' => "Hello?World",
],
'malformed UTF-8 multiple bytes' => [
'input' => "Test\xC3\x28Data",
'allowNewlines' => true,
'expected' => "Test?(Data",
],
'malformed UTF-8 with ANSI escape' => [
'input' => "Line\xFF\x1B[31mColor\xFE",
'allowNewlines' => true,
'expected' => "Line?Color?",
],
'malformed UTF-8 in array' => [
'input' => ["Item\xFF", "Data\xC3\x28"],
'allowNewlines' => true,
'expected' => ["Item?", "Data?("],
],
'valid UTF-8 unchanged' => [
'input' => "Hello 世界 Test",
'allowNewlines' => true,
'expected' => "Hello 世界 Test",
],
'mixed valid and invalid UTF-8' => [
'input' => "Hello\xFF世界\xFETest",
'allowNewlines' => true,
'expected' => "Hello?世界?Test",
],
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/IO/BufferIOTest.php | tests/Composer/Test/IO/BufferIOTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\IO;
use Composer\IO\BufferIO;
use Composer\Test\TestCase;
use Symfony\Component\Console\Input\StreamableInputInterface;
class BufferIOTest extends TestCase
{
public function testSetUserInputs(): void
{
$bufferIO = new BufferIO();
$refl = new \ReflectionProperty($bufferIO, 'input');
(\PHP_VERSION_ID < 80100) and $refl->setAccessible(true);
$input = $refl->getValue($bufferIO);
if (!$input instanceof StreamableInputInterface) {
self::expectException('\RuntimeException');
self::expectExceptionMessage('Setting the user inputs requires at least the version 3.2 of the symfony/console component.');
}
$bufferIO->setUserInputs([
'yes',
'no',
'',
]);
self::assertTrue($bufferIO->askConfirmation('Please say yes!', false));
self::assertFalse($bufferIO->askConfirmation('Now please say no!', true));
self::assertSame('default', $bufferIO->ask('Empty string last', 'default'));
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/IO/NullIOTest.php | tests/Composer/Test/IO/NullIOTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\IO;
use Composer\IO\NullIO;
use Composer\Test\TestCase;
class NullIOTest extends TestCase
{
public function testIsInteractive(): void
{
$io = new NullIO();
self::assertFalse($io->isInteractive());
}
public function testHasAuthentication(): void
{
$io = new NullIO();
self::assertFalse($io->hasAuthentication('foo'));
}
public function testAskAndHideAnswer(): void
{
$io = new NullIO();
self::assertNull($io->askAndHideAnswer('foo'));
}
public function testGetAuthentications(): void
{
$io = new NullIO();
self::assertIsArray($io->getAuthentications());
self::assertEmpty($io->getAuthentications());
self::assertEquals(['username' => null, 'password' => null], $io->getAuthentication('foo'));
}
public function testAsk(): void
{
$io = new NullIO();
self::assertEquals('foo', $io->ask('bar', 'foo'));
}
public function testAskConfirmation(): void
{
$io = new NullIO();
self::assertFalse($io->askConfirmation('bar', false));
}
public function testAskAndValidate(): void
{
$io = new NullIO();
self::assertEquals('foo', $io->askAndValidate('question', static function ($x): bool {
return true;
}, null, 'foo'));
}
public function testSelect(): void
{
$io = new NullIO();
self::assertEquals('1', $io->select('question', ['item1', 'item2'], '1', 2, 'foo', true));
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/RepositoryUtilsTest.php | tests/Composer/Test/Repository/RepositoryUtilsTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository;
use Composer\Package\PackageInterface;
use Composer\Repository\RepositoryUtils;
use Composer\Test\TestCase;
use Generator;
class RepositoryUtilsTest extends TestCase
{
/**
* @dataProvider provideFilterRequireTests
* @param PackageInterface[] $pkgs
* @param string[] $expected
*/
public function testFilterRequiredPackages(array $pkgs, PackageInterface $requirer, array $expected, bool $includeRequireDev = false): void
{
$expected = array_map(static function (string $name) use ($pkgs): PackageInterface {
return $pkgs[$name];
}, $expected);
self::assertSame($expected, RepositoryUtils::filterRequiredPackages($pkgs, $requirer, $includeRequireDev));
}
/**
* @return array<PackageInterface>
*/
private static function getPackages(): array
{
$packageA = self::getPackage('required/a');
$packageB = self::getPackage('required/b');
self::configureLinks($packageB, ['require' => ['required/c' => '*']]);
$packageC = self::getPackage('required/c');
$packageCAlias = self::getAliasPackage($packageC, '2.0.0');
$packageCircular = self::getPackage('required/circular');
self::configureLinks($packageCircular, ['require' => ['required/circular-b' => '*']]);
$packageCircularB = self::getPackage('required/circular-b');
self::configureLinks($packageCircularB, ['require' => ['required/circular' => '*']]);
return [
self::getPackage('dummy/pkg'),
self::getPackage('dummy/pkg2', '2.0.0'),
'a' => $packageA,
'b' => $packageB,
'c' => $packageC,
'c-alias' => $packageCAlias,
'circular' => $packageCircular,
'circular-b' => $packageCircularB,
];
}
public static function provideFilterRequireTests(): Generator
{
$pkgs = self::getPackages();
$requirer = self::getPackage('requirer/pkg');
yield 'no require' => [$pkgs, $requirer, []];
$requirer = self::getPackage('requirer/pkg');
self::configureLinks($requirer, ['require-dev' => ['required/a' => '*']]);
yield 'require-dev has no effect' => [$pkgs, $requirer, []];
$requirer = self::getPackage('requirer/pkg');
self::configureLinks($requirer, ['require-dev' => ['required/a' => '*']]);
yield 'require-dev works if called with it enabled' => [$pkgs, $requirer, ['a'], true];
$requirer = self::getPackage('requirer/pkg');
self::configureLinks($requirer, ['require' => ['required/a' => '*']]);
yield 'simple require' => [$pkgs, $requirer, ['a']];
$requirer = self::getPackage('requirer/pkg');
self::configureLinks($requirer, ['require' => ['required/a' => 'dev-lala']]);
yield 'require constraint is irrelevant' => [$pkgs, $requirer, ['a']];
$requirer = self::getPackage('requirer/pkg');
self::configureLinks($requirer, ['require' => ['required/b' => '*']]);
yield 'require transitive deps and aliases are included' => [$pkgs, $requirer, ['b', 'c', 'c-alias']];
$requirer = self::getPackage('requirer/pkg');
self::configureLinks($requirer, ['require' => ['required/circular' => '*']]);
yield 'circular deps are no problem' => [$pkgs, $requirer, ['circular', 'circular-b']];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/VcsRepositoryTest.php | tests/Composer/Test/Repository/VcsRepositoryTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository;
use Composer\Test\TestCase;
use Composer\Util\Platform;
use Symfony\Component\Process\ExecutableFinder;
use Composer\Package\Dumper\ArrayDumper;
use Composer\Repository\VcsRepository;
use Composer\Util\Filesystem;
use Composer\Util\ProcessExecutor;
use Composer\IO\NullIO;
use Composer\Config;
/**
* @group slow
*/
class VcsRepositoryTest extends TestCase
{
/**
* @var string
*/
private static $composerHome;
/**
* @var string
*/
private static $gitRepo;
/**
* @var ?string
*/
private $skipped = null;
protected function initialize(): void
{
$locator = new ExecutableFinder();
if (!$locator->find('git')) {
$this->skipped = 'This test needs a git binary in the PATH to be able to run';
return;
}
$oldCwd = Platform::getCwd();
self::$composerHome = self::getUniqueTmpDirectory();
self::$gitRepo = self::getUniqueTmpDirectory();
if (!@chdir(self::$gitRepo)) {
$this->skipped = 'Could not move into the temp git repo '.self::$gitRepo;
return;
}
// init
$process = new ProcessExecutor;
$exec = static function ($command) use ($process): void {
$cwd = Platform::getCwd();
if ($process->execute($command, $output, $cwd) !== 0) {
throw new \RuntimeException('Failed to execute '.$command.': '.$process->getErrorOutput());
}
};
$exec('git init -q');
$exec('git checkout -b master');
$exec('git config user.email composertest@example.org');
$exec('git config user.name ComposerTest');
$exec('git config commit.gpgsign false');
touch('foo');
$exec('git add foo');
$exec('git commit -m init');
// non-composed tag & branch
$exec('git tag 0.5.0');
$exec('git branch oldbranch');
// add composed tag & master branch
$composer = ['name' => 'a/b'];
file_put_contents('composer.json', json_encode($composer));
$exec('git add composer.json');
$exec('git commit -m addcomposer');
$exec('git tag 0.6.0');
// add feature-a branch
$exec('git checkout -b feature/a-1.0-B');
file_put_contents('foo', 'bar feature');
$exec('git add foo');
$exec('git commit -m change-a');
// add foo#bar branch which should result in dev-foo+bar
$exec('git branch foo#bar');
// add version to composer.json
$exec('git checkout master');
$composer['version'] = '1.0.0';
file_put_contents('composer.json', json_encode($composer));
$exec('git add composer.json');
$exec('git commit -m addversion');
// create tag with wrong version in it
$exec('git tag 0.9.0');
// create tag with correct version in it
$exec('git tag 1.0.0');
// add feature-b branch
$exec('git checkout -b feature-b');
file_put_contents('foo', 'baz feature');
$exec('git add foo');
$exec('git commit -m change-b');
// add 1.0 branch
$exec('git checkout master');
$exec('git branch 1.0');
// add 1.0.x branch
$exec('git branch 1.1.x');
// update master to 2.0
$composer['version'] = '2.0.0';
file_put_contents('composer.json', json_encode($composer));
$exec('git add composer.json');
$exec('git commit -m bump-version');
chdir($oldCwd);
}
public function setUp(): void
{
if (!self::$gitRepo) {
$this->initialize();
}
if ($this->skipped) {
$this->markTestSkipped($this->skipped);
}
}
public static function tearDownAfterClass(): void
{
$fs = new Filesystem;
$fs->removeDirectory(self::$composerHome);
$fs->removeDirectory(self::$gitRepo);
}
public function testLoadVersions(): void
{
$expected = [
'0.6.0' => true,
'1.0.0' => true,
'1.0.x-dev' => true,
'1.1.x-dev' => true,
'dev-feature-b' => true,
'dev-feature/a-1.0-B' => true,
'dev-foo+bar' => true,
'dev-master' => true,
'9999999-dev' => true, // alias of dev-master
];
$config = new Config();
$config->merge([
'config' => [
'home' => self::$composerHome,
],
]);
$httpDownloader = $this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock();
$repo = new VcsRepository(['url' => self::$gitRepo, 'type' => 'vcs'], new NullIO, $config, $httpDownloader);
$packages = $repo->getPackages();
$dumper = new ArrayDumper();
foreach ($packages as $package) {
if (isset($expected[$package->getPrettyVersion()])) {
unset($expected[$package->getPrettyVersion()]);
} else {
$this->fail('Unexpected version '.$package->getPrettyVersion().' in '.json_encode($dumper->dump($package)));
}
}
self::assertEmpty($expected, 'Missing versions: '.implode(', ', array_keys($expected)));
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/ComposerRepositoryTest.php | tests/Composer/Test/Repository/ComposerRepositoryTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository;
use Composer\IO\NullIO;
use Composer\Json\JsonFile;
use Composer\Repository\ComposerRepository;
use Composer\Repository\RepositoryInterface;
use Composer\Semver\Constraint\Constraint;
use Composer\Test\Mock\FactoryMock;
use Composer\Test\TestCase;
use Composer\Package\Loader\ArrayLoader;
class ComposerRepositoryTest extends TestCase
{
/**
* @dataProvider loadDataProvider
*
* @param mixed[] $expected
* @param array<string, mixed> $repoPackages
*/
public function testLoadData(array $expected, array $repoPackages): void
{
$repoConfig = [
'url' => 'http://example.org',
];
$repository = $this->getMockBuilder('Composer\Repository\ComposerRepository')
->onlyMethods(['loadRootServerFile'])
->setConstructorArgs([
$repoConfig,
new NullIO,
FactoryMock::createConfig(),
$this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(),
$this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock(),
])
->getMock();
$repository
->expects($this->exactly(2))
->method('loadRootServerFile')
->will($this->returnValue($repoPackages));
// Triggers initialization
$packages = $repository->getPackages();
// Final sanity check, ensure the correct number of packages were added.
self::assertCount(count($expected), $packages);
foreach ($expected as $index => $pkg) {
self::assertSame($pkg['name'].' '.$pkg['version'], $packages[$index]->getName().' '.$packages[$index]->getPrettyVersion());
}
}
public static function loadDataProvider(): array
{
return [
// Old repository format
[
[
['name' => 'foo/bar', 'version' => '1.0.0'],
],
['foo/bar' => [
'name' => 'foo/bar',
'versions' => [
'1.0.0' => ['name' => 'foo/bar', 'version' => '1.0.0'],
],
]],
],
// New repository format
[
[
['name' => 'bar/foo', 'version' => '3.14'],
['name' => 'bar/foo', 'version' => '3.145'],
],
['packages' => [
'bar/foo' => [
'3.14' => ['name' => 'bar/foo', 'version' => '3.14'],
'3.145' => ['name' => 'bar/foo', 'version' => '3.145'],
],
]],
],
// New repository format but without versions as keys should also be supported
[
[
['name' => 'bar/foo', 'version' => '3.14'],
['name' => 'bar/foo', 'version' => '3.145'],
],
['packages' => [
'bar/foo' => [
['name' => 'bar/foo', 'version' => '3.14'],
['name' => 'bar/foo', 'version' => '3.145'],
],
]],
],
];
}
public function testWhatProvides(): void
{
$repo = $this->getMockBuilder('Composer\Repository\ComposerRepository')
->setConstructorArgs([
['url' => 'https://dummy.test.link'],
new NullIO,
FactoryMock::createConfig(),
$this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(),
$this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock(),
])
->onlyMethods(['fetchFile'])
->getMock();
$cache = $this->getMockBuilder('Composer\Cache')->disableOriginalConstructor()->getMock();
$cache->expects($this->any())
->method('sha256')
->will($this->returnValue(false));
$properties = [
'cache' => $cache,
'loader' => new ArrayLoader(),
'providerListing' => ['a' => ['sha256' => 'xxx']],
'providersUrl' => 'https://dummy.test.link/to/%package%/file',
];
foreach ($properties as $property => $value) {
$ref = new \ReflectionProperty($repo, $property);
(\PHP_VERSION_ID < 80100) and $ref->setAccessible(true);
$ref->setValue($repo, $value);
}
$repo->expects($this->any())
->method('fetchFile')
->will($this->returnValue([
'packages' => [
[[
'uid' => 1,
'name' => 'a',
'version' => 'dev-master',
'extra' => ['branch-alias' => ['dev-master' => '1.0.x-dev']],
]],
[[
'uid' => 2,
'name' => 'a',
'version' => 'dev-develop',
'extra' => ['branch-alias' => ['dev-develop' => '1.1.x-dev']],
]],
[[
'uid' => 3,
'name' => 'a',
'version' => '0.6',
]],
],
]));
$reflMethod = new \ReflectionMethod(ComposerRepository::class, 'whatProvides');
(\PHP_VERSION_ID < 80100) and $reflMethod->setAccessible(true);
$packages = $reflMethod->invoke($repo, 'a');
self::assertCount(5, $packages);
self::assertEquals(['1', '1-alias', '2', '2-alias', '3'], array_keys($packages));
self::assertSame($packages['2'], $packages['2-alias']->getAliasOf());
}
public function testSearchWithType(): void
{
$repoConfig = [
'url' => 'http://example.org',
];
$result = [
'results' => [
[
'name' => 'foo',
'description' => null,
],
],
];
$httpDownloader = $this->getHttpDownloaderMock();
$httpDownloader->expects(
[
['url' => 'http://example.org/packages.json', 'body' => JsonFile::encode(['search' => '/search.json?q=%query%&type=%type%'])],
['url' => 'http://example.org/search.json?q=foo&type=composer-plugin', 'body' => JsonFile::encode($result)],
['url' => 'http://example.org/search.json?q=foo&type=library', 'body' => JsonFile::encode([])],
],
true
);
$eventDispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')
->disableOriginalConstructor()
->getMock();
$config = FactoryMock::createConfig();
$config->merge(['config' => ['cache-read-only' => true]]);
$repository = new ComposerRepository($repoConfig, new NullIO, $config, $httpDownloader, $eventDispatcher);
self::assertSame(
[['name' => 'foo', 'description' => null]],
$repository->search('foo', RepositoryInterface::SEARCH_FULLTEXT, 'composer-plugin')
);
self::assertEmpty(
$repository->search('foo', RepositoryInterface::SEARCH_FULLTEXT, 'library')
);
}
public function testSearchWithSpecialChars(): void
{
$repoConfig = [
'url' => 'http://example.org',
];
$httpDownloader = $this->getHttpDownloaderMock();
$httpDownloader->expects(
[
['url' => 'http://example.org/packages.json', 'body' => JsonFile::encode(['search' => '/search.json?q=%query%&type=%type%'])],
['url' => 'http://example.org/search.json?q=foo+bar&type=', 'body' => JsonFile::encode([])],
],
true
);
$eventDispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')
->disableOriginalConstructor()
->getMock();
$config = FactoryMock::createConfig();
$config->merge(['config' => ['cache-read-only' => true]]);
$repository = new ComposerRepository($repoConfig, new NullIO, $config, $httpDownloader, $eventDispatcher);
self::assertEmpty(
$repository->search('foo bar', RepositoryInterface::SEARCH_FULLTEXT)
);
}
public function testSearchWithAbandonedPackages(): void
{
$repoConfig = [
'url' => 'http://example.org',
];
$result = [
'results' => [
[
'name' => 'foo1',
'description' => null,
'abandoned' => true,
],
[
'name' => 'foo2',
'description' => null,
'abandoned' => 'bar',
],
],
];
$httpDownloader = $this->getHttpDownloaderMock();
$httpDownloader->expects(
[
['url' => 'http://example.org/packages.json', 'body' => JsonFile::encode(['search' => '/search.json?q=%query%'])],
['url' => 'http://example.org/search.json?q=foo', 'body' => JsonFile::encode($result)],
],
true
);
$eventDispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')
->disableOriginalConstructor()
->getMock();
$config = FactoryMock::createConfig();
$config->merge(['config' => ['cache-read-only' => true]]);
$repository = new ComposerRepository($repoConfig, new NullIO, $config, $httpDownloader, $eventDispatcher);
self::assertSame(
[
['name' => 'foo1', 'description' => null, 'abandoned' => true],
['name' => 'foo2', 'description' => null, 'abandoned' => 'bar'],
],
$repository->search('foo')
);
}
/**
* @dataProvider provideCanonicalizeUrlTestCases
* @param non-empty-string $url
* @param non-empty-string $repositoryUrl
*/
public function testCanonicalizeUrl(string $expected, string $url, string $repositoryUrl): void
{
$repository = new ComposerRepository(
['url' => $repositoryUrl],
new NullIO(),
FactoryMock::createConfig(),
$this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(),
$this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock()
);
$object = new \ReflectionObject($repository);
$method = $object->getMethod('canonicalizeUrl');
(\PHP_VERSION_ID < 80100) and $method->setAccessible(true);
// ComposerRepository::__construct ensures that the repository URL has a
// protocol, so reset it here in order to test all cases.
$property = $object->getProperty('url');
(\PHP_VERSION_ID < 80100) and $property->setAccessible(true);
$property->setValue($repository, $repositoryUrl);
self::assertSame($expected, $method->invoke($repository, $url));
}
public static function provideCanonicalizeUrlTestCases(): array
{
return [
[
'https://example.org/path/to/file',
'/path/to/file',
'https://example.org',
],
[
'https://example.org/canonic_url',
'https://example.org/canonic_url',
'https://should-not-see-me.test',
],
[
'file:///path/to/repository/file',
'/path/to/repository/file',
'file:///path/to/repository',
],
[
// Assert that the repository URL is returned unchanged if it is
// not a URL.
// (Backward compatibility test)
'invalid_repo_url',
'/path/to/file',
'invalid_repo_url',
],
[
// Assert that URLs can contain sequences resembling pattern
// references as understood by preg_replace() without messing up
// the result.
// (Regression test)
'https://example.org/path/to/unusual_$0_filename',
'/path/to/unusual_$0_filename',
'https://example.org',
],
];
}
public function testGetProviderNamesWillReturnPartialPackageNames(): void
{
$httpDownloader = $this->getHttpDownloaderMock();
$httpDownloader->expects(
[
[
'url' => 'http://example.org/packages.json',
'body' => JsonFile::encode([
'providers-lazy-url' => '/foo/p/%package%.json',
'packages' => ['foo/bar' => [
'dev-branch' => ['name' => 'foo/bar'],
'v1.0.0' => ['name' => 'foo/bar'],
]],
]),
],
],
true
);
$repository = new ComposerRepository(
['url' => 'http://example.org/packages.json'],
new NullIO(),
FactoryMock::createConfig(),
$httpDownloader
);
self::assertEquals(['foo/bar'], $repository->getPackageNames());
}
public function testGetSecurityAdvisoriesAssertRepositoryHttpOptionsAreUsed(): void
{
$httpDownloader = $this->getHttpDownloaderMock();
$httpDownloader->expects(
[
[
'url' => 'https://example.org/packages.json',
'body' => JsonFile::encode([
'packages' => ['foo/bar' => [
'dev-branch' => ['name' => 'foo/bar'],
'v1.0.0' => ['name' => 'foo/bar'],
]],
'metadata-url' => 'https://example.org/p2/%package%.json',
'security-advisories' => [
'api-url' => 'https://example.org/security-advisories',
],
]),
'options' => ['http' => ['verify_peer' => false]],
],
[
'url' => 'https://example.org/security-advisories',
'body' => JsonFile::encode(['advisories' => []]),
'options' => ['http' => [
'verify_peer' => false,
'method' => 'POST',
'header' => [
'Content-type: application/x-www-form-urlencoded',
],
'timeout' => 10,
'content' => http_build_query(['packages' => ['foo/bar']]),
]],
],
],
true
);
$repository = new ComposerRepository(
['url' => 'https://example.org/packages.json', 'options' => ['http' => ['verify_peer' => false]]],
new NullIO(),
FactoryMock::createConfig(),
$httpDownloader
);
self::assertSame([
'namesFound' => [],
'advisories' => [],
], $repository->getSecurityAdvisories(['foo/bar' => new Constraint('=', '1.0.0.0')]));
}
public function testGetSecurityAdvisoriesAssertRepositoryAdvisoriesIsZeroIndexedArrayWithConsecutiveKeys(): void
{
$packageName = 'foo/bar';
$advisory1 = $this->generateSecurityAdvisory($packageName, 'CVE-1999-1000', '>=1.0.0,<1.1.0');
$advisory2 = $this->generateSecurityAdvisory($packageName, 'CVE-1999-1000', '>=2.0.0');
$advisory3 = $this->generateSecurityAdvisory($packageName, 'CVE-1999-1000', '>=1.0.0,<1.1.0');
$expectedPackageAdvisories = [
$advisory1,
$advisory3,
];
$httpDownloader = $this->getHttpDownloaderMock();
$httpDownloader->expects(
[
[
'url' => 'https://example.org/packages.json',
'body' => JsonFile::encode([
'packages' => [
$packageName => [
'dev-branch' => ['name' => $packageName],
'v1.0.0' => ['name' => $packageName],
],
],
'metadata-url' => 'https://example.org/p2/%package%.json',
'security-advisories' => [
'api-url' => 'https://example.org/security-advisories',
],
]),
'options' => ['http' => ['verify_peer' => false]],
],
[
'url' => 'https://example.org/security-advisories',
'body' => JsonFile::encode([
'advisories' => [
$packageName => [
$advisory1,
$advisory2,
$advisory3,
],
],
]),
'options' => [
'http' => [
'verify_peer' => false,
'method' => 'POST',
'header' => [
'Content-type: application/x-www-form-urlencoded',
],
'timeout' => 10,
'content' => http_build_query(['packages' => [$packageName]]),
],
],
],
],
true
);
$repository = new ComposerRepository(
['url' => 'https://example.org/packages.json', 'options' => ['http' => ['verify_peer' => false]]],
new NullIO(),
FactoryMock::createConfig(),
$httpDownloader
);
[
'advisories' => $actualAdvisories,
] = $repository->getSecurityAdvisories([$packageName => new Constraint('=', '1.0.0.0')]);
$this->assertIsArray($actualAdvisories);
$this->assertArrayHasKey($packageName, $actualAdvisories);
$actualPackageAdvisories = $actualAdvisories[$packageName];
$this->assertSameSize($expectedPackageAdvisories, $actualPackageAdvisories);
foreach ($expectedPackageAdvisories as $i => $expectedAdvisory) {
$this->assertArrayHasKey($i, $actualPackageAdvisories);
$this->assertSame($expectedAdvisory['advisoryId'], $actualPackageAdvisories[$i]->advisoryId);
}
}
/**
* @return array<string, mixed>
*/
private function generateSecurityAdvisory(string $packageName, ?string $cve, string $affectedVersions): array
{
return [
'advisoryId' => uniqid('PKSA-'),
'packageName' => $packageName,
'remoteId' => 'test',
'title' => 'Security Advisory',
'link' => null,
'cve' => $cve,
'affectedVersions' => $affectedVersions,
'source' => 'Tests',
'reportedAt' => '2024-04-31 12:37:47',
'composerRepository' => 'Package Repository',
'severity' => 'high',
'sources' => [
[
'name' => 'Security Advisory',
'remoteId' => 'test',
],
],
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/CompositeRepositoryTest.php | tests/Composer/Test/Repository/CompositeRepositoryTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository;
use Composer\Repository\CompositeRepository;
use Composer\Repository\ArrayRepository;
use Composer\Test\TestCase;
class CompositeRepositoryTest extends TestCase
{
public function testHasPackage(): void
{
$arrayRepoOne = new ArrayRepository;
$arrayRepoOne->addPackage(self::getPackage('foo', '1'));
$arrayRepoTwo = new ArrayRepository;
$arrayRepoTwo->addPackage(self::getPackage('bar', '1'));
$repo = new CompositeRepository([$arrayRepoOne, $arrayRepoTwo]);
self::assertTrue($repo->hasPackage(self::getPackage('foo', '1')), "Should have package 'foo/1'");
self::assertTrue($repo->hasPackage(self::getPackage('bar', '1')), "Should have package 'bar/1'");
self::assertFalse($repo->hasPackage(self::getPackage('foo', '2')), "Should not have package 'foo/2'");
self::assertFalse($repo->hasPackage(self::getPackage('bar', '2')), "Should not have package 'bar/2'");
}
public function testFindPackage(): void
{
$arrayRepoOne = new ArrayRepository;
$arrayRepoOne->addPackage(self::getPackage('foo', '1'));
$arrayRepoTwo = new ArrayRepository;
$arrayRepoTwo->addPackage(self::getPackage('bar', '1'));
$repo = new CompositeRepository([$arrayRepoOne, $arrayRepoTwo]);
self::assertEquals('foo', $repo->findPackage('foo', '1')->getName(), "Should find package 'foo/1' and get name of 'foo'");
self::assertEquals('1', $repo->findPackage('foo', '1')->getPrettyVersion(), "Should find package 'foo/1' and get pretty version of '1'");
self::assertEquals('bar', $repo->findPackage('bar', '1')->getName(), "Should find package 'bar/1' and get name of 'bar'");
self::assertEquals('1', $repo->findPackage('bar', '1')->getPrettyVersion(), "Should find package 'bar/1' and get pretty version of '1'");
self::assertNull($repo->findPackage('foo', '2'), "Should not find package 'foo/2'");
}
public function testFindPackages(): void
{
$arrayRepoOne = new ArrayRepository;
$arrayRepoOne->addPackage(self::getPackage('foo', '1'));
$arrayRepoOne->addPackage(self::getPackage('foo', '2'));
$arrayRepoOne->addPackage(self::getPackage('bat', '1'));
$arrayRepoTwo = new ArrayRepository;
$arrayRepoTwo->addPackage(self::getPackage('bar', '1'));
$arrayRepoTwo->addPackage(self::getPackage('bar', '2'));
$arrayRepoTwo->addPackage(self::getPackage('foo', '3'));
$repo = new CompositeRepository([$arrayRepoOne, $arrayRepoTwo]);
$bats = $repo->findPackages('bat');
self::assertCount(1, $bats, "Should find one instance of 'bats' (defined in just one repository)");
self::assertEquals('bat', $bats[0]->getName(), "Should find packages named 'bat'");
$bars = $repo->findPackages('bar');
self::assertCount(2, $bars, "Should find two instances of 'bar' (both defined in the same repository)");
self::assertEquals('bar', $bars[0]->getName(), "Should find packages named 'bar'");
$foos = $repo->findPackages('foo');
self::assertCount(3, $foos, "Should find three instances of 'foo' (two defined in one repository, the third in the other)");
self::assertEquals('foo', $foos[0]->getName(), "Should find packages named 'foo'");
}
public function testGetPackages(): void
{
$arrayRepoOne = new ArrayRepository;
$arrayRepoOne->addPackage(self::getPackage('foo', '1'));
$arrayRepoTwo = new ArrayRepository;
$arrayRepoTwo->addPackage(self::getPackage('bar', '1'));
$repo = new CompositeRepository([$arrayRepoOne, $arrayRepoTwo]);
$packages = $repo->getPackages();
self::assertCount(2, $packages, "Should get two packages");
self::assertEquals("foo", $packages[0]->getName(), "First package should have name of 'foo'");
self::assertEquals("1", $packages[0]->getPrettyVersion(), "First package should have pretty version of '1'");
self::assertEquals("bar", $packages[1]->getName(), "Second package should have name of 'bar'");
self::assertEquals("1", $packages[1]->getPrettyVersion(), "Second package should have pretty version of '1'");
}
public function testAddRepository(): void
{
$arrayRepoOne = new ArrayRepository;
$arrayRepoOne->addPackage(self::getPackage('foo', '1'));
$arrayRepoTwo = new ArrayRepository;
$arrayRepoTwo->addPackage(self::getPackage('bar', '1'));
$arrayRepoTwo->addPackage(self::getPackage('bar', '2'));
$arrayRepoTwo->addPackage(self::getPackage('bar', '3'));
$repo = new CompositeRepository([$arrayRepoOne]);
self::assertCount(1, $repo, "Composite repository should have just one package before addRepository() is called");
$repo->addRepository($arrayRepoTwo);
self::assertCount(4, $repo, "Composite repository should have four packages after addRepository() is called");
}
public function testCount(): void
{
$arrayRepoOne = new ArrayRepository;
$arrayRepoOne->addPackage(self::getPackage('foo', '1'));
$arrayRepoTwo = new ArrayRepository;
$arrayRepoTwo->addPackage(self::getPackage('bar', '1'));
$repo = new CompositeRepository([$arrayRepoOne, $arrayRepoTwo]);
self::assertCount(2, $repo, "Should return '2' for count(\$repo)");
}
/**
* @dataProvider provideMethodCalls
*
* @param mixed[] $args
*/
public function testNoRepositories(string $method, array $args): void
{
$repo = new CompositeRepository([]);
self::assertEquals([], call_user_func_array([$repo, $method], $args));
}
public static function provideMethodCalls(): array
{
return [
['findPackages', ['foo']],
['search', ['foo']],
['getPackages', []],
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/RepositoryFactoryTest.php | tests/Composer/Test/Repository/RepositoryFactoryTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository;
use Composer\Repository\RepositoryFactory;
use Composer\Test\TestCase;
class RepositoryFactoryTest extends TestCase
{
public function testManagerWithAllRepositoryTypes(): void
{
$manager = RepositoryFactory::manager(
$this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
$this->getMockBuilder('Composer\Config')->getMock(),
$this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(),
$this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock()
);
$ref = new \ReflectionProperty($manager, 'repositoryClasses');
(\PHP_VERSION_ID < 80100) and $ref->setAccessible(true);
$repositoryClasses = $ref->getValue($manager);
self::assertEquals([
'composer',
'vcs',
'package',
'pear',
'git',
'bitbucket',
'git-bitbucket',
'github',
'gitlab',
'svn',
'fossil',
'perforce',
'hg',
'artifact',
'path',
], array_keys($repositoryClasses));
}
/**
* @dataProvider generateRepositoryNameProvider
*
* @param int|string $index
* @param array<string, string> $config
* @param array<string, mixed> $existingRepos
*
* @phpstan-param array{url?: string} $config
*/
public function testGenerateRepositoryName($index, array $config, array $existingRepos, string $expected): void
{
self::assertSame($expected, RepositoryFactory::generateRepositoryName($index, $config, $existingRepos));
}
public static function generateRepositoryNameProvider(): array
{
return [
[0, [], [], '0'],
[0, [], [[]], '02'],
[0, ['url' => 'https://example.org'], [], 'example.org'],
[0, ['url' => 'https://example.org'], ['example.org' => []], 'example.org2'],
['example.org', ['url' => 'https://example.org/repository'], [], 'example.org'],
['example.org', ['url' => 'https://example.org/repository'], ['example.org' => []], 'example.org2'],
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/FilterRepositoryTest.php | tests/Composer/Test/Repository/FilterRepositoryTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository;
use Composer\Test\TestCase;
use Composer\Repository\FilterRepository;
use Composer\Repository\ArrayRepository;
use Composer\Semver\Constraint\MatchAllConstraint;
use Composer\Package\BasePackage;
class FilterRepositoryTest extends TestCase
{
/**
* @var ArrayRepository
*/
private $arrayRepo;
public function setUp(): void
{
$this->arrayRepo = new ArrayRepository();
$this->arrayRepo->addPackage(self::getPackage('foo/aaa', '1.0.0'));
$this->arrayRepo->addPackage(self::getPackage('foo/bbb', '1.0.0'));
$this->arrayRepo->addPackage(self::getPackage('bar/xxx', '1.0.0'));
$this->arrayRepo->addPackage(self::getPackage('baz/yyy', '1.0.0'));
}
/**
* @dataProvider provideRepoMatchingTestCases
*
* @param string[] $expected
* @param array{only?: array<string>, exclude?: array<string>, canonical?: bool} $config
*/
public function testRepoMatching(array $expected, $config): void
{
$repo = new FilterRepository($this->arrayRepo, $config);
$packages = $repo->getPackages();
self::assertSame($expected, array_map(static function ($p): string {
return $p->getName();
}, $packages));
}
public static function provideRepoMatchingTestCases(): array
{
return [
[['foo/aaa', 'foo/bbb'], ['only' => ['foo/*']]],
[['foo/aaa', 'baz/yyy'], ['only' => ['foo/aaa', 'baz/yyy']]],
[['bar/xxx'], ['exclude' => ['foo/*', 'baz/yyy']]],
// make sure sub-patterns are not matched without wildcard
[['foo/aaa', 'foo/bbb', 'bar/xxx', 'baz/yyy'], ['exclude' => ['foo/aa', 'az/yyy']]],
[[], ['only' => ['foo/aa', 'az/yyy']]],
// empty "only" means no packages allowed
[[], ['only' => []]],
// absent "only" means all packages allowed
[['foo/aaa', 'foo/bbb', 'bar/xxx', 'baz/yyy'], []],
// empty or absent "exclude" have the same effect: none
[['foo/aaa', 'foo/bbb', 'bar/xxx', 'baz/yyy'], ['exclude' => []]],
[['foo/aaa', 'foo/bbb', 'bar/xxx', 'baz/yyy'], []],
];
}
public function testBothFiltersDisallowed(): void
{
$this->expectException(\InvalidArgumentException::class);
new FilterRepository($this->arrayRepo, ['only' => [], 'exclude' => []]);
}
public function testSecurityAdvisoriesDisabledInChild(): void
{
$repo = new FilterRepository($this->arrayRepo, ['only' => ['foo/*']]);
self::assertFalse($repo->hasSecurityAdvisories());
self::assertSame(['namesFound' => [], 'advisories' => []], $repo->getSecurityAdvisories(['foo/aaa' => new MatchAllConstraint()], true));
}
public function testCanonicalDefaultTrue(): void
{
$repo = new FilterRepository($this->arrayRepo, []);
$result = $repo->loadPackages(['foo/aaa' => new MatchAllConstraint], BasePackage::STABILITIES, []);
self::assertCount(1, $result['packages']);
self::assertCount(1, $result['namesFound']);
}
public function testNonCanonical(): void
{
$repo = new FilterRepository($this->arrayRepo, ['canonical' => false]);
$result = $repo->loadPackages(['foo/aaa' => new MatchAllConstraint], BasePackage::STABILITIES, []);
self::assertCount(1, $result['packages']);
self::assertCount(0, $result['namesFound']);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/ArrayRepositoryTest.php | tests/Composer/Test/Repository/ArrayRepositoryTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository;
use Composer\Repository\ArrayRepository;
use Composer\Repository\RepositoryInterface;
use Composer\Test\TestCase;
class ArrayRepositoryTest extends TestCase
{
public function testAddPackage(): void
{
$repo = new ArrayRepository;
$repo->addPackage(self::getPackage('foo', '1'));
self::assertCount(1, $repo);
}
public function testRemovePackage(): void
{
$package = self::getPackage('bar', '2');
$repo = new ArrayRepository;
$repo->addPackage(self::getPackage('foo', '1'));
$repo->addPackage($package);
self::assertCount(2, $repo);
$repo->removePackage(self::getPackage('foo', '1'));
self::assertCount(1, $repo);
self::assertEquals([$package], $repo->getPackages());
}
public function testHasPackage(): void
{
$repo = new ArrayRepository;
$repo->addPackage(self::getPackage('foo', '1'));
$repo->addPackage(self::getPackage('bar', '2'));
self::assertTrue($repo->hasPackage(self::getPackage('foo', '1')));
self::assertFalse($repo->hasPackage(self::getPackage('bar', '1')));
}
public function testFindPackages(): void
{
$repo = new ArrayRepository();
$repo->addPackage(self::getPackage('foo', '1'));
$repo->addPackage(self::getPackage('bar', '2'));
$repo->addPackage(self::getPackage('bar', '3'));
$foo = $repo->findPackages('foo');
self::assertCount(1, $foo);
self::assertEquals('foo', $foo[0]->getName());
$bar = $repo->findPackages('bar');
self::assertCount(2, $bar);
self::assertEquals('bar', $bar[0]->getName());
}
public function testAutomaticallyAddAliasedPackageButNotRemove(): void
{
$repo = new ArrayRepository();
$package = self::getPackage('foo', '1');
$alias = self::getAliasPackage($package, '2');
$repo->addPackage($alias);
self::assertCount(2, $repo);
self::assertTrue($repo->hasPackage(self::getPackage('foo', '1')));
self::assertTrue($repo->hasPackage(self::getPackage('foo', '2')));
$repo->removePackage($alias);
self::assertCount(1, $repo);
}
public function testSearch(): void
{
$repo = new ArrayRepository();
$repo->addPackage(self::getPackage('foo', '1'));
$repo->addPackage(self::getPackage('bar', '1'));
self::assertSame(
[['name' => 'foo', 'description' => null]],
$repo->search('foo', RepositoryInterface::SEARCH_FULLTEXT)
);
self::assertSame(
[['name' => 'bar', 'description' => null]],
$repo->search('bar')
);
self::assertEmpty(
$repo->search('foobar')
);
}
public function testSearchWithPackageType(): void
{
$repo = new ArrayRepository();
$repo->addPackage(self::getPackage('foo', '1', 'Composer\Package\CompletePackage'));
$repo->addPackage(self::getPackage('bar', '1', 'Composer\Package\CompletePackage'));
$package = self::getPackage('foobar', '1', 'Composer\Package\CompletePackage');
$package->setType('composer-plugin');
$repo->addPackage($package);
self::assertSame(
[['name' => 'foo', 'description' => null]],
$repo->search('foo', RepositoryInterface::SEARCH_FULLTEXT, 'library')
);
self::assertEmpty($repo->search('bar', RepositoryInterface::SEARCH_FULLTEXT, 'package'));
self::assertSame(
[['name' => 'foobar', 'description' => null]],
$repo->search('foo', 0, 'composer-plugin')
);
}
public function testSearchWithAbandonedPackages(): void
{
$repo = new ArrayRepository();
$package1 = self::getPackage('foo1', '1');
$package1->setAbandoned(true);
$repo->addPackage($package1);
$package2 = self::getPackage('foo2', '1');
$package2->setAbandoned('bar');
$repo->addPackage($package2);
self::assertSame(
[
['name' => 'foo1', 'description' => null, 'abandoned' => true],
['name' => 'foo2', 'description' => null, 'abandoned' => 'bar'],
],
$repo->search('foo')
);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/ArtifactRepositoryTest.php | tests/Composer/Test/Repository/ArtifactRepositoryTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository;
use Composer\Repository\ArtifactRepository;
use Composer\Test\TestCase;
use Composer\IO\NullIO;
use Composer\Package\BasePackage;
class ArtifactRepositoryTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
if (!extension_loaded('zip')) {
$this->markTestSkipped('You need the zip extension to run this test.');
}
}
public function testExtractsConfigsFromZipArchives(): void
{
$expectedPackages = [
'vendor0/package0-0.0.1',
'composer/composer-1.0.0-alpha6',
'vendor1/package2-4.3.2',
'vendor3/package1-5.4.3',
'test/jsonInRoot-1.0.0',
'test/jsonInRootTarFile-1.0.0',
'test/jsonInFirstLevel-1.0.0',
//The files not-an-artifact.zip and jsonSecondLevel are not valid
//artifacts and do not get detected.
];
$coordinates = ['type' => 'artifact', 'url' => __DIR__ . '/Fixtures/artifacts'];
$repo = new ArtifactRepository($coordinates, new NullIO());
$foundPackages = array_map(static function (BasePackage $package) {
return "{$package->getPrettyName()}-{$package->getPrettyVersion()}";
}, $repo->getPackages());
sort($expectedPackages);
sort($foundPackages);
self::assertSame($expectedPackages, $foundPackages);
$tarPackage = array_filter($repo->getPackages(), static function (BasePackage $package): bool {
return $package->getPrettyName() === 'test/jsonInRootTarFile';
});
self::assertCount(1, $tarPackage);
$tarPackage = array_pop($tarPackage);
self::assertSame('tar', $tarPackage->getDistType());
}
public function testAbsoluteRepoUrlCreatesAbsoluteUrlPackages(): void
{
$absolutePath = __DIR__ . '/Fixtures/artifacts';
$coordinates = ['type' => 'artifact', 'url' => $absolutePath];
$repo = new ArtifactRepository($coordinates, new NullIO());
foreach ($repo->getPackages() as $package) {
self::assertSame(strpos($package->getDistUrl(), strtr($absolutePath, '\\', '/')), 0);
}
}
public function testRelativeRepoUrlCreatesRelativeUrlPackages(): void
{
$relativePath = 'tests/Composer/Test/Repository/Fixtures/artifacts';
$coordinates = ['type' => 'artifact', 'url' => $relativePath];
$repo = new ArtifactRepository($coordinates, new NullIO());
foreach ($repo->getPackages() as $package) {
self::assertSame(strpos($package->getDistUrl(), $relativePath), 0);
}
}
}
//Files jsonInFirstLevel.zip, jsonInRoot.zip and jsonInSecondLevel.zip were generated with:
//
//$archivesToCreate = array(
// 'jsonInRoot' => array(
// "extra.txt" => "Testing testing testing",
// "composer.json" => '{ "name": "test/jsonInRoot", "version": "1.0.0" }',
// "subdir/extra.txt" => "Testing testing testing",
// "subdir/extra2.txt" => "Testing testing testing",
// ),
//
// 'jsonInFirstLevel' => array(
// "extra.txt" => "Testing testing testing",
// "subdir/composer.json" => '{ "name": "test/jsonInFirstLevel", "version": "1.0.0" }',
// "subdir/extra.txt" => "Testing testing testing",
// "subdir/extra2.txt" => "Testing testing testing",
// ),
//
// 'jsonInSecondLevel' => array(
// "extra.txt" => "Testing testing testing",
// "subdir/extra1.txt" => "Testing testing testing",
// "subdir/foo/composer.json" => '{ "name": "test/jsonInSecondLevel", "version": "1.0.0" }',
// "subdir/foo/extra1.txt" => "Testing testing testing",
// "subdir/extra2.txt" => "Testing testing testing",
// "subdir/extra3.txt" => "Testing testing testing",
// ),
//);
//
//foreach ($archivesToCreate as $archiveName => $fileDetails) {
// $zipFile = new ZipArchive();
// $zipFile->open("$archiveName.zip", ZIPARCHIVE::CREATE);
//
// foreach ($fileDetails as $filename => $fileContents) {
// $zipFile->addFromString($filename, $fileContents);
// }
//
// $zipFile->close();
//}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/RepositoryManagerTest.php | tests/Composer/Test/Repository/RepositoryManagerTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository;
use Composer\Repository\RepositoryManager;
use Composer\Test\TestCase;
use Composer\Util\Filesystem;
use Composer\Config;
class RepositoryManagerTest extends TestCase
{
/** @var string */
protected $tmpdir;
public function setUp(): void
{
$this->tmpdir = self::getUniqueTmpDirectory();
}
protected function tearDown(): void
{
parent::tearDown();
if (is_dir($this->tmpdir)) {
$fs = new Filesystem();
$fs->removeDirectory($this->tmpdir);
}
}
public function testPrepend(): void
{
$rm = new RepositoryManager(
$this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
new Config,
$this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(),
$this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock()
);
$repository1 = $this->getMockBuilder('Composer\Repository\RepositoryInterface')->getMock();
$repository2 = $this->getMockBuilder('Composer\Repository\RepositoryInterface')->getMock();
$rm->addRepository($repository1);
$rm->prependRepository($repository2);
self::assertEquals([$repository2, $repository1], $rm->getRepositories());
}
/**
* @dataProvider provideRepoCreationTestCases
*
* @doesNotPerformAssertions
* @param array<string, mixed> $options
*/
public function testRepoCreation(string $type, array $options): void
{
$rm = new RepositoryManager(
$this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
$config = new Config,
$this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(),
$this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock()
);
$tmpdir = $this->tmpdir;
$config->merge(['config' => ['cache-repo-dir' => $tmpdir]]);
$rm->setRepositoryClass('composer', 'Composer\Repository\ComposerRepository');
$rm->setRepositoryClass('vcs', 'Composer\Repository\VcsRepository');
$rm->setRepositoryClass('package', 'Composer\Repository\PackageRepository');
$rm->setRepositoryClass('pear', 'Composer\Repository\PearRepository');
$rm->setRepositoryClass('git', 'Composer\Repository\VcsRepository');
$rm->setRepositoryClass('svn', 'Composer\Repository\VcsRepository');
$rm->setRepositoryClass('perforce', 'Composer\Repository\VcsRepository');
$rm->setRepositoryClass('hg', 'Composer\Repository\VcsRepository');
$rm->setRepositoryClass('artifact', 'Composer\Repository\ArtifactRepository');
$rm->createRepository('composer', ['url' => 'http://example.org']);
$rm->createRepository($type, $options);
}
public static function provideRepoCreationTestCases(): array
{
$cases = [
['composer', ['url' => 'http://example.org']],
['vcs', ['url' => 'http://github.com/foo/bar']],
['git', ['url' => 'http://github.com/foo/bar']],
['git', ['url' => 'git@example.org:foo/bar.git']],
['svn', ['url' => 'svn://example.org/foo/bar']],
['package', ['package' => []]],
];
if (class_exists('ZipArchive')) {
$cases[] = ['artifact', ['url' => '/path/to/zips']];
}
return $cases;
}
/**
* @dataProvider provideInvalidRepoCreationTestCases
*
* @param array<string, mixed> $options
*/
public function testInvalidRepoCreationThrows(string $type, array $options): void
{
self::expectException('InvalidArgumentException');
$rm = new RepositoryManager(
$this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
$config = new Config,
$this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(),
$this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock()
);
$tmpdir = $this->tmpdir;
$config->merge(['config' => ['cache-repo-dir' => $tmpdir]]);
$rm->createRepository($type, $options);
}
public static function provideInvalidRepoCreationTestCases(): array
{
return [
['pear', ['url' => 'http://pear.example.org/foo']],
['invalid', []],
];
}
public function testFilterRepoWrapping(): void
{
$rm = new RepositoryManager(
$this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
$config = $this->getMockBuilder('Composer\Config')->onlyMethods(['get'])->getMock(),
$this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(),
$this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock()
);
$rm->setRepositoryClass('path', 'Composer\Repository\PathRepository');
/** @var \Composer\Repository\FilterRepository $repo */
$repo = $rm->createRepository('path', ['type' => 'path', 'url' => __DIR__, 'only' => ['foo/bar']]);
self::assertInstanceOf('Composer\Repository\FilterRepository', $repo);
self::assertInstanceOf('Composer\Repository\PathRepository', $repo->getRepository());
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/PlatformRepositoryTest.php | tests/Composer/Test/Repository/PlatformRepositoryTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository;
use Composer\Composer;
use Composer\Package\Link;
use Composer\Package\PackageInterface;
use Composer\Repository\PlatformRepository;
use Composer\Test\TestCase;
use PHPUnit\Framework\Assert;
class PlatformRepositoryTest extends TestCase
{
public function testHhvmPackage(): void
{
$hhvmDetector = $this->getMockBuilder('Composer\Platform\HhvmDetector')->getMock();
$platformRepository = new PlatformRepository([], [], null, $hhvmDetector);
$hhvmDetector
->method('getVersion')
->willReturn('2.1.0');
$hhvm = $platformRepository->findPackage('hhvm', '*');
self::assertNotNull($hhvm, 'hhvm found');
self::assertSame('2.1.0', $hhvm->getPrettyVersion());
}
public static function providePhpFlavorTestCases(): array
{
return [
[
[
'PHP_VERSION' => '7.1.33',
],
[
'php' => '7.1.33',
],
],
[
[
'PHP_VERSION' => '7.2.31-1+ubuntu16.04.1+deb.sury.org+1',
'PHP_DEBUG' => true,
],
[
'php' => '7.2.31',
'php-debug' => '7.2.31',
],
],
[
[
'PHP_VERSION' => '7.2.31-1+ubuntu16.04.1+deb.sury.org+1',
'PHP_ZTS' => true,
],
[
'php' => '7.2.31',
'php-zts' => '7.2.31',
],
],
[
[
'PHP_VERSION' => '7.2.31-1+ubuntu16.04.1+deb.sury.org+1',
'PHP_INT_SIZE' => 8,
],
[
'php' => '7.2.31',
'php-64bit' => '7.2.31',
],
],
[
[
'PHP_VERSION' => '7.2.31-1+ubuntu16.04.1+deb.sury.org+1',
'AF_INET6' => 30,
],
[
'php' => '7.2.31',
'php-ipv6' => '7.2.31',
],
],
[
[
'PHP_VERSION' => '7.2.31-1+ubuntu16.04.1+deb.sury.org+1',
],
[
'php' => '7.2.31',
'php-ipv6' => '7.2.31',
],
[
['inet_pton', ['::'], ''],
],
],
[
[
'PHP_VERSION' => '7.2.31-1+ubuntu16.04.1+deb.sury.org+1',
],
[
'php' => '7.2.31',
],
[
['inet_pton', ['::'], false],
],
],
];
}
/**
* @dataProvider providePhpFlavorTestCases
*
* @param array<string, mixed> $constants
* @param array<string, string> $packages
* @param list<array{string, list<string>, string|bool}> $functions
*/
public function testPhpVersion(array $constants, array $packages, array $functions = []): void
{
$runtime = $this->getMockBuilder('Composer\Platform\Runtime')->getMock();
$runtime
->method('getExtensions')
->willReturn([]);
$runtime
->method('hasConstant')
->willReturnCallback(static function ($constant, $class = null) use ($constants): bool {
return isset($constants[ltrim($class.'::'.$constant, ':')]);
});
$runtime
->method('getConstant')
->willReturnCallback(static function ($constant, $class = null) use ($constants) {
return $constants[ltrim($class.'::'.$constant, ':')] ?? null;
});
$runtime
->method('invoke')
->willReturnMap($functions);
$repository = new PlatformRepository([], [], $runtime);
foreach ($packages as $packageName => $version) {
$package = $repository->findPackage($packageName, '*');
self::assertNotNull($package, sprintf('Expected to find package "%s"', $packageName));
self::assertSame($version, $package->getPrettyVersion(), sprintf('Expected package "%s" version to be %s, got %s', $packageName, $version, $package->getPrettyVersion()));
}
}
public function testInetPtonRegression(): void
{
$runtime = $this->getMockBuilder('Composer\Platform\Runtime')->getMock();
$runtime
->expects(self::once())
->method('invoke')
->with('inet_pton', ['::'])
->willReturn(false);
$runtime
->method('hasConstant')
->willReturn(false); // suppressing PHP_ZTS & AF_INET6
$constants = [
'PHP_VERSION' => '7.0.0',
'PHP_DEBUG' => false,
];
$runtime
->method('getConstant')
->willReturnCallback(static function ($constant, $class = null) use ($constants) {
return $constants[ltrim($class.'::'.$constant, ':')] ?? null;
});
$runtime
->method('getExtensions')
->willReturn([]);
$repository = new PlatformRepository([], [], $runtime);
$package = $repository->findPackage('php-ipv6', '*');
self::assertNull($package);
}
public static function provideLibraryTestCases(): array
{
return [
'amqp' => [
'amqp',
'
amqp
Version => 1.9.4
Revision => release
Compiled => Nov 19 2019 @ 08:44:26
AMQP protocol version => 0-9-1
librabbitmq version => 0.9.0
Default max channels per connection => 256
Default max frame size => 131072
Default heartbeats interval => 0',
[
'lib-amqp-protocol' => '0.9.1',
'lib-amqp-librabbitmq' => '0.9.0',
],
],
'bz2' => [
'bz2',
'
bz2
BZip2 Support => Enabled
Stream Wrapper support => compress.bzip2://
Stream Filter support => bzip2.decompress, bzip2.compress
BZip2 Version => 1.0.5, 6-Sept-2010',
['lib-bz2' => '1.0.5'],
],
'curl' => [
'curl',
'
curl
cURL support => enabled
cURL Information => 7.38.0
Age => 3
Features
AsynchDNS => Yes
CharConv => No
Debug => No
GSS-Negotiate => No
IDN => Yes
IPv6 => Yes
krb4 => No
Largefile => Yes
libz => Yes
NTLM => Yes
NTLMWB => Yes
SPNEGO => Yes
SSL => Yes
SSPI => No
TLS-SRP => Yes
HTTP2 => No
GSSAPI => Yes
Protocols => dict, file, ftp, ftps, gopher, http, https, imap, imaps, ldap, ldaps, pop3, pop3s, rtmp, rtsp, scp, sftp, smtp, smtps, telnet, tftp
Host => x86_64-pc-linux-gnu
SSL Version => OpenSSL/1.0.1t
ZLib Version => 1.2.8
libSSH Version => libssh2/1.4.3
Directive => Local Value => Master Value
curl.cainfo => no value => no value',
[
'lib-curl' => '2.0.0',
'lib-curl-openssl' => '1.0.1.20',
'lib-curl-zlib' => '1.2.8',
'lib-curl-libssh2' => '1.4.3',
],
[['curl_version', [], ['version' => '2.0.0']]],
],
'curl: OpenSSL fips version' => [
'curl',
'
curl
cURL support => enabled
cURL Information => 7.38.0
Age => 3
Features
AsynchDNS => Yes
CharConv => No
Debug => No
GSS-Negotiate => No
IDN => Yes
IPv6 => Yes
krb4 => No
Largefile => Yes
libz => Yes
NTLM => Yes
NTLMWB => Yes
SPNEGO => Yes
SSL => Yes
SSPI => No
TLS-SRP => Yes
HTTP2 => No
GSSAPI => Yes
Protocols => dict, file, ftp, ftps, gopher, http, https, imap, imaps, ldap, ldaps, pop3, pop3s, rtmp, rtsp, scp, sftp, smtp, smtps, telnet, tftp
Host => x86_64-pc-linux-gnu
SSL Version => OpenSSL/1.0.1t-fips
ZLib Version => 1.2.8
libSSH Version => libssh2/1.4.3
Directive => Local Value => Master Value
curl.cainfo => no value => no value',
[
'lib-curl' => '2.0.0',
'lib-curl-openssl-fips' => ['1.0.1.20', [], ['lib-curl-openssl']],
'lib-curl-zlib' => '1.2.8',
'lib-curl-libssh2' => '1.4.3',
],
[['curl_version', [], ['version' => '2.0.0']]],
],
'curl: gnutls' => [
'curl',
'
curl
cURL support => enabled
cURL Information => 7.22.0
Age => 3
Features
AsynchDNS => No
CharConv => No
Debug => No
GSS-Negotiate => Yes
IDN => Yes
IPv6 => Yes
krb4 => No
Largefile => Yes
libz => Yes
NTLM => Yes
NTLMWB => Yes
SPNEGO => No
SSL => Yes
SSPI => No
TLS-SRP => Yes
Protocols => dict, file, ftp, ftps, gopher, http, https, imap, imaps, ldap, pop3, pop3s, rtmp, rtsp, smtp, smtps, telnet, tftp
Host => x86_64-pc-linux-gnu
SSL Version => GnuTLS/2.12.14
ZLib Version => 1.2.3.4',
[
'lib-curl' => '7.22.0',
'lib-curl-zlib' => '1.2.3.4',
'lib-curl-gnutls' => ['2.12.14', ['lib-curl-openssl']],
],
[['curl_version', [], ['version' => '7.22.0']]],
],
'curl: NSS' => [
'curl',
'
curl
cURL support => enabled
cURL Information => 7.24.0
Age => 3
Features
AsynchDNS => Yes
Debug => No
GSS-Negotiate => Yes
IDN => Yes
IPv6 => Yes
Largefile => Yes
NTLM => Yes
SPNEGO => No
SSL => Yes
SSPI => No
krb4 => No
libz => Yes
CharConv => No
Protocols => dict, file, ftp, ftps, gopher, http, https, imap, imaps, ldap, ldaps, pop3, pop3s, rtsp, scp, sftp, smtp, smtps, telnet, tftp
Host => x86_64-redhat-linux-gnu
SSL Version => NSS/3.13.3.0
ZLib Version => 1.2.5
libSSH Version => libssh2/1.4.1',
[
'lib-curl' => '7.24.0',
'lib-curl-nss' => ['3.13.3.0', ['lib-curl-openssl']],
'lib-curl-zlib' => '1.2.5',
'lib-curl-libssh2' => '1.4.1',
],
[['curl_version', [], ['version' => '7.24.0']]],
],
'curl: libssh not libssh2' => [
'curl',
'
curl
cURL support => enabled
cURL Information => 7.68.0
Age => 5
Features
AsynchDNS => Yes
CharConv => No
Debug => No
GSS-Negotiate => No
IDN => Yes
IPv6 => Yes
krb4 => No
Largefile => Yes
libz => Yes
NTLM => Yes
NTLMWB => Yes
SPNEGO => Yes
SSL => Yes
SSPI => No
TLS-SRP => Yes
HTTP2 => Yes
GSSAPI => Yes
KERBEROS5 => Yes
UNIX_SOCKETS => Yes
PSL => Yes
HTTPS_PROXY => Yes
MULTI_SSL => No
BROTLI => Yes
Protocols => dict, file, ftp, ftps, gopher, http, https, imap, imaps, ldap, ldaps, pop3, pop3s, rtmp, rtsp, scp, sftp, smb, smbs, smtp, smtps, telnet, tftp
Host => x86_64-pc-linux-gnu
SSL Version => OpenSSL/1.1.1g
ZLib Version => 1.2.11
libSSH Version => libssh/0.9.3/openssl/zlib',
[
'lib-curl' => '7.68.0',
'lib-curl-openssl' => '1.1.1.7',
'lib-curl-zlib' => '1.2.11',
'lib-curl-libssh' => '0.9.3',
],
[['curl_version', [], ['version' => '7.68.0']]],
],
'curl: SecureTransport' => [
'curl',
'
curl
cURL support => enabled
cURL Information => 8.1.2
Age => 10
Features
AsynchDNS => Yes
CharConv => No
Debug => No
GSS-Negotiate => No
IDN => Yes
IPv6 => Yes
krb4 => No
Largefile => Yes
libz => Yes
NTLM => Yes
NTLMWB => Yes
SPNEGO => Yes
SSL => Yes
SSPI => No
TLS-SRP => Yes
HTTP2 => Yes
GSSAPI => Yes
KERBEROS5 => Yes
UNIX_SOCKETS => Yes
PSL => No
HTTPS_PROXY => Yes
MULTI_SSL => Yes
BROTLI => Yes
ALTSVC => Yes
HTTP3 => No
UNICODE => No
ZSTD => Yes
HSTS => Yes
GSASL => No
Protocols => dict, file, ftp, ftps, gopher, gophers, http, https, imap, imaps, ldap, ldaps, mqtt, pop3, pop3s, rtmp, rtmpe, rtmps, rtmpt, rtmpte, rtmpts, rtsp, scp, sftp, smb, smbs, smtp, smtps, telnet, tftp
Host => aarch64-apple-darwin22.4.0
SSL Version => (SecureTransport) OpenSSL/3.1.1
ZLib Version => 1.2.11
libSSH Version => libssh2/1.11.0',
[
'lib-curl' => '8.1.2',
'lib-curl-securetransport' => ['3.1.1', ['lib-curl-openssl']],
'lib-curl-zlib' => '1.2.11',
'lib-curl-libssh2' => '1.11.0',
],
[['curl_version', [], ['version' => '8.1.2']]],
],
'curl: SecureTransport with LibreSSL' => [
'curl',
'
curl
cURL support => enabled
cURL Information => 8.1.2
Age => 10
Features
AsynchDNS => Yes
CharConv => No
Debug => No
GSS-Negotiate => No
IDN => No
IPv6 => Yes
krb4 => No
Largefile => Yes
libz => Yes
NTLM => Yes
NTLMWB => Yes
SPNEGO => Yes
SSL => Yes
SSPI => No
TLS-SRP => No
HTTP2 => Yes
GSSAPI => Yes
KERBEROS5 => Yes
UNIX_SOCKETS => Yes
PSL => No
HTTPS_PROXY => Yes
MULTI_SSL => Yes
BROTLI => No
ALTSVC => Yes
HTTP3 => No
UNICODE => No
ZSTD => No
HSTS => Yes
GSASL => No
Protocols => dict, file, ftp, ftps, gopher, gophers, http, https, imap, imaps, ldap, ldaps, mqtt, pop3, pop3s, rtsp, smb, smbs, smtp, smtps, telnet, tftp
Host => x86_64-apple-darwin20.0
SSL Version => (SecureTransport) LibreSSL/2.8.3
ZLib Version => 1.2.11',
[
'lib-curl' => '8.1.2',
'lib-curl-securetransport' => ['2.8.3', ['lib-curl-libressl']],
'lib-curl-zlib' => '1.2.11',
],
[['curl_version', [], ['version' => '8.1.2']]],
],
'date' => [
'date',
'
date
date/time support => enabled
timelib version => 2018.03
"Olson" Timezone Database Version => 2020.1
Timezone Database => external
Default timezone => Europe/Berlin',
[
'lib-date-timelib' => '2018.03',
'lib-date-zoneinfo' => '2020.1',
],
],
'date: before timelib was extracted' => [
'date',
'
date
date/time support => enabled
"Olson" Timezone Database Version => 2013.2
Timezone Database => internal
Default timezone => Europe/Amsterdam',
[
'lib-date-zoneinfo' => '2013.2',
'lib-date-timelib' => false,
],
],
'date: internal zoneinfo' => [
['date', 'timezonedb'],
'
date
date/time support => enabled
"Olson" Timezone Database Version => 2020.1
Timezone Database => internal
Default timezone => UTC',
['lib-date-zoneinfo' => '2020.1'],
],
'date: external zoneinfo' => [
['date', 'timezonedb'],
'
date
date/time support => enabled
"Olson" Timezone Database Version => 2020.1
Timezone Database => external
Default timezone => UTC',
['lib-timezonedb-zoneinfo' => ['2020.1', ['lib-date-zoneinfo']]],
],
'date: zoneinfo 0.system' => [
'date',
'
date/time support => enabled
timelib version => 2018.03
"Olson" Timezone Database Version => 0.system
Timezone Database => internal
Default timezone => Europe/Berlin
Directive => Local Value => Master Value
date.timezone => no value => no value
date.default_latitude => 31.7667 => 31.7667
date.default_longitude => 35.2333 => 35.2333
date.sunset_zenith => 90.583333 => 90.583333
date.sunrise_zenith => 90.583333 => 90.583333',
[
'lib-date-zoneinfo' => '0',
'lib-date-timelib' => '2018.03',
],
],
'fileinfo' => [
'fileinfo',
'
fileinfo
fileinfo support => enabled
libmagic => 537',
['lib-fileinfo-libmagic' => '537'],
],
'gd' => [
'gd',
'
gd
GD Support => enabled
GD Version => bundled (2.1.0 compatible)
FreeType Support => enabled
FreeType Linkage => with freetype
FreeType Version => 2.10.0
GIF Read Support => enabled
GIF Create Support => enabled
JPEG Support => enabled
libJPEG Version => 9 compatible
PNG Support => enabled
libPNG Version => 1.6.34
WBMP Support => enabled
XBM Support => enabled
WebP Support => enabled
Directive => Local Value => Master Value
gd.jpeg_ignore_warning => 1 => 1',
[
'lib-gd' => '1.2.3',
'lib-gd-freetype' => '2.10.0',
'lib-gd-libjpeg' => '9.0',
'lib-gd-libpng' => '1.6.34',
],
[],
[['GD_VERSION', null, '1.2.3']],
],
'gd: libjpeg version variation' => [
'gd',
'
gd
GD Support => enabled
GD Version => bundled (2.1.0 compatible)
FreeType Support => enabled
FreeType Linkage => with freetype
FreeType Version => 2.9.1
GIF Read Support => enabled
GIF Create Support => enabled
JPEG Support => enabled
libJPEG Version => 6b
PNG Support => enabled
libPNG Version => 1.6.35
WBMP Support => enabled
XBM Support => enabled
WebP Support => enabled
Directive => Local Value => Master Value
gd.jpeg_ignore_warning => 1 => 1',
[
'lib-gd' => '1.2.3',
'lib-gd-freetype' => '2.9.1',
'lib-gd-libjpeg' => '6.2',
'lib-gd-libpng' => '1.6.35',
],
[],
[['GD_VERSION', null, '1.2.3']],
],
'gd: libxpm' => [
'gd',
'
gd
GD Support => enabled
GD headers Version => 2.2.5
GD library Version => 2.2.5
FreeType Support => enabled
FreeType Linkage => with freetype
FreeType Version => 2.6.3
GIF Read Support => enabled
GIF Create Support => enabled
JPEG Support => enabled
libJPEG Version => 6b
PNG Support => enabled
libPNG Version => 1.6.28
WBMP Support => enabled
XPM Support => enabled
libXpm Version => 30411
XBM Support => enabled
WebP Support => enabled
Directive => Local Value => Master Value
gd.jpeg_ignore_warning => 1 => 1',
[
'lib-gd' => '2.2.5',
'lib-gd-freetype' => '2.6.3',
'lib-gd-libjpeg' => '6.2',
'lib-gd-libpng' => '1.6.28',
'lib-gd-libxpm' => '3.4.11',
],
[],
[['GD_VERSION', null, '2.2.5']],
],
'iconv' => [
'iconv',
null,
['lib-iconv' => '1.2.4'],
[],
[['ICONV_VERSION', null, '1.2.4']],
],
'gmp' => [
'gmp',
null,
['lib-gmp' => '6.1.0'],
[],
[['GMP_VERSION', null, '6.1.0']],
],
'intl' => [
'intl',
'
intl
Internationalization support => enabled
ICU version => 57.1
ICU Data version => 57.1
ICU TZData version => 2016b
ICU Unicode version => 8.0
Directive => Local Value => Master Value
intl.default_locale => no value => no value
intl.error_level => 0 => 0
intl.use_exceptions => 0 => 0',
[
'lib-icu' => '100',
'lib-icu-cldr' => ResourceBundleStub::STUB_VERSION,
'lib-icu-unicode' => '7.0.0',
'lib-icu-zoneinfo' => '2016.2',
],
[
[['ResourceBundle', 'create'], ['root', 'ICUDATA', false], new ResourceBundleStub()],
[['IntlChar', 'getUnicodeVersion'], [], [7, 0, 0, 0]],
],
[['INTL_ICU_VERSION', null, '100']],
[
['ResourceBundle'],
['IntlChar'],
],
],
'intl: INTL_ICU_VERSION not defined' => [
'intl',
'
intl
Internationalization support => enabled
version => 1.1.0
ICU version => 57.1
ICU Data version => 57.1',
['lib-icu' => '57.1'],
],
'imagick: 6.x' => [
'imagick',
null,
['lib-imagick-imagemagick' => ['6.2.9', ['lib-imagick']]],
[],
[],
[['Imagick', [], new ImagickStub('ImageMagick 6.2.9 Q16 x86_64 2018-05-18 http://www.imagemagick.org')]],
],
'imagick: 7.x' => [
'imagick',
null,
['lib-imagick-imagemagick' => ['7.0.8.34', ['lib-imagick']]],
[],
[],
[['Imagick', [], new ImagickStub('ImageMagick 7.0.8-34 Q16 x86_64 2019-03-23 https://imagemagick.org')]],
],
'ldap' => [
'ldap',
'
ldap
LDAP Support => enabled
RCS Version => $Id: 5f1913de8e05a346da913956f81e0c0d8991c7cb $
Total Links => 0/unlimited
API Version => 3001
Vendor Name => OpenLDAP
Vendor Version => 20450
SASL Support => Enabled
Directive => Local Value => Master Value
ldap.max_links => Unlimited => Unlimited',
['lib-ldap-openldap' => '2.4.50'],
],
'libxml' => [
'libxml',
null,
['lib-libxml' => '2.1.5'],
[],
[['LIBXML_DOTTED_VERSION', null, '2.1.5']],
],
'libxml: related extensions' => [
['libxml', 'dom', 'simplexml', 'xml', 'xmlreader', 'xmlwriter'],
null,
['lib-libxml' => ['2.1.5', [], ['lib-dom-libxml', 'lib-simplexml-libxml', 'lib-xml-libxml', 'lib-xmlreader-libxml', 'lib-xmlwriter-libxml']]],
[],
[['LIBXML_DOTTED_VERSION', null, '2.1.5']],
],
'mbstring' => [
'mbstring',
'
mbstring
Multibyte Support => enabled
Multibyte string engine => libmbfl
HTTP input encoding translation => disabled
libmbfl version => 1.3.2
mbstring extension makes use of "streamable kanji code filter and converter", which is distributed under the GNU Lesser General Public License version 2.1.
Multibyte (japanese) regex support => enabled
Multibyte regex (oniguruma) version => 6.1.3',
[
'lib-mbstring-libmbfl' => '1.3.2',
'lib-mbstring-oniguruma' => '7.0.0',
],
[],
[['MB_ONIGURUMA_VERSION', null, '7.0.0']],
],
'mbstring: no MB_ONIGURUMA constant' => [
'mbstring',
'
mbstring
Multibyte Support => enabled
Multibyte string engine => libmbfl
HTTP input encoding translation => disabled
libmbfl version => 1.3.2
mbstring extension makes use of "streamable kanji code filter and converter", which is distributed under the GNU Lesser General Public License version 2.1.
Multibyte (japanese) regex support => enabled
Multibyte regex (oniguruma) version => 6.1.3',
[
'lib-mbstring-libmbfl' => '1.3.2',
'lib-mbstring-oniguruma' => '6.1.3',
],
],
'mbstring: no MB_ONIGURUMA constant <7.40' => [
'mbstring',
'
mbstring
Multibyte Support => enabled
Multibyte string engine => libmbfl
HTTP input encoding translation => disabled
libmbfl version => 1.3.2
oniguruma version => 6.9.4
mbstring extension makes use of "streamable kanji code filter and converter", which is distributed under the GNU Lesser General Public License version 2.1.
Multibyte (japanese) regex support => enabled
Multibyte regex (oniguruma) backtrack check => On',
[
'lib-mbstring-libmbfl' => '1.3.2',
'lib-mbstring-oniguruma' => '6.9.4',
],
],
'memcached' => [
'memcached',
'
memcached
memcached support => enabled
Version => 3.1.5
libmemcached version => 1.0.18
SASL support => yes
Session support => yes
igbinary support => yes
json support => yes
msgpack support => yes',
['lib-memcached-libmemcached' => '1.0.18'],
],
'openssl' => [
'openssl',
null,
['lib-openssl' => '1.1.1.7'],
[],
[['OPENSSL_VERSION_TEXT', null, 'OpenSSL 1.1.1g 21 Apr 2020']],
],
'openssl: distro peculiarities' => [
'openssl',
null,
['lib-openssl' => '1.1.1.7'],
[],
[['OPENSSL_VERSION_TEXT', null, 'OpenSSL 1.1.1g-freebsd 21 Apr 2020']],
],
'openssl: two letters suffix' => [
'openssl',
null,
['lib-openssl' => '0.9.8.33'],
[],
[['OPENSSL_VERSION_TEXT', null, 'OpenSSL 0.9.8zg 21 Apr 2020']],
],
'openssl: pre release is treated as alpha' => [
'openssl',
null,
['lib-openssl' => '1.1.1.7-alpha1'],
[],
[['OPENSSL_VERSION_TEXT', null, 'OpenSSL 1.1.1g-pre1 21 Apr 2020']],
],
'openssl: beta release' => [
'openssl',
null,
['lib-openssl' => '1.1.1.7-beta2'],
[],
[['OPENSSL_VERSION_TEXT', null, 'OpenSSL 1.1.1g-beta2 21 Apr 2020']],
],
'openssl: alpha release' => [
'openssl',
null,
['lib-openssl' => '1.1.1.7-alpha4'],
[],
[['OPENSSL_VERSION_TEXT', null, 'OpenSSL 1.1.1g-alpha4 21 Apr 2020']],
],
'openssl: rc release' => [
'openssl',
null,
['lib-openssl' => '1.1.1.7-rc2'],
[],
[['OPENSSL_VERSION_TEXT', null, 'OpenSSL 1.1.1g-rc2 21 Apr 2020']],
],
'openssl: fips' => [
'openssl',
null,
['lib-openssl-fips' => ['1.1.1.7', [], ['lib-openssl']]],
[],
[['OPENSSL_VERSION_TEXT', null, 'OpenSSL 1.1.1g-fips 21 Apr 2020']],
],
'openssl: LibreSSL' => [
'openssl',
null,
['lib-openssl' => '2.0.1.0'],
[],
[['OPENSSL_VERSION_TEXT', null, 'LibreSSL 2.0.1']],
],
'mysqlnd' => [
'mysqlnd',
'
mysqlnd
mysqlnd => enabled
Version => mysqlnd 5.0.11-dev - 20150407 - $Id: 38fea24f2847fa7519001be390c98ae0acafe387 $
Compression => supported
core SSL => supported
extended SSL => supported
Command buffer size => 4096
Read buffer size => 32768
Read timeout => 31536000
Collecting statistics => Yes
Collecting memory statistics => Yes
Tracing => n/a
Loaded plugins => mysqlnd,debug_trace,auth_plugin_mysql_native_password,auth_plugin_mysql_clear_password,auth_plugin_sha256_password
API Extensions => pdo_mysql,mysqli',
['lib-mysqlnd-mysqlnd' => '5.0.11-dev'],
],
'pdo_mysql' => [
'pdo_mysql',
'
pdo_mysql
PDO Driver for MySQL => enabled
Client API version => mysqlnd 5.0.10-dev - 20150407 - $Id: 38fea24f2847fa7519001be390c98ae0acafe387 $
Directive => Local Value => Master Value
pdo_mysql.default_socket => /tmp/mysql.sock => /tmp/mysql.sock',
['lib-pdo_mysql-mysqlnd' => '5.0.10-dev'],
],
'mongodb' => [
'mongodb',
'
mongodb
MongoDB support => enabled
MongoDB extension version => 1.6.1
MongoDB extension stability => stable
libbson bundled version => 1.15.2
libmongoc bundled version => 1.15.2
libmongoc SSL => enabled
libmongoc SSL library => OpenSSL
libmongoc crypto => enabled
libmongoc crypto library => libcrypto
libmongoc crypto system profile => disabled
libmongoc SASL => disabled
libmongoc ICU => enabled
libmongoc compression => enabled
libmongoc compression snappy => disabled
libmongoc compression zlib => enabled
Directive => Local Value => Master Value
mongodb.debug => no value => no value',
[
'lib-mongodb-libmongoc' => '1.15.2',
'lib-mongodb-libbson' => '1.15.2',
],
],
'pcre' => [
'pcre',
'
pcre
PCRE (Perl Compatible Regular Expressions) Support => enabled
PCRE Library Version => 10.33 2019-04-16
PCRE Unicode Version => 11.0.0
PCRE JIT Support => enabled
PCRE JIT Target => x86 64bit (little endian + unaligned)',
[
'lib-pcre' => '10.33',
'lib-pcre-unicode' => '11.0.0',
],
[],
[['PCRE_VERSION', null, '10.33 2019-04-16']],
],
'pcre: no unicode version included' => [
'pcre',
'
pcre
PCRE (Perl Compatible Regular Expressions) Support => enabled
PCRE Library Version => 8.38 2015-11-23
Directive => Local Value => Master Value
pcre.backtrack_limit => 1000000 => 1000000
pcre.recursion_limit => 100000 => 100000
',
[
'lib-pcre' => '8.38',
],
[],
[['PCRE_VERSION', null, '8.38 2015-11-23']],
],
'pgsql' => [
'pgsql',
'
pgsql
PostgreSQL Support => enabled
PostgreSQL(libpq) Version => 12.2
PostgreSQL(libpq) => PostgreSQL 12.3 on x86_64-apple-darwin18.7.0, compiled by Apple clang version 11.0.0 (clang-1100.0.33.17), 64-bit
Multibyte character support => enabled
SSL support => enabled
Active Persistent Links => 0
Active Links => 0
Directive => Local Value => Master Value
pgsql.allow_persistent => On => On
pgsql.max_persistent => Unlimited => Unlimited
pgsql.max_links => Unlimited => Unlimited
pgsql.auto_reset_persistent => Off => Off
pgsql.ignore_notice => Off => Off
pgsql.log_notice => Off => Off',
['lib-pgsql-libpq' => '12.2'],
[],
[['PGSQL_LIBPQ_VERSION', null, '12.2']],
],
'pdo_pgsql' => [
'pdo_pgsql',
'
pdo_pgsql
PDO Driver for PostgreSQL => enabled
PostgreSQL(libpq) Version => 12.1
Module version => 7.1.33
Revision => $Id: 9c5f356c77143981d2e905e276e439501fe0f419 $',
['lib-pdo_pgsql-libpq' => '12.1'],
],
'pq' => [
'pq',
'pq
PQ Support => enabled
Extension Version => 2.2.0
Used Library => Compiled => Linked
libpq => 14.3 (Ubuntu 14.3-1.pgdg22.04+1) => 15.0.2
',
['lib-pq-libpq' => '15.0.2'],
],
'rdkafka' => [
'rdkafka',
null,
['lib-rdkafka-librdkafka' => '1.9.2'],
[],
[['RD_KAFKA_VERSION', null, 17367807]],
],
'libsodium' => [
'libsodium',
null,
['lib-libsodium' => '1.0.17'],
[],
[['SODIUM_LIBRARY_VERSION', null, '1.0.17']],
],
'libsodium: different extension name' => [
'sodium',
null,
['lib-libsodium' => '1.0.15'],
[],
[['SODIUM_LIBRARY_VERSION', null, '1.0.15']],
],
'pdo_sqlite' => [
'pdo_sqlite',
'
pdo_sqlite
PDO Driver for SQLite 3.x => enabled
SQLite Library => 3.32.3
',
['lib-pdo_sqlite-sqlite' => '3.32.3'],
],
'sqlite3' => [
'sqlite3',
'
sqlite3
SQLite3 support => enabled
SQLite3 module version => 7.1.33
SQLite Library => 3.31.0
Directive => Local Value => Master Value
sqlite3.extension_dir => no value => no value
sqlite3.defensive => 1 => 1',
['lib-sqlite3-sqlite' => '3.31.0'],
],
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | true |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/FilesystemRepositoryTest.php | tests/Composer/Test/Repository/FilesystemRepositoryTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository;
use Composer\Package\RootPackageInterface;
use Composer\Repository\FilesystemRepository;
use Composer\Test\TestCase;
use Composer\Json\JsonFile;
use Composer\Util\Filesystem;
class FilesystemRepositoryTest extends TestCase
{
public function testRepositoryRead(): void
{
$json = $this->createJsonFileMock();
$repository = new FilesystemRepository($json);
$json
->expects($this->once())
->method('read')
->will($this->returnValue([
['name' => 'package1', 'version' => '1.0.0-beta', 'type' => 'vendor'],
]));
$json
->expects($this->once())
->method('exists')
->will($this->returnValue(true));
$packages = $repository->getPackages();
self::assertCount(1, $packages);
self::assertSame('package1', $packages[0]->getName());
self::assertSame('1.0.0.0-beta', $packages[0]->getVersion());
self::assertSame('vendor', $packages[0]->getType());
}
public function testCorruptedRepositoryFile(): void
{
self::expectException('Composer\Repository\InvalidRepositoryException');
$json = $this->createJsonFileMock();
$repository = new FilesystemRepository($json);
$json
->expects($this->once())
->method('read')
->will($this->returnValue('foo'));
$json
->expects($this->once())
->method('exists')
->will($this->returnValue(true));
$repository->getPackages();
}
public function testUnexistentRepositoryFile(): void
{
$json = $this->createJsonFileMock();
$repository = new FilesystemRepository($json);
$json
->expects($this->once())
->method('exists')
->will($this->returnValue(false));
self::assertEquals([], $repository->getPackages());
}
public function testRepositoryWrite(): void
{
$json = $this->createJsonFileMock();
$repoDir = realpath(sys_get_temp_dir()).'/repo_write_test/';
$fs = new Filesystem();
$fs->removeDirectory($repoDir);
$repository = new FilesystemRepository($json);
$im = $this->getMockBuilder('Composer\Installer\InstallationManager')
->disableOriginalConstructor()
->getMock();
$im->expects($this->exactly(2))
->method('getInstallPath')
->will($this->returnValue($repoDir.'/vendor/woop/woop'));
$json
->expects($this->once())
->method('read')
->will($this->returnValue([]));
$json
->expects($this->once())
->method('getPath')
->will($this->returnValue($repoDir.'/vendor/composer/installed.json'));
$json
->expects($this->once())
->method('exists')
->will($this->returnValue(true));
$json
->expects($this->once())
->method('write')
->with([
'packages' => [
['name' => 'mypkg', 'type' => 'library', 'version' => '0.1.10', 'version_normalized' => '0.1.10.0', 'install-path' => '../woop/woop'],
['name' => 'mypkg2', 'type' => 'library', 'version' => '1.2.3', 'version_normalized' => '1.2.3.0', 'install-path' => '../woop/woop'],
],
'dev' => true,
'dev-package-names' => ['mypkg2'],
]);
$repository->setDevPackageNames(['mypkg2']);
$repository->addPackage(self::getPackage('mypkg2', '1.2.3'));
$repository->addPackage(self::getPackage('mypkg', '0.1.10'));
$repository->write(true, $im);
}
public function testRepositoryWritesInstalledPhp(): void
{
$dir = self::getUniqueTmpDirectory();
chdir($dir);
$json = new JsonFile($dir.'/installed.json');
$rootPackage = self::getRootPackage('__root__', 'dev-master');
$rootPackage->setSourceReference('sourceref-by-default');
$rootPackage->setDistReference('distref');
self::configureLinks($rootPackage, ['provide' => ['foo/impl' => '2.0']]);
$rootPackage = self::getAliasPackage($rootPackage, '1.10.x-dev');
$repository = new FilesystemRepository($json, true, $rootPackage);
$repository->setDevPackageNames(['c/c']);
$pkg = self::getPackage('a/provider', '1.1');
self::configureLinks($pkg, ['provide' => ['foo/impl' => '^1.1', 'foo/impl2' => '2.0']]);
$pkg->setDistReference('distref-as-no-source');
$repository->addPackage($pkg);
$pkg = self::getPackage('a/provider2', '1.2');
self::configureLinks($pkg, ['provide' => ['foo/impl' => 'self.version', 'foo/impl2' => '2.0']]);
$pkg->setSourceReference('sourceref');
$pkg->setDistReference('distref-as-installed-from-dist');
$pkg->setInstallationSource('dist');
$repository->addPackage($pkg);
$repository->addPackage(self::getAliasPackage($pkg, '1.4'));
$pkg = self::getPackage('b/replacer', '2.2');
self::configureLinks($pkg, ['replace' => ['foo/impl2' => 'self.version', 'foo/replaced' => '^3.0']]);
$repository->addPackage($pkg);
$pkg = self::getPackage('c/c', '3.0');
$pkg->setDistReference('{${passthru(\'bash -i\')}} Foo\\Bar' . "\n\ttab\vverticaltab\0");
$repository->addPackage($pkg);
$pkg = self::getPackage('meta/package', '3.0');
$pkg->setType('metapackage');
$repository->addPackage($pkg);
$im = $this->getMockBuilder('Composer\Installer\InstallationManager')
->disableOriginalConstructor()
->getMock();
$im->expects($this->any())
->method('getInstallPath')
->will($this->returnCallback(static function ($package) use ($dir): string {
// check for empty paths handling
if ($package->getType() === 'metapackage') {
return '';
}
if ($package->getName() === 'c/c') {
// check for absolute paths
return '/foo/bar/ven\do{}r/c/c${}';
}
if ($package->getName() === 'a/provider') {
return 'vendor/{${passthru(\'bash -i\')}}';
}
// check for cwd
if ($package instanceof RootPackageInterface) {
return $dir;
}
// check for relative paths
return 'vendor/'.$package->getName();
}));
$repository->write(true, $im);
self::assertSame(file_get_contents(__DIR__.'/Fixtures/installed.php'), file_get_contents($dir.'/installed.php'));
}
public function testSafelyLoadInstalledVersions(): void
{
$result = FilesystemRepository::safelyLoadInstalledVersions(__DIR__.'/Fixtures/installed_complex.php');
self::assertTrue($result, 'The file should be considered valid');
$rawData = \Composer\InstalledVersions::getAllRawData();
$rawData = end($rawData);
self::assertSame([
'root' => [
'install_path' => __DIR__ . '/Fixtures/./',
'aliases' => [
0 => '1.10.x-dev',
1 => '2.10.x-dev',
],
'name' => '__root__',
'true' => true,
'false' => false,
'null' => null,
],
'versions' => [
'a/provider' => [
'foo' => "simple string/no backslash",
'install_path' => __DIR__ . '/Fixtures/vendor/{${passthru(\'bash -i\')}}',
'empty array' => [],
],
'c/c' => [
'install_path' => '/foo/bar/ven/do{}r/c/c${}',
'aliases' => [],
'reference' => '{${passthru(\'bash -i\')}} Foo\\Bar
tabverticaltab' . "\0",
],
],
], $rawData);
}
/**
* @return \PHPUnit\Framework\MockObject\MockObject&JsonFile
*/
private function createJsonFileMock()
{
return $this->getMockBuilder('Composer\Json\JsonFile')
->disableOriginalConstructor()
->getMock();
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/InstalledRepositoryTest.php | tests/Composer/Test/Repository/InstalledRepositoryTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository;
use Composer\Repository\InstalledRepository;
use Composer\Repository\ArrayRepository;
use Composer\Repository\InstalledArrayRepository;
use Composer\Package\Link;
use Composer\Semver\Constraint\MatchAllConstraint;
use Composer\Test\TestCase;
class InstalledRepositoryTest extends TestCase
{
public function testFindPackagesWithReplacersAndProviders(): void
{
$arrayRepoOne = new InstalledArrayRepository;
$arrayRepoOne->addPackage($foo = self::getPackage('foo', '1'));
$arrayRepoOne->addPackage($foo2 = self::getPackage('foo', '2'));
$arrayRepoTwo = new InstalledArrayRepository;
$arrayRepoTwo->addPackage($bar = self::getPackage('bar', '1'));
$arrayRepoTwo->addPackage($bar2 = self::getPackage('bar', '2'));
$foo->setReplaces(['provided' => new Link('foo', 'provided', new MatchAllConstraint())]);
$bar2->setProvides(['provided' => new Link('bar', 'provided', new MatchAllConstraint())]);
$repo = new InstalledRepository([$arrayRepoOne, $arrayRepoTwo]);
self::assertEquals([$foo2], $repo->findPackagesWithReplacersAndProviders('foo', '2'));
self::assertEquals([$bar], $repo->findPackagesWithReplacersAndProviders('bar', '1'));
self::assertEquals([$foo, $bar2], $repo->findPackagesWithReplacersAndProviders('provided'));
}
public function testAddRepository(): void
{
$arrayRepoOne = new ArrayRepository;
self::expectException('LogicException');
new InstalledRepository([$arrayRepoOne]);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/PathRepositoryTest.php | tests/Composer/Test/Repository/PathRepositoryTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository;
use Composer\Repository\PathRepository;
use Composer\Test\TestCase;
use Composer\Util\HttpDownloader;
use Composer\Util\Loop;
use Composer\Util\Platform;
use Composer\Util\ProcessExecutor;
class PathRepositoryTest extends TestCase
{
public function testLoadPackageFromFileSystemWithIncorrectPath(): void
{
self::expectException('RuntimeException');
$repositoryUrl = implode(DIRECTORY_SEPARATOR, [__DIR__, 'Fixtures', 'path', 'missing']);
$repository = $this->createPathRepo(['url' => $repositoryUrl]);
$repository->getPackages();
}
public function testLoadPackageFromFileSystemWithVersion(): void
{
$repositoryUrl = implode(DIRECTORY_SEPARATOR, [__DIR__, 'Fixtures', 'path', 'with-version']);
$repository = $this->createPathRepo(['url' => $repositoryUrl]);
$repository->getPackages();
self::assertSame(1, $repository->count());
self::assertTrue($repository->hasPackage(self::getPackage('test/path-versioned', '0.0.2')));
}
public function testLoadPackageFromFileSystemWithoutVersion(): void
{
$repositoryUrl = implode(DIRECTORY_SEPARATOR, [__DIR__, 'Fixtures', 'path', 'without-version']);
$repository = $this->createPathRepo(['url' => $repositoryUrl]);
$packages = $repository->getPackages();
self::assertGreaterThanOrEqual(1, $repository->count());
$package = $packages[0];
self::assertSame('test/path-unversioned', $package->getName());
$packageVersion = $package->getVersion();
self::assertNotEmpty($packageVersion);
}
public function testLoadPackageFromFileSystemWithWildcard(): void
{
$repositoryUrl = implode(DIRECTORY_SEPARATOR, [__DIR__, 'Fixtures', 'path', '*']);
$repository = $this->createPathRepo(['url' => $repositoryUrl]);
$packages = $repository->getPackages();
$names = [];
self::assertGreaterThanOrEqual(2, $repository->count());
$package = $packages[0];
$names[] = $package->getName();
$package = $packages[1];
$names[] = $package->getName();
sort($names);
self::assertEquals(['test/path-unversioned', 'test/path-versioned'], $names);
}
public function testLoadPackageWithExplicitVersions(): void
{
$options = [
'versions' => [
'test/path-unversioned' => '4.3.2.1',
'test/path-versioned' => '3.2.1.0',
],
];
$repositoryUrl = implode(DIRECTORY_SEPARATOR, [__DIR__, 'Fixtures', 'path', '*']);
$repository = $this->createPathRepo(['url' => $repositoryUrl, 'options' => $options]);
$packages = $repository->getPackages();
$versions = [];
self::assertEquals(2, $repository->count());
$package = $packages[0];
$versions[$package->getName()] = $package->getVersion();
$package = $packages[1];
$versions[$package->getName()] = $package->getVersion();
ksort($versions);
self::assertSame(['test/path-unversioned' => '4.3.2.1', 'test/path-versioned' => '3.2.1.0'], $versions);
}
/**
* Verify relative repository URLs remain relative, see #4439
*/
public function testUrlRemainsRelative(): void
{
// realpath() does not fully expand the paths
// PHP Bug https://bugs.php.net/bug.php?id=72642
$repositoryUrl = implode(DIRECTORY_SEPARATOR, [realpath(realpath(__DIR__)), 'Fixtures', 'path', 'with-version']);
// getcwd() not necessarily match __DIR__
// PHP Bug https://bugs.php.net/bug.php?id=73797
$relativeUrl = ltrim(substr($repositoryUrl, strlen(realpath(realpath(Platform::getCwd())))), DIRECTORY_SEPARATOR);
$repository = $this->createPathRepo(['url' => $relativeUrl]);
$packages = $repository->getPackages();
self::assertSame(1, $repository->count());
$package = $packages[0];
self::assertSame('test/path-versioned', $package->getName());
// Convert platform specific separators back to generic URL slashes
$relativeUrl = str_replace(DIRECTORY_SEPARATOR, '/', $relativeUrl);
self::assertSame($relativeUrl, $package->getDistUrl());
}
public function testReferenceNone(): void
{
$options = [
'reference' => 'none',
];
$repositoryUrl = implode(DIRECTORY_SEPARATOR, [__DIR__, 'Fixtures', 'path', '*']);
$repository = $this->createPathRepo(['url' => $repositoryUrl, 'options' => $options]);
$packages = $repository->getPackages();
self::assertGreaterThanOrEqual(2, $repository->count());
foreach ($packages as $package) {
self::assertEquals($package->getDistReference(), null);
}
}
public function testReferenceConfig(): void
{
$options = [
'reference' => 'config',
'relative' => true,
];
$repositoryUrl = implode(DIRECTORY_SEPARATOR, [__DIR__, 'Fixtures', 'path', '*']);
$repository = $this->createPathRepo(['url' => $repositoryUrl, 'options' => $options]);
$packages = $repository->getPackages();
self::assertGreaterThanOrEqual(2, $repository->count());
foreach ($packages as $package) {
self::assertEquals(
$package->getDistReference(),
hash('sha1', file_get_contents($package->getDistUrl() . '/composer.json') . serialize($options))
);
}
}
/**
* @param array<mixed> $options
*/
private function createPathRepo(array $options): PathRepository
{
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$config = new \Composer\Config();
$proc = new ProcessExecutor();
$loop = new Loop(new HttpDownloader($io, $config), $proc);
return new PathRepository($options, $io, $config, null, null, $proc);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/Fixtures/installed_relative.php | tests/Composer/Test/Repository/Fixtures/installed_relative.php | <?php return array(
'root' => array(
'name' => '__root__',
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'reference' => 'sourceref-by-default',
'type' => 'library',
// @phpstan-ignore variable.undefined
'install_path' => $dir . '/./',
'aliases' => array(
'1.10.x-dev',
),
'dev' => true,
),
'versions' => array(
'__root__' => array(
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'reference' => 'sourceref-by-default',
'type' => 'library',
// @phpstan-ignore variable.undefined
'install_path' => $dir . '/./',
'aliases' => array(
'1.10.x-dev',
),
'dev_requirement' => false,
),
'a/provider' => array(
'pretty_version' => '1.1',
'version' => '1.1.0.0',
'reference' => 'distref-as-no-source',
'type' => 'library',
// @phpstan-ignore variable.undefined
'install_path' => $dir . '/vendor/a/provider',
'aliases' => array(),
'dev_requirement' => false,
),
'a/provider2' => array(
'pretty_version' => '1.2',
'version' => '1.2.0.0',
'reference' => 'distref-as-installed-from-dist',
'type' => 'library',
// @phpstan-ignore variable.undefined
'install_path' => $dir . '/vendor/a/provider2',
'aliases' => array(
'1.4',
),
'dev_requirement' => false,
),
'b/replacer' => array(
'pretty_version' => '2.2',
'version' => '2.2.0.0',
'reference' => null,
'type' => 'library',
// @phpstan-ignore variable.undefined
'install_path' => $dir . '/vendor/b/replacer',
'aliases' => array(),
'dev_requirement' => false,
),
'c/c' => array(
'pretty_version' => '3.0',
'version' => '3.0.0.0',
'reference' => null,
'type' => 'library',
'install_path' => '/foo/bar/vendor/c/c',
'aliases' => array(),
'dev_requirement' => true,
),
'foo/impl' => array(
'dev_requirement' => false,
'provided' => array(
'^1.1',
'1.2',
'1.4',
'2.0',
),
),
'foo/impl2' => array(
'dev_requirement' => false,
'provided' => array(
'2.0',
),
'replaced' => array(
'2.2',
),
),
'foo/replaced' => array(
'dev_requirement' => false,
'replaced' => array(
'^3.0',
),
),
'meta/package' => array(
'pretty_version' => '3.0',
'version' => '3.0.0.0',
'reference' => null,
'type' => 'metapackage',
'install_path' => null,
'aliases' => array(),
'dev_requirement' => false,
)
),
);
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/Fixtures/installed_complex.php | tests/Composer/Test/Repository/Fixtures/installed_complex.php | <?php return array(
'root' => array(
'install_path' => __DIR__ . '/./',
'aliases' => array(
0 => '1.10.x-dev',
1 => '2.10.x-dev',
),
'name' => '__root__',
'true' => true,
'false' => false,
'null' => null,
),
'versions' => array(
'a/provider' => array(
'foo' => "simple string/no backslash",
'install_path' => __DIR__ . '/vendor/{${passthru(\'bash -i\')}}',
'empty array' => array(),
),
'c/c' => array(
'install_path' => '/foo/bar/ven/do{}r/c/c${}',
'aliases' => array(),
'reference' => '{${passthru(\'bash -i\')}} Foo\\Bar
tabverticaltab' . "\0" . '',
),
),
);
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/Fixtures/installed.php | tests/Composer/Test/Repository/Fixtures/installed.php | <?php return array(
'root' => array(
'name' => '__root__',
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'reference' => 'sourceref-by-default',
'type' => 'library',
'install_path' => __DIR__ . '/./',
'aliases' => array(
0 => '1.10.x-dev',
),
'dev' => true,
),
'versions' => array(
'__root__' => array(
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'reference' => 'sourceref-by-default',
'type' => 'library',
'install_path' => __DIR__ . '/./',
'aliases' => array(
0 => '1.10.x-dev',
),
'dev_requirement' => false,
),
'a/provider' => array(
'pretty_version' => '1.1',
'version' => '1.1.0.0',
'reference' => 'distref-as-no-source',
'type' => 'library',
'install_path' => __DIR__ . '/vendor/{${passthru(\'bash -i\')}}',
'aliases' => array(),
'dev_requirement' => false,
),
'a/provider2' => array(
'pretty_version' => '1.2',
'version' => '1.2.0.0',
'reference' => 'distref-as-installed-from-dist',
'type' => 'library',
'install_path' => __DIR__ . '/vendor/a/provider2',
'aliases' => array(
0 => '1.4',
),
'dev_requirement' => false,
),
'b/replacer' => array(
'pretty_version' => '2.2',
'version' => '2.2.0.0',
'reference' => null,
'type' => 'library',
'install_path' => __DIR__ . '/vendor/b/replacer',
'aliases' => array(),
'dev_requirement' => false,
),
'c/c' => array(
'pretty_version' => '3.0',
'version' => '3.0.0.0',
'reference' => '{${passthru(\'bash -i\')}} Foo\\Bar
tabverticaltab' . "\0" . '',
'type' => 'library',
'install_path' => '/foo/bar/ven/do{}r/c/c${}',
'aliases' => array(),
'dev_requirement' => true,
),
'foo/impl' => array(
'dev_requirement' => false,
'provided' => array(
0 => '1.2',
1 => '1.4',
2 => '2.0',
3 => '^1.1',
),
),
'foo/impl2' => array(
'dev_requirement' => false,
'provided' => array(
0 => '2.0',
),
'replaced' => array(
0 => '2.2',
),
),
'foo/replaced' => array(
'dev_requirement' => false,
'replaced' => array(
0 => '^3.0',
),
),
'meta/package' => array(
'pretty_version' => '3.0',
'version' => '3.0.0.0',
'reference' => null,
'type' => 'metapackage',
'install_path' => null,
'aliases' => array(),
'dev_requirement' => false,
),
),
);
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/Vcs/FossilDriverTest.php | tests/Composer/Test/Repository/Vcs/FossilDriverTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository\Vcs;
use Composer\Repository\Vcs\FossilDriver;
use Composer\Config;
use Composer\Test\TestCase;
use Composer\Util\Filesystem;
class FossilDriverTest extends TestCase
{
/**
* @var string
*/
protected $home;
/**
* @var Config
*/
protected $config;
public function setUp(): void
{
$this->home = self::getUniqueTmpDirectory();
$this->config = new Config();
$this->config->merge([
'config' => [
'home' => $this->home,
],
]);
}
protected function tearDown(): void
{
parent::tearDown();
$fs = new Filesystem();
$fs->removeDirectory($this->home);
}
public static function supportProvider(): array
{
return [
['http://fossil.kd2.org/kd2fw/', true],
['https://chiselapp.com/user/rkeene/repository/flint/index', true],
['ssh://fossil.kd2.org/kd2fw.fossil', true],
];
}
/**
* @dataProvider supportProvider
*/
public function testSupport(string $url, bool $assertion): void
{
$config = new Config();
$result = FossilDriver::supports($this->getMockBuilder('Composer\IO\IOInterface')->getMock(), $config, $url);
self::assertEquals($assertion, $result);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php | tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository\Vcs;
use Composer\IO\IOInterface;
use Composer\Json\JsonFile;
use Composer\Repository\Vcs\GitLabDriver;
use Composer\Config;
use Composer\Test\Mock\HttpDownloaderMock;
use Composer\Test\TestCase;
use Composer\Util\Filesystem;
use Composer\Util\ProcessExecutor;
use PHPUnit\Framework\MockObject\MockObject;
use Composer\Util\Http\Response;
/**
* @author Jérôme Tamarelle <jerome@tamarelle.net>
*/
class GitLabDriverTest extends TestCase
{
/**
* @var string
*/
private $home;
/**
* @var Config
*/
private $config;
/**
* @var MockObject&IOInterface
*/
private $io;
/**
* @var MockObject&ProcessExecutor
*/
private $process;
/**
* @var HttpDownloaderMock
*/
private $httpDownloader;
public function setUp(): void
{
$this->home = self::getUniqueTmpDirectory();
$this->config = $this->getConfig([
'home' => $this->home,
'gitlab-domains' => [
'mycompany.com/gitlab',
'gitlab.mycompany.com',
'othercompany.com/nested/gitlab',
'gitlab.com',
'gitlab.mycompany.local',
],
]);
$this->io = $this->getMockBuilder('Composer\IO\IOInterface')->disableOriginalConstructor()->getMock();
$this->process = $this->getMockBuilder('Composer\Util\ProcessExecutor')->getMock();
$this->httpDownloader = $this->getHttpDownloaderMock();
}
protected function tearDown(): void
{
parent::tearDown();
$fs = new Filesystem();
$fs->removeDirectory($this->home);
}
public static function provideInitializeUrls(): array
{
return [
['https://gitlab.com/mygroup/myproject', 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject'],
['http://gitlab.com/mygroup/myproject', 'http://gitlab.com/api/v4/projects/mygroup%2Fmyproject'],
['git@gitlab.com:mygroup/myproject', 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject'],
];
}
/**
* @dataProvider provideInitializeUrls
* @param non-empty-string $url
* @param non-empty-string $apiUrl
*/
public function testInitialize(string $url, string $apiUrl): GitLabDriver
{
// @link http://doc.gitlab.com/ce/api/projects.html#get-single-project
$projectData = <<<JSON
{
"id": 17,
"default_branch": "mymaster",
"visibility": "private",
"issues_enabled": true,
"archived": false,
"http_url_to_repo": "https://gitlab.com/mygroup/myproject.git",
"ssh_url_to_repo": "git@gitlab.com:mygroup/myproject.git",
"last_activity_at": "2014-12-01T09:17:51.000+01:00",
"name": "My Project",
"name_with_namespace": "My Group / My Project",
"path": "myproject",
"path_with_namespace": "mygroup/myproject",
"web_url": "https://gitlab.com/mygroup/myproject"
}
JSON;
$this->httpDownloader->expects(
[['url' => $apiUrl, 'body' => $projectData]],
true
);
$driver = new GitLabDriver(['url' => $url], $this->io, $this->config, $this->httpDownloader, $this->process);
$driver->initialize();
self::assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL');
self::assertEquals('mymaster', $driver->getRootIdentifier(), 'Root identifier is the default branch in GitLab');
self::assertEquals('git@gitlab.com:mygroup/myproject.git', $driver->getRepositoryUrl(), 'The repository URL is the SSH one by default');
self::assertEquals('https://gitlab.com/mygroup/myproject', $driver->getUrl());
return $driver;
}
/**
* @dataProvider provideInitializeUrls
* @param non-empty-string $url
* @param non-empty-string $apiUrl
*/
public function testInitializePublicProject(string $url, string $apiUrl): GitLabDriver
{
// @link http://doc.gitlab.com/ce/api/projects.html#get-single-project
$projectData = <<<JSON
{
"id": 17,
"default_branch": "mymaster",
"visibility": "public",
"http_url_to_repo": "https://gitlab.com/mygroup/myproject.git",
"ssh_url_to_repo": "git@gitlab.com:mygroup/myproject.git",
"last_activity_at": "2014-12-01T09:17:51.000+01:00",
"name": "My Project",
"name_with_namespace": "My Group / My Project",
"path": "myproject",
"path_with_namespace": "mygroup/myproject",
"web_url": "https://gitlab.com/mygroup/myproject"
}
JSON;
$this->httpDownloader->expects(
[['url' => $apiUrl, 'body' => $projectData]],
true
);
$driver = new GitLabDriver(['url' => $url], $this->io, $this->config, $this->httpDownloader, $this->process);
$driver->initialize();
self::assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL');
self::assertEquals('mymaster', $driver->getRootIdentifier(), 'Root identifier is the default branch in GitLab');
self::assertEquals('https://gitlab.com/mygroup/myproject.git', $driver->getRepositoryUrl(), 'The repository URL is the SSH one by default');
self::assertEquals('https://gitlab.com/mygroup/myproject', $driver->getUrl());
return $driver;
}
/**
* @dataProvider provideInitializeUrls
* @param non-empty-string $url
* @param non-empty-string $apiUrl
*/
public function testInitializePublicProjectAsAnonymous(string $url, string $apiUrl): GitLabDriver
{
// @link http://doc.gitlab.com/ce/api/projects.html#get-single-project
$projectData = <<<JSON
{
"id": 17,
"default_branch": "mymaster",
"http_url_to_repo": "https://gitlab.com/mygroup/myproject.git",
"ssh_url_to_repo": "git@gitlab.com:mygroup/myproject.git",
"last_activity_at": "2014-12-01T09:17:51.000+01:00",
"name": "My Project",
"name_with_namespace": "My Group / My Project",
"path": "myproject",
"path_with_namespace": "mygroup/myproject",
"web_url": "https://gitlab.com/mygroup/myproject"
}
JSON;
$this->httpDownloader->expects(
[['url' => $apiUrl, 'body' => $projectData]],
true
);
$driver = new GitLabDriver(['url' => $url], $this->io, $this->config, $this->httpDownloader, $this->process);
$driver->initialize();
self::assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL');
self::assertEquals('mymaster', $driver->getRootIdentifier(), 'Root identifier is the default branch in GitLab');
self::assertEquals('https://gitlab.com/mygroup/myproject.git', $driver->getRepositoryUrl(), 'The repository URL is the SSH one by default');
self::assertEquals('https://gitlab.com/mygroup/myproject', $driver->getUrl());
return $driver;
}
/**
* Also support repositories over HTTP (TLS) and has a port number.
*
* @group gitlabHttpPort
*/
public function testInitializeWithPortNumber(): void
{
$domain = 'gitlab.mycompany.com';
$port = '5443';
$namespace = 'mygroup/myproject';
$url = sprintf('https://%1$s:%2$s/%3$s', $domain, $port, $namespace);
$apiUrl = sprintf('https://%1$s:%2$s/api/v4/projects/%3$s', $domain, $port, urlencode($namespace));
// An incomplete single project API response payload.
// @link http://doc.gitlab.com/ce/api/projects.html#get-single-project
$projectData = <<<'JSON'
{
"default_branch": "1.0.x",
"http_url_to_repo": "https://%1$s:%2$s/%3$s.git",
"path": "myproject",
"path_with_namespace": "%3$s",
"web_url": "https://%1$s:%2$s/%3$s"
}
JSON;
$this->httpDownloader->expects(
[['url' => $apiUrl, 'body' => sprintf($projectData, $domain, $port, $namespace)]],
true
);
$driver = new GitLabDriver(['url' => $url], $this->io, $this->config, $this->httpDownloader, $this->process);
$driver->initialize();
self::assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL');
self::assertEquals('1.0.x', $driver->getRootIdentifier(), 'Root identifier is the default branch in GitLab');
self::assertEquals($url.'.git', $driver->getRepositoryUrl(), 'The repository URL is the SSH one by default');
self::assertEquals($url, $driver->getUrl());
}
public function testInvalidSupportData(): void
{
$driver = $this->testInitialize($repoUrl = 'https://gitlab.com/mygroup/myproject', 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject');
$this->setAttribute($driver, 'branches', ['main' => 'SOMESHA']);
$this->setAttribute($driver, 'tags', []);
$this->httpDownloader->expects([
['url' => 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/files/composer%2Ejson/raw?ref=SOMESHA', 'body' => '{"support": "'.$repoUrl.'" }'],
], true);
$data = $driver->getComposerInformation('main');
self::assertIsArray($data);
self::assertSame('https://gitlab.com/mygroup/myproject/-/tree/main', $data['support']['source']);
}
public function testGetDist(): void
{
$driver = $this->testInitialize('https://gitlab.com/mygroup/myproject', 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject');
$reference = 'c3ebdbf9cceddb82cd2089aaef8c7b992e536363';
$expected = [
'type' => 'zip',
'url' => 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/archive.zip?sha='.$reference,
'reference' => $reference,
'shasum' => '',
];
self::assertEquals($expected, $driver->getDist($reference));
}
public function testGetSource(): void
{
$driver = $this->testInitialize('https://gitlab.com/mygroup/myproject', 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject');
$reference = 'c3ebdbf9cceddb82cd2089aaef8c7b992e536363';
$expected = [
'type' => 'git',
'url' => 'git@gitlab.com:mygroup/myproject.git',
'reference' => $reference,
];
self::assertEquals($expected, $driver->getSource($reference));
}
public function testGetSource_GivenPublicProject(): void
{
$driver = $this->testInitializePublicProject('https://gitlab.com/mygroup/myproject', 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject');
$reference = 'c3ebdbf9cceddb82cd2089aaef8c7b992e536363';
$expected = [
'type' => 'git',
'url' => 'https://gitlab.com/mygroup/myproject.git',
'reference' => $reference,
];
self::assertEquals($expected, $driver->getSource($reference));
}
public function testGetTags(): void
{
$driver = $this->testInitialize('https://gitlab.com/mygroup/myproject', 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject');
$apiUrl = 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?per_page=100';
// @link http://doc.gitlab.com/ce/api/repositories.html#list-project-repository-tags
$tagData = <<<JSON
[
{
"name": "v1.0.0",
"commit": {
"id": "092ed2c762bbae331e3f51d4a17f67310bf99a81",
"committed_date": "2012-05-28T04:42:42-07:00"
}
},
{
"name": "v2.0.0",
"commit": {
"id": "8e8f60b3ec86d63733db3bd6371117a758027ec6",
"committed_date": "2014-07-06T12:59:11.000+02:00"
}
}
]
JSON;
$this->httpDownloader->expects(
[['url' => $apiUrl, 'body' => $tagData]],
true
);
$driver->setHttpDownloader($this->httpDownloader);
$expected = [
'v1.0.0' => '092ed2c762bbae331e3f51d4a17f67310bf99a81',
'v2.0.0' => '8e8f60b3ec86d63733db3bd6371117a758027ec6',
];
self::assertEquals($expected, $driver->getTags());
self::assertEquals($expected, $driver->getTags(), 'Tags are cached');
}
public function testGetPaginatedRefs(): void
{
$driver = $this->testInitialize('https://gitlab.com/mygroup/myproject', 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject');
// @link http://doc.gitlab.com/ce/api/repositories.html#list-project-repository-branches
$branchData = [
[
"name" => "mymaster",
"commit" => [
"id" => "97eda36b5c1dd953a3792865c222d4e85e5f302e",
"committed_date" => "2013-01-03T21:04:07.000+01:00",
],
],
[
"name" => "staging",
"commit" => [
"id" => "502cffe49f136443f2059803f2e7192d1ac066cd",
"committed_date" => "2013-03-09T16:35:23.000+01:00",
],
],
];
for ($i = 0; $i < 98; $i++) {
$branchData[] = [
"name" => "stagingdupe",
"commit" => [
"id" => "502cffe49f136443f2059803f2e7192d1ac066cd",
"committed_date" => "2013-03-09T16:35:23.000+01:00",
],
];
}
$branchData = JsonFile::encode($branchData);
$this->httpDownloader->expects(
[
[
'url' => 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/branches?per_page=100',
'body' => $branchData,
'headers' => ['Link: <http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=2&per_page=20>; rel="next", <http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=1&per_page=20>; rel="first", <http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=3&per_page=20>; rel="last"'],
],
[
'url' => "http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=2&per_page=20",
'body' => $branchData,
'headers' => ['Link: <http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=2&per_page=20>; rel="prev", <http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=1&per_page=20>; rel="first", <http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=3&per_page=20>; rel="last"'],
],
],
true
);
$driver->setHttpDownloader($this->httpDownloader);
$expected = [
'mymaster' => '97eda36b5c1dd953a3792865c222d4e85e5f302e',
'staging' => '502cffe49f136443f2059803f2e7192d1ac066cd',
'stagingdupe' => '502cffe49f136443f2059803f2e7192d1ac066cd',
];
self::assertEquals($expected, $driver->getBranches());
self::assertEquals($expected, $driver->getBranches(), 'Branches are cached');
}
public function testGetBranches(): void
{
$driver = $this->testInitialize('https://gitlab.com/mygroup/myproject', 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject');
$apiUrl = 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/branches?per_page=100';
// @link http://doc.gitlab.com/ce/api/repositories.html#list-project-repository-branches
$branchData = <<<JSON
[
{
"name": "mymaster",
"commit": {
"id": "97eda36b5c1dd953a3792865c222d4e85e5f302e",
"committed_date": "2013-01-03T21:04:07.000+01:00"
}
},
{
"name": "staging",
"commit": {
"id": "502cffe49f136443f2059803f2e7192d1ac066cd",
"committed_date": "2013-03-09T16:35:23.000+01:00"
}
}
]
JSON;
$this->httpDownloader->expects(
[['url' => $apiUrl, 'body' => $branchData]],
true
);
$driver->setHttpDownloader($this->httpDownloader);
$expected = [
'mymaster' => '97eda36b5c1dd953a3792865c222d4e85e5f302e',
'staging' => '502cffe49f136443f2059803f2e7192d1ac066cd',
];
self::assertEquals($expected, $driver->getBranches());
self::assertEquals($expected, $driver->getBranches(), 'Branches are cached');
}
/**
* @group gitlabHttpPort
* @dataProvider dataForTestSupports
*/
public function testSupports(string $url, bool $expected): void
{
self::assertSame($expected, GitLabDriver::supports($this->io, $this->config, $url));
}
public static function dataForTestSupports(): array
{
return [
['http://gitlab.com/foo/bar', true],
['http://gitlab.mycompany.com:5443/foo/bar', true],
['http://gitlab.com/foo/bar/', true],
['http://gitlab.com/foo/bar/', true],
['http://gitlab.com/foo/bar.git', true],
['http://gitlab.com/foo/bar.git', true],
['http://gitlab.com/foo/bar.baz.git', true],
['https://gitlab.com/foo/bar', extension_loaded('openssl')], // Platform requirement
['https://gitlab.mycompany.com:5443/foo/bar', extension_loaded('openssl')], // Platform requirement
['git@gitlab.com:foo/bar.git', extension_loaded('openssl')],
['git@example.com:foo/bar.git', false],
['http://example.com/foo/bar', false],
['http://mycompany.com/gitlab/mygroup/myproject', true],
['https://mycompany.com/gitlab/mygroup/myproject', extension_loaded('openssl')],
['http://othercompany.com/nested/gitlab/mygroup/myproject', true],
['https://othercompany.com/nested/gitlab/mygroup/myproject', extension_loaded('openssl')],
['http://gitlab.com/mygroup/mysubgroup/mysubsubgroup/myproject', true],
['https://gitlab.com/mygroup/mysubgroup/mysubsubgroup/myproject', extension_loaded('openssl')],
];
}
public function testGitlabSubDirectory(): void
{
$url = 'https://mycompany.com/gitlab/mygroup/my-pro.ject';
$apiUrl = 'https://mycompany.com/gitlab/api/v4/projects/mygroup%2Fmy-pro%2Eject';
$projectData = <<<JSON
{
"id": 17,
"default_branch": "mymaster",
"visibility": "private",
"http_url_to_repo": "https://gitlab.com/gitlab/mygroup/my-pro.ject",
"ssh_url_to_repo": "git@gitlab.com:mygroup/my-pro.ject.git",
"last_activity_at": "2014-12-01T09:17:51.000+01:00",
"name": "My Project",
"name_with_namespace": "My Group / My Project",
"path": "myproject",
"path_with_namespace": "mygroup/my-pro.ject",
"web_url": "https://gitlab.com/gitlab/mygroup/my-pro.ject"
}
JSON;
$this->httpDownloader->expects(
[['url' => $apiUrl, 'body' => $projectData]],
true
);
$driver = new GitLabDriver(['url' => $url], $this->io, $this->config, $this->httpDownloader, $this->process);
$driver->initialize();
self::assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL');
}
public function testGitlabSubGroup(): void
{
$url = 'https://gitlab.com/mygroup/mysubgroup/myproject';
$apiUrl = 'https://gitlab.com/api/v4/projects/mygroup%2Fmysubgroup%2Fmyproject';
$projectData = <<<JSON
{
"id": 17,
"default_branch": "mymaster",
"visibility": "private",
"http_url_to_repo": "https://gitlab.com/mygroup/mysubgroup/my-pro.ject",
"ssh_url_to_repo": "git@gitlab.com:mygroup/mysubgroup/my-pro.ject.git",
"last_activity_at": "2014-12-01T09:17:51.000+01:00",
"name": "My Project",
"name_with_namespace": "My Group / My Project",
"path": "myproject",
"path_with_namespace": "mygroup/mysubgroup/my-pro.ject",
"web_url": "https://gitlab.com/mygroup/mysubgroup/my-pro.ject"
}
JSON;
$this->httpDownloader->expects(
[['url' => $apiUrl, 'body' => $projectData]],
true
);
$driver = new GitLabDriver(['url' => $url], $this->io, $this->config, $this->httpDownloader, $this->process);
$driver->initialize();
self::assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL');
}
public function testGitlabSubDirectorySubGroup(): void
{
$url = 'https://mycompany.com/gitlab/mygroup/mysubgroup/myproject';
$apiUrl = 'https://mycompany.com/gitlab/api/v4/projects/mygroup%2Fmysubgroup%2Fmyproject';
$projectData = <<<JSON
{
"id": 17,
"default_branch": "mymaster",
"visibility": "private",
"http_url_to_repo": "https://mycompany.com/gitlab/mygroup/mysubgroup/my-pro.ject",
"ssh_url_to_repo": "git@mycompany.com:mygroup/mysubgroup/my-pro.ject.git",
"last_activity_at": "2014-12-01T09:17:51.000+01:00",
"name": "My Project",
"name_with_namespace": "My Group / My Project",
"path": "myproject",
"path_with_namespace": "mygroup/mysubgroup/my-pro.ject",
"web_url": "https://mycompany.com/gitlab/mygroup/mysubgroup/my-pro.ject"
}
JSON;
$this->httpDownloader->expects(
[['url' => $apiUrl, 'body' => $projectData]],
true
);
$driver = new GitLabDriver(['url' => $url], $this->io, $this->config, $this->httpDownloader, $this->process);
$driver->initialize();
self::assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL');
}
public function testForwardsOptions(): void
{
$options = [
'ssl' => [
'verify_peer' => false,
],
];
$projectData = <<<JSON
{
"id": 17,
"default_branch": "mymaster",
"visibility": "private",
"http_url_to_repo": "https://gitlab.mycompany.local/mygroup/myproject",
"ssh_url_to_repo": "git@gitlab.mycompany.local:mygroup/myproject.git",
"last_activity_at": "2014-12-01T09:17:51.000+01:00",
"name": "My Project",
"name_with_namespace": "My Group / My Project",
"path": "myproject",
"path_with_namespace": "mygroup/myproject",
"web_url": "https://gitlab.mycompany.local/mygroup/myproject"
}
JSON;
$this->httpDownloader->expects(
[['url' => 'https://gitlab.mycompany.local/api/v4/projects/mygroup%2Fmyproject', 'body' => $projectData]],
true
);
$driver = new GitLabDriver(
['url' => 'https://gitlab.mycompany.local/mygroup/myproject', 'options' => $options],
$this->io,
$this->config,
$this->httpDownloader,
$this->process
);
$driver->initialize();
}
public function testProtocolOverrideRepositoryUrlGeneration(): void
{
// @link http://doc.gitlab.com/ce/api/projects.html#get-single-project
$projectData = <<<JSON
{
"id": 17,
"default_branch": "mymaster",
"visibility": "private",
"http_url_to_repo": "https://gitlab.com/mygroup/myproject.git",
"ssh_url_to_repo": "git@gitlab.com:mygroup/myproject.git",
"last_activity_at": "2014-12-01T09:17:51.000+01:00",
"name": "My Project",
"name_with_namespace": "My Group / My Project",
"path": "myproject",
"path_with_namespace": "mygroup/myproject",
"web_url": "https://gitlab.com/mygroup/myproject"
}
JSON;
$apiUrl = 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject';
$url = 'git@gitlab.com:mygroup/myproject';
$this->httpDownloader->expects(
[['url' => $apiUrl, 'body' => $projectData]],
true
);
$config = clone $this->config;
$config->merge(['config' => ['gitlab-protocol' => 'http']]);
$driver = new GitLabDriver(['url' => $url], $this->io, $config, $this->httpDownloader, $this->process);
$driver->initialize();
self::assertEquals('https://gitlab.com/mygroup/myproject.git', $driver->getRepositoryUrl(), 'Repository URL matches config request for http not git');
}
/**
* @param object $object
* @param mixed $value
*/
protected function setAttribute($object, string $attribute, $value): void
{
$attr = new \ReflectionProperty($object, $attribute);
(\PHP_VERSION_ID < 80100) and $attr->setAccessible(true);
$attr->setValue($object, $value);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Repository/Vcs/HgDriverTest.php | tests/Composer/Test/Repository/Vcs/HgDriverTest.php | <?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test\Repository\Vcs;
use Composer\Repository\Vcs\HgDriver;
use Composer\Test\TestCase;
use Composer\Util\Filesystem;
use Composer\Config;
class HgDriverTest extends TestCase
{
/** @var \Composer\IO\IOInterface&\PHPUnit\Framework\MockObject\MockObject */
private $io;
/** @var Config */
private $config;
/** @var string */
private $home;
public function setUp(): void
{
$this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$this->home = self::getUniqueTmpDirectory();
$this->config = new Config();
$this->config->merge([
'config' => [
'home' => $this->home,
],
]);
}
protected function tearDown(): void
{
parent::tearDown();
$fs = new Filesystem;
$fs->removeDirectory($this->home);
}
/**
* @dataProvider supportsDataProvider
*/
public function testSupports(string $repositoryUrl): void
{
self::assertTrue(
HgDriver::supports($this->io, $this->config, $repositoryUrl)
);
}
public static function supportsDataProvider(): array
{
return [
['ssh://bitbucket.org/user/repo'],
['ssh://hg@bitbucket.org/user/repo'],
['ssh://user@bitbucket.org/user/repo'],
['https://bitbucket.org/user/repo'],
['https://user@bitbucket.org/user/repo'],
];
}
public function testGetBranchesFilterInvalidBranchNames(): void
{
$process = $this->getProcessExecutorMock();
$driver = new HgDriver(['url' => 'https://example.org/acme.git'], $this->io, $this->config, $this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(), $process);
$stdout = <<<HG_BRANCHES
default 1:dbf6c8acb640
--help 1:dbf6c8acb640
HG_BRANCHES;
$stdout1 = <<<HG_BOOKMARKS
help 1:dbf6c8acb641
--help 1:dbf6c8acb641
HG_BOOKMARKS;
$process
->expects([[
'cmd' => ['hg', 'branches'],
'stdout' => $stdout,
], [
'cmd' => ['hg', 'bookmarks'],
'stdout' => $stdout1,
]]);
$branches = $driver->getBranches();
self::assertSame([
'help' => 'dbf6c8acb641',
'default' => 'dbf6c8acb640',
], $branches);
}
public function testFileGetContentInvalidIdentifier(): void
{
self::expectException('\RuntimeException');
$process = $this->getProcessExecutorMock();
$driver = new HgDriver(['url' => 'https://example.org/acme.git'], $this->io, $this->config, $this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(), $process);
self::assertNull($driver->getFileContent('file.txt', 'h'));
$driver->getFileContent('file.txt', '-h');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.