Get rid of all the ->at() mock invocations

main
Jordi Boggiano 2 years ago
parent 095c36ecf8
commit ffd62795bc
No known key found for this signature in database
GPG Key ID: 7BBD42C429EC80BC

@ -21,9 +21,6 @@
"homepage": "https://seld.be" "homepage": "https://seld.be"
} }
], ],
"_comment": [
"symfony/polyfill-php73 sould be removed once https://github.com/symfony/symfony/pull/44523 is released and the symfony/console requirement bumped to match that release"
],
"require": { "require": {
"php": "^7.2.5 || ^8.0", "php": "^7.2.5 || ^8.0",
"composer/ca-bundle": "^1.0", "composer/ca-bundle": "^1.0",
@ -35,13 +32,12 @@
"psr/log": "^1.0 || ^2.0", "psr/log": "^1.0 || ^2.0",
"seld/jsonlint": "^1.4", "seld/jsonlint": "^1.4",
"seld/phar-utils": "^1.0", "seld/phar-utils": "^1.0",
"symfony/console": "^5.4 || ^6.0", "symfony/console": "^5.4.1 || ^6.0",
"symfony/filesystem": "^5.4 || ^6.0", "symfony/filesystem": "^5.4 || ^6.0",
"symfony/finder": "^5.4 || ^6.0", "symfony/finder": "^5.4 || ^6.0",
"symfony/process": "^5.4 || ^6.0", "symfony/process": "^5.4 || ^6.0",
"react/promise": "^2.8", "react/promise": "^2.8",
"composer/pcre": "^1.0", "composer/pcre": "^1.0"
"symfony/polyfill-php73": "^1.9"
}, },
"require-dev": { "require-dev": {
"symfony/phpunit-bridge": "^6.0", "symfony/phpunit-bridge": "^6.0",

16
composer.lock generated

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "21b7ce031989ab306ee91098fa461436", "content-hash": "274d271909468b2a6c06b562724a1662",
"packages": [ "packages": [
{ {
"name": "composer/ca-bundle", "name": "composer/ca-bundle",
@ -780,23 +780,23 @@
}, },
{ {
"name": "symfony/console", "name": "symfony/console",
"version": "v5.4.0", "version": "v5.4.1",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/console.git", "url": "https://github.com/symfony/console.git",
"reference": "ec3661faca1d110d6c307e124b44f99ac54179e3" "reference": "9130e1a0fc93cb0faadca4ee917171bd2ca9e5f4"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/console/zipball/ec3661faca1d110d6c307e124b44f99ac54179e3", "url": "https://api.github.com/repos/symfony/console/zipball/9130e1a0fc93cb0faadca4ee917171bd2ca9e5f4",
"reference": "ec3661faca1d110d6c307e124b44f99ac54179e3", "reference": "9130e1a0fc93cb0faadca4ee917171bd2ca9e5f4",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"php": ">=7.2.5", "php": ">=7.2.5",
"symfony/deprecation-contracts": "^2.1|^3", "symfony/deprecation-contracts": "^2.1|^3",
"symfony/polyfill-mbstring": "~1.0", "symfony/polyfill-mbstring": "~1.0",
"symfony/polyfill-php73": "^1.8", "symfony/polyfill-php73": "^1.9",
"symfony/polyfill-php80": "^1.16", "symfony/polyfill-php80": "^1.16",
"symfony/service-contracts": "^1.1|^2|^3", "symfony/service-contracts": "^1.1|^2|^3",
"symfony/string": "^5.1|^6.0" "symfony/string": "^5.1|^6.0"
@ -859,7 +859,7 @@
"terminal" "terminal"
], ],
"support": { "support": {
"source": "https://github.com/symfony/console/tree/v5.4.0" "source": "https://github.com/symfony/console/tree/v5.4.1"
}, },
"funding": [ "funding": [
{ {
@ -875,7 +875,7 @@
"type": "tidelift" "type": "tidelift"
} }
], ],
"time": "2021-11-29T15:30:56+00:00" "time": "2021-12-09T11:22:43+00:00"
}, },
{ {
"name": "symfony/deprecation-contracts", "name": "symfony/deprecation-contracts",

@ -1,7 +1,7 @@
<?php <?php
$bestDirFound = null; $bestDirFound = null;
$dirs = glob(__DIR__.'/../vendor/bin/.phpunit/phpunit-*'); $dirs = glob(__DIR__.'/../vendor/bin/.phpunit/phpunit-*', GLOB_ONLYDIR);
natsort($dirs); natsort($dirs);
foreach (array_reverse($dirs) as $dir) { foreach (array_reverse($dirs) as $dir) {

@ -16,7 +16,6 @@
> >
<php> <php>
<env name="SYMFONY_DEPRECATIONS_HELPER" value="max[direct]=0"/> <env name="SYMFONY_DEPRECATIONS_HELPER" value="max[direct]=0"/>
<env name="SYMFONY_PHPUNIT_REMOVE_RETURN_TYPEHINT" value="1"/>
<env name="COMPOSER_TEST_SUITE" value="1"/> <env name="COMPOSER_TEST_SUITE" value="1"/>
</php> </php>
<testsuites> <testsuites>

@ -25,7 +25,7 @@ class Response
private $request; private $request;
/** @var int */ /** @var int */
private $code; private $code;
/** @var string[] */ /** @var list<string> */
private $headers; private $headers;
/** @var ?string */ /** @var ?string */
private $body; private $body;
@ -33,7 +33,7 @@ class Response
/** /**
* @param Request $request * @param Request $request
* @param int $code * @param int $code
* @param string[] $headers * @param list<string> $headers
* @param ?string $body * @param ?string $body
*/ */
public function __construct(array $request, $code, array $headers, $body) public function __construct(array $request, $code, array $headers, $body)

@ -165,7 +165,7 @@ class Svn
} }
$errorOutput = $this->process->getErrorOutput(); $errorOutput = $this->process->getErrorOutput();
$fullOutput = implode("\n", array($output, $errorOutput)); $fullOutput = trim(implode("\n", array($output, $errorOutput)));
// the error is not auth-related // the error is not auth-related
if (false === stripos($fullOutput, 'Could not authenticate to server:') if (false === stripos($fullOutput, 'Could not authenticate to server:')

@ -38,8 +38,9 @@ class AllFunctionalTest extends TestCase
chdir(__DIR__.'/Fixtures/functional'); chdir(__DIR__.'/Fixtures/functional');
} }
public function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
if ($this->oldcwd) { if ($this->oldcwd) {
chdir($this->oldcwd); chdir($this->oldcwd);
} }

@ -14,11 +14,12 @@ namespace Composer\Test;
use Composer\Console\Application; use Composer\Console\Application;
use Composer\XdebugHandler\XdebugHandler; use Composer\XdebugHandler\XdebugHandler;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;
class ApplicationTest extends TestCase class ApplicationTest extends TestCase
{ {
public function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown(); parent::tearDown();
@ -34,27 +35,26 @@ class ApplicationTest extends TestCase
putenv('COMPOSER_NO_INTERACTION=1'); putenv('COMPOSER_NO_INTERACTION=1');
$index = 0; $inputMock->expects($this->any())
$inputMock->expects($this->at($index++))
->method('hasParameterOption')
->with($this->equalTo('--no-plugins'))
->will($this->returnValue(true));
$inputMock->expects($this->at($index++))
->method('hasParameterOption') ->method('hasParameterOption')
->with($this->equalTo('--no-scripts')) ->willReturnCallback(function ($opt): bool {
->will($this->returnValue(false)); switch ($opt) {
case '--no-plugins':
$inputMock->expects($this->at($index++)) return true;
case '--no-scripts':
return false;
case '--no-cache':
return false;
}
return false;
});
$inputMock->expects($this->once())
->method('setInteractive') ->method('setInteractive')
->with($this->equalTo(false)); ->with($this->equalTo(false));
$inputMock->expects($this->at($index++)) $inputMock->expects($this->once())
->method('hasParameterOption')
->with($this->equalTo('--no-cache'))
->will($this->returnValue(false));
$inputMock->expects($this->at($index++))
->method('getParameterOption') ->method('getParameterOption')
->with($this->equalTo(array('--working-dir', '-d'))) ->with($this->equalTo(array('--working-dir', '-d')))
->will($this->returnValue(false)); ->will($this->returnValue(false));
@ -63,33 +63,22 @@ class ApplicationTest extends TestCase
->method('getFirstArgument') ->method('getFirstArgument')
->will($this->returnValue('show')); ->will($this->returnValue('show'));
$index = 0; $output = new BufferedOutput();
$outputMock->expects($this->at($index++)) $expectedOutput = '';
->method("write");
if (XdebugHandler::isXdebugActive()) { if (XdebugHandler::isXdebugActive()) {
$outputMock->expects($this->at($index++)) $expectedOutput .= '<warning>Composer is operating slower than normal because you have Xdebug enabled. See https://getcomposer.org/xdebug</warning>'.PHP_EOL;
->method("getVerbosity")
->willReturn(OutputInterface::VERBOSITY_NORMAL);
$outputMock->expects($this->at($index++))
->method("write")
->with($this->equalTo('<warning>Composer is operating slower than normal because you have Xdebug enabled. See https://getcomposer.org/xdebug</warning>'));
} }
$outputMock->expects($this->at($index++)) $expectedOutput .= sprintf('<warning>Warning: This development build of Composer is over 60 days old. It is recommended to update it by running "%s self-update" to get the latest version.</warning>', $_SERVER['PHP_SELF']).PHP_EOL;
->method("getVerbosity")
->willReturn(OutputInterface::VERBOSITY_NORMAL);
$outputMock->expects($this->at($index++))
->method("write")
->with($this->equalTo(sprintf('<warning>Warning: This development build of Composer is over 60 days old. It is recommended to update it by running "%s self-update" to get the latest version.</warning>', $_SERVER['PHP_SELF'])));
if (!defined('COMPOSER_DEV_WARNING_TIME')) { if (!defined('COMPOSER_DEV_WARNING_TIME')) {
define('COMPOSER_DEV_WARNING_TIME', time() - 1); define('COMPOSER_DEV_WARNING_TIME', time() - 1);
} }
$application->doRun($inputMock, $outputMock); $application->doRun($inputMock, $output);
$this->assertStringContainsString($expectedOutput, $output->fetch());
} }
/** /**
@ -107,27 +96,26 @@ class ApplicationTest extends TestCase
putenv('COMPOSER_NO_INTERACTION=1'); putenv('COMPOSER_NO_INTERACTION=1');
$index = 0; $inputMock->expects($this->any())
$inputMock->expects($this->at($index++))
->method('hasParameterOption')
->with($this->equalTo('--no-plugins'))
->will($this->returnValue(true));
$inputMock->expects($this->at($index++))
->method('hasParameterOption') ->method('hasParameterOption')
->with($this->equalTo('--no-scripts')) ->willReturnCallback(function ($opt): bool {
->will($this->returnValue(false)); switch ($opt) {
case '--no-plugins':
$inputMock->expects($this->at($index++)) return true;
case '--no-scripts':
return false;
case '--no-cache':
return false;
}
return false;
});
$inputMock->expects($this->once())
->method('setInteractive') ->method('setInteractive')
->with($this->equalTo(false)); ->with($this->equalTo(false));
$inputMock->expects($this->at($index++)) $inputMock->expects($this->once())
->method('hasParameterOption')
->with($this->equalTo('--no-cache'))
->will($this->returnValue(false));
$inputMock->expects($this->at($index++))
->method('getParameterOption') ->method('getParameterOption')
->with($this->equalTo(array('--working-dir', '-d'))) ->with($this->equalTo(array('--working-dir', '-d')))
->will($this->returnValue(false)); ->will($this->returnValue(false));

@ -150,6 +150,7 @@ class AutoloadGeneratorTest extends TestCase
protected function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
chdir($this->origDir); chdir($this->origDir);
if (is_dir($this->workingDir)) { if (is_dir($this->workingDir)) {
@ -957,17 +958,13 @@ EOF;
$notAutoloadPackages[] = $b = new Package('b/b', '1.0', '1.0'); $notAutoloadPackages[] = $b = new Package('b/b', '1.0', '1.0');
$notAutoloadPackages[] = $c = new Package('c/c', '1.0', '1.0'); $notAutoloadPackages[] = $c = new Package('c/c', '1.0', '1.0');
$this->repository->expects($this->at(1)) $this->repository->expects($this->exactly(3))
->method('getCanonicalPackages') ->method('getCanonicalPackages')
->will($this->returnValue($autoloadPackages)); ->willReturnOnConsecutiveCalls(
$autoloadPackages,
$this->repository->expects($this->at(3)) $notAutoloadPackages,
->method('getCanonicalPackages') $notAutoloadPackages
->will($this->returnValue($notAutoloadPackages)); );
$this->repository->expects($this->at(5))
->method('getCanonicalPackages')
->will($this->returnValue($notAutoloadPackages));
$this->fs->ensureDirectoryExists($this->vendorDir.'/a/a'); $this->fs->ensureDirectoryExists($this->vendorDir.'/a/a');
$this->fs->ensureDirectoryExists($this->vendorDir.'/b/b'); $this->fs->ensureDirectoryExists($this->vendorDir.'/b/b');
@ -1283,14 +1280,12 @@ EOF;
public function testPreAndPostEventsAreDispatchedDuringAutoloadDump() public function testPreAndPostEventsAreDispatchedDuringAutoloadDump()
{ {
$this->eventDispatcher $this->eventDispatcher
->expects($this->at(0)) ->expects($this->exactly(2))
->method('dispatchScript')
->with(ScriptEvents::PRE_AUTOLOAD_DUMP, false);
$this->eventDispatcher
->expects($this->at(1))
->method('dispatchScript') ->method('dispatchScript')
->with(ScriptEvents::POST_AUTOLOAD_DUMP, false); ->withConsecutive(
[ScriptEvents::PRE_AUTOLOAD_DUMP, false],
[ScriptEvents::POST_AUTOLOAD_DUMP, false]
);
$package = new RootPackage('root/a', '1.0', '1.0'); $package = new RootPackage('root/a', '1.0', '1.0');
$package->setAutoload(array('psr-0' => array('Prefix' => 'foo/bar/non/existing/'))); $package->setAutoload(array('psr-0' => array('Prefix' => 'foo/bar/non/existing/')));

@ -55,6 +55,7 @@ class CacheTest extends TestCase
protected function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
if (is_dir($this->root)) { if (is_dir($this->root)) {
$fs = new Filesystem; $fs = new Filesystem;
$fs->removeDirectory($this->root); $fs->removeDirectory($this->root);

@ -42,6 +42,7 @@ class JsonConfigSourceTest extends TestCase
protected function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
if (is_dir($this->workingDir)) { if (is_dir($this->workingDir)) {
$this->fs->removeDirectory($this->workingDir); $this->fs->removeDirectory($this->workingDir);
} }

@ -254,13 +254,12 @@ class DownloadManagerTest extends TestCase
->will($this->returnValue('prettyPackage')); ->will($this->returnValue('prettyPackage'));
$package $package
->expects($this->at(3)) ->expects($this->exactly(2))
->method('setInstallationSource')
->with('dist');
$package
->expects($this->at(5))
->method('setInstallationSource') ->method('setInstallationSource')
->with('source'); ->withConsecutive(
['dist'],
['source']
);
$downloaderFail = $this->createDownloaderMock(); $downloaderFail = $this->createDownloaderMock();
$downloaderFail $downloaderFail
@ -280,15 +279,13 @@ class DownloadManagerTest extends TestCase
->setMethods(array('getDownloaderForPackage')) ->setMethods(array('getDownloaderForPackage'))
->getMock(); ->getMock();
$manager $manager
->expects($this->at(0)) ->expects($this->exactly(2))
->method('getDownloaderForPackage')
->with($package)
->will($this->returnValue($downloaderFail));
$manager
->expects($this->at(1))
->method('getDownloaderForPackage') ->method('getDownloaderForPackage')
->with($package) ->with($package)
->will($this->returnValue($downloaderSuccess)); ->willReturnOnConsecutiveCalls(
$downloaderFail,
$downloaderSuccess
);
$manager->download($package, 'target_dir'); $manager->download($package, 'target_dir');
} }

@ -220,7 +220,7 @@ class FileDownloaderTest extends TestCase
$dispatcher = new EventDispatcher( $dispatcher = new EventDispatcher(
$composerMock, $composerMock,
$this->getMockBuilder('Composer\IO\IOInterface')->getMock(), $this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
new ProcessExecutorMock $this->getProcessExecutorMock()
); );
$dispatcher->addListener(PluginEvents::PRE_FILE_DOWNLOAD, function (PreFileDownloadEvent $event) use ($expectedUrl) { $dispatcher->addListener(PluginEvents::PRE_FILE_DOWNLOAD, function (PreFileDownloadEvent $event) use ($expectedUrl) {
$event->setProcessedUrl($expectedUrl); $event->setProcessedUrl($expectedUrl);
@ -322,7 +322,7 @@ class FileDownloaderTest extends TestCase
$dispatcher = new EventDispatcher( $dispatcher = new EventDispatcher(
$composerMock, $composerMock,
$this->getMockBuilder('Composer\IO\IOInterface')->getMock(), $this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
new ProcessExecutorMock $this->getProcessExecutorMock()
); );
$dispatcher->addListener(PluginEvents::PRE_FILE_DOWNLOAD, function (PreFileDownloadEvent $event) use ($customCacheKey) { $dispatcher->addListener(PluginEvents::PRE_FILE_DOWNLOAD, function (PreFileDownloadEvent $event) use ($customCacheKey) {
$event->setCustomCacheKey($customCacheKey); $event->setCustomCacheKey($customCacheKey);
@ -387,15 +387,12 @@ class FileDownloaderTest extends TestCase
$this->config = $this->getMockBuilder('Composer\Config')->getMock(); $this->config = $this->getMockBuilder('Composer\Config')->getMock();
$this->config $this->config
->expects($this->at(0)) ->expects($this->atLeast(2))
->method('get') ->method('get')
->with('cache-files-ttl') ->willReturnMap([
->will($this->returnValue($expectedTtl)); ['cache-files-ttl', 0, $expectedTtl],
$this->config ['cache-files-maxsize', 0, '500M'],
->expects($this->at(1)) ]);
->method('get')
->with('cache-files-maxsize')
->will($this->returnValue('500M'));
$cacheMock = $this->getMockBuilder('Composer\Cache') $cacheMock = $this->getMockBuilder('Composer\Cache')
->disableOriginalConstructor() ->disableOriginalConstructor()
@ -492,13 +489,12 @@ class FileDownloaderTest extends TestCase
->will($this->returnValue(array($distUrl))); ->will($this->returnValue(array($distUrl)));
$ioMock = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $ioMock = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$ioMock->expects($this->at(0)) $ioMock->expects($this->atLeast(2))
->method('writeError')
->with($this->stringContains('Downloading'));
$ioMock->expects($this->at(1))
->method('writeError') ->method('writeError')
->with($this->stringContains('Downgrading')); ->withConsecutive(
[$this->stringContains('Downloading')],
[$this->stringContains('Downgrading')]
);
$path = $this->getUniqueTmpDirectory(); $path = $this->getUniqueTmpDirectory();
$filesystem = $this->getMockBuilder('Composer\Util\Filesystem')->getMock(); $filesystem = $this->getMockBuilder('Composer\Util\Filesystem')->getMock();

@ -29,6 +29,7 @@ class FossilDownloaderTest extends TestCase
protected function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
if (is_dir($this->workingDir)) { if (is_dir($this->workingDir)) {
$fs = new Filesystem; $fs = new Filesystem;
$fs->removeDirectory($this->workingDir); $fs->removeDirectory($this->workingDir);
@ -46,7 +47,7 @@ class FossilDownloaderTest extends TestCase
{ {
$io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$config = $config ?: $this->getMockBuilder('Composer\Config')->getMock(); $config = $config ?: $this->getMockBuilder('Composer\Config')->getMock();
$executor = $executor ?: new ProcessExecutorMock; $executor = $executor ?: $this->getProcessExecutorMock();
$filesystem = $filesystem ?: $this->getMockBuilder('Composer\Util\Filesystem')->getMock(); $filesystem = $filesystem ?: $this->getMockBuilder('Composer\Util\Filesystem')->getMock();
return new FossilDownloader($io, $config, $executor, $filesystem); return new FossilDownloader($io, $config, $executor, $filesystem);
@ -75,7 +76,7 @@ class FossilDownloaderTest extends TestCase
->method('getSourceUrls') ->method('getSourceUrls')
->will($this->returnValue(array('http://fossil.kd2.org/kd2fw/'))); ->will($this->returnValue(array('http://fossil.kd2.org/kd2fw/')));
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
$this->getCmd('fossil clone -- \'http://fossil.kd2.org/kd2fw/\' \'repo.fossil\''), $this->getCmd('fossil clone -- \'http://fossil.kd2.org/kd2fw/\' \'repo.fossil\''),
$this->getCmd('fossil open --nested -- \'repo.fossil\''), $this->getCmd('fossil open --nested -- \'repo.fossil\''),
@ -84,8 +85,6 @@ class FossilDownloaderTest extends TestCase
$downloader = $this->getDownloaderMock(null, null, $process); $downloader = $this->getDownloaderMock(null, null, $process);
$downloader->install($packageMock, 'repo'); $downloader->install($packageMock, 'repo');
$process->assertComplete($this);
} }
public function testUpdateforPackageWithoutSourceReference() public function testUpdateforPackageWithoutSourceReference()
@ -124,7 +123,7 @@ class FossilDownloaderTest extends TestCase
->method('getVersion') ->method('getVersion')
->will($this->returnValue('1.0.0.0')); ->will($this->returnValue('1.0.0.0'));
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
$this->getCmd("fossil changes"), $this->getCmd("fossil changes"),
$this->getCmd("fossil pull && fossil up 'trunk'"), $this->getCmd("fossil pull && fossil up 'trunk'"),
@ -134,8 +133,6 @@ class FossilDownloaderTest extends TestCase
$downloader->prepare('update', $packageMock, $this->workingDir, $packageMock); $downloader->prepare('update', $packageMock, $this->workingDir, $packageMock);
$downloader->update($packageMock, $packageMock, $this->workingDir); $downloader->update($packageMock, $packageMock, $this->workingDir);
$downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock); $downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock);
$process->assertComplete($this);
} }
public function testRemove() public function testRemove()
@ -146,7 +143,7 @@ class FossilDownloaderTest extends TestCase
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
$this->getCmd('fossil changes'), $this->getCmd('fossil changes'),
), true); ), true);
@ -161,8 +158,6 @@ class FossilDownloaderTest extends TestCase
$downloader->prepare('uninstall', $packageMock, $this->workingDir); $downloader->prepare('uninstall', $packageMock, $this->workingDir);
$downloader->remove($packageMock, $this->workingDir); $downloader->remove($packageMock, $this->workingDir);
$downloader->cleanup('uninstall', $packageMock, $this->workingDir); $downloader->cleanup('uninstall', $packageMock, $this->workingDir);
$process->assertComplete($this);
} }
public function testGetInstallationSource() public function testGetInstallationSource()

@ -39,6 +39,7 @@ class GitDownloaderTest extends TestCase
protected function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
if (is_dir($this->workingDir)) { if (is_dir($this->workingDir)) {
$this->fs->removeDirectory($this->workingDir); $this->fs->removeDirectory($this->workingDir);
} }
@ -85,7 +86,7 @@ class GitDownloaderTest extends TestCase
protected function getDownloaderMock($io = null, $config = null, $executor = null, $filesystem = null) protected function getDownloaderMock($io = null, $config = null, $executor = null, $filesystem = null)
{ {
$io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$executor = $executor ?: new ProcessExecutorMock; $executor = $executor ?: $this->getProcessExecutorMock();
$filesystem = $filesystem ?: $this->getMockBuilder('Composer\Util\Filesystem')->getMock(); $filesystem = $filesystem ?: $this->getMockBuilder('Composer\Util\Filesystem')->getMock();
$config = $this->setupConfig($config); $config = $this->setupConfig($config);
@ -124,7 +125,7 @@ class GitDownloaderTest extends TestCase
->method('getPrettyVersion') ->method('getPrettyVersion')
->will($this->returnValue('dev-master')); ->will($this->returnValue('dev-master'));
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
$this->winCompat("git clone --no-checkout -- 'https://example.com/composer/composer' 'composerPath' && cd 'composerPath' && 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'"), $this->winCompat("git clone --no-checkout -- 'https://example.com/composer/composer' 'composerPath' && cd 'composerPath' && 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'"),
$this->winCompat("git branch -r"), $this->winCompat("git branch -r"),
@ -136,8 +137,6 @@ class GitDownloaderTest extends TestCase
$downloader->prepare('install', $packageMock, 'composerPath'); $downloader->prepare('install', $packageMock, 'composerPath');
$downloader->install($packageMock, 'composerPath'); $downloader->install($packageMock, 'composerPath');
$downloader->cleanup('install', $packageMock, 'composerPath'); $downloader->cleanup('install', $packageMock, 'composerPath');
$process->assertComplete($this);
} }
public function testDownloadWithCache() public function testDownloadWithCache()
@ -165,7 +164,7 @@ class GitDownloaderTest extends TestCase
$filesystem = new \Composer\Util\Filesystem; $filesystem = new \Composer\Util\Filesystem;
$filesystem->removeDirectory($cachePath); $filesystem->removeDirectory($cachePath);
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
array('cmd' => $this->winCompat(sprintf("git clone --mirror -- 'https://example.com/composer/composer' '%s'", $cachePath)), 'callback' => function () use ($cachePath) { array('cmd' => $this->winCompat(sprintf("git clone --mirror -- 'https://example.com/composer/composer' '%s'", $cachePath)), 'callback' => function () use ($cachePath) {
@mkdir($cachePath, 0777, true); @mkdir($cachePath, 0777, true);
@ -183,8 +182,6 @@ class GitDownloaderTest extends TestCase
$downloader->install($packageMock, 'composerPath'); $downloader->install($packageMock, 'composerPath');
$downloader->cleanup('install', $packageMock, 'composerPath'); $downloader->cleanup('install', $packageMock, 'composerPath');
@rmdir($cachePath); @rmdir($cachePath);
$process->assertComplete($this);
} }
public function testDownloadUsesVariousProtocolsAndSetsPushUrlForGithub() public function testDownloadUsesVariousProtocolsAndSetsPushUrlForGithub()
@ -203,7 +200,7 @@ class GitDownloaderTest extends TestCase
->method('getPrettyVersion') ->method('getPrettyVersion')
->will($this->returnValue('1.0.0')); ->will($this->returnValue('1.0.0'));
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
array( array(
'cmd' => $this->winCompat("git clone --no-checkout -- 'https://github.com/mirrors/composer' 'composerPath' && cd 'composerPath' && git remote add composer -- 'https://github.com/mirrors/composer' && git fetch composer && git remote set-url origin -- 'https://github.com/mirrors/composer' && git remote set-url composer -- 'https://github.com/mirrors/composer'"), 'cmd' => $this->winCompat("git clone --no-checkout -- 'https://github.com/mirrors/composer' 'composerPath' && cd 'composerPath' && git remote add composer -- 'https://github.com/mirrors/composer' && git fetch composer && git remote set-url origin -- 'https://github.com/mirrors/composer' && git remote set-url composer -- 'https://github.com/mirrors/composer'"),
@ -222,8 +219,6 @@ class GitDownloaderTest extends TestCase
$downloader->prepare('install', $packageMock, 'composerPath'); $downloader->prepare('install', $packageMock, 'composerPath');
$downloader->install($packageMock, 'composerPath'); $downloader->install($packageMock, 'composerPath');
$downloader->cleanup('install', $packageMock, 'composerPath'); $downloader->cleanup('install', $packageMock, 'composerPath');
$process->assertComplete($this);
} }
public function pushUrlProvider() public function pushUrlProvider()
@ -260,7 +255,7 @@ class GitDownloaderTest extends TestCase
->method('getPrettyVersion') ->method('getPrettyVersion')
->will($this->returnValue('1.0.0')); ->will($this->returnValue('1.0.0'));
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
$this->winCompat("git clone --no-checkout -- '{$url}' 'composerPath' && cd 'composerPath' && git remote add composer -- '{$url}' && git fetch composer && git remote set-url origin -- '{$url}' && git remote set-url composer -- '{$url}'"), $this->winCompat("git clone --no-checkout -- '{$url}' 'composerPath' && cd 'composerPath' && git remote add composer -- '{$url}' && git fetch composer && git remote set-url origin -- '{$url}' && git remote set-url composer -- '{$url}'"),
$this->winCompat("git remote set-url --push origin -- '{$pushUrl}'"), $this->winCompat("git remote set-url --push origin -- '{$pushUrl}'"),
@ -276,8 +271,6 @@ class GitDownloaderTest extends TestCase
$downloader->prepare('install', $packageMock, 'composerPath'); $downloader->prepare('install', $packageMock, 'composerPath');
$downloader->install($packageMock, 'composerPath'); $downloader->install($packageMock, 'composerPath');
$downloader->cleanup('install', $packageMock, 'composerPath'); $downloader->cleanup('install', $packageMock, 'composerPath');
$process->assertComplete($this);
} }
public function testDownloadThrowsRuntimeExceptionIfGitCommandFails() public function testDownloadThrowsRuntimeExceptionIfGitCommandFails()
@ -296,7 +289,7 @@ class GitDownloaderTest extends TestCase
->method('getPrettyVersion') ->method('getPrettyVersion')
->will($this->returnValue('1.0.0')); ->will($this->returnValue('1.0.0'));
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
array( array(
'cmd' => $this->winCompat("git clone --no-checkout -- 'https://example.com/composer/composer' 'composerPath' && cd 'composerPath' && 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'"), 'cmd' => $this->winCompat("git clone --no-checkout -- 'https://example.com/composer/composer' 'composerPath' && cd 'composerPath' && 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'"),
@ -312,8 +305,6 @@ class GitDownloaderTest extends TestCase
$downloader->install($packageMock, 'composerPath'); $downloader->install($packageMock, 'composerPath');
$downloader->cleanup('install', $packageMock, 'composerPath'); $downloader->cleanup('install', $packageMock, 'composerPath');
$process->assertComplete($this);
$this->fail('This test should throw'); $this->fail('This test should throw');
} catch (\RuntimeException $e) { } catch (\RuntimeException $e) {
if ('RuntimeException' !== get_class($e)) { if ('RuntimeException' !== get_class($e)) {
@ -358,7 +349,7 @@ class GitDownloaderTest extends TestCase
->method('getPrettyVersion') ->method('getPrettyVersion')
->will($this->returnValue('1.0.0')); ->will($this->returnValue('1.0.0'));
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
$this->winCompat('git show-ref --head -d'), $this->winCompat('git show-ref --head -d'),
$this->winCompat('git status --porcelain --untracked-files=no'), $this->winCompat('git status --porcelain --untracked-files=no'),
@ -375,8 +366,6 @@ class GitDownloaderTest extends TestCase
$downloader->prepare('update', $packageMock, $this->workingDir, $packageMock); $downloader->prepare('update', $packageMock, $this->workingDir, $packageMock);
$downloader->update($packageMock, $packageMock, $this->workingDir); $downloader->update($packageMock, $packageMock, $this->workingDir);
$downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock); $downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock);
$process->assertComplete($this);
} }
public function testUpdateWithNewRepoUrl() public function testUpdateWithNewRepoUrl()
@ -400,7 +389,7 @@ class GitDownloaderTest extends TestCase
->method('getPrettyVersion') ->method('getPrettyVersion')
->will($this->returnValue('1.0.0')); ->will($this->returnValue('1.0.0'));
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
$this->winCompat("git show-ref --head -d"), $this->winCompat("git show-ref --head -d"),
$this->winCompat("git status --porcelain --untracked-files=no"), $this->winCompat("git status --porcelain --untracked-files=no"),
@ -426,8 +415,6 @@ composer https://github.com/old/url (push)
$downloader->prepare('update', $packageMock, $this->workingDir, $packageMock); $downloader->prepare('update', $packageMock, $this->workingDir, $packageMock);
$downloader->update($packageMock, $packageMock, $this->workingDir); $downloader->update($packageMock, $packageMock, $this->workingDir);
$downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock); $downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock);
$process->assertComplete($this);
} }
/** /**
@ -449,7 +436,7 @@ composer https://github.com/old/url (push)
->method('getVersion') ->method('getVersion')
->will($this->returnValue('1.0.0.0')); ->will($this->returnValue('1.0.0.0'));
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
$this->winCompat('git show-ref --head -d'), $this->winCompat('git show-ref --head -d'),
$this->winCompat('git status --porcelain --untracked-files=no'), $this->winCompat('git status --porcelain --untracked-files=no'),
@ -463,7 +450,6 @@ composer https://github.com/old/url (push)
'return' => 1, 'return' => 1,
), ),
$this->winCompat('git --version'), $this->winCompat('git --version'),
$this->winCompat('git branch -r'),
), true); ), true);
$this->fs->ensureDirectoryExists($this->workingDir.'/.git'); $this->fs->ensureDirectoryExists($this->workingDir.'/.git');
@ -476,8 +462,6 @@ composer https://github.com/old/url (push)
$downloader->update($packageMock, $packageMock, $this->workingDir); $downloader->update($packageMock, $packageMock, $this->workingDir);
$downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock); $downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock);
$process->assertComplete($this);
$this->fail('This test should throw'); $this->fail('This test should throw');
} catch (\RuntimeException $e) { } catch (\RuntimeException $e) {
if ('RuntimeException' !== get_class($e)) { if ('RuntimeException' !== get_class($e)) {
@ -506,7 +490,7 @@ composer https://github.com/old/url (push)
->method('getPrettyVersion') ->method('getPrettyVersion')
->will($this->returnValue('1.0.0')); ->will($this->returnValue('1.0.0'));
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
$this->winCompat('git show-ref --head -d'), $this->winCompat('git show-ref --head -d'),
$this->winCompat('git status --porcelain --untracked-files=no'), $this->winCompat('git status --porcelain --untracked-files=no'),
@ -532,8 +516,6 @@ composer https://github.com/old/url (push)
$downloader->prepare('update', $packageMock, $this->workingDir, $packageMock); $downloader->prepare('update', $packageMock, $this->workingDir, $packageMock);
$downloader->update($packageMock, $packageMock, $this->workingDir); $downloader->update($packageMock, $packageMock, $this->workingDir);
$downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock); $downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock);
$process->assertComplete($this);
} }
public function testDowngradeShowsAppropriateMessage() public function testDowngradeShowsAppropriateMessage()
@ -569,12 +551,14 @@ composer https://github.com/old/url (push)
->method('getFullPrettyVersion') ->method('getFullPrettyVersion')
->will($this->returnValue('1.0.0')); ->will($this->returnValue('1.0.0'));
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$ioMock = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $ioMock = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$ioMock->expects($this->at(0)) $ioMock->expects($this->atLeastOnce())
->method('writeError') ->method('writeError')
->with($this->stringContains('Downgrading')); ->withConsecutive(
[$this->stringContains('Downgrading')]
);
$this->fs->ensureDirectoryExists($this->workingDir.'/.git'); $this->fs->ensureDirectoryExists($this->workingDir.'/.git');
$downloader = $this->getDownloaderMock($ioMock, null, $process); $downloader = $this->getDownloaderMock($ioMock, null, $process);
@ -611,12 +595,14 @@ composer https://github.com/old/url (push)
->method('getPrettyVersion') ->method('getPrettyVersion')
->will($this->returnValue('dev-ref2')); ->will($this->returnValue('dev-ref2'));
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$ioMock = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $ioMock = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$ioMock->expects($this->at(0)) $ioMock->expects($this->atLeastOnce())
->method('writeError') ->method('writeError')
->with($this->stringContains('Upgrading')); ->withConsecutive(
[$this->stringContains('Upgrading')]
);
$this->fs->ensureDirectoryExists($this->workingDir.'/.git'); $this->fs->ensureDirectoryExists($this->workingDir.'/.git');
$downloader = $this->getDownloaderMock($ioMock, null, $process); $downloader = $this->getDownloaderMock($ioMock, null, $process);
@ -631,7 +617,7 @@ composer https://github.com/old/url (push)
$expectedGitResetCommand = $this->winCompat("git status --porcelain --untracked-files=no"); $expectedGitResetCommand = $this->winCompat("git status --porcelain --untracked-files=no");
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
'git show-ref --head -d', 'git show-ref --head -d',
$expectedGitResetCommand, $expectedGitResetCommand,
@ -649,8 +635,6 @@ composer https://github.com/old/url (push)
$downloader->prepare('uninstall', $packageMock, $this->workingDir); $downloader->prepare('uninstall', $packageMock, $this->workingDir);
$downloader->remove($packageMock, $this->workingDir); $downloader->remove($packageMock, $this->workingDir);
$downloader->cleanup('uninstall', $packageMock, $this->workingDir); $downloader->cleanup('uninstall', $packageMock, $this->workingDir);
$process->assertComplete($this);
} }
public function testGetInstallationSource() public function testGetInstallationSource()

@ -29,6 +29,7 @@ class HgDownloaderTest extends TestCase
protected function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
if (is_dir($this->workingDir)) { if (is_dir($this->workingDir)) {
$fs = new Filesystem; $fs = new Filesystem;
$fs->removeDirectory($this->workingDir); $fs->removeDirectory($this->workingDir);
@ -46,7 +47,7 @@ class HgDownloaderTest extends TestCase
{ {
$io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$config = $config ?: $this->getMockBuilder('Composer\Config')->getMock(); $config = $config ?: $this->getMockBuilder('Composer\Config')->getMock();
$executor = $executor ?: new ProcessExecutorMock; $executor = $executor ?: $this->getProcessExecutorMock();
$filesystem = $filesystem ?: $this->getMockBuilder('Composer\Util\Filesystem')->getMock(); $filesystem = $filesystem ?: $this->getMockBuilder('Composer\Util\Filesystem')->getMock();
return new HgDownloader($io, $config, $executor, $filesystem); return new HgDownloader($io, $config, $executor, $filesystem);
@ -75,7 +76,7 @@ class HgDownloaderTest extends TestCase
->method('getSourceUrls') ->method('getSourceUrls')
->will($this->returnValue(array('https://mercurial.dev/l3l0/composer'))); ->will($this->returnValue(array('https://mercurial.dev/l3l0/composer')));
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
$this->getCmd('hg clone -- \'https://mercurial.dev/l3l0/composer\' \'composerPath\''), $this->getCmd('hg clone -- \'https://mercurial.dev/l3l0/composer\' \'composerPath\''),
$this->getCmd('hg up -- \'ref\''), $this->getCmd('hg up -- \'ref\''),
@ -83,8 +84,6 @@ class HgDownloaderTest extends TestCase
$downloader = $this->getDownloaderMock(null, null, $process); $downloader = $this->getDownloaderMock(null, null, $process);
$downloader->install($packageMock, 'composerPath'); $downloader->install($packageMock, 'composerPath');
$process->assertComplete($this);
} }
public function testUpdateforPackageWithoutSourceReference() public function testUpdateforPackageWithoutSourceReference()
@ -118,7 +117,7 @@ class HgDownloaderTest extends TestCase
->method('getSourceUrls') ->method('getSourceUrls')
->will($this->returnValue(array('https://github.com/l3l0/composer'))); ->will($this->returnValue(array('https://github.com/l3l0/composer')));
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
$this->getCmd('hg st'), $this->getCmd('hg st'),
$this->getCmd("hg pull -- 'https://github.com/l3l0/composer' && hg up -- 'ref'"), $this->getCmd("hg pull -- 'https://github.com/l3l0/composer' && hg up -- 'ref'"),
@ -128,8 +127,6 @@ class HgDownloaderTest extends TestCase
$downloader->prepare('update', $packageMock, $this->workingDir, $packageMock); $downloader->prepare('update', $packageMock, $this->workingDir, $packageMock);
$downloader->update($packageMock, $packageMock, $this->workingDir); $downloader->update($packageMock, $packageMock, $this->workingDir);
$downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock); $downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock);
$process->assertComplete($this);
} }
public function testRemove() public function testRemove()
@ -138,7 +135,7 @@ class HgDownloaderTest extends TestCase
$fs->ensureDirectoryExists($this->workingDir.'/.hg'); $fs->ensureDirectoryExists($this->workingDir.'/.hg');
$packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
$this->getCmd('hg st'), $this->getCmd('hg st'),
), true); ), true);
@ -153,8 +150,6 @@ class HgDownloaderTest extends TestCase
$downloader->prepare('uninstall', $packageMock, $this->workingDir); $downloader->prepare('uninstall', $packageMock, $this->workingDir);
$downloader->remove($packageMock, $this->workingDir); $downloader->remove($packageMock, $this->workingDir);
$downloader->cleanup('uninstall', $packageMock, $this->workingDir); $downloader->cleanup('uninstall', $packageMock, $this->workingDir);
$process->assertComplete($this);
} }
public function testGetInstallationSource() public function testGetInstallationSource()

@ -49,7 +49,7 @@ class PerforceDownloaderTest extends TestCase
$this->repoConfig = $this->getRepoConfig(); $this->repoConfig = $this->getRepoConfig();
$this->config = $this->getConfig(); $this->config = $this->getConfig();
$this->io = $this->getMockIoInterface(); $this->io = $this->getMockIoInterface();
$this->processExecutor = new ProcessExecutorMock; $this->processExecutor = $this->getProcessExecutorMock();
$this->repository = $this->getMockRepository($this->repoConfig, $this->io, $this->config); $this->repository = $this->getMockRepository($this->repoConfig, $this->io, $this->config);
$this->package = $this->getMockPackageInterface($this->repository); $this->package = $this->getMockPackageInterface($this->repository);
$this->downloader = new PerforceDownloader($this->io, $this->config, $this->processExecutor); $this->downloader = new PerforceDownloader($this->io, $this->config, $this->processExecutor);
@ -140,13 +140,13 @@ class PerforceDownloaderTest extends TestCase
$this->io->expects($this->once())->method('writeError')->with($this->stringContains('Cloning '.$ref)); $this->io->expects($this->once())->method('writeError')->with($this->stringContains('Cloning '.$ref));
$perforceMethods = array('setStream', 'p4Login', 'writeP4ClientSpec', 'connectClient', 'syncCodeBase', 'cleanupClientSpec'); $perforceMethods = array('setStream', 'p4Login', 'writeP4ClientSpec', 'connectClient', 'syncCodeBase', 'cleanupClientSpec');
$perforce = $this->getMockBuilder('Composer\Util\Perforce')->disableOriginalConstructor()->getMock(); $perforce = $this->getMockBuilder('Composer\Util\Perforce')->disableOriginalConstructor()->getMock();
$perforce->expects($this->at(0))->method('initializePath')->with($this->equalTo($this->testPath)); $perforce->expects($this->once())->method('initializePath')->with($this->equalTo($this->testPath));
$perforce->expects($this->at(1))->method('setStream')->with($this->equalTo($ref)); $perforce->expects($this->once())->method('setStream')->with($this->equalTo($ref));
$perforce->expects($this->at(2))->method('p4Login'); $perforce->expects($this->once())->method('p4Login');
$perforce->expects($this->at(3))->method('writeP4ClientSpec'); $perforce->expects($this->once())->method('writeP4ClientSpec');
$perforce->expects($this->at(4))->method('connectClient'); $perforce->expects($this->once())->method('connectClient');
$perforce->expects($this->at(5))->method('syncCodeBase')->with($label); $perforce->expects($this->once())->method('syncCodeBase')->with($label);
$perforce->expects($this->at(6))->method('cleanupClientSpec'); $perforce->expects($this->once())->method('cleanupClientSpec');
$this->downloader->setPerforce($perforce); $this->downloader->setPerforce($perforce);
$this->downloader->doInstall($this->package, $this->testPath, 'url'); $this->downloader->doInstall($this->package, $this->testPath, 'url');
} }
@ -163,13 +163,13 @@ class PerforceDownloaderTest extends TestCase
$this->io->expects($this->once())->method('writeError')->with($this->stringContains('Cloning '.$ref)); $this->io->expects($this->once())->method('writeError')->with($this->stringContains('Cloning '.$ref));
$perforceMethods = array('setStream', 'p4Login', 'writeP4ClientSpec', 'connectClient', 'syncCodeBase', 'cleanupClientSpec'); $perforceMethods = array('setStream', 'p4Login', 'writeP4ClientSpec', 'connectClient', 'syncCodeBase', 'cleanupClientSpec');
$perforce = $this->getMockBuilder('Composer\Util\Perforce')->disableOriginalConstructor()->getMock(); $perforce = $this->getMockBuilder('Composer\Util\Perforce')->disableOriginalConstructor()->getMock();
$perforce->expects($this->at(0))->method('initializePath')->with($this->equalTo($this->testPath)); $perforce->expects($this->once())->method('initializePath')->with($this->equalTo($this->testPath));
$perforce->expects($this->at(1))->method('setStream')->with($this->equalTo($ref)); $perforce->expects($this->once())->method('setStream')->with($this->equalTo($ref));
$perforce->expects($this->at(2))->method('p4Login'); $perforce->expects($this->once())->method('p4Login');
$perforce->expects($this->at(3))->method('writeP4ClientSpec'); $perforce->expects($this->once())->method('writeP4ClientSpec');
$perforce->expects($this->at(4))->method('connectClient'); $perforce->expects($this->once())->method('connectClient');
$perforce->expects($this->at(5))->method('syncCodeBase')->with($label); $perforce->expects($this->once())->method('syncCodeBase')->with($label);
$perforce->expects($this->at(6))->method('cleanupClientSpec'); $perforce->expects($this->once())->method('cleanupClientSpec');
$this->downloader->setPerforce($perforce); $this->downloader->setPerforce($perforce);
$this->downloader->doInstall($this->package, $this->testPath, 'url'); $this->downloader->doInstall($this->package, $this->testPath, 'url');
} }

@ -39,8 +39,9 @@ class XzDownloaderTest extends TestCase
$this->testDir = $this->getUniqueTmpDirectory(); $this->testDir = $this->getUniqueTmpDirectory();
} }
public function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
$this->fs = new Filesystem; $this->fs = new Filesystem;
$this->fs->removeDirectory($this->testDir); $this->fs->removeDirectory($this->testDir);
} }

@ -42,8 +42,9 @@ class ZipDownloaderTest extends TestCase
$this->package = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $this->package = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
} }
public function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
$fs = new Filesystem; $fs = new Filesystem;
$fs->removeDirectory($this->testDir); $fs->removeDirectory($this->testDir);
$this->setPrivateProperty('hasZipArchive', null); $this->setPrivateProperty('hasZipArchive', null);

@ -38,17 +38,16 @@ class EventDispatcherTest extends TestCase
'Composer\Test\EventDispatcher\EventDispatcherTest::call', 'Composer\Test\EventDispatcher\EventDispatcherTest::call',
), $io); ), $io);
$io->expects($this->at(0)) $io->expects($this->once())
->method('isVerbose') ->method('isVerbose')
->willReturn(0); ->willReturn(0);
$io->expects($this->at(1)) $io->expects($this->atLeast(2))
->method('writeError')
->with('> Composer\Test\EventDispatcher\EventDispatcherTest::call');
$io->expects($this->at(2))
->method('writeError') ->method('writeError')
->with('<error>Script Composer\Test\EventDispatcher\EventDispatcherTest::call handling the post-install-cmd event terminated with an exception</error>'); ->withConsecutive(
['> Composer\Test\EventDispatcher\EventDispatcherTest::call'],
['<error>Script Composer\Test\EventDispatcher\EventDispatcherTest::call handling the post-install-cmd event terminated with an exception</error>']
);
$dispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, false); $dispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, false);
} }
@ -60,7 +59,7 @@ class EventDispatcherTest extends TestCase
*/ */
public function testDispatcherCanExecuteSingleCommandLineScript($command) public function testDispatcherCanExecuteSingleCommandLineScript($command)
{ {
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
$command, $command,
), true); ), true);
@ -80,8 +79,6 @@ class EventDispatcherTest extends TestCase
->will($this->returnValue($listener)); ->will($this->returnValue($listener));
$dispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, false); $dispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, false);
$process->assertComplete($this);
} }
/** /**
@ -110,7 +107,7 @@ class EventDispatcherTest extends TestCase
$dispatcher = new EventDispatcher( $dispatcher = new EventDispatcher(
$composer, $composer,
$this->getMockBuilder('Composer\IO\IOInterface')->getMock(), $this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
new ProcessExecutorMock $this->getProcessExecutorMock()
); );
$event = $this->getMockBuilder('Composer\Script\Event') $event = $this->getMockBuilder('Composer\Script\Event')
@ -191,7 +188,7 @@ class EventDispatcherTest extends TestCase
$dispatcher = new EventDispatcher( $dispatcher = new EventDispatcher(
$composer, $composer,
$io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE), $io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE),
new ProcessExecutorMock $this->getProcessExecutorMock()
); );
$listener = array($this, 'someMethod'); $listener = array($this, 'someMethod');
@ -226,7 +223,7 @@ class EventDispatcherTest extends TestCase
public function testDispatcherCanExecuteCliAndPhpInSameEventScriptStack() public function testDispatcherCanExecuteCliAndPhpInSameEventScriptStack()
{ {
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
'echo -n foo', 'echo -n foo',
'echo -n bar', 'echo -n bar',
@ -259,8 +256,6 @@ class EventDispatcherTest extends TestCase
'> post-install-cmd: Composer\Test\EventDispatcher\EventDispatcherTest::someMethod'.PHP_EOL. '> post-install-cmd: Composer\Test\EventDispatcher\EventDispatcherTest::someMethod'.PHP_EOL.
'> post-install-cmd: echo -n bar'.PHP_EOL; '> post-install-cmd: echo -n bar'.PHP_EOL;
$this->assertEquals($expected, $io->getOutput()); $this->assertEquals($expected, $io->getOutput());
$process->assertComplete($this);
} }
public function testDispatcherCanPutEnv() public function testDispatcherCanPutEnv()
@ -269,7 +264,7 @@ class EventDispatcherTest extends TestCase
->setConstructorArgs(array( ->setConstructorArgs(array(
$this->createComposerInstance(), $this->createComposerInstance(),
$io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE), $io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE),
new ProcessExecutorMock, $this->getProcessExecutorMock(),
)) ))
->setMethods(array( ->setMethods(array(
'getListeners', 'getListeners',
@ -302,7 +297,7 @@ class EventDispatcherTest extends TestCase
$dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->setConstructorArgs(array( $dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->setConstructorArgs(array(
$this->createComposerInstance(), $this->createComposerInstance(),
$io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE), $io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE),
new ProcessExecutorMock, $this->getProcessExecutorMock(),
))->setMethods(array( ))->setMethods(array(
'getListeners', 'getListeners',
))->getMock(); ))->getMock();
@ -368,7 +363,7 @@ class EventDispatcherTest extends TestCase
public function testDispatcherCanExecuteComposerScriptGroups() public function testDispatcherCanExecuteComposerScriptGroups()
{ {
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
'echo -n foo', 'echo -n foo',
'echo -n baz', 'echo -n baz',
@ -411,13 +406,11 @@ class EventDispatcherTest extends TestCase
'> subgroup: echo -n baz'.PHP_EOL. '> subgroup: echo -n baz'.PHP_EOL.
'> group: echo -n bar'.PHP_EOL; '> group: echo -n bar'.PHP_EOL;
$this->assertEquals($expected, $io->getOutput()); $this->assertEquals($expected, $io->getOutput());
$process->assertComplete($this);
} }
public function testRecursionInScriptsNames() public function testRecursionInScriptsNames()
{ {
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
'echo Hello '.ProcessExecutor::escape('World'), 'echo Hello '.ProcessExecutor::escape('World'),
), true); ), true);
@ -452,8 +445,6 @@ class EventDispatcherTest extends TestCase
"> hello: echo Hello " .$this->getCmd("'World'").PHP_EOL; "> hello: echo Hello " .$this->getCmd("'World'").PHP_EOL;
$this->assertEquals($expected, $io->getOutput()); $this->assertEquals($expected, $io->getOutput());
$process->assertComplete($this);
} }
public function testDispatcherDetectInfiniteRecursion() public function testDispatcherDetectInfiniteRecursion()
@ -464,7 +455,7 @@ class EventDispatcherTest extends TestCase
->setConstructorArgs(array( ->setConstructorArgs(array(
$composer = $this->createComposerInstance(), $composer = $this->createComposerInstance(),
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(), $io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
new ProcessExecutorMock, $this->getProcessExecutorMock(),
)) ))
->setMethods(array( ->setMethods(array(
'getListeners', 'getListeners',
@ -563,22 +554,21 @@ class EventDispatcherTest extends TestCase
->method('getListeners') ->method('getListeners')
->will($this->returnValue($listener)); ->will($this->returnValue($listener));
$io->expects($this->at(0)) $io->expects($this->once())
->method('isVerbose') ->method('isVerbose')
->willReturn(0); ->willReturn(0);
$io->expects($this->at(1)) $io->expects($this->atLeast(2))
->method('writeError') ->method('writeError')
->willReturn('> exit 1'); ->withConsecutive(
['> exit 1'],
['<error>Script '.$code.' handling the post-install-cmd event returned with error code 1</error>']
);
$io->expects($this->at(2)) $io->expects($this->once())
->method('isInteractive') ->method('isInteractive')
->willReturn(1); ->willReturn(1);
$io->expects($this->at(3))
->method('writeError')
->with($this->equalTo('<error>Script '.$code.' handling the post-install-cmd event returned with error code 1</error>'));
$this->setExpectedException('RuntimeException'); $this->setExpectedException('RuntimeException');
$dispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, false); $dispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, false);
} }
@ -589,7 +579,7 @@ class EventDispatcherTest extends TestCase
->setConstructorArgs(array( ->setConstructorArgs(array(
$this->createComposerInstance(), $this->createComposerInstance(),
$this->getMockBuilder('Composer\IO\IOInterface')->getMock(), $this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
new ProcessExecutorMock, $this->getProcessExecutorMock(),
)) ))
->setMethods(array('getListeners')) ->setMethods(array('getListeners'))
->getMock(); ->getMock();

@ -22,12 +22,12 @@ class ConsoleIOTest extends TestCase
public function testIsInteractive() public function testIsInteractive()
{ {
$inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock(); $inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock();
$inputMock->expects($this->at(0)) $inputMock->expects($this->exactly(2))
->method('isInteractive') ->method('isInteractive')
->will($this->returnValue(true)); ->willReturnOnConsecutiveCalls(
$inputMock->expects($this->at(1)) true,
->method('isInteractive') false
->will($this->returnValue(false)); );
$outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock(); $outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock();
$helperMock = $this->getMockBuilder('Symfony\Component\Console\Helper\HelperSet')->getMock(); $helperMock = $this->getMockBuilder('Symfony\Component\Console\Helper\HelperSet')->getMock();
@ -109,27 +109,17 @@ class ConsoleIOTest extends TestCase
$outputMock->expects($this->any()) $outputMock->expects($this->any())
->method('getVerbosity') ->method('getVerbosity')
->willReturn(OutputInterface::VERBOSITY_NORMAL); ->willReturn(OutputInterface::VERBOSITY_NORMAL);
$outputMock->expects($this->at(1)) $outputMock->expects($this->atLeast(7))
->method('write')
->with($this->equalTo('something (<question>strlen = 23</question>)'));
$outputMock->expects($this->at(3))
->method('write')
->with($this->equalTo(str_repeat("\x08", 23)), $this->equalTo(false));
$outputMock->expects($this->at(5))
->method('write')
->with($this->equalTo('shorter (<comment>12</comment>)'), $this->equalTo(false));
$outputMock->expects($this->at(7))
->method('write') ->method('write')
->with($this->equalTo(str_repeat(' ', 11)), $this->equalTo(false)); ->withConsecutive(
$outputMock->expects($this->at(9)) [$this->equalTo('something (<question>strlen = 23</question>)')],
->method('write') [$this->equalTo(str_repeat("\x08", 23)), $this->equalTo(false)],
->with($this->equalTo(str_repeat("\x08", 11)), $this->equalTo(false)); [$this->equalTo('shorter (<comment>12</comment>)'), $this->equalTo(false)],
$outputMock->expects($this->at(11)) [$this->equalTo(str_repeat(' ', 11)), $this->equalTo(false)],
->method('write') [$this->equalTo(str_repeat("\x08", 11)), $this->equalTo(false)],
->with($this->equalTo(str_repeat("\x08", 12)), $this->equalTo(false)); [$this->equalTo(str_repeat("\x08", 12)), $this->equalTo(false)],
$outputMock->expects($this->at(13)) [$this->equalTo('something longer than initial (<info>34</info>)')]
->method('write') );
->with($this->equalTo('something longer than initial (<info>34</info>)'));
$helperMock = $this->getMockBuilder('Symfony\Component\Console\Helper\HelperSet')->getMock(); $helperMock = $this->getMockBuilder('Symfony\Component\Console\Helper\HelperSet')->getMock();

@ -62,6 +62,7 @@ class BinaryInstallerTest extends TestCase
protected function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
$this->fs->removeDirectory($this->rootDir); $this->fs->removeDirectory($this->rootDir);
} }

@ -98,6 +98,7 @@ class LibraryInstallerTest extends TestCase
protected function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
$this->fs->removeDirectory($this->rootDir); $this->fs->removeDirectory($this->rootDir);
} }

@ -141,13 +141,13 @@ class SuggestedPackagesReporterTest extends TestCase
{ {
$this->suggestedPackagesReporter->addPackage('a', 'b', 'c'); $this->suggestedPackagesReporter->addPackage('a', 'b', 'c');
$this->io->expects($this->at(0)) $this->io->expects($this->exactly(3))
->method('write') ->method('write')
->with('<comment>a</comment> suggests:'); ->withConsecutive(
['<comment>a</comment> suggests:'],
$this->io->expects($this->at(1)) [' - <info>b</info>: c'],
->method('write') ['']
->with(' - <info>b</info>: c'); );
$this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE); $this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE);
} }
@ -159,13 +159,13 @@ class SuggestedPackagesReporterTest extends TestCase
{ {
$this->suggestedPackagesReporter->addPackage('a', 'b', ''); $this->suggestedPackagesReporter->addPackage('a', 'b', '');
$this->io->expects($this->at(0)) $this->io->expects($this->exactly(3))
->method('write') ->method('write')
->with('<comment>a</comment> suggests:'); ->withConsecutive(
['<comment>a</comment> suggests:'],
$this->io->expects($this->at(1)) [' - <info>b</info>'],
->method('write') ['']
->with(' - <info>b</info>'); );
$this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE); $this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE);
} }
@ -178,17 +178,14 @@ class SuggestedPackagesReporterTest extends TestCase
$this->suggestedPackagesReporter->addPackage('source', 'target1', "\x1b[1;37;42m Like us\r\non Facebook \x1b[0m"); $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->suggestedPackagesReporter->addPackage('source', 'target2', "<bg=green>Like us on Facebook</>");
$this->io->expects($this->at(0)) $this->io->expects($this->exactly(4))
->method('write') ->method('write')
->with('<comment>source</comment> suggests:'); ->withConsecutive(
['<comment>source</comment> suggests:'],
$this->io->expects($this->at(1)) [' - <info>target1</info>: [1;37;42m Like us on Facebook [0m'],
->method('write') [' - <info>target2</info>: \\<bg=green>Like us on Facebook\\</>'],
->with(' - <info>target1</info>: [1;37;42m Like us on Facebook [0m'); ['']
);
$this->io->expects($this->at(2))
->method('write')
->with(' - <info>target2</info>: \\<bg=green>Like us on Facebook\\</>');
$this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE); $this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE);
} }
@ -201,25 +198,16 @@ class SuggestedPackagesReporterTest extends TestCase
$this->suggestedPackagesReporter->addPackage('a', 'b', 'c'); $this->suggestedPackagesReporter->addPackage('a', 'b', 'c');
$this->suggestedPackagesReporter->addPackage('source package', 'target', 'because reasons'); $this->suggestedPackagesReporter->addPackage('source package', 'target', 'because reasons');
$this->io->expects($this->at(0)) $this->io->expects($this->exactly(6))
->method('write')
->with('<comment>a</comment> suggests:');
$this->io->expects($this->at(1))
->method('write')
->with(' - <info>b</info>: c');
$this->io->expects($this->at(2))
->method('write')
->with('');
$this->io->expects($this->at(3))
->method('write') ->method('write')
->with('<comment>source package</comment> suggests:'); ->withConsecutive(
['<comment>a</comment> suggests:'],
$this->io->expects($this->at(4)) [' - <info>b</info>: c'],
->method('write') [''],
->with(' - <info>target</info>: because reasons'); ['<comment>source package</comment> suggests:'],
[' - <info>target</info>: because reasons'],
['']
);
$this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE); $this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE);
} }
@ -251,13 +239,13 @@ class SuggestedPackagesReporterTest extends TestCase
$this->suggestedPackagesReporter->addPackage('a', 'b', 'c'); $this->suggestedPackagesReporter->addPackage('a', 'b', 'c');
$this->suggestedPackagesReporter->addPackage('source package', 'target', 'because reasons'); $this->suggestedPackagesReporter->addPackage('source package', 'target', 'because reasons');
$this->io->expects($this->at(0)) $this->io->expects($this->exactly(3))
->method('write')
->with('<comment>source package</comment> suggests:');
$this->io->expects($this->at(1))
->method('write') ->method('write')
->with(' - <info>target</info>: because reasons'); ->withConsecutive(
['<comment>source package</comment> suggests:'],
[' - <info>target</info>: because reasons'],
['']
);
$this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE, $repository); $this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE, $repository);
} }

@ -56,8 +56,9 @@ class InstallerTest extends TestCase
chdir(__DIR__); chdir(__DIR__);
} }
public function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
Platform::clearEnv('COMPOSER_POOL_OPTIMIZER'); Platform::clearEnv('COMPOSER_POOL_OPTIMIZER');
chdir($this->prevCwd); chdir($this->prevCwd);

@ -12,31 +12,120 @@
namespace Composer\Test\Mock; namespace Composer\Test\Mock;
use Composer\Config;
use Composer\IO\BufferIO;
use Composer\IO\IOInterface;
use Composer\Util\HttpDownloader; use Composer\Util\HttpDownloader;
use Composer\Util\Http\Response; use Composer\Util\Http\Response;
use Composer\Downloader\TransportException; use Composer\Downloader\TransportException;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\AssertionFailedError;
class HttpDownloaderMock extends HttpDownloader class HttpDownloaderMock extends HttpDownloader
{ {
/** /**
* @var array<string, string> * @var array<array{url: string, options: array<mixed>|null, status: int, body: string, headers: list<string>}>|null
*/ */
protected $contentMap; private $expectations = null;
/**
* @var bool
*/
private $strict = false;
/**
* @var array{status: int, body: string, headers: array<string>}
*/
private $defaultHandler = array('status' => 200, 'body' => '', 'headers' => []);
/**
* @var string[]
*/
private $log = array();
public function __construct(IOInterface $io = null, Config $config = null)
{
if ($io === null) {
$io = new BufferIO();
}
if ($config === null) {
$config = new Config(false);
}
parent::__construct($io, $config);
}
/** /**
* @param array<string, string> $contentMap associative array of locations and content * @param array<array{url: string, options?: array<mixed>, status?: int, body?: string, headers?: array<string>}> $expectations
* @param bool $strict set to true if you want to provide *all* expected http requests, and not just a subset you are interested in testing
* @param array{status?: int, body?: string, headers?: array<string>} $defaultHandler default URL handler for undefined requests if not in strict mode
*/ */
public function __construct(array $contentMap) public function expects(array $expectations, bool $strict = false, array $defaultHandler = array('return' => 0, 'stdout' => '', 'stderr' => '')): void
{ {
$this->contentMap = $contentMap; $default = ['url' => '', 'options' => null, 'status' => 200, 'body' => '', 'headers' => ['']];
$this->expectations = array_map(function (array $expect) use ($default): array {
if ($diff = array_diff_key(array_merge($default, $expect), $default)) {
throw new \UnexpectedValueException('Unexpected keys in process execution step: '.implode(', ', array_keys($diff)));
}
return array_merge($default, $expect);
}, $expectations);
$this->strict = $strict;
$this->defaultHandler = array_merge($this->defaultHandler, $defaultHandler);
} }
public function get($fileUrl, $options = array()) public function assertComplete(): void
{ {
if (!empty($this->contentMap[$fileUrl])) { // this was not configured to expect anything, so no need to react here
return new Response(array('url' => $fileUrl), 200, array(), $this->contentMap[$fileUrl]); if (!is_array($this->expectations)) {
return;
} }
throw new TransportException('The "'.$fileUrl.'" file could not be downloaded (NOT FOUND)', 404); if (count($this->expectations) > 0) {
$expectations = array_map(function ($expect) {
return $expect['url'];
}, $this->expectations);
throw new AssertionFailedError(
'There are still '.count($this->expectations).' expected HTTP requests which have not been consumed:'.PHP_EOL.
implode(PHP_EOL, $expectations).PHP_EOL.PHP_EOL.
'Received calls:'.PHP_EOL.implode(PHP_EOL, $this->log)
);
}
// dummy assertion to ensure the test is not marked as having no assertions
Assert::assertTrue(true);
}
public function get($fileUrl, $options = array()): Response
{
$this->log[] = $fileUrl;
if (is_array($this->expectations) && count($this->expectations) > 0 && $fileUrl === $this->expectations[0]['url'] && ($this->expectations[0]['options'] === null || $options === $this->expectations[0]['options'])) {
$expect = array_shift($this->expectations);
return $this->respond($fileUrl, $expect['status'], $expect['headers'], $expect['body']);
}
if (!$this->strict) {
return $this->respond($fileUrl, $this->defaultHandler['status'], $this->defaultHandler['headers'], $this->defaultHandler['body']);
}
throw new AssertionFailedError(
'Received unexpected request for "'.$fileUrl.'"'.PHP_EOL.
(is_array($this->expectations) && count($this->expectations) > 0 ? 'Expected "'.$this->expectations[0]['url'].'" at this point.' : 'Expected no more calls at this point.').PHP_EOL.
'Received calls:'.PHP_EOL.implode(PHP_EOL, array_slice($this->log, 0, -1))
);
}
/**
* @param string[] $headers
*/
private function respond(string $url, int $status, array $headers, string $body): Response
{
if ($status < 400) {
return new Response(array('url' => $url), $status, $headers, $body);
}
$e = new TransportException('The "'.$url.'" file could not be downloaded', $status);
$e->setHeaders($headers);
$e->setResponse($body);
throw $e;
} }
} }

