1
0
Fork 0

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

pull/10343/head
Jordi Boggiano 2021-12-09 17:09:07 +01:00
parent 095c36ecf8
commit ffd62795bc
No known key found for this signature in database
GPG Key ID: 7BBD42C429EC80BC
56 changed files with 746 additions and 921 deletions

View File

@ -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",

16
composer.lock generated
View File

@ -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",

View File

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

View File

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

View File

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

View File

@ -165,7 +165,7 @@ class Svn
}
$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:')

View File

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

View File

@ -14,11 +14,12 @@ namespace Composer\Test;
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,27 +35,26 @@ class ApplicationTest extends TestCase
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));
->willReturnCallback(function ($opt): bool {
switch ($opt) {
case '--no-plugins':
return true;
case '--no-scripts':
return false;
case '--no-cache':
return false;
}
$inputMock->expects($this->at($index++))
->method('hasParameterOption')
->with($this->equalTo('--no-scripts'))
->will($this->returnValue(false));
return false;
});
$inputMock->expects($this->at($index++))
$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));
@ -63,33 +63,22 @@ class ApplicationTest extends TestCase
->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('<warning>Composer is operating slower than normal because you have Xdebug enabled. See https://getcomposer.org/xdebug</warning>'));
$expectedOutput .= '<warning>Composer is operating slower than normal because you have Xdebug enabled. See https://getcomposer.org/xdebug</warning>'.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>Warning: This development build of Composer is over 60 days old. It is recommended to update it by running "%s self-update" to get the latest version.</warning>', $_SERVER['PHP_SELF'])));
$expectedOutput .= sprintf('<warning>Warning: This development build of Composer is over 60 days old. It is recommended to update it by running "%s self-update" to get the latest version.</warning>', $_SERVER['PHP_SELF']).PHP_EOL;
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());
}
/**
@ -107,27 +96,26 @@ class ApplicationTest extends TestCase
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));
->willReturnCallback(function ($opt): bool {
switch ($opt) {
case '--no-plugins':
return true;
case '--no-scripts':
return false;
case '--no-cache':
return false;
}
$inputMock->expects($this->at($index++))
->method('hasParameterOption')
->with($this->equalTo('--no-scripts'))
->will($this->returnValue(false));
return false;
});
$inputMock->expects($this->at($index++))
$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));

View File

@ -150,6 +150,7 @@ class AutoloadGeneratorTest extends TestCase
protected function tearDown(): void
{
parent::tearDown();
chdir($this->origDir);
if (is_dir($this->workingDir)) {
@ -957,17 +958,13 @@ EOF;
$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 @@ EOF;
public function testPreAndPostEventsAreDispatchedDuringAutoloadDump()
{
$this->eventDispatcher
->expects($this->at(0))
->expects($this->exactly(2))
->method('dispatchScript')
->with(ScriptEvents::PRE_AUTOLOAD_DUMP, false);
$this->eventDispatcher
->expects($this->at(1))
->method('dispatchScript')
->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/')));

View File

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

View File

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

View File

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

View File

@ -220,7 +220,7 @@ class FileDownloaderTest extends TestCase
$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 @@ class FileDownloaderTest extends TestCase
$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 @@ class FileDownloaderTest extends TestCase
$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 @@ class FileDownloaderTest extends TestCase
->will($this->returnValue(array($distUrl)));
$ioMock = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$ioMock->expects($this->at(0))
$ioMock->expects($this->atLeast(2))
->method('writeError')
->with($this->stringContains('Downloading'));
$ioMock->expects($this->at(1))
->method('writeError')
->with($this->stringContains('Downgrading'));
->withConsecutive(
[$this->stringContains('Downloading')],
[$this->stringContains('Downgrading')]
);
$path = $this->getUniqueTmpDirectory();
$filesystem = $this->getMockBuilder('Composer\Util\Filesystem')->getMock();

View File

@ -29,6 +29,7 @@ class FossilDownloaderTest extends TestCase
protected function tearDown(): void
{
parent::tearDown();
if (is_dir($this->workingDir)) {
$fs = new Filesystem;
$fs->removeDirectory($this->workingDir);
@ -46,7 +47,7 @@ class FossilDownloaderTest extends TestCase
{
$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 @@ class FossilDownloaderTest extends TestCase
->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 @@ class FossilDownloaderTest extends TestCase
$downloader = $this->getDownloaderMock(null, null, $process);
$downloader->install($packageMock, 'repo');
$process->assertComplete($this);
}
public function testUpdateforPackageWithoutSourceReference()
@ -124,7 +123,7 @@ class FossilDownloaderTest extends TestCase
->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 @@ class FossilDownloaderTest extends TestCase
$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 @@ class FossilDownloaderTest extends TestCase
$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 @@ class FossilDownloaderTest extends TestCase
$downloader->prepare('uninstall', $packageMock, $this->workingDir);
$downloader->remove($packageMock, $this->workingDir);
$downloader->cleanup('uninstall', $packageMock, $this->workingDir);
$process->assertComplete($this);
}
public function testGetInstallationSource()

View File

@ -39,6 +39,7 @@ class GitDownloaderTest extends TestCase
protected function tearDown(): void
{
parent::tearDown();
if (is_dir($this->workingDir)) {
$this->fs->removeDirectory($this->workingDir);
}
@ -85,7 +86,7 @@ class GitDownloaderTest extends TestCase
protected function getDownloaderMock($io = null, $config = null, $executor = null, $filesystem = null)
{
$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 @@ class GitDownloaderTest extends TestCase
->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 @@ class GitDownloaderTest extends TestCase
$downloader->prepare('install', $packageMock, 'composerPath');
$downloader->install($packageMock, 'composerPath');
$downloader->cleanup('install', $packageMock, 'composerPath');
$process->assertComplete($this);
}
public function testDownloadWithCache()
@ -165,7 +164,7 @@ class GitDownloaderTest extends TestCase
$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 @@ class GitDownloaderTest extends TestCase
$downloader->install($packageMock, 'composerPath');
$downloader->cleanup('install', $packageMock, 'composerPath');
@rmdir($cachePath);
$process->assertComplete($this);
}
public function testDownloadUsesVariousProtocolsAndSetsPushUrlForGithub()
@ -203,7 +200,7 @@ class GitDownloaderTest extends TestCase
->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 @@ class GitDownloaderTest extends TestCase
$downloader->prepare('install', $packageMock, 'composerPath');
$downloader->install($packageMock, 'composerPath');
$downloader->cleanup('install', $packageMock, 'composerPath');
$process->assertComplete($this);
}
public function pushUrlProvider()
@ -260,7 +255,7 @@ class GitDownloaderTest extends TestCase
->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 @@ class GitDownloaderTest extends TestCase
$downloader->prepare('install', $packageMock, 'composerPath');
$downloader->install($packageMock, 'composerPath');
$downloader->cleanup('install', $packageMock, 'composerPath');
$process->assertComplete($this);
}
public function testDownloadThrowsRuntimeExceptionIfGitCommandFails()
@ -296,7 +289,7 @@ class GitDownloaderTest extends TestCase
->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 @@ class GitDownloaderTest extends TestCase
$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 @@ class GitDownloaderTest extends TestCase
->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 @@ class GitDownloaderTest extends TestCase
$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 @@ class GitDownloaderTest extends TestCase
->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 @@ composer https://github.com/old/url (push)
$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 @@ composer https://github.com/old/url (push)
->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 @@ composer https://github.com/old/url (push)
'return' => 1,
),
$this->winCompat('git --version'),
$this->winCompat('git branch -r'),
), true);
$this->fs->ensureDirectoryExists($this->workingDir.'/.git');
@ -476,8 +462,6 @@ composer https://github.com/old/url (push)
$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 @@ composer https://github.com/old/url (push)
->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 @@ composer https://github.com/old/url (push)
$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 @@ composer https://github.com/old/url (push)
->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 @@ composer https://github.com/old/url (push)
->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 @@ composer https://github.com/old/url (push)
$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 @@ composer https://github.com/old/url (push)
$downloader->prepare('uninstall', $packageMock, $this->workingDir);
$downloader->remove($packageMock, $this->workingDir);
$downloader->cleanup('uninstall', $packageMock, $this->workingDir);
$process->assertComplete($this);
}
public function testGetInstallationSource()

View File

@ -29,6 +29,7 @@ class HgDownloaderTest extends TestCase
protected function tearDown(): void
{
parent::tearDown();
if (is_dir($this->workingDir)) {
$fs = new Filesystem;
$fs->removeDirectory($this->workingDir);
@ -46,7 +47,7 @@ class HgDownloaderTest extends TestCase
{
$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 @@ class HgDownloaderTest extends TestCase
->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 @@ class HgDownloaderTest extends TestCase
$downloader = $this->getDownloaderMock(null, null, $process);
$downloader->install($packageMock, 'composerPath');
$process->assertComplete($this);
}
public function testUpdateforPackageWithoutSourceReference()
@ -118,7 +117,7 @@ class HgDownloaderTest extends TestCase
->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 @@ class HgDownloaderTest extends TestCase
$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 @@ class HgDownloaderTest extends TestCase
$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 @@ class HgDownloaderTest extends TestCase
$downloader->prepare('uninstall', $packageMock, $this->workingDir);
$downloader->remove($packageMock, $this->workingDir);
$downloader->cleanup('uninstall', $packageMock, $this->workingDir);
$process->assertComplete($this);
}
public function testGetInstallationSource()

View File

@ -49,7 +49,7 @@ class PerforceDownloaderTest extends TestCase
$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 @@ class PerforceDownloaderTest extends TestCase
$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 @@ class PerforceDownloaderTest extends TestCase
$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');
}

View File

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

View File

@ -42,8 +42,9 @@ class ZipDownloaderTest extends TestCase
$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);

View File

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

View File

@ -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 @@ class ConsoleIOTest extends TestCase
$outputMock->expects($this->any())
->method('getVerbosity')
->willReturn(OutputInterface::VERBOSITY_NORMAL);
$outputMock->expects($this->at(1))
$outputMock->expects($this->atLeast(7))
->method('write')
->with($this->equalTo('something (<question>strlen = 23</question>)'));
$outputMock->expects($this->at(3))
->method('write')
->with($this->equalTo(str_repeat("\x08", 23)), $this->equalTo(false));
$outputMock->expects($this->at(5))
->method('write')
->with($this->equalTo('shorter (<comment>12</comment>)'), $this->equalTo(false));
$outputMock->expects($this->at(7))
->method('write')
->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 (<info>34</info>)'));
->withConsecutive(
[$this->equalTo('something (<question>strlen = 23</question>)')],
[$this->equalTo(str_repeat("\x08", 23)), $this->equalTo(false)],
[$this->equalTo('shorter (<comment>12</comment>)'), $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 (<info>34</info>)')]
);
$helperMock = $this->getMockBuilder('Symfony\Component\Console\Helper\HelperSet')->getMock();

View File

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

View File

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

View File

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

View File

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

View File

@ -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<string, string>
* @var array<array{url: string, options: array<mixed>|null, status: int, body: string, headers: list<string>}>|null
*/
protected $contentMap;
private $expectations = null;
/**
* @var bool
*/
private $strict = false;
/**
* @var array{status: int, body: string, headers: array<string>}
*/
private $defaultHandler = array('status' => 200, 'body' => '', 'headers' => []);
/**
* @var string[]
*/
private $log = array();
public function __construct(IOInterface $io = null, Config $config = null)
{
if ($io === null) {
$io = new BufferIO();
}
if ($config === null) {
$config = new Config(false);
}
parent::__construct($io, $config);
}
/**
* @param array<string, string> $contentMap associative array of locations and content
* @param array<array{url: string, options?: array<mixed>, status?: int, body?: string, headers?: array<string>}> $expectations
* @param bool $strict set to true if you want to provide *all* expected http requests, and not just a subset you are interested in testing
* @param array{status?: int, body?: string, headers?: array<string>} $defaultHandler default URL handler for undefined requests if not in strict mode
*/
public function __construct(array $contentMap)
public function expects(array $expectations, bool $strict = false, array $defaultHandler = array('return' => 0, 'stdout' => '', 'stderr' => '')): void
{
$this->contentMap = $contentMap;
$default = ['url' => '', 'options' => null, 'status' => 200, 'body' => '', 'headers' => ['']];
$this->expectations = array_map(function (array $expect) use ($default): array {
if ($diff = array_diff_key(array_merge($default, $expect), $default)) {
throw new \UnexpectedValueException('Unexpected keys in process execution step: '.implode(', ', array_keys($diff)));
}
return array_merge($default, $expect);
}, $expectations);
$this->strict = $strict;
$this->defaultHandler = array_merge($this->defaultHandler, $defaultHandler);
}
public function get($fileUrl, $options = array())
public function assertComplete(): void
{
if (!empty($this->contentMap[$fileUrl])) {
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;
}
}

