From 9b99079cefa2a5a5614c23199d95127591f7f77f Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Thu, 9 Dec 2021 17:09:07 +0100 Subject: [PATCH] Get rid of all the ->at() mock invocations --- composer.json | 8 +- composer.lock | 16 +- phpstan/locate-phpunit-autoloader.php | 2 +- phpunit.xml.dist | 1 - src/Composer/Util/Http/Response.php | 4 +- src/Composer/Util/Svn.php | 2 +- tests/Composer/Test/AllFunctionalTest.php | 3 +- tests/Composer/Test/ApplicationTest.php | 80 +++---- .../Test/Autoload/AutoloadGeneratorTest.php | 29 +-- tests/Composer/Test/CacheTest.php | 1 + .../Test/Config/JsonConfigSourceTest.php | 1 + .../Test/Downloader/DownloadManagerTest.php | 23 +- .../Test/Downloader/FileDownloaderTest.php | 28 +-- .../Test/Downloader/FossilDownloaderTest.php | 15 +- .../Test/Downloader/GitDownloaderTest.php | 60 ++--- .../Test/Downloader/HgDownloaderTest.php | 15 +- .../Downloader/PerforceDownloaderTest.php | 30 +-- .../Test/Downloader/XzDownloaderTest.php | 3 +- .../Test/Downloader/ZipDownloaderTest.php | 3 +- .../EventDispatcher/EventDispatcherTest.php | 56 ++--- tests/Composer/Test/IO/ConsoleIOTest.php | 40 ++-- .../Test/Installer/BinaryInstallerTest.php | 1 + .../Test/Installer/LibraryInstallerTest.php | 1 + .../SuggestedPackagesReporterTest.php | 80 +++---- tests/Composer/Test/InstallerTest.php | 3 +- .../Composer/Test/Mock/HttpDownloaderMock.php | 107 ++++++++- .../Test/Mock/ProcessExecutorMock.php | 22 +- .../Archiver/ArchivableFilesFinderTest.php | 1 + .../Test/Package/Archiver/ArchiverTest.php | 3 +- .../Package/Loader/RootPackageLoaderTest.php | 10 +- .../Package/Version/VersionGuesserTest.php | 56 ++--- .../Package/Version/VersionSelectorTest.php | 12 +- .../Test/Plugin/PluginInstallerTest.php | 1 + tests/Composer/Test/PolyfillTestCase.php | 137 ------------ .../Repository/ComposerRepositoryTest.php | 64 ++++-- .../Test/Repository/RepositoryManagerTest.php | 3 +- .../Test/Repository/Vcs/FossilDriverTest.php | 3 +- .../Repository/Vcs/GitBitbucketDriverTest.php | 3 +- .../Test/Repository/Vcs/GitHubDriverTest.php | 136 +++++------ .../Test/Repository/Vcs/GitLabDriverTest.php | 168 +++++++------- .../Test/Repository/Vcs/HgDriverTest.php | 3 +- .../Repository/Vcs/PerforceDriverTest.php | 11 +- .../Test/Repository/Vcs/SvnDriverTest.php | 18 +- tests/Composer/Test/TestCase.php | 40 +++- tests/Composer/Test/Util/BitbucketTest.php | 8 +- tests/Composer/Test/Util/ErrorHandlerTest.php | 3 +- tests/Composer/Test/Util/FilesystemTest.php | 3 +- tests/Composer/Test/Util/GitHubTest.php | 41 +--- tests/Composer/Test/Util/GitLabTest.php | 48 ++-- tests/Composer/Test/Util/GitTest.php | 8 +- .../Test/Util/Http/ProxyHelperTest.php | 1 + .../Test/Util/Http/ProxyManagerTest.php | 1 + tests/Composer/Test/Util/PerforceTest.php | 211 ++++++++---------- .../Test/Util/RemoteFilesystemTest.php | 24 +- .../Test/Util/StreamContextFactoryTest.php | 1 + tests/complete.phpunit.xml | 1 - 56 files changed, 742 insertions(+), 911 deletions(-) delete mode 100644 tests/Composer/Test/PolyfillTestCase.php diff --git a/composer.json b/composer.json index f9e24e15b0da..3141e0ad8377 100644 --- a/composer.json +++ b/composer.json @@ -21,9 +21,6 @@ "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": { "php": "^7.2.5 || ^8.0", "composer/ca-bundle": "^1.0", @@ -35,13 +32,12 @@ "psr/log": "^1.0 || ^2.0", "seld/jsonlint": "^1.4", "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/finder": "^5.4 || ^6.0", "symfony/process": "^5.4 || ^6.0", "react/promise": "^2.8", - "composer/pcre": "^1.0", - "symfony/polyfill-php73": "^1.9" + "composer/pcre": "^1.0" }, "require-dev": { "symfony/phpunit-bridge": "^6.0", diff --git a/composer.lock b/composer.lock index 5c34ed2ce327..1ddfc319d594 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "21b7ce031989ab306ee91098fa461436", + "content-hash": "274d271909468b2a6c06b562724a1662", "packages": [ { "name": "composer/ca-bundle", @@ -780,23 +780,23 @@ }, { "name": "symfony/console", - "version": "v5.4.0", + "version": "v5.4.1", "source": { "type": "git", "url": "https://github.com/symfony/console.git", - "reference": "ec3661faca1d110d6c307e124b44f99ac54179e3" + "reference": "9130e1a0fc93cb0faadca4ee917171bd2ca9e5f4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/ec3661faca1d110d6c307e124b44f99ac54179e3", - "reference": "ec3661faca1d110d6c307e124b44f99ac54179e3", + "url": "https://api.github.com/repos/symfony/console/zipball/9130e1a0fc93cb0faadca4ee917171bd2ca9e5f4", + "reference": "9130e1a0fc93cb0faadca4ee917171bd2ca9e5f4", "shasum": "" }, "require": { "php": ">=7.2.5", "symfony/deprecation-contracts": "^2.1|^3", "symfony/polyfill-mbstring": "~1.0", - "symfony/polyfill-php73": "^1.8", + "symfony/polyfill-php73": "^1.9", "symfony/polyfill-php80": "^1.16", "symfony/service-contracts": "^1.1|^2|^3", "symfony/string": "^5.1|^6.0" @@ -859,7 +859,7 @@ "terminal" ], "support": { - "source": "https://github.com/symfony/console/tree/v5.4.0" + "source": "https://github.com/symfony/console/tree/v5.4.1" }, "funding": [ { @@ -875,7 +875,7 @@ "type": "tidelift" } ], - "time": "2021-11-29T15:30:56+00:00" + "time": "2021-12-09T11:22:43+00:00" }, { "name": "symfony/deprecation-contracts", diff --git a/phpstan/locate-phpunit-autoloader.php b/phpstan/locate-phpunit-autoloader.php index ec8251bb753b..93a179389a32 100644 --- a/phpstan/locate-phpunit-autoloader.php +++ b/phpstan/locate-phpunit-autoloader.php @@ -1,7 +1,7 @@ - diff --git a/src/Composer/Util/Http/Response.php b/src/Composer/Util/Http/Response.php index d94638ae40ab..39c68d6f2c2a 100644 --- a/src/Composer/Util/Http/Response.php +++ b/src/Composer/Util/Http/Response.php @@ -25,7 +25,7 @@ class Response private $request; /** @var int */ private $code; - /** @var string[] */ + /** @var list */ private $headers; /** @var ?string */ private $body; @@ -33,7 +33,7 @@ class Response /** * @param Request $request * @param int $code - * @param string[] $headers + * @param list $headers * @param ?string $body */ public function __construct(array $request, $code, array $headers, $body) diff --git a/src/Composer/Util/Svn.php b/src/Composer/Util/Svn.php index 3338020359ee..562cf5fd2e92 100644 --- a/src/Composer/Util/Svn.php +++ b/src/Composer/Util/Svn.php @@ -165,7 +165,7 @@ private function executeWithAuthRetry($svnCommand, $cwd, $url, $path, $verbose) } $errorOutput = $this->process->getErrorOutput(); - $fullOutput = implode("\n", array($output, $errorOutput)); + $fullOutput = trim(implode("\n", array($output, $errorOutput))); // the error is not auth-related if (false === stripos($fullOutput, 'Could not authenticate to server:') diff --git a/tests/Composer/Test/AllFunctionalTest.php b/tests/Composer/Test/AllFunctionalTest.php index bec7958212a4..07fcbf7a69ff 100644 --- a/tests/Composer/Test/AllFunctionalTest.php +++ b/tests/Composer/Test/AllFunctionalTest.php @@ -38,8 +38,9 @@ public function setUp(): void chdir(__DIR__.'/Fixtures/functional'); } - public function tearDown(): void + protected function tearDown(): void { + parent::tearDown(); if ($this->oldcwd) { chdir($this->oldcwd); } diff --git a/tests/Composer/Test/ApplicationTest.php b/tests/Composer/Test/ApplicationTest.php index f2303243706a..6d48bc58a0d4 100644 --- a/tests/Composer/Test/ApplicationTest.php +++ b/tests/Composer/Test/ApplicationTest.php @@ -14,11 +14,12 @@ use Composer\Console\Application; use Composer\XdebugHandler\XdebugHandler; +use Symfony\Component\Console\Output\BufferedOutput; use Symfony\Component\Console\Output\OutputInterface; class ApplicationTest extends TestCase { - public function tearDown(): void + protected function tearDown(): void { parent::tearDown(); @@ -34,22 +35,24 @@ public function testDevWarning() putenv('COMPOSER_NO_INTERACTION=1'); - $index = 0; - $inputMock->expects($this->at($index++)) + $inputMock->expects($this->any()) ->method('hasParameterOption') - ->with($this->equalTo('--no-plugins')) - ->will($this->returnValue(true)); - - $inputMock->expects($this->at($index++)) + ->willReturnCallback(function ($opt): bool { + switch ($opt) { + case '--no-plugins': + return true; + case '--no-cache': + return false; + } + + return false; + }); + + $inputMock->expects($this->once()) ->method('setInteractive') ->with($this->equalTo(false)); - $inputMock->expects($this->at($index++)) - ->method('hasParameterOption') - ->with($this->equalTo('--no-cache')) - ->will($this->returnValue(false)); - - $inputMock->expects($this->at($index++)) + $inputMock->expects($this->once()) ->method('getParameterOption') ->with($this->equalTo(array('--working-dir', '-d'))) ->will($this->returnValue(false)); @@ -58,33 +61,22 @@ public function testDevWarning() ->method('getFirstArgument') ->will($this->returnValue('show')); - $index = 0; - $outputMock->expects($this->at($index++)) - ->method("write"); + $output = new BufferedOutput(); + $expectedOutput = ''; if (XdebugHandler::isXdebugActive()) { - $outputMock->expects($this->at($index++)) - ->method("getVerbosity") - ->willReturn(OutputInterface::VERBOSITY_NORMAL); - - $outputMock->expects($this->at($index++)) - ->method("write") - ->with($this->equalTo('Composer is operating slower than normal because you have Xdebug enabled. See https://getcomposer.org/xdebug')); + $expectedOutput .= 'Composer is operating slower than normal because you have Xdebug enabled. See https://getcomposer.org/xdebug'.PHP_EOL; } - $outputMock->expects($this->at($index++)) - ->method("getVerbosity") - ->willReturn(OutputInterface::VERBOSITY_NORMAL); - - $outputMock->expects($this->at($index++)) - ->method("write") - ->with($this->equalTo(sprintf('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.', $_SERVER['PHP_SELF']))); + $expectedOutput .= sprintf('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.', $_SERVER['PHP_SELF']).PHP_EOL; if (!defined('COMPOSER_DEV_WARNING_TIME')) { define('COMPOSER_DEV_WARNING_TIME', time() - 1); } - $application->doRun($inputMock, $outputMock); + $application->doRun($inputMock, $output); + + $this->assertStringContainsString($expectedOutput, $output->fetch()); } /** @@ -102,22 +94,24 @@ public function ensureNoDevWarning($command) putenv('COMPOSER_NO_INTERACTION=1'); - $index = 0; - $inputMock->expects($this->at($index++)) + $inputMock->expects($this->any()) ->method('hasParameterOption') - ->with($this->equalTo('--no-plugins')) - ->will($this->returnValue(true)); - - $inputMock->expects($this->at($index++)) + ->willReturnCallback(function ($opt): bool { + switch ($opt) { + case '--no-plugins': + return true; + case '--no-cache': + return false; + } + + return false; + }); + + $inputMock->expects($this->once()) ->method('setInteractive') ->with($this->equalTo(false)); - $inputMock->expects($this->at($index++)) - ->method('hasParameterOption') - ->with($this->equalTo('--no-cache')) - ->will($this->returnValue(false)); - - $inputMock->expects($this->at($index++)) + $inputMock->expects($this->once()) ->method('getParameterOption') ->with($this->equalTo(array('--working-dir', '-d'))) ->will($this->returnValue(false)); diff --git a/tests/Composer/Test/Autoload/AutoloadGeneratorTest.php b/tests/Composer/Test/Autoload/AutoloadGeneratorTest.php index 396477e7aaef..dc6561d70fc5 100644 --- a/tests/Composer/Test/Autoload/AutoloadGeneratorTest.php +++ b/tests/Composer/Test/Autoload/AutoloadGeneratorTest.php @@ -150,6 +150,7 @@ protected function setUp(): void protected function tearDown(): void { + parent::tearDown(); chdir($this->origDir); if (is_dir($this->workingDir)) { @@ -957,17 +958,13 @@ public function testFilesAutoloadGenerationRemoveExtraEntitiesFromAutoloadFiles( $notAutoloadPackages[] = $b = new Package('b/b', '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') - ->will($this->returnValue($autoloadPackages)); - - $this->repository->expects($this->at(3)) - ->method('getCanonicalPackages') - ->will($this->returnValue($notAutoloadPackages)); - - $this->repository->expects($this->at(5)) - ->method('getCanonicalPackages') - ->will($this->returnValue($notAutoloadPackages)); + ->willReturnOnConsecutiveCalls( + $autoloadPackages, + $notAutoloadPackages, + $notAutoloadPackages + ); $this->fs->ensureDirectoryExists($this->vendorDir.'/a/a'); $this->fs->ensureDirectoryExists($this->vendorDir.'/b/b'); @@ -1283,14 +1280,12 @@ public function testIncludePathFileWithoutPathsIsSkipped() public function testPreAndPostEventsAreDispatchedDuringAutoloadDump() { $this->eventDispatcher - ->expects($this->at(0)) - ->method('dispatchScript') - ->with(ScriptEvents::PRE_AUTOLOAD_DUMP, false); - - $this->eventDispatcher - ->expects($this->at(1)) + ->expects($this->exactly(2)) ->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->setAutoload(array('psr-0' => array('Prefix' => 'foo/bar/non/existing/'))); diff --git a/tests/Composer/Test/CacheTest.php b/tests/Composer/Test/CacheTest.php index 2429c303f297..4d0ede656bf1 100644 --- a/tests/Composer/Test/CacheTest.php +++ b/tests/Composer/Test/CacheTest.php @@ -55,6 +55,7 @@ public function setUp(): void protected function tearDown(): void { + parent::tearDown(); if (is_dir($this->root)) { $fs = new Filesystem; $fs->removeDirectory($this->root); diff --git a/tests/Composer/Test/Config/JsonConfigSourceTest.php b/tests/Composer/Test/Config/JsonConfigSourceTest.php index 1f725004f22c..3d9e68980645 100644 --- a/tests/Composer/Test/Config/JsonConfigSourceTest.php +++ b/tests/Composer/Test/Config/JsonConfigSourceTest.php @@ -42,6 +42,7 @@ protected function setUp(): void protected function tearDown(): void { + parent::tearDown(); if (is_dir($this->workingDir)) { $this->fs->removeDirectory($this->workingDir); } diff --git a/tests/Composer/Test/Downloader/DownloadManagerTest.php b/tests/Composer/Test/Downloader/DownloadManagerTest.php index eca909696457..d2f03aa3f895 100644 --- a/tests/Composer/Test/Downloader/DownloadManagerTest.php +++ b/tests/Composer/Test/Downloader/DownloadManagerTest.php @@ -254,13 +254,12 @@ public function testFullPackageDownloadFailover() ->will($this->returnValue('prettyPackage')); $package - ->expects($this->at(3)) - ->method('setInstallationSource') - ->with('dist'); - $package - ->expects($this->at(5)) + ->expects($this->exactly(2)) ->method('setInstallationSource') - ->with('source'); + ->withConsecutive( + ['dist'], + ['source'] + ); $downloaderFail = $this->createDownloaderMock(); $downloaderFail @@ -280,15 +279,13 @@ public function testFullPackageDownloadFailover() ->setMethods(array('getDownloaderForPackage')) ->getMock(); $manager - ->expects($this->at(0)) - ->method('getDownloaderForPackage') - ->with($package) - ->will($this->returnValue($downloaderFail)); - $manager - ->expects($this->at(1)) + ->expects($this->exactly(2)) ->method('getDownloaderForPackage') ->with($package) - ->will($this->returnValue($downloaderSuccess)); + ->willReturnOnConsecutiveCalls( + $downloaderFail, + $downloaderSuccess + ); $manager->download($package, 'target_dir'); } diff --git a/tests/Composer/Test/Downloader/FileDownloaderTest.php b/tests/Composer/Test/Downloader/FileDownloaderTest.php index 047b2c8db95e..f8e617f0b380 100644 --- a/tests/Composer/Test/Downloader/FileDownloaderTest.php +++ b/tests/Composer/Test/Downloader/FileDownloaderTest.php @@ -220,7 +220,7 @@ public function testDownloadWithCustomProcessedUrl() $dispatcher = new EventDispatcher( $composerMock, $this->getMockBuilder('Composer\IO\IOInterface')->getMock(), - new ProcessExecutorMock + $this->getProcessExecutorMock() ); $dispatcher->addListener(PluginEvents::PRE_FILE_DOWNLOAD, function (PreFileDownloadEvent $event) use ($expectedUrl) { $event->setProcessedUrl($expectedUrl); @@ -322,7 +322,7 @@ public function testDownloadWithCustomCacheKey() $dispatcher = new EventDispatcher( $composerMock, $this->getMockBuilder('Composer\IO\IOInterface')->getMock(), - new ProcessExecutorMock + $this->getProcessExecutorMock() ); $dispatcher->addListener(PluginEvents::PRE_FILE_DOWNLOAD, function (PreFileDownloadEvent $event) use ($customCacheKey) { $event->setCustomCacheKey($customCacheKey); @@ -387,15 +387,12 @@ public function testCacheGarbageCollectionIsCalled() $this->config = $this->getMockBuilder('Composer\Config')->getMock(); $this->config - ->expects($this->at(0)) + ->expects($this->atLeast(2)) ->method('get') - ->with('cache-files-ttl') - ->will($this->returnValue($expectedTtl)); - $this->config - ->expects($this->at(1)) - ->method('get') - ->with('cache-files-maxsize') - ->will($this->returnValue('500M')); + ->willReturnMap([ + ['cache-files-ttl', 0, $expectedTtl], + ['cache-files-maxsize', 0, '500M'], + ]); $cacheMock = $this->getMockBuilder('Composer\Cache') ->disableOriginalConstructor() @@ -492,13 +489,12 @@ public function testDowngradeShowsAppropriateMessage() ->will($this->returnValue(array($distUrl))); $ioMock = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); - $ioMock->expects($this->at(0)) - ->method('writeError') - ->with($this->stringContains('Downloading')); - - $ioMock->expects($this->at(1)) + $ioMock->expects($this->atLeast(2)) ->method('writeError') - ->with($this->stringContains('Downgrading')); + ->withConsecutive( + [$this->stringContains('Downloading')], + [$this->stringContains('Downgrading')] + ); $path = $this->getUniqueTmpDirectory(); $filesystem = $this->getMockBuilder('Composer\Util\Filesystem')->getMock(); diff --git a/tests/Composer/Test/Downloader/FossilDownloaderTest.php b/tests/Composer/Test/Downloader/FossilDownloaderTest.php index dd15eff913bb..db26b9d8cb7a 100644 --- a/tests/Composer/Test/Downloader/FossilDownloaderTest.php +++ b/tests/Composer/Test/Downloader/FossilDownloaderTest.php @@ -29,6 +29,7 @@ protected function setUp(): void protected function tearDown(): void { + parent::tearDown(); if (is_dir($this->workingDir)) { $fs = new Filesystem; $fs->removeDirectory($this->workingDir); @@ -46,7 +47,7 @@ protected function getDownloaderMock($io = null, $config = null, $executor = nul { $io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $config = $config ?: $this->getMockBuilder('Composer\Config')->getMock(); - $executor = $executor ?: new ProcessExecutorMock; + $executor = $executor ?: $this->getProcessExecutorMock(); $filesystem = $filesystem ?: $this->getMockBuilder('Composer\Util\Filesystem')->getMock(); return new FossilDownloader($io, $config, $executor, $filesystem); @@ -75,7 +76,7 @@ public function testInstall() ->method('getSourceUrls') ->will($this->returnValue(array('http://fossil.kd2.org/kd2fw/'))); - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( $this->getCmd('fossil clone -- \'http://fossil.kd2.org/kd2fw/\' \'repo.fossil\''), $this->getCmd('fossil open --nested -- \'repo.fossil\''), @@ -84,8 +85,6 @@ public function testInstall() $downloader = $this->getDownloaderMock(null, null, $process); $downloader->install($packageMock, 'repo'); - - $process->assertComplete($this); } public function testUpdateforPackageWithoutSourceReference() @@ -124,7 +123,7 @@ public function testUpdate() ->method('getVersion') ->will($this->returnValue('1.0.0.0')); - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( $this->getCmd("fossil changes"), $this->getCmd("fossil pull && fossil up 'trunk'"), @@ -134,8 +133,6 @@ public function testUpdate() $downloader->prepare('update', $packageMock, $this->workingDir, $packageMock); $downloader->update($packageMock, $packageMock, $this->workingDir); $downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock); - - $process->assertComplete($this); } public function testRemove() @@ -146,7 +143,7 @@ public function testRemove() $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( $this->getCmd('fossil changes'), ), true); @@ -161,8 +158,6 @@ public function testRemove() $downloader->prepare('uninstall', $packageMock, $this->workingDir); $downloader->remove($packageMock, $this->workingDir); $downloader->cleanup('uninstall', $packageMock, $this->workingDir); - - $process->assertComplete($this); } public function testGetInstallationSource() diff --git a/tests/Composer/Test/Downloader/GitDownloaderTest.php b/tests/Composer/Test/Downloader/GitDownloaderTest.php index e9629338cd9c..442978080894 100644 --- a/tests/Composer/Test/Downloader/GitDownloaderTest.php +++ b/tests/Composer/Test/Downloader/GitDownloaderTest.php @@ -39,6 +39,7 @@ protected function setUp(): void protected function tearDown(): void { + parent::tearDown(); if (is_dir($this->workingDir)) { $this->fs->removeDirectory($this->workingDir); } @@ -85,7 +86,7 @@ protected function setupConfig($config = null) protected function getDownloaderMock($io = null, $config = null, $executor = null, $filesystem = null) { $io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); - $executor = $executor ?: new ProcessExecutorMock; + $executor = $executor ?: $this->getProcessExecutorMock(); $filesystem = $filesystem ?: $this->getMockBuilder('Composer\Util\Filesystem')->getMock(); $config = $this->setupConfig($config); @@ -124,7 +125,7 @@ public function testDownload() ->method('getPrettyVersion') ->will($this->returnValue('dev-master')); - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $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 branch -r"), @@ -136,8 +137,6 @@ public function testDownload() $downloader->prepare('install', $packageMock, 'composerPath'); $downloader->install($packageMock, 'composerPath'); $downloader->cleanup('install', $packageMock, 'composerPath'); - - $process->assertComplete($this); } public function testDownloadWithCache() @@ -165,7 +164,7 @@ public function testDownloadWithCache() $filesystem = new \Composer\Util\Filesystem; $filesystem->removeDirectory($cachePath); - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( array('cmd' => $this->winCompat(sprintf("git clone --mirror -- 'https://example.com/composer/composer' '%s'", $cachePath)), 'callback' => function () use ($cachePath) { @mkdir($cachePath, 0777, true); @@ -183,8 +182,6 @@ public function testDownloadWithCache() $downloader->install($packageMock, 'composerPath'); $downloader->cleanup('install', $packageMock, 'composerPath'); @rmdir($cachePath); - - $process->assertComplete($this); } public function testDownloadUsesVariousProtocolsAndSetsPushUrlForGithub() @@ -203,7 +200,7 @@ public function testDownloadUsesVariousProtocolsAndSetsPushUrlForGithub() ->method('getPrettyVersion') ->will($this->returnValue('1.0.0')); - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(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'"), @@ -222,8 +219,6 @@ public function testDownloadUsesVariousProtocolsAndSetsPushUrlForGithub() $downloader->prepare('install', $packageMock, 'composerPath'); $downloader->install($packageMock, 'composerPath'); $downloader->cleanup('install', $packageMock, 'composerPath'); - - $process->assertComplete($this); } public function pushUrlProvider() @@ -260,7 +255,7 @@ public function testDownloadAndSetPushUrlUseCustomVariousProtocolsForGithub($pro ->method('getPrettyVersion') ->will($this->returnValue('1.0.0')); - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $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 remote set-url --push origin -- '{$pushUrl}'"), @@ -276,8 +271,6 @@ public function testDownloadAndSetPushUrlUseCustomVariousProtocolsForGithub($pro $downloader->prepare('install', $packageMock, 'composerPath'); $downloader->install($packageMock, 'composerPath'); $downloader->cleanup('install', $packageMock, 'composerPath'); - - $process->assertComplete($this); } public function testDownloadThrowsRuntimeExceptionIfGitCommandFails() @@ -296,7 +289,7 @@ public function testDownloadThrowsRuntimeExceptionIfGitCommandFails() ->method('getPrettyVersion') ->will($this->returnValue('1.0.0')); - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(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'"), @@ -312,8 +305,6 @@ public function testDownloadThrowsRuntimeExceptionIfGitCommandFails() $downloader->install($packageMock, 'composerPath'); $downloader->cleanup('install', $packageMock, 'composerPath'); - $process->assertComplete($this); - $this->fail('This test should throw'); } catch (\RuntimeException $e) { if ('RuntimeException' !== get_class($e)) { @@ -358,7 +349,7 @@ public function testUpdate() ->method('getPrettyVersion') ->will($this->returnValue('1.0.0')); - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( $this->winCompat('git show-ref --head -d'), $this->winCompat('git status --porcelain --untracked-files=no'), @@ -375,8 +366,6 @@ public function testUpdate() $downloader->prepare('update', $packageMock, $this->workingDir, $packageMock); $downloader->update($packageMock, $packageMock, $this->workingDir); $downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock); - - $process->assertComplete($this); } public function testUpdateWithNewRepoUrl() @@ -400,7 +389,7 @@ public function testUpdateWithNewRepoUrl() ->method('getPrettyVersion') ->will($this->returnValue('1.0.0')); - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( $this->winCompat("git show-ref --head -d"), $this->winCompat("git status --porcelain --untracked-files=no"), @@ -426,8 +415,6 @@ public function testUpdateWithNewRepoUrl() $downloader->prepare('update', $packageMock, $this->workingDir, $packageMock); $downloader->update($packageMock, $packageMock, $this->workingDir); $downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock); - - $process->assertComplete($this); } /** @@ -449,7 +436,7 @@ public function testUpdateThrowsRuntimeExceptionIfGitCommandFails() ->method('getVersion') ->will($this->returnValue('1.0.0.0')); - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( $this->winCompat('git show-ref --head -d'), $this->winCompat('git status --porcelain --untracked-files=no'), @@ -463,7 +450,6 @@ public function testUpdateThrowsRuntimeExceptionIfGitCommandFails() 'return' => 1, ), $this->winCompat('git --version'), - $this->winCompat('git branch -r'), ), true); $this->fs->ensureDirectoryExists($this->workingDir.'/.git'); @@ -476,8 +462,6 @@ public function testUpdateThrowsRuntimeExceptionIfGitCommandFails() $downloader->update($packageMock, $packageMock, $this->workingDir); $downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock); - $process->assertComplete($this); - $this->fail('This test should throw'); } catch (\RuntimeException $e) { if ('RuntimeException' !== get_class($e)) { @@ -506,7 +490,7 @@ public function testUpdateDoesntThrowsRuntimeExceptionIfGitCommandFailsAtFirstBu ->method('getPrettyVersion') ->will($this->returnValue('1.0.0')); - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( $this->winCompat('git show-ref --head -d'), $this->winCompat('git status --porcelain --untracked-files=no'), @@ -532,8 +516,6 @@ public function testUpdateDoesntThrowsRuntimeExceptionIfGitCommandFailsAtFirstBu $downloader->prepare('update', $packageMock, $this->workingDir, $packageMock); $downloader->update($packageMock, $packageMock, $this->workingDir); $downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock); - - $process->assertComplete($this); } public function testDowngradeShowsAppropriateMessage() @@ -569,12 +551,14 @@ public function testDowngradeShowsAppropriateMessage() ->method('getFullPrettyVersion') ->will($this->returnValue('1.0.0')); - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $ioMock = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); - $ioMock->expects($this->at(0)) + $ioMock->expects($this->atLeastOnce()) ->method('writeError') - ->with($this->stringContains('Downgrading')); + ->withConsecutive( + [$this->stringContains('Downgrading')] + ); $this->fs->ensureDirectoryExists($this->workingDir.'/.git'); $downloader = $this->getDownloaderMock($ioMock, null, $process); @@ -611,12 +595,14 @@ public function testNotUsingDowngradingWithReferences() ->method('getPrettyVersion') ->will($this->returnValue('dev-ref2')); - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $ioMock = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); - $ioMock->expects($this->at(0)) + $ioMock->expects($this->atLeastOnce()) ->method('writeError') - ->with($this->stringContains('Upgrading')); + ->withConsecutive( + [$this->stringContains('Upgrading')] + ); $this->fs->ensureDirectoryExists($this->workingDir.'/.git'); $downloader = $this->getDownloaderMock($ioMock, null, $process); @@ -631,7 +617,7 @@ public function testRemove() $expectedGitResetCommand = $this->winCompat("git status --porcelain --untracked-files=no"); $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( 'git show-ref --head -d', $expectedGitResetCommand, @@ -649,8 +635,6 @@ public function testRemove() $downloader->prepare('uninstall', $packageMock, $this->workingDir); $downloader->remove($packageMock, $this->workingDir); $downloader->cleanup('uninstall', $packageMock, $this->workingDir); - - $process->assertComplete($this); } public function testGetInstallationSource() diff --git a/tests/Composer/Test/Downloader/HgDownloaderTest.php b/tests/Composer/Test/Downloader/HgDownloaderTest.php index c36ec247b39f..decf69854747 100644 --- a/tests/Composer/Test/Downloader/HgDownloaderTest.php +++ b/tests/Composer/Test/Downloader/HgDownloaderTest.php @@ -29,6 +29,7 @@ protected function setUp(): void protected function tearDown(): void { + parent::tearDown(); if (is_dir($this->workingDir)) { $fs = new Filesystem; $fs->removeDirectory($this->workingDir); @@ -46,7 +47,7 @@ protected function getDownloaderMock($io = null, $config = null, $executor = nul { $io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $config = $config ?: $this->getMockBuilder('Composer\Config')->getMock(); - $executor = $executor ?: new ProcessExecutorMock; + $executor = $executor ?: $this->getProcessExecutorMock(); $filesystem = $filesystem ?: $this->getMockBuilder('Composer\Util\Filesystem')->getMock(); return new HgDownloader($io, $config, $executor, $filesystem); @@ -75,7 +76,7 @@ public function testDownload() ->method('getSourceUrls') ->will($this->returnValue(array('https://mercurial.dev/l3l0/composer'))); - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( $this->getCmd('hg clone -- \'https://mercurial.dev/l3l0/composer\' \'composerPath\''), $this->getCmd('hg up -- \'ref\''), @@ -83,8 +84,6 @@ public function testDownload() $downloader = $this->getDownloaderMock(null, null, $process); $downloader->install($packageMock, 'composerPath'); - - $process->assertComplete($this); } public function testUpdateforPackageWithoutSourceReference() @@ -118,7 +117,7 @@ public function testUpdate() ->method('getSourceUrls') ->will($this->returnValue(array('https://github.com/l3l0/composer'))); - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( $this->getCmd('hg st'), $this->getCmd("hg pull -- 'https://github.com/l3l0/composer' && hg up -- 'ref'"), @@ -128,8 +127,6 @@ public function testUpdate() $downloader->prepare('update', $packageMock, $this->workingDir, $packageMock); $downloader->update($packageMock, $packageMock, $this->workingDir); $downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock); - - $process->assertComplete($this); } public function testRemove() @@ -138,7 +135,7 @@ public function testRemove() $fs->ensureDirectoryExists($this->workingDir.'/.hg'); $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( $this->getCmd('hg st'), ), true); @@ -153,8 +150,6 @@ public function testRemove() $downloader->prepare('uninstall', $packageMock, $this->workingDir); $downloader->remove($packageMock, $this->workingDir); $downloader->cleanup('uninstall', $packageMock, $this->workingDir); - - $process->assertComplete($this); } public function testGetInstallationSource() diff --git a/tests/Composer/Test/Downloader/PerforceDownloaderTest.php b/tests/Composer/Test/Downloader/PerforceDownloaderTest.php index a5c8e2e3f396..6cdc762754e5 100644 --- a/tests/Composer/Test/Downloader/PerforceDownloaderTest.php +++ b/tests/Composer/Test/Downloader/PerforceDownloaderTest.php @@ -49,7 +49,7 @@ protected function setUp(): void $this->repoConfig = $this->getRepoConfig(); $this->config = $this->getConfig(); $this->io = $this->getMockIoInterface(); - $this->processExecutor = new ProcessExecutorMock; + $this->processExecutor = $this->getProcessExecutorMock(); $this->repository = $this->getMockRepository($this->repoConfig, $this->io, $this->config); $this->package = $this->getMockPackageInterface($this->repository); $this->downloader = new PerforceDownloader($this->io, $this->config, $this->processExecutor); @@ -140,13 +140,13 @@ public function testDoInstallWithTag() $this->io->expects($this->once())->method('writeError')->with($this->stringContains('Cloning '.$ref)); $perforceMethods = array('setStream', 'p4Login', 'writeP4ClientSpec', 'connectClient', 'syncCodeBase', 'cleanupClientSpec'); $perforce = $this->getMockBuilder('Composer\Util\Perforce')->disableOriginalConstructor()->getMock(); - $perforce->expects($this->at(0))->method('initializePath')->with($this->equalTo($this->testPath)); - $perforce->expects($this->at(1))->method('setStream')->with($this->equalTo($ref)); - $perforce->expects($this->at(2))->method('p4Login'); - $perforce->expects($this->at(3))->method('writeP4ClientSpec'); - $perforce->expects($this->at(4))->method('connectClient'); - $perforce->expects($this->at(5))->method('syncCodeBase')->with($label); - $perforce->expects($this->at(6))->method('cleanupClientSpec'); + $perforce->expects($this->once())->method('initializePath')->with($this->equalTo($this->testPath)); + $perforce->expects($this->once())->method('setStream')->with($this->equalTo($ref)); + $perforce->expects($this->once())->method('p4Login'); + $perforce->expects($this->once())->method('writeP4ClientSpec'); + $perforce->expects($this->once())->method('connectClient'); + $perforce->expects($this->once())->method('syncCodeBase')->with($label); + $perforce->expects($this->once())->method('cleanupClientSpec'); $this->downloader->setPerforce($perforce); $this->downloader->doInstall($this->package, $this->testPath, 'url'); } @@ -163,13 +163,13 @@ public function testDoInstallWithNoTag() $this->io->expects($this->once())->method('writeError')->with($this->stringContains('Cloning '.$ref)); $perforceMethods = array('setStream', 'p4Login', 'writeP4ClientSpec', 'connectClient', 'syncCodeBase', 'cleanupClientSpec'); $perforce = $this->getMockBuilder('Composer\Util\Perforce')->disableOriginalConstructor()->getMock(); - $perforce->expects($this->at(0))->method('initializePath')->with($this->equalTo($this->testPath)); - $perforce->expects($this->at(1))->method('setStream')->with($this->equalTo($ref)); - $perforce->expects($this->at(2))->method('p4Login'); - $perforce->expects($this->at(3))->method('writeP4ClientSpec'); - $perforce->expects($this->at(4))->method('connectClient'); - $perforce->expects($this->at(5))->method('syncCodeBase')->with($label); - $perforce->expects($this->at(6))->method('cleanupClientSpec'); + $perforce->expects($this->once())->method('initializePath')->with($this->equalTo($this->testPath)); + $perforce->expects($this->once())->method('setStream')->with($this->equalTo($ref)); + $perforce->expects($this->once())->method('p4Login'); + $perforce->expects($this->once())->method('writeP4ClientSpec'); + $perforce->expects($this->once())->method('connectClient'); + $perforce->expects($this->once())->method('syncCodeBase')->with($label); + $perforce->expects($this->once())->method('cleanupClientSpec'); $this->downloader->setPerforce($perforce); $this->downloader->doInstall($this->package, $this->testPath, 'url'); } diff --git a/tests/Composer/Test/Downloader/XzDownloaderTest.php b/tests/Composer/Test/Downloader/XzDownloaderTest.php index 7032004e17c3..ee9d48c10b2a 100644 --- a/tests/Composer/Test/Downloader/XzDownloaderTest.php +++ b/tests/Composer/Test/Downloader/XzDownloaderTest.php @@ -39,8 +39,9 @@ public function setUp(): void $this->testDir = $this->getUniqueTmpDirectory(); } - public function tearDown(): void + protected function tearDown(): void { + parent::tearDown(); $this->fs = new Filesystem; $this->fs->removeDirectory($this->testDir); } diff --git a/tests/Composer/Test/Downloader/ZipDownloaderTest.php b/tests/Composer/Test/Downloader/ZipDownloaderTest.php index eec37356ad51..bd5b06c8b7c3 100644 --- a/tests/Composer/Test/Downloader/ZipDownloaderTest.php +++ b/tests/Composer/Test/Downloader/ZipDownloaderTest.php @@ -42,8 +42,9 @@ public function setUp(): void $this->package = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); } - public function tearDown(): void + protected function tearDown(): void { + parent::tearDown(); $fs = new Filesystem; $fs->removeDirectory($this->testDir); $this->setPrivateProperty('hasZipArchive', null); diff --git a/tests/Composer/Test/EventDispatcher/EventDispatcherTest.php b/tests/Composer/Test/EventDispatcher/EventDispatcherTest.php index 9065c61ec4ec..fc3c3df0bd65 100644 --- a/tests/Composer/Test/EventDispatcher/EventDispatcherTest.php +++ b/tests/Composer/Test/EventDispatcher/EventDispatcherTest.php @@ -38,17 +38,16 @@ public function testListenerExceptionsAreCaught() 'Composer\Test\EventDispatcher\EventDispatcherTest::call', ), $io); - $io->expects($this->at(0)) + $io->expects($this->once()) ->method('isVerbose') ->willReturn(0); - $io->expects($this->at(1)) - ->method('writeError') - ->with('> Composer\Test\EventDispatcher\EventDispatcherTest::call'); - - $io->expects($this->at(2)) + $io->expects($this->atLeast(2)) ->method('writeError') - ->with('Script Composer\Test\EventDispatcher\EventDispatcherTest::call handling the post-install-cmd event terminated with an exception'); + ->withConsecutive( + ['> Composer\Test\EventDispatcher\EventDispatcherTest::call'], + ['Script Composer\Test\EventDispatcher\EventDispatcherTest::call handling the post-install-cmd event terminated with an exception'] + ); $dispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, false); } @@ -60,7 +59,7 @@ public function testListenerExceptionsAreCaught() */ public function testDispatcherCanExecuteSingleCommandLineScript($command) { - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( $command, ), true); @@ -80,8 +79,6 @@ public function testDispatcherCanExecuteSingleCommandLineScript($command) ->will($this->returnValue($listener)); $dispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, false); - - $process->assertComplete($this); } /** @@ -110,7 +107,7 @@ public function testDispatcherPassDevModeToAutoloadGeneratorForScriptEvents($dev $dispatcher = new EventDispatcher( $composer, $this->getMockBuilder('Composer\IO\IOInterface')->getMock(), - new ProcessExecutorMock + $this->getProcessExecutorMock() ); $event = $this->getMockBuilder('Composer\Script\Event') @@ -191,7 +188,7 @@ public function testDispatcherRemoveListener() $dispatcher = new EventDispatcher( $composer, $io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE), - new ProcessExecutorMock + $this->getProcessExecutorMock() ); $listener = array($this, 'someMethod'); @@ -226,7 +223,7 @@ public function testDispatcherRemoveListener() public function testDispatcherCanExecuteCliAndPhpInSameEventScriptStack() { - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( 'echo -n foo', 'echo -n bar', @@ -259,8 +256,6 @@ public function testDispatcherCanExecuteCliAndPhpInSameEventScriptStack() '> post-install-cmd: Composer\Test\EventDispatcher\EventDispatcherTest::someMethod'.PHP_EOL. '> post-install-cmd: echo -n bar'.PHP_EOL; $this->assertEquals($expected, $io->getOutput()); - - $process->assertComplete($this); } public function testDispatcherCanPutEnv() @@ -269,7 +264,7 @@ public function testDispatcherCanPutEnv() ->setConstructorArgs(array( $this->createComposerInstance(), $io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE), - new ProcessExecutorMock, + $this->getProcessExecutorMock(), )) ->setMethods(array( 'getListeners', @@ -302,7 +297,7 @@ public function testDispatcherAppendsDirBinOnPathForEveryListener() $dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->setConstructorArgs(array( $this->createComposerInstance(), $io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE), - new ProcessExecutorMock, + $this->getProcessExecutorMock(), ))->setMethods(array( 'getListeners', ))->getMock(); @@ -368,7 +363,7 @@ public static function getTestEnv() public function testDispatcherCanExecuteComposerScriptGroups() { - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( 'echo -n foo', 'echo -n baz', @@ -411,13 +406,11 @@ public function testDispatcherCanExecuteComposerScriptGroups() '> subgroup: echo -n baz'.PHP_EOL. '> group: echo -n bar'.PHP_EOL; $this->assertEquals($expected, $io->getOutput()); - - $process->assertComplete($this); } public function testRecursionInScriptsNames() { - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( 'echo Hello '.ProcessExecutor::escape('World'), ), true); @@ -452,8 +445,6 @@ public function testRecursionInScriptsNames() "> hello: echo Hello " .$this->getCmd("'World'").PHP_EOL; $this->assertEquals($expected, $io->getOutput()); - - $process->assertComplete($this); } public function testDispatcherDetectInfiniteRecursion() @@ -464,7 +455,7 @@ public function testDispatcherDetectInfiniteRecursion() ->setConstructorArgs(array( $composer = $this->createComposerInstance(), $io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(), - new ProcessExecutorMock, + $this->getProcessExecutorMock(), )) ->setMethods(array( 'getListeners', @@ -563,22 +554,21 @@ public function testDispatcherOutputsErrorOnFailedCommand() ->method('getListeners') ->will($this->returnValue($listener)); - $io->expects($this->at(0)) + $io->expects($this->once()) ->method('isVerbose') ->willReturn(0); - $io->expects($this->at(1)) + $io->expects($this->atLeast(2)) ->method('writeError') - ->willReturn('> exit 1'); + ->withConsecutive( + ['> exit 1'], + ['Script '.$code.' handling the post-install-cmd event returned with error code 1'] + ); - $io->expects($this->at(2)) + $io->expects($this->once()) ->method('isInteractive') ->willReturn(1); - $io->expects($this->at(3)) - ->method('writeError') - ->with($this->equalTo('Script '.$code.' handling the post-install-cmd event returned with error code 1')); - $this->setExpectedException('RuntimeException'); $dispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, false); } @@ -589,7 +579,7 @@ public function testDispatcherInstallerEvents() ->setConstructorArgs(array( $this->createComposerInstance(), $this->getMockBuilder('Composer\IO\IOInterface')->getMock(), - new ProcessExecutorMock, + $this->getProcessExecutorMock(), )) ->setMethods(array('getListeners')) ->getMock(); diff --git a/tests/Composer/Test/IO/ConsoleIOTest.php b/tests/Composer/Test/IO/ConsoleIOTest.php index 3d2d29fba3e1..dc2f6017bcbd 100644 --- a/tests/Composer/Test/IO/ConsoleIOTest.php +++ b/tests/Composer/Test/IO/ConsoleIOTest.php @@ -22,12 +22,12 @@ class ConsoleIOTest extends TestCase public function testIsInteractive() { $inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock(); - $inputMock->expects($this->at(0)) + $inputMock->expects($this->exactly(2)) ->method('isInteractive') - ->will($this->returnValue(true)); - $inputMock->expects($this->at(1)) - ->method('isInteractive') - ->will($this->returnValue(false)); + ->willReturnOnConsecutiveCalls( + true, + false + ); $outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock(); $helperMock = $this->getMockBuilder('Symfony\Component\Console\Helper\HelperSet')->getMock(); @@ -109,27 +109,17 @@ public function testOverwrite() $outputMock->expects($this->any()) ->method('getVerbosity') ->willReturn(OutputInterface::VERBOSITY_NORMAL); - $outputMock->expects($this->at(1)) - ->method('write') - ->with($this->equalTo('something (strlen = 23)')); - $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 (12)'), $this->equalTo(false)); - $outputMock->expects($this->at(7)) + $outputMock->expects($this->atLeast(7)) ->method('write') - ->with($this->equalTo(str_repeat(' ', 11)), $this->equalTo(false)); - $outputMock->expects($this->at(9)) - ->method('write') - ->with($this->equalTo(str_repeat("\x08", 11)), $this->equalTo(false)); - $outputMock->expects($this->at(11)) - ->method('write') - ->with($this->equalTo(str_repeat("\x08", 12)), $this->equalTo(false)); - $outputMock->expects($this->at(13)) - ->method('write') - ->with($this->equalTo('something longer than initial (34)')); + ->withConsecutive( + [$this->equalTo('something (strlen = 23)')], + [$this->equalTo(str_repeat("\x08", 23)), $this->equalTo(false)], + [$this->equalTo('shorter (12)'), $this->equalTo(false)], + [$this->equalTo(str_repeat(' ', 11)), $this->equalTo(false)], + [$this->equalTo(str_repeat("\x08", 11)), $this->equalTo(false)], + [$this->equalTo(str_repeat("\x08", 12)), $this->equalTo(false)], + [$this->equalTo('something longer than initial (34)')], + ); $helperMock = $this->getMockBuilder('Symfony\Component\Console\Helper\HelperSet')->getMock(); diff --git a/tests/Composer/Test/Installer/BinaryInstallerTest.php b/tests/Composer/Test/Installer/BinaryInstallerTest.php index 2a15903ef4bc..da7a8c4779f0 100644 --- a/tests/Composer/Test/Installer/BinaryInstallerTest.php +++ b/tests/Composer/Test/Installer/BinaryInstallerTest.php @@ -62,6 +62,7 @@ protected function setUp(): void protected function tearDown(): void { + parent::tearDown(); $this->fs->removeDirectory($this->rootDir); } diff --git a/tests/Composer/Test/Installer/LibraryInstallerTest.php b/tests/Composer/Test/Installer/LibraryInstallerTest.php index 1e7f0ee17250..6d0e1f5a9788 100644 --- a/tests/Composer/Test/Installer/LibraryInstallerTest.php +++ b/tests/Composer/Test/Installer/LibraryInstallerTest.php @@ -98,6 +98,7 @@ protected function setUp(): void protected function tearDown(): void { + parent::tearDown(); $this->fs->removeDirectory($this->rootDir); } diff --git a/tests/Composer/Test/Installer/SuggestedPackagesReporterTest.php b/tests/Composer/Test/Installer/SuggestedPackagesReporterTest.php index beb4685eb66f..8416c1e7592a 100644 --- a/tests/Composer/Test/Installer/SuggestedPackagesReporterTest.php +++ b/tests/Composer/Test/Installer/SuggestedPackagesReporterTest.php @@ -141,13 +141,13 @@ public function testOutput() { $this->suggestedPackagesReporter->addPackage('a', 'b', 'c'); - $this->io->expects($this->at(0)) + $this->io->expects($this->exactly(3)) ->method('write') - ->with('a suggests:'); - - $this->io->expects($this->at(1)) - ->method('write') - ->with(' - b: c'); + ->withConsecutive( + ['a suggests:'], + [' - b: c'], + [''] + ); $this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE); } @@ -159,13 +159,13 @@ public function testOutputWithNoSuggestionReason() { $this->suggestedPackagesReporter->addPackage('a', 'b', ''); - $this->io->expects($this->at(0)) + $this->io->expects($this->exactly(3)) ->method('write') - ->with('a suggests:'); - - $this->io->expects($this->at(1)) - ->method('write') - ->with(' - b'); + ->withConsecutive( + ['a suggests:'], + [' - b'], + [''] + ); $this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE); } @@ -178,17 +178,14 @@ public function testOutputIgnoresFormatting() $this->suggestedPackagesReporter->addPackage('source', 'target1', "\x1b[1;37;42m Like us\r\non Facebook \x1b[0m"); $this->suggestedPackagesReporter->addPackage('source', 'target2', "Like us on Facebook"); - $this->io->expects($this->at(0)) + $this->io->expects($this->exactly(4)) ->method('write') - ->with('source suggests:'); - - $this->io->expects($this->at(1)) - ->method('write') - ->with(' - target1: [1;37;42m Like us on Facebook [0m'); - - $this->io->expects($this->at(2)) - ->method('write') - ->with(' - target2: \\Like us on Facebook\\'); + ->withConsecutive( + ['source suggests:'], + [' - target1: [1;37;42m Like us on Facebook [0m'], + [' - target2: \\Like us on Facebook\\'], + [''] + ); $this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE); } @@ -201,25 +198,16 @@ public function testOutputMultiplePackages() $this->suggestedPackagesReporter->addPackage('a', 'b', 'c'); $this->suggestedPackagesReporter->addPackage('source package', 'target', 'because reasons'); - $this->io->expects($this->at(0)) - ->method('write') - ->with('a suggests:'); - - $this->io->expects($this->at(1)) - ->method('write') - ->with(' - b: c'); - - $this->io->expects($this->at(2)) - ->method('write') - ->with(''); - - $this->io->expects($this->at(3)) + $this->io->expects($this->exactly(6)) ->method('write') - ->with('source package suggests:'); - - $this->io->expects($this->at(4)) - ->method('write') - ->with(' - target: because reasons'); + ->withConsecutive( + ['a suggests:'], + [' - b: c'], + [''], + ['source package suggests:'], + [' - target: because reasons'], + [''] + ); $this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE); } @@ -251,13 +239,13 @@ public function testOutputSkipInstalledPackages() $this->suggestedPackagesReporter->addPackage('a', 'b', 'c'); $this->suggestedPackagesReporter->addPackage('source package', 'target', 'because reasons'); - $this->io->expects($this->at(0)) - ->method('write') - ->with('source package suggests:'); - - $this->io->expects($this->at(1)) + $this->io->expects($this->exactly(3)) ->method('write') - ->with(' - target: because reasons'); + ->withConsecutive( + ['source package suggests:'], + [' - target: because reasons'], + [''] + ); $this->suggestedPackagesReporter->output(SuggestedPackagesReporter::MODE_BY_PACKAGE, $repository); } diff --git a/tests/Composer/Test/InstallerTest.php b/tests/Composer/Test/InstallerTest.php index 8d15e0e5a10c..667aa9f96234 100644 --- a/tests/Composer/Test/InstallerTest.php +++ b/tests/Composer/Test/InstallerTest.php @@ -56,8 +56,9 @@ public function setUp(): void chdir(__DIR__); } - public function tearDown(): void + protected function tearDown(): void { + parent::tearDown(); Platform::clearEnv('COMPOSER_POOL_OPTIMIZER'); chdir($this->prevCwd); diff --git a/tests/Composer/Test/Mock/HttpDownloaderMock.php b/tests/Composer/Test/Mock/HttpDownloaderMock.php index b58a9628a02b..99ba2892e74c 100644 --- a/tests/Composer/Test/Mock/HttpDownloaderMock.php +++ b/tests/Composer/Test/Mock/HttpDownloaderMock.php @@ -12,31 +12,120 @@ namespace Composer\Test\Mock; +use Composer\Config; +use Composer\IO\BufferIO; +use Composer\IO\IOInterface; use Composer\Util\HttpDownloader; use Composer\Util\Http\Response; use Composer\Downloader\TransportException; +use PHPUnit\Framework\Assert; +use PHPUnit\Framework\AssertionFailedError; class HttpDownloaderMock extends HttpDownloader { /** - * @var array + * @var array|null, status: int, body: string, headers: list}>|null */ - protected $contentMap; + private $expectations = null; + /** + * @var bool + */ + private $strict = false; + /** + * @var array{status: int, body: string, headers: array} + */ + 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 $contentMap associative array of locations and content + * @param array, status?: int, body?: string, headers?: array}> $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} $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])) { - return new Response(array('url' => $fileUrl), 200, array(), $this->contentMap[$fileUrl]); + // this was not configured to expect anything, so no need to react here + 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; } } diff --git a/tests/Composer/Test/Mock/ProcessExecutorMock.php b/tests/Composer/Test/Mock/ProcessExecutorMock.php index 247f815a81a3..da54b3c3dff2 100644 --- a/tests/Composer/Test/Mock/ProcessExecutorMock.php +++ b/tests/Composer/Test/Mock/ProcessExecutorMock.php @@ -14,6 +14,7 @@ use Composer\Util\ProcessExecutor; use Composer\Util\Platform; +use PHPUnit\Framework\Assert; use PHPUnit\Framework\TestCase; use PHPUnit\Framework\AssertionFailedError; use Symfony\Component\Process\Process; @@ -25,9 +26,9 @@ class ProcessExecutorMock extends ProcessExecutor { /** - * @var array + * @var array|null */ - private $expectations = array(); + private $expectations = null; /** * @var bool */ @@ -64,10 +65,14 @@ public function expects(array $expectations, $strict = false, array $defaultHand $this->defaultHandler = array_merge($this->defaultHandler, $defaultHandler); } - /** @return void */ - public function assertComplete(TestCase $testCase) + public function assertComplete(): void { - 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) { return $expect['cmd']; }, $this->expectations); @@ -78,7 +83,8 @@ public function assertComplete(TestCase $testCase) ); } - $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) @@ -115,7 +121,7 @@ private function doExecute($command, $cwd, $tty, &$output = null) $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); $stdout = $expect['stdout']; $stderr = $expect['stderr']; @@ -130,7 +136,7 @@ private function doExecute($command, $cwd, $tty, &$output = null) } else { throw new AssertionFailedError( '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)) ); } diff --git a/tests/Composer/Test/Package/Archiver/ArchivableFilesFinderTest.php b/tests/Composer/Test/Package/Archiver/ArchivableFilesFinderTest.php index 2cd274e11f4d..ca77abb31d2f 100644 --- a/tests/Composer/Test/Package/Archiver/ArchivableFilesFinderTest.php +++ b/tests/Composer/Test/Package/Archiver/ArchivableFilesFinderTest.php @@ -97,6 +97,7 @@ protected function setUp(): void protected function tearDown(): void { + parent::tearDown(); $fs = new Filesystem; $fs->removeDirectory($this->sources); } diff --git a/tests/Composer/Test/Package/Archiver/ArchiverTest.php b/tests/Composer/Test/Package/Archiver/ArchiverTest.php index fa09813c6102..9601fa1c6144 100644 --- a/tests/Composer/Test/Package/Archiver/ArchiverTest.php +++ b/tests/Composer/Test/Package/Archiver/ArchiverTest.php @@ -41,8 +41,9 @@ public function setUp(): void $this->testDir = $this->getUniqueTmpDirectory(); } - public function tearDown(): void + protected function tearDown(): void { + parent::tearDown(); $this->filesystem->removeDirectory($this->testDir); } diff --git a/tests/Composer/Test/Package/Loader/RootPackageLoaderTest.php b/tests/Composer/Test/Package/Loader/RootPackageLoaderTest.php index d523debc056b..d99fcd110327 100644 --- a/tests/Composer/Test/Package/Loader/RootPackageLoaderTest.php +++ b/tests/Composer/Test/Package/Loader/RootPackageLoaderTest.php @@ -81,7 +81,7 @@ public function testNoVersionIsVisibleInPrettyVersion() $config = new Config; $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)); $package = $loader->load(array()); @@ -121,7 +121,7 @@ public function testFeatureBranchPrettyVersion() ->getMock() ; - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( array( 'cmd' => 'git branch -a --no-color --no-abbrev -v', @@ -136,8 +136,6 @@ public function testFeatureBranchPrettyVersion() $package = $loader->load(array('require' => array('foo/bar' => 'self.version'))); $this->assertEquals("dev-master", $package->getPrettyVersion()); - - $process->assertComplete($this); } public function testNonFeatureBranchPrettyVersion() @@ -151,7 +149,7 @@ public function testNonFeatureBranchPrettyVersion() ->getMock() ; - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( array( 'cmd' => 'git branch -a --no-color --no-abbrev -v', @@ -165,7 +163,5 @@ public function testNonFeatureBranchPrettyVersion() $package = $loader->load(array('require' => array('foo/bar' => 'self.version'), "non-feature-branches" => array("latest-.*"))); $this->assertEquals("dev-latest-production", $package->getPrettyVersion()); - - $process->assertComplete($this); } } diff --git a/tests/Composer/Test/Package/Version/VersionGuesserTest.php b/tests/Composer/Test/Package/Version/VersionGuesserTest.php index 64e20fbd0163..6bb2df0f95cd 100644 --- a/tests/Composer/Test/Package/Version/VersionGuesserTest.php +++ b/tests/Composer/Test/Package/Version/VersionGuesserTest.php @@ -33,7 +33,7 @@ public function testHgGuessVersionReturnsData() { $branch = 'default'; - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( array('cmd' => 'git branch -a --no-color --no-abbrev -v', 'return' => 128), array('cmd' => 'git describe --exact-match --tags', 'return' => 128), @@ -53,8 +53,6 @@ public function testHgGuessVersionReturnsData() $this->assertEquals("dev-".$branch, $versionArray['version']); $this->assertEquals("dev-".$branch, $versionArray['pretty_version']); $this->assertEmpty($versionArray['commit']); - - $process->assertComplete($this); } public function testGuessVersionReturnsData() @@ -62,7 +60,7 @@ public function testGuessVersionReturnsData() $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; $anotherCommitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( array( 'cmd' => 'git branch -a --no-color --no-abbrev -v', @@ -80,8 +78,6 @@ public function testGuessVersionReturnsData() $this->assertArrayNotHasKey('feature_version', $versionArray); $this->assertArrayNotHasKey('feature_pretty_version', $versionArray); $this->assertEquals($commitHash, $versionArray['commit']); - - $process->assertComplete($this); } public function testGuessVersionDoesNotSeeCustomDefaultBranchAsNonFeatureBranch() @@ -89,7 +85,7 @@ public function testGuessVersionDoesNotSeeCustomDefaultBranchAsNonFeatureBranch( $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; $anotherCommitHash = '13a15d220da53c52eddd5f32ffca64a7b3801bea'; - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( array( 'cmd' => 'git branch -a --no-color --no-abbrev -v', @@ -105,8 +101,6 @@ public function testGuessVersionDoesNotSeeCustomDefaultBranchAsNonFeatureBranch( $this->assertEquals("dev-current", $versionArray['version']); $this->assertEquals($anotherCommitHash, $versionArray['commit']); - - $process->assertComplete($this); } public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationForArbitraryNaming() @@ -114,7 +108,7 @@ public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationF $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; $anotherCommitHash = '13a15d220da53c52eddd5f32ffca64a7b3801bea'; - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( array( 'cmd' => 'git branch -a --no-color --no-abbrev -v', @@ -135,8 +129,6 @@ public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationF $this->assertEquals($anotherCommitHash, $versionArray['commit']); $this->assertEquals("dev-feature", $versionArray['feature_version']); $this->assertEquals("dev-feature", $versionArray['feature_pretty_version']); - - $process->assertComplete($this); } public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationForArbitraryNamingRegex() @@ -144,7 +136,7 @@ public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationF $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; $anotherCommitHash = '13a15d220da53c52eddd5f32ffca64a7b3801bea'; - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( array( 'cmd' => 'git branch -a --no-color --no-abbrev -v', @@ -165,8 +157,6 @@ public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationF $this->assertEquals($anotherCommitHash, $versionArray['commit']); $this->assertEquals("dev-feature", $versionArray['feature_version']); $this->assertEquals("dev-feature", $versionArray['feature_pretty_version']); - - $process->assertComplete($this); } public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationForArbitraryNamingWhenOnNonFeatureBranch() @@ -174,7 +164,7 @@ public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationF $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; $anotherCommitHash = '13a15d220da53c52eddd5f32ffca64a7b3801bea'; - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( array( 'cmd' => 'git branch -a --no-color --no-abbrev -v', @@ -191,15 +181,13 @@ public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationF $this->assertEquals($commitHash, $versionArray['commit']); $this->assertArrayNotHasKey('feature_version', $versionArray); $this->assertArrayNotHasKey('feature_pretty_version', $versionArray); - - $process->assertComplete($this); } public function testDetachedHeadBecomesDevHash() { $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( array( 'cmd' => 'git branch -a --no-color --no-abbrev -v', @@ -214,15 +202,13 @@ public function testDetachedHeadBecomesDevHash() $versionData = $guesser->guessVersion(array(), 'dummy/path'); $this->assertEquals("dev-$commitHash", $versionData['version']); - - $process->assertComplete($this); } public function testDetachedFetchHeadBecomesDevHashGit2() { $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( array( 'cmd' => 'git branch -a --no-color --no-abbrev -v', @@ -237,15 +223,13 @@ public function testDetachedFetchHeadBecomesDevHashGit2() $versionData = $guesser->guessVersion(array(), 'dummy/path'); $this->assertEquals("dev-$commitHash", $versionData['version']); - - $process->assertComplete($this); } public function testDetachedCommitHeadBecomesDevHashGit2() { $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( array( 'cmd' => 'git branch -a --no-color --no-abbrev -v', @@ -260,13 +244,11 @@ public function testDetachedCommitHeadBecomesDevHashGit2() $versionData = $guesser->guessVersion(array(), 'dummy/path'); $this->assertEquals("dev-$commitHash", $versionData['version']); - - $process->assertComplete($this); } public function testTagBecomesVersion() { - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( array( 'cmd' => 'git branch -a --no-color --no-abbrev -v', @@ -284,13 +266,11 @@ public function testTagBecomesVersion() $versionData = $guesser->guessVersion(array(), 'dummy/path'); $this->assertEquals("2.0.5.0-alpha2", $versionData['version']); - - $process->assertComplete($this); } public function testTagBecomesPrettyVersion() { - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( array( 'cmd' => 'git branch -a --no-color --no-abbrev -v', @@ -309,13 +289,11 @@ public function testTagBecomesPrettyVersion() $this->assertEquals('1.0.0.0', $versionData['version']); $this->assertEquals('1.0.0', $versionData['pretty_version']); - - $process->assertComplete($this); } public function testInvalidTagBecomesVersion() { - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( array( 'cmd' => 'git branch -a --no-color --no-abbrev -v', @@ -329,13 +307,11 @@ public function testInvalidTagBecomesVersion() $versionData = $guesser->guessVersion(array(), 'dummy/path'); $this->assertEquals("dev-foo", $versionData['version']); - - $process->assertComplete($this); } public function testNumericBranchesShowNicely() { - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( array( 'cmd' => 'git branch -a --no-color --no-abbrev -v', @@ -350,13 +326,11 @@ public function testNumericBranchesShowNicely() $this->assertEquals("1.5.x-dev", $versionData['pretty_version']); $this->assertEquals("1.5.9999999.9999999-dev", $versionData['version']); - - $process->assertComplete($this); } public function testRemoteBranchesAreSelected() { - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( array( 'cmd' => 'git branch -a --no-color --no-abbrev -v', @@ -375,7 +349,5 @@ public function testRemoteBranchesAreSelected() $versionData = $guesser->guessVersion(array('version' => 'self.version'), 'dummy/path'); $this->assertEquals("1.5.x-dev", $versionData['pretty_version']); $this->assertEquals("1.5.9999999.9999999-dev", $versionData['version']); - - $process->assertComplete($this); } } diff --git a/tests/Composer/Test/Package/Version/VersionSelectorTest.php b/tests/Composer/Test/Package/Version/VersionSelectorTest.php index 153c522f6b96..027534c6ec76 100644 --- a/tests/Composer/Test/Package/Version/VersionSelectorTest.php +++ b/tests/Composer/Test/Package/Version/VersionSelectorTest.php @@ -181,15 +181,13 @@ public function testMostStableVersionIsReturnedRegardlessOfOrder() $packages = array($package1, $package2); $repositorySet = $this->createMockRepositorySet(); - $repositorySet->expects($this->at(0)) + $repositorySet->expects($this->exactly(2)) ->method('findPackages') ->with($packageName, null) - ->will($this->returnValue($packages)); - - $repositorySet->expects($this->at(1)) - ->method('findPackages') - ->with($packageName, null) - ->will($this->returnValue(array_reverse($packages))); + ->willReturnOnConsecutiveCalls( + $packages, + array_reverse($packages) + ); $versionSelector = new VersionSelector($repositorySet); $best = $versionSelector->findBestCandidate($packageName); diff --git a/tests/Composer/Test/Plugin/PluginInstallerTest.php b/tests/Composer/Test/Plugin/PluginInstallerTest.php index 088d5eb033bf..66d83d98792c 100644 --- a/tests/Composer/Test/Plugin/PluginInstallerTest.php +++ b/tests/Composer/Test/Plugin/PluginInstallerTest.php @@ -129,6 +129,7 @@ protected function setUp(): void protected function tearDown(): void { + parent::tearDown(); $filesystem = new Filesystem(); $filesystem->removeDirectory($this->directory); } diff --git a/tests/Composer/Test/PolyfillTestCase.php b/tests/Composer/Test/PolyfillTestCase.php deleted file mode 100644 index da8aa3e991f3..000000000000 --- a/tests/Composer/Test/PolyfillTestCase.php +++ /dev/null @@ -1,137 +0,0 @@ - - * Jordi Boggiano - * - * 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); - } - } - } -} diff --git a/tests/Composer/Test/Repository/ComposerRepositoryTest.php b/tests/Composer/Test/Repository/ComposerRepositoryTest.php index d2f1ca8ed313..49a1af38770b 100644 --- a/tests/Composer/Test/Repository/ComposerRepositoryTest.php +++ b/tests/Composer/Test/Repository/ComposerRepositoryTest.php @@ -58,7 +58,7 @@ public function testLoadData(array $expected, array $repoPackages) } $repository - ->expects($this->at(2)) + ->expects($this->once()) ->method('createPackages') ->with($this->identicalTo($expected), $this->equalTo('root file (http://example.org/packages.json)')) ->will($this->returnValue($stubs)); @@ -181,16 +181,22 @@ public function testSearchWithType() ), ); - $httpDownloader = new HttpDownloaderMock(array( - 'http://example.org/packages.json' => JsonFile::encode(array('search' => '/search.json?q=%query%&type=%type%')), - '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()), - )); + $httpDownloader = $this->getHttpDownloaderMock(); + $httpDownloader->expects( + [ + ['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') ->disableOriginalConstructor() ->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( array(array('name' => 'foo', 'description' => null)), @@ -205,7 +211,7 @@ public function testSearchWithType() public function testSearchWithAbandonedPackages() { $repoConfig = array( - 'url' => 'http://2.example.org', + 'url' => 'http://example.org', ); $result = array( @@ -223,15 +229,22 @@ public function testSearchWithAbandonedPackages() ), ); - $httpDownloader = new HttpDownloaderMock(array( - 'http://2.example.org/packages.json' => JsonFile::encode(array('search' => '/search.json?q=%query%')), - 'http://2.example.org/search.json?q=foo' => JsonFile::encode($result), - )); + $httpDownloader = $this->getHttpDownloaderMock(); + $httpDownloader->expects( + [ + ['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') ->disableOriginalConstructor() ->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( array( @@ -313,15 +326,22 @@ public function provideCanonicalizeUrlTestCases() public function testGetProviderNamesWillReturnPartialPackageNames() { - $httpDownloader = new HttpDownloaderMock(array( - 'http://example.org/packages.json' => 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'), - )), - )), - )); + $httpDownloader = $this->getHttpDownloaderMock(); + $httpDownloader->expects( + [ + [ + 'url' => 'http://example.org/packages.json', + '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( array('url' => 'http://example.org/packages.json'), diff --git a/tests/Composer/Test/Repository/RepositoryManagerTest.php b/tests/Composer/Test/Repository/RepositoryManagerTest.php index 6a7df6be8a18..59f23dff1006 100644 --- a/tests/Composer/Test/Repository/RepositoryManagerTest.php +++ b/tests/Composer/Test/Repository/RepositoryManagerTest.php @@ -26,8 +26,9 @@ public function setUp(): void $this->tmpdir = $this->getUniqueTmpDirectory(); } - public function tearDown(): void + protected function tearDown(): void { + parent::tearDown(); if (is_dir($this->tmpdir)) { $fs = new Filesystem(); $fs->removeDirectory($this->tmpdir); diff --git a/tests/Composer/Test/Repository/Vcs/FossilDriverTest.php b/tests/Composer/Test/Repository/Vcs/FossilDriverTest.php index 462047a7b91c..06c6bd5b6145 100644 --- a/tests/Composer/Test/Repository/Vcs/FossilDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/FossilDriverTest.php @@ -39,8 +39,9 @@ public function setUp(): void )); } - public function tearDown(): void + protected function tearDown(): void { + parent::tearDown(); $fs = new Filesystem(); $fs->removeDirectory($this->home); } diff --git a/tests/Composer/Test/Repository/Vcs/GitBitbucketDriverTest.php b/tests/Composer/Test/Repository/Vcs/GitBitbucketDriverTest.php index 1e11161077af..50e89f52bb14 100644 --- a/tests/Composer/Test/Repository/Vcs/GitBitbucketDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/GitBitbucketDriverTest.php @@ -51,8 +51,9 @@ protected function setUp(): void ->getMock(); } - public function tearDown(): void + protected function tearDown(): void { + parent::tearDown(); $fs = new Filesystem; $fs->removeDirectory($this->home); } diff --git a/tests/Composer/Test/Repository/Vcs/GitHubDriverTest.php b/tests/Composer/Test/Repository/Vcs/GitHubDriverTest.php index 6e3728a7a882..efafa06261ef 100644 --- a/tests/Composer/Test/Repository/Vcs/GitHubDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/GitHubDriverTest.php @@ -39,8 +39,9 @@ public function setUp(): void )); } - public function tearDown(): void + protected function tearDown(): void { + parent::tearDown(); $fs = new Filesystem; $fs->removeDirectory($this->home); } @@ -58,18 +59,19 @@ public function testPrivateRepository() ->method('isInteractive') ->will($this->returnValue(true)); - $httpDownloader = $this->getMockBuilder('Composer\Util\HttpDownloader') - ->setConstructorArgs(array($io, $this->config)) - ->getMock(); + $httpDownloader = $this->getHttpDownloaderMock($io, $this->config); + $httpDownloader->expects( + [ + ['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)); - $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()) ->method('askAndHideAnswer') ->with($this->equalTo('Token (hidden): ')) @@ -79,16 +81,6 @@ public function testPrivateRepository() ->method('setAuthentication') ->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(); $authConfigSource = $this->getMockBuilder('Composer\Config\ConfigSourceInterface')->getMock(); $this->config->setConfigSource($configSource); @@ -127,21 +119,21 @@ public function testPublicRepository() ->method('isInteractive') ->will($this->returnValue(true)); - $httpDownloader = $this->getMockBuilder('Composer\Util\HttpDownloader') - ->setConstructorArgs(array($io, $this->config)) - ->getMock(); - $httpDownloader->expects($this->at(0)) - ->method('get') - ->with($this->equalTo($repoApiUrl)) - ->will($this->returnValue(new Response(array('url' => $repoApiUrl), 200, array(), '{"master_branch": "test_master", "owner": {"login": "composer"}, "name": "packagist"}'))); + $httpDownloader = $this->getHttpDownloaderMock($io, $this->config); + $httpDownloader->expects( + [ + ['url' => $repoApiUrl, 'body' => '{"master_branch": "test_master", "owner": {"login": "composer"}, "name": "packagist"}'], + ], + true + ); $repoConfig = array( 'url' => $repoUrl, ); $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(); $this->setAttribute($gitHubDriver, 'tags', array($identifier => $sha)); @@ -170,36 +162,24 @@ public function testPublicRepository2() ->method('isInteractive') ->will($this->returnValue(true)); - $httpDownloader = $this->getMockBuilder('Composer\Util\HttpDownloader') - ->setConstructorArgs(array($io, $this->config)) - ->getMock(); - $httpDownloader->expects($this->at(0)) - ->method('get') - ->with($this->equalTo($url = $repoApiUrl)) - ->will($this->returnValue(new Response(array('url' => $url), 200, array(), '{"master_branch": "test_master", "owner": {"login": "composer"}, "name": "packagist"}'))); - - $httpDownloader->expects($this->at(1)) - ->method('get') - ->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.'" }}').'"}'))); - - $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").'"}'))); + $httpDownloader = $this->getHttpDownloaderMock($io, $this->config); + $httpDownloader->expects( + [ + ['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.'" }}').'"}'], + ['url' => 'https://api.github.com/repos/composer/packagist/commits/feature%2F3.2-foo', 'body' => '{"commit": {"committer":{ "date": "2012-09-10"}}}'], + ['url' => 'https://api.github.com/repos/composer/packagist/contents/.github/FUNDING.yml', 'body' => '{"encoding": "base64", "content": "'.base64_encode("custom: https://example.com").'"}'], + ], + true + ); $repoConfig = array( 'url' => $repoUrl, ); $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(); $this->setAttribute($gitHubDriver, 'tags', array($identifier => $sha)); @@ -233,35 +213,22 @@ public function testPublicRepositoryArchived() ->method('isInteractive') ->will($this->returnValue(true)); - $httpDownloader = $this->getMockBuilder('Composer\Util\HttpDownloader') - ->setConstructorArgs(array($io, $this->config)) - ->getMock(); - - $httpDownloader->expects($this->at(0)) - ->method('get') - ->with($this->equalTo($repoApiUrl)) - ->will($this->returnValue(new Response(array('url' => $repoApiUrl), 200, array(), '{"master_branch": "test_master", "owner": {"login": "composer"}, "name": "packagist", "archived": 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").'"}'))); + $httpDownloader = $this->getHttpDownloaderMock($io, $this->config); + $httpDownloader->expects( + [ + ['url' => $repoApiUrl, 'body' => '{"master_branch": "test_master", "owner": {"login": "composer"}, "name": "packagist", "archived": true}'], + ['url' => $composerJsonUrl, 'body' => '{"encoding": "base64", "content": "' . base64_encode('{"name": "composer/packagist"}') . '"}'], + ['url' => 'https://api.github.com/repos/composer/packagist/commits/'.$sha, 'body' => '{"commit": {"committer":{ "date": "2012-09-10"}}}'], + ['url' => 'https://api.github.com/repos/composer/packagist/contents/.github/FUNDING.yml', 'body' => '{"encoding": "base64", "content": "'.base64_encode("custom: https://example.com").'"}'], + ], + true + ); $repoConfig = array( 'url' => $repoUrl, ); - $gitHubDriver = new GitHubDriver($repoConfig, $io, $this->config, $httpDownloader, new ProcessExecutorMock); + $gitHubDriver = new GitHubDriver($repoConfig, $io, $this->config, $httpDownloader, $this->getProcessExecutorMock()); $gitHubDriver->initialize(); $this->setAttribute($gitHubDriver, 'tags', array($identifier => $sha)); @@ -283,20 +250,19 @@ public function testPrivateRepositoryNoInteraction() ->method('isInteractive') ->will($this->returnValue(false)); - $httpDownloader = $this->getMockBuilder('Composer\Util\HttpDownloader') - ->setConstructorArgs(array($io, $this->config)) - ->getMock(); - - $httpDownloader->expects($this->at(0)) - ->method('get') - ->with($this->equalTo($repoApiUrl)) - ->will($this->throwException(new TransportException('HTTP/1.1 404 Not Found', 404))); + $httpDownloader = $this->getHttpDownloaderMock($io, $this->config); + $httpDownloader->expects( + [ + ['url' => $repoApiUrl, 'status' => 404], + ], + true + ); // clean local clone if present $fs = new Filesystem(); $fs->removeDirectory(sys_get_temp_dir() . '/composer-test'); - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( 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/'), @@ -337,8 +303,6 @@ public function testPrivateRepositoryNoInteraction() $this->assertEquals('git', $source['type']); $this->assertEquals($repoSshUrl, $source['url']); $this->assertEquals($sha, $source['reference']); - - $process->assertComplete($this); } /** diff --git a/tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php b/tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php index a4c0f3ca34c1..919efeb737d9 100644 --- a/tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php @@ -12,10 +12,14 @@ namespace Composer\Test\Repository\Vcs; +use Composer\IO\IOInterface; use Composer\Repository\Vcs\GitLabDriver; use Composer\Config; +use Composer\Test\Mock\HttpDownloaderMock; use Composer\Test\TestCase; use Composer\Util\Filesystem; +use Composer\Util\ProcessExecutor; +use PHPUnit\Framework\MockObject\MockObject; use Prophecy\Argument; use Composer\Util\Http\Response; @@ -33,15 +37,15 @@ class GitLabDriverTest extends TestCase */ private $config; /** - * @var \Prophecy\Prophecy\ObjectProphecy + * @var MockObject&IOInterface */ private $io; /** - * @var \Prophecy\Prophecy\ObjectProphecy + * @var MockObject&ProcessExecutor */ private $process; /** - * @var \Prophecy\Prophecy\ObjectProphecy + * @var HttpDownloaderMock */ private $httpDownloader; @@ -61,13 +65,14 @@ public function setUp(): void ), )); - $this->io = $this->prophesize('Composer\IO\IOInterface'); - $this->process = $this->prophesize('Composer\Util\ProcessExecutor'); - $this->httpDownloader = $this->prophesize('Composer\Util\HttpDownloader'); + $this->io = $this->getMockBuilder('Composer\IO\IOInterface')->disableOriginalConstructor()->getMock(); + $this->process = $this->getMockBuilder('Composer\Util\ProcessExecutor')->getMock(); + $this->httpDownloader = $this->getHttpDownloaderMock(); } - public function tearDown(): void + protected function tearDown(): void { + parent::tearDown(); $fs = new Filesystem(); $fs->removeDirectory($this->home); } @@ -106,11 +111,12 @@ public function testInitialize($url, $apiUrl) } JSON; - $this->mockResponse($apiUrl, array(), $projectData) - ->shouldBeCalledTimes(1) - ; + $this->httpDownloader->expects( + [['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(); $this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL'); @@ -146,11 +152,12 @@ public function testInitializePublicProject($url, $apiUrl) } JSON; - $this->mockResponse($apiUrl, array(), $projectData) - ->shouldBeCalledTimes(1) - ; + $this->httpDownloader->expects( + [['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(); $this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL'); @@ -185,11 +192,12 @@ public function testInitializePublicProjectAsAnonymous($url, $apiUrl) } JSON; - $this->mockResponse($apiUrl, array(), $projectData) - ->shouldBeCalledTimes(1) - ; + $this->httpDownloader->expects( + [['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(); $this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL'); @@ -225,10 +233,12 @@ public function testInitializeWithPortNumber() } JSON; - $this->mockResponse($apiUrl, array(), sprintf($projectData, $domain, $port, $namespace)) - ->shouldBeCalledTimes(1); + $this->httpDownloader->expects( + [['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(); $this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL'); @@ -306,11 +316,11 @@ public function testGetTags() ] JSON; - $this->mockResponse($apiUrl, array(), $tagData) - ->shouldBeCalledTimes(1) - ; - - $driver->setHttpDownloader($this->httpDownloader->reveal()); + $this->httpDownloader->expects( + [['url' => $apiUrl, 'body' => $tagData]], + true + ); + $driver->setHttpDownloader($this->httpDownloader); $expected = array( 'v1.0.0' => '092ed2c762bbae331e3f51d4a17f67310bf99a81', @@ -325,8 +335,6 @@ public function testGetPaginatedRefs() { $driver = $this->testInitialize('https://gitlab.com/mygroup/myproject', 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject'); - $apiUrl = 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/branches?per_page=100'; - // @link http://doc.gitlab.com/ce/api/repositories.html#list-project-repository-branches $branchData = array( array( @@ -357,20 +365,23 @@ public function testGetPaginatedRefs() $branchData = json_encode($branchData); - $headers = array('Link: ; rel="next", ; rel="first", ; rel="last"'); - $this->httpDownloader - ->get($apiUrl, array()) - ->willReturn(new Response(array('url' => $apiUrl), 200, $headers, $branchData)) - ->shouldBeCalledTimes(1); - - $apiUrl = "http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=2&per_page=20"; - $headers = array('Link: ; rel="prev", ; rel="first", ; rel="last"'); - $this->httpDownloader - ->get($apiUrl, array()) - ->willReturn(new Response(array('url' => $apiUrl), 200, $headers, $branchData)) - ->shouldBeCalledTimes(1); + $this->httpDownloader->expects( + [ + [ + 'url' => 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/branches?per_page=100', + 'body' => $branchData, + 'headers' => array('Link: ; rel="next", ; rel="first", ; rel="last"'), + ], + [ + 'url' => "http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=2&per_page=20", + 'body' => $branchData, + 'headers' => array('Link: ; rel="prev", ; rel="first", ; rel="last"'), + ], + ], + true + ); - $driver->setHttpDownloader($this->httpDownloader->reveal()); + $driver->setHttpDownloader($this->httpDownloader); $expected = array( 'mymaster' => '97eda36b5c1dd953a3792865c222d4e85e5f302e', @@ -408,11 +419,12 @@ public function testGetBranches() ] JSON; - $this->mockResponse($apiUrl, array(), $branchData) - ->shouldBeCalledTimes(1) - ; + $this->httpDownloader->expects( + [['url' => $apiUrl, 'body' => $branchData]], + true + ); - $driver->setHttpDownloader($this->httpDownloader->reveal()); + $driver->setHttpDownloader($this->httpDownloader); $expected = array( 'mymaster' => '97eda36b5c1dd953a3792865c222d4e85e5f302e', @@ -432,7 +444,7 @@ public function testGetBranches() */ 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() @@ -480,11 +492,12 @@ public function testGitlabSubDirectory() } JSON; - $this->mockResponse($apiUrl, array(), $projectData) - ->shouldBeCalledTimes(1) - ; + $this->httpDownloader->expects( + [['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(); $this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL'); @@ -511,11 +524,12 @@ public function testGitlabSubGroup() } JSON; - $this->mockResponse($apiUrl, array(), $projectData) - ->shouldBeCalledTimes(1) - ; + $this->httpDownloader->expects( + [['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(); $this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL'); @@ -542,11 +556,12 @@ public function testGitlabSubDirectorySubGroup() } JSON; - $this->mockResponse($apiUrl, array(), $projectData) - ->shouldBeCalledTimes(1) - ; + $this->httpDownloader->expects( + [['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(); $this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL'); @@ -575,15 +590,17 @@ public function testForwardsOptions() } JSON; - $this->mockResponse(Argument::cetera(), $options, $projectData) - ->shouldBeCalled(); + $this->httpDownloader->expects( + [['url' => 'https:///api/v4/projects/%2Fmyproject', 'body' => $projectData]], + true + ); $driver = new GitLabDriver( array('url' => 'https://gitlab.mycompany.local/mygroup/myproject', 'options' => $options), - $this->io->reveal(), + $this->io, $this->config, - $this->httpDownloader->reveal(), - $this->process->reveal() + $this->httpDownloader, + $this->process ); $driver->initialize(); } @@ -609,28 +626,15 @@ public function testProtocolOverrideRepositoryUrlGeneration() $apiUrl = 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject'; $url = 'git@gitlab.com:mygroup/myproject'; - $this->mockResponse($apiUrl, array(), $projectData) - ->shouldBeCalledTimes(1) - ; + $this->httpDownloader->expects( + [['url' => $apiUrl, 'body' => $projectData]], + true + ); $config = clone $this->config; $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(); $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)); - } } diff --git a/tests/Composer/Test/Repository/Vcs/HgDriverTest.php b/tests/Composer/Test/Repository/Vcs/HgDriverTest.php index 93c10f27ebad..68b9c9e65a33 100644 --- a/tests/Composer/Test/Repository/Vcs/HgDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/HgDriverTest.php @@ -38,8 +38,9 @@ public function setUp(): void )); } - public function tearDown(): void + protected function tearDown(): void { + parent::tearDown(); $fs = new Filesystem; $fs->removeDirectory($this->home); } diff --git a/tests/Composer/Test/Repository/Vcs/PerforceDriverTest.php b/tests/Composer/Test/Repository/Vcs/PerforceDriverTest.php index df810bceebd6..a918b7ff904d 100644 --- a/tests/Composer/Test/Repository/Vcs/PerforceDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/PerforceDriverTest.php @@ -71,7 +71,7 @@ protected function setUp(): void 'branch' => self::TEST_BRANCH, ); $this->io = $this->getMockIOInterface(); - $this->process = new ProcessExecutorMock; + $this->process = $this->getProcessExecutorMock(); $this->httpDownloader = $this->getMockHttpDownloader(); $this->perforce = $this->getMockPerforce(); $this->driver = new PerforceDriver($this->repoConfig, $this->io, $this->config, $this->httpDownloader, $this->process); @@ -80,6 +80,7 @@ protected function setUp(): void protected function tearDown(): void { + parent::tearDown(); //cleanup directory under test path $fs = new Filesystem; $fs->removeDirectory($this->testPath); @@ -146,10 +147,10 @@ public function testInitializeCapturesVariablesFromRepoConfig() public function testInitializeLogsInAndConnectsClient() { - $this->perforce->expects($this->at(0))->method('p4Login'); - $this->perforce->expects($this->at(1))->method('checkStream'); - $this->perforce->expects($this->at(2))->method('writeP4ClientSpec'); - $this->perforce->expects($this->at(3))->method('connectClient'); + $this->perforce->expects($this->once())->method('p4Login'); + $this->perforce->expects($this->once())->method('checkStream'); + $this->perforce->expects($this->once())->method('writeP4ClientSpec'); + $this->perforce->expects($this->once())->method('connectClient'); $this->driver->initialize(); } diff --git a/tests/Composer/Test/Repository/Vcs/SvnDriverTest.php b/tests/Composer/Test/Repository/Vcs/SvnDriverTest.php index e67e275fea9e..440d2e35a0d4 100644 --- a/tests/Composer/Test/Repository/Vcs/SvnDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/SvnDriverTest.php @@ -40,15 +40,16 @@ public function setUp(): void )); } - public function tearDown(): void + protected function tearDown(): void { + parent::tearDown(); $fs = new Filesystem(); $fs->removeDirectory($this->home); } 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(); $httpDownloader = $this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(); @@ -57,10 +58,15 @@ public function testWrongCredentialsInUrl() $output .= " authorization failed: Could not authenticate to server:"; $output .= " rejected Basic challenge (https://corp.svn.local/)"; - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array( - 'svn --version', - 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 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); $repoConfig = array( @@ -69,8 +75,6 @@ public function testWrongCredentialsInUrl() $svn = new SvnDriver($repoConfig, $console, $this->config, $httpDownloader, $process); $svn->initialize(); - - $process->assertComplete($this); } public static function supportProvider() diff --git a/tests/Composer/Test/TestCase.php b/tests/Composer/Test/TestCase.php index 5255b5066cce..8640a946a7c8 100644 --- a/tests/Composer/Test/TestCase.php +++ b/tests/Composer/Test/TestCase.php @@ -12,11 +12,15 @@ namespace Composer\Test; +use Composer\Config; +use Composer\IO\IOInterface; use Composer\Pcre\Preg; use Composer\Semver\VersionParser; use Composer\Package\RootPackageInterface; use Composer\Package\PackageInterface; use Composer\Semver\Constraint\Constraint; +use Composer\Test\Mock\HttpDownloaderMock; +use Composer\Test\Mock\ProcessExecutorMock; use Composer\Util\Filesystem; use Composer\Util\Platform; use Composer\Util\Silencer; @@ -31,7 +35,7 @@ use Composer\Package\CompletePackageInterface; use Composer\Package\Package; -abstract class TestCase extends PolyfillTestCase +abstract class TestCase extends \PHPUnit\Framework\TestCase { /** * @var ?VersionParser @@ -42,6 +46,26 @@ abstract class TestCase extends PolyfillTestCase */ private static $executableCache = array(); + /** + * @var list + */ + private $httpDownloaderMocks = []; + /** + * @var list + */ + private $processExecutorMocks = []; + + protected function tearDown(): void + { + parent::tearDown(); + foreach ($this->httpDownloaderMocks as $mock) { + $mock->assertComplete(); + } + foreach ($this->processExecutorMocks as $mock) { + $mock->assertComplete(); + } + } + /** * @return string */ @@ -226,4 +250,18 @@ protected function getCmd($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; + } } diff --git a/tests/Composer/Test/Util/BitbucketTest.php b/tests/Composer/Test/Util/BitbucketTest.php index eece02ab5bb5..4f40f6ed2a05 100644 --- a/tests/Composer/Test/Util/BitbucketTest.php +++ b/tests/Composer/Test/Util/BitbucketTest.php @@ -301,9 +301,9 @@ public function testRequestAccessTokenWithUsernameAndPasswordWithNotFoundRespons public function testUsernamePasswordAuthenticationFlow() { $this->io - ->expects($this->at(0)) + ->expects($this->atLeastOnce()) ->method('writeError') - ->with($this->message) + ->withConsecutive([$this->message]) ; $this->io->expects($this->exactly(2)) @@ -469,7 +469,7 @@ public function testAuthorizeOAuthWithWrongOriginUrl() public function testAuthorizeOAuthWithoutAvailableGitConfigToken() { - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $process->expects(array(), false, array('return' => -1)); $bitbucket = new Bitbucket($this->io, $this->config, $process, $this->httpDownloader, $this->time); @@ -479,7 +479,7 @@ public function testAuthorizeOAuthWithoutAvailableGitConfigToken() public function testAuthorizeOAuthWithAvailableGitConfigToken() { - $process = new ProcessExecutorMock; + $process = $this->getProcessExecutorMock(); $bitbucket = new Bitbucket($this->io, $this->config, $process, $this->httpDownloader, $this->time); diff --git a/tests/Composer/Test/Util/ErrorHandlerTest.php b/tests/Composer/Test/Util/ErrorHandlerTest.php index 45bb198de9b9..8e082ecb4a24 100644 --- a/tests/Composer/Test/Util/ErrorHandlerTest.php +++ b/tests/Composer/Test/Util/ErrorHandlerTest.php @@ -25,8 +25,9 @@ public function setUp(): void ErrorHandler::register(); } - public function tearDown(): void + protected function tearDown(): void { + parent::tearDown(); restore_error_handler(); } diff --git a/tests/Composer/Test/Util/FilesystemTest.php b/tests/Composer/Test/Util/FilesystemTest.php index fa514cfae33c..6123b95f7f0f 100644 --- a/tests/Composer/Test/Util/FilesystemTest.php +++ b/tests/Composer/Test/Util/FilesystemTest.php @@ -39,8 +39,9 @@ public function setUp(): void $this->testFile = $this->getUniqueTmpDirectory() . '/composer_test_file'; } - public function tearDown(): void + protected function tearDown(): void { + parent::tearDown(); if (is_dir($this->workingDir)) { $this->fs->removeDirectory($this->workingDir); } diff --git a/tests/Composer/Test/Util/GitHubTest.php b/tests/Composer/Test/Util/GitHubTest.php index ed605c3c7b6f..b82b8e1d3ce0 100644 --- a/tests/Composer/Test/Util/GitHubTest.php +++ b/tests/Composer/Test/Util/GitHubTest.php @@ -12,6 +12,7 @@ namespace Composer\Test\Util; +use _PHPStan_c862bb974\Symfony\Component\Console\Output\BufferedOutput; use Composer\Downloader\TransportException; use Composer\Util\GitHub; use Composer\Util\Http\Response; @@ -33,9 +34,9 @@ public function testUsernamePasswordAuthenticationFlow() { $io = $this->getIOMock(); $io - ->expects($this->at(0)) + ->expects($this->atLeastOnce()) ->method('writeError') - ->with($this->message) + ->withConsecutive([$this->message]) ; $io ->expects($this->once()) @@ -45,15 +46,10 @@ public function testUsernamePasswordAuthenticationFlow() ; $httpDownloader = $this->getHttpDownloaderMock(); - $httpDownloader - ->expects($this->once()) - ->method('get') - ->with( - $this->equalTo($url = sprintf('https://api.%s/', $this->origin)), - $this->anything() - ) - ->willReturn(new Response(array('url' => $url), 200, array(), '{}')) - ; + $httpDownloader->expects( + [['url' => sprintf('https://api.%s/', $this->origin), 'body' => '{}']], + true + ); $config = $this->getConfigMock(); $config @@ -83,11 +79,10 @@ public function testUsernamePasswordFailure() ; $httpDownloader = $this->getHttpDownloaderMock(); - $httpDownloader - ->expects($this->exactly(1)) - ->method('get') - ->will($this->throwException(new TransportException('', 401))) - ; + $httpDownloader->expects( + [['url' => sprintf('https://api.%s/', $this->origin), 'status' => 401]], + true + ); $config = $this->getConfigMock(); $config @@ -123,20 +118,6 @@ private function getConfigMock() 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 */ diff --git a/tests/Composer/Test/Util/GitLabTest.php b/tests/Composer/Test/Util/GitLabTest.php index 6cbb340233d3..cd2a85dad484 100644 --- a/tests/Composer/Test/Util/GitLabTest.php +++ b/tests/Composer/Test/Util/GitLabTest.php @@ -13,6 +13,7 @@ namespace Composer\Test\Util; use Composer\Downloader\TransportException; +use Composer\Test\Mock\HttpDownloaderMock; use Composer\Util\GitLab; use Composer\Util\Http\Response; use Composer\Test\TestCase; @@ -37,9 +38,9 @@ public function testUsernamePasswordAuthenticationFlow() { $io = $this->getIOMock(); $io - ->expects($this->at(0)) + ->expects($this->atLeastOnce()) ->method('writeError') - ->with($this->message) + ->withConsecutive([$this->message]) ; $io ->expects($this->once()) @@ -55,15 +56,10 @@ public function testUsernamePasswordAuthenticationFlow() ; $httpDownloader = $this->getHttpDownloaderMock(); - $httpDownloader - ->expects($this->once()) - ->method('get') - ->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))) - ; + $httpDownloader->expects( + [['url' => sprintf('http://%s/oauth/token', $this->origin), 'body' => sprintf('{"access_token": "%s", "token_type": "bearer", "expires_in": 7200}', $this->token)]], + true + ); $config = $this->getConfigMock(); $config @@ -95,12 +91,16 @@ public function testUsernamePasswordFailure() ; $httpDownloader = $this->getHttpDownloaderMock(); - $httpDownloader - ->expects($this->exactly(5)) - ->method('get') - ->will($this->throwException($e = new TransportException('', 401))) - ; - $e->setResponse('{}'); + $httpDownloader->expects( + [ + ['url' => 'https://gitlab.com/oauth/token', 'status' => 401, 'body' => '{}'], + ['url' => 'https://gitlab.com/oauth/token', 'status' => 401, 'body' => '{}'], + ['url' => 'https://gitlab.com/oauth/token', 'status' => 401, 'body' => '{}'], + ['url' => 'https://gitlab.com/oauth/token', 'status' => 401, 'body' => '{}'], + ['url' => 'https://gitlab.com/oauth/token', 'status' => 401, 'body' => '{}'], + ], + true + ); $config = $this->getConfigMock(); $config @@ -136,20 +136,6 @@ private function getConfigMock() 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 */ diff --git a/tests/Composer/Test/Util/GitTest.php b/tests/Composer/Test/Util/GitTest.php index 279a15af9a0a..8b7b90770fa2 100644 --- a/tests/Composer/Test/Util/GitTest.php +++ b/tests/Composer/Test/Util/GitTest.php @@ -36,7 +36,7 @@ protected function setUp(): void { $this->io = $this->getMockBuilder('Composer\IO\IOInterface')->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->git = new Git($this->io, $this->config, $this->process, $this->fs); } @@ -61,8 +61,6 @@ public function testRunCommandPublicGitHubRepositoryNotInitialClone($protocol, $ $this->process->expects(array('git command'), true); $this->git->runCommand($commandCallable, 'https://github.com/acme/repo', null, true); - - $this->process->assertComplete($this); } public function publicGithubNoCredentialsProvider() @@ -92,8 +90,6 @@ public function testRunCommandPrivateGitHubRepositoryNotInitialCloneNotInteracti ), true); $this->git->runCommand($commandCallable, 'https://github.com/acme/repo', null, true); - - $this->process->assertComplete($this); } /** @@ -139,8 +135,6 @@ public function testRunCommandPrivateGitHubRepositoryNotInitialCloneNotInteracti ->willReturn(array('username' => 'token', 'password' => $gitHubToken)); $this->git->runCommand($commandCallable, $gitUrl, null, true); - - $this->process->assertComplete($this); } public function privateGithubWithCredentialsProvider() diff --git a/tests/Composer/Test/Util/Http/ProxyHelperTest.php b/tests/Composer/Test/Util/Http/ProxyHelperTest.php index 41ff3fe45093..e8c00a827f67 100644 --- a/tests/Composer/Test/Util/Http/ProxyHelperTest.php +++ b/tests/Composer/Test/Util/Http/ProxyHelperTest.php @@ -32,6 +32,7 @@ protected function setUp(): void protected function tearDown(): void { + parent::tearDown(); unset( $_SERVER['HTTP_PROXY'], $_SERVER['http_proxy'], diff --git a/tests/Composer/Test/Util/Http/ProxyManagerTest.php b/tests/Composer/Test/Util/Http/ProxyManagerTest.php index 6cb5d6bf240a..84365aa9bc8f 100644 --- a/tests/Composer/Test/Util/Http/ProxyManagerTest.php +++ b/tests/Composer/Test/Util/Http/ProxyManagerTest.php @@ -33,6 +33,7 @@ protected function setUp(): void protected function tearDown(): void { + parent::tearDown(); unset( $_SERVER['HTTP_PROXY'], $_SERVER['http_proxy'], diff --git a/tests/Composer/Test/Util/PerforceTest.php b/tests/Composer/Test/Util/PerforceTest.php index 3f23024df02b..223747301505 100644 --- a/tests/Composer/Test/Util/PerforceTest.php +++ b/tests/Composer/Test/Util/PerforceTest.php @@ -12,6 +12,7 @@ namespace Composer\Test\Util; +use Composer\Json\JsonFile; use Composer\Util\Perforce; use Composer\Test\TestCase; use Composer\Util\ProcessExecutor; @@ -153,10 +154,9 @@ public function testQueryP4UserWithUserSetInP4VariablesWithWindowsOS() return true; }; - $this->processExecutor->expects($this->at(0)) - ->method('execute') + $this->processExecutor->method('execute') ->with($this->equalTo($expectedCommand)) - ->will($this->returnCallback($callback)); + ->willReturnCallback($callback); $this->perforce->queryP4user(); $this->assertEquals('TEST_P4VARIABLE_USER', $this->perforce->getUser()); } @@ -171,10 +171,9 @@ public function testQueryP4UserWithUserSetInP4VariablesNotWindowsOS() return true; }; - $this->processExecutor->expects($this->at(0)) - ->method('execute') + $this->processExecutor->method('execute') ->with($this->equalTo($expectedCommand)) - ->will($this->returnCallback($callback)); + ->willReturnCallback($callback); $this->perforce->queryP4user(); $this->assertEquals('TEST_P4VARIABLE_USER', $this->perforce->getUser()); } @@ -183,10 +182,9 @@ public function testQueryP4UserQueriesForUser() { $this->perforce->setUser(null); $expectedQuestion = 'Enter P4 User:'; - $this->io->expects($this->at(0)) - ->method('ask') + $this->io->method('ask') ->with($this->equalTo($expectedQuestion)) - ->will($this->returnValue('TEST_QUERY_USER')); + ->willReturn('TEST_QUERY_USER'); $this->perforce->queryP4user(); $this->assertEquals('TEST_QUERY_USER', $this->perforce->getUser()); } @@ -197,14 +195,16 @@ public function testQueryP4UserStoresResponseToQueryForUserWithWindows() $this->perforce->setUser(null); $expectedQuestion = 'Enter P4 User:'; $expectedCommand = 'p4 set P4USER=TEST_QUERY_USER'; - $this->io->expects($this->at(0)) + $this->io->expects($this->once()) ->method('ask') ->with($this->equalTo($expectedQuestion)) - ->will($this->returnValue('TEST_QUERY_USER')); - $this->processExecutor->expects($this->at(1)) + ->willReturn('TEST_QUERY_USER'); + $this->processExecutor->expects($this->exactly(2)) ->method('execute') - ->with($this->equalTo($expectedCommand)) - ->will($this->returnValue(0)); + ->willReturnMap([ + ['p4 set', 0], + [$expectedCommand, 0], + ]); $this->perforce->queryP4user(); } @@ -214,14 +214,16 @@ public function testQueryP4UserStoresResponseToQueryForUserWithoutWindows() $this->perforce->setUser(null); $expectedQuestion = 'Enter P4 User:'; $expectedCommand = 'export P4USER=TEST_QUERY_USER'; - $this->io->expects($this->at(0)) + $this->io->expects($this->once()) ->method('ask') ->with($this->equalTo($expectedQuestion)) - ->will($this->returnValue('TEST_QUERY_USER')); - $this->processExecutor->expects($this->at(1)) + ->willReturn('TEST_QUERY_USER'); + $this->processExecutor->expects($this->exactly(2)) ->method('execute') - ->with($this->equalTo($expectedCommand)) - ->will($this->returnValue(0)); + ->willReturnMap([ + ['echo $P4USER', 0], + $expectedCommand => 0, + ]); $this->perforce->queryP4user(); } @@ -247,10 +249,9 @@ public function testQueryP4PasswordWithPasswordSetInP4VariablesWithWindowsOS() return true; }; - $this->processExecutor->expects($this->at(0)) - ->method('execute') + $this->processExecutor->method('execute') ->with($this->equalTo($expectedCommand)) - ->will($this->returnCallback($callback)); + ->willReturnCallback($callback); $password = $this->perforce->queryP4Password(); $this->assertEquals('TEST_P4VARIABLE_PASSWORD', $password); } @@ -264,10 +265,9 @@ public function testQueryP4PasswordWithPasswordSetInP4VariablesNotWindowsOS() return true; }; - $this->processExecutor->expects($this->at(0)) - ->method('execute') + $this->processExecutor->method('execute') ->with($this->equalTo($expectedCommand)) - ->will($this->returnCallback($callback)); + ->willReturnCallback($callback); $password = $this->perforce->queryP4Password(); $this->assertEquals('TEST_P4VARIABLE_PASSWORD', $password); @@ -276,10 +276,10 @@ public function testQueryP4PasswordWithPasswordSetInP4VariablesNotWindowsOS() public function testQueryP4PasswordQueriesForPassword() { $expectedQuestion = 'Enter password for Perforce user user: '; - $this->io->expects($this->at(0)) + $this->io->expects($this->once()) ->method('askAndHideAnswer') ->with($this->equalTo($expectedQuestion)) - ->will($this->returnValue('TEST_QUERY_PASSWORD')); + ->willReturn('TEST_QUERY_PASSWORD'); $password = $this->perforce->queryP4Password(); $this->assertEquals('TEST_QUERY_PASSWORD', $password); @@ -329,10 +329,10 @@ public function testWriteP4ClientSpecWithStream() public function testIsLoggedIn() { $expectedCommand = 'p4 -u user -p port login -s'; - $this->processExecutor->expects($this->at(0)) + $this->processExecutor->expects($this->once()) ->method('execute') ->with($this->equalTo($expectedCommand), $this->equalTo(null)) - ->will($this->returnValue(0)); + ->willReturn(0); $this->perforce->isLoggedIn(); } @@ -340,10 +340,10 @@ public function testIsLoggedIn() public function testConnectClient() { $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') ->with($this->equalTo($expectedCommand), $this->equalTo(null)) - ->will($this->returnValue(0)); + ->willReturn(0); $this->perforce->connectClient(); } @@ -352,29 +352,26 @@ public function testGetBranchesWithStream() { $this->setPerforceToStream(); - $expectedCommand = 'p4 -u user -c composer_perforce_TEST_depot_branch -p port streams '.ProcessExecutor::escape('//depot/...'); - $this->processExecutor->expects($this->at(0)) + $expectations = [ + ['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') - ->with($this->equalTo($expectedCommand)) ->will( $this->returnCallback( - function ($command, &$output) { - $output = 'Stream //depot/branch mainline none \'branch\'' . PHP_EOL; - - return true; + function ($command, &$output) use ($expectations, &$count) { + $index = $count++; + if ($command !== $expectations[$index][0]) { + 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(); $this->assertEquals('//depot/branch@1234', $branches['master']); @@ -391,7 +388,7 @@ public function testGetBranchesWithoutStream() $this->processExecutor->expects($this->once()) ->method('execute') ->with($this->equalTo($expectedCommand)) - ->will($this->returnCallback($expectedCallback)); + ->willReturnCallback($expectedCallback); $branches = $this->perforce->getBranches(); $this->assertEquals('//depot@5678', $branches['master']); } @@ -399,7 +396,7 @@ public function testGetBranchesWithoutStream() public function testGetTagsWithoutStream() { $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') ->with($this->equalTo($expectedCommand)) ->will( @@ -422,7 +419,7 @@ public function testGetTagsWithStream() $this->setPerforceToStream(); $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') ->with($this->equalTo($expectedCommand)) ->will( @@ -467,7 +464,7 @@ function ($command, &$output) { public function testGetComposerInformationWithoutLabelWithoutStream() { $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') ->with($this->equalTo($expectedCommand)) ->will( @@ -492,30 +489,23 @@ function ($command, &$output) { public function testGetComposerInformationWithLabelWithoutStream() { - $expectedCommand = 'p4 -u user -p port files '.ProcessExecutor::escape('//depot/composer.json@0.0.1'); - $this->processExecutor->expects($this->at(0)) + $expectations = [ + ['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') - ->with($this->equalTo($expectedCommand)) ->will( $this->returnCallback( - function ($command, &$output) { - $output = '//depot/composer.json#1 - branch change 10001 (text)'; - - return true; - } - ) - ); - - $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; + function ($command, &$output) use ($expectations, &$count) { + $index = $count++; + if ($command !== $expectations[$index][0]) { + throw new \InvalidArgumentException('Expected '.$expectations[$index][0].' and got '.$command); + } + $output = $expectations[$index][1]; + + return 0; } ) ); @@ -536,7 +526,7 @@ public function testGetComposerInformationWithoutLabelWithStream() $this->setPerforceToStream(); $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') ->with($this->equalTo($expectedCommand)) ->will( @@ -562,34 +552,28 @@ function ($command, &$output) { public function testGetComposerInformationWithLabelWithStream() { - $this->setPerforceToStream(); - $expectedCommand = 'p4 -u user -p port files '.ProcessExecutor::escape('//depot/branch/composer.json@0.0.1'); - $this->processExecutor->expects($this->at(0)) + $expectations = [ + [ 'p4 -u user -p port files '.ProcessExecutor::escape('//depot/branch/composer.json@0.0.1'), '//depot/composer.json#1 - branch change 10001 (text)'], + ['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') - ->with($this->equalTo($expectedCommand)) ->will( $this->returnCallback( - function ($command, &$output) { - $output = '//depot/composer.json#1 - branch change 10001 (text)'; - - return true; + function ($command, &$output) use ($expectations, &$count) { + $index = $count++; + if ($command !== $expectations[$index][0]) { + 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->processExecutor->expects($this->at(1)) - ->method('execute') - ->with($this->equalTo($expectedCommand)) - ->will( - $this->returnCallback( - function ($command, &$output) { - $output = PerforceTest::getComposerJson(); - - return true; - } - ) - ); + $this->setPerforceToStream(); $result = $this->perforce->getComposerInformation('//depot/branch@0.0.1'); @@ -605,10 +589,10 @@ function ($command, &$output) { public function testSyncCodeBaseWithoutStream() { $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') ->with($this->equalTo($expectedCommand), $this->equalTo(null)) - ->will($this->returnValue(0)); + ->willReturn(0); $this->perforce->syncCodeBase('label'); } @@ -617,10 +601,10 @@ public function testSyncCodeBaseWithStream() { $this->setPerforceToStream(); $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') ->with($this->equalTo($expectedCommand)) - ->will($this->returnValue(0)); + ->willReturn(0); $this->perforce->syncCodeBase('label'); } @@ -630,10 +614,10 @@ public function testCheckServerExists() $processExecutor = $this->getMockBuilder('Composer\Util\ProcessExecutor')->getMock(); $expectedCommand = 'p4 -p '.ProcessExecutor::escape('perforce.does.exist:port').' info -s'; - $processExecutor->expects($this->at(0)) + $processExecutor->expects($this->once()) ->method('execute') ->with($this->equalTo($expectedCommand), $this->equalTo(null)) - ->will($this->returnValue(0)); + ->willReturn(0); $result = $this->perforce->checkServerExists('perforce.does.exist:port', $processExecutor); $this->assertTrue($result); @@ -651,10 +635,10 @@ public function testCheckServerClientError() $processExecutor = $this->getMockBuilder('Composer\Util\ProcessExecutor')->getMock(); $expectedCommand = 'p4 -p '.ProcessExecutor::escape('perforce.does.exist:port').' info -s'; - $processExecutor->expects($this->at(0)) + $processExecutor->expects($this->once()) ->method('execute') ->with($this->equalTo($expectedCommand), $this->equalTo(null)) - ->will($this->returnValue(127)); + ->willReturn(127); $result = $this->perforce->checkServerExists('perforce.does.exist:port', $processExecutor); $this->assertFalse($result); @@ -665,19 +649,14 @@ public function testCheckServerClientError() */ public static function getComposerJson() { - $composer_json = array( - '{', - '"name": "test/perforce",', - '"description": "Basic project for testing",', - '"minimum-stability": "dev",', - '"autoload": {', - '"psr-0" : {', - '}', - '}', - '}', - ); - - return implode($composer_json); + return JsonFile::encode([ + 'name' => 'test/perforce', + 'description' => 'Basic project for testing', + 'minimum-stability' => 'dev', + 'autoload' => [ + 'psr-0' => [] + ] + ], JSON_FORCE_OBJECT); } /** diff --git a/tests/Composer/Test/Util/RemoteFilesystemTest.php b/tests/Composer/Test/Util/RemoteFilesystemTest.php index 4233dc948a4d..1fd35cffdad3 100644 --- a/tests/Composer/Test/Util/RemoteFilesystemTest.php +++ b/tests/Composer/Test/Util/RemoteFilesystemTest.php @@ -206,20 +206,19 @@ public function testCopyWithSuccessOnRetry() 'retry' => true, )); - $fs->expects($this->at(0)) + $counter = 0; + $fs->expects($this->exactly(2)) ->method('getRemoteContents') - ->willReturnCallback(function ($originUrl, $fileUrl, $ctx, &$http_response_header) { - $http_response_header = array('http/1.1 401 unauthorized'); + ->willReturnCallback(function ($originUrl, $fileUrl, $ctx, &$http_response_header) use (&$counter) { + 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)) - ->method('getRemoteContents') - ->willReturnCallback(function ($originUrl, $fileUrl, $ctx, &$http_response_header) { - $http_response_header = array('http/1.1 200 OK'); - - return 'expects($this->at(1)) - ->method('getAuthentication') + ->method('getAuthentication') ->with('bitbucket.org') ->willReturn(array( 'username' => 'x-token-auth', diff --git a/tests/Composer/Test/Util/StreamContextFactoryTest.php b/tests/Composer/Test/Util/StreamContextFactoryTest.php index d17b9b7cc13b..4a4c8b50c821 100644 --- a/tests/Composer/Test/Util/StreamContextFactoryTest.php +++ b/tests/Composer/Test/Util/StreamContextFactoryTest.php @@ -26,6 +26,7 @@ protected function setUp(): 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']); ProxyManager::reset(); } diff --git a/tests/complete.phpunit.xml b/tests/complete.phpunit.xml index e60a38d5bba0..14b2de0939dc 100644 --- a/tests/complete.phpunit.xml +++ b/tests/complete.phpunit.xml @@ -16,7 +16,6 @@ > -