@ -14,6 +14,7 @@ namespace Composer\Test\Mock;
use Composer\Util\ProcessExecutor; use Composer\Util\ProcessExecutor;
use Composer\Util\Platform; use Composer\Util\Platform;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\AssertionFailedError; use PHPUnit\Framework\AssertionFailedError;
use Symfony\Component\Process\Process; use Symfony\Component\Process\Process;
@ -25,9 +26,9 @@ use React\Promise\Promise;
class ProcessExecutorMock extends ProcessExecutor class ProcessExecutorMock extends ProcessExecutor
{ {
/** /**
* @var array<array{cmd: string, return: int, stdout: string, stderr: string, callback: ?callable}> * @var array<array{cmd: string, return: int, stdout: string, stderr: string, callback: ?callable}>|null
*/ */
private $expectations = array(); private $expectations = null;
/** /**
* @var bool * @var bool
*/ */
@ -64,10 +65,14 @@ class ProcessExecutorMock extends ProcessExecutor
$this->defaultHandler = array_merge($this->defaultHandler, $defaultHandler); $this->defaultHandler = array_merge($this->defaultHandler, $defaultHandler);
} }
/** @return void */ public function assertComplete(): void
public function assertComplete(TestCase $testCase)
{ {
if ($this->expectations) { // this was not configured to expect anything, so no need to react here
if (!is_array($this->expectations)) {
return;
}
if (count($this->expectations) > 0) {
$expectations = array_map(function ($expect) { $expectations = array_map(function ($expect) {
return $expect['cmd']; return $expect['cmd'];
}, $this->expectations); }, $this->expectations);
@ -78,7 +83,8 @@ class ProcessExecutorMock extends ProcessExecutor
); );
} }
$testCase->assertTrue(true); // dummy assertion to ensure the test is not marked as having no assertions
Assert::assertTrue(true);
} }
public function execute($command, &$output = null, $cwd = null) public function execute($command, &$output = null, $cwd = null)
@ -115,7 +121,7 @@ class ProcessExecutorMock extends ProcessExecutor
$this->log[] = $command; $this->log[] = $command;
if ($this->expectations && $command === $this->expectations[0]['cmd']) { if (is_array($this->expectations) && count($this->expectations) > 0 && $command === $this->expectations[0]['cmd']) {
$expect = array_shift($this->expectations); $expect = array_shift($this->expectations);
$stdout = $expect['stdout']; $stdout = $expect['stdout'];
$stderr = $expect['stderr']; $stderr = $expect['stderr'];
@ -130,7 +136,7 @@ class ProcessExecutorMock extends ProcessExecutor
} else { } else {
throw new AssertionFailedError( throw new AssertionFailedError(
'Received unexpected command "'.$command.'" in "'.$cwd.'"'.PHP_EOL. 'Received unexpected command "'.$command.'" in "'.$cwd.'"'.PHP_EOL.
($this->expectations ? 'Expected "'.$this->expectations[0]['cmd'].'" at this point.' : 'Expected no more calls at this point.').PHP_EOL. (is_array($this->expectations) && count($this->expectations) > 0 ? 'Expected "'.$this->expectations[0]['cmd'].'" at this point.' : 'Expected no more calls at this point.').PHP_EOL.
'Received calls:'.PHP_EOL.implode(PHP_EOL, array_slice($this->log, 0, -1)) 'Received calls:'.PHP_EOL.implode(PHP_EOL, array_slice($this->log, 0, -1))
); );
} }

