1
0
Fork 0

Merge pull request #10343 from Seldaek/drop_old_php

Upgrade to PHP 7.2+
pull/10419/head
Jordi Boggiano 2022-01-03 12:50:13 +01:00 committed by GitHub
commit efa08e7791
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
127 changed files with 11179 additions and 2930 deletions

View File

@ -22,12 +22,6 @@ jobs:
strategy:
matrix:
php-version:
- "5.3"
- "5.4"
- "5.5"
- "5.6"
- "7.0"
- "7.1"
- "7.2"
- "7.3"
- "7.4"
@ -37,30 +31,34 @@ jobs:
os: [ubuntu-latest]
experimental: [false]
include:
- php-version: "5.3"
- php-version: "7.2"
dependencies: highest
os: ubuntu-latest
experimental: false
- php-version: "5.3"
- php-version: "7.2"
dependencies: lowest
os: ubuntu-latest
experimental: false
- php-version: "8.0"
- php-version: "8.1"
dependencies: highest
os: ubuntu-latest
experimental: false
- php-version: "8.1"
os: windows-latest
dependencies: locked
experimental: false
- php-version: "8.0"
- php-version: "8.1"
os: macos-latest
dependencies: locked
experimental: false
- php-version: "8.1"
dependencies: lowest
- php-version: "8.2"
dependencies: lowest-ignore
os: ubuntu-latest
experimental: false
- php-version: "8.1"
dependencies: highest
experimental: true
- php-version: "8.2"
dependencies: highest-ignore
os: ubuntu-latest
experimental: false
experimental: true
steps:
- name: "Checkout"
@ -99,24 +97,6 @@ jobs:
if: "matrix.dependencies == 'locked'"
run: "composer install ${{ env.COMPOSER_FLAGS }}"
- name: "Require latest PHPUnitBridge for PHP 8.x"
if: "startsWith(matrix.php-version, '8.')"
# using ~ here to avoid issues with windows CLI removing the ^
run: 'composer require --no-update --dev "symfony/phpunit-bridge:~5.2"'
# temporary fix until phpunit-bridge has a release supporting 8.1
- name: "Require latest dev PHPUnitBridge for PHP 8.1"
if: "matrix.experimental"
# using ~ here to avoid issues with windows CLI removing the ^
run: 'composer require --no-update --dev "symfony/phpunit-bridge:~5.4@dev"'
- name: "Set ignored deprecations for php 8.1+ on lowest or locked deps"
if: "matrix.php-version >= '8.1' && !contains(matrix.dependencies, 'highest')"
run: "echo \"SYMFONY_DEPRECATIONS_HELPER=baselineFile=./tests/deprecations-8.1.json&max[direct]=0\" >> $GITHUB_ENV"
- name: "Update dev requirements to latest available for the current PHP even on locked builds as they are not bundled dependencies"
run: "composer config platform --unset && composer update ${{ env.COMPOSER_FLAGS }} symfony/phpunit-bridge phpspec/prophecy phpdocumentor/* sebastian/* doctrine/instantiator"
- name: "Run install again using composer binary from source"
run: "bin/composer install ${{ env.COMPOSER_FLAGS }}"

View File

@ -17,7 +17,7 @@ jobs:
strategy:
matrix:
php-version:
- "5.3"
- "7.2"
- "latest"
steps:

View File

@ -17,11 +17,16 @@ jobs:
name: "PHPStan"
runs-on: ubuntu-latest
continue-on-error: ${{ matrix.experimental }}
strategy:
matrix:
php-version:
- "7.4"
include:
- php-version: "7.2"
experimental: false
- php-version: "8.1"
experimental: true
fail-fast: false
steps:
- name: "Checkout"
@ -46,12 +51,16 @@ jobs:
key: "php-${{ matrix.php-version }}-symfony-php-unit-version-${{ env.SYMFONY_PHPUNIT_VERSION }}-${{ hashFiles('**/composer.lock') }}"
restore-keys: "php-${{ matrix.php-version }}-symfony-php-unit-version-${{ env.SYMFONY_PHPUNIT_VERSION }}"
- name: "Install highest dependencies from composer.json using composer binary provided by system"
- name: "Install highest dependencies"
if: "matrix.experimental == true"
run: "composer config platform --unset && composer update ${{ env.COMPOSER_FLAGS }}"
- name: "Install PHPStan"
# Locked to phpunit 7.5 here as newer ones have void return types which break inheritance
run: "bin/composer require --dev phpstan/phpstan:^1.0 phpstan/phpstan-phpunit:^1.0 phpstan/phpstan-deprecation-rules:^1 phpstan/phpstan-strict-rules:^1 phpunit/phpunit:^7.5.20 --with-all-dependencies ${{ env.COMPOSER_FLAGS }}"
- name: "Install locked dependencies"
if: "matrix.experimental == false"
run: "composer config platform --unset && composer update ${{ env.COMPOSER_FLAGS }}"
- name: "Initialize PHPUnit sources"
run: "vendor/bin/simple-phpunit --filter NO_TEST_JUST_AUTOLOAD_THANKS"
- name: "Run PHPStan"
run: "vendor/bin/phpstan analyse --configuration=phpstan/config.neon"
run: "composer phpstan"

View File