View File

@ -14,6 +14,7 @@ namespace Composer\Test\Mock;
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 @@ use React\Promise\Promise;
class ProcessExecutorMock extends ProcessExecutor
{
/**
* @var array<array{cmd: string, return: int, stdout: string, stderr: string, callback: ?callable}>
* @var array<array{cmd: string, return: int, stdout: string, stderr: string, callback: ?callable}>|null
*/
private $expectations = array();
private $expectations = null;
/**
* @var bool
*/
@ -64,10 +65,14 @@ class ProcessExecutorMock extends ProcessExecutor
$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 @@ class ProcessExecutorMock extends ProcessExecutor
);
}
$testCase->assertTrue(true);
// dummy assertion to ensure the test is not marked as having no assertions
Assert::assertTrue(true);
}
public function execute($command, &$output = null, $cwd = null)
@ -115,7 +121,7 @@ class ProcessExecutorMock extends ProcessExecutor
$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 @@ class ProcessExecutorMock extends ProcessExecutor
} 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))
);
}

View File

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

View File

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

View File

@ -81,7 +81,7 @@ class RootPackageLoaderTest extends TestCase
$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 @@ class RootPackageLoaderTest extends TestCase
->getMock()
;
$process = new ProcessExecutorMock;
$process = $this->getProcessExecutorMock();
$process->expects(array(
array(
'cmd' => 'git branch -a --no-color --no-abbrev -v',
@ -136,8 +136,6 @@ class RootPackageLoaderTest extends TestCase
$package = $loader->load(array('require' => array('foo/bar' => 'self.version')));
$this->assertEquals("dev-master", $package->getPrettyVersion());
$process->assertComplete($this);
}
public function testNonFeatureBranchPrettyVersion()
@ -151,7 +149,7 @@ class RootPackageLoaderTest extends TestCase
->getMock()
;
$process = new ProcessExecutorMock;
$process = $this->getProcessExecutorMock();
$process->expects(array(
array(
'cmd' => 'git branch -a --no-color --no-abbrev -v',
@ -165,7 +163,5 @@ class RootPackageLoaderTest extends TestCase
$package = $loader->load(array('require' => array('foo/bar' => 'self.version'), "non-feature-branches" => array("latest-.*")));
$this->assertEquals("dev-latest-production", $package->getPrettyVersion());
$process->assertComplete($this);
}
}

View File

@ -33,7 +33,7 @@ class VersionGuesserTest extends TestCase
{
$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 @@ class VersionGuesserTest extends TestCase
$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 @@ class VersionGuesserTest extends TestCase
$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 @@ class VersionGuesserTest extends TestCase
$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 @@ class VersionGuesserTest extends TestCase
$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 @@ class VersionGuesserTest extends TestCase
$this->assertEquals("dev-current", $versionArray['version']);
$this->assertEquals($anotherCommitHash, $versionArray['commit']);
$process->assertComplete($this);
}
public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationForArbitraryNaming()
@ -114,7 +108,7 @@ class VersionGuesserTest extends TestCase
$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 @@ class VersionGuesserTest extends TestCase
$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 @@ class VersionGuesserTest extends TestCase
$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 @@ class VersionGuesserTest extends TestCase
$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 @@ class VersionGuesserTest extends TestCase
$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 @@ class VersionGuesserTest extends TestCase
$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 @@ class VersionGuesserTest extends TestCase
$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 @@ class VersionGuesserTest extends TestCase
$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 @@ class VersionGuesserTest extends TestCase
$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 @@ class VersionGuesserTest extends TestCase
$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 @@ class VersionGuesserTest extends TestCase
$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 @@ class VersionGuesserTest extends TestCase
$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 @@ class VersionGuesserTest extends TestCase
$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 @@ class VersionGuesserTest extends TestCase
$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);
}
}

