Skip to content

Commit

Permalink
minor #5269 Prep work to migrate to PHPUnit 9.x (sanmai, keradus)
Browse files Browse the repository at this point in the history
This PR was squashed before being merged into the 2.16 branch.

Discussion
----------

Prep work to migrate to PHPUnit 9.x

**This is a fully backward-compatible change.**

The general idea is to make the package testable under PHP 5.6 - 7.x - 8.0. This requires using both PHPUnit 5.x and 9.x, because only the last works correctly under PHP 8 (as is - collects coverage report).

But PHPUnit 9 has quite a lot of legacy methods removed, and PHPUnit 8 has these methods but with `void` return type. Therefore implementing these methods straight away is a no-go. This can be [with a version-dependent trait](https://github.com/symfony/phpunit-bridge/blob/5.x/Legacy/PolyfillAssertTrait.php), but for a small handful of functions used here it easier to do this by overloading them from `__call` and `__callStatic`. This is where `DeprecatedTestMethods` trait comes into play.

And there are also `setUp(): void` etc. which are **not** taken care in this PR.

- There's also above-mentioned `PolyfillAssertTrait` from `symfony/phpunit-bridge`, but it is tagged `@internal` so it's a risky game to use it.
- And there's also [phpunitgoodpractices/polyfill](https://packagist.org/packages/phpunitgoodpractices/polyfill), but it should be trivial to switch to any of those down the line.

---
Extracted from #5262 (it handles  `setUp(): void` among other things)

Commits
-------

3d8284e Prep work to migrate to PHPUnit 9.x
  • Loading branch information
keradus committed Dec 1, 2020
2 parents e3d378f + 3d8284e commit 694dfb7
Show file tree
Hide file tree
Showing 67 changed files with 157 additions and 153 deletions.
1 change: 1 addition & 0 deletions .composer-require-checker.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"PHPUnit\\Framework\\Constraint\\IsIdentical",
"PHPUnit\\Framework\\TestCase",
"PHPUnit\\Runner\\Version",
"PHPUnitGoodPractices\\Polyfill\\PolyfillTrait",
"PHPUnitGoodPractices\\Traits\\ExpectationViaCodeOverAnnotationTrait",
"PHPUnitGoodPractices\\Traits\\ExpectOverSetExceptionTrait",
"PHPUnitGoodPractices\\Traits\\IdentityOverEqualityTrait",
Expand Down
2 changes: 1 addition & 1 deletion .php_cs.dist
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ $config = PhpCsFixer\Config::create()
->setRiskyAllowed(true)
->setRules([
'@PHP56Migration' => true,
'@PHPUnit60Migration:risky' => true,
'@PHPUnit75Migration:risky' => true,
'@PhpCsFixer' => true,
'@PhpCsFixer:risky' => true,
'header_comment' => ['header' => $header],
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"php-cs-fixer/phpunit-constraint-isidenticalstring": "^1.2",
"php-cs-fixer/phpunit-constraint-xmlmatchesxsd": "^1.2.1",
"phpunit/phpunit": "^5.7.27 || ^6.5.14 || ^7.1",
"phpunitgoodpractices/polyfill": "^1.5",
"phpunitgoodpractices/traits": "^1.9.1",
"symfony/phpunit-bridge": "^5.1",
"symfony/yaml": "^3.0 || ^4.0 || ^5.0"
Expand Down
6 changes: 3 additions & 3 deletions tests/AutoReview/ProjectCodeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -261,8 +261,8 @@ static function (\ReflectionMethod $reflectionMethod) use ($reflectionClass) {
}

foreach ($publicMethods as $method) {
static::assertRegExp(
'/^(test|provide|setUpBeforeClass$|tearDownAfterClass$)/',
static::assertMatchesRegularExpression(
'/^(test|expect|provide|setUpBeforeClass$|tearDownAfterClass$)/',
$method->getName(),
sprintf('Public method "%s::%s" is not properly named.', $reflectionClass->getName(), $method->getName())
);
Expand All @@ -285,7 +285,7 @@ public function testThatDataProvidersAreCorrectlyNamed($testClassName)
}

foreach ($usedDataProviderMethodNames as $dataProviderMethodName) {
static::assertRegExp('/^provide[A-Z]\S+Cases$/', $dataProviderMethodName, sprintf(
static::assertMatchesRegularExpression('/^provide[A-Z]\S+Cases$/', $dataProviderMethodName, sprintf(
'Data provider in "%s" with name "%s" is not correctly named.',
$testClassName,
$dataProviderMethodName
Expand Down
8 changes: 4 additions & 4 deletions tests/Cache/FileHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public function testWriteThrowsIOExceptionIfFileCanNotBeWritten()
$file = __DIR__.'/non-existent-directory/.php_cs.cache';

$this->expectException(\Symfony\Component\Filesystem\Exception\IOException::class);
$this->expectExceptionMessageRegExp(sprintf(
$this->expectExceptionMessageMatches(sprintf(
'#^Directory of cache file "%s" does not exists.#',
preg_quote($file, '#')
));
Expand Down Expand Up @@ -135,7 +135,7 @@ public function testWriteCacheToDirectory()
$handler = new FileHandler($dir);

$this->expectException(\Symfony\Component\Filesystem\Exception\IOException::class);
$this->expectExceptionMessageRegExp(sprintf(
$this->expectExceptionMessageMatches(sprintf(
'#^%s$#',
preg_quote('Cannot write cache file "'.realpath($dir).'" as the location exists as directory.', '#')
));
Expand All @@ -153,7 +153,7 @@ public function testWriteCacheToNonWriteableFile()
$handler = new FileHandler($file);

$this->expectException(\Symfony\Component\Filesystem\Exception\IOException::class);
$this->expectExceptionMessageRegExp(sprintf(
$this->expectExceptionMessageMatches(sprintf(
'#^%s$#',
preg_quote('Cannot write to file "'.realpath($file).'" as it is not writable.', '#')
));
Expand All @@ -166,7 +166,7 @@ public function testWriteCacheFilePermissions()
$file = __DIR__.'/../Fixtures/cache-file-handler/rw_cache.test';
@unlink($file);

static::assertFileNotExists($file);
static::assertFileDoesNotExist($file);

$handler = new FileHandler($file);
$handler->write(new Cache($this->createSignature()));
Expand Down
8 changes: 4 additions & 4 deletions tests/ConfigTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public function testConfigRulesUsingSeparateMethod()
new ToolInfo()
);

static::assertArraySubset(
static::assertSame(
[
'cast_spaces' => true,
'braces' => true,
Expand All @@ -65,7 +65,7 @@ public function testConfigRulesUsingJsonMethod()
new ToolInfo()
);

static::assertArraySubset(
static::assertSame(
[
'array_syntax' => [
'syntax' => 'short',
Expand Down Expand Up @@ -190,7 +190,7 @@ public function testThatMutatorHasFluentInterface()
public function testRegisterCustomFixersWithInvalidArgument()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessageRegExp('/^Argument must be an array or a Traversable, got "\w+"\.$/');
$this->expectExceptionMessageMatches('/^Argument must be an array or a Traversable, got "\w+"\.$/');

$config = new Config();
$config->registerCustomFixers('foo');
Expand Down Expand Up @@ -257,7 +257,7 @@ public function testSetInvalidFinder()
$config = new Config();

$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessageRegExp('/^Argument must be an array or a Traversable, got "integer"\.$/');
$this->expectExceptionMessageMatches('/^Argument must be an array or a Traversable, got "integer"\.$/');

$config->setFinder(123);
}
Expand Down
10 changes: 5 additions & 5 deletions tests/Console/Command/DescribeCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ public function testExecuteWithUnknownRuleName()
$commandTester = new CommandTester($command);

$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessageRegExp('#^Rule "Foo/bar" not found\.$#');
$this->expectExceptionMessageMatches('#^Rule "Foo/bar" not found\.$#');
$commandTester->execute([
'command' => $command->getName(),
'name' => 'Foo/bar',
Expand All @@ -146,7 +146,7 @@ public function testExecuteWithUnknownSetName()
$commandTester = new CommandTester($command);

$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessageRegExp('#^Set "@NoSuchSet" not found\.$#');
$this->expectExceptionMessageMatches('#^Set "@NoSuchSet" not found\.$#');
$commandTester->execute([
'command' => $command->getName(),
'name' => '@NoSuchSet',
Expand All @@ -163,7 +163,7 @@ public function testExecuteWithoutName()
$commandTester = new CommandTester($command);

$this->expectException(\RuntimeException::class);
$this->expectExceptionMessageRegExp('/^Not enough arguments( \(missing: "name"\))?\.$/');
$this->expectExceptionMessageMatches('/^Not enough arguments( \(missing: "name"\))?\.$/');
$commandTester->execute([
'command' => $command->getName(),
]);
Expand All @@ -172,7 +172,7 @@ public function testExecuteWithoutName()
public function testGetAlternativeSuggestion()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessageRegExp('#^Rule "Foo2/bar" not found\. Did you mean "Foo/bar"\?$#');
$this->expectExceptionMessageMatches('#^Rule "Foo2/bar" not found\. Did you mean "Foo/bar"\?$#');
$this->execute('Foo2/bar', false);
}

Expand Down Expand Up @@ -205,7 +205,7 @@ public function testFixerClassNameIsExposedWhenVerbose()
]
);

static::assertContains(\get_class($mock), $commandTester->getDisplay(true));
static::assertStringContainsString(\get_class($mock), $commandTester->getDisplay(true));
}

/**
Expand Down
2 changes: 1 addition & 1 deletion tests/Console/Command/FixCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public function testEmptyRulesValue()
$this->expectException(
\PhpCsFixer\ConfigurationException\InvalidConfigurationException::class
);
$this->expectExceptionMessageRegExp(
$this->expectExceptionMessageMatches(
'#^Empty rules value is not allowed\.$#'
);

Expand Down
12 changes: 6 additions & 6 deletions tests/Console/ConfigurationResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ final class ConfigurationResolverTest extends TestCase
public function testSetOptionWithUndefinedOption()
{
$this->expectException(InvalidConfigurationException::class);
$this->expectExceptionMessageRegExp('/^Unknown option name: "foo"\.$/');
$this->expectExceptionMessageMatches('/^Unknown option name: "foo"\.$/');

$this->createConfigurationResolver(['foo' => 'bar']);
}
Expand Down Expand Up @@ -275,7 +275,7 @@ public function provideResolveConfigFileDefaultCases()
public function testResolveConfigFileChooseFileWithInvalidFile()
{
$this->expectException(InvalidConfigurationException::class);
$this->expectExceptionMessageRegExp(
$this->expectExceptionMessageMatches(
'#^The config file: ".+[\/\\\]Fixtures[\/\\\]ConfigurationResolverConfigFile[\/\\\]case_5[\/\\\]\.php_cs\.dist" does not return a "PhpCsFixer\\\ConfigInterface" instance\. Got: "string"\.$#'
);

Expand All @@ -289,7 +289,7 @@ public function testResolveConfigFileChooseFileWithInvalidFile()
public function testResolveConfigFileChooseFileWithInvalidFormat()
{
$this->expectException(InvalidConfigurationException::class);
$this->expectExceptionMessageRegExp('/^The format "xls" is not defined, supported are "checkstyle", "gitlab", "json", "junit", "txt", "xml"\.$/');
$this->expectExceptionMessageMatches('/^The format "xls" is not defined, supported are "checkstyle", "gitlab", "json", "junit", "txt", "xml"\.$/');

$dirBase = $this->getFixtureDir();

Expand All @@ -301,7 +301,7 @@ public function testResolveConfigFileChooseFileWithInvalidFormat()
public function testResolveConfigFileChooseFileWithPathArrayWithoutConfig()
{
$this->expectException(InvalidConfigurationException::class);
$this->expectExceptionMessageRegExp('/^For multiple paths config parameter is required\.$/');
$this->expectExceptionMessageMatches('/^For multiple paths config parameter is required\.$/');

$dirBase = $this->getFixtureDir();

Expand Down Expand Up @@ -1160,7 +1160,7 @@ public function testResolveUnknownDiffer()
]);

$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessageRegExp('#^"diff\-format" must be any of "null", "sbd", "udiff", got "XXX"\.$#');
$this->expectExceptionMessageMatches('#^"diff\-format" must be any of "null", "sbd", "udiff", got "XXX"\.$#');

$resolver->getDiffer();
}
Expand Down Expand Up @@ -1210,7 +1210,7 @@ public function testWithEmptyRules()
$resolver = $this->createConfigurationResolver(['rules' => '']);

$this->expectException(InvalidConfigurationException::class);
$this->expectExceptionMessageRegExp('/^Empty rules value is not allowed\.$/');
$this->expectExceptionMessageMatches('/^Empty rules value is not allowed\.$/');

$resolver->getRules();
}
Expand Down
10 changes: 5 additions & 5 deletions tests/Console/Output/ErrorOutputTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -134,13 +134,13 @@ public function testLintingExceptionOutputsAppliedFixersAndDiff()

$displayed = $this->readFullStreamOutput($output);

static::assertContains($fixerName, $displayed);
static::assertContains($diffSpecificContext, $displayed);
static::assertStringContainsString($fixerName, $displayed);
static::assertStringContainsString($diffSpecificContext, $displayed);

static::assertContains($noDiffLintFixerName, $displayed);
static::assertStringContainsString($noDiffLintFixerName, $displayed);

static::assertNotContains($invalidErrorFixerName, $displayed);
static::assertNotContains($invalidDiff, $displayed);
static::assertStringNotContainsString($invalidErrorFixerName, $displayed);
static::assertStringNotContainsString($invalidDiff, $displayed);
}

/**
Expand Down
4 changes: 2 additions & 2 deletions tests/DocBlock/AnnotationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -460,9 +460,9 @@ public function testSetTypesOnBadTag()
public function testGetTagsWithTypes()
{
$tags = Annotation::getTagsWithTypes();
static::assertInternalType('array', $tags);
static::assertIsArray($tags);
foreach ($tags as $tag) {
static::assertInternalType('string', $tag);
static::assertIsString($tag);
static::assertNotEmpty($tag);
}
}
Expand Down
12 changes: 6 additions & 6 deletions tests/DocBlock/DocBlockTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public function testGetLines()
{
$doc = new DocBlock(self::$sample);

static::assertInternalType('array', $doc->getLines());
static::assertIsArray($doc->getLines());
static::assertCount(15, $doc->getLines());

foreach ($doc->getLines() as $index => $line) {
Expand All @@ -79,7 +79,7 @@ public function testGetAnnotations()
{
$doc = new DocBlock(self::$sample);

static::assertInternalType('array', $doc->getAnnotations());
static::assertIsArray($doc->getAnnotations());
static::assertCount(5, $doc->getAnnotations());

foreach ($doc->getAnnotations() as $index => $annotations) {
Expand All @@ -96,7 +96,7 @@ public function testGetAnnotationsOfTypeParam()

$annotations = $doc->getAnnotationsOfType('param');

static::assertInternalType('array', $annotations);
static::assertIsArray($annotations);
static::assertCount(3, $annotations);

$first = ' * @param string $hello
Expand All @@ -118,7 +118,7 @@ public function testGetAnnotationsOfTypeThrows()

$annotations = $doc->getAnnotationsOfType('throws');

static::assertInternalType('array', $annotations);
static::assertIsArray($annotations);
static::assertCount(1, $annotations);

$content = ' * @throws \Exception asdnjkasd
Expand All @@ -135,7 +135,7 @@ public function testGetAnnotationsOfTypeReturn()

$annotations = $doc->getAnnotationsOfType('return');

static::assertInternalType('array', $annotations);
static::assertIsArray($annotations);
static::assertCount(1, $annotations);

$content = ' * @return void
Expand All @@ -150,7 +150,7 @@ public function testGetAnnotationsOfTypeFoo()

$annotations = $doc->getAnnotationsOfType('foo');

static::assertInternalType('array', $annotations);
static::assertIsArray($annotations);
static::assertCount(0, $annotations);
}

Expand Down
6 changes: 3 additions & 3 deletions tests/Error/ErrorsManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public function testThatCanReportAndRetrieveInvalidErrors()

$errors = $errorsManager->getInvalidErrors();

static::assertInternalType('array', $errors);
static::assertIsArray($errors);
static::assertCount(1, $errors);
static::assertSame($error, array_shift($errors));

Expand All @@ -71,7 +71,7 @@ public function testThatCanReportAndRetrieveExceptionErrors()

$errors = $errorsManager->getExceptionErrors();

static::assertInternalType('array', $errors);
static::assertIsArray($errors);
static::assertCount(1, $errors);
static::assertSame($error, array_shift($errors));

Expand All @@ -94,7 +94,7 @@ public function testThatCanReportAndRetrieveInvalidFileErrors()

$errors = $errorsManager->getLintErrors();

static::assertInternalType('array', $errors);
static::assertIsArray($errors);
static::assertCount(1, $errors);
static::assertSame($error, array_shift($errors));

Expand Down
2 changes: 1 addition & 1 deletion tests/FileReaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public function testThrowsExceptionOnFail()
$reader = new FileReader();

$this->expectException(\RuntimeException::class);
$this->expectExceptionMessageRegExp('#^Failed to read content from "'.preg_quote($nonExistentFilePath, '#').'.*$#');
$this->expectExceptionMessageMatches('#^Failed to read content from "'.preg_quote($nonExistentFilePath, '#').'.*$#');

$reader->read($nonExistentFilePath);
}
Expand Down
14 changes: 7 additions & 7 deletions tests/FileRemovalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public function testShutdownRemovesObservedFilesSetup()
*/
public function testShutdownRemovesObservedFiles()
{
static::assertFileNotExists(sys_get_temp_dir().'/cs_fixer_foo.php');
static::assertFileDoesNotExist(sys_get_temp_dir().'/cs_fixer_foo.php');
static::assertFileExists(sys_get_temp_dir().'/cs_fixer_bar.php');
}

Expand All @@ -82,8 +82,8 @@ public function testCleanRemovesObservedFiles()

$fileRemoval->clean();

static::assertFileNotExists($fs->url().'/foo.php');
static::assertFileNotExists($fs->url().'/baz.php');
static::assertFileDoesNotExist($fs->url().'/foo.php');
static::assertFileDoesNotExist($fs->url().'/baz.php');
static::assertFileExists($fs->url().'/bar.php');
}

Expand All @@ -98,8 +98,8 @@ public function testDestructRemovesObservedFiles()

$fileRemoval->__destruct();

static::assertFileNotExists($fs->url().'/foo.php');
static::assertFileNotExists($fs->url().'/baz.php');
static::assertFileDoesNotExist($fs->url().'/foo.php');
static::assertFileDoesNotExist($fs->url().'/baz.php');
static::assertFileExists($fs->url().'/bar.php');
}

Expand All @@ -114,7 +114,7 @@ public function testDeleteObservedFile()

$fileRemoval->delete($fs->url().'/foo.php');

static::assertFileNotExists($fs->url().'/foo.php');
static::assertFileDoesNotExist($fs->url().'/foo.php');
static::assertFileExists($fs->url().'/baz.php');
}

Expand All @@ -126,7 +126,7 @@ public function testDeleteNonObservedFile()

$fileRemoval->delete($fs->url().'/foo.php');

static::assertFileNotExists($fs->url().'/foo.php');
static::assertFileDoesNotExist($fs->url().'/foo.php');
}

private function getMockFileSystem()
Expand Down
Loading

0 comments on commit 694dfb7

Please sign in to comment.