@ -97,6 +97,7 @@ class ArchivableFilesFinderTest extends TestCase
protected function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
$fs = new Filesystem; $fs = new Filesystem;
$fs->removeDirectory($this->sources); $fs->removeDirectory($this->sources);
} }

@ -41,8 +41,9 @@ abstract class ArchiverTest extends TestCase
$this->testDir = $this->getUniqueTmpDirectory(); $this->testDir = $this->getUniqueTmpDirectory();
} }
public function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
$this->filesystem->removeDirectory($this->testDir); $this->filesystem->removeDirectory($this->testDir);
} }

@ -81,7 +81,7 @@ class RootPackageLoaderTest extends TestCase
$config = new Config; $config = new Config;
$config->merge(array('repositories' => array('packagist' => false))); $config->merge(array('repositories' => array('packagist' => false)));
$loader = new RootPackageLoader($manager, $config, null, new VersionGuesser($config, $process = new ProcessExecutorMock, new VersionParser())); $loader = new RootPackageLoader($manager, $config, null, new VersionGuesser($config, $process = $this->getProcessExecutorMock(), new VersionParser()));
$process->expects(array(), false, array('return' => 1)); $process->expects(array(), false, array('return' => 1));
$package = $loader->load(array()); $package = $loader->load(array());
@ -121,7 +121,7 @@ class RootPackageLoaderTest extends TestCase
->getMock() ->getMock()
; ;
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
array( array(
'cmd' => 'git branch -a --no-color --no-abbrev -v', 'cmd' => 'git branch -a --no-color --no-abbrev -v',
@ -136,8 +136,6 @@ class RootPackageLoaderTest extends TestCase
$package = $loader->load(array('require' => array('foo/bar' => 'self.version'))); $package = $loader->load(array('require' => array('foo/bar' => 'self.version')));
$this->assertEquals("dev-master", $package->getPrettyVersion()); $this->assertEquals("dev-master", $package->getPrettyVersion());
$process->assertComplete($this);
} }
public function testNonFeatureBranchPrettyVersion() public function testNonFeatureBranchPrettyVersion()
@ -151,7 +149,7 @@ class RootPackageLoaderTest extends TestCase
->getMock() ->getMock()
; ;
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
array( array(
'cmd' => 'git branch -a --no-color --no-abbrev -v', 'cmd' => 'git branch -a --no-color --no-abbrev -v',
@ -165,7 +163,5 @@ class RootPackageLoaderTest extends TestCase
$package = $loader->load(array('require' => array('foo/bar' => 'self.version'), "non-feature-branches" => array("latest-.*"))); $package = $loader->load(array('require' => array('foo/bar' => 'self.version'), "non-feature-branches" => array("latest-.*")));
$this->assertEquals("dev-latest-production", $package->getPrettyVersion()); $this->assertEquals("dev-latest-production", $package->getPrettyVersion());
$process->assertComplete($this);
} }
} }