View File

@ -181,15 +181,13 @@ class VersionSelectorTest extends TestCase
$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);

View File

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

View File

@ -1,137 +0,0 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Test {
use PHPUnit\Framework\TestCase;
if (method_exists('PHPUnit\Framework\TestCase', 'assertFileDoesNotExist')) {
abstract class PolyfillTestCase extends TestCase
{
}
} else {
abstract class PolyfillTestCase extends TestCase
{
// all the functions below are form https://github.com/symfony/phpunit-bridge/blob/bd341a45ef79b30918376e8b8e2279fac6894c3b/Legacy/PolyfillAssertTrait.php
/**
* @param string $filename
* @param string $message
*
* @return void
*/
public static function assertIsNotReadable($filename, $message = '')
{
static::assertNotIsReadable($filename, $message);
}
/**
* @param string $filename
* @param string $message
*
* @return void
*/
public static function assertIsNotWritable($filename, $message = '')
{
static::assertNotIsWritable($filename, $message);
}
/**
* @param string $directory
* @param string $message
*
* @return void
*/
public static function assertDirectoryDoesNotExist($directory, $message = '')
{
static::assertDirectoryNotExists($directory, $message);
}
/**
* @param string $directory
* @param string $message
*
* @return void
*/
public static function assertDirectoryIsNotReadable($directory, $message = '')
{
static::assertDirectoryNotIsReadable($directory, $message);
}
/**
* @param string $directory
* @param string $message
*
* @return void
*/
public static function assertDirectoryIsNotWritable($directory, $message = '')
{
static::assertDirectoryNotIsWritable($directory, $message);
}
/**
* @param string $filename
* @param string $message
*
* @return void
*/
public static function assertFileDoesNotExist($filename, $message = '')
{
static::assertFileNotExists($filename, $message);
}
/**
* @param string $filename
* @param string $message
*
* @return void
*/
public static function assertFileIsNotReadable($filename, $message = '')
{
static::assertFileNotIsReadable($filename, $message);
}
/**
* @param string $filename
* @param string $message
*
* @return void
*/
public static function assertFileIsNotWritable($filename, $message = '')
{
static::assertFileNotIsWritable($filename, $message);
}
/**
* @param string $pattern
* @param string $string
* @param string $message
*
* @return void
*/
public static function assertMatchesRegularExpression($pattern, $string, $message = '')
{
static::assertRegExp($pattern, $string, $message);
}
/**
* @param string $pattern
* @param string $string
* @param string $message
*
* @return void
*/
public static function assertDoesNotMatchRegularExpression($pattern, $string, $message = '')
{
static::assertNotRegExp($pattern, $string, $message);
}
}
}
}