@ -22,7 +22,7 @@
}
],
"require": {
"php": "^5.3.2 || ^7.0 || ^8.0",
"php": "^7.2.5 || ^8.0",
"composer/ca-bundle": "^1.0",
"composer/metadata-minifier": "^1.0",
"composer/semver": "^3.0",
@ -31,17 +31,20 @@
"justinrainbow/json-schema": "^5.2.11",
"psr/log": "^1.0 || ^2.0",
"seld/jsonlint": "^1.4",
"seld/phar-utils": "^1.0",
"symfony/console": "^2.8.52 || ^3.4.35 || ^4.4 || ^5.0",
"symfony/filesystem": "^2.8.52 || ^3.4.35 || ^4.4 || ^5.0 || ^6.0",
"symfony/finder": "^2.8.52 || ^3.4.35 || ^4.4 || ^5.0 || ^6.0",
"symfony/process": "^2.8.52 || ^3.4.35 || ^4.4 || ^5.0 || ^6.0",
"react/promise": "^1.2 || ^2.7",
"seld/phar-utils": "^1.2",
"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"
},
"require-dev": {
"symfony/phpunit-bridge": "^4.2 || ^5.0 || ^6.0",
"phpspec/prophecy": "^1.10"
"symfony/phpunit-bridge": "^6.0",
"phpstan/phpstan": "^1.0",
"phpstan/phpstan-phpunit": "^1.0",
"phpstan/phpstan-deprecation-rules": "^1",
"phpstan/phpstan-strict-rules": "^1"
},
"suggest": {
"ext-openssl": "Enabling the openssl extension allows you to access https URLs for repositories and packages",
@ -50,13 +53,13 @@
},
"config": {
"platform": {
"php": "5.3.9"
"php": "7.2.5"
},
"platform-check": false
},
"extra": {
"branch-alias": {
"dev-main": "2.2-dev"
"dev-main": "2.3-dev"
}
},
"autoload": {
@ -80,18 +83,11 @@
"scripts": {
"compile": "@php -dphar.readonly=0 bin/compile",
"test": "@php simple-phpunit",
"phpstan-setup": [
"@composer config platform --unset",
"@composer update",
"@composer require --dev phpstan/phpstan:^1.0 phpstan/phpstan-phpunit:^1.0 phpstan/phpstan-deprecation-rules:^1 phpstan/phpstan-strict-rules:^1 phpunit/phpunit:^7.5.20 --with-all-dependencies",
"git checkout composer.json composer.lock"
],
"phpstan": "@php vendor/bin/phpstan analyse --configuration=phpstan/config.neon"
},
"scripts-descriptions": {
"compile": "Compile composer.phar",
"test": "Run all tests",
"phpstan-setup": "Prepare environment to run PHPStan locally (must be run with PHP7.4)",
"phpstan": "Runs PHPStan (after phpstan-setup was executed, must be run with PHP7.4)"
},
"support": {

1361
composer.lock generated

File diff suppressed because it is too large Load Diff

8875
phpstan/baseline-8.1.neon Normal file

File diff suppressed because it is too large Load Diff

View File

@ -950,11 +950,6 @@ parameters:
count: 1
path: ../src/Composer/Command/GlobalCommand.php
-
message: "#^Return type \\(int\\|void\\) of method Composer\\\\Command\\\\GlobalCommand\\:\\:run\\(\\) should be covariant with return type \\(int\\) of method Symfony\\\\Component\\\\Console\\\\Command\\\\Command\\:\\:run\\(\\)$#"
count: 1
path: ../src/Composer/Command/GlobalCommand.php
-
message: "#^Cannot call method getPackage\\(\\) on Composer\\\\Composer\\|null\\.$#"
count: 1
@ -2440,16 +2435,6 @@ parameters:
count: 3
path: ../src/Composer/Compiler.php
-
message: "#^Only booleans are allowed in an if condition, array\\<int, bool\\|string\\> given\\.$#"
count: 1
path: ../src/Composer/Compiler.php
-
message: "#^Only booleans are allowed in an if condition, array\\<int, string\\> given\\.$#"
count: 1
path: ../src/Composer/Compiler.php
-
message: "#^Parameter \\#1 \\$haystack of function strpos expects string, string\\|false given\\.$#"
count: 1
@ -4235,6 +4220,11 @@ parameters:
count: 2
path: ../src/Composer/Installer/InstallationManager.php
-
message: "#^Constant PHP_WINDOWS_EVENT_CTRL_C not found\\.$#"
count: 1
path: ../src/Composer/Installer/InstallationManager.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 1
@ -4245,6 +4235,11 @@ parameters:
count: 2
path: ../src/Composer/Installer/InstallationManager.php
-
message: "#^Function sapi_windows_set_ctrl_handler not found\\.$#"
count: 3
path: ../src/Composer/Installer/InstallationManager.php
-
message: "#^Only booleans are allowed in &&, Composer\\\\EventDispatcher\\\\EventDispatcher\\|null given on the right side\\.$#"
count: 2
@ -6745,6 +6740,16 @@ parameters:
count: 2
path: ../src/Composer/Util/Http/CurlDownloader.php
-
message: "#^Constant CURLOPT_PROXY_CAINFO not found\\.$#"
count: 1
path: ../src/Composer/Util/Http/CurlDownloader.php
-
message: "#^Constant CURLOPT_PROXY_CAPATH not found\\.$#"
count: 1
path: ../src/Composer/Util/Http/CurlDownloader.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
count: 3
@ -8450,12 +8455,12 @@ parameters:
path: ../tests/Composer/Test/Json/JsonValidationExceptionTest.php
-
message: "#^Composer\\\\Test\\\\Mock\\\\HttpDownloaderMock\\:\\:__construct\\(\\) does not call parent constructor from Composer\\\\Util\\\\HttpDownloader\\.$#"
message: "#^Property Composer\\\\Test\\\\Mock\\\\HttpDownloaderMock\\:\\:\\$defaultHandler \\(array\\{status\\: int, body\\: string, headers\\: array\\<string\\>\\}\\) does not accept non\\-empty\\-array\\<literal\\-string&non\\-empty\\-string, array\\<string\\>\\|int\\|string\\>\\.$#"
count: 1
path: ../tests/Composer/Test/Mock/HttpDownloaderMock.php
-
message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#"
message: "#^Property Composer\\\\Test\\\\Mock\\\\HttpDownloaderMock\\:\\:\\$expectations \\(array\\<array\\{url\\: string, options\\: array\\|null, status\\: int, body\\: string, headers\\: array\\<int, string\\>\\}\\>\\|null\\) does not accept array\\<non\\-empty\\-array\\<literal\\-string&non\\-empty\\-string, array\\|int\\|string\\|null\\>\\>\\.$#"
count: 1
path: ../tests/Composer/Test/Mock/HttpDownloaderMock.php
@ -8469,31 +8474,11 @@ parameters:
count: 1
path: ../tests/Composer/Test/Mock/InstallationManagerMock.php
-
message: "#^Call to method PHPUnit\\\\Framework\\\\Assert\\:\\:assertTrue\\(\\) with true will always evaluate to true\\.$#"
count: 1
path: ../tests/Composer/Test/Mock/ProcessExecutorMock.php
-
message: "#^Only booleans are allowed in &&, array\\<array\\<string, \\(callable\\)\\|int\\|string\\|null\\>\\> given on the left side\\.$#"
count: 1
path: ../tests/Composer/Test/Mock/ProcessExecutorMock.php
-
message: "#^Only booleans are allowed in a ternary operator condition, array\\<array\\<string, \\(callable\\)\\|int\\|string\\|null\\>\\> given\\.$#"
count: 1
path: ../tests/Composer/Test/Mock/ProcessExecutorMock.php
-
message: "#^Only booleans are allowed in an elseif condition, array\\<string, \\(callable\\)\\|int\\|string\\|null\\> given\\.$#"
count: 1
path: ../tests/Composer/Test/Mock/ProcessExecutorMock.php
-
message: "#^Only booleans are allowed in an if condition, array\\<array\\<string, \\(callable\\)\\|int\\|string\\|null\\>\\> given\\.$#"
count: 1
path: ../tests/Composer/Test/Mock/ProcessExecutorMock.php
-
message: "#^Only booleans are allowed in an if condition, string given\\.$#"
count: 2
@ -8510,7 +8495,7 @@ parameters:
path: ../tests/Composer/Test/Mock/ProcessExecutorMock.php
-
message: "#^Property Composer\\\\Test\\\\Mock\\\\ProcessExecutorMock\\:\\:\\$expectations \\(array\\<array\\{cmd\\: string, return\\: int, stdout\\: string, stderr\\: string, callback\\: \\(callable\\(\\)\\: mixed\\)\\|null\\}\\>\\) does not accept array\\<non\\-empty\\-array\\<literal\\-string&non\\-empty\\-string, \\(callable\\(\\)\\: mixed\\)\\|int\\|string\\|null\\>\\>\\.$#"
message: "#^Property Composer\\\\Test\\\\Mock\\\\ProcessExecutorMock\\:\\:\\$expectations \\(array\\<array\\{cmd\\: string, return\\: int, stdout\\: string, stderr\\: string, callback\\: \\(callable\\(\\)\\: mixed\\)\\|null\\}\\>\\|null\\) does not accept array\\<non\\-empty\\-array\\<literal\\-string&non\\-empty\\-string, \\(callable\\(\\)\\: mixed\\)\\|int\\|string\\|null\\>\\>\\.$#"
count: 1
path: ../tests/Composer/Test/Mock/ProcessExecutorMock.php
@ -8824,11 +8809,6 @@ parameters:
count: 1
path: ../tests/Composer/Test/Repository/RepositoryManagerTest.php
-
message: "#^Only booleans are allowed in an if condition, string\\|null given\\.$#"
count: 1
path: ../tests/Composer/Test/Repository/RepositoryManagerTest.php
-
message: "#^Dynamic call to static method Composer\\\\Test\\\\TestCase\\:\\:getUniqueTmpDirectory\\(\\)\\.$#"
count: 1
@ -8869,31 +8849,6 @@ parameters:
count: 1
path: ../tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php
-
message: "#^Parameter \\#1 \\$io of static method Composer\\\\Repository\\\\Vcs\\\\GitLabDriver\\:\\:supports\\(\\) expects Composer\\\\IO\\\\IOInterface, object given\\.$#"
count: 1
path: ../tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php
-
message: "#^Parameter \\#2 \\$io of class Composer\\\\Repository\\\\Vcs\\\\GitLabDriver constructor expects Composer\\\\IO\\\\IOInterface, object given\\.$#"
count: 9
path: ../tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php
-
message: "#^Parameter \\#4 \\$body of class Composer\\\\Util\\\\Http\\\\Response constructor expects string\\|null, string\\|false given\\.$#"
count: 2
path: ../tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php
-
message: "#^Parameter \\#4 \\$httpDownloader of class Composer\\\\Repository\\\\Vcs\\\\GitLabDriver constructor expects Composer\\\\Util\\\\HttpDownloader, object given\\.$#"
count: 9
path: ../tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php
-
message: "#^Parameter \\#5 \\$process of class Composer\\\\Repository\\\\Vcs\\\\GitLabDriver constructor expects Composer\\\\Util\\\\ProcessExecutor, object given\\.$#"
count: 9
path: ../tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php
-
message: "#^Dynamic call to static method Composer\\\\Test\\\\TestCase\\:\\:getUniqueTmpDirectory\\(\\)\\.$#"
count: 1
@ -8944,11 +8899,6 @@ parameters:
count: 1
path: ../tests/Composer/Test/Repository/VcsRepositoryTest.php
-
message: "#^Call to function method_exists\\(\\) with \\$this\\(Composer\\\\Test\\\\TestCase\\) and 'expectException' will always evaluate to true\\.$#"
count: 1
path: ../tests/Composer/Test/TestCase.php
-
message: "#^Method Composer\\\\Test\\\\TestCase\\:\\:getPackage\\(\\) should return Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage but returns PackageClass of Composer\\\\Package\\\\PackageInterface\\.$#"
count: 1

View File

@ -3,6 +3,7 @@ includes:
- ../vendor/phpstan/phpstan-deprecation-rules/rules.neon
- ../vendor/phpstan/phpstan-strict-rules/rules.neon
- ./baseline.neon
- ./ignore-by-php-version.neon.php
parameters:
level: 8
@ -36,22 +37,16 @@ parameters:
# we don't have different constructors for parent/child
- '~^Unsafe usage of new static\(\)\.$~'
# BC with older PHPUnit
- '~^Call to an undefined static method Composer\\Test\\PolyfillTestCase::setExpectedException\(\)\.$~'
- '~^Call to an undefined method Composer\\Test\\[a-zA-Z0-9\\]+::(assertFileDoesNotExist|assertMatchesRegularExpression)\(\)\.$~'
# Mock errors
- '~^Call to an undefined method (PHPUnit\\Framework\\MockObject\\MockObject|Prophecy\\Prophecy\\ObjectProphecy)::.*$~'
# Ignore some irrelevant errors in test files
- '~Method Composer\\Test\\[^:]+::(setUp(BeforeClass)?|tearDown(AfterClass)?|test[^(]+)\(\) has no return type specified.~'
- '~Method Composer\\Test\\[^:]+::(data\w+|provide\w+|\w+?Provider)\(\) has no return type specified.~'
# PHPUnit assertions as instance methods
- '~Dynamic call to static method PHPUnit\\Framework\\Assert::\w+\(\)~'
- '~Dynamic call to static method PHPUnit\\Framework\\TestCase::(once|at|exactly|will|exactly|returnValue|returnCallback|any|atLeastOnce|throwException|onConsecutiveCalls|never|returnValueMap)\(\)~'
- '~Dynamic call to static method PHPUnit\\Framework\\TestCase::(once|atLeast|exactly|will|exactly|returnValue|returnCallback|any|atLeastOnce|throwException|onConsecutiveCalls|never|returnValueMap)\(\)~'
bootstrapFiles:
- ./locate-phpunit-autoloader.php
- ../tests/bootstrap.php
paths:

View File

@ -0,0 +1,14 @@
<?php declare(strict_types = 1);
use PHPStan\DependencyInjection\NeonAdapter;
$adapter = new NeonAdapter();
// more inspiration at https://github.com/phpstan/phpstan-src/blob/master/build/ignore-by-php-version.neon.php
$config = [];
if (PHP_VERSION_ID >= 80000) {
$config = array_merge_recursive($config, $adapter->load(__DIR__ . '/baseline-8.1.neon'));
}
$config['parameters']['phpVersion'] = PHP_VERSION_ID;
return $config;

View File

@ -0,0 +1,22 @@
<?php
$bestDirFound = null;
$dirs = glob(__DIR__.'/../vendor/bin/.phpunit/phpunit-*', GLOB_ONLYDIR);
natsort($dirs);
foreach (array_reverse($dirs) as $dir) {
$bestDirFound = $dir;
if (PHP_VERSION_ID >= 80000 && false !== strpos($dir, 'phpunit-9')) {
break;
}
if (PHP_VERSION_ID < 80000 && false !== strpos($dir, 'phpunit-8')) {
break;
}
}
if (null === $bestDirFound) {
echo 'Run "composer test" to initialize PHPUnit sources before running PHPStan'.PHP_EOL;
exit(1);
}
include $bestDirFound.'/vendor/autoload.php';

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

@ -163,7 +163,8 @@ class ClassMapGenerator
$rejectedClasses = array();
$realSubPath = substr($filePath, strlen($basePath) + 1);
$realSubPath = substr($realSubPath, 0, strrpos($realSubPath, '.'));
$dotPosition = strrpos($realSubPath, '.');
$realSubPath = substr($realSubPath, 0, $dotPosition === false ? PHP_INT_MAX : $dotPosition);
foreach ($classes as $class) {
// silently skip if ns doesn't have common root
@ -226,7 +227,7 @@ class ClassMapGenerator
$message = 'File at "%s" does not exist, check your classmap definitions';
} elseif (!Filesystem::isReadable($path)) {
$message = 'File at "%s" is not readable, check its permissions';
} elseif ('' === trim(file_get_contents($path))) {
} elseif ('' === trim((string) file_get_contents($path))) {
// The input file was really empty and thus contains no classes
return array();
} else {

View File

@ -218,7 +218,7 @@ class Cache
$file = Preg::replace('{[^'.$this->allowlist.']}i', '-', $file);
if (file_exists($this->root . $file)) {
try {
touch($this->root . $file, filemtime($this->root . $file), time());
touch($this->root . $file, (int) filemtime($this->root . $file), time());
} catch (\ErrorException $e) {
// fallback in case the above failed due to incorrect ownership
// see https://github.com/composer/composer/issues/4070

View File

@ -62,10 +62,9 @@ EOT
}
/**
* @return int|void
* @throws \Symfony\Component\Console\Exception\ExceptionInterface
*/
public function run(InputInterface $input, OutputInterface $output)
public function run(InputInterface $input, OutputInterface $output): int
{
if (!method_exists($input, '__toString')) {
throw new \LogicException('Expected an Input instance that is stringable, got '.get_class($input));

View File

@ -298,6 +298,9 @@ TAGSPUBKEY
}
$pubkeyid = openssl_pkey_get_public($sigFile);
if (false === $pubkeyid) {
throw new \RuntimeException('Failed loading the public key from '.$sigFile);
}
$algo = defined('OPENSSL_ALGO_SHA384') ? OPENSSL_ALGO_SHA384 : 'SHA384';
if (!in_array('sha384', array_map('strtolower', openssl_get_md_methods()))) {
throw new \RuntimeException('SHA384 is not supported by your openssl extension, could not verify the phar file integrity');
@ -308,6 +311,7 @@ TAGSPUBKEY
// PHP 8 automatically frees the key instance and deprecates the function
if (PHP_VERSION_ID < 80000) {
// @phpstan-ignore-next-line
openssl_free_key($pubkeyid);
}

View File

@ -50,25 +50,13 @@ class Compiler
unlink($pharFile);
}
// TODO in v2.3 always call with an array
if (method_exists('Symfony\Component\Process\Process', 'fromShellCommandline')) {
$process = new Process(array('git', 'log', '--pretty="%H"', '-n1', 'HEAD'), __DIR__);
} else {
// @phpstan-ignore-next-line
$process = new Process('git log --pretty="%H" -n1 HEAD', __DIR__);
}
$process = new Process(array('git', 'log', '--pretty=%H', '-n1', 'HEAD'), __DIR__);
if ($process->run() != 0) {
throw new \RuntimeException('Can\'t run git log. You must ensure to run compile from composer git repository clone and that git binary is available.');
}
$this->version = trim($process->getOutput());
// TODO in v2.3 always call with an array
if (method_exists('Symfony\Component\Process\Process', 'fromShellCommandline')) {
$process = new Process(array('git', 'log', '-n1', '--pretty=%ci', 'HEAD'), __DIR__);
} else {
// @phpstan-ignore-next-line
$process = new Process('git log -n1 --pretty=%ci HEAD', __DIR__);
}
$process = new Process(array('git', 'log', '-n1', '--pretty=%ci', 'HEAD'), __DIR__);
if ($process->run() != 0) {
throw new \RuntimeException('Can\'t run git log. You must ensure to run compile from composer git repository clone and that git binary is available.');
}
@ -137,8 +125,8 @@ class Compiler
$finder->files()
->ignoreVCS(true)
->notPath('/\/(composer\.(json|lock)|[A-Z]+\.md|\.gitignore|appveyor.yml|phpunit\.xml\.dist|phpstan\.neon\.dist|phpstan-config\.neon)$/')
->notPath('/bin\/(jsonlint|validate-json|simple-phpunit)(\.bat)?$/')
->notPath('symfony/debug/Resources/ext/')
->notPath('/bin\/(jsonlint|validate-json|simple-phpunit|phpstan|phpstan\.phar)(\.bat)?$/')
->notPath('symfony/console/Resources/completion.bash')
->notPath('justinrainbow/json-schema/demo/')
->notPath('justinrainbow/json-schema/dist/')
->notPath('composer/installed.json')
@ -150,13 +138,18 @@ class Compiler
->sort($finderSort)
;
$extraFiles = array(
realpath(__DIR__ . '/../../vendor/composer/spdx-licenses/res/spdx-exceptions.json'),
realpath(__DIR__ . '/../../vendor/composer/spdx-licenses/res/spdx-licenses.json'),
realpath(CaBundle::getBundledCaBundlePath()),
realpath(__DIR__ . '/../../vendor/symfony/console/Resources/bin/hiddeninput.exe'),
realpath(__DIR__ . '/../../vendor/symfony/polyfill-mbstring/Resources/mb_convert_variables.php8'),
);
$extraFiles = [];
foreach (array(
__DIR__ . '/../../vendor/composer/spdx-licenses/res/spdx-exceptions.json',
__DIR__ . '/../../vendor/composer/spdx-licenses/res/spdx-licenses.json',
CaBundle::getBundledCaBundlePath(),
__DIR__ . '/../../vendor/symfony/console/Resources/bin/hiddeninput.exe',
) as $file) {
$extraFiles[$file] = realpath($file);
if (!file_exists($file)) {
throw new \RuntimeException('Extra file listed is missing from the filesystem: '.$file);
}
}
$unexpectedFiles = array();
foreach ($finder as $file) {
@ -173,11 +166,11 @@ class Compiler
}
}
if ($extraFiles) {
throw new \RuntimeException('These files were expected but not added to the phar, they might be excluded or gone from the source package:'.PHP_EOL.implode(PHP_EOL, $extraFiles));
if (count($extraFiles) > 0) {
throw new \RuntimeException('These files were expected but not added to the phar, they might be excluded or gone from the source package:'.PHP_EOL.var_export($extraFiles, true));
}
if ($unexpectedFiles) {
throw new \RuntimeException('These files were unexpectedly added to the phar, make sure they are excluded or listed in $extraFiles:'.PHP_EOL.implode(PHP_EOL, $unexpectedFiles));
if (count($unexpectedFiles) > 0) {
throw new \RuntimeException('These files were unexpectedly added to the phar, make sure they are excluded or listed in $extraFiles:'.PHP_EOL.var_export($unexpectedFiles, true));
}
// Add bin/composer
@ -200,7 +193,14 @@ class Compiler
$util->updateTimestamps($this->versionDate);
$util->save($pharFile, \Phar::SHA512);
Linter::lint($pharFile);
Linter::lint($pharFile, [
'vendor/symfony/console/Attribute/AsCommand.php',
'vendor/symfony/polyfill-intl-grapheme/bootstrap80.php',
'vendor/symfony/polyfill-intl-normalizer/bootstrap80.php',
'vendor/symfony/polyfill-mbstring/bootstrap80.php',
'vendor/symfony/polyfill-php73/Resources/stubs/JsonException.php',
'vendor/symfony/service-contracts/Attribute/SubscribedService.php',
]);
}
/**

View File

@ -55,7 +55,7 @@ class Composer
const VERSION = '@package_version@';
const BRANCH_ALIAS_VERSION = '@package_branch_alias_version@';
const RELEASE_DATE = '@release_date@';
const SOURCE_VERSION = '2.2.999-dev+source';
const SOURCE_VERSION = '2.3.999-dev+source';
/**
* Version number of the internal composer-runtime-api package

View File

@ -119,10 +119,7 @@ class Application extends BaseApplication
parent::__construct('Composer', Composer::getVersion());
}
/**
* @return int
*/
public function run(InputInterface $input = null, OutputInterface $output = null)
public function run(InputInterface $input = null, OutputInterface $output = null): int
{
if (null === $output) {
$output = Factory::createOutput();
@ -131,10 +128,7 @@ class Application extends BaseApplication
return parent::run($input, $output);
}
/**
* @return int
*/
public function doRun(InputInterface $input, OutputInterface $output)
public function doRun(InputInterface $input, OutputInterface $output): int
{
$this->disablePluginsByDefault = $input->hasParameterOption('--no-plugins');
$this->disableScriptsByDefault = $input->hasParameterOption('--no-scripts');
@ -483,10 +477,7 @@ class Application extends BaseApplication
return $this->io;
}
/**
* @return string
*/
public function getHelp()
public function getHelp(): string
{
return self::$logo . parent::getHelp();
}
@ -495,7 +486,7 @@ class Application extends BaseApplication
* Initializes all the composer commands.
* @return \Symfony\Component\Console\Command\Command[]
*/
protected function getDefaultCommands()
protected function getDefaultCommands(): array
{
$commands = array_merge(parent::getDefaultCommands(), array(
new Command\AboutCommand(),
@ -535,10 +526,7 @@ class Application extends BaseApplication
return $commands;
}
/**
* @return string
*/
public function getLongVersion()
public function getLongVersion(): string
{
if (Composer::BRANCH_ALIAS_VERSION && Composer::BRANCH_ALIAS_VERSION !== '@package_branch_alias_version'.'@') {
return sprintf(
@ -553,10 +541,7 @@ class Application extends BaseApplication
return parent::getLongVersion() . ' ' . Composer::RELEASE_DATE;
}
/**
* @return InputDefinition
*/
protected function getDefaultInputDefinition()
protected function getDefaultInputDefinition(): InputDefinition
{
$definition = parent::getDefaultInputDefinition();
$definition->addOption(new InputOption('--profile', null, InputOption::VALUE_NONE, 'Display timing and memory usage information'));

View File

@ -60,12 +60,7 @@ class HtmlOutputFormatter extends OutputFormatter
parent::__construct(true, $styles);
}
/**
* @param ?string $message
*
* @return string
*/
public function format($message)
public function format(?string $message): ?string
{
$formatted = parent::format($message);

View File

@ -205,20 +205,12 @@ class Decisions implements \Iterator, \Countable
array_pop($this->decisionQueue);
}
/**
* @return int
*/
#[\ReturnTypeWillChange]
public function count()
public function count(): int
{
return \count($this->decisionQueue);
}
/**
* @return void
*/
#[\ReturnTypeWillChange]
public function rewind()
public function rewind(): void
{
end($this->decisionQueue);
}
@ -232,29 +224,17 @@ class Decisions implements \Iterator, \Countable
return current($this->decisionQueue);
}
/**
* @return ?int
*/
#[\ReturnTypeWillChange]
public function key()
public function key(): ?int
{
return key($this->decisionQueue);
}
/**
* @return void
*/
#[\ReturnTypeWillChange]
public function next()
public function next(): void
{
prev($this->decisionQueue);
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function valid()
public function valid(): bool
{
return false !== current($this->decisionQueue);
}

View File

@ -129,10 +129,8 @@ class Pool implements \Countable
/**
* Returns how many packages have been loaded into the pool
* @return int
*/
#[\ReturnTypeWillChange]
public function count()
public function count(): int
{
return \count($this->packages);
}

View File

@ -103,11 +103,7 @@ class RuleSet implements \IteratorAggregate, \Countable
}
}
/**
* @return int
*/
#[\ReturnTypeWillChange]
public function count()
public function count(): int
{
return $this->nextRuleId;
}
@ -127,11 +123,7 @@ class RuleSet implements \IteratorAggregate, \Countable
return $this->rules;
}
/**
* @return RuleSetIterator
*/
#[\ReturnTypeWillChange]
public function getIterator()
public function getIterator(): RuleSetIterator
{
return new RuleSetIterator($this->getRules());
}

View File

@ -42,11 +42,7 @@ class RuleSetIterator implements \Iterator
$this->rewind();
}
/**
* @return Rule
*/
#[\ReturnTypeWillChange]
public function current()
public function current(): Rule
{
return $this->rules[$this->currentType][$this->currentOffset];
}
@ -54,17 +50,12 @@ class RuleSetIterator implements \Iterator
/**
* @return RuleSet::TYPE_*|-1
*/
#[\ReturnTypeWillChange]
public function key()
public function key(): int
{
return $this->currentType;
}
/**
* @return void
*/
#[\ReturnTypeWillChange]
public function next()
public function next(): void
{
$this->currentOffset++;
@ -88,11 +79,7 @@ class RuleSetIterator implements \Iterator
}
}
/**
* @return void
*/
#[\ReturnTypeWillChange]
public function rewind()
public function rewind(): void
{
$this->currentOffset = 0;
@ -111,11 +98,7 @@ class RuleSetIterator implements \Iterator
} while (isset($this->types[$this->currentTypeOffset]) && !\count($this->rules[$this->currentType]));
}
/**
* @return bool
*/
#[\ReturnTypeWillChange]
public function valid()
public function valid(): bool
{
return isset($this->rules[$this->currentType], $this->rules[$this->currentType][$this->currentOffset]);
}

View File

@ -159,74 +159,47 @@ abstract class BaseIO implements IOInterface
ProcessExecutor::setTimeout((int) $config->get('process-timeout'));
}
/**
* @return void
*/
public function emergency($message, array $context = array())
public function emergency($message, array $context = array()): void
{
$this->log(LogLevel::EMERGENCY, $message, $context);
}
/**
* @return void
*/
public function alert($message, array $context = array())
public function alert($message, array $context = array()): void
{
$this->log(LogLevel::ALERT, $message, $context);
}
/**
* @return void
*/
public function critical($message, array $context = array())
public function critical($message, array $context = array()): void
{
$this->log(LogLevel::CRITICAL, $message, $context);
}
/**
* @return void
*/
public function error($message, array $context = array())
public function error($message, array $context = array()): void
{
$this->log(LogLevel::ERROR, $message, $context);
}
/**
* @return void
*/
public function warning($message, array $context = array())
public function warning($message, array $context = array()): void
{
$this->log(LogLevel::WARNING, $message, $context);
}
/**
* @return void
*/
public function notice($message, array $context = array())
public function notice($message, array $context = array()): void
{
$this->log(LogLevel::NOTICE, $message, $context);
}
/**
* @return void
*/
public function info($message, array $context = array())
public function info($message, array $context = array()): void
{
$this->log(LogLevel::INFO, $message, $context);
}
/**
* @return void
*/
public function debug($message, array $context = array())
public function debug($message, array $context = array()): void
{
$this->log(LogLevel::DEBUG, $message, $context);
}
/**
* @return void
*/
public function log($level, $message, array $context = array())
public function log($level, $message, array $context = array()): void
{
if (in_array($level, array(LogLevel::EMERGENCY, LogLevel::ALERT, LogLevel::CRITICAL, LogLevel::ERROR))) {
$this->writeError('<error>'.$message.'</error>');

View File

@ -223,7 +223,7 @@ class InstallationManager
};
$handleInterruptsUnix = function_exists('pcntl_async_signals') && function_exists('pcntl_signal');
$handleInterruptsWindows = function_exists('sapi_windows_set_ctrl_handler') && PHP_SAPI === 'cli';
$handleInterruptsWindows = PHP_VERSION_ID >= 70400 && function_exists('sapi_windows_set_ctrl_handler') && PHP_SAPI === 'cli';
$prevHandler = null;
$windowsHandler = null;
if ($handleInterruptsUnix) {

View File

@ -23,8 +23,7 @@ class ArchivableFilesFilter extends FilterIterator
/**
* @return bool true if the current element is acceptable, otherwise false.
*/
#[\ReturnTypeWillChange]
public function accept()
public function accept(): bool
{
$file = $this->getInnerIterator()->current();
if ($file->isDir()) {

View File

@ -90,8 +90,7 @@ class ArchivableFilesFinder extends \FilterIterator
parent::__construct($this->finder->getIterator());
}
#[\ReturnTypeWillChange]
public function accept()
public function accept(): bool
{
/** @var SplFileInfo $current */
$current = $this->getInnerIterator()->current();

View File

@ -80,7 +80,7 @@ class Locker
*/
public static function getContentHash($composerFileContents)
{
$content = json_decode($composerFileContents, true);
$content = JsonFile::parseJson($composerFileContents, 'composer.json');
$relevantKeys = array(
'name',
@ -107,7 +107,7 @@ class Locker
ksort($relevantContent);
return md5(json_encode($relevantContent));
return md5(JsonFile::encode($relevantContent, 0));
}
/**

View File

@ -32,7 +32,7 @@ interface PluginInterface
*
* @var string
*/
const PLUGIN_API_VERSION = '2.2.0';
const PLUGIN_API_VERSION = '2.3.0';
/**
* Apply plugin modifications to Composer

View File

@ -322,8 +322,7 @@ class ArrayRepository implements RepositoryInterface
*
* @return int Number of packages
*/
#[\ReturnTypeWillChange]
public function count()
public function count(): int
{
if (null === $this->packages) {
$this->initialize();

View File

@ -178,8 +178,7 @@ class CompositeRepository implements RepositoryInterface
/**
* @inheritDoc
*/
#[\ReturnTypeWillChange]
public function count()
public function count(): int
{
$total = 0;
foreach ($this->repositories as $repository) {

View File

@ -181,8 +181,7 @@ class FilterRepository implements RepositoryInterface
/**
* @inheritDoc
*/
#[\ReturnTypeWillChange]
public function count()
public function count(): int
{
if ($this->repo->count() > 0) {
return count($this->getPackages());

View File

@ -54,15 +54,6 @@ class ErrorHandler
}
if (self::$io) {
// ignore symfony/* deprecation warnings
// TODO remove in 2.3
if (Preg::isMatch('{^Return type of Symfony\\\\.*ReturnTypeWillChange}is', $message)) {
return true;
}
if (strpos(strtr($file, '\\', '/'), 'vendor/symfony/') !== false) {
return true;
}
self::$io->writeError('<warning>Deprecation Notice: '.$message.' in '.$file.':'.$line.'</warning>');
if (self::$io->isVerbose()) {
self::$io->writeError('<warning>Stack trace:</warning>');

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

@ -98,9 +98,7 @@ class Perforce
*/
public static function checkServerExists($url, ProcessExecutor $processExecutor)
{
$output = null;
return 0 === $processExecutor->execute('p4 -p ' . ProcessExecutor::escape($url) . ' info -s', $output);
return 0 === $processExecutor->execute('p4 -p ' . ProcessExecutor::escape($url) . ' info -s', $ignoredOutput);
}
/**

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

@ -137,7 +137,11 @@ final class TlsHelper
*/
public static function getCertificateFingerprint($certificate)
{
$pubkeydetails = openssl_pkey_get_details(openssl_get_publickey($certificate));
$pubkey = openssl_get_publickey($certificate);
if ($pubkey === false) {
throw new \RuntimeException('Failed to retrieve the public key from certificate');
}
$pubkeydetails = openssl_pkey_get_details($pubkey);
$pubkeypem = $pubkeydetails['key'];
//Convert PEM to DER before SHA1'ing
$start = '-----BEGIN PUBLIC KEY-----';

View File

@ -31,15 +31,16 @@ class AllFunctionalTest extends TestCase
*/
private static $pharPath;
public function setUp()
public function setUp(): void
{
$this->oldcwd = getcwd();
chdir(__DIR__.'/Fixtures/functional');
}
public function tearDown()
protected function tearDown(): void
{
parent::tearDown();
if ($this->oldcwd) {
chdir($this->oldcwd);
}
@ -51,12 +52,12 @@ class AllFunctionalTest extends TestCase
}
}
public static function setUpBeforeClass()
public static function setUpBeforeClass(): void
{
self::$pharPath = self::getUniqueTmpDirectory() . '/composer.phar';
}
public static function tearDownAfterClass()
public static function tearDownAfterClass(): void
{
$fs = new Filesystem;
$fs->removeDirectory(dirname(self::$pharPath));
@ -123,18 +124,10 @@ class AllFunctionalTest extends TestCase
'COMPOSER_CACHE_DIR' => $this->testDir.'cache',
);
// TODO in v2.3 always call with an array
if (method_exists('Symfony\Component\Process\Process', 'fromShellCommandline')) {
$cmd = array((defined('PHP_BINARY') ? PHP_BINARY : 'php'), self::$pharPath, '--no-ansi', $testData['RUN']);
$proc = new Process($cmd, $this->testDir, $env, null, 300);
} else {
$cmd = (defined('PHP_BINARY') ? escapeshellcmd(PHP_BINARY) : 'php') .' '.escapeshellarg(self::$pharPath).' --no-ansi '.$testData['RUN'];
// @phpstan-ignore-next-line
$proc = new Process($cmd, $this->testDir, $env, null, 300);
}
$proc = Process::fromShellCommandline(escapeshellcmd(PHP_BINARY).' '.escapeshellarg(self::$pharPath).' --no-ansi '.$testData['RUN'], $this->testDir, $env, null, 300);
$output = '';
$exitcode = $proc->run(function ($type, $buffer) use (&$output) {
$exitCode = $proc->run(function ($type, $buffer) use (&$output) {
$output .= $buffer;
});
@ -176,16 +169,16 @@ class AllFunctionalTest extends TestCase
}
}
if (isset($testData['EXPECT-REGEX'])) {
$this->assertRegExp($testData['EXPECT-REGEX'], $this->cleanOutput($output));
$this->assertMatchesRegularExpression($testData['EXPECT-REGEX'], $this->cleanOutput($output));
}
if (isset($testData['EXPECT-REGEXES'])) {
$cleanOutput = $this->cleanOutput($output);
foreach (explode("\n", $testData['EXPECT-REGEXES']) as $regex) {
$this->assertRegExp($regex, $cleanOutput, 'Output: '.$output);
$this->assertMatchesRegularExpression($regex, $cleanOutput, 'Output: '.$output);
}
}
if (isset($testData['EXPECT-EXIT-CODE'])) {
$this->assertSame($testData['EXPECT-EXIT-CODE'], $exitcode);
$this->assertSame($testData['EXPECT-EXIT-CODE'], $exitCode);
}
}
@ -204,7 +197,7 @@ class AllFunctionalTest extends TestCase
/**
* @param string $file
* @return array<string, int|string>
* @return array{RUN: string, EXPECT?: string, EXPECT-EXIT-CODE?: int, EXPECT-REGEX?: string, EXPECT-REGEXES?: string, TEST?: string}
*/
private function parseTestFile($file)
{
@ -261,7 +254,7 @@ class AllFunctionalTest extends TestCase
throw new \RuntimeException('The test file must have a section named "EXPECT", "EXPECT-REGEX", or "EXPECT-REGEXES".');
}
return $data;
return $data; // @phpstan-ignore-line
}
/**

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()
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

@ -29,7 +29,7 @@ use Composer\Installer\InstallationManager;
use Composer\Config;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Util\Platform;
use PHPUnit_Framework_MockObject_MockObject as MockObject;
use PHPUnit\Framework\MockObject\MockObject;
class AutoloadGeneratorTest extends TestCase
{
@ -54,12 +54,12 @@ class AutoloadGeneratorTest extends TestCase
private $origDir;
/**
* @var InstallationManager|MockObject
* @var InstallationManager&MockObject
*/
private $im;
/**
* @var InstalledRepositoryInterface|MockObject
* @var InstalledRepositoryInterface&MockObject
*/
private $repository;
@ -74,7 +74,7 @@ class AutoloadGeneratorTest extends TestCase
private $fs;
/**
* @var EventDispatcher|MockObject
* @var EventDispatcher&MockObject
*/
private $eventDispatcher;
@ -89,7 +89,7 @@ class AutoloadGeneratorTest extends TestCase
*/
public $configValueMap;
protected function setUp()
protected function setUp(): void
{
$this->fs = new Filesystem;
$that = $this;
@ -148,8 +148,9 @@ class AutoloadGeneratorTest extends TestCase
$this->generator = new AutoloadGenerator($this->eventDispatcher);
}
protected function tearDown()
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/')));
@ -1866,38 +1861,16 @@ EOF;
/**
* @param string $expected
* @param string $actual
* @param string $message
* @param bool $canonicalize
* @param bool $ignoreCase
* @param string|null $message
*
* @return void
*/
public static function assertFileContentEquals($expected, $actual, $message = '', $canonicalize = false, $ignoreCase = false)
public static function assertFileContentEquals(string $expected, string $actual, ?string $message = null)
{
self::assertEqualsNormalized(
file_get_contents($expected),
file_get_contents($actual),
$message ?: $expected.' equals '.$actual,
0,
10,
$canonicalize,
$ignoreCase
self::assertSame(
str_replace("\r", '', (string) file_get_contents($expected)),
str_replace("\r", '', (string) file_get_contents($actual)),
$message ?? $expected.' equals '.$actual
);
}
/**
* @param string $expected
* @param string $actual
* @param string $message
* @param int $delta
* @param int $maxDepth
* @param bool $canonicalize
* @param bool $ignoreCase
*
* @return void
*/
public static function assertEqualsNormalized($expected, $actual, $message = '', $delta = 0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false)
{
parent::assertEquals(str_replace("\r", '', $expected), str_replace("\r", '', $actual), $message, $delta, $maxDepth, $canonicalize, $ignoreCase);
}
}

View File

@ -146,7 +146,8 @@ class ClassMapGeneratorTest extends TestCase
$find = $r->getMethod('findClasses');
$find->setAccessible(true);
$this->setExpectedException('RuntimeException', 'does not exist');
self::expectException('RuntimeException');
self::expectExceptionMessage('does not exist');
$find->invoke(null, __DIR__ . '/no-file');
}
@ -232,7 +233,8 @@ class ClassMapGeneratorTest extends TestCase
public function testCreateMapThrowsWhenDirectoryDoesNotExist()
{
$this->setExpectedException('RuntimeException', 'Could not scan for classes inside');
self::expectException('RuntimeException');
self::expectExceptionMessage('Could not scan for classes inside');
ClassMapGenerator::createMap(__DIR__ . '/no-file.no-foler');
}

View File

@ -28,7 +28,7 @@ class CacheTest extends TestCase
/** @var Cache&\PHPUnit\Framework\MockObject\MockObject */
private $cache;
public function setUp()
public function setUp(): void
{
$this->root = $this->getUniqueTmpDirectory();
$this->files = array();
@ -44,7 +44,7 @@ class CacheTest extends TestCase
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$this->cache = $this->getMockBuilder('Composer\Cache')
->setMethods(array('getFinder'))
->onlyMethods(array('getFinder'))
->setConstructorArgs(array($io, $this->root))
->getMock();
$this->cache
@ -53,8 +53,9 @@ class CacheTest extends TestCase
->will($this->returnValue($this->finder));
}
protected function tearDown()
protected function tearDown(): void
{
parent::tearDown();
if (is_dir($this->root)) {
$fs = new Filesystem;
$fs->removeDirectory($this->root);

View File

@ -49,17 +49,14 @@ class ArchiveCommandTest extends TestCase
$composer->setPackage($package);
$command = $this->getMockBuilder('Composer\Command\ArchiveCommand')
->setMethods(array(
->onlyMethods(array(
'mergeApplicationDefinition',
'bind',
'getSynopsis',
'initialize',
'isInteractive',
'getComposer',
))->getMock();
$command->expects($this->atLeastOnce())->method('getComposer')
->willReturn($composer);
$command->method('isInteractive')->willReturn(false);
$command->run($input, $output);
}
@ -73,12 +70,10 @@ class ArchiveCommandTest extends TestCase
$config = Factory::createConfig();
$command = $this->getMockBuilder('Composer\Command\ArchiveCommand')
->setMethods(array(
->onlyMethods(array(
'mergeApplicationDefinition',
'bind',
'getSynopsis',
'initialize',
'isInteractive',
'getComposer',
'archive',
))->getMock();
@ -96,7 +91,6 @@ class ArchiveCommandTest extends TestCase
false,
null
)->willReturn(0);
$command->method('isInteractive')->willReturn(false);
$this->assertEquals(0, $command->run($input, $output));
}

View File

@ -82,14 +82,14 @@ class InitCommandTest extends TestCase
public function testParseEmptyAuthorString()
{
$command = new InitCommand;
$this->setExpectedException('InvalidArgumentException');
self::expectException('InvalidArgumentException');
$command->parseAuthorString('');
}
public function testParseAuthorStringWithInvalidEmail()
{
$command = new InitCommand;
$this->setExpectedException('InvalidArgumentException');
self::expectException('InvalidArgumentException');
$command->parseAuthorString('John Smith <john>');
}

View File

@ -47,6 +47,9 @@ class RunScriptCommandTest extends TestCase
->method('hasArgument')
->with('command')
->willReturn(false);
$input
->method('isInteractive')
->willReturn(false);
$output = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock();
@ -73,17 +76,14 @@ class RunScriptCommandTest extends TestCase
$composer->setEventDispatcher($ed);
$command = $this->getMockBuilder('Composer\Command\RunScriptCommand')
->setMethods(array(
->onlyMethods(array(
'mergeApplicationDefinition',
'bind',
'getSynopsis',
'initialize',
'isInteractive',
'getComposer',
))
->getMock();
$command->expects($this->any())->method('getComposer')->willReturn($composer);
$command->method('isInteractive')->willReturn(false);
$command->run($input, $output);
}

View File

@ -34,14 +34,15 @@ class JsonConfigSourceTest extends TestCase
return __DIR__.'/Fixtures/'.$name;
}
protected function setUp()
protected function setUp(): void
{
$this->fs = new Filesystem;
$this->workingDir = $this->getUniqueTmpDirectory();
}
protected function tearDown()
protected function tearDown(): void
{
parent::tearDown();
if (is_dir($this->workingDir)) {
$this->fs->removeDirectory($this->workingDir);
}

View File

@ -259,10 +259,8 @@ class ConfigTest extends TestCase
*/
public function testProhibitedUrlsThrowException($url)
{
$this->setExpectedException(
'Composer\Downloader\TransportException',
'Your configuration does not allow connections to ' . $url
);
self::expectException('Composer\Downloader\TransportException');
self::expectExceptionMessage('Your configuration does not allow connections to ' . $url);
$config = new Config(false);
$config->prohibitUrlByConfig($url);
}

View File

@ -32,7 +32,7 @@ class DefaultPolicyTest extends TestCase
/** @var DefaultPolicy */
protected $policy;
public function setUp()
public function setUp(): void
{
$this->repositorySet = new RepositorySet('dev');
$this->repo = new ArrayRepository;

View File

@ -27,7 +27,7 @@ class RuleSetIteratorTest extends TestCase
/** @var Pool */
protected $pool;
protected function setUp()
protected function setUp(): void
{
$this->pool = new Pool();

View File

@ -67,7 +67,7 @@ class RuleSetTest extends TestCase
{
$ruleSet = new RuleSet;
$this->setExpectedException('OutOfBoundsException');
self::expectException('OutOfBoundsException');
// @phpstan-ignore-next-line
$ruleSet->add(new GenericRule(array(), Rule::RULE_ROOT_REQUIRE, array('packageName' => '', 'constraint' => new MatchAllConstraint)), 7);
}

View File

@ -48,7 +48,7 @@ class SolverTest extends TestCase
/** @var Pool */
protected $pool;
public function setUp()
public function setUp(): void
{
$this->repoSet = new RepositorySet();
$this->repo = new ArrayRepository;
@ -537,7 +537,7 @@ class SolverTest extends TestCase
$this->request->requireName('A');
// must explicitly pick the provider, so error in this case
$this->setExpectedException('Composer\DependencyResolver\SolverProblemsException');
self::expectException('Composer\DependencyResolver\SolverProblemsException');
$this->createSolver();
$this->solver->solve($this->request);
}
@ -571,7 +571,7 @@ class SolverTest extends TestCase
$this->request->requireName('A');
$this->setExpectedException('Composer\DependencyResolver\SolverProblemsException');
self::expectException('Composer\DependencyResolver\SolverProblemsException');
$this->createSolver();
$this->solver->solve($this->request);
}
@ -743,7 +743,7 @@ class SolverTest extends TestCase
$this->request->requireName('C', $this->getVersionConstraint('==', '2.0.0.0-dev'));
$this->setExpectedException('Composer\DependencyResolver\SolverProblemsException');
self::expectException('Composer\DependencyResolver\SolverProblemsException');
$this->createSolver();
$this->solver->solve($this->request);

View File

@ -23,7 +23,7 @@ use Composer\Test\TestCase;
class TransactionTest extends TestCase
{
public function setUp()
public function setUp(): void
{
}

View File

@ -13,6 +13,7 @@
namespace Composer\Test\Downloader;
use Composer\Downloader\DownloadManager;
use Composer\Package\PackageInterface;
use Composer\Test\TestCase;
class DownloadManagerTest extends TestCase
@ -23,7 +24,7 @@ class DownloadManagerTest extends TestCase
/** @var \Composer\IO\IOInterface&\PHPUnit\Framework\MockObject\MockObject */
protected $io;
public function setUp()
public function setUp(): void
{
$this->filesystem = $this->getMockBuilder('Composer\Util\Filesystem')->getMock();
$this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
@ -37,7 +38,7 @@ class DownloadManagerTest extends TestCase
$manager->setDownloader('test', $downloader);
$this->assertSame($downloader, $manager->getDownloader('test'));
$this->setExpectedException('InvalidArgumentException');
self::expectException('InvalidArgumentException');
$manager->getDownloader('unregistered');
}
@ -51,7 +52,7 @@ class DownloadManagerTest extends TestCase
$manager = new DownloadManager($this->io, false, $this->filesystem);
$this->setExpectedException('InvalidArgumentException');
self::expectException('InvalidArgumentException');
$manager->getDownloaderForPackage($package);
}
@ -76,7 +77,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloader'))
->onlyMethods(array('getDownloader'))
->getMock();
$manager
@ -108,7 +109,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloader'))
->onlyMethods(array('getDownloader'))
->getMock();
$manager
@ -117,7 +118,7 @@ class DownloadManagerTest extends TestCase
->with('git')
->will($this->returnValue($downloader));
$this->setExpectedException('LogicException');
self::expectException('LogicException');
$manager->getDownloaderForPackage($package);
}
@ -142,7 +143,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloader'))
->onlyMethods(array('getDownloader'))
->getMock();
$manager
@ -174,7 +175,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloader'))
->onlyMethods(array('getDownloader'))
->getMock();
$manager
@ -183,7 +184,7 @@ class DownloadManagerTest extends TestCase
->with('pear')
->will($this->returnValue($downloader));
$this->setExpectedException('LogicException');
self::expectException('LogicException');
$manager->getDownloaderForPackage($package);
}
@ -226,7 +227,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloaderForPackage'))
->onlyMethods(array('getDownloaderForPackage'))
->getMock();
$manager
->expects($this->once())
@ -254,13 +255,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
@ -277,18 +277,16 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloaderForPackage'))
->onlyMethods(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');
}
@ -307,7 +305,7 @@ class DownloadManagerTest extends TestCase
$manager = new DownloadManager($this->io, false, $this->filesystem);
$this->setExpectedException('InvalidArgumentException');
self::expectException('InvalidArgumentException');
$manager->download($package, 'target_dir');
}
@ -336,7 +334,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloaderForPackage'))
->onlyMethods(array('getDownloaderForPackage'))
->getMock();
$manager
->expects($this->once())
@ -372,7 +370,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloaderForPackage'))
->onlyMethods(array('getDownloaderForPackage'))
->getMock();
$manager
->expects($this->once())
@ -402,7 +400,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloaderForPackage'))
->onlyMethods(array('getDownloaderForPackage'))
->getMock();
$manager
->expects($this->once())
@ -438,7 +436,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloaderForPackage'))
->onlyMethods(array('getDownloaderForPackage'))
->getMock();
$manager
->expects($this->once())
@ -475,7 +473,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloaderForPackage'))
->onlyMethods(array('getDownloaderForPackage'))
->getMock();
$manager
->expects($this->once())
@ -512,7 +510,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloaderForPackage'))
->onlyMethods(array('getDownloaderForPackage'))
->getMock();
$manager
->expects($this->once())
@ -539,7 +537,7 @@ class DownloadManagerTest extends TestCase
$manager = new DownloadManager($this->io, false, $this->filesystem);
$manager->setPreferSource(true);
$this->setExpectedException('InvalidArgumentException');
self::expectException('InvalidArgumentException');
$manager->download($package, 'target_dir');
}
@ -642,20 +640,30 @@ class DownloadManagerTest extends TestCase
{
$initial = null;
if ($prevPkgSource) {
$initial = $this->prophesize('Composer\Package\PackageInterface');
$initial->getInstallationSource()->willReturn($prevPkgSource);
$initial->isDev()->willReturn($prevPkgIsDev);
$initial = $this->getMockBuilder(PackageInterface::class)->getMock();
$initial->expects($this->atLeastOnce())
->method('getInstallationSource')
->willReturn($prevPkgSource);
$initial->expects($this->any())
->method('isDev')
->willReturn($prevPkgIsDev);
}
$target = $this->prophesize('Composer\Package\PackageInterface');
$target->getSourceType()->willReturn(in_array('source', $targetAvailable, true) ? 'git' : null);
$target->getDistType()->willReturn(in_array('dist', $targetAvailable, true) ? 'zip' : null);
$target->isDev()->willReturn($targetIsDev);
$target = $this->getMockBuilder(PackageInterface::class)->getMock();
$target->expects($this->atLeastOnce())
->method('getSourceType')
->willReturn(in_array('source', $targetAvailable, true) ? 'git' : null);
$target->expects($this->atLeastOnce())
->method('getDistType')
->willReturn(in_array('dist', $targetAvailable, true) ? 'zip' : null);
$target->expects($this->any())
->method('isDev')
->willReturn($targetIsDev);
$manager = new DownloadManager($this->io, false, $this->filesystem);
$method = new \ReflectionMethod($manager, 'getAvailableSources');
$method->setAccessible(true);
$this->assertEquals($expected, $method->invoke($manager, $target->reveal(), $initial ? $initial->reveal() : null));
$this->assertEquals($expected, $method->invoke($manager, $target, $initial ?? null));
}
public static function updatesProvider()
@ -688,7 +696,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloaderForPackage'))
->onlyMethods(array('getDownloaderForPackage'))
->getMock();
$manager
->expects($this->exactly(2))
@ -711,7 +719,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloaderForPackage'))
->onlyMethods(array('getDownloaderForPackage'))
->getMock();
$manager
->expects($this->once())
@ -728,7 +736,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloaderForPackage'))
->onlyMethods(array('getDownloaderForPackage'))
->getMock();
$manager
->expects($this->once())
@ -771,7 +779,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloaderForPackage'))
->onlyMethods(array('getDownloaderForPackage'))
->getMock();
$manager
->expects($this->once())
@ -814,7 +822,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloaderForPackage'))
->onlyMethods(array('getDownloaderForPackage'))
->getMock();
$manager
->expects($this->once())
@ -860,7 +868,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloaderForPackage'))
->onlyMethods(array('getDownloaderForPackage'))
->getMock();
$manager
->expects($this->once())
@ -907,7 +915,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloaderForPackage'))
->onlyMethods(array('getDownloaderForPackage'))
->getMock();
$manager
->expects($this->once())
@ -954,7 +962,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloaderForPackage'))
->onlyMethods(array('getDownloaderForPackage'))
->getMock();
$manager
->expects($this->once())
@ -1001,7 +1009,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloaderForPackage'))
->onlyMethods(array('getDownloaderForPackage'))
->getMock();
$manager
->expects($this->once())
@ -1044,7 +1052,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloaderForPackage'))
->onlyMethods(array('getDownloaderForPackage'))
->getMock();
$manager
->expects($this->once())
@ -1087,7 +1095,7 @@ class DownloadManagerTest extends TestCase
$manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')
->setConstructorArgs(array($this->io, false, $this->filesystem))
->setMethods(array('getDownloaderForPackage'))
->onlyMethods(array('getDownloaderForPackage'))
->getMock();
$manager
->expects($this->once())

View File

@ -30,7 +30,7 @@ class FileDownloaderTest extends TestCase
/** @var \Composer\Config&\PHPUnit\Framework\MockObject\MockObject */
private $config;
public function setUp()
public function setUp(): void
{
$this->httpDownloader = $this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock();
$this->config = $this->getMockBuilder('Composer\Config')->getMock();
@ -67,7 +67,7 @@ class FileDownloaderTest extends TestCase
->will($this->returnValue(null))
;
$this->setExpectedException('InvalidArgumentException');
self::expectException('InvalidArgumentException');
$downloader = $this->getDownloader();
$downloader->download($packageMock, '/path');
@ -85,7 +85,7 @@ class FileDownloaderTest extends TestCase
->will($this->returnValue(array('url')))
;
$path = tempnam($this->getUniqueTmpDirectory(), 'c');
$path = $this->createTempFile($this->getUniqueTmpDirectory());
$downloader = $this->getDownloader();
try {
@ -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

@ -22,13 +22,14 @@ class FossilDownloaderTest extends TestCase
/** @var string */
private $workingDir;
protected function setUp()
protected function setUp(): void
{
$this->workingDir = $this->getUniqueTmpDirectory();
}
protected function tearDown()
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);
@ -59,7 +60,7 @@ class FossilDownloaderTest extends TestCase
->method('getSourceReference')
->will($this->returnValue(null));
$this->setExpectedException('InvalidArgumentException');
self::expectException('InvalidArgumentException');
$downloader = $this->getDownloaderMock();
$downloader->install($packageMock, '/path');
@ -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()
@ -96,7 +95,7 @@ class FossilDownloaderTest extends TestCase
->method('getSourceReference')
->will($this->returnValue(null));
$this->setExpectedException('InvalidArgumentException');
self::expectException('InvalidArgumentException');
$downloader = $this->getDownloaderMock();
$downloader->prepare('update', $sourcePackageMock, '/path', $initialPackageMock);
@ -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

@ -27,7 +27,7 @@ class GitDownloaderTest extends TestCase
/** @var string */
private $workingDir;
protected function setUp()
protected function setUp(): void
{
$this->skipIfNotExecutable('git');
@ -37,8 +37,9 @@ class GitDownloaderTest extends TestCase
$this->workingDir = $this->getUniqueTmpDirectory();
}
protected function tearDown()
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);
@ -99,7 +100,7 @@ class GitDownloaderTest extends TestCase
->method('getSourceReference')
->will($this->returnValue(null));
$this->setExpectedException('InvalidArgumentException');
self::expectException('InvalidArgumentException');
$downloader = $this->getDownloaderMock();
$downloader->download($packageMock, '/path');
@ -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)) {
@ -331,7 +322,7 @@ class GitDownloaderTest extends TestCase
->method('getSourceReference')
->will($this->returnValue(null));
$this->setExpectedException('InvalidArgumentException');
self::expectException('InvalidArgumentException');
$downloader = $this->getDownloaderMock();
$downloader->download($sourcePackageMock, '/path', $initialPackageMock);
@ -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

@ -22,13 +22,14 @@ class HgDownloaderTest extends TestCase
/** @var string */
private $workingDir;
protected function setUp()
protected function setUp(): void
{
$this->workingDir = $this->getUniqueTmpDirectory();
}
protected function tearDown()
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);
@ -59,7 +60,7 @@ class HgDownloaderTest extends TestCase
->method('getSourceReference')
->will($this->returnValue(null));
$this->setExpectedException('InvalidArgumentException');
self::expectException('InvalidArgumentException');
$downloader = $this->getDownloaderMock();
$downloader->install($packageMock, '/path');
@ -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()
@ -95,7 +94,7 @@ class HgDownloaderTest extends TestCase
->method('getSourceReference')
->will($this->returnValue(null));
$this->setExpectedException('InvalidArgumentException');
self::expectException('InvalidArgumentException');
$downloader = $this->getDownloaderMock();
$downloader->prepare('update', $sourcePackageMock, '/path', $initialPackageMock);
@ -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

@ -43,13 +43,13 @@ class PerforceDownloaderTest extends TestCase
/** @var string */
protected $testPath;
protected function setUp()
protected function setUp(): void
{
$this->testPath = $this->getUniqueTmpDirectory();
$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);
@ -103,7 +103,7 @@ class PerforceDownloaderTest extends TestCase
protected function getMockRepository(array $repoConfig, IOInterface $io, Config $config)
{
$repository = $this->getMockBuilder('Composer\Repository\VcsRepository')
->setMethods(array('getRepoConfig'))
->onlyMethods(array('getRepoConfig'))
->setConstructorArgs(array($repoConfig, $io, $config, Factory::createHttpDownloader($io, $config)))
->getMock();
$repository->expects($this->any())->method('getRepoConfig')->will($this->returnValue($repoConfig));
@ -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

@ -31,7 +31,7 @@ class XzDownloaderTest extends TestCase
*/
private $testDir;
public function setUp()
public function setUp(): void
{
if (Platform::isWindows()) {
$this->markTestSkipped('Skip test on Windows');
@ -39,8 +39,12 @@ class XzDownloaderTest extends TestCase
$this->testDir = $this->getUniqueTmpDirectory();
}
public function tearDown()
protected function tearDown(): void
{
if (Platform::isWindows()) {
return;
}
parent::tearDown();
$this->fs = new Filesystem;
$this->fs->removeDirectory($this->testDir);
}

View File

@ -32,7 +32,7 @@ class ZipDownloaderTest extends TestCase
/** @var \Composer\Package\PackageInterface&\PHPUnit\Framework\MockObject\MockObject */
private $package;
public function setUp()
public function setUp(): void
{
$this->testDir = $this->getUniqueTmpDirectory();
$this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
@ -42,8 +42,9 @@ class ZipDownloaderTest extends TestCase
$this->package = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
}
public function tearDown()
protected function tearDown(): void
{
parent::tearDown();
$fs = new Filesystem;
$fs->removeDirectory($this->testDir);
$this->setPrivateProperty('hasZipArchive', null);
@ -107,7 +108,8 @@ class ZipDownloaderTest extends TestCase
public function testZipArchiveOnlyFailed()
{
$this->setExpectedException('RuntimeException', 'There was an error extracting the ZIP file');
self::expectException('RuntimeException');
self::expectExceptionMessage('There was an error extracting the ZIP file');
if (!class_exists('ZipArchive')) {
$this->markTestSkipped('zip extension missing');
}
@ -115,10 +117,10 @@ class ZipDownloaderTest extends TestCase
$this->setPrivateProperty('hasZipArchive', true);
$downloader = new MockedZipDownloader($this->io, $this->config, $this->httpDownloader);
$zipArchive = $this->getMockBuilder('ZipArchive')->getMock();
$zipArchive->expects($this->at(0))
$zipArchive->expects($this->once())
->method('open')
->will($this->returnValue(true));
$zipArchive->expects($this->at(1))
$zipArchive->expects($this->once())
->method('extractTo')
->will($this->returnValue(false));
@ -129,7 +131,8 @@ class ZipDownloaderTest extends TestCase
public function testZipArchiveExtractOnlyFailed()
{
$this->setExpectedException('RuntimeException', 'The archive may contain identical file names with different capitalization (which fails on case insensitive filesystems): Not a directory');
self::expectException('RuntimeException');
self::expectExceptionMessage('The archive may contain identical file names with different capitalization (which fails on case insensitive filesystems): Not a directory');
if (!class_exists('ZipArchive')) {
$this->markTestSkipped('zip extension missing');
}
@ -137,10 +140,10 @@ class ZipDownloaderTest extends TestCase
$this->setPrivateProperty('hasZipArchive', true);
$downloader = new MockedZipDownloader($this->io, $this->config, $this->httpDownloader);
$zipArchive = $this->getMockBuilder('ZipArchive')->getMock();
$zipArchive->expects($this->at(0))
$zipArchive->expects($this->once())
->method('open')
->will($this->returnValue(true));
$zipArchive->expects($this->at(1))
$zipArchive->expects($this->once())
->method('extractTo')
->will($this->throwException(new \ErrorException('Not a directory')));
@ -158,10 +161,10 @@ class ZipDownloaderTest extends TestCase
$this->setPrivateProperty('hasZipArchive', true);
$downloader = new MockedZipDownloader($this->io, $this->config, $this->httpDownloader);
$zipArchive = $this->getMockBuilder('ZipArchive')->getMock();
$zipArchive->expects($this->at(0))
$zipArchive->expects($this->once())
->method('open')
->will($this->returnValue(true));
$zipArchive->expects($this->at(1))
$zipArchive->expects($this->once())
->method('extractTo')
->will($this->returnValue(true));
@ -172,7 +175,8 @@ class ZipDownloaderTest extends TestCase
public function testSystemUnzipOnlyFailed()
{
$this->setExpectedException('Exception', 'Failed to extract : (1) unzip');
self::expectException('Exception');
self::expectExceptionMessage('Failed to extract : (1) unzip');
$this->setPrivateProperty('isWindows', false);
$this->setPrivateProperty('hasZipArchive', false);
$this->setPrivateProperty('unzipCommands', array(array('unzip', 'unzip -qq %s -d %s')));
@ -189,7 +193,7 @@ class ZipDownloaderTest extends TestCase
->will($this->returnValue('output'));
$processExecutor = $this->getMockBuilder('Composer\Util\ProcessExecutor')->getMock();
$processExecutor->expects($this->at(0))
$processExecutor->expects($this->once())
->method('executeAsync')
->will($this->returnValue(\React\Promise\resolve($procMock)));
@ -216,7 +220,7 @@ class ZipDownloaderTest extends TestCase
->will($this->returnValue('output'));
$processExecutor = $this->getMockBuilder('Composer\Util\ProcessExecutor')->getMock();
$processExecutor->expects($this->at(0))
$processExecutor->expects($this->once())
->method('executeAsync')
->will($this->returnValue(\React\Promise\resolve($procMock)));
@ -246,15 +250,15 @@ class ZipDownloaderTest extends TestCase
->will($this->returnValue('output'));
$processExecutor = $this->getMockBuilder('Composer\Util\ProcessExecutor')->getMock();
$processExecutor->expects($this->at(0))
$processExecutor->expects($this->once())
->method('executeAsync')
->will($this->returnValue(\React\Promise\resolve($procMock)));
$zipArchive = $this->getMockBuilder('ZipArchive')->getMock();
$zipArchive->expects($this->at(0))
$zipArchive->expects($this->once())
->method('open')
->will($this->returnValue(true));
$zipArchive->expects($this->at(1))
$zipArchive->expects($this->once())
->method('extractTo')
->will($this->returnValue(true));
@ -266,7 +270,8 @@ class ZipDownloaderTest extends TestCase
public function testNonWindowsFallbackFailed()
{
$this->setExpectedException('Exception', 'There was an error extracting the ZIP file');
self::expectException('Exception');
self::expectExceptionMessage('There was an error extracting the ZIP file');
if (!class_exists('ZipArchive')) {
$this->markTestSkipped('zip extension missing');
}
@ -286,15 +291,15 @@ class ZipDownloaderTest extends TestCase
->will($this->returnValue('output'));
$processExecutor = $this->getMockBuilder('Composer\Util\ProcessExecutor')->getMock();
$processExecutor->expects($this->at(0))
$processExecutor->expects($this->once())
->method('executeAsync')
->will($this->returnValue(\React\Promise\resolve($procMock)));
$zipArchive = $this->getMockBuilder('ZipArchive')->getMock();
$zipArchive->expects($this->at(0))
$zipArchive->expects($this->once())
->method('open')
->will($this->returnValue(true));
$zipArchive->expects($this->at(1))
$zipArchive->expects($this->once())
->method('extractTo')
->will($this->returnValue(false));

View File

@ -31,24 +31,23 @@ class EventDispatcherTest extends TestCase
{
public function testListenerExceptionsAreCaught()
{
$this->setExpectedException('RuntimeException');
self::expectException('RuntimeException');
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
$dispatcher = $this->getDispatcherStubForListenersTest(array(
'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);
@ -71,7 +70,7 @@ class EventDispatcherTest extends TestCase
$this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
$process,
))
->setMethods(array('getListeners'))
->onlyMethods(array('getListeners'))
->getMock();
$listener = array($command);
@ -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')
@ -139,7 +136,7 @@ class EventDispatcherTest extends TestCase
{
$generator = $this->getMockBuilder('Composer\Autoload\AutoloadGenerator')
->disableOriginalConstructor()
->setMethods(array(
->onlyMethods(array(
'buildPackageMap',
'parseAutoloads',
'createLoader',
@ -166,7 +163,7 @@ class EventDispatcherTest extends TestCase
{
$rm = $this->getMockBuilder('Composer\Repository\RepositoryManager')
->disableOriginalConstructor()
->setMethods(array('getLocalRepository'))
->onlyMethods(array('getLocalRepository'))
->getMock();
$repo = $this->getMockBuilder('Composer\Repository\InstalledRepositoryInterface')->getMock();
@ -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',
@ -238,7 +235,7 @@ class EventDispatcherTest extends TestCase
$io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE),
$process,
))
->setMethods(array(
->onlyMethods(array(
'getListeners',
))
->getMock();
@ -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,9 +264,9 @@ class EventDispatcherTest extends TestCase
->setConstructorArgs(array(
$this->createComposerInstance(),
$io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE),
new ProcessExecutorMock,
$this->getProcessExecutorMock(),
))
->setMethods(array(
->onlyMethods(array(
'getListeners',
))
->getMock();
@ -302,8 +297,8 @@ class EventDispatcherTest extends TestCase
$dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->setConstructorArgs(array(
$this->createComposerInstance(),
$io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE),
new ProcessExecutorMock,
))->setMethods(array(
$this->getProcessExecutorMock(),
))->onlyMethods(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',
@ -381,7 +376,7 @@ class EventDispatcherTest extends TestCase
$io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE),
$process,
))
->setMethods(array(
->onlyMethods(array(
'getListeners',
))
->getMock();
@ -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);
@ -428,7 +421,7 @@ class EventDispatcherTest extends TestCase
$io = new BufferIO('', OutputInterface::VERBOSITY_VERBOSE),
$process,
))
->setMethods(array(
->onlyMethods(array(
'getListeners',
))
->getMock();
@ -452,21 +445,19 @@ class EventDispatcherTest extends TestCase
"> hello: echo Hello " .$this->getCmd("'World'").PHP_EOL;
$this->assertEquals($expected, $io->getOutput());
$process->assertComplete($this);
}
public function testDispatcherDetectInfiniteRecursion()
{
$this->setExpectedException('RuntimeException');
self::expectException('RuntimeException');
$dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')
->setConstructorArgs(array(
$composer = $this->createComposerInstance(),
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
new ProcessExecutorMock,
$this->getProcessExecutorMock(),
))
->setMethods(array(
->onlyMethods(array(
'getListeners',
))
->getMock();
@ -500,7 +491,7 @@ class EventDispatcherTest extends TestCase
$this->createComposerInstance(),
$io,
))
->setMethods(array('getListeners'))
->onlyMethods(array('getListeners'))
->getMock();
$dispatcher->expects($this->atLeastOnce())
@ -527,7 +518,7 @@ class EventDispatcherTest extends TestCase
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
new ProcessExecutor($io),
))
->setMethods(array('getListeners'))
->onlyMethods(array('getListeners'))
->getMock();
$listener = array('echo foo');
@ -554,7 +545,7 @@ class EventDispatcherTest extends TestCase
$io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
new ProcessExecutor,
))
->setMethods(array('getListeners'))
->onlyMethods(array('getListeners'))
->getMock();
$code = 'exit 1';
@ -563,23 +554,22 @@ 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');
self::expectException('RuntimeException');
$dispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, false);
}
@ -589,9 +579,9 @@ class EventDispatcherTest extends TestCase
->setConstructorArgs(array(
$this->createComposerInstance(),
$this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
new ProcessExecutorMock,
$this->getProcessExecutorMock(),
))
->setMethods(array('getListeners'))
->onlyMethods(array('getListeners'))
->getMock();
$dispatcher->expects($this->atLeastOnce())

View File

@ -32,7 +32,8 @@ final class PlatformRequirementFilterFactoryTest extends TestCase
public function testFromBoolThrowsExceptionIfTypeIsUnknown()
{
$this->setExpectedException('InvalidArgumentException', 'PlatformRequirementFilter: Unknown $boolOrList parameter NULL. Please report at https://github.com/composer/composer/issues/new.');
self::expectException('InvalidArgumentException');
self::expectExceptionMessage('PlatformRequirementFilter: Unknown $boolOrList parameter NULL. Please report at https://github.com/composer/composer/issues/new.');
PlatformRequirementFilterFactory::fromBoolOrList(null);
}

View File

@ -8,7 +8,7 @@ Checks that package versions in InstalledVersions are correct on initial install
update
--EXPECT--
> Hooks::preUpdate
!!PreUpdate:["composer/ca-bundle","composer/composer","composer/metadata-minifier","composer/pcre","composer/semver","composer/spdx-licenses","composer/xdebug-handler","justinrainbow/json-schema","psr/log","react/promise","seld/jsonlint","seld/phar-utils","symfony/console","symfony/debug","symfony/filesystem","symfony/finder","symfony/polyfill-ctype","symfony/polyfill-mbstring","symfony/process"]
!!PreUpdate:["composer/ca-bundle","composer/composer","composer/metadata-minifier","composer/pcre","composer/semver","composer/spdx-licenses","composer/xdebug-handler","justinrainbow/json-schema","psr/container","psr/log","psr/log-implementation","react/promise","seld/jsonlint","seld/phar-utils","symfony/console","symfony/deprecation-contracts","symfony/filesystem","symfony/finder","symfony/polyfill-ctype","symfony/polyfill-intl-grapheme","symfony/polyfill-intl-normalizer","symfony/polyfill-mbstring","symfony/polyfill-php73","symfony/polyfill-php80","symfony/process","symfony/service-contracts","symfony/string"]
!!Versions:console:%[2-8]\.\d+\.\d+.0%;process:%[2-8]\.\d+\.\d+.0%;filesystem:%[2-8]\.\d+\.\d+.0%
Loading composer repositories with package information
Updating dependencies
@ -26,12 +26,12 @@ Package operations: 6 installs, 0 updates, 0 removals%(\nAs there is no 'unzip'
- Downloading symfony/filesystem (%v?[2-8]\.\d+\.\d+%)
- Installing symfony/console (99999.1.2): Symlinking from symfony-console
- Installing plugin/a (1.1.1): Symlinking from plugin-a
!!PluginAInit["composer/ca-bundle","composer/composer","composer/metadata-minifier","composer/pcre","composer/semver","composer/spdx-licenses","composer/xdebug-handler","justinrainbow/json-schema","psr/log","react/promise","seld/jsonlint","seld/phar-utils","symfony/console","symfony/debug","symfony/filesystem","symfony/finder","symfony/polyfill-ctype","symfony/polyfill-mbstring","symfony/process","root/pkg"]
!!PluginAInit["composer/ca-bundle","composer/composer","composer/metadata-minifier","composer/pcre","composer/semver","composer/spdx-licenses","composer/xdebug-handler","justinrainbow/json-schema","psr/container","psr/log","psr/log-implementation","react/promise","seld/jsonlint","seld/phar-utils","symfony/console","symfony/deprecation-contracts","symfony/filesystem","symfony/finder","symfony/polyfill-ctype","symfony/polyfill-intl-grapheme","symfony/polyfill-intl-normalizer","symfony/polyfill-mbstring","symfony/polyfill-php73","symfony/polyfill-php80","symfony/process","symfony/service-contracts","symfony/string","root/pkg"]
!!PluginA:null
!!PluginB:null
!!Versions:console:%[2-8]\.\d+\.\d+.0%;process:%[2-8]\.\d+\.\d+.0%;filesystem:%[2-8]\.\d+\.\d+.0%
- Installing plugin/b (2.2.2): Symlinking from plugin-b
!!PluginBInit["composer/ca-bundle","composer/composer","composer/metadata-minifier","composer/pcre","composer/semver","composer/spdx-licenses","composer/xdebug-handler","justinrainbow/json-schema","psr/log","react/promise","seld/jsonlint","seld/phar-utils","symfony/console","symfony/debug","symfony/filesystem","symfony/finder","symfony/polyfill-ctype","symfony/polyfill-mbstring","symfony/process","plugin/a","root/pkg"]
!!PluginBInit["composer/ca-bundle","composer/composer","composer/metadata-minifier","composer/pcre","composer/semver","composer/spdx-licenses","composer/xdebug-handler","justinrainbow/json-schema","psr/container","psr/log","psr/log-implementation","react/promise","seld/jsonlint","seld/phar-utils","symfony/console","symfony/deprecation-contracts","symfony/filesystem","symfony/finder","symfony/polyfill-ctype","symfony/polyfill-intl-grapheme","symfony/polyfill-intl-normalizer","symfony/polyfill-mbstring","symfony/polyfill-php73","symfony/polyfill-php80","symfony/process","symfony/service-contracts","symfony/string","plugin/a","root/pkg"]
!!PluginA:1.1.1.0
!!PluginB:null
!!Versions:console:%[2-8]\.\d+\.\d+.0%;process:%[2-8]\.\d+\.\d+.0%;filesystem:%[2-8]\.\d+\.\d+.0%
@ -42,7 +42,7 @@ Generating autoload files
2 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
> Hooks::postUpdate
!!PostUpdate:["composer/ca-bundle","composer/composer","composer/metadata-minifier","composer/pcre","composer/semver","composer/spdx-licenses","composer/xdebug-handler","justinrainbow/json-schema","psr/log","react/promise","seld/jsonlint","seld/phar-utils","symfony/console","symfony/debug","symfony/filesystem","symfony/finder","symfony/polyfill-ctype","symfony/polyfill-mbstring","symfony/process","plugin/a","plugin/b","root/pkg"]
!!PostUpdate:["composer/ca-bundle","composer/composer","composer/metadata-minifier","composer/pcre","composer/semver","composer/spdx-licenses","composer/xdebug-handler","justinrainbow/json-schema","psr/container","psr/log","psr/log-implementation","react/promise","seld/jsonlint","seld/phar-utils","symfony/console","symfony/deprecation-contracts","symfony/filesystem","symfony/finder","symfony/polyfill-ctype","symfony/polyfill-intl-grapheme","symfony/polyfill-intl-normalizer","symfony/polyfill-mbstring","symfony/polyfill-php73","symfony/polyfill-php80","symfony/process","symfony/service-contracts","symfony/string","plugin/a","plugin/b","root/pkg"]
!!Versions:console:%[2-8]\.\d+\.\d+.0%;process:%[2-8]\.\d+\.\d+.0%;filesystem:%[2-8]\.\d+\.\d+.0%
--EXPECT-EXIT-CODE--

View File

@ -7,14 +7,14 @@ Checks that package versions in InstalledVersions are correct during an upgrade.
--RUN--
update plugin/* symfony/console symfony/filesystem symfony/process
--EXPECT--
!!PluginA:1.1.1.0["composer/ca-bundle","composer/composer","composer/metadata-minifier","composer/pcre","composer/semver","composer/spdx-licenses","composer/xdebug-handler","justinrainbow/json-schema","psr/log","react/promise","seld/jsonlint","seld/phar-utils","symfony/console","symfony/debug","symfony/filesystem","symfony/finder","symfony/polyfill-ctype","symfony/polyfill-mbstring","symfony/process","plugin/a","plugin/b","root/pkg"]
!!PluginA:1.1.1.0["composer/ca-bundle","composer/composer","composer/metadata-minifier","composer/pcre","composer/semver","composer/spdx-licenses","composer/xdebug-handler","justinrainbow/json-schema","psr/container","psr/log","psr/log-implementation","react/promise","seld/jsonlint","seld/phar-utils","symfony/console","symfony/deprecation-contracts","symfony/filesystem","symfony/finder","symfony/polyfill-ctype","symfony/polyfill-intl-grapheme","symfony/polyfill-intl-normalizer","symfony/polyfill-mbstring","symfony/polyfill-php73","symfony/polyfill-php80","symfony/process","symfony/service-contracts","symfony/string","plugin/a","plugin/b","root/pkg"]
!!PluginB:2.2.2.0
!!Versions:console:%[2-8]\.\d+\.\d+.0%;process:%[2-8]\.\d+\.\d+.0%;filesystem:%[2-8]\.\d+\.\d+.0%
!!PluginB:2.2.2.0["composer/ca-bundle","composer/composer","composer/metadata-minifier","composer/pcre","composer/semver","composer/spdx-licenses","composer/xdebug-handler","justinrainbow/json-schema","psr/log","react/promise","seld/jsonlint","seld/phar-utils","symfony/console","symfony/debug","symfony/filesystem","symfony/finder","symfony/polyfill-ctype","symfony/polyfill-mbstring","symfony/process","plugin/a","plugin/b","root/pkg"]
!!PluginB:2.2.2.0["composer/ca-bundle","composer/composer","composer/metadata-minifier","composer/pcre","composer/semver","composer/spdx-licenses","composer/xdebug-handler","justinrainbow/json-schema","psr/container","psr/log","psr/log-implementation","react/promise","seld/jsonlint","seld/phar-utils","symfony/console","symfony/deprecation-contracts","symfony/filesystem","symfony/finder","symfony/polyfill-ctype","symfony/polyfill-intl-grapheme","symfony/polyfill-intl-normalizer","symfony/polyfill-mbstring","symfony/polyfill-php73","symfony/polyfill-php80","symfony/process","symfony/service-contracts","symfony/string","plugin/a","plugin/b","root/pkg"]
!!PluginA:1.1.1.0
!!Versions:console:%[2-8]\.\d+\.\d+.0%;process:%[2-8]\.\d+\.\d+.0%;filesystem:%[2-8]\.\d+\.\d+.0%
> Hooks::preUpdate
!!PreUpdate:["composer/ca-bundle","composer/composer","composer/metadata-minifier","composer/pcre","composer/semver","composer/spdx-licenses","composer/xdebug-handler","justinrainbow/json-schema","psr/log","react/promise","seld/jsonlint","seld/phar-utils","symfony/console","symfony/debug","symfony/filesystem","symfony/finder","symfony/polyfill-ctype","symfony/polyfill-mbstring","symfony/process","plugin/a","plugin/b","root/pkg"]
!!PreUpdate:["composer/ca-bundle","composer/composer","composer/metadata-minifier","composer/pcre","composer/semver","composer/spdx-licenses","composer/xdebug-handler","justinrainbow/json-schema","psr/container","psr/log","psr/log-implementation","react/promise","seld/jsonlint","seld/phar-utils","symfony/console","symfony/deprecation-contracts","symfony/filesystem","symfony/finder","symfony/polyfill-ctype","symfony/polyfill-intl-grapheme","symfony/polyfill-intl-normalizer","symfony/polyfill-mbstring","symfony/polyfill-php73","symfony/polyfill-php80","symfony/process","symfony/service-contracts","symfony/string","plugin/a","plugin/b","root/pkg"]
!!Versions:console:%[2-8]\.\d+\.\d+.0%;process:%[2-8]\.\d+\.\d+.0%;filesystem:%[2-8]\.\d+\.\d+.0%
Loading composer repositories with package information
Updating dependencies
@ -30,12 +30,12 @@ Package operations: 0 installs, 5 updates, 0 removals%(\nAs there is no 'unzip'
- Downloading symfony/filesystem (%v?[2-8]\.\d+\.\d+%)
- Upgrading symfony/console (99999.1.2 => 99999.1.3): Mirroring from symfony-console
- Upgrading plugin/a (1.1.1 => 1.1.2): Mirroring from plugin-a
!!PluginAInit["composer/ca-bundle","composer/composer","composer/metadata-minifier","composer/pcre","composer/semver","composer/spdx-licenses","composer/xdebug-handler","justinrainbow/json-schema","psr/log","react/promise","seld/jsonlint","seld/phar-utils","symfony/console","symfony/debug","symfony/filesystem","symfony/finder","symfony/polyfill-ctype","symfony/polyfill-mbstring","symfony/process","plugin/a","plugin/b","root/pkg"]
!!PluginAInit["composer/ca-bundle","composer/composer","composer/metadata-minifier","composer/pcre","composer/semver","composer/spdx-licenses","composer/xdebug-handler","justinrainbow/json-schema","psr/container","psr/log","psr/log-implementation","react/promise","seld/jsonlint","seld/phar-utils","symfony/console","symfony/deprecation-contracts","symfony/filesystem","symfony/finder","symfony/polyfill-ctype","symfony/polyfill-intl-grapheme","symfony/polyfill-intl-normalizer","symfony/polyfill-mbstring","symfony/polyfill-php73","symfony/polyfill-php80","symfony/process","symfony/service-contracts","symfony/string","plugin/a","plugin/b","root/pkg"]
!!PluginA:1.1.1.0
!!PluginB:2.2.2.0
!!Versions:console:%[2-8]\.\d+\.\d+.0%;process:%[2-8]\.\d+\.\d+.0%;filesystem:%[2-8]\.\d+\.\d+.0%
- Upgrading plugin/b (2.2.2 => 2.2.3): Mirroring from plugin-b
!!PluginBInit["composer/ca-bundle","composer/composer","composer/metadata-minifier","composer/pcre","composer/semver","composer/spdx-licenses","composer/xdebug-handler","justinrainbow/json-schema","psr/log","react/promise","seld/jsonlint","seld/phar-utils","symfony/console","symfony/debug","symfony/filesystem","symfony/finder","symfony/polyfill-ctype","symfony/polyfill-mbstring","symfony/process","plugin/a","plugin/b","root/pkg"]
!!PluginBInit["composer/ca-bundle","composer/composer","composer/metadata-minifier","composer/pcre","composer/semver","composer/spdx-licenses","composer/xdebug-handler","justinrainbow/json-schema","psr/container","psr/log","psr/log-implementation","react/promise","seld/jsonlint","seld/phar-utils","symfony/console","symfony/deprecation-contracts","symfony/filesystem","symfony/finder","symfony/polyfill-ctype","symfony/polyfill-intl-grapheme","symfony/polyfill-intl-normalizer","symfony/polyfill-mbstring","symfony/polyfill-php73","symfony/polyfill-php80","symfony/process","symfony/service-contracts","symfony/string","plugin/a","plugin/b","root/pkg"]
!!PluginA:1.1.2.0
!!PluginB:2.2.2.0
!!Versions:console:%[2-8]\.\d+\.\d+.0%;process:%[2-8]\.\d+\.\d+.0%;filesystem:%[2-8]\.\d+\.\d+.0%
@ -45,7 +45,7 @@ Generating autoload files
2 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
> Hooks::postUpdate
!!PostUpdate:["composer/ca-bundle","composer/composer","composer/metadata-minifier","composer/pcre","composer/semver","composer/spdx-licenses","composer/xdebug-handler","justinrainbow/json-schema","psr/log","react/promise","seld/jsonlint","seld/phar-utils","symfony/console","symfony/debug","symfony/filesystem","symfony/finder","symfony/polyfill-ctype","symfony/polyfill-mbstring","symfony/process","plugin/a","plugin/b","root/pkg"]
!!PostUpdate:["composer/ca-bundle","composer/composer","composer/metadata-minifier","composer/pcre","composer/semver","composer/spdx-licenses","composer/xdebug-handler","justinrainbow/json-schema","psr/container","psr/log","psr/log-implementation","react/promise","seld/jsonlint","seld/phar-utils","symfony/console","symfony/deprecation-contracts","symfony/filesystem","symfony/finder","symfony/polyfill-ctype","symfony/polyfill-intl-grapheme","symfony/polyfill-intl-normalizer","symfony/polyfill-mbstring","symfony/polyfill-php73","symfony/polyfill-php80","symfony/process","symfony/service-contracts","symfony/string","plugin/a","plugin/b","root/pkg"]
!!Versions:console:%[2-8]\.\d+\.\d+.0%;process:%[2-8]\.\d+\.\d+.0%;filesystem:%[2-8]\.\d+\.\d+.0%
!!PluginA:1.1.2.0
!!PluginB:2.2.3.0

View File

@ -27,7 +27,8 @@ class BufferIOTest extends TestCase
$input = $refl->getValue($bufferIO);
if (!$input instanceof StreamableInputInterface) {
$this->setExpectedException('\RuntimeException', 'Setting the user inputs requires at least the version 3.2 of the symfony/console component.');
self::expectException('\RuntimeException');
self::expectExceptionMessage('Setting the user inputs requires at least the version 3.2 of the symfony/console component.');
}
$bufferIO->setUserInputs(array(

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

@ -22,7 +22,7 @@ class InstalledVersionsTest extends TestCase
*/
private $root;
public static function setUpBeforeClass()
public static function setUpBeforeClass(): void
{
// disable multiple-ClassLoader-based checks of InstalledVersions by making it seem like no
// class loaders are registered
@ -31,12 +31,12 @@ class InstalledVersionsTest extends TestCase
$prop->setValue(array());
}
public static function tearDownAfterClass()
public static function tearDownAfterClass(): void
{
self::setUpBeforeClass();
}
public function setUp()
public function setUp(): void
{
$this->root = $this->getUniqueTmpDirectory();
@ -200,7 +200,7 @@ class InstalledVersionsTest extends TestCase
public function testGetVersionOutOfBounds()
{
$this->setExpectedException('OutOfBoundsException');
self::expectException('OutOfBoundsException');
InstalledVersions::getVersion('not/installed');
}

View File

@ -46,7 +46,7 @@ class BinaryInstallerTest extends TestCase
*/
protected $fs;
protected function setUp()
protected function setUp(): void
{
$this->fs = new Filesystem;
@ -60,8 +60,9 @@ class BinaryInstallerTest extends TestCase
$this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
}
protected function tearDown()
protected function tearDown(): void
{
parent::tearDown();
$this->fs->removeDirectory($this->rootDir);
}

View File

@ -36,7 +36,7 @@ class InstallationManagerTest extends TestCase
*/
protected $io;
public function setUp()
public function setUp(): void
{
$this->loop = $this->getMockBuilder('Composer\Util\Loop')->disableOriginalConstructor()->getMock();
$this->repository = $this->getMockBuilder('Composer\Repository\InstalledRepositoryInterface')->getMock();
@ -59,7 +59,7 @@ class InstallationManagerTest extends TestCase
$manager->addInstaller($installer);
$this->assertSame($installer, $manager->getInstaller('vendor'));
$this->setExpectedException('InvalidArgumentException');
self::expectException('InvalidArgumentException');
$manager->getInstaller('unregistered');
}
@ -97,7 +97,7 @@ class InstallationManagerTest extends TestCase
{
$manager = $this->getMockBuilder('Composer\Installer\InstallationManager')
->setConstructorArgs(array($this->loop, $this->io))
->setMethods(array('install', 'update', 'uninstall'))
->onlyMethods(array('install', 'update', 'uninstall'))
->getMock();
$installOperation = new InstallOperation($package = $this->createPackageMock());

View File

@ -65,7 +65,7 @@ class LibraryInstallerTest extends TestCase
*/
protected $fs;
protected function setUp()
protected function setUp(): void
{
$this->fs = new Filesystem;
@ -96,8 +96,9 @@ class LibraryInstallerTest extends TestCase
$this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
}
protected function tearDown()
protected function tearDown(): void
{
parent::tearDown();
$this->fs->removeDirectory($this->rootDir);
}
@ -222,7 +223,7 @@ class LibraryInstallerTest extends TestCase
$this->assertFileExists($this->vendorDir, 'Vendor dir should be created');
$this->assertFileExists($this->binDir, 'Bin dir should be created');
$this->setExpectedException('InvalidArgumentException');
self::expectException('InvalidArgumentException');
$library->update($this->repository, $initial, $target);
}
@ -259,7 +260,7 @@ class LibraryInstallerTest extends TestCase
$library->uninstall($this->repository, $package);
$this->setExpectedException('InvalidArgumentException');
self::expectException('InvalidArgumentException');
$library->uninstall($this->repository, $package);
}

View File

@ -30,7 +30,7 @@ class MetapackageInstallerTest extends TestCase
*/
private $io;
protected function setUp()
protected function setUp(): void
{
$this->repository = $this->getMockBuilder('Composer\Repository\InstalledRepositoryInterface')->getMock();
@ -80,7 +80,7 @@ class MetapackageInstallerTest extends TestCase
$this->installer->update($this->repository, $initial, $target);
$this->setExpectedException('InvalidArgumentException');
self::expectException('InvalidArgumentException');
$this->installer->update($this->repository, $initial, $target);
}
@ -102,7 +102,7 @@ class MetapackageInstallerTest extends TestCase
$this->installer->uninstall($this->repository, $package);
$this->setExpectedException('InvalidArgumentException');
self::expectException('InvalidArgumentException');
$this->installer->uninstall($this->repository, $package);
}

View File

@ -30,7 +30,7 @@ class SuggestedPackagesReporterTest extends TestCase
*/
private $suggestedPackagesReporter;
protected function setUp()
protected function setUp(): void
{
$this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock();
@ -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

@ -50,14 +50,15 @@ class InstallerTest extends TestCase
/** @var ?string */
protected $tempComposerHome;
public function setUp()
public function setUp(): void
{
$this->prevCwd = getcwd();
chdir(__DIR__);
}
public function tearDown()
protected function tearDown(): void
{
parent::tearDown();
Platform::clearEnv('COMPOSER_POOL_OPTIMIZER');
chdir($this->prevCwd);
@ -234,7 +235,7 @@ class InstallerTest extends TestCase
* @param ?string $expectOutput
* @param ?string $expectOutputOptimized
* @param string $expect
* @param int|string $expectResult
* @param int|class-string<\Throwable> $expectResult
*/
public function testSlowIntegration($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectInstalled, $expectOutput, $expectOutputOptimized, $expect, $expectResult)
{
@ -257,7 +258,7 @@ class InstallerTest extends TestCase
* @param ?string $expectOutput
* @param ?string $expectOutputOptimized
* @param string $expect
* @param int|string $expectResult
* @param int|class-string<\Throwable> $expectResult
*/
public function testIntegrationWithPoolOptimizer($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectInstalled, $expectOutput, $expectOutputOptimized, $expect, $expectResult)
{
@ -280,7 +281,7 @@ class InstallerTest extends TestCase
* @param ?string $expectOutput
* @param ?string $expectOutputOptimized
* @param string $expect
* @param int|string $expectResult
* @param int|class-string<\Throwable> $expectResult
*/
public function testIntegrationWithRawPool($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectInstalled, $expectOutput, $expectOutputOptimized, $expect, $expectResult)
{
@ -301,7 +302,7 @@ class InstallerTest extends TestCase
* @param ?mixed[] $expectInstalled
* @param ?string $expectOutput
* @param string $expect
* @param int|string $expectResult
* @param int|class-string<\Throwable> $expectResult
* @return void
*/
private function doTestIntegration($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectInstalled, $expectOutput, $expect, $expectResult)
@ -318,7 +319,8 @@ class InstallerTest extends TestCase
// Prepare for exceptions
if (!is_int($expectResult)) {
$normalizedOutput = rtrim(str_replace("\n", PHP_EOL, $expect));
$this->setExpectedException($expectResult, $normalizedOutput);
self::expectException($expectResult);
self::expectExceptionMessage($normalizedOutput);
}
// Create Composer mock object according to configuration
@ -451,6 +453,9 @@ class InstallerTest extends TestCase
$application->setAutoExit(false);
$appOutput = fopen('php://memory', 'w+');
if (false === $appOutput) {
self::fail('Failed to open memory stream');
}
$input = new StringInput($run.' -vvv');
$input->setInteractive(false);
$result = $application->run($input, new StreamOutput($appOutput));
@ -553,7 +558,7 @@ class InstallerTest extends TestCase
if (!empty($testData['LOCK'])) {
$lock = JsonFile::parseJson($testData['LOCK']);
if (!isset($lock['hash'])) {
$lock['hash'] = md5(json_encode($composer));
$lock['hash'] = md5(JsonFile::encode($composer, 0));
}
}
if (!empty($testData['INSTALLED'])) {

View File

@ -99,7 +99,7 @@ class JsonFileTest extends TestCase
public function testSchemaValidationError()
{
$file = tempnam(sys_get_temp_dir(), 'c');
$file = $this->createTempFile();
file_put_contents($file, '{ "name": null }');
$json = new JsonFile($file);
$expectedMessage = sprintf('"%s" does not match the expected JSON schema', $file);
@ -123,7 +123,7 @@ class JsonFileTest extends TestCase
public function testSchemaValidationLaxAdditionalProperties()
{
$file = tempnam(sys_get_temp_dir(), 'c');
$file = $this->createTempFile();
file_put_contents($file, '{ "name": "vendor/package", "description": "generic description", "foo": "bar" }');
$json = new JsonFile($file);
try {
@ -139,7 +139,7 @@ class JsonFileTest extends TestCase
public function testSchemaValidationLaxRequired()
{
$file = tempnam(sys_get_temp_dir(), 'c');
$file = $this->createTempFile();
$json = new JsonFile($file);
$expectedMessage = sprintf('"%s" does not match the expected JSON schema', $file);
@ -209,10 +209,10 @@ class JsonFileTest extends TestCase
public function testCustomSchemaValidationLax()
{
$file = tempnam(sys_get_temp_dir(), 'c');
$file = $this->createTempFile();
file_put_contents($file, '{ "custom": "property", "another custom": "property" }');
$schema = tempnam(sys_get_temp_dir(), 'c');
$schema = $this->createTempFile();
file_put_contents($schema, '{ "properties": { "custom": { "type": "string" }}}');
$json = new JsonFile($file);
@ -225,10 +225,10 @@ class JsonFileTest extends TestCase
public function testCustomSchemaValidationStrict()
{
$file = tempnam(sys_get_temp_dir(), 'c');
$file = $this->createTempFile();
file_put_contents($file, '{ "custom": "property" }');
$schema = tempnam(sys_get_temp_dir(), 'c');
$schema = $this->createTempFile();
file_put_contents($schema, '{ "properties": { "custom": { "type": "string" }}}');
$json = new JsonFile($file);

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('status' => 200, 'body' => '', 'headers' => [])): void
{
$this->contentMap = $contentMap;
$default = ['url' => '', 'options' => null, 'status' => 200, 'body' => '', 'headers' => ['']];
$this->expectations = array_map(function (array $expect) use ($default): array {
if (count($diff = array_diff_key(array_merge($default, $expect), $default)) > 0) {
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); // @phpstan-ignore-line
}
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}>|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); // @phpstan-ignore-line
}
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

@ -33,7 +33,7 @@ class ArchivableFilesFinderTest extends TestCase
*/
protected $fs;
protected function setUp()
protected function setUp(): void
{
$fs = new Filesystem;
$this->fs = $fs;
@ -95,8 +95,9 @@ class ArchivableFilesFinderTest extends TestCase
}
}
protected function tearDown()
protected function tearDown(): void
{
parent::tearDown();
$fs = new Filesystem;
$fs->removeDirectory($this->sources);
}

View File

@ -32,7 +32,7 @@ class ArchiveManagerTest extends ArchiverTest
*/
protected $targetDir;
public function setUp()
public function setUp(): void
{
parent::setUp();
@ -50,7 +50,7 @@ class ArchiveManagerTest extends ArchiverTest
public function testUnknownFormat()
{
$this->setExpectedException('RuntimeException');
self::expectException('RuntimeException');
$package = $this->setupPackage();

View File

@ -34,15 +34,16 @@ abstract class ArchiverTest extends TestCase
*/
protected $testDir;
public function setUp()
public function setUp(): void
{
$this->filesystem = new Filesystem();
$this->process = new ProcessExecutor();
$this->testDir = $this->getUniqueTmpDirectory();
}
public function tearDown()
protected function tearDown(): void
{
parent::tearDown();
$this->filesystem->removeDirectory($this->testDir);
}

View File

@ -35,7 +35,7 @@ class BasePackageTest extends TestCase
public function testSetAnotherRepository()
{
$this->setExpectedException('LogicException');
self::expectException('LogicException');
$package = $this->getMockForAbstractClass('Composer\Package\BasePackage', array('foo'));

View File

@ -24,11 +24,11 @@ class ArrayDumperTest extends TestCase
*/
private $dumper;
/**
* @var \Composer\Package\CompletePackageInterface|\PHPUnit_Framework_MockObject_MockObject
* @var \Composer\Package\CompletePackageInterface|\PHPUnit\Framework\MockObject\MockObject
*/
private $package;
public function setUp()
public function setUp(): void
{
$this->dumper = new ArrayDumper();
$this->package = $this->getMockBuilder('Composer\Package\CompletePackageInterface')->getMock();

View File

@ -24,7 +24,7 @@ class ArrayLoaderTest extends TestCase
*/
private $loader;
public function setUp()
public function setUp(): void
{
$this->loader = new ArrayLoader(null);
}

View File

@ -20,8 +20,6 @@ use Composer\Package\RootPackage;
use Composer\Package\Version\VersionGuesser;
use Composer\Semver\VersionParser;
use Composer\Test\TestCase;
use Composer\Test\Mock\ProcessExecutorMock;
use Prophecy\Argument;
class RootPackageLoaderTest extends TestCase
{
@ -81,7 +79,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());
@ -93,9 +91,10 @@ class RootPackageLoaderTest extends TestCase
public function testPrettyVersionForRootPackageInVersionBranch()
{
// see #6845
$manager = $this->prophesize('Composer\\Repository\\RepositoryManager');
$versionGuesser = $this->prophesize('Composer\\Package\\Version\\VersionGuesser');
$versionGuesser->guessVersion(Argument::cetera())
$manager = $this->getMockBuilder('Composer\\Repository\\RepositoryManager')->disableOriginalConstructor()->getMock();
$versionGuesser = $this->getMockBuilder('Composer\\Package\\Version\\VersionGuesser')->disableOriginalConstructor()->getMock();
$versionGuesser->expects($this->atLeastOnce())
->method('guessVersion')
->willReturn(array(
'name' => 'A',
'version' => '3.0.9999999.9999999-dev',
@ -104,7 +103,7 @@ class RootPackageLoaderTest extends TestCase
));
$config = new Config;
$config->merge(array('repositories' => array('packagist' => false)));
$loader = new RootPackageLoader($manager->reveal(), $config, null, $versionGuesser->reveal());
$loader = new RootPackageLoader($manager, $config, null, $versionGuesser);
$package = $loader->load(array());
$this->assertEquals('3.0-dev', $package->getPrettyVersion());
@ -121,7 +120,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 +135,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 +148,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 +162,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

@ -12,6 +12,7 @@
namespace Composer\Test\Package;
use Composer\Json\JsonFile;
use Composer\Package\Locker;
use Composer\Plugin\PluginInterface;
use Composer\IO\NullIO;
@ -53,7 +54,7 @@ class LockerTest extends TestCase
->method('exists')
->will($this->returnValue(false));
$this->setExpectedException('LogicException');
self::expectException('LogicException');
$locker->getLockedRepository();
}
@ -170,7 +171,7 @@ class LockerTest extends TestCase
->method('getPrettyName')
->will($this->returnValue('pkg1'));
$this->setExpectedException('LogicException');
self::expectException('LogicException');
$locker->setLockData(array($package1), array(), array(), array(), array(), 'dev', array(), false, false, array());
}
@ -282,16 +283,13 @@ class LockerTest extends TestCase
*/
private function createPackageMock()
{
return $this->getMockBuilder('Composer\Package\PackageInterface')
->getMock();
return $this->getMockBuilder('Composer\Package\PackageInterface')->getMock();
}
/**
* @param array<string, string> $customData
*
* @return false|string
*/
private function getJsonContent(array $customData = array())
private function getJsonContent(array $customData = array()): string
{
$data = array_merge(array(
'minimum-stability' => 'beta',
@ -300,6 +298,6 @@ class LockerTest extends TestCase
ksort($data);
return json_encode($data);
return JsonFile::encode($data, 0);
}
}

View File

@ -14,84 +14,112 @@ namespace Composer\Test\Package;
use Composer\Package\Link;
use Composer\Package\RootAliasPackage;
use Composer\Package\RootPackage;
use Composer\Semver\Constraint\MatchAllConstraint;
use Composer\Test\TestCase;
use Prophecy\Argument;
use PHPUnit\Framework\MockObject\MockObject;
class RootAliasPackageTest extends TestCase
{
public function testUpdateRequires()
{
$root = $this->getMockRootPackageInterface();
$root->setRequires(Argument::type('array'))->shouldBeCalled();
$alias = new RootAliasPackage($root->reveal(), '1.0', '1.0.0.0');
$this->assertEmpty($alias->getRequires());
$links = array(new Link('a', 'b', new MatchAllConstraint(), Link::TYPE_REQUIRE, 'self.version'));
$root = $this->getMockRootPackage();
$root->expects($this->once())
->method('setRequires')
->with($this->equalTo($links));
$alias = new RootAliasPackage($root, '1.0', '1.0.0.0');
$this->assertEmpty($alias->getRequires());
$alias->setRequires($links);
$this->assertNotEmpty($alias->getRequires());
}
public function testUpdateDevRequires()
{
$root = $this->getMockRootPackageInterface();
$root->setDevRequires(Argument::type('array'))->shouldBeCalled();
$alias = new RootAliasPackage($root->reveal(), '1.0', '1.0.0.0');
$this->assertEmpty($alias->getDevRequires());
$links = array(new Link('a', 'b', new MatchAllConstraint(), Link::TYPE_DEV_REQUIRE, 'self.version'));
$root = $this->getMockRootPackage();
$root->expects($this->once())
->method('setDevRequires')
->with($this->equalTo($links));
$alias = new RootAliasPackage($root, '1.0', '1.0.0.0');
$this->assertEmpty($alias->getDevRequires());
$alias->setDevRequires($links);
$this->assertNotEmpty($alias->getDevRequires());
}
public function testUpdateConflicts()
{
$root = $this->getMockRootPackageInterface();
$root->setConflicts(Argument::type('array'))->shouldBeCalled();
$alias = new RootAliasPackage($root->reveal(), '1.0', '1.0.0.0');
$this->assertEmpty($alias->getConflicts());
$links = array(new Link('a', 'b', new MatchAllConstraint(), Link::TYPE_CONFLICT, 'self.version'));
$root = $this->getMockRootPackage();
$root->expects($this->once())
->method('setConflicts')
->with($this->equalTo($links));
$alias = new RootAliasPackage($root, '1.0', '1.0.0.0');
$this->assertEmpty($alias->getConflicts());
$alias->setConflicts($links);
$this->assertNotEmpty($alias->getConflicts());
}
public function testUpdateProvides()
{
$root = $this->getMockRootPackageInterface();
$root->setProvides(Argument::type('array'))->shouldBeCalled();
$alias = new RootAliasPackage($root->reveal(), '1.0', '1.0.0.0');
$this->assertEmpty($alias->getProvides());
$links = array(new Link('a', 'b', new MatchAllConstraint(), Link::TYPE_PROVIDE, 'self.version'));
$root = $this->getMockRootPackage();
$root->expects($this->once())
->method('setProvides')
->with($this->equalTo($links));
$alias = new RootAliasPackage($root, '1.0', '1.0.0.0');
$this->assertEmpty($alias->getProvides());
$alias->setProvides($links);
$this->assertNotEmpty($alias->getProvides());
}
public function testUpdateReplaces()
{
$root = $this->getMockRootPackageInterface();
$root->setReplaces(Argument::type('array'))->shouldBeCalled();
$alias = new RootAliasPackage($root->reveal(), '1.0', '1.0.0.0');
$this->assertEmpty($alias->getReplaces());
$links = array(new Link('a', 'b', new MatchAllConstraint(), Link::TYPE_REPLACE, 'self.version'));
$root = $this->getMockRootPackage();
$root->expects($this->once())
->method('setReplaces')
->with($this->equalTo($links));
$alias = new RootAliasPackage($root, '1.0', '1.0.0.0');
$this->assertEmpty($alias->getReplaces());
$alias->setReplaces($links);
$this->assertNotEmpty($alias->getReplaces());
}
/**
* @return \Prophecy\Prophecy\ObjectProphecy
* @return RootPackage&MockObject
*/
protected function getMockRootPackageInterface()
protected function getMockRootPackage()
{
$root = $this->prophesize('Composer\\Package\\RootPackage');
$root->getName()->willReturn('something/something')->shouldBeCalled();
$root->getRequires()->willReturn(array())->shouldBeCalled();
$root->getDevRequires()->willReturn(array())->shouldBeCalled();
$root->getConflicts()->willReturn(array())->shouldBeCalled();
$root->getProvides()->willReturn(array())->shouldBeCalled();
$root->getReplaces()->willReturn(array())->shouldBeCalled();
$root = $this->getMockBuilder(RootPackage::class)->disableOriginalConstructor()->getMock();
$root->expects($this->atLeastOnce())
->method('getName')
->willReturn('something/something');
$root->expects($this->atLeastOnce())
->method('getRequires')
->willReturn(array());
$root->expects($this->atLeastOnce())
->method('getDevRequires')
->willReturn(array());
$root->expects($this->atLeastOnce())
->method('getConflicts')
->willReturn(array());
$root->expects($this->atLeastOnce())
->method('getProvides')
->willReturn(array());
$root->expects($this->atLeastOnce())
->method('getReplaces')
->willReturn(array());
return $root;
}

View File

@ -22,7 +22,7 @@ use Composer\Test\Mock\ProcessExecutorMock;
class VersionGuesserTest extends TestCase
{
public function setUp()
public function setUp(): void
{
if (!function_exists('proc_open')) {
$this->markTestSkipped('proc_open() is not available');
@ -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

@ -25,7 +25,7 @@ class HhvmDetectorTest extends TestCase
*/
private $hhvmDetector;
protected function setUp()
protected function setUp(): void
{
$this->hhvmDetector = new HhvmDetector();
$this->hhvmDetector->reset();

View File

@ -68,7 +68,7 @@ class PluginInstallerTest extends TestCase
*/
protected $io;
protected function setUp()
protected function setUp(): void
{
$loader = new JsonLoader(new ArrayLoader());
$this->packages = array();
@ -127,8 +127,9 @@ class PluginInstallerTest extends TestCase
$this->composer->setPluginManager($this->pm);
}
protected function tearDown()
protected function tearDown(): void
{
parent::tearDown();
$filesystem = new Filesystem();
$filesystem->removeDirectory($this->directory);
}
@ -282,7 +283,7 @@ class PluginInstallerTest extends TestCase
{
// reset the plugin manager's installed plugins
$this->pm = $this->getMockBuilder('Composer\Plugin\PluginManager')
->setMethods(array('getPluginApiVersion'))
->onlyMethods(array('getPluginApiVersion'))
->setConstructorArgs(array($this->io, $this->composer))
->getMock();
@ -431,13 +432,13 @@ class PluginInstallerTest extends TestCase
/**
* @dataProvider invalidImplementationClassNames
* @param callable $invalidImplementationClassNames
* @param string $expect
* @param class-string<\Throwable> $expect
*
* @return void
*/
public function testQueryingWithInvalidCapabilityClassNameThrows($invalidImplementationClassNames, $expect = 'UnexpectedValueException')
{
$this->setExpectedException($expect);
self::expectException($expect);
$capabilityApi = 'Composer\Plugin\Capability\Capability';

View File

@ -1,759 +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;
use PHPUnit\Framework\Constraint\LogicalNot;
use PHPUnit\Framework\Constraint\StringContains;
if (method_exists('PHPUnit\Framework\TestCase', 'assertStringContainsString')) {
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 $message
*
* @return void
*/
public static function assertIsInt($actual, $message = '')
{
static::assertInternalType('int', $actual, $message);
}
/**
* @param string $message
*
* @return void
*/
public static function assertIsNumeric($actual, $message = '')
{
static::assertInternalType('numeric', $actual, $message);
}
/**
* @param string $message
*
* @return void
*/
public static function assertIsObject($actual, $message = '')
{
static::assertInternalType('object', $actual, $message);
}
/**
* @param string $message
*
* @return void
*/
public static function assertIsResource($actual, $message = '')
{
static::assertInternalType('resource', $actual, $message);
}
/**
* @param string $message
*
* @return void
*/
public static function assertIsString($actual, $message = '')
{
static::assertInternalType('string', $actual, $message);
}
/**
* @param string $message
*
* @return void
*/
public static function assertIsScalar($actual, $message = '')
{
static::assertInternalType('scalar', $actual, $message);
}
/**
* @param string $message
*
* @return void
*/
public static function assertIsCallable($actual, $message = '')
{
static::assertInternalType('callable', $actual, $message);
}
/**
* @param string $message
*
* @return void
*/
public static function assertIsIterable($actual, $message = '')
{
static::assertInternalType('iterable', $actual, $message);
}
/**
* @param string $needle
* @param string $haystack
* @param string $message
*
* @return void
*/
public static function assertStringContainsString($needle, $haystack, $message = '')
{
$constraint = new StringContains($needle, false);
static::assertThat($haystack, $constraint, $message);
}
/**
* @param string $needle
* @param string $haystack
* @param string $message
*
* @return void
*/
public static function assertStringContainsStringIgnoringCase($needle, $haystack, $message = '')
{
$constraint = new StringContains($needle, true);
static::assertThat($haystack, $constraint, $message);
}
/**
* @param string $needle
* @param string $haystack
* @param string $message
*
* @return void
*/
public static function assertStringNotContainsString($needle, $haystack, $message = '')
{
$constraint = new LogicalNot(new StringContains($needle, false));
static::assertThat($haystack, $constraint, $message);
}
/**
* @param string $needle
* @param string $haystack
* @param string $message
*
* @return void
*/
public static function assertStringNotContainsStringIgnoringCase($needle, $haystack, $message = '')
{
$constraint = new LogicalNot(new StringContains($needle, true));
static::assertThat($haystack, $constraint, $message);
}
/**
* @param string $message
*
* @return void
*/
public static function assertFinite($actual, $message = '')
{
static::assertInternalType('float', $actual, $message);
static::assertTrue(is_finite($actual), $message ? $message : "Failed asserting that $actual is finite.");
}
/**
* @param string $message
*
* @return void
*/
public static function assertInfinite($actual, $message = '')
{
static::assertInternalType('float', $actual, $message);
static::assertTrue(is_infinite($actual), $message ? $message : "Failed asserting that $actual is infinite.");
}
/**
* @param string $message
*
* @return void
*/
public static function assertNan($actual, $message = '')
{
static::assertInternalType('float', $actual, $message);
static::assertTrue(is_nan($actual), $message ? $message : "Failed asserting that $actual is nan.");
}
/**
* @param string $filename
* @param string $message
*
* @return void
*/
public static function assertIsReadable($filename, $message = '')
{
static::assertInternalType('string', $filename, $message);
static::assertTrue(is_readable($filename), $message ? $message : "Failed asserting that $filename is readable.");
}
/**
* @param string $filename
* @param string $message
*
* @return void
*/
public static function assertNotIsReadable($filename, $message = '')
{
static::assertInternalType('string', $filename, $message);
static::assertFalse(is_readable($filename), $message ? $message : "Failed asserting that $filename is not readable.");
}
/**
* @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 assertIsWritable($filename, $message = '')
{
static::assertInternalType('string', $filename, $message);
static::assertTrue(is_writable($filename), $message ? $message : "Failed asserting that $filename is writable.");
}
/**
* @param string $filename
* @param string $message
*
* @return void
*/
public static function assertNotIsWritable($filename, $message = '')
{
static::assertInternalType('string', $filename, $message);
static::assertFalse(is_writable($filename), $message ? $message : "Failed asserting that $filename is not writable.");
}
/**
* @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 assertDirectoryExists($directory, $message = '')
{
static::assertInternalType('string', $directory, $message);
static::assertTrue(is_dir($directory), $message ? $message : "Failed asserting that $directory exists.");
}
/**
* @param string $directory
* @param string $message
*
* @return void
*/
public static function assertDirectoryNotExists($directory, $message = '')
{
static::assertInternalType('string', $directory, $message);
static::assertFalse(is_dir($directory), $message ? $message : "Failed asserting that $directory does not exist.");
}
/**
* @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 assertDirectoryIsReadable($directory, $message = '')
{
static::assertDirectoryExists($directory, $message);
static::assertIsReadable($directory, $message);
}
/**
* @param string $directory
* @param string $message
*
* @return void
*/
public static function assertDirectoryNotIsReadable($directory, $message = '')
{
static::assertDirectoryExists($directory, $message);
static::assertNotIsReadable($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 assertDirectoryIsWritable($directory, $message = '')
{
static::assertDirectoryExists($directory, $message);
static::assertIsWritable($directory, $message);
}
/**
* @param string $directory
* @param string $message
*
* @return void
*/
public static function assertDirectoryNotIsWritable($directory, $message = '')
{
static::assertDirectoryExists($directory, $message);
static::assertNotIsWritable($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 assertFileExists($filename, $message = '')
{
static::assertInternalType('string', $filename, $message);
static::assertTrue(file_exists($filename), $message ? $message : "Failed asserting that $filename exists.");
}
/**
* @param string $filename
* @param string $message
*
* @return void
*/
public static function assertFileNotExists($filename, $message = '')
{
static::assertInternalType('string', $filename, $message);
static::assertFalse(file_exists($filename), $message ? $message : "Failed asserting that $filename does not exist.");
}
/**
* @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 assertFileIsReadable($filename, $message = '')
{
static::assertFileExists($filename, $message);
static::assertIsReadable($filename, $message);
}
/**
* @param string $filename
* @param string $message
*
* @return void
*/
public static function assertFileNotIsReadable($filename, $message = '')
{
static::assertFileExists($filename, $message);
static::assertNotIsReadable($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 assertFileIsWritable($filename, $message = '')
{
static::assertFileExists($filename, $message);
static::assertIsWritable($filename, $message);
}
/**
* @param string $filename
* @param string $message
*
* @return void
*/
public static function assertFileNotIsWritable($filename, $message = '')
{
static::assertFileExists($filename, $message);
static::assertNotIsWritable($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);
}
}
}
}
namespace {
foreach (array(
'PHPUnit\Framework\Constraint\IsEqual',
'PHPUnit\Framework\Constraint\StringContains',
'PHPUnit\Framework\Constraint\TraversableContains',
) as $class) {
if (!class_exists($class) && class_exists(str_replace('\\', '_', $class))) {
class_alias(str_replace('\\', '_', $class), $class);
}
}
foreach (array(
'PHPUnit\Framework\SelfDescribing',
) as $interface) {
if (!interface_exists($interface) && interface_exists(str_replace('\\', '_', $interface))) {
class_alias(str_replace('\\', '_', $interface), $interface);
}
}
if (!class_exists('PHPUnit\Framework\Constraint\Constraint')) {
class_alias('PHPUnit_Framework_Constraint', 'PHPUnit\Framework\Constraint\Constraint');
}
}
// all the code below taken from various PHPUnit versions to make things work on PHPUnit 4.8 / PHP 5.3
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\Constraint {
use PHPUnit\Framework\ExpectationFailedException;
if (!class_exists('PHPUnit\Framework\Constraint\RegularExpression')) {
/**
* Constraint that asserts that the string it is evaluated for matches
* a regular expression.
*
* Checks a given value using the Perl Compatible Regular Expression extension
* in PHP. The pattern is matched by executing preg_match().
*
* The pattern string passed in the constructor.
*/
class RegularExpression extends Constraint
{
/**
* @var string
*/
protected $pattern;
/**
* @param string $pattern
*/
public function __construct($pattern)
{
parent::__construct();
$this->pattern = $pattern;
}
/**
* Evaluates the constraint for parameter $other. Returns true if the
* constraint is met, false otherwise.
*
* @param mixed $other Value or object to evaluate.
*
* @return bool
*/
protected function matches($other)
{
return \preg_match($this->pattern, $other) > 0;
}
/**
* Returns a string representation of the constraint.
*
* @return string
*/
public function toString()
{
return \sprintf(
'matches PCRE pattern "%s"',
$this->pattern
);
}
}
}
if (!class_exists('PHPUnit\Framework\Constraint\LogicalNot')) {
/**
* Logical NOT.
*/
class LogicalNot extends Constraint
{
/**
* @var Constraint
*/
protected $constraint;
/**
* @param Constraint $constraint
*/
public function __construct($constraint)
{
parent::__construct();
if (!($constraint instanceof Constraint)) {
$constraint = new IsEqual($constraint);
}
$this->constraint = $constraint;
}
/**
* @param string $string
*
* @return string
*/
public static function negate($string)
{
$positives = array(
'contains ',
'exists',
'has ',
'is ',
'are ',
'matches ',
'starts with ',
'ends with ',
'reference ',
'not not ',
);
$negatives = array(
'does not contain ',
'does not exist',
'does not have ',
'is not ',
'are not ',
'does not match ',
'starts not with ',
'ends not with ',
'don\'t reference ',
'not ',
);
\preg_match('/(\'[\w\W]*\')([\w\W]*)("[\w\W]*")/i', $string, $matches);
if (\count($matches) > 0) {
$nonInput = $matches[2];
$negatedString = \str_replace(
$nonInput,
\str_replace(
$positives,
$negatives,
$nonInput
),
$string
);
} else {
$negatedString = \str_replace(
$positives,
$negatives,
$string
);
}
return $negatedString;
}
/**
* Evaluates the constraint for parameter $other
*
* If $returnResult is set to false (the default), an exception is thrown
* in case of a failure. null is returned otherwise.
*
* If $returnResult is true, the result of the evaluation is returned as
* a boolean value instead: true in case of success, false in case of a
* failure.
*
* @param mixed $other Value or object to evaluate.
* @param string $description Additional information about the test
* @param bool $returnResult Whether to return a result or throw an exception
*
* @throws ExpectationFailedException
* @return mixed
*/
public function evaluate($other, $description = '', $returnResult = false)
{
$success = !$this->constraint->evaluate($other, $description, true);
if ($returnResult) {
return $success;
}
if (!$success) {
$this->fail($other, $description);
}
}
/**
* Returns the description of the failure
*
* The beginning of failure messages is "Failed asserting that" in most
* cases. This method should return the second part of that sentence.
*
* @param mixed $other Evaluated value or object.
*
* @return string
*/
protected function failureDescription($other)
{
switch (\get_class($this->constraint)) {
case 'PHPUnit\Framework\Constraint\LogicalAnd':
case 'PHPUnit\Framework\Constraint\LogicalNot':
case 'PHPUnit\Framework\Constraint\LogicalOr':
return 'not( ' . $this->constraint->failureDescription($other) . ' )';
default:
return self::negate(
$this->constraint->failureDescription($other)
);
}
}
/**
* Returns a string representation of the constraint.
*
* @return string
*/
public function toString()
{
switch (\get_class($this->constraint)) {
case 'PHPUnit\Framework\Constraint\LogicalAnd':
case 'PHPUnit\Framework\Constraint\LogicalNot':
case 'PHPUnit\Framework\Constraint\LogicalOr':
return 'not( ' . $this->constraint->toString() . ' )';
default:
return self::negate(
$this->constraint->toString()
);
}
}
/**
* Counts the number of constraint elements.
*
* @return int
*/
public function count()
{
return \count($this->constraint);
}
}
}
}

View File

@ -50,7 +50,8 @@ class StrictConfirmationQuestionTest extends TestCase
{
list($input, $dialog) = $this->createInput($answer."\n");
$this->setExpectedException('InvalidArgumentException', 'Please answer yes, y, no, or n.');
self::expectException('InvalidArgumentException');
self::expectExceptionMessage('Please answer yes, y, no, or n.');
$question = new StrictConfirmationQuestion('Do you like French fries?');
$question->setMaxAttempts(1);

View File

@ -19,7 +19,7 @@ use Composer\Package\BasePackage;
class ArtifactRepositoryTest extends TestCase
{
public function setUp()
public function setUp(): void
{
parent::setUp();
if (!extension_loaded('zip')) {

View File

@ -37,7 +37,7 @@ class ComposerRepositoryTest extends TestCase
);
$repository = $this->getMockBuilder('Composer\Repository\ComposerRepository')
->setMethods(array('loadRootServerFile', 'createPackages'))
->onlyMethods(array('loadRootServerFile', 'createPackages'))
->setConstructorArgs(array(
$repoConfig,
new NullIO,
@ -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));
@ -111,7 +111,7 @@ class ComposerRepositoryTest extends TestCase
$this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(),
$this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock(),
))
->setMethods(array('fetchFile'))
->onlyMethods(array('fetchFile'))
->getMock();
$cache = $this->getMockBuilder('Composer\Cache')->disableOriginalConstructor()->getMock();
@ -156,7 +156,6 @@ class ComposerRepositoryTest extends TestCase
),
)));
$versionParser = new VersionParser();
$reflMethod = new \ReflectionMethod($repo, 'whatProvides');
$reflMethod->setAccessible(true);
$packages = $reflMethod->invoke($repo, 'a');
@ -181,16 +180,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 +210,7 @@ class ComposerRepositoryTest extends TestCase
public function testSearchWithAbandonedPackages()
{
$repoConfig = array(
'url' => 'http://2.example.org',
'url' => 'http://example.org',
);
$result = array(
@ -223,15 +228,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 +325,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

@ -129,7 +129,7 @@ class CompositeRepositoryTest extends TestCase
/**
* @dataProvider provideMethodCalls
*
* @param string $method
* @param string $method
* @param mixed[] $args
*/
public function testNoRepositories($method, $args)

View File

@ -48,7 +48,7 @@ class FilesystemRepositoryTest extends TestCase
public function testCorruptedRepositoryFile()
{
$this->setExpectedException('Composer\Repository\InvalidRepositoryException');
self::expectException('Composer\Repository\InvalidRepositoryException');
$json = $this->createJsonFileMock();
$repository = new FilesystemRepository($json);

View File

@ -25,7 +25,7 @@ class FilterRepositoryTest extends TestCase
*/
private $arrayRepo;
public function setUp()
public function setUp(): void
{
$this->arrayRepo = new ArrayRepository();
$this->arrayRepo->addPackage($this->getPackage('foo/aaa', '1.0.0'));

View File

@ -45,7 +45,7 @@ class InstalledRepositoryTest extends TestCase
{
$arrayRepoOne = new ArrayRepository;
$this->setExpectedException('LogicException');
self::expectException('LogicException');
new InstalledRepository(array($arrayRepoOne));
}

View File

@ -19,7 +19,7 @@ class PathRepositoryTest extends TestCase
{
public function testLoadPackageFromFileSystemWithIncorrectPath()
{
$this->setExpectedException('RuntimeException');
self::expectException('RuntimeException');
$ioInterface = $this->getMockBuilder('Composer\IO\IOInterface')
->getMock();

View File

@ -118,7 +118,7 @@ class PlatformRepositoryTest extends TestCase
*
* @param array<string, mixed> $constants
* @param array<string, string> $packages
* @param array<string, mixed> $functions
* @param list<array{string, list<string>, string|bool}> $functions
*/
public function testPhpVersion(array $constants, array $packages, array $functions = array())
{
@ -1086,10 +1086,11 @@ Linked Version => 1.2.11',
* @param string|string[] $extensions
* @param string|null $info
* @param array<string,string|false> $expectations
* @param array<string,mixed> $functions
* @param array<string,mixed> $constants
* @param array<string,class-string> $classDefinitions
* @param list<mixed> $functions
* @param list<mixed> $constants
* @param list<mixed> $classDefinitions
*/
public function testLibraryInformation(
$extensions,
$info,

View File

@ -21,13 +21,14 @@ class RepositoryManagerTest extends TestCase
/** @var string */
protected $tmpdir;
public function setUp()
public function setUp(): void
{
$this->tmpdir = $this->getUniqueTmpDirectory();
}
public function tearDown()
protected function tearDown(): void
{
parent::tearDown();
if (is_dir($this->tmpdir)) {
$fs = new Filesystem();
$fs->removeDirectory($this->tmpdir);
@ -56,17 +57,17 @@ class RepositoryManagerTest extends TestCase
*
* @param string $type
* @param array<string, mixed> $options
* @param string|null $exception
* @param class-string<\Throwable>|null $exception
*/
public function testRepoCreation($type, $options, $exception = null)
public function testRepoCreation($type, $options, ?string $exception = null)
{
if ($exception) {
$this->setExpectedException($exception);
if ($exception !== null) {
self::expectException($exception);
}
$rm = new RepositoryManager(
$this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
$config = $this->getMockBuilder('Composer\Config')->setMethods(array('get'))->getMock(),
$config = $this->getMockBuilder('Composer\Config')->onlyMethods(array('get'))->getMock(),
$this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(),
$this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock()
);
@ -118,7 +119,7 @@ class RepositoryManagerTest extends TestCase
{
$rm = new RepositoryManager(
$this->getMockBuilder('Composer\IO\IOInterface')->getMock(),
$config = $this->getMockBuilder('Composer\Config')->setMethods(array('get'))->getMock(),
$config = $this->getMockBuilder('Composer\Config')->onlyMethods(array('get'))->getMock(),
$this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(),
$this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock()
);

Some files were not shown because too many files have changed in this diff Show More