@ -33,7 +33,7 @@ class VersionGuesserTest extends TestCase
{ {
$branch = 'default'; $branch = 'default';
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
array('cmd' => 'git branch -a --no-color --no-abbrev -v', 'return' => 128), array('cmd' => 'git branch -a --no-color --no-abbrev -v', 'return' => 128),
array('cmd' => 'git describe --exact-match --tags', 'return' => 128), array('cmd' => 'git describe --exact-match --tags', 'return' => 128),
@ -53,8 +53,6 @@ class VersionGuesserTest extends TestCase
$this->assertEquals("dev-".$branch, $versionArray['version']); $this->assertEquals("dev-".$branch, $versionArray['version']);
$this->assertEquals("dev-".$branch, $versionArray['pretty_version']); $this->assertEquals("dev-".$branch, $versionArray['pretty_version']);
$this->assertEmpty($versionArray['commit']); $this->assertEmpty($versionArray['commit']);
$process->assertComplete($this);
} }
public function testGuessVersionReturnsData() public function testGuessVersionReturnsData()
@ -62,7 +60,7 @@ class VersionGuesserTest extends TestCase
$commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea';
$anotherCommitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; $anotherCommitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea';
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
array( array(
'cmd' => 'git branch -a --no-color --no-abbrev -v', 'cmd' => 'git branch -a --no-color --no-abbrev -v',
@ -80,8 +78,6 @@ class VersionGuesserTest extends TestCase
$this->assertArrayNotHasKey('feature_version', $versionArray); $this->assertArrayNotHasKey('feature_version', $versionArray);
$this->assertArrayNotHasKey('feature_pretty_version', $versionArray); $this->assertArrayNotHasKey('feature_pretty_version', $versionArray);
$this->assertEquals($commitHash, $versionArray['commit']); $this->assertEquals($commitHash, $versionArray['commit']);
$process->assertComplete($this);
} }
public function testGuessVersionDoesNotSeeCustomDefaultBranchAsNonFeatureBranch() public function testGuessVersionDoesNotSeeCustomDefaultBranchAsNonFeatureBranch()
@ -89,7 +85,7 @@ class VersionGuesserTest extends TestCase
$commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea';
$anotherCommitHash = '13a15d220da53c52eddd5f32ffca64a7b3801bea'; $anotherCommitHash = '13a15d220da53c52eddd5f32ffca64a7b3801bea';
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
array( array(
'cmd' => 'git branch -a --no-color --no-abbrev -v', 'cmd' => 'git branch -a --no-color --no-abbrev -v',
@ -105,8 +101,6 @@ class VersionGuesserTest extends TestCase
$this->assertEquals("dev-current", $versionArray['version']); $this->assertEquals("dev-current", $versionArray['version']);
$this->assertEquals($anotherCommitHash, $versionArray['commit']); $this->assertEquals($anotherCommitHash, $versionArray['commit']);
$process->assertComplete($this);
} }
public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationForArbitraryNaming() public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationForArbitraryNaming()
@ -114,7 +108,7 @@ class VersionGuesserTest extends TestCase
$commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea';
$anotherCommitHash = '13a15d220da53c52eddd5f32ffca64a7b3801bea'; $anotherCommitHash = '13a15d220da53c52eddd5f32ffca64a7b3801bea';
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
array( array(
'cmd' => 'git branch -a --no-color --no-abbrev -v', 'cmd' => 'git branch -a --no-color --no-abbrev -v',
@ -135,8 +129,6 @@ class VersionGuesserTest extends TestCase
$this->assertEquals($anotherCommitHash, $versionArray['commit']); $this->assertEquals($anotherCommitHash, $versionArray['commit']);
$this->assertEquals("dev-feature", $versionArray['feature_version']); $this->assertEquals("dev-feature", $versionArray['feature_version']);
$this->assertEquals("dev-feature", $versionArray['feature_pretty_version']); $this->assertEquals("dev-feature", $versionArray['feature_pretty_version']);
$process->assertComplete($this);
} }
public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationForArbitraryNamingRegex() public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationForArbitraryNamingRegex()
@ -144,7 +136,7 @@ class VersionGuesserTest extends TestCase
$commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea';
$anotherCommitHash = '13a15d220da53c52eddd5f32ffca64a7b3801bea'; $anotherCommitHash = '13a15d220da53c52eddd5f32ffca64a7b3801bea';
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
array( array(
'cmd' => 'git branch -a --no-color --no-abbrev -v', 'cmd' => 'git branch -a --no-color --no-abbrev -v',
@ -165,8 +157,6 @@ class VersionGuesserTest extends TestCase
$this->assertEquals($anotherCommitHash, $versionArray['commit']); $this->assertEquals($anotherCommitHash, $versionArray['commit']);
$this->assertEquals("dev-feature", $versionArray['feature_version']); $this->assertEquals("dev-feature", $versionArray['feature_version']);
$this->assertEquals("dev-feature", $versionArray['feature_pretty_version']); $this->assertEquals("dev-feature", $versionArray['feature_pretty_version']);
$process->assertComplete($this);
} }
public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationForArbitraryNamingWhenOnNonFeatureBranch() public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationForArbitraryNamingWhenOnNonFeatureBranch()
@ -174,7 +164,7 @@ class VersionGuesserTest extends TestCase
$commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea';
$anotherCommitHash = '13a15d220da53c52eddd5f32ffca64a7b3801bea'; $anotherCommitHash = '13a15d220da53c52eddd5f32ffca64a7b3801bea';
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
array( array(
'cmd' => 'git branch -a --no-color --no-abbrev -v', 'cmd' => 'git branch -a --no-color --no-abbrev -v',
@ -191,15 +181,13 @@ class VersionGuesserTest extends TestCase
$this->assertEquals($commitHash, $versionArray['commit']); $this->assertEquals($commitHash, $versionArray['commit']);
$this->assertArrayNotHasKey('feature_version', $versionArray); $this->assertArrayNotHasKey('feature_version', $versionArray);
$this->assertArrayNotHasKey('feature_pretty_version', $versionArray); $this->assertArrayNotHasKey('feature_pretty_version', $versionArray);
$process->assertComplete($this);
} }
public function testDetachedHeadBecomesDevHash() public function testDetachedHeadBecomesDevHash()
{ {
$commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea';
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
array( array(
'cmd' => 'git branch -a --no-color --no-abbrev -v', 'cmd' => 'git branch -a --no-color --no-abbrev -v',
@ -214,15 +202,13 @@ class VersionGuesserTest extends TestCase
$versionData = $guesser->guessVersion(array(), 'dummy/path'); $versionData = $guesser->guessVersion(array(), 'dummy/path');
$this->assertEquals("dev-$commitHash", $versionData['version']); $this->assertEquals("dev-$commitHash", $versionData['version']);
$process->assertComplete($this);
} }
public function testDetachedFetchHeadBecomesDevHashGit2() public function testDetachedFetchHeadBecomesDevHashGit2()
{ {
$commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea';
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
array( array(
'cmd' => 'git branch -a --no-color --no-abbrev -v', 'cmd' => 'git branch -a --no-color --no-abbrev -v',
@ -237,15 +223,13 @@ class VersionGuesserTest extends TestCase
$versionData = $guesser->guessVersion(array(), 'dummy/path'); $versionData = $guesser->guessVersion(array(), 'dummy/path');
$this->assertEquals("dev-$commitHash", $versionData['version']); $this->assertEquals("dev-$commitHash", $versionData['version']);
$process->assertComplete($this);
} }
public function testDetachedCommitHeadBecomesDevHashGit2() public function testDetachedCommitHeadBecomesDevHashGit2()
{ {
$commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea';
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
array( array(
'cmd' => 'git branch -a --no-color --no-abbrev -v', 'cmd' => 'git branch -a --no-color --no-abbrev -v',
@ -260,13 +244,11 @@ class VersionGuesserTest extends TestCase
$versionData = $guesser->guessVersion(array(), 'dummy/path'); $versionData = $guesser->guessVersion(array(), 'dummy/path');
$this->assertEquals("dev-$commitHash", $versionData['version']); $this->assertEquals("dev-$commitHash", $versionData['version']);
$process->assertComplete($this);
} }
public function testTagBecomesVersion() public function testTagBecomesVersion()
{ {
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
array( array(
'cmd' => 'git branch -a --no-color --no-abbrev -v', 'cmd' => 'git branch -a --no-color --no-abbrev -v',
@ -284,13 +266,11 @@ class VersionGuesserTest extends TestCase
$versionData = $guesser->guessVersion(array(), 'dummy/path'); $versionData = $guesser->guessVersion(array(), 'dummy/path');
$this->assertEquals("2.0.5.0-alpha2", $versionData['version']); $this->assertEquals("2.0.5.0-alpha2", $versionData['version']);
$process->assertComplete($this);
} }
public function testTagBecomesPrettyVersion() public function testTagBecomesPrettyVersion()
{ {
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
array( array(
'cmd' => 'git branch -a --no-color --no-abbrev -v', 'cmd' => 'git branch -a --no-color --no-abbrev -v',
@ -309,13 +289,11 @@ class VersionGuesserTest extends TestCase
$this->assertEquals('1.0.0.0', $versionData['version']); $this->assertEquals('1.0.0.0', $versionData['version']);
$this->assertEquals('1.0.0', $versionData['pretty_version']); $this->assertEquals('1.0.0', $versionData['pretty_version']);
$process->assertComplete($this);
} }
public function testInvalidTagBecomesVersion() public function testInvalidTagBecomesVersion()
{ {
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
array( array(
'cmd' => 'git branch -a --no-color --no-abbrev -v', 'cmd' => 'git branch -a --no-color --no-abbrev -v',
@ -329,13 +307,11 @@ class VersionGuesserTest extends TestCase
$versionData = $guesser->guessVersion(array(), 'dummy/path'); $versionData = $guesser->guessVersion(array(), 'dummy/path');
$this->assertEquals("dev-foo", $versionData['version']); $this->assertEquals("dev-foo", $versionData['version']);
$process->assertComplete($this);
} }
public function testNumericBranchesShowNicely() public function testNumericBranchesShowNicely()
{ {
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
array( array(
'cmd' => 'git branch -a --no-color --no-abbrev -v', 'cmd' => 'git branch -a --no-color --no-abbrev -v',
@ -350,13 +326,11 @@ class VersionGuesserTest extends TestCase
$this->assertEquals("1.5.x-dev", $versionData['pretty_version']); $this->assertEquals("1.5.x-dev", $versionData['pretty_version']);
$this->assertEquals("1.5.9999999.9999999-dev", $versionData['version']); $this->assertEquals("1.5.9999999.9999999-dev", $versionData['version']);
$process->assertComplete($this);
} }
public function testRemoteBranchesAreSelected() public function testRemoteBranchesAreSelected()
{ {
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
array( array(
'cmd' => 'git branch -a --no-color --no-abbrev -v', 'cmd' => 'git branch -a --no-color --no-abbrev -v',
@ -375,7 +349,5 @@ class VersionGuesserTest extends TestCase
$versionData = $guesser->guessVersion(array('version' => 'self.version'), 'dummy/path'); $versionData = $guesser->guessVersion(array('version' => 'self.version'), 'dummy/path');
$this->assertEquals("1.5.x-dev", $versionData['pretty_version']); $this->assertEquals("1.5.x-dev", $versionData['pretty_version']);
$this->assertEquals("1.5.9999999.9999999-dev", $versionData['version']); $this->assertEquals("1.5.9999999.9999999-dev", $versionData['version']);
$process->assertComplete($this);
} }
} }

@ -181,15 +181,13 @@ class VersionSelectorTest extends TestCase
$packages = array($package1, $package2); $packages = array($package1, $package2);
$repositorySet = $this->createMockRepositorySet(); $repositorySet = $this->createMockRepositorySet();
$repositorySet->expects($this->at(0)) $repositorySet->expects($this->exactly(2))
->method('findPackages') ->method('findPackages')
->with($packageName, null) ->with($packageName, null)
->will($this->returnValue($packages)); ->willReturnOnConsecutiveCalls(
$packages,
$repositorySet->expects($this->at(1)) array_reverse($packages)
->method('findPackages') );
->with($packageName, null)
->will($this->returnValue(array_reverse($packages)));
$versionSelector = new VersionSelector($repositorySet); $versionSelector = new VersionSelector($repositorySet);
$best = $versionSelector->findBestCandidate($packageName); $best = $versionSelector->findBestCandidate($packageName);

@ -129,6 +129,7 @@ class PluginInstallerTest extends TestCase
protected function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
$filesystem = new Filesystem(); $filesystem = new Filesystem();
$filesystem->removeDirectory($this->directory); $filesystem->removeDirectory($this->directory);
} }

@ -1,137 +0,0 @@
<?php
/*
* 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 {
use PHPUnit\Framework\TestCase;
if (method_exists('PHPUnit\Framework\TestCase', 'assertFileDoesNotExist')) {
abstract class PolyfillTestCase extends TestCase
{
}
} else {
abstract class PolyfillTestCase extends TestCase
{
// all the functions below are form https://github.com/symfony/phpunit-bridge/blob/bd341a45ef79b30918376e8b8e2279fac6894c3b/Legacy/PolyfillAssertTrait.php
/**
* @param string $filename
* @param string $message
*
* @return void
*/
public static function assertIsNotReadable($filename, $message = '')
{
static::assertNotIsReadable($filename, $message);
}
/**
* @param string $filename
* @param string $message
*
* @return void
*/
public static function assertIsNotWritable($filename, $message = '')
{
static::assertNotIsWritable($filename, $message);
}
/**
* @param string $directory
* @param string $message
*
* @return void
*/
public static function assertDirectoryDoesNotExist($directory, $message = '')
{
static::assertDirectoryNotExists($directory, $message);
}
/**
* @param string $directory
* @param string $message
*
* @return void
*/
public static function assertDirectoryIsNotReadable($directory, $message = '')
{
static::assertDirectoryNotIsReadable($directory, $message);
}
/**
* @param string $directory
* @param string $message
*
* @return void
*/
public static function assertDirectoryIsNotWritable($directory, $message = '')
{
static::assertDirectoryNotIsWritable($directory, $message);
}
/**
* @param string $filename
* @param string $message
*
* @return void
*/
public static function assertFileDoesNotExist($filename, $message = '')
{
static::assertFileNotExists($filename, $message);
}
/**
* @param string $filename
* @param string $message
*
* @return void
*/
public static function assertFileIsNotReadable($filename, $message = '')
{
static::assertFileNotIsReadable($filename, $message);
}
/**
* @param string $filename
* @param string $message
*
* @return void
*/
public static function assertFileIsNotWritable($filename, $message = '')
{
static::assertFileNotIsWritable($filename, $message);
}
/**
* @param string $pattern
* @param string $string
* @param string $message
*
* @return void
*/
public static function assertMatchesRegularExpression($pattern, $string, $message = '')
{
static::assertRegExp($pattern, $string, $message);
}
/**
* @param string $pattern
* @param string $string
* @param string $message
*
* @return void
*/
public static function assertDoesNotMatchRegularExpression($pattern, $string, $message = '')
{
static::assertNotRegExp($pattern, $string, $message);
}
}
}
}

@ -58,7 +58,7 @@ class ComposerRepositoryTest extends TestCase
} }
$repository $repository
->expects($this->at(2)) ->expects($this->once())
->method('createPackages') ->method('createPackages')
->with($this->identicalTo($expected), $this->equalTo('root file (http://example.org/packages.json)')) ->with($this->identicalTo($expected), $this->equalTo('root file (http://example.org/packages.json)'))
->will($this->returnValue($stubs)); ->will($this->returnValue($stubs));
@ -181,16 +181,22 @@ class ComposerRepositoryTest extends TestCase
), ),
); );
$httpDownloader = new HttpDownloaderMock(array( $httpDownloader = $this->getHttpDownloaderMock();
'http://example.org/packages.json' => JsonFile::encode(array('search' => '/search.json?q=%query%&type=%type%')), $httpDownloader->expects(
'http://example.org/search.json?q=foo&type=composer-plugin' => JsonFile::encode($result), [
'http://example.org/search.json?q=foo&type=library' => JsonFile::encode(array()), ['url' => 'http://example.org/packages.json', 'body' => JsonFile::encode(array('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(array())],
],
true
);
$eventDispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher') $eventDispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock(); ->getMock();
$repository = new ComposerRepository($repoConfig, new NullIO, FactoryMock::createConfig(), $httpDownloader, $eventDispatcher); $config = FactoryMock::createConfig();
$config->merge(['config' => ['cache-read-only' => true]]);
$repository = new ComposerRepository($repoConfig, new NullIO, $config, $httpDownloader, $eventDispatcher);
$this->assertSame( $this->assertSame(
array(array('name' => 'foo', 'description' => null)), array(array('name' => 'foo', 'description' => null)),
@ -205,7 +211,7 @@ class ComposerRepositoryTest extends TestCase
public function testSearchWithAbandonedPackages() public function testSearchWithAbandonedPackages()
{ {
$repoConfig = array( $repoConfig = array(
'url' => 'http://2.example.org', 'url' => 'http://example.org',
); );
$result = array( $result = array(
@ -223,15 +229,22 @@ class ComposerRepositoryTest extends TestCase
), ),
); );
$httpDownloader = new HttpDownloaderMock(array( $httpDownloader = $this->getHttpDownloaderMock();
'http://2.example.org/packages.json' => JsonFile::encode(array('search' => '/search.json?q=%query%')), $httpDownloader->expects(
'http://2.example.org/search.json?q=foo' => JsonFile::encode($result), [
)); ['url' => 'http://example.org/packages.json', 'body' => JsonFile::encode(array('search' => '/search.json?q=%query%'))],
['url' => 'http://example.org/search.json?q=foo', 'body' => JsonFile::encode($result)],
],
true
);
$eventDispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher') $eventDispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock(); ->getMock();
$repository = new ComposerRepository($repoConfig, new NullIO, FactoryMock::createConfig(), $httpDownloader, $eventDispatcher); $config = FactoryMock::createConfig();
$config->merge(['config' => ['cache-read-only' => true]]);
$repository = new ComposerRepository($repoConfig, new NullIO, $config, $httpDownloader, $eventDispatcher);
$this->assertSame( $this->assertSame(
array( array(
@ -313,15 +326,22 @@ class ComposerRepositoryTest extends TestCase
public function testGetProviderNamesWillReturnPartialPackageNames() public function testGetProviderNamesWillReturnPartialPackageNames()
{ {
$httpDownloader = new HttpDownloaderMock(array( $httpDownloader = $this->getHttpDownloaderMock();
'http://example.org/packages.json' => JsonFile::encode(array( $httpDownloader->expects(
'providers-lazy-url' => '/foo/p/%package%.json', [
'packages' => array('foo/bar' => array( [
'dev-branch' => array('name' => 'foo/bar'), 'url' => 'http://example.org/packages.json',
'v1.0.0' => array('name' => 'foo/bar'), 'body' => JsonFile::encode(array(
)), 'providers-lazy-url' => '/foo/p/%package%.json',
)), 'packages' => array('foo/bar' => array(
)); 'dev-branch' => array('name' => 'foo/bar'),
'v1.0.0' => array('name' => 'foo/bar'),
)),
)),
],
],
true
);
$repository = new ComposerRepository( $repository = new ComposerRepository(
array('url' => 'http://example.org/packages.json'), array('url' => 'http://example.org/packages.json'),

@ -26,8 +26,9 @@ class RepositoryManagerTest extends TestCase
$this->tmpdir = $this->getUniqueTmpDirectory(); $this->tmpdir = $this->getUniqueTmpDirectory();
} }
public function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
if (is_dir($this->tmpdir)) { if (is_dir($this->tmpdir)) {
$fs = new Filesystem(); $fs = new Filesystem();
$fs->removeDirectory($this->tmpdir); $fs->removeDirectory($this->tmpdir);

@ -39,8 +39,9 @@ class FossilDriverTest extends TestCase
)); ));
} }
public function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
$fs = new Filesystem(); $fs = new Filesystem();
$fs->removeDirectory($this->home); $fs->removeDirectory($this->home);
} }

@ -51,8 +51,9 @@ class GitBitbucketDriverTest extends TestCase
->getMock(); ->getMock();
} }
public function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
$fs = new Filesystem; $fs = new Filesystem;
$fs->removeDirectory($this->home); $fs->removeDirectory($this->home);
} }

@ -39,8 +39,9 @@ class GitHubDriverTest extends TestCase
)); ));
} }
public function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
$fs = new Filesystem; $fs = new Filesystem;
$fs->removeDirectory($this->home); $fs->removeDirectory($this->home);
} }
@ -58,18 +59,19 @@ class GitHubDriverTest extends TestCase
->method('isInteractive') ->method('isInteractive')
->will($this->returnValue(true)); ->will($this->returnValue(true));
$httpDownloader = $this->getMockBuilder('Composer\Util\HttpDownloader') $httpDownloader = $this->getHttpDownloaderMock($io, $this->config);
->setConstructorArgs(array($io, $this->config)) $httpDownloader->expects(
->getMock(); [
['url' => $repoApiUrl, 'status' => 404],
['url' => 'https://api.github.com/', 'body' => '{}'],
['url' => $repoApiUrl, 'body' => '{"master_branch": "test_master", "private": true, "owner": {"login": "composer"}, "name": "packagist"}'],
],
true
);
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array(), false, array('return' => 1)); $process->expects(array(), false, array('return' => 1));
$httpDownloader->expects($this->at(0))
->method('get')
->with($this->equalTo($repoApiUrl))
->will($this->throwException(new TransportException('HTTP/1.1 404 Not Found', 404)));
$io->expects($this->once()) $io->expects($this->once())
->method('askAndHideAnswer') ->method('askAndHideAnswer')
->with($this->equalTo('Token (hidden): ')) ->with($this->equalTo('Token (hidden): '))
@ -79,16 +81,6 @@ class GitHubDriverTest extends TestCase
->method('setAuthentication') ->method('setAuthentication')
->with($this->equalTo('github.com'), $this->matchesRegularExpression('{sometoken}'), $this->matchesRegularExpression('{x-oauth-basic}')); ->with($this->equalTo('github.com'), $this->matchesRegularExpression('{sometoken}'), $this->matchesRegularExpression('{x-oauth-basic}'));
$httpDownloader->expects($this->at(1))
->method('get')
->with($this->equalTo($url = 'https://api.github.com/'))
->will($this->returnValue(new Response(array('url' => $url), 200, array(), '{}')));
$httpDownloader->expects($this->at(2))
->method('get')
->with($this->equalTo($url = $repoApiUrl))
->will($this->returnValue(new Response(array('url' => $url), 200, array(), '{"master_branch": "test_master", "private": true, "owner": {"login": "composer"}, "name": "packagist"}')));
$configSource = $this->getMockBuilder('Composer\Config\ConfigSourceInterface')->getMock(); $configSource = $this->getMockBuilder('Composer\Config\ConfigSourceInterface')->getMock();
$authConfigSource = $this->getMockBuilder('Composer\Config\ConfigSourceInterface')->getMock(); $authConfigSource = $this->getMockBuilder('Composer\Config\ConfigSourceInterface')->getMock();
$this->config->setConfigSource($configSource); $this->config->setConfigSource($configSource);
@ -127,21 +119,21 @@ class GitHubDriverTest extends TestCase
->method('isInteractive') ->method('isInteractive')
->will($this->returnValue(true)); ->will($this->returnValue(true));
$httpDownloader = $this->getMockBuilder('Composer\Util\HttpDownloader')
->setConstructorArgs(array($io, $this->config))
->getMock();
$httpDownloader->expects($this->at(0)) $httpDownloader = $this->getHttpDownloaderMock($io, $this->config);
->method('get') $httpDownloader->expects(
->with($this->equalTo($repoApiUrl)) [
->will($this->returnValue(new Response(array('url' => $repoApiUrl), 200, array(), '{"master_branch": "test_master", "owner": {"login": "composer"}, "name": "packagist"}'))); ['url' => $repoApiUrl, 'body' => '{"master_branch": "test_master", "owner": {"login": "composer"}, "name": "packagist"}'],
],
true
);
$repoConfig = array( $repoConfig = array(
'url' => $repoUrl, 'url' => $repoUrl,
); );
$repoUrl = 'https://github.com/composer/packagist.git'; $repoUrl = 'https://github.com/composer/packagist.git';
$gitHubDriver = new GitHubDriver($repoConfig, $io, $this->config, $httpDownloader, new ProcessExecutorMock); $gitHubDriver = new GitHubDriver($repoConfig, $io, $this->config, $httpDownloader, $this->getProcessExecutorMock());
$gitHubDriver->initialize(); $gitHubDriver->initialize();
$this->setAttribute($gitHubDriver, 'tags', array($identifier => $sha)); $this->setAttribute($gitHubDriver, 'tags', array($identifier => $sha));
@ -170,36 +162,24 @@ class GitHubDriverTest extends TestCase
->method('isInteractive') ->method('isInteractive')
->will($this->returnValue(true)); ->will($this->returnValue(true));
$httpDownloader = $this->getMockBuilder('Composer\Util\HttpDownloader')
->setConstructorArgs(array($io, $this->config))
->getMock();
$httpDownloader->expects($this->at(0)) $httpDownloader = $this->getHttpDownloaderMock($io, $this->config);
->method('get') $httpDownloader->expects(
->with($this->equalTo($url = $repoApiUrl)) [
->will($this->returnValue(new Response(array('url' => $url), 200, array(), '{"master_branch": "test_master", "owner": {"login": "composer"}, "name": "packagist"}'))); ['url' => $repoApiUrl, 'body' => '{"master_branch": "test_master", "owner": {"login": "composer"}, "name": "packagist"}'],
['url' => 'https://api.github.com/repos/composer/packagist/contents/composer.json?ref=feature%2F3.2-foo', 'body' => '{"encoding":"base64","content":"'.base64_encode('{"support": {"source": "'.$repoUrl.'" }}').'"}'],
$httpDownloader->expects($this->at(1)) ['url' => 'https://api.github.com/repos/composer/packagist/commits/feature%2F3.2-foo', 'body' => '{"commit": {"committer":{ "date": "2012-09-10"}}}'],
->method('get') ['url' => 'https://api.github.com/repos/composer/packagist/contents/.github/FUNDING.yml', 'body' => '{"encoding": "base64", "content": "'.base64_encode("custom: https://example.com").'"}'],
->with($this->equalTo($url = 'https://api.github.com/repos/composer/packagist/contents/composer.json?ref=feature%2F3.2-foo')) ],
->will($this->returnValue(new Response(array('url' => $url), 200, array(), '{"encoding":"base64","content":"'.base64_encode('{"support": {"source": "'.$repoUrl.'" }}').'"}'))); true
);
$httpDownloader->expects($this->at(2))
->method('get')
->with($this->equalTo($url = 'https://api.github.com/repos/composer/packagist/commits/feature%2F3.2-foo'))
->will($this->returnValue(new Response(array('url' => $url), 200, array(), '{"commit": {"committer":{ "date": "2012-09-10"}}}')));
$httpDownloader->expects($this->at(3))
->method('get')
->with($this->equalTo($url = 'https://api.github.com/repos/composer/packagist/contents/.github/FUNDING.yml'))
->will($this->returnValue(new Response(array('url' => $url), 200, array(), '{"encoding": "base64", "content": "'.base64_encode("custom: https://example.com").'"}')));
$repoConfig = array( $repoConfig = array(
'url' => $repoUrl, 'url' => $repoUrl,
); );
$repoUrl = 'https://github.com/composer/packagist.git'; $repoUrl = 'https://github.com/composer/packagist.git';
$gitHubDriver = new GitHubDriver($repoConfig, $io, $this->config, $httpDownloader, new ProcessExecutorMock); $gitHubDriver = new GitHubDriver($repoConfig, $io, $this->config, $httpDownloader, $this->getProcessExecutorMock());
$gitHubDriver->initialize(); $gitHubDriver->initialize();
$this->setAttribute($gitHubDriver, 'tags', array($identifier => $sha)); $this->setAttribute($gitHubDriver, 'tags', array($identifier => $sha));
@ -233,35 +213,22 @@ class GitHubDriverTest extends TestCase
->method('isInteractive') ->method('isInteractive')
->will($this->returnValue(true)); ->will($this->returnValue(true));
$httpDownloader = $this->getMockBuilder('Composer\Util\HttpDownloader') $httpDownloader = $this->getHttpDownloaderMock($io, $this->config);
->setConstructorArgs(array($io, $this->config)) $httpDownloader->expects(
->getMock(); [
['url' => $repoApiUrl, 'body' => '{"master_branch": "test_master", "owner": {"login": "composer"}, "name": "packagist", "archived": true}'],
$httpDownloader->expects($this->at(0)) ['url' => $composerJsonUrl, 'body' => '{"encoding": "base64", "content": "' . base64_encode('{"name": "composer/packagist"}') . '"}'],
->method('get') ['url' => 'https://api.github.com/repos/composer/packagist/commits/'.$sha, 'body' => '{"commit": {"committer":{ "date": "2012-09-10"}}}'],
->with($this->equalTo($repoApiUrl)) ['url' => 'https://api.github.com/repos/composer/packagist/contents/.github/FUNDING.yml', 'body' => '{"encoding": "base64", "content": "'.base64_encode("custom: https://example.com").'"}'],
->will($this->returnValue(new Response(array('url' => $repoApiUrl), 200, array(), '{"master_branch": "test_master", "owner": {"login": "composer"}, "name": "packagist", "archived": true}'))); ],
true
$httpDownloader->expects($this->at(1)) );
->method('get')
->with($this->equalTo($composerJsonUrl))
->will($this->returnValue(new Response(array('url' => $composerJsonUrl), 200, array(), '{"encoding": "base64", "content": "' . base64_encode('{"name": "composer/packagist"}') . '"}')));
$httpDownloader->expects($this->at(2))
->method('get')
->with($this->equalTo($url = 'https://api.github.com/repos/composer/packagist/commits/'.$sha))
->will($this->returnValue(new Response(array('url' => $url), 200, array(), '{"commit": {"committer":{ "date": "2012-09-10"}}}')));
$httpDownloader->expects($this->at(3))
->method('get')
->with($this->equalTo($url = 'https://api.github.com/repos/composer/packagist/contents/.github/FUNDING.yml'))
->will($this->returnValue(new Response(array('url' => $url), 200, array(), '{"encoding": "base64", "content": "'.base64_encode("custom: https://example.com").'"}')));
$repoConfig = array( $repoConfig = array(
'url' => $repoUrl, 'url' => $repoUrl,
); );
$gitHubDriver = new GitHubDriver($repoConfig, $io, $this->config, $httpDownloader, new ProcessExecutorMock); $gitHubDriver = new GitHubDriver($repoConfig, $io, $this->config, $httpDownloader, $this->getProcessExecutorMock());
$gitHubDriver->initialize(); $gitHubDriver->initialize();
$this->setAttribute($gitHubDriver, 'tags', array($identifier => $sha)); $this->setAttribute($gitHubDriver, 'tags', array($identifier => $sha));
@ -283,20 +250,19 @@ class GitHubDriverTest extends TestCase
->method('isInteractive') ->method('isInteractive')
->will($this->returnValue(false)); ->will($this->returnValue(false));
$httpDownloader = $this->getMockBuilder('Composer\Util\HttpDownloader') $httpDownloader = $this->getHttpDownloaderMock($io, $this->config);
->setConstructorArgs(array($io, $this->config)) $httpDownloader->expects(
->getMock(); [
['url' => $repoApiUrl, 'status' => 404],
$httpDownloader->expects($this->at(0)) ],
->method('get') true
->with($this->equalTo($repoApiUrl)) );
->will($this->throwException(new TransportException('HTTP/1.1 404 Not Found', 404)));
// clean local clone if present // clean local clone if present
$fs = new Filesystem(); $fs = new Filesystem();
$fs->removeDirectory(sys_get_temp_dir() . '/composer-test'); $fs->removeDirectory(sys_get_temp_dir() . '/composer-test');
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
array('cmd' => 'git config github.accesstoken', 'return' => 1), array('cmd' => 'git config github.accesstoken', 'return' => 1),
'git clone --mirror -- '.ProcessExecutor::escape($repoSshUrl).' '.ProcessExecutor::escape($this->config->get('cache-vcs-dir').'/git-github.com-composer-packagist.git/'), 'git clone --mirror -- '.ProcessExecutor::escape($repoSshUrl).' '.ProcessExecutor::escape($this->config->get('cache-vcs-dir').'/git-github.com-composer-packagist.git/'),
@ -337,8 +303,6 @@ class GitHubDriverTest extends TestCase
$this->assertEquals('git', $source['type']); $this->assertEquals('git', $source['type']);
$this->assertEquals($repoSshUrl, $source['url']); $this->assertEquals($repoSshUrl, $source['url']);
$this->assertEquals($sha, $source['reference']); $this->assertEquals($sha, $source['reference']);
$process->assertComplete($this);
} }
/** /**

@ -12,10 +12,14 @@
namespace Composer\Test\Repository\Vcs; namespace Composer\Test\Repository\Vcs;
use Composer\IO\IOInterface;
use Composer\Repository\Vcs\GitLabDriver; use Composer\Repository\Vcs\GitLabDriver;
use Composer\Config; use Composer\Config;
use Composer\Test\Mock\HttpDownloaderMock;
use Composer\Test\TestCase; use Composer\Test\TestCase;
use Composer\Util\Filesystem; use Composer\Util\Filesystem;
use Composer\Util\ProcessExecutor;
use PHPUnit\Framework\MockObject\MockObject;
use Prophecy\Argument; use Prophecy\Argument;
use Composer\Util\Http\Response; use Composer\Util\Http\Response;
@ -33,15 +37,15 @@ class GitLabDriverTest extends TestCase
*/ */
private $config; private $config;
/** /**
* @var \Prophecy\Prophecy\ObjectProphecy * @var MockObject&IOInterface
*/ */
private $io; private $io;
/** /**
* @var \Prophecy\Prophecy\ObjectProphecy * @var MockObject&ProcessExecutor
*/ */
private $process; private $process;
/** /**
* @var \Prophecy\Prophecy\ObjectProphecy * @var HttpDownloaderMock
*/ */
private $httpDownloader; private $httpDownloader;
@ -61,13 +65,14 @@ class GitLabDriverTest extends TestCase
), ),
)); ));
$this->io = $this->prophesize('Composer\IO\IOInterface'); $this->io = $this->getMockBuilder('Composer\IO\IOInterface')->disableOriginalConstructor()->getMock();
$this->process = $this->prophesize('Composer\Util\ProcessExecutor'); $this->process = $this->getMockBuilder('Composer\Util\ProcessExecutor')->getMock();
$this->httpDownloader = $this->prophesize('Composer\Util\HttpDownloader'); $this->httpDownloader = $this->getHttpDownloaderMock();
} }
public function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
$fs = new Filesystem(); $fs = new Filesystem();
$fs->removeDirectory($this->home); $fs->removeDirectory($this->home);
} }
@ -108,11 +113,12 @@ class GitLabDriverTest extends TestCase
} }
JSON; JSON;
$this->mockResponse($apiUrl, array(), $projectData) $this->httpDownloader->expects(
->shouldBeCalledTimes(1) [['url' => $apiUrl, 'body' => $projectData]],
; true
);
$driver = new GitLabDriver(array('url' => $url), $this->io->reveal(), $this->config, $this->httpDownloader->reveal(), $this->process->reveal()); $driver = new GitLabDriver(array('url' => $url), $this->io, $this->config, $this->httpDownloader, $this->process);
$driver->initialize(); $driver->initialize();
$this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL'); $this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL');
@ -148,11 +154,12 @@ JSON;
} }
JSON; JSON;
$this->mockResponse($apiUrl, array(), $projectData) $this->httpDownloader->expects(
->shouldBeCalledTimes(1) [['url' => $apiUrl, 'body' => $projectData]],
; true
);
$driver = new GitLabDriver(array('url' => $url), $this->io->reveal(), $this->config, $this->httpDownloader->reveal(), $this->process->reveal()); $driver = new GitLabDriver(array('url' => $url), $this->io, $this->config, $this->httpDownloader, $this->process);
$driver->initialize(); $driver->initialize();
$this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL'); $this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL');
@ -187,11 +194,12 @@ JSON;
} }
JSON; JSON;
$this->mockResponse($apiUrl, array(), $projectData) $this->httpDownloader->expects(
->shouldBeCalledTimes(1) [['url' => $apiUrl, 'body' => $projectData]],
; true
);
$driver = new GitLabDriver(array('url' => $url), $this->io->reveal(), $this->config, $this->httpDownloader->reveal(), $this->process->reveal()); $driver = new GitLabDriver(array('url' => $url), $this->io, $this->config, $this->httpDownloader, $this->process);
$driver->initialize(); $driver->initialize();
$this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL'); $this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL');
@ -227,10 +235,12 @@ JSON;
} }
JSON; JSON;
$this->mockResponse($apiUrl, array(), sprintf($projectData, $domain, $port, $namespace)) $this->httpDownloader->expects(
->shouldBeCalledTimes(1); [['url' => $apiUrl, 'body' => sprintf($projectData, $domain, $port, $namespace)]],
true
);
$driver = new GitLabDriver(array('url' => $url), $this->io->reveal(), $this->config, $this->httpDownloader->reveal(), $this->process->reveal()); $driver = new GitLabDriver(array('url' => $url), $this->io, $this->config, $this->httpDownloader, $this->process);
$driver->initialize(); $driver->initialize();
$this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL'); $this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL');
@ -308,11 +318,11 @@ JSON;
] ]
JSON; JSON;
$this->mockResponse($apiUrl, array(), $tagData) $this->httpDownloader->expects(
->shouldBeCalledTimes(1) [['url' => $apiUrl, 'body' => $tagData]],
; true
);
$driver->setHttpDownloader($this->httpDownloader->reveal()); $driver->setHttpDownloader($this->httpDownloader);
$expected = array( $expected = array(
'v1.0.0' => '092ed2c762bbae331e3f51d4a17f67310bf99a81', 'v1.0.0' => '092ed2c762bbae331e3f51d4a17f67310bf99a81',
@ -327,8 +337,6 @@ JSON;
{ {
$driver = $this->testInitialize('https://gitlab.com/mygroup/myproject', 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject'); $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 // @link http://doc.gitlab.com/ce/api/repositories.html#list-project-repository-branches
$branchData = array( $branchData = array(
array( array(
@ -359,20 +367,23 @@ JSON;
$branchData = json_encode($branchData); $branchData = json_encode($branchData);
$headers = array('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"'); $this->httpDownloader->expects(
$this->httpDownloader [
->get($apiUrl, array()) [
->willReturn(new Response(array('url' => $apiUrl), 200, $headers, $branchData)) 'url' => 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/branches?per_page=100',
->shouldBeCalledTimes(1); 'body' => $branchData,
'headers' => array('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"'),
$apiUrl = "http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=2&per_page=20"; ],
$headers = array('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"'); [
$this->httpDownloader 'url' => "http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=2&per_page=20",
->get($apiUrl, array()) 'body' => $branchData,
->willReturn(new Response(array('url' => $apiUrl), 200, $headers, $branchData)) 'headers' => array('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"'),
->shouldBeCalledTimes(1); ],
],
true
);
$driver->setHttpDownloader($this->httpDownloader->reveal()); $driver->setHttpDownloader($this->httpDownloader);
$expected = array( $expected = array(
'mymaster' => '97eda36b5c1dd953a3792865c222d4e85e5f302e', 'mymaster' => '97eda36b5c1dd953a3792865c222d4e85e5f302e',
@ -410,11 +421,12 @@ JSON;
] ]
JSON; JSON;
$this->mockResponse($apiUrl, array(), $branchData) $this->httpDownloader->expects(
->shouldBeCalledTimes(1) [['url' => $apiUrl, 'body' => $branchData]],
; true
);
$driver->setHttpDownloader($this->httpDownloader->reveal()); $driver->setHttpDownloader($this->httpDownloader);
$expected = array( $expected = array(
'mymaster' => '97eda36b5c1dd953a3792865c222d4e85e5f302e', 'mymaster' => '97eda36b5c1dd953a3792865c222d4e85e5f302e',
@ -434,7 +446,7 @@ JSON;
*/ */
public function testSupports($url, $expected) public function testSupports($url, $expected)
{ {
$this->assertSame($expected, GitLabDriver::supports($this->io->reveal(), $this->config, $url)); $this->assertSame($expected, GitLabDriver::supports($this->io, $this->config, $url));
} }
public function dataForTestSupports() public function dataForTestSupports()
@ -482,11 +494,12 @@ JSON;
} }
JSON; JSON;
$this->mockResponse($apiUrl, array(), $projectData) $this->httpDownloader->expects(
->shouldBeCalledTimes(1) [['url' => $apiUrl, 'body' => $projectData]],
; true
);
$driver = new GitLabDriver(array('url' => $url), $this->io->reveal(), $this->config, $this->httpDownloader->reveal(), $this->process->reveal()); $driver = new GitLabDriver(array('url' => $url), $this->io, $this->config, $this->httpDownloader, $this->process);
$driver->initialize(); $driver->initialize();
$this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL'); $this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL');
@ -513,11 +526,12 @@ JSON;
} }
JSON; JSON;
$this->mockResponse($apiUrl, array(), $projectData) $this->httpDownloader->expects(
->shouldBeCalledTimes(1) [['url' => $apiUrl, 'body' => $projectData]],
; true
);
$driver = new GitLabDriver(array('url' => $url), $this->io->reveal(), $this->config, $this->httpDownloader->reveal(), $this->process->reveal()); $driver = new GitLabDriver(array('url' => $url), $this->io, $this->config, $this->httpDownloader, $this->process);
$driver->initialize(); $driver->initialize();
$this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL'); $this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL');
@ -544,11 +558,12 @@ JSON;
} }
JSON; JSON;
$this->mockResponse($apiUrl, array(), $projectData) $this->httpDownloader->expects(
->shouldBeCalledTimes(1) [['url' => $apiUrl, 'body' => $projectData]],
; true
);
$driver = new GitLabDriver(array('url' => $url), $this->io->reveal(), $this->config, $this->httpDownloader->reveal(), $this->process->reveal()); $driver = new GitLabDriver(array('url' => $url), $this->io, $this->config, $this->httpDownloader, $this->process);
$driver->initialize(); $driver->initialize();
$this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL'); $this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL');
@ -577,15 +592,17 @@ JSON;
} }
JSON; JSON;
$this->mockResponse(Argument::cetera(), $options, $projectData) $this->httpDownloader->expects(
->shouldBeCalled(); [['url' => 'https:///api/v4/projects/%2Fmyproject', 'body' => $projectData]],
true
);
$driver = new GitLabDriver( $driver = new GitLabDriver(
array('url' => 'https://gitlab.mycompany.local/mygroup/myproject', 'options' => $options), array('url' => 'https://gitlab.mycompany.local/mygroup/myproject', 'options' => $options),
$this->io->reveal(), $this->io,
$this->config, $this->config,
$this->httpDownloader->reveal(), $this->httpDownloader,
$this->process->reveal() $this->process
); );
$driver->initialize(); $driver->initialize();
} }
@ -611,28 +628,15 @@ JSON;
$apiUrl = 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject'; $apiUrl = 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject';
$url = 'git@gitlab.com:mygroup/myproject'; $url = 'git@gitlab.com:mygroup/myproject';
$this->mockResponse($apiUrl, array(), $projectData) $this->httpDownloader->expects(
->shouldBeCalledTimes(1) [['url' => $apiUrl, 'body' => $projectData]],
; true
);
$config = clone $this->config; $config = clone $this->config;
$config->merge(array('config' => array('gitlab-protocol' => 'http'))); $config->merge(array('config' => array('gitlab-protocol' => 'http')));
$driver = new GitLabDriver(array('url' => $url), $this->io->reveal(), $config, $this->httpDownloader->reveal(), $this->process->reveal()); $driver = new GitLabDriver(array('url' => $url), $this->io, $config, $this->httpDownloader, $this->process);
$driver->initialize(); $driver->initialize();
$this->assertEquals('https://gitlab.com/mygroup/myproject.git', $driver->getRepositoryUrl(), 'Repository URL matches config request for http not git'); $this->assertEquals('https://gitlab.com/mygroup/myproject.git', $driver->getRepositoryUrl(), 'Repository URL matches config request for http not git');
} }
/**
* @param string $url
* @param mixed[] $options
* @param string|null $return
*
* @return \Prophecy\Prophecy\MethodProphecy
*/
private function mockResponse($url, $options, $return)
{
return $this->httpDownloader
->get($url, $options)
->willReturn(new Response(array('url' => $url), 200, array(), $return));
}
} }