View File

@ -58,7 +58,7 @@ class ComposerRepositoryTest extends TestCase
}
$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 @@ class ComposerRepositoryTest extends TestCase
),
);
$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 @@ class ComposerRepositoryTest extends TestCase
public function testSearchWithAbandonedPackages()
{
$repoConfig = array(
'url' => 'http://2.example.org',
'url' => 'http://example.org',
);
$result = array(
@ -223,15 +229,22 @@ class ComposerRepositoryTest extends TestCase
),
);
$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 @@ class ComposerRepositoryTest extends TestCase
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'),

View File

@ -26,8 +26,9 @@ class RepositoryManagerTest extends TestCase
$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);

View File

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

View File

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

View File

@ -39,8 +39,9 @@ class GitHubDriverTest extends TestCase
));
}
public function tearDown(): void
protected function tearDown(): void
{
parent::tearDown();
$fs = new Filesystem;
$fs->removeDirectory($this->home);
}
@ -58,18 +59,19 @@ class GitHubDriverTest extends TestCase
->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 @@ class GitHubDriverTest extends TestCase
->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 @@ class GitHubDriverTest extends TestCase
->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 @@ class GitHubDriverTest extends TestCase
->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 @@ class GitHubDriverTest extends TestCase
->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 @@ class GitHubDriverTest extends TestCase
->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 @@ class GitHubDriverTest extends TestCase
$this->assertEquals('git', $source['type']);
$this->assertEquals($repoSshUrl, $source['url']);
$this->assertEquals($sha, $source['reference']);
$process->assertComplete($this);
}
/**

View File

@ -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 @@ class GitLabDriverTest extends TestCase
),
));
$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);
}
@ -108,11 +113,12 @@ class GitLabDriverTest extends TestCase
}
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');
@ -148,11 +154,12 @@ JSON;
}
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');
@ -187,11 +194,12 @@ JSON;
}
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');
@ -227,10 +235,12 @@ JSON;
}
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');
@ -308,11 +318,11 @@ JSON;
]
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',
@ -327,8 +337,6 @@ JSON;
{
$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(
@ -359,20 +367,23 @@ JSON;
$branchData = json_encode($branchData);
$headers = array('Link: <http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=2&per_page=20>; rel="next", <http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=1&per_page=20>; rel="first", <http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=3&per_page=20>; rel="last"');
$this->httpDownloader
->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: <http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=2&per_page=20>; rel="next", <http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=1&per_page=20>; rel="first", <http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=3&per_page=20>; rel="last"'),
],
[
'url' => "http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=2&per_page=20",
'body' => $branchData,
'headers' => array('Link: <http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=2&per_page=20>; rel="prev", <http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=1&per_page=20>; rel="first", <http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=3&per_page=20>; rel="last"'),
],
],
true
);
$apiUrl = "http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=2&per_page=20";
$headers = array('Link: <http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=2&per_page=20>; rel="prev", <http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=1&per_page=20>; rel="first", <http://gitlab.com/api/v4/projects/mygroup%2Fmyproject/repository/tags?id=mygroup%2Fmyproject&page=3&per_page=20>; rel="last"');
$this->httpDownloader
->get($apiUrl, array())
->willReturn(new Response(array('url' => $apiUrl), 200, $headers, $branchData))
->shouldBeCalledTimes(1);
$driver->setHttpDownloader($this->httpDownloader->reveal());
$driver->setHttpDownloader($this->httpDownloader);
$expected = array(
'mymaster' => '97eda36b5c1dd953a3792865c222d4e85e5f302e',
@ -410,11 +421,12 @@ JSON;
]
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',
@ -434,7 +446,7 @@ JSON;
*/
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()
@ -482,11 +494,12 @@ JSON;
}
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');
@ -513,11 +526,12 @@ JSON;
}
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');
@ -544,11 +558,12 @@ JSON;
}
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');
@ -577,15 +592,17 @@ JSON;
}
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();
}
@ -611,28 +628,15 @@ JSON;
$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));
}
}