@ -38,8 +38,9 @@ class HgDriverTest extends TestCase
)); ));
} }
public function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
$fs = new Filesystem; $fs = new Filesystem;
$fs->removeDirectory($this->home); $fs->removeDirectory($this->home);
} }

@ -71,7 +71,7 @@ class PerforceDriverTest extends TestCase
'branch' => self::TEST_BRANCH, 'branch' => self::TEST_BRANCH,
); );
$this->io = $this->getMockIOInterface(); $this->io = $this->getMockIOInterface();
$this->process = new ProcessExecutorMock; $this->process = $this->getProcessExecutorMock();
$this->httpDownloader = $this->getMockHttpDownloader(); $this->httpDownloader = $this->getMockHttpDownloader();
$this->perforce = $this->getMockPerforce(); $this->perforce = $this->getMockPerforce();
$this->driver = new PerforceDriver($this->repoConfig, $this->io, $this->config, $this->httpDownloader, $this->process); $this->driver = new PerforceDriver($this->repoConfig, $this->io, $this->config, $this->httpDownloader, $this->process);
@ -80,6 +80,7 @@ class PerforceDriverTest extends TestCase
protected function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
//cleanup directory under test path //cleanup directory under test path
$fs = new Filesystem; $fs = new Filesystem;
$fs->removeDirectory($this->testPath); $fs->removeDirectory($this->testPath);
@ -146,10 +147,10 @@ class PerforceDriverTest extends TestCase
public function testInitializeLogsInAndConnectsClient() public function testInitializeLogsInAndConnectsClient()
{ {
$this->perforce->expects($this->at(0))->method('p4Login'); $this->perforce->expects($this->once())->method('p4Login');
$this->perforce->expects($this->at(1))->method('checkStream'); $this->perforce->expects($this->once())->method('checkStream');
$this->perforce->expects($this->at(2))->method('writeP4ClientSpec'); $this->perforce->expects($this->once())->method('writeP4ClientSpec');
$this->perforce->expects($this->at(3))->method('connectClient'); $this->perforce->expects($this->once())->method('connectClient');
$this->driver->initialize(); $this->driver->initialize();
} }

@ -40,15 +40,16 @@ class SvnDriverTest extends TestCase
)); ));
} }
public function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
$fs = new Filesystem(); $fs = new Filesystem();
$fs->removeDirectory($this->home); $fs->removeDirectory($this->home);
} }
public function testWrongCredentialsInUrl() public function testWrongCredentialsInUrl()
{ {
$this->setExpectedException('RuntimeException'); $this->setExpectedException('RuntimeException', "Repository https://till:secret@corp.svn.local/repo could not be processed, wrong credentials provided (svn: OPTIONS of 'https://corp.svn.local/repo': authorization failed: Could not authenticate to server: rejected Basic challenge (https://corp.svn.local/))");
$console = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $console = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$httpDownloader = $this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(); $httpDownloader = $this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock();
@ -57,10 +58,15 @@ class SvnDriverTest extends TestCase
$output .= " authorization failed: Could not authenticate to server:"; $output .= " authorization failed: Could not authenticate to server:";
$output .= " rejected Basic challenge (https://corp.svn.local/)"; $output .= " rejected Basic challenge (https://corp.svn.local/)";
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array( $process->expects(array(
'svn --version', array('cmd' => "svn ls --verbose --non-interactive --username 'till' --password 'secret' -- 'https://till:secret@corp.svn.local/repo/trunk'", 'return' => 1, 'stderr' => $output),
array('cmd' => '', 'return' => 1, 'stderr' => $output), array('cmd' => "svn ls --verbose --non-interactive --username 'till' --password 'secret' -- 'https://till:secret@corp.svn.local/repo/trunk'", 'return' => 1, 'stderr' => $output),
array('cmd' => "svn ls --verbose --non-interactive --username 'till' --password 'secret' -- 'https://till:secret@corp.svn.local/repo/trunk'", 'return' => 1, 'stderr' => $output),
array('cmd' => "svn ls --verbose --non-interactive --username 'till' --password 'secret' -- 'https://till:secret@corp.svn.local/repo/trunk'", 'return' => 1, 'stderr' => $output),
array('cmd' => "svn ls --verbose --non-interactive --username 'till' --password 'secret' -- 'https://till:secret@corp.svn.local/repo/trunk'", 'return' => 1, 'stderr' => $output),
array('cmd' => "svn ls --verbose --non-interactive --username 'till' --password 'secret' -- 'https://till:secret@corp.svn.local/repo/trunk'", 'return' => 1, 'stderr' => $output),
array('cmd' => 'svn --version', 'return' => 0, 'stdout' => '1.2.3'),
), true); ), true);
$repoConfig = array( $repoConfig = array(
@ -69,8 +75,6 @@ class SvnDriverTest extends TestCase
$svn = new SvnDriver($repoConfig, $console, $this->config, $httpDownloader, $process); $svn = new SvnDriver($repoConfig, $console, $this->config, $httpDownloader, $process);
$svn->initialize(); $svn->initialize();
$process->assertComplete($this);
} }
public static function supportProvider() public static function supportProvider()

@ -12,11 +12,15 @@
namespace Composer\Test; namespace Composer\Test;
use Composer\Config;
use Composer\IO\IOInterface;
use Composer\Pcre\Preg; use Composer\Pcre\Preg;
use Composer\Semver\VersionParser; use Composer\Semver\VersionParser;
use Composer\Package\RootPackageInterface; use Composer\Package\RootPackageInterface;
use Composer\Package\PackageInterface; use Composer\Package\PackageInterface;
use Composer\Semver\Constraint\Constraint; use Composer\Semver\Constraint\Constraint;
use Composer\Test\Mock\HttpDownloaderMock;
use Composer\Test\Mock\ProcessExecutorMock;
use Composer\Util\Filesystem; use Composer\Util\Filesystem;
use Composer\Util\Platform; use Composer\Util\Platform;
use Composer\Util\Silencer; use Composer\Util\Silencer;
@ -31,7 +35,7 @@ use Composer\Package\CompleteAliasPackage;
use Composer\Package\CompletePackageInterface; use Composer\Package\CompletePackageInterface;
use Composer\Package\Package; use Composer\Package\Package;
abstract class TestCase extends PolyfillTestCase abstract class TestCase extends \PHPUnit\Framework\TestCase
{ {
/** /**
* @var ?VersionParser * @var ?VersionParser
@ -42,6 +46,26 @@ abstract class TestCase extends PolyfillTestCase
*/ */
private static $executableCache = array(); private static $executableCache = array();
/**
* @var list<HttpDownloaderMock>
*/
private $httpDownloaderMocks = [];
/**
* @var list<ProcessExecutorMock>
*/
private $processExecutorMocks = [];
protected function tearDown(): void
{
parent::tearDown();
foreach ($this->httpDownloaderMocks as $mock) {
$mock->assertComplete();
}
foreach ($this->processExecutorMocks as $mock) {
$mock->assertComplete();
}
}
/** /**
* @return string * @return string
*/ */
@ -226,4 +250,18 @@ abstract class TestCase extends PolyfillTestCase
return $cmd; return $cmd;
} }
protected function getHttpDownloaderMock(IOInterface $io = null, Config $config = null): HttpDownloaderMock
{
$this->httpDownloaderMocks[] = $mock = new HttpDownloaderMock($io, $config);
return $mock;
}
protected function getProcessExecutorMock(): ProcessExecutorMock
{
$this->processExecutorMocks[] = $mock = new ProcessExecutorMock();
return $mock;
}
} }