View File

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

View File

@ -71,7 +71,7 @@ class PerforceDriverTest extends TestCase
'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 @@ class PerforceDriverTest extends TestCase
protected function tearDown(): void
{
parent::tearDown();
//cleanup directory under test path
$fs = new Filesystem;
$fs->removeDirectory($this->testPath);
@ -146,10 +147,10 @@ class PerforceDriverTest extends TestCase
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();
}

View File

@ -40,15 +40,16 @@ class SvnDriverTest extends TestCase
));
}
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 @@ class SvnDriverTest extends TestCase
$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 @@ class SvnDriverTest extends TestCase
$svn = new SvnDriver($repoConfig, $console, $this->config, $httpDownloader, $process);
$svn->initialize();
$process->assertComplete($this);
}
public static function supportProvider()

View File

@ -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\CompleteAliasPackage;
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<HttpDownloaderMock>
*/
private $httpDownloaderMocks = [];
/**
* @var list<ProcessExecutorMock>
*/
private $processExecutorMocks = [];
protected function tearDown(): void
{
parent::tearDown();
foreach ($this->httpDownloaderMocks as $mock) {
$mock->assertComplete();
}
foreach ($this->processExecutorMocks as $mock) {
$mock->assertComplete();
}
}
/**
* @return string
*/
@ -226,4 +250,18 @@ abstract class TestCase extends PolyfillTestCase
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;
}
}

View File

@ -301,9 +301,9 @@ class BitbucketTest extends TestCase
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 @@ class BitbucketTest extends TestCase
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 @@ class BitbucketTest extends TestCase
public function testAuthorizeOAuthWithAvailableGitConfigToken()
{
$process = new ProcessExecutorMock;
$process = $this->getProcessExecutorMock();
$bitbucket = new Bitbucket($this->io, $this->config, $process, $this->httpDownloader, $this->time);

View File

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

View File

@ -39,8 +39,9 @@ class FilesystemTest extends TestCase
$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);
}

View File

@ -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 @@ class GitHubTest extends TestCase
{
$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 @@ class GitHubTest extends TestCase
;
$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 @@ class GitHubTest extends TestCase
;
$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 @@ class GitHubTest extends TestCase
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
*/

View File

@ -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 @@ class GitLabTest extends TestCase
{
$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 @@ class GitLabTest extends TestCase
;
$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 @@ class GitLabTest extends TestCase
;
$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 @@ class GitLabTest extends TestCase
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
*/

View File

@ -36,7 +36,7 @@ class GitTest extends TestCase
{
$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 @@ class GitTest extends TestCase
$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 @@ class GitTest extends TestCase
), true);
$this->git->runCommand($commandCallable, 'https://github.com/acme/repo', null, true);
$this->process->assertComplete($this);
}
/**
@ -139,8 +135,6 @@ class GitTest extends TestCase
->willReturn(array('username' => 'token', 'password' => $gitHubToken));
$this->git->runCommand($commandCallable, $gitUrl, null, true);
$this->process->assertComplete($this);
}
public function privateGithubWithCredentialsProvider()

View File

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

View File

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

View File

@ -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 @@ class PerforceTest extends TestCase
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 @@ class PerforceTest extends TestCase
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 @@ class PerforceTest extends TestCase
{
$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 @@ class PerforceTest extends TestCase
$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 @@ class PerforceTest extends TestCase
$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 @@ class PerforceTest extends TestCase
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 @@ class PerforceTest extends TestCase
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 @@ class PerforceTest extends TestCase
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 @@ class PerforceTest extends TestCase
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 @@ class PerforceTest extends TestCase
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 @@ class PerforceTest extends TestCase
{
$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;
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 true;
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 @@ class PerforceTest extends TestCase
$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 @@ class PerforceTest extends TestCase
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 @@ class PerforceTest extends TestCase
$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 @@ class PerforceTest extends TestCase
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 @@ class PerforceTest extends TestCase
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)';
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 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;
return 0;
}
)
);
@ -536,7 +526,7 @@ class PerforceTest extends TestCase
$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 @@ class PerforceTest extends TestCase
public function testGetComposerInformationWithLabelWithStream()
{
$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')
->will(
$this->returnCallback(
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;
}
)
);
$this->setPerforceToStream();
$expectedCommand = 'p4 -u user -p port files '.ProcessExecutor::escape('//depot/branch/composer.json@0.0.1');
$this->processExecutor->expects($this->at(0))
->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_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;
}
)
);
$result = $this->perforce->getComposerInformation('//depot/branch@0.0.1');
@ -605,10 +589,10 @@ class PerforceTest extends TestCase
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 @@ class PerforceTest extends TestCase
{
$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 @@ class PerforceTest extends TestCase
$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 @@ class PerforceTest extends TestCase
$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 @@ class PerforceTest extends TestCase
*/
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);
}
/**

View File

@ -206,20 +206,19 @@ class RemoteFilesystemTest extends TestCase
'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 '<?php $copied = "Copied"; ';
return '<?php $copied = "Copied"; ';
}
});
$file = tempnam(sys_get_temp_dir(), 'z');
@ -324,8 +323,7 @@ class RemoteFilesystemTest extends TestCase
return $arg === 'bitbucket.org';
});
$io
->expects($this->at(1))
->method('getAuthentication')
->method('getAuthentication')
->with('bitbucket.org')
->willReturn(array(
'username' => 'x-token-auth',

View File

@ -26,6 +26,7 @@ class StreamContextFactoryTest extends TestCase
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();
}

View File

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