@ -301,9 +301,9 @@ class BitbucketTest extends TestCase
public function testUsernamePasswordAuthenticationFlow() public function testUsernamePasswordAuthenticationFlow()
{ {
$this->io $this->io
->expects($this->at(0)) ->expects($this->atLeastOnce())
->method('writeError') ->method('writeError')
->with($this->message) ->withConsecutive([$this->message])
; ;
$this->io->expects($this->exactly(2)) $this->io->expects($this->exactly(2))
@ -469,7 +469,7 @@ class BitbucketTest extends TestCase
public function testAuthorizeOAuthWithoutAvailableGitConfigToken() public function testAuthorizeOAuthWithoutAvailableGitConfigToken()
{ {
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$process->expects(array(), false, array('return' => -1)); $process->expects(array(), false, array('return' => -1));
$bitbucket = new Bitbucket($this->io, $this->config, $process, $this->httpDownloader, $this->time); $bitbucket = new Bitbucket($this->io, $this->config, $process, $this->httpDownloader, $this->time);
@ -479,7 +479,7 @@ class BitbucketTest extends TestCase
public function testAuthorizeOAuthWithAvailableGitConfigToken() public function testAuthorizeOAuthWithAvailableGitConfigToken()
{ {
$process = new ProcessExecutorMock; $process = $this->getProcessExecutorMock();
$bitbucket = new Bitbucket($this->io, $this->config, $process, $this->httpDownloader, $this->time); $bitbucket = new Bitbucket($this->io, $this->config, $process, $this->httpDownloader, $this->time);

@ -25,8 +25,9 @@ class ErrorHandlerTest extends TestCase
ErrorHandler::register(); ErrorHandler::register();
} }
public function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
restore_error_handler(); restore_error_handler();
} }

@ -39,8 +39,9 @@ class FilesystemTest extends TestCase
$this->testFile = $this->getUniqueTmpDirectory() . '/composer_test_file'; $this->testFile = $this->getUniqueTmpDirectory() . '/composer_test_file';
} }
public function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
if (is_dir($this->workingDir)) { if (is_dir($this->workingDir)) {
$this->fs->removeDirectory($this->workingDir); $this->fs->removeDirectory($this->workingDir);
} }

@ -12,6 +12,7 @@
namespace Composer\Test\Util; namespace Composer\Test\Util;
use _PHPStan_c862bb974\Symfony\Component\Console\Output\BufferedOutput;
use Composer\Downloader\TransportException; use Composer\Downloader\TransportException;
use Composer\Util\GitHub; use Composer\Util\GitHub;
use Composer\Util\Http\Response; use Composer\Util\Http\Response;
@ -33,9 +34,9 @@ class GitHubTest extends TestCase
{ {
$io = $this->getIOMock(); $io = $this->getIOMock();
$io $io
->expects($this->at(0)) ->expects($this->atLeastOnce())
->method('writeError') ->method('writeError')
->with($this->message) ->withConsecutive([$this->message])
; ;
$io $io
->expects($this->once()) ->expects($this->once())
@ -45,15 +46,10 @@ class GitHubTest extends TestCase
; ;
$httpDownloader = $this->getHttpDownloaderMock(); $httpDownloader = $this->getHttpDownloaderMock();
$httpDownloader $httpDownloader->expects(
->expects($this->once()) [['url' => sprintf('https://api.%s/', $this->origin), 'body' => '{}']],
->method('get') true
->with( );
$this->equalTo($url = sprintf('https://api.%s/', $this->origin)),
$this->anything()
)
->willReturn(new Response(array('url' => $url), 200, array(), '{}'))
;
$config = $this->getConfigMock(); $config = $this->getConfigMock();
$config $config
@ -83,11 +79,10 @@ class GitHubTest extends TestCase
; ;
$httpDownloader = $this->getHttpDownloaderMock(); $httpDownloader = $this->getHttpDownloaderMock();
$httpDownloader $httpDownloader->expects(
->expects($this->exactly(1)) [['url' => sprintf('https://api.%s/', $this->origin), 'status' => 401]],
->method('get') true
->will($this->throwException(new TransportException('', 401))) );
;
$config = $this->getConfigMock(); $config = $this->getConfigMock();
$config $config
@ -123,20 +118,6 @@ class GitHubTest extends TestCase
return $this->getMockBuilder('Composer\Config')->getMock(); return $this->getMockBuilder('Composer\Config')->getMock();
} }
/**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Util\HttpDownloader
*/
private function getHttpDownloaderMock()
{
$httpDownloader = $this
->getMockBuilder('Composer\Util\HttpDownloader')
->disableOriginalConstructor()
->getMock()
;
return $httpDownloader;
}
/** /**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Config\JsonConfigSource * @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Config\JsonConfigSource
*/ */

@ -13,6 +13,7 @@
namespace Composer\Test\Util; namespace Composer\Test\Util;
use Composer\Downloader\TransportException; use Composer\Downloader\TransportException;
use Composer\Test\Mock\HttpDownloaderMock;
use Composer\Util\GitLab; use Composer\Util\GitLab;
use Composer\Util\Http\Response; use Composer\Util\Http\Response;
use Composer\Test\TestCase; use Composer\Test\TestCase;
@ -37,9 +38,9 @@ class GitLabTest extends TestCase
{ {
$io = $this->getIOMock(); $io = $this->getIOMock();
$io $io
->expects($this->at(0)) ->expects($this->atLeastOnce())
->method('writeError') ->method('writeError')
->with($this->message) ->withConsecutive([$this->message])
; ;
$io $io
->expects($this->once()) ->expects($this->once())
@ -55,15 +56,10 @@ class GitLabTest extends TestCase
; ;
$httpDownloader = $this->getHttpDownloaderMock(); $httpDownloader = $this->getHttpDownloaderMock();
$httpDownloader $httpDownloader->expects(
->expects($this->once()) [['url' => sprintf('http://%s/oauth/token', $this->origin), 'body' => sprintf('{"access_token": "%s", "token_type": "bearer", "expires_in": 7200}', $this->token)]],
->method('get') true
->with( );
$this->equalTo($url = sprintf('http://%s/oauth/token', $this->origin)),
$this->anything()
)
->willReturn(new Response(array('url' => $url), 200, array(), sprintf('{"access_token": "%s", "token_type": "bearer", "expires_in": 7200}', $this->token)))
;
$config = $this->getConfigMock(); $config = $this->getConfigMock();
$config $config
@ -95,12 +91,16 @@ class GitLabTest extends TestCase
; ;
$httpDownloader = $this->getHttpDownloaderMock(); $httpDownloader = $this->getHttpDownloaderMock();
$httpDownloader $httpDownloader->expects(
->expects($this->exactly(5)) [
->method('get') ['url' => 'https://gitlab.com/oauth/token', 'status' => 401, 'body' => '{}'],
->will($this->throwException($e = new TransportException('', 401))) ['url' => 'https://gitlab.com/oauth/token', 'status' => 401, 'body' => '{}'],
; ['url' => 'https://gitlab.com/oauth/token', 'status' => 401, 'body' => '{}'],
$e->setResponse('{}'); ['url' => 'https://gitlab.com/oauth/token', 'status' => 401, 'body' => '{}'],
['url' => 'https://gitlab.com/oauth/token', 'status' => 401, 'body' => '{}'],
],
true
);
$config = $this->getConfigMock(); $config = $this->getConfigMock();
$config $config
@ -136,20 +136,6 @@ class GitLabTest extends TestCase
return $this->getMockBuilder('Composer\Config')->getMock(); return $this->getMockBuilder('Composer\Config')->getMock();
} }
/**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Util\HttpDownloader
*/
private function getHttpDownloaderMock()
{
$httpDownloader = $this
->getMockBuilder('Composer\Util\HttpDownloader')
->disableOriginalConstructor()
->getMock()
;
return $httpDownloader;
}
/** /**
* @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Config\JsonConfigSource * @return \PHPUnit\Framework\MockObject\MockObject&\Composer\Config\JsonConfigSource
*/ */

@ -36,7 +36,7 @@ class GitTest extends TestCase
{ {
$this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$this->config = $this->getMockBuilder('Composer\Config')->disableOriginalConstructor()->getMock(); $this->config = $this->getMockBuilder('Composer\Config')->disableOriginalConstructor()->getMock();
$this->process = new ProcessExecutorMock; $this->process = $this->getProcessExecutorMock();
$this->fs = $this->getMockBuilder('Composer\Util\Filesystem')->disableOriginalConstructor()->getMock(); $this->fs = $this->getMockBuilder('Composer\Util\Filesystem')->disableOriginalConstructor()->getMock();
$this->git = new Git($this->io, $this->config, $this->process, $this->fs); $this->git = new Git($this->io, $this->config, $this->process, $this->fs);
} }
@ -61,8 +61,6 @@ class GitTest extends TestCase
$this->process->expects(array('git command'), true); $this->process->expects(array('git command'), true);
$this->git->runCommand($commandCallable, 'https://github.com/acme/repo', null, true); $this->git->runCommand($commandCallable, 'https://github.com/acme/repo', null, true);
$this->process->assertComplete($this);
} }
public function publicGithubNoCredentialsProvider() public function publicGithubNoCredentialsProvider()
@ -92,8 +90,6 @@ class GitTest extends TestCase
), true); ), true);
$this->git->runCommand($commandCallable, 'https://github.com/acme/repo', null, true); $this->git->runCommand($commandCallable, 'https://github.com/acme/repo', null, true);
$this->process->assertComplete($this);
} }
/** /**
@ -139,8 +135,6 @@ class GitTest extends TestCase
->willReturn(array('username' => 'token', 'password' => $gitHubToken)); ->willReturn(array('username' => 'token', 'password' => $gitHubToken));
$this->git->runCommand($commandCallable, $gitUrl, null, true); $this->git->runCommand($commandCallable, $gitUrl, null, true);
$this->process->assertComplete($this);
} }
public function privateGithubWithCredentialsProvider() public function privateGithubWithCredentialsProvider()

@ -32,6 +32,7 @@ class ProxyHelperTest extends TestCase
protected function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
unset( unset(
$_SERVER['HTTP_PROXY'], $_SERVER['HTTP_PROXY'],
$_SERVER['http_proxy'], $_SERVER['http_proxy'],

@ -33,6 +33,7 @@ class ProxyManagerTest extends TestCase
protected function tearDown(): void protected function tearDown(): void
{ {
parent::tearDown();
unset( unset(
$_SERVER['HTTP_PROXY'], $_SERVER['HTTP_PROXY'],
$_SERVER['http_proxy'], $_SERVER['http_proxy'],

@ -12,6 +12,7 @@
namespace Composer\Test\Util; namespace Composer\Test\Util;
use Composer\Json\JsonFile;
use Composer\Util\Perforce; use Composer\Util\Perforce;
use Composer\Test\TestCase; use Composer\Test\TestCase;
use Composer\Util\ProcessExecutor; use Composer\Util\ProcessExecutor;
@ -153,10 +154,9 @@ class PerforceTest extends TestCase
return true; return true;
}; };
$this->processExecutor->expects($this->at(0)) $this->processExecutor->method('execute')
->method('execute')
->with($this->equalTo($expectedCommand)) ->with($this->equalTo($expectedCommand))
->will($this->returnCallback($callback)); ->willReturnCallback($callback);
$this->perforce->queryP4user(); $this->perforce->queryP4user();
$this->assertEquals('TEST_P4VARIABLE_USER', $this->perforce->getUser()); $this->assertEquals('TEST_P4VARIABLE_USER', $this->perforce->getUser());
} }
@ -171,10 +171,9 @@ class PerforceTest extends TestCase
return true; return true;
}; };
$this->processExecutor->expects($this->at(0)) $this->processExecutor->method('execute')
->method('execute')
->with($this->equalTo($expectedCommand)) ->with($this->equalTo($expectedCommand))
->will($this->returnCallback($callback)); ->willReturnCallback($callback);
$this->perforce->queryP4user(); $this->perforce->queryP4user();
$this->assertEquals('TEST_P4VARIABLE_USER', $this->perforce->getUser()); $this->assertEquals('TEST_P4VARIABLE_USER', $this->perforce->getUser());
} }
@ -183,10 +182,9 @@ class PerforceTest extends TestCase
{ {
$this->perforce->setUser(null); $this->perforce->setUser(null);
$expectedQuestion = 'Enter P4 User:'; $expectedQuestion = 'Enter P4 User:';
$this->io->expects($this->at(0)) $this->io->method('ask')
->method('ask')
->with($this->equalTo($expectedQuestion)) ->with($this->equalTo($expectedQuestion))
->will($this->returnValue('TEST_QUERY_USER')); ->willReturn('TEST_QUERY_USER');
$this->perforce->queryP4user(); $this->perforce->queryP4user();
$this->assertEquals('TEST_QUERY_USER', $this->perforce->getUser()); $this->assertEquals('TEST_QUERY_USER', $this->perforce->getUser());
} }
@ -197,14 +195,16 @@ class PerforceTest extends TestCase
$this->perforce->setUser(null); $this->perforce->setUser(null);
$expectedQuestion = 'Enter P4 User:'; $expectedQuestion = 'Enter P4 User:';
$expectedCommand = 'p4 set P4USER=TEST_QUERY_USER'; $expectedCommand = 'p4 set P4USER=TEST_QUERY_USER';
$this->io->expects($this->at(0)) $this->io->expects($this->once())
->method('ask') ->method('ask')
->with($this->equalTo($expectedQuestion)) ->with($this->equalTo($expectedQuestion))
->will($this->returnValue('TEST_QUERY_USER')); ->willReturn('TEST_QUERY_USER');
$this->processExecutor->expects($this->at(1)) $this->processExecutor->expects($this->exactly(2))
->method('execute') ->method('execute')
->with($this->equalTo($expectedCommand)) ->willReturnMap([
->will($this->returnValue(0)); ['p4 set', 0],
[$expectedCommand, 0],
]);
$this->perforce->queryP4user(); $this->perforce->queryP4user();
} }
@ -214,14 +214,16 @@ class PerforceTest extends TestCase
$this->perforce->setUser(null); $this->perforce->setUser(null);
$expectedQuestion = 'Enter P4 User:'; $expectedQuestion = 'Enter P4 User:';
$expectedCommand = 'export P4USER=TEST_QUERY_USER'; $expectedCommand = 'export P4USER=TEST_QUERY_USER';
$this->io->expects($this->at(0)) $this->io->expects($this->once())
->method('ask') ->method('ask')
->with($this->equalTo($expectedQuestion)) ->with($this->equalTo($expectedQuestion))
->will($this->returnValue('TEST_QUERY_USER')); ->willReturn('TEST_QUERY_USER');
$this->processExecutor->expects($this->at(1)) $this->processExecutor->expects($this->exactly(2))
->method('execute') ->method('execute')
->with($this->equalTo($expectedCommand)) ->willReturnMap([
->will($this->returnValue(0)); ['echo $P4USER', 0],
$expectedCommand => 0,
]);
$this->perforce->queryP4user(); $this->perforce->queryP4user();
} }
@ -247,10 +249,9 @@ class PerforceTest extends TestCase
return true; return true;
}; };
$this->processExecutor->expects($this->at(0)) $this->processExecutor->method('execute')
->method('execute')
->with($this->equalTo($expectedCommand)) ->with($this->equalTo($expectedCommand))
->will($this->returnCallback($callback)); ->willReturnCallback($callback);
$password = $this->perforce->queryP4Password(); $password = $this->perforce->queryP4Password();
$this->assertEquals('TEST_P4VARIABLE_PASSWORD', $password); $this->assertEquals('TEST_P4VARIABLE_PASSWORD', $password);
} }
@ -264,10 +265,9 @@ class PerforceTest extends TestCase
return true; return true;
}; };
$this->processExecutor->expects($this->at(0)) $this->processExecutor->method('execute')
->method('execute')
->with($this->equalTo($expectedCommand)) ->with($this->equalTo($expectedCommand))
->will($this->returnCallback($callback)); ->willReturnCallback($callback);
$password = $this->perforce->queryP4Password(); $password = $this->perforce->queryP4Password();
$this->assertEquals('TEST_P4VARIABLE_PASSWORD', $password); $this->assertEquals('TEST_P4VARIABLE_PASSWORD', $password);
@ -276,10 +276,10 @@ class PerforceTest extends TestCase
public function testQueryP4PasswordQueriesForPassword() public function testQueryP4PasswordQueriesForPassword()
{ {
$expectedQuestion = 'Enter password for Perforce user user: '; $expectedQuestion = 'Enter password for Perforce user user: ';
$this->io->expects($this->at(0)) $this->io->expects($this->once())
->method('askAndHideAnswer') ->method('askAndHideAnswer')
->with($this->equalTo($expectedQuestion)) ->with($this->equalTo($expectedQuestion))
->will($this->returnValue('TEST_QUERY_PASSWORD')); ->willReturn('TEST_QUERY_PASSWORD');
$password = $this->perforce->queryP4Password(); $password = $this->perforce->queryP4Password();
$this->assertEquals('TEST_QUERY_PASSWORD', $password); $this->assertEquals('TEST_QUERY_PASSWORD', $password);
@ -329,10 +329,10 @@ class PerforceTest extends TestCase
public function testIsLoggedIn() public function testIsLoggedIn()
{ {
$expectedCommand = 'p4 -u user -p port login -s'; $expectedCommand = 'p4 -u user -p port login -s';
$this->processExecutor->expects($this->at(0)) $this->processExecutor->expects($this->once())
->method('execute') ->method('execute')
->with($this->equalTo($expectedCommand), $this->equalTo(null)) ->with($this->equalTo($expectedCommand), $this->equalTo(null))
->will($this->returnValue(0)); ->willReturn(0);
$this->perforce->isLoggedIn(); $this->perforce->isLoggedIn();
} }
@ -340,10 +340,10 @@ class PerforceTest extends TestCase
public function testConnectClient() public function testConnectClient()
{ {
$expectedCommand = 'p4 -u user -c composer_perforce_TEST_depot -p port client -i < path/composer_perforce_TEST_depot.p4.spec'; $expectedCommand = 'p4 -u user -c composer_perforce_TEST_depot -p port client -i < path/composer_perforce_TEST_depot.p4.spec';
$this->processExecutor->expects($this->at(0)) $this->processExecutor->expects($this->once())
->method('execute') ->method('execute')
->with($this->equalTo($expectedCommand), $this->equalTo(null)) ->with($this->equalTo($expectedCommand), $this->equalTo(null))
->will($this->returnValue(0)); ->willReturn(0);
$this->perforce->connectClient(); $this->perforce->connectClient();
} }
@ -352,29 +352,26 @@ class PerforceTest extends TestCase
{ {
$this->setPerforceToStream(); $this->setPerforceToStream();
$expectedCommand = 'p4 -u user -c composer_perforce_TEST_depot_branch -p port streams '.ProcessExecutor::escape('//depot/...'); $expectations = [
$this->processExecutor->expects($this->at(0)) ['p4 -u user -c composer_perforce_TEST_depot_branch -p port streams '.ProcessExecutor::escape('//depot/...'), 'Stream //depot/branch mainline none \'branch\'' . PHP_EOL],
['p4 -u user -p port changes '.ProcessExecutor::escape('//depot/branch/...'), 'Change 1234 on 2014/03/19 by Clark.Stuth@Clark.Stuth_test_client \'test changelist\''],
];
$count = 0;
$this->processExecutor->expects($this->exactly(2))
->method('execute') ->method('execute')
->with($this->equalTo($expectedCommand))
->will( ->will(
$this->returnCallback( $this->returnCallback(
function ($command, &$output) { function ($command, &$output) use ($expectations, &$count) {
$output = 'Stream //depot/branch mainline none \'branch\'' . PHP_EOL; $index = $count++;
if ($command !== $expectations[$index][0]) {
return true; throw new \InvalidArgumentException('Expected '.$expectations[$index][0].' and got '.$command);
}
$output = $expectations[$index][1];
return 0;
} }
) )
); );
$expectedCommand2 = 'p4 -u user -p port changes '.ProcessExecutor::escape('//depot/branch/...');
$expectedCallback = function ($command, &$output) {
$output = 'Change 1234 on 2014/03/19 by Clark.Stuth@Clark.Stuth_test_client \'test changelist\'';
return true;
};
$this->processExecutor->expects($this->at(1))
->method('execute')
->with($this->equalTo($expectedCommand2))
->will($this->returnCallback($expectedCallback));
$branches = $this->perforce->getBranches(); $branches = $this->perforce->getBranches();
$this->assertEquals('//depot/branch@1234', $branches['master']); $this->assertEquals('//depot/branch@1234', $branches['master']);
@ -391,7 +388,7 @@ class PerforceTest extends TestCase
$this->processExecutor->expects($this->once()) $this->processExecutor->expects($this->once())
->method('execute') ->method('execute')
->with($this->equalTo($expectedCommand)) ->with($this->equalTo($expectedCommand))
->will($this->returnCallback($expectedCallback)); ->willReturnCallback($expectedCallback);
$branches = $this->perforce->getBranches(); $branches = $this->perforce->getBranches();
$this->assertEquals('//depot@5678', $branches['master']); $this->assertEquals('//depot@5678', $branches['master']);
} }
@ -399,7 +396,7 @@ class PerforceTest extends TestCase
public function testGetTagsWithoutStream() public function testGetTagsWithoutStream()
{ {
$expectedCommand = 'p4 -u user -c composer_perforce_TEST_depot -p port labels'; $expectedCommand = 'p4 -u user -c composer_perforce_TEST_depot -p port labels';
$this->processExecutor->expects($this->at(0)) $this->processExecutor->expects($this->once())
->method('execute') ->method('execute')
->with($this->equalTo($expectedCommand)) ->with($this->equalTo($expectedCommand))
->will( ->will(
@ -422,7 +419,7 @@ class PerforceTest extends TestCase
$this->setPerforceToStream(); $this->setPerforceToStream();
$expectedCommand = 'p4 -u user -c composer_perforce_TEST_depot_branch -p port labels'; $expectedCommand = 'p4 -u user -c composer_perforce_TEST_depot_branch -p port labels';
$this->processExecutor->expects($this->at(0)) $this->processExecutor->expects($this->once())
->method('execute') ->method('execute')
->with($this->equalTo($expectedCommand)) ->with($this->equalTo($expectedCommand))
->will( ->will(
@ -467,7 +464,7 @@ class PerforceTest extends TestCase
public function testGetComposerInformationWithoutLabelWithoutStream() public function testGetComposerInformationWithoutLabelWithoutStream()
{ {
$expectedCommand = 'p4 -u user -c composer_perforce_TEST_depot -p port print '.ProcessExecutor::escape('//depot/composer.json'); $expectedCommand = 'p4 -u user -c composer_perforce_TEST_depot -p port print '.ProcessExecutor::escape('//depot/composer.json');
$this->processExecutor->expects($this->at(0)) $this->processExecutor->expects($this->once())
->method('execute') ->method('execute')
->with($this->equalTo($expectedCommand)) ->with($this->equalTo($expectedCommand))
->will( ->will(
@ -492,30 +489,23 @@ class PerforceTest extends TestCase
public function testGetComposerInformationWithLabelWithoutStream() public function testGetComposerInformationWithLabelWithoutStream()
{ {
$expectedCommand = 'p4 -u user -p port files '.ProcessExecutor::escape('//depot/composer.json@0.0.1'); $expectations = [
$this->processExecutor->expects($this->at(0)) ['p4 -u user -p port files '.ProcessExecutor::escape('//depot/composer.json@0.0.1'), '//depot/composer.json#1 - branch change 10001 (text)'],
['p4 -u user -c composer_perforce_TEST_depot -p port print '.ProcessExecutor::escape('//depot/composer.json@10001'), PerforceTest::getComposerJson()],
];
$count = 0;
$this->processExecutor->expects($this->exactly(2))
->method('execute') ->method('execute')
->with($this->equalTo($expectedCommand))
->will( ->will(
$this->returnCallback( $this->returnCallback(
function ($command, &$output) { function ($command, &$output) use ($expectations, &$count) {
$output = '//depot/composer.json#1 - branch change 10001 (text)'; $index = $count++;
if ($command !== $expectations[$index][0]) {
return true; throw new \InvalidArgumentException('Expected '.$expectations[$index][0].' and got '.$command);
} }
) $output = $expectations[$index][1];
);
return 0;
$expectedCommand = 'p4 -u user -c composer_perforce_TEST_depot -p port print '.ProcessExecutor::escape('//depot/composer.json@10001');
$this->processExecutor->expects($this->at(1))
->method('execute')
->with($this->equalTo($expectedCommand))
->will(
$this->returnCallback(
function ($command, &$output) {
$output = PerforceTest::getComposerJson();
return true;
} }
) )
); );
@ -536,7 +526,7 @@ class PerforceTest extends TestCase
$this->setPerforceToStream(); $this->setPerforceToStream();
$expectedCommand = 'p4 -u user -c composer_perforce_TEST_depot_branch -p port print '.ProcessExecutor::escape('//depot/branch/composer.json'); $expectedCommand = 'p4 -u user -c composer_perforce_TEST_depot_branch -p port print '.ProcessExecutor::escape('//depot/branch/composer.json');
$this->processExecutor->expects($this->at(0)) $this->processExecutor->expects($this->once())
->method('execute') ->method('execute')
->with($this->equalTo($expectedCommand)) ->with($this->equalTo($expectedCommand))
->will( ->will(
@ -562,34 +552,28 @@ class PerforceTest extends TestCase
public function testGetComposerInformationWithLabelWithStream() public function testGetComposerInformationWithLabelWithStream()
{ {
$this->setPerforceToStream(); $expectations = [
$expectedCommand = 'p4 -u user -p port files '.ProcessExecutor::escape('//depot/branch/composer.json@0.0.1'); [ 'p4 -u user -p port files '.ProcessExecutor::escape('//depot/branch/composer.json@0.0.1'), '//depot/composer.json#1 - branch change 10001 (text)'],
$this->processExecutor->expects($this->at(0)) ['p4 -u user -c composer_perforce_TEST_depot_branch -p port print '.ProcessExecutor::escape('//depot/branch/composer.json@10001'), PerforceTest::getComposerJson()],
];
$count = 0;
$this->processExecutor->expects($this->exactly(2))
->method('execute') ->method('execute')
->with($this->equalTo($expectedCommand))
->will( ->will(
$this->returnCallback( $this->returnCallback(
function ($command, &$output) { function ($command, &$output) use ($expectations, &$count) {
$output = '//depot/composer.json#1 - branch change 10001 (text)'; $index = $count++;
if ($command !== $expectations[$index][0]) {
return true; throw new \InvalidArgumentException('Expected '.$expectations[$index][0].' and got '.$command);
}
$output = $expectations[$index][1];
return 0;
} }
) )
); );
$expectedCommand = 'p4 -u user -c composer_perforce_TEST_depot_branch -p port print '.ProcessExecutor::escape('//depot/branch/composer.json@10001'); $this->setPerforceToStream();
$this->processExecutor->expects($this->at(1))
->method('execute')
->with($this->equalTo($expectedCommand))
->will(
$this->returnCallback(
function ($command, &$output) {
$output = PerforceTest::getComposerJson();
return true;
}
)
);
$result = $this->perforce->getComposerInformation('//depot/branch@0.0.1'); $result = $this->perforce->getComposerInformation('//depot/branch@0.0.1');
@ -605,10 +589,10 @@ class PerforceTest extends TestCase
public function testSyncCodeBaseWithoutStream() public function testSyncCodeBaseWithoutStream()
{ {
$expectedCommand = 'p4 -u user -c composer_perforce_TEST_depot -p port sync -f @label'; $expectedCommand = 'p4 -u user -c composer_perforce_TEST_depot -p port sync -f @label';
$this->processExecutor->expects($this->at(0)) $this->processExecutor->expects($this->once())
->method('execute') ->method('execute')
->with($this->equalTo($expectedCommand), $this->equalTo(null)) ->with($this->equalTo($expectedCommand), $this->equalTo(null))
->will($this->returnValue(0)); ->willReturn(0);
$this->perforce->syncCodeBase('label'); $this->perforce->syncCodeBase('label');
} }
@ -617,10 +601,10 @@ class PerforceTest extends TestCase
{ {
$this->setPerforceToStream(); $this->setPerforceToStream();
$expectedCommand = 'p4 -u user -c composer_perforce_TEST_depot_branch -p port sync -f @label'; $expectedCommand = 'p4 -u user -c composer_perforce_TEST_depot_branch -p port sync -f @label';
$this->processExecutor->expects($this->at(0)) $this->processExecutor->expects($this->once())
->method('execute') ->method('execute')
->with($this->equalTo($expectedCommand)) ->with($this->equalTo($expectedCommand))
->will($this->returnValue(0)); ->willReturn(0);
$this->perforce->syncCodeBase('label'); $this->perforce->syncCodeBase('label');
} }
@ -630,10 +614,10 @@ class PerforceTest extends TestCase
$processExecutor = $this->getMockBuilder('Composer\Util\ProcessExecutor')->getMock(); $processExecutor = $this->getMockBuilder('Composer\Util\ProcessExecutor')->getMock();
$expectedCommand = 'p4 -p '.ProcessExecutor::escape('perforce.does.exist:port').' info -s'; $expectedCommand = 'p4 -p '.ProcessExecutor::escape('perforce.does.exist:port').' info -s';
$processExecutor->expects($this->at(0)) $processExecutor->expects($this->once())
->method('execute') ->method('execute')
->with($this->equalTo($expectedCommand), $this->equalTo(null)) ->with($this->equalTo($expectedCommand), $this->equalTo(null))
->will($this->returnValue(0)); ->willReturn(0);
$result = $this->perforce->checkServerExists('perforce.does.exist:port', $processExecutor); $result = $this->perforce->checkServerExists('perforce.does.exist:port', $processExecutor);
$this->assertTrue($result); $this->assertTrue($result);
@ -651,10 +635,10 @@ class PerforceTest extends TestCase
$processExecutor = $this->getMockBuilder('Composer\Util\ProcessExecutor')->getMock(); $processExecutor = $this->getMockBuilder('Composer\Util\ProcessExecutor')->getMock();
$expectedCommand = 'p4 -p '.ProcessExecutor::escape('perforce.does.exist:port').' info -s'; $expectedCommand = 'p4 -p '.ProcessExecutor::escape('perforce.does.exist:port').' info -s';
$processExecutor->expects($this->at(0)) $processExecutor->expects($this->once())
->method('execute') ->method('execute')
->with($this->equalTo($expectedCommand), $this->equalTo(null)) ->with($this->equalTo($expectedCommand), $this->equalTo(null))
->will($this->returnValue(127)); ->willReturn(127);
$result = $this->perforce->checkServerExists('perforce.does.exist:port', $processExecutor); $result = $this->perforce->checkServerExists('perforce.does.exist:port', $processExecutor);
$this->assertFalse($result); $this->assertFalse($result);
@ -665,19 +649,14 @@ class PerforceTest extends TestCase
*/ */
public static function getComposerJson() public static function getComposerJson()
{ {
$composer_json = array( return JsonFile::encode([
'{', 'name' => 'test/perforce',
'"name": "test/perforce",', 'description' => 'Basic project for testing',
'"description": "Basic project for testing",', 'minimum-stability' => 'dev',
'"minimum-stability": "dev",', 'autoload' => [
'"autoload": {', 'psr-0' => []
'"psr-0" : {', ]
'}', ], JSON_FORCE_OBJECT);
'}',
'}',
);
return implode($composer_json);
} }
/** /**

@ -206,20 +206,19 @@ class RemoteFilesystemTest extends TestCase
'retry' => true, 'retry' => true,
)); ));
$fs->expects($this->at(0)) $counter = 0;
$fs->expects($this->exactly(2))
->method('getRemoteContents') ->method('getRemoteContents')
->willReturnCallback(function ($originUrl, $fileUrl, $ctx, &$http_response_header) { ->willReturnCallback(function ($originUrl, $fileUrl, $ctx, &$http_response_header) use (&$counter) {
$http_response_header = array('http/1.1 401 unauthorized'); if ($counter++ === 0) {
$http_response_header = array('http/1.1 401 unauthorized');
return ''; return '';
}); } else {
$http_response_header = array('http/1.1 200 OK');
$fs->expects($this->at(1)) return '<?php $copied = "Copied"; ';
->method('getRemoteContents') }
->willReturnCallback(function ($originUrl, $fileUrl, $ctx, &$http_response_header) {
$http_response_header = array('http/1.1 200 OK');
return '<?php $copied = "Copied"; ';
}); });
$file = tempnam(sys_get_temp_dir(), 'z'); $file = tempnam(sys_get_temp_dir(), 'z');
@ -324,8 +323,7 @@ class RemoteFilesystemTest extends TestCase
return $arg === 'bitbucket.org'; return $arg === 'bitbucket.org';
}); });
$io $io
->expects($this->at(1)) ->method('getAuthentication')
->method('getAuthentication')
->with('bitbucket.org') ->with('bitbucket.org')
->willReturn(array( ->willReturn(array(
'username' => 'x-token-auth', 'username' => 'x-token-auth',

@ -26,6 +26,7 @@ class StreamContextFactoryTest extends TestCase
protected function tearDown(): void 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']); unset($_SERVER['HTTP_PROXY'], $_SERVER['http_proxy'], $_SERVER['HTTPS_PROXY'], $_SERVER['https_proxy'], $_SERVER['NO_PROXY'], $_SERVER['no_proxy']);
ProxyManager::reset(); ProxyManager::reset();
} }

@ -16,7 +16,6 @@
> >
<php> <php>
<env name="SYMFONY_DEPRECATIONS_HELPER" value="weak"/> <env name="SYMFONY_DEPRECATIONS_HELPER" value="weak"/>
<env name="SYMFONY_PHPUNIT_REMOVE_RETURN_TYPEHINT" value="1"/>
</php> </php>
<testsuites> <testsuites>
<testsuite name="Full Composer Test Suite"> <testsuite name="Full Composer Test Suite">

Loading…
Cancel
Save