updated composer

This commit is contained in:
2021-05-18 13:47:03 +00:00
parent e248cd036c
commit ba92152daa
1187 changed files with 20804 additions and 22320 deletions

View File

@@ -2,6 +2,20 @@
All notable changes of the PHPUnit 8.5 release series are documented in this file using the [Keep a CHANGELOG](https://keepachangelog.com/) principles.
## [8.5.15] - 2021-03-17
### Fixed
* [#4591](https://github.com/sebastianbergmann/phpunit/issues/4591): TeamCity logger logs warnings as test failures
## [8.5.14] - 2021-01-17
### Fixed
* [#4535](https://github.com/sebastianbergmann/phpunit/issues/4535): `getMockFromWsdl()` does not handle methods that do not have parameters correctly
* [#4572](https://github.com/sebastianbergmann/phpunit/issues/4572): Schema validation does not work with `%xx` sequences in path to `phpunit.xsd`
* [#4575](https://github.com/sebastianbergmann/phpunit/issues/4575): PHPUnit 8.5 incompatibility with PHP 8.1
## [8.5.13] - 2020-12-01
### Fixed
@@ -116,6 +130,8 @@ All notable changes of the PHPUnit 8.5 release series are documented in this fil
* [#3967](https://github.com/sebastianbergmann/phpunit/issues/3967): Cannot double interface that extends interface that extends `\Throwable`
* [#3968](https://github.com/sebastianbergmann/phpunit/pull/3968): Test class run in a separate PHP process are passing when `exit` called inside
[8.5.15]: https://github.com/sebastianbergmann/phpunit/compare/8.5.14...8.5.15
[8.5.14]: https://github.com/sebastianbergmann/phpunit/compare/8.5.13...8.5.14
[8.5.13]: https://github.com/sebastianbergmann/phpunit/compare/8.5.12...8.5.13
[8.5.12]: https://github.com/sebastianbergmann/phpunit/compare/8.5.11...8.5.12
[8.5.11]: https://github.com/sebastianbergmann/phpunit/compare/8.5.10...8.5.11

View File

@@ -1,6 +1,6 @@
PHPUnit
Copyright (c) 2001-2020, Sebastian Bergmann <sebastian@phpunit.de>.
Copyright (c) 2001-2021, Sebastian Bergmann <sebastian@phpunit.de>.
All rights reserved.
Redistribution and use in source and binary forms, with or without

View File

@@ -13,7 +13,7 @@ if (version_compare('7.2.0', PHP_VERSION, '>')) {
fwrite(
STDERR,
sprintf(
'This version of PHPUnit is supported on PHP 7.2, PHP 7.3, and PHP 7.4.' . PHP_EOL .
'This version of PHPUnit requires PHP >= 7.2.' . PHP_EOL .
'You are using PHP %s (%s).' . PHP_EOL,
PHP_VERSION,
PHP_BINARY

View File

@@ -9,9 +9,11 @@
*/
namespace PHPUnit;
use Throwable;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
interface Exception extends \Throwable
interface Exception extends Throwable
{
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -9,6 +9,8 @@
*/
namespace PHPUnit\Framework\Constraint;
use function array_key_exists;
use function is_array;
use ArrayAccess;
/**
@@ -52,8 +54,8 @@ final class ArrayHasKey extends Constraint
*/
protected function matches($other): bool
{
if (\is_array($other)) {
return \array_key_exists($this->key, $other);
if (is_array($other)) {
return array_key_exists($this->key, $other);
}
if ($other instanceof ArrayAccess) {
@@ -64,7 +66,7 @@ final class ArrayHasKey extends Constraint
}
/**
* Returns the description of the failure
* 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.

View File

@@ -9,8 +9,14 @@
*/
namespace PHPUnit\Framework\Constraint;
use function array_replace_recursive;
use function is_array;
use function iterator_to_array;
use function var_export;
use ArrayObject;
use PHPUnit\Framework\ExpectationFailedException;
use SebastianBergmann\Comparator\ComparisonFailure;
use Traversable;
/**
* Constraint that asserts that the array it is evaluated for has a specified subset.
@@ -41,7 +47,7 @@ final class ArraySubset extends Constraint
}
/**
* Evaluates the constraint for parameter $other
* 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.
@@ -50,8 +56,8 @@ final class ArraySubset extends Constraint
* a boolean value instead: true in case of success, false in case of a
* failure.
*
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws ExpectationFailedException
*/
public function evaluate($other, string $description = '', bool $returnResult = false)
{
@@ -60,7 +66,7 @@ final class ArraySubset extends Constraint
$other = $this->toArray($other);
$this->subset = $this->toArray($this->subset);
$patched = \array_replace_recursive($other, $this->subset);
$patched = array_replace_recursive($other, $this->subset);
if ($this->strict) {
$result = $other === $patched;
@@ -76,8 +82,8 @@ final class ArraySubset extends Constraint
$f = new ComparisonFailure(
$patched,
$other,
\var_export($patched, true),
\var_export($other, true)
var_export($patched, true),
var_export($other, true)
);
$this->fail($other, $description, $f);
@@ -95,7 +101,7 @@ final class ArraySubset extends Constraint
}
/**
* Returns the description of the failure
* 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.
@@ -111,16 +117,16 @@ final class ArraySubset extends Constraint
private function toArray(iterable $other): array
{
if (\is_array($other)) {
if (is_array($other)) {
return $other;
}
if ($other instanceof \ArrayObject) {
if ($other instanceof ArrayObject) {
return $other->getArrayCopy();
}
if ($other instanceof \Traversable) {
return \iterator_to_array($other);
if ($other instanceof Traversable) {
return iterator_to_array($other);
}
// Keep BC even if we know that array would not be the expected one

View File

@@ -31,7 +31,7 @@ final class Attribute extends Composite
}
/**
* Evaluates the constraint for parameter $other
* 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.
@@ -40,9 +40,9 @@ final class Attribute extends Composite
* a boolean value instead: true in case of success, false in case of a
* failure.
*
* @throws ExpectationFailedException
* @throws \PHPUnit\Framework\Exception
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws ExpectationFailedException
*/
public function evaluate($other, string $description = '', bool $returnResult = false)
{
@@ -65,7 +65,7 @@ final class Attribute extends Composite
}
/**
* Returns the description of the failure
* 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.

View File

@@ -11,14 +11,19 @@ namespace PHPUnit\Framework\Constraint;
/**
* Constraint that evaluates against a specified closure.
*
* @psalm-template CallbackInput of mixed
*/
final class Callback extends Constraint
{
/**
* @var callable
*
* @psalm-var callable(CallbackInput $input): bool
*/
private $callback;
/** @psalm-param callable(CallbackInput $input): bool $callback */
public function __construct(callable $callback)
{
$this->callback = $callback;
@@ -37,9 +42,11 @@ final class Callback extends Constraint
* constraint is met, false otherwise.
*
* @param mixed $other value or object to evaluate
*
* @psalm-param CallbackInput $other
*/
protected function matches($other): bool
{
return \call_user_func($this->callback, $other);
return ($this->callback)($other);
}
}

View File

@@ -9,7 +9,12 @@
*/
namespace PHPUnit\Framework\Constraint;
use function get_class;
use function is_object;
use function sprintf;
use PHPUnit\Framework\Exception;
use ReflectionClass;
use ReflectionException;
/**
* Constraint that asserts that the class it is evaluated for has a given
@@ -34,7 +39,7 @@ class ClassHasAttribute extends Constraint
*/
public function toString(): string
{
return \sprintf(
return sprintf(
'has attribute "%s"',
$this->attributeName
);
@@ -49,9 +54,9 @@ class ClassHasAttribute extends Constraint
protected function matches($other): bool
{
try {
return (new \ReflectionClass($other))->hasProperty($this->attributeName);
return (new ReflectionClass($other))->hasProperty($this->attributeName);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
@@ -62,7 +67,7 @@ class ClassHasAttribute extends Constraint
}
/**
* Returns the description of the failure
* 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.
@@ -71,10 +76,10 @@ class ClassHasAttribute extends Constraint
*/
protected function failureDescription($other): string
{
return \sprintf(
return sprintf(
'%sclass "%s" %s',
\is_object($other) ? 'object of ' : '',
\is_object($other) ? \get_class($other) : $other,
is_object($other) ? 'object of ' : '',
is_object($other) ? get_class($other) : $other,
$this->toString()
);
}

View File

@@ -9,7 +9,10 @@
*/
namespace PHPUnit\Framework\Constraint;
use function sprintf;
use PHPUnit\Framework\Exception;
use ReflectionClass;
use ReflectionException;
/**
* Constraint that asserts that the class it is evaluated for has a given
@@ -24,7 +27,7 @@ final class ClassHasStaticAttribute extends ClassHasAttribute
*/
public function toString(): string
{
return \sprintf(
return sprintf(
'has static attribute "%s"',
$this->attributeName()
);
@@ -39,13 +42,13 @@ final class ClassHasStaticAttribute extends ClassHasAttribute
protected function matches($other): bool
{
try {
$class = new \ReflectionClass($other);
$class = new ReflectionClass($other);
if ($class->hasProperty($this->attributeName())) {
return $class->getProperty($this->attributeName())->isStatic();
}
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),

View File

@@ -9,6 +9,7 @@
*/
namespace PHPUnit\Framework\Constraint;
use function count;
use PHPUnit\Framework\ExpectationFailedException;
/**
@@ -28,7 +29,7 @@ abstract class Composite extends Constraint
}
/**
* Evaluates the constraint for parameter $other
* 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.
@@ -37,8 +38,8 @@ abstract class Composite extends Constraint
* a boolean value instead: true in case of success, false in case of a
* failure.
*
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws ExpectationFailedException
*/
public function evaluate($other, string $description = '', bool $returnResult = false)
{
@@ -58,7 +59,7 @@ abstract class Composite extends Constraint
*/
public function count(): int
{
return \count($this->innerConstraint);
return count($this->innerConstraint);
}
protected function innerConstraint(): Constraint

View File

@@ -9,6 +9,7 @@
*/
namespace PHPUnit\Framework\Constraint;
use function sprintf;
use Countable;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\SelfDescribing;
@@ -26,7 +27,7 @@ abstract class Constraint implements Countable, SelfDescribing
private $exporter;
/**
* Evaluates the constraint for parameter $other
* 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.
@@ -35,8 +36,8 @@ abstract class Constraint implements Countable, SelfDescribing
* a boolean value instead: true in case of success, false in case of a
* failure.
*
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws ExpectationFailedException
*/
public function evaluate($other, string $description = '', bool $returnResult = false)
{
@@ -87,20 +88,20 @@ abstract class Constraint implements Countable, SelfDescribing
}
/**
* Throws an exception for the given compared value and test description
* Throws an exception for the given compared value and test description.
*
* @param mixed $other evaluated value or object
* @param string $description Additional information about the test
* @param ComparisonFailure $comparisonFailure
*
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws ExpectationFailedException
*
* @psalm-return never-return
*/
protected function fail($other, $description, ComparisonFailure $comparisonFailure = null): void
{
$failureDescription = \sprintf(
$failureDescription = sprintf(
'Failed asserting that %s.',
$this->failureDescription($other)
);
@@ -122,7 +123,7 @@ abstract class Constraint implements Countable, SelfDescribing
}
/**
* Return additional failure description where needed
* Return additional failure description where needed.
*
* The function can be overridden to provide additional failure
* information like a diff
@@ -135,7 +136,7 @@ abstract class Constraint implements Countable, SelfDescribing
}
/**
* Returns the description of the failure
* 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.

View File

@@ -9,7 +9,12 @@
*/
namespace PHPUnit\Framework\Constraint;
use function count;
use function is_array;
use function iterator_count;
use function sprintf;
use Countable;
use EmptyIterator;
use Generator;
use Iterator;
use IteratorAggregate;
@@ -29,7 +34,7 @@ class Count extends Constraint
public function toString(): string
{
return \sprintf(
return sprintf(
'count matches %d',
$this->expectedCount
);
@@ -49,11 +54,11 @@ class Count extends Constraint
*/
protected function getCountOf($other): ?int
{
if ($other instanceof Countable || \is_array($other)) {
return \count($other);
if ($other instanceof Countable || is_array($other)) {
return count($other);
}
if ($other instanceof \EmptyIterator) {
if ($other instanceof EmptyIterator) {
return 0;
}
@@ -69,11 +74,11 @@ class Count extends Constraint
}
if (!$iterator instanceof Iterator) {
return \iterator_count($iterator);
return iterator_count($iterator);
}
$key = $iterator->key();
$count = \iterator_count($iterator);
$count = iterator_count($iterator);
// Manually rewind $iterator to previous key, since iterator_count
// moves pointer.
@@ -114,7 +119,7 @@ class Count extends Constraint
*/
protected function failureDescription($other): string
{
return \sprintf(
return sprintf(
'actual size %d matches expected size %d',
$this->getCountOf($other),
$this->expectedCount

View File

@@ -9,6 +9,9 @@
*/
namespace PHPUnit\Framework\Constraint;
use function is_dir;
use function sprintf;
/**
* Constraint that checks if the directory(name) that it is evaluated for exists.
*
@@ -32,11 +35,11 @@ final class DirectoryExists extends Constraint
*/
protected function matches($other): bool
{
return \is_dir($other);
return is_dir($other);
}
/**
* Returns the description of the failure
* 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.
@@ -45,7 +48,7 @@ final class DirectoryExists extends Constraint
*/
protected function failureDescription($other): string
{
return \sprintf(
return sprintf(
'directory "%s" exists',
$other
);

View File

@@ -9,6 +9,8 @@
*/
namespace PHPUnit\Framework\Constraint;
use function get_class;
use function sprintf;
use PHPUnit\Util\Filter;
use Throwable;
@@ -29,7 +31,7 @@ final class Exception extends Constraint
*/
public function toString(): string
{
return \sprintf(
return sprintf(
'exception of type "%s"',
$this->className
);
@@ -47,7 +49,7 @@ final class Exception extends Constraint
}
/**
* Returns the description of the failure
* 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.
@@ -64,15 +66,15 @@ final class Exception extends Constraint
. "\n" . Filter::getFilteredStacktrace($other);
}
return \sprintf(
return sprintf(
'exception of type "%s" matches expected exception "%s"%s',
\get_class($other),
get_class($other),
$this->className,
$message
);
}
return \sprintf(
return sprintf(
'exception of type "%s" is thrown',
$this->className
);

View File

@@ -9,6 +9,9 @@
*/
namespace PHPUnit\Framework\Constraint;
use function sprintf;
use Throwable;
final class ExceptionCode extends Constraint
{
/**
@@ -33,7 +36,7 @@ final class ExceptionCode extends Constraint
* Evaluates the constraint for parameter $other. Returns true if the
* constraint is met, false otherwise.
*
* @param \Throwable $other
* @param Throwable $other
*/
protected function matches($other): bool
{
@@ -41,7 +44,7 @@ final class ExceptionCode extends Constraint
}
/**
* Returns the description of the failure
* 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.
@@ -52,7 +55,7 @@ final class ExceptionCode extends Constraint
*/
protected function failureDescription($other): string
{
return \sprintf(
return sprintf(
'%s is equal to expected exception code %s',
$this->exporter()->export($other->getCode()),
$this->exporter()->export($this->expectedCode)

View File

@@ -9,6 +9,10 @@
*/
namespace PHPUnit\Framework\Constraint;
use function sprintf;
use function strpos;
use Throwable;
final class ExceptionMessage extends Constraint
{
/**
@@ -34,7 +38,7 @@ final class ExceptionMessage extends Constraint
* Evaluates the constraint for parameter $other. Returns true if the
* constraint is met, false otherwise.
*
* @param \Throwable $other
* @param Throwable $other
*/
protected function matches($other): bool
{
@@ -42,11 +46,11 @@ final class ExceptionMessage extends Constraint
return $other->getMessage() === '';
}
return \strpos((string) $other->getMessage(), $this->expectedMessage) !== false;
return strpos((string) $other->getMessage(), $this->expectedMessage) !== false;
}
/**
* Returns the description of the failure
* 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.
@@ -56,13 +60,13 @@ final class ExceptionMessage extends Constraint
protected function failureDescription($other): string
{
if ($this->expectedMessage === '') {
return \sprintf(
return sprintf(
"exception message is empty but is '%s'",
$other->getMessage()
);
}
return \sprintf(
return sprintf(
"exception message '%s' contains '%s'",
$other->getMessage(),
$this->expectedMessage

View File

@@ -9,6 +9,8 @@
*/
namespace PHPUnit\Framework\Constraint;
use function sprintf;
use Exception;
use PHPUnit\Util\RegularExpression as RegularExpressionUtil;
final class ExceptionMessageRegularExpression extends Constraint
@@ -34,8 +36,8 @@ final class ExceptionMessageRegularExpression extends Constraint
*
* @param \PHPUnit\Framework\Exception $other
*
* @throws \Exception
* @throws \PHPUnit\Framework\Exception
* @throws Exception
*/
protected function matches($other): bool
{
@@ -51,7 +53,7 @@ final class ExceptionMessageRegularExpression extends Constraint
}
/**
* Returns the description of the failure
* 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.
@@ -60,7 +62,7 @@ final class ExceptionMessageRegularExpression extends Constraint
*/
protected function failureDescription($other): string
{
return \sprintf(
return sprintf(
"exception message '%s' matches '%s'",
$other->getMessage(),
$this->expectedMessageRegExp

View File

@@ -9,6 +9,9 @@
*/
namespace PHPUnit\Framework\Constraint;
use function file_exists;
use function sprintf;
/**
* Constraint that checks if the file(name) that it is evaluated for exists.
*
@@ -32,11 +35,11 @@ final class FileExists extends Constraint
*/
protected function matches($other): bool
{
return \file_exists($other);
return file_exists($other);
}
/**
* Returns the description of the failure
* 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.
@@ -45,7 +48,7 @@ final class FileExists extends Constraint
*/
protected function failureDescription($other): string
{
return \sprintf(
return sprintf(
'file "%s" exists',
$other
);

View File

@@ -17,7 +17,7 @@ use PHPUnit\Framework\ExpectationFailedException;
final class IsAnything extends Constraint
{
/**
* Evaluates the constraint for parameter $other
* 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.

View File

@@ -9,7 +9,12 @@
*/
namespace PHPUnit\Framework\Constraint;
use function count;
use function gettype;
use function sprintf;
use function strpos;
use Countable;
use EmptyIterator;
/**
* Constraint that checks whether a variable is empty().
@@ -32,19 +37,19 @@ final class IsEmpty extends Constraint
*/
protected function matches($other): bool
{
if ($other instanceof \EmptyIterator) {
if ($other instanceof EmptyIterator) {
return true;
}
if ($other instanceof Countable) {
return \count($other) === 0;
return count($other) === 0;
}
return empty($other);
}
/**
* Returns the description of the failure
* 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.
@@ -53,11 +58,11 @@ final class IsEmpty extends Constraint
*/
protected function failureDescription($other): string
{
$type = \gettype($other);
$type = gettype($other);
return \sprintf(
return sprintf(
'%s %s %s',
\strpos($type, 'a') === 0 || \strpos($type, 'o') === 0 ? 'an' : 'a',
strpos($type, 'a') === 0 || strpos($type, 'o') === 0 ? 'an' : 'a',
$type,
$this->toString()
);

View File

@@ -9,6 +9,10 @@
*/
namespace PHPUnit\Framework\Constraint;
use function is_string;
use function sprintf;
use function strpos;
use function trim;
use PHPUnit\Framework\ExpectationFailedException;
use SebastianBergmann\Comparator\ComparisonFailure;
use SebastianBergmann\Comparator\Factory as ComparatorFactory;
@@ -53,7 +57,7 @@ final class IsEqual extends Constraint
}
/**
* Evaluates the constraint for parameter $other
* 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.
@@ -94,7 +98,7 @@ final class IsEqual extends Constraint
}
throw new ExpectationFailedException(
\trim($description . "\n" . $f->getMessage()),
trim($description . "\n" . $f->getMessage()),
$f
);
}
@@ -111,25 +115,25 @@ final class IsEqual extends Constraint
{
$delta = '';
if (\is_string($this->value)) {
if (\strpos($this->value, "\n") !== false) {
if (is_string($this->value)) {
if (strpos($this->value, "\n") !== false) {
return 'is equal to <text>';
}
return \sprintf(
return sprintf(
"is equal to '%s'",
$this->value
);
}
if ($this->delta != 0) {
$delta = \sprintf(
$delta = sprintf(
' with delta <%F>',
$this->delta
);
}
return \sprintf(
return sprintf(
'is equal to %s%s',
$this->exporter()->export($this->value),
$delta

View File

@@ -9,6 +9,8 @@
*/
namespace PHPUnit\Framework\Constraint;
use function is_finite;
/**
* Constraint that accepts finite.
*/
@@ -30,6 +32,6 @@ final class IsFinite extends Constraint
*/
protected function matches($other): bool
{
return \is_finite($other);
return is_finite($other);
}
}

View File

@@ -9,6 +9,15 @@
*/
namespace PHPUnit\Framework\Constraint;
use function abs;
use function get_class;
use function is_array;
use function is_float;
use function is_infinite;
use function is_nan;
use function is_object;
use function is_string;
use function sprintf;
use PHPUnit\Framework\ExpectationFailedException;
use SebastianBergmann\Comparator\ComparisonFailure;
@@ -41,7 +50,7 @@ final class IsIdentical extends Constraint
}
/**
* Evaluates the constraint for parameter $other
* 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.
@@ -50,15 +59,15 @@ final class IsIdentical extends Constraint
* a boolean value instead: true in case of success, false in case of a
* failure.
*
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws ExpectationFailedException
*/
public function evaluate($other, string $description = '', bool $returnResult = false)
{
if (\is_float($this->value) && \is_float($other) &&
!\is_infinite($this->value) && !\is_infinite($other) &&
!\is_nan($this->value) && !\is_nan($other)) {
$success = \abs($this->value - $other) < self::EPSILON;
if (is_float($this->value) && is_float($other) &&
!is_infinite($this->value) && !is_infinite($other) &&
!is_nan($this->value) && !is_nan($other)) {
$success = abs($this->value - $other) < self::EPSILON;
} else {
$success = $this->value === $other;
}
@@ -71,17 +80,17 @@ final class IsIdentical extends Constraint
$f = null;
// if both values are strings, make sure a diff is generated
if (\is_string($this->value) && \is_string($other)) {
if (is_string($this->value) && is_string($other)) {
$f = new ComparisonFailure(
$this->value,
$other,
\sprintf("'%s'", $this->value),
\sprintf("'%s'", $other)
sprintf("'%s'", $this->value),
sprintf("'%s'", $other)
);
}
// if both values are array, make sure a diff is generated
if (\is_array($this->value) && \is_array($other)) {
if (is_array($this->value) && is_array($other)) {
$f = new ComparisonFailure(
$this->value,
$other,
@@ -101,16 +110,16 @@ final class IsIdentical extends Constraint
*/
public function toString(): string
{
if (\is_object($this->value)) {
if (is_object($this->value)) {
return 'is identical to an object of class "' .
\get_class($this->value) . '"';
get_class($this->value) . '"';
}
return 'is identical to ' . $this->exporter()->export($this->value);
}
/**
* Returns the description of the failure
* 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.
@@ -121,15 +130,15 @@ final class IsIdentical extends Constraint
*/
protected function failureDescription($other): string
{
if (\is_object($this->value) && \is_object($other)) {
if (is_object($this->value) && is_object($other)) {
return 'two variables reference the same object';
}
if (\is_string($this->value) && \is_string($other)) {
if (is_string($this->value) && is_string($other)) {
return 'two strings are identical';
}
if (\is_array($this->value) && \is_array($other)) {
if (is_array($this->value) && is_array($other)) {
return 'two arrays are identical';
}

View File

@@ -9,6 +9,8 @@
*/
namespace PHPUnit\Framework\Constraint;
use function is_infinite;
/**
* Constraint that accepts infinite.
*/
@@ -30,6 +32,6 @@ final class IsInfinite extends Constraint
*/
protected function matches($other): bool
{
return \is_infinite($other);
return is_infinite($other);
}
}

View File

@@ -9,6 +9,10 @@
*/
namespace PHPUnit\Framework\Constraint;
use function sprintf;
use ReflectionClass;
use ReflectionException;
/**
* Constraint that asserts that the object it is evaluated for is an instance
* of a given class.
@@ -32,7 +36,7 @@ final class IsInstanceOf extends Constraint
*/
public function toString(): string
{
return \sprintf(
return sprintf(
'is instance of %s "%s"',
$this->getType(),
$this->className
@@ -51,7 +55,7 @@ final class IsInstanceOf extends Constraint
}
/**
* Returns the description of the failure
* 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.
@@ -62,7 +66,7 @@ final class IsInstanceOf extends Constraint
*/
protected function failureDescription($other): string
{
return \sprintf(
return sprintf(
'%s is an instance of %s "%s"',
$this->exporter()->shortenedExport($other),
$this->getType(),
@@ -73,12 +77,12 @@ final class IsInstanceOf extends Constraint
private function getType(): string
{
try {
$reflection = new \ReflectionClass($this->className);
$reflection = new ReflectionClass($this->className);
if ($reflection->isInterface()) {
return 'interface';
}
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
}
return 'class';

View File

@@ -9,6 +9,10 @@
*/
namespace PHPUnit\Framework\Constraint;
use function json_decode;
use function json_last_error;
use function sprintf;
/**
* Constraint that asserts that a string is valid JSON.
*/
@@ -34,9 +38,9 @@ final class IsJson extends Constraint
return false;
}
\json_decode($other);
json_decode($other);
if (\json_last_error()) {
if (json_last_error()) {
return false;
}
@@ -44,7 +48,7 @@ final class IsJson extends Constraint
}
/**
* Returns the description of the failure
* 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.
@@ -59,12 +63,12 @@ final class IsJson extends Constraint
return 'an empty string is valid JSON';
}
\json_decode($other);
json_decode($other);
$error = JsonMatchesErrorMessageProvider::determineJsonError(
(string) \json_last_error()
(string) json_last_error()
);
return \sprintf(
return sprintf(
'%s is valid JSON (%s)',
$this->exporter()->shortenedExport($other),
$error

View File

@@ -9,6 +9,8 @@
*/
namespace PHPUnit\Framework\Constraint;
use function is_nan;
/**
* Constraint that accepts nan.
*/
@@ -30,6 +32,6 @@ final class IsNan extends Constraint
*/
protected function matches($other): bool
{
return \is_nan($other);
return is_nan($other);
}
}

View File

@@ -9,6 +9,9 @@
*/
namespace PHPUnit\Framework\Constraint;
use function is_readable;
use function sprintf;
/**
* Constraint that checks if the file/dir(name) that it is evaluated for is readable.
*
@@ -32,11 +35,11 @@ final class IsReadable extends Constraint
*/
protected function matches($other): bool
{
return \is_readable($other);
return is_readable($other);
}
/**
* Returns the description of the failure
* 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.
@@ -45,7 +48,7 @@ final class IsReadable extends Constraint
*/
protected function failureDescription($other): string
{
return \sprintf(
return sprintf(
'"%s" is readable',
$other
);

View File

@@ -9,6 +9,21 @@
*/
namespace PHPUnit\Framework\Constraint;
use function get_resource_type;
use function is_array;
use function is_bool;
use function is_callable;
use function is_float;
use function is_int;
use function is_iterable;
use function is_numeric;
use function is_object;
use function is_resource;
use function is_scalar;
use function is_string;
use function sprintf;
use TypeError;
/**
* Constraint that asserts that the value it is evaluated for is of a
* specified type.
@@ -111,7 +126,7 @@ final class IsType extends Constraint
{
if (!isset(self::KNOWN_TYPES[$type])) {
throw new \PHPUnit\Framework\Exception(
\sprintf(
sprintf(
'Type specified for PHPUnit\Framework\Constraint\IsType <%s> ' .
'is not a valid type.',
$type
@@ -127,7 +142,7 @@ final class IsType extends Constraint
*/
public function toString(): string
{
return \sprintf(
return sprintf(
'is of type "%s"',
$this->type
);
@@ -143,57 +158,57 @@ final class IsType extends Constraint
{
switch ($this->type) {
case 'numeric':
return \is_numeric($other);
return is_numeric($other);
case 'integer':
case 'int':
return \is_int($other);
return is_int($other);
case 'double':
case 'float':
case 'real':
return \is_float($other);
return is_float($other);
case 'string':
return \is_string($other);
return is_string($other);
case 'boolean':
case 'bool':
return \is_bool($other);
return is_bool($other);
case 'null':
return null === $other;
case 'array':
return \is_array($other);
return is_array($other);
case 'object':
return \is_object($other);
return is_object($other);
case 'resource':
if (\is_resource($other)) {
if (is_resource($other)) {
return true;
}
try {
$resource = @\get_resource_type($other);
$resource = @get_resource_type($other);
if (\is_string($resource)) {
if (is_string($resource)) {
return true;
}
} catch (\TypeError $e) {
} catch (TypeError $e) {
}
return false;
case 'scalar':
return \is_scalar($other);
return is_scalar($other);
case 'callable':
return \is_callable($other);
return is_callable($other);
case 'iterable':
return \is_iterable($other);
return is_iterable($other);
}
}
}

View File

@@ -9,6 +9,9 @@
*/
namespace PHPUnit\Framework\Constraint;
use function is_writable;
use function sprintf;
/**
* Constraint that checks if the file/dir(name) that it is evaluated for is writable.
*
@@ -32,11 +35,11 @@ final class IsWritable extends Constraint
*/
protected function matches($other): bool
{
return \is_writable($other);
return is_writable($other);
}
/**
* Returns the description of the failure
* 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.
@@ -45,7 +48,7 @@ final class IsWritable extends Constraint
*/
protected function failureDescription($other): string
{
return \sprintf(
return sprintf(
'"%s" is writable',
$other
);

View File

@@ -9,6 +9,8 @@
*/
namespace PHPUnit\Framework\Constraint;
use function json_decode;
use function sprintf;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Util\Json;
use SebastianBergmann\Comparator\ComparisonFailure;
@@ -33,7 +35,7 @@ final class JsonMatches extends Constraint
*/
public function toString(): string
{
return \sprintf(
return sprintf(
'matches JSON string "%s"',
$this->value
);
@@ -65,15 +67,15 @@ final class JsonMatches extends Constraint
}
/**
* Throws an exception for the given compared value and test description
* Throws an exception for the given compared value and test description.
*
* @param mixed $other evaluated value or object
* @param string $description Additional information about the test
* @param ComparisonFailure $comparisonFailure
*
* @throws ExpectationFailedException
* @throws \PHPUnit\Framework\Exception
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws ExpectationFailedException
*
* @psalm-return never-return
*/
@@ -93,8 +95,8 @@ final class JsonMatches extends Constraint
}
$comparisonFailure = new ComparisonFailure(
\json_decode($this->value),
\json_decode($other),
json_decode($this->value),
json_decode($other),
Json::prettify($recodedValue),
Json::prettify($recodedOther),
false,

View File

@@ -9,6 +9,14 @@
*/
namespace PHPUnit\Framework\Constraint;
use const JSON_ERROR_CTRL_CHAR;
use const JSON_ERROR_DEPTH;
use const JSON_ERROR_NONE;
use const JSON_ERROR_STATE_MISMATCH;
use const JSON_ERROR_SYNTAX;
use const JSON_ERROR_UTF8;
use function strtolower;
/**
* Provides human readable messages for each JSON error.
*/
@@ -20,17 +28,17 @@ final class JsonMatchesErrorMessageProvider
public static function determineJsonError(string $error, string $prefix = ''): ?string
{
switch ($error) {
case \JSON_ERROR_NONE:
case JSON_ERROR_NONE:
return null;
case \JSON_ERROR_DEPTH:
case JSON_ERROR_DEPTH:
return $prefix . 'Maximum stack depth exceeded';
case \JSON_ERROR_STATE_MISMATCH:
case JSON_ERROR_STATE_MISMATCH:
return $prefix . 'Underflow or the modes mismatch';
case \JSON_ERROR_CTRL_CHAR:
case JSON_ERROR_CTRL_CHAR:
return $prefix . 'Unexpected control character found';
case \JSON_ERROR_SYNTAX:
case JSON_ERROR_SYNTAX:
return $prefix . 'Syntax error, malformed JSON';
case \JSON_ERROR_UTF8:
case JSON_ERROR_UTF8:
return $prefix . 'Malformed UTF-8 characters, possibly incorrectly encoded';
default:
@@ -43,7 +51,7 @@ final class JsonMatchesErrorMessageProvider
*/
public static function translateTypeToPrefix(string $type): string
{
switch (\strtolower($type)) {
switch (strtolower($type)) {
case 'expected':
$prefix = 'Expected value JSON decode error - ';

View File

@@ -9,6 +9,8 @@
*/
namespace PHPUnit\Framework\Constraint;
use function array_values;
use function count;
use PHPUnit\Framework\ExpectationFailedException;
/**
@@ -25,7 +27,7 @@ final class LogicalAnd extends Constraint
{
$constraint = new self;
$constraint->constraints = \array_values($constraints);
$constraint->constraints = array_values($constraints);
return $constraint;
}
@@ -52,7 +54,7 @@ final class LogicalAnd extends Constraint
}
/**
* Evaluates the constraint for parameter $other
* 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.
@@ -61,8 +63,8 @@ final class LogicalAnd extends Constraint
* a boolean value instead: true in case of success, false in case of a
* failure.
*
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws ExpectationFailedException
*/
public function evaluate($other, string $description = '', bool $returnResult = false)
{
@@ -111,7 +113,7 @@ final class LogicalAnd extends Constraint
$count = 0;
foreach ($this->constraints as $constraint) {
$count += \count($constraint);
$count += count($constraint);
}
return $count;

View File

@@ -9,6 +9,10 @@
*/
namespace PHPUnit\Framework\Constraint;
use function count;
use function get_class;
use function preg_match;
use function str_replace;
use PHPUnit\Framework\ExpectationFailedException;
/**
@@ -49,14 +53,14 @@ final class LogicalNot extends Constraint
'not ',
];
\preg_match('/(\'[\w\W]*\')([\w\W]*)("[\w\W]*")/i', $string, $matches);
preg_match('/(\'[\w\W]*\')([\w\W]*)("[\w\W]*")/i', $string, $matches);
if (\count($matches) > 0) {
if (count($matches) > 0) {
$nonInput = $matches[2];
$negatedString = \str_replace(
$negatedString = str_replace(
$nonInput,
\str_replace(
str_replace(
$positives,
$negatives,
$nonInput
@@ -64,7 +68,7 @@ final class LogicalNot extends Constraint
$string
);
} else {
$negatedString = \str_replace(
$negatedString = str_replace(
$positives,
$negatives,
$string
@@ -87,7 +91,7 @@ final class LogicalNot extends Constraint
}
/**
* Evaluates the constraint for parameter $other
* 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.
@@ -96,8 +100,8 @@ final class LogicalNot extends Constraint
* a boolean value instead: true in case of success, false in case of a
* failure.
*
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws ExpectationFailedException
*/
public function evaluate($other, string $description = '', bool $returnResult = false)
{
@@ -117,7 +121,7 @@ final class LogicalNot extends Constraint
*/
public function toString(): string
{
switch (\get_class($this->constraint)) {
switch (get_class($this->constraint)) {
case LogicalAnd::class:
case self::class:
case LogicalOr::class:
@@ -135,11 +139,11 @@ final class LogicalNot extends Constraint
*/
public function count(): int
{
return \count($this->constraint);
return count($this->constraint);
}
/**
* Returns the description of the failure
* 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.
@@ -150,7 +154,7 @@ final class LogicalNot extends Constraint
*/
protected function failureDescription($other): string
{
switch (\get_class($this->constraint)) {
switch (get_class($this->constraint)) {
case LogicalAnd::class:
case self::class:
case LogicalOr::class:

View File

@@ -9,6 +9,8 @@
*/
namespace PHPUnit\Framework\Constraint;
use function array_values;
use function count;
use PHPUnit\Framework\ExpectationFailedException;
/**
@@ -25,7 +27,7 @@ final class LogicalOr extends Constraint
{
$constraint = new self;
$constraint->constraints = \array_values($constraints);
$constraint->constraints = array_values($constraints);
return $constraint;
}
@@ -49,7 +51,7 @@ final class LogicalOr extends Constraint
}
/**
* Evaluates the constraint for parameter $other
* 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.
@@ -58,8 +60,8 @@ final class LogicalOr extends Constraint
* a boolean value instead: true in case of success, false in case of a
* failure.
*
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws ExpectationFailedException
*/
public function evaluate($other, string $description = '', bool $returnResult = false)
{
@@ -108,7 +110,7 @@ final class LogicalOr extends Constraint
$count = 0;
foreach ($this->constraints as $constraint) {
$count += \count($constraint);
$count += count($constraint);
}
return $count;

View File

@@ -9,6 +9,8 @@
*/
namespace PHPUnit\Framework\Constraint;
use function array_values;
use function count;
use PHPUnit\Framework\ExpectationFailedException;
/**
@@ -25,7 +27,7 @@ final class LogicalXor extends Constraint
{
$constraint = new self;
$constraint->constraints = \array_values($constraints);
$constraint->constraints = array_values($constraints);
return $constraint;
}
@@ -49,7 +51,7 @@ final class LogicalXor extends Constraint
}
/**
* Evaluates the constraint for parameter $other
* 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.
@@ -58,8 +60,8 @@ final class LogicalXor extends Constraint
* a boolean value instead: true in case of success, false in case of a
* failure.
*
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws ExpectationFailedException
*/
public function evaluate($other, string $description = '', bool $returnResult = false)
{
@@ -113,7 +115,7 @@ final class LogicalXor extends Constraint
$count = 0;
foreach ($this->constraints as $constraint) {
$count += \count($constraint);
$count += count($constraint);
}
return $count;

View File

@@ -9,6 +9,9 @@
*/
namespace PHPUnit\Framework\Constraint;
use function preg_match;
use function sprintf;
/**
* Constraint that asserts that the string it is evaluated for matches
* a regular expression.
@@ -35,7 +38,7 @@ class RegularExpression extends Constraint
*/
public function toString(): string
{
return \sprintf(
return sprintf(
'matches PCRE pattern "%s"',
$this->pattern
);
@@ -49,6 +52,6 @@ class RegularExpression extends Constraint
*/
protected function matches($other): bool
{
return \preg_match($this->pattern, $other) > 0;
return preg_match($this->pattern, $other) > 0;
}
}

View File

@@ -9,6 +9,11 @@
*/
namespace PHPUnit\Framework\Constraint;
use function mb_stripos;
use function mb_strpos;
use function mb_strtolower;
use function sprintf;
/**
* Constraint that asserts that the string it is evaluated for contains
* a given string.
@@ -42,12 +47,12 @@ final class StringContains extends Constraint
public function toString(): string
{
if ($this->ignoreCase) {
$string = \mb_strtolower($this->string);
$string = mb_strtolower($this->string);
} else {
$string = $this->string;
}
return \sprintf(
return sprintf(
'contains "%s"',
$string
);
@@ -66,9 +71,9 @@ final class StringContains extends Constraint
}
if ($this->ignoreCase) {
return \mb_stripos($other, $this->string) !== false;
return mb_stripos($other, $this->string) !== false;
}
return \mb_strpos($other, $this->string) !== false;
return mb_strpos($other, $this->string) !== false;
}
}

View File

@@ -9,6 +9,9 @@
*/
namespace PHPUnit\Framework\Constraint;
use function strlen;
use function substr;
/**
* Constraint that asserts that the string it is evaluated for ends with a given
* suffix.
@@ -41,6 +44,6 @@ final class StringEndsWith extends Constraint
*/
protected function matches($other): bool
{
return \substr($other, 0 - \strlen($this->suffix)) === $this->suffix;
return substr($other, 0 - strlen($this->suffix)) === $this->suffix;
}
}

View File

@@ -9,6 +9,13 @@
*/
namespace PHPUnit\Framework\Constraint;
use const DIRECTORY_SEPARATOR;
use function explode;
use function implode;
use function preg_match;
use function preg_quote;
use function preg_replace;
use function strtr;
use SebastianBergmann\Diff\Differ;
/**
@@ -52,32 +59,32 @@ final class StringMatchesFormatDescription extends RegularExpression
protected function additionalFailureDescription($other): string
{
$from = \explode("\n", $this->string);
$to = \explode("\n", $this->convertNewlines($other));
$from = explode("\n", $this->string);
$to = explode("\n", $this->convertNewlines($other));
foreach ($from as $index => $line) {
if (isset($to[$index]) && $line !== $to[$index]) {
$line = $this->createPatternFromFormat($line);
if (\preg_match($line, $to[$index]) > 0) {
if (preg_match($line, $to[$index]) > 0) {
$from[$index] = $to[$index];
}
}
}
$this->string = \implode("\n", $from);
$other = \implode("\n", $to);
$this->string = implode("\n", $from);
$other = implode("\n", $to);
return (new Differ("--- Expected\n+++ Actual\n"))->diff($this->string, $other);
}
private function createPatternFromFormat(string $string): string
{
$string = \strtr(
\preg_quote($string, '/'),
$string = strtr(
preg_quote($string, '/'),
[
'%%' => '%',
'%e' => '\\' . \DIRECTORY_SEPARATOR,
'%e' => '\\' . DIRECTORY_SEPARATOR,
'%s' => '[^\r\n]+',
'%S' => '[^\r\n]*',
'%a' => '.+',
@@ -96,6 +103,6 @@ final class StringMatchesFormatDescription extends RegularExpression
private function convertNewlines($text): string
{
return \preg_replace('/\r\n/', "\n", $text);
return preg_replace('/\r\n/', "\n", $text);
}
}

View File

@@ -9,6 +9,8 @@
*/
namespace PHPUnit\Framework\Constraint;
use function strlen;
use function strpos;
use PHPUnit\Framework\InvalidArgumentException;
/**
@@ -24,7 +26,7 @@ final class StringStartsWith extends Constraint
public function __construct(string $prefix)
{
if (\strlen($prefix) === 0) {
if (strlen($prefix) === 0) {
throw InvalidArgumentException::create(1, 'non-empty string');
}
@@ -47,6 +49,6 @@ final class StringStartsWith extends Constraint
*/
protected function matches($other): bool
{
return \strpos((string) $other, $this->prefix) === 0;
return strpos((string) $other, $this->prefix) === 0;
}
}

View File

@@ -9,6 +9,11 @@
*/
namespace PHPUnit\Framework\Constraint;
use function is_array;
use function is_object;
use function is_string;
use function sprintf;
use function strpos;
use SplObjectStorage;
/**
@@ -48,7 +53,7 @@ final class TraversableContains extends Constraint
*/
public function toString(): string
{
if (\is_string($this->value) && \strpos($this->value, "\n") !== false) {
if (is_string($this->value) && strpos($this->value, "\n") !== false) {
return 'contains "' . $this->value . '"';
}
@@ -67,7 +72,7 @@ final class TraversableContains extends Constraint
return $other->contains($this->value);
}
if (\is_object($this->value)) {
if (is_object($this->value)) {
foreach ($other as $element) {
if ($this->checkForObjectIdentity && $element === $this->value) {
return true;
@@ -95,7 +100,7 @@ final class TraversableContains extends Constraint
}
/**
* Returns the description of the failure
* 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.
@@ -106,9 +111,9 @@ final class TraversableContains extends Constraint
*/
protected function failureDescription($other): string
{
return \sprintf(
return sprintf(
'%s %s',
\is_array($other) ? 'an array' : 'a traversable',
is_array($other) ? 'an array' : 'a traversable',
$this->toString()
);
}

View File

@@ -9,6 +9,10 @@
*/
namespace PHPUnit\Framework\Constraint;
use function is_array;
use function is_string;
use function sprintf;
use function strpos;
use SplObjectStorage;
/**
@@ -34,7 +38,7 @@ final class TraversableContainsEqual extends Constraint
*/
public function toString(): string
{
if (\is_string($this->value) && \strpos($this->value, "\n") !== false) {
if (is_string($this->value) && strpos($this->value, "\n") !== false) {
return 'contains "' . $this->value . '"';
}
@@ -64,7 +68,7 @@ final class TraversableContainsEqual extends Constraint
}
/**
* Returns the description of the failure
* 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.
@@ -75,9 +79,9 @@ final class TraversableContainsEqual extends Constraint
*/
protected function failureDescription($other): string
{
return \sprintf(
return sprintf(
'%s %s',
\is_array($other) ? 'an array' : 'a traversable',
is_array($other) ? 'an array' : 'a traversable',
$this->toString()
);
}

View File

@@ -9,6 +9,10 @@
*/
namespace PHPUnit\Framework\Constraint;
use function is_array;
use function is_string;
use function sprintf;
use function strpos;
use SplObjectStorage;
/**
@@ -34,7 +38,7 @@ final class TraversableContainsIdentical extends Constraint
*/
public function toString(): string
{
if (\is_string($this->value) && \strpos($this->value, "\n") !== false) {
if (is_string($this->value) && strpos($this->value, "\n") !== false) {
return 'contains "' . $this->value . '"';
}
@@ -63,7 +67,7 @@ final class TraversableContainsIdentical extends Constraint
}
/**
* Returns the description of the failure
* 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.
@@ -74,9 +78,9 @@ final class TraversableContainsIdentical extends Constraint
*/
protected function failureDescription($other): string
{
return \sprintf(
return sprintf(
'%s %s',
\is_array($other) ? 'an array' : 'a traversable',
is_array($other) ? 'an array' : 'a traversable',
$this->toString()
);
}

View File

@@ -44,7 +44,7 @@ final class TraversableContainsOnly extends Constraint
}
/**
* Evaluates the constraint for parameter $other
* 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.
@@ -53,8 +53,8 @@ final class TraversableContainsOnly extends Constraint
* a boolean value instead: true in case of success, false in case of a
* failure.
*
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws ExpectationFailedException
*/
public function evaluate($other, string $description = '', bool $returnResult = false)
{

View File

@@ -9,6 +9,8 @@
*/
namespace PHPUnit\Framework;
use function count;
use function explode;
use PHPUnit\Util\Test as TestUtil;
/**
@@ -44,17 +46,17 @@ final class DataProviderTestSuite extends TestSuite
public function hasDependencies(): bool
{
return \count($this->dependencies) > 0;
return count($this->dependencies) > 0;
}
/**
* Returns the size of the each test created using the data provider(s)
* Returns the size of the each test created using the data provider(s).
*
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
public function getSize(): int
{
[$className, $methodName] = \explode('::', $this->getName());
[$className, $methodName] = explode('::', $this->getName());
return TestUtil::getSize($className, $methodName);
}

View File

@@ -9,7 +9,11 @@
*/
namespace PHPUnit\Framework;
use function array_keys;
use function get_object_vars;
use PHPUnit\Util\Filter;
use RuntimeException;
use Throwable;
/**
* Base class for all PHPUnit Framework exceptions.
@@ -33,20 +37,20 @@ use PHPUnit\Util\Filter;
*
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
class Exception extends \RuntimeException implements \PHPUnit\Exception
class Exception extends RuntimeException implements \PHPUnit\Exception
{
/**
* @var array
*/
protected $serializableTrace;
public function __construct($message = '', $code = 0, \Throwable $previous = null)
public function __construct($message = '', $code = 0, Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
$this->serializableTrace = $this->getTrace();
foreach (\array_keys($this->serializableTrace) as $key) {
foreach (array_keys($this->serializableTrace) as $key) {
unset($this->serializableTrace[$key]['args']);
}
}
@@ -64,7 +68,7 @@ class Exception extends \RuntimeException implements \PHPUnit\Exception
public function __sleep(): array
{
return \array_keys(\get_object_vars($this));
return array_keys(get_object_vars($this));
}
/**

View File

@@ -9,6 +9,7 @@
*/
namespace PHPUnit\Framework;
use Exception;
use SebastianBergmann\Comparator\ComparisonFailure;
/**
@@ -27,7 +28,7 @@ final class ExpectationFailedException extends AssertionFailedError
*/
protected $comparisonFailure;
public function __construct(string $message, ComparisonFailure $comparisonFailure = null, \Exception $previous = null)
public function __construct(string $message, ComparisonFailure $comparisonFailure = null, Exception $previous = null)
{
$this->comparisonFailure = $comparisonFailure;

View File

@@ -9,6 +9,11 @@
*/
namespace PHPUnit\Framework;
use function debug_backtrace;
use function in_array;
use function lcfirst;
use function sprintf;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
@@ -16,15 +21,15 @@ final class InvalidArgumentException extends Exception
{
public static function create(int $argument, string $type): self
{
$stack = \debug_backtrace();
$stack = debug_backtrace();
return new self(
\sprintf(
sprintf(
'Argument #%d of %s::%s() must be %s %s',
$argument,
$stack[1]['class'],
$stack[1]['function'],
\in_array(\lcfirst($type)[0], ['a', 'e', 'i', 'o', 'u'], true) ? 'an' : 'a',
in_array(lcfirst($type)[0], ['a', 'e', 'i', 'o', 'u'], true) ? 'an' : 'a',
$type
)
);

View File

@@ -9,6 +9,9 @@
*/
namespace PHPUnit\Framework;
use function array_keys;
use function get_class;
use function spl_object_hash;
use PHPUnit\Util\Filter;
use Throwable;
@@ -77,13 +80,13 @@ final class ExceptionWrapper extends Exception
{
$this->originalException($t);
$this->className = \get_class($t);
$this->className = get_class($t);
$this->file = $t->getFile();
$this->line = $t->getLine();
$this->serializableTrace = $t->getTrace();
foreach (\array_keys($this->serializableTrace) as $key) {
foreach (array_keys($this->serializableTrace) as $key) {
unset($this->serializableTrace[$key]['args']);
}
@@ -100,13 +103,13 @@ final class ExceptionWrapper extends Exception
/**
* Method to contain static originalException to exclude it from stacktrace to prevent the stacktrace contents,
* which can be quite big, from being garbage-collected, thus blocking memory until shutdown.
* Approach works both for var_dump() and var_export() and print_r()
* Approach works both for var_dump() and var_export() and print_r().
*/
private function originalException(Throwable $exceptionToStore = null): ?Throwable
{
static $originalExceptions;
$instanceId = \spl_object_hash($this);
$instanceId = spl_object_hash($this);
if ($exceptionToStore) {
$originalExceptions[$instanceId] = $exceptionToStore;

View File

@@ -9,6 +9,8 @@
*/
namespace PHPUnit\Framework\MockObject;
use function call_user_func_array;
use function func_get_args;
use PHPUnit\Framework\MockObject\Rule\AnyInvokedCount;
/**
@@ -20,9 +22,9 @@ trait Method
{
$expects = $this->expects(new AnyInvokedCount);
return \call_user_func_array(
return call_user_func_array(
[$expects, 'method'],
\func_get_args()
func_get_args()
);
}
}

View File

@@ -9,6 +9,16 @@
*/
namespace PHPUnit\Framework\MockObject\Builder;
use function array_map;
use function array_merge;
use function count;
use function get_class;
use function gettype;
use function in_array;
use function is_object;
use function is_string;
use function sprintf;
use function strtolower;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\MockObject\ConfigurableMethod;
use PHPUnit\Framework\MockObject\IncompatibleReturnValueException;
@@ -25,6 +35,7 @@ use PHPUnit\Framework\MockObject\Stub\ReturnSelf;
use PHPUnit\Framework\MockObject\Stub\ReturnStub;
use PHPUnit\Framework\MockObject\Stub\ReturnValueMap;
use PHPUnit\Framework\MockObject\Stub\Stub;
use Throwable;
final class InvocationMocker implements InvocationStubber, MethodNameMatch
{
@@ -72,12 +83,12 @@ final class InvocationMocker implements InvocationStubber, MethodNameMatch
public function willReturn($value, ...$nextValues): self
{
if (\count($nextValues) === 0) {
if (count($nextValues) === 0) {
$this->ensureTypeOfReturnValues([$value]);
$stub = $value instanceof Stub ? $value : new ReturnStub($value);
} else {
$values = \array_merge([$value], $nextValues);
$values = array_merge([$value], $nextValues);
$this->ensureTypeOfReturnValues($values);
@@ -129,7 +140,7 @@ final class InvocationMocker implements InvocationStubber, MethodNameMatch
return $this->will($stub);
}
public function willThrowException(\Throwable $exception): self
public function willThrowException(Throwable $exception): self
{
$stub = new Exception($exception);
@@ -205,16 +216,16 @@ final class InvocationMocker implements InvocationStubber, MethodNameMatch
);
}
$configurableMethodNames = \array_map(
$configurableMethodNames = array_map(
static function (ConfigurableMethod $configurable) {
return \strtolower($configurable->getName());
return strtolower($configurable->getName());
},
$this->configurableMethods
);
if (\is_string($constraint) && !\in_array(\strtolower($constraint), $configurableMethodNames, true)) {
if (is_string($constraint) && !in_array(strtolower($constraint), $configurableMethodNames, true)) {
throw new RuntimeException(
\sprintf(
sprintf(
'Trying to configure method "%s" which cannot be configured because it does not exist, has not been specified, is final, or is static',
$constraint
)
@@ -275,10 +286,10 @@ final class InvocationMocker implements InvocationStubber, MethodNameMatch
foreach ($values as $value) {
if (!$configuredMethod->mayReturn($value)) {
throw new IncompatibleReturnValueException(
\sprintf(
sprintf(
'Method %s may not return value of type %s, its return declaration is "%s"',
$configuredMethod->getName(),
\is_object($value) ? \get_class($value) : \gettype($value),
is_object($value) ? get_class($value) : gettype($value),
$configuredMethod->getReturnTypeDeclaration()
)
);

View File

@@ -10,6 +10,7 @@
namespace PHPUnit\Framework\MockObject\Builder;
use PHPUnit\Framework\MockObject\Stub\Stub;
use Throwable;
interface InvocationStubber
{
@@ -57,5 +58,5 @@ interface InvocationStubber
public function willReturnOnConsecutiveCalls(...$values)/*: self */;
/** @return self */
public function willThrowException(\Throwable $exception)/*: self */;
public function willThrowException(Throwable $exception)/*: self */;
}

View File

@@ -9,9 +9,11 @@
*/
namespace PHPUnit\Framework\MockObject;
use Throwable;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
interface Exception extends \Throwable
interface Exception extends Throwable
{
}

View File

@@ -9,9 +9,54 @@
*/
namespace PHPUnit\Framework\MockObject;
use const DIRECTORY_SEPARATOR;
use const PHP_EOL;
use const PHP_MAJOR_VERSION;
use const PREG_OFFSET_CAPTURE;
use const WSDL_CACHE_NONE;
use function array_diff_assoc;
use function array_map;
use function array_merge;
use function array_pop;
use function array_unique;
use function class_exists;
use function count;
use function explode;
use function extension_loaded;
use function implode;
use function in_array;
use function interface_exists;
use function is_array;
use function is_object;
use function is_string;
use function md5;
use function mt_rand;
use function preg_match;
use function preg_match_all;
use function range;
use function serialize;
use function sort;
use function sprintf;
use function str_replace;
use function strlen;
use function strpos;
use function strtolower;
use function substr;
use function trait_exists;
use Doctrine\Instantiator\Exception\ExceptionInterface as InstantiatorException;
use Doctrine\Instantiator\Instantiator;
use Exception;
use Iterator;
use IteratorAggregate;
use PHPUnit\Framework\InvalidArgumentException;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use SoapClient;
use SoapFault;
use Text_Template;
use Throwable;
use Traversable;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
@@ -40,7 +85,7 @@ final class Generator
private static $cache = [];
/**
* @var \Text_Template[]
* @var Text_Template[]
*/
private static $templates = [];
@@ -54,11 +99,11 @@ final class Generator
*/
public function getMock($type, $methods = [], array $arguments = [], string $mockClassName = '', bool $callOriginalConstructor = true, bool $callOriginalClone = true, bool $callAutoload = true, bool $cloneArguments = true, bool $callOriginalMethods = false, object $proxyTarget = null, bool $allowMockingUnknownTypes = true, bool $returnValueGeneration = true): MockObject
{
if (!\is_array($type) && !\is_string($type)) {
if (!is_array($type) && !is_string($type)) {
throw InvalidArgumentException::create(1, 'array or string');
}
if (!\is_array($methods) && null !== $methods) {
if (!is_array($methods) && null !== $methods) {
throw InvalidArgumentException::create(2, 'array');
}
@@ -66,9 +111,9 @@ final class Generator
$type = 'Iterator';
}
if (\is_array($type)) {
$type = \array_unique(
\array_map(
if (is_array($type)) {
$type = array_unique(
array_map(
static function ($type) {
if ($type === 'Traversable' ||
$type === '\\Traversable' ||
@@ -84,21 +129,21 @@ final class Generator
}
if (!$allowMockingUnknownTypes) {
if (\is_array($type)) {
if (is_array($type)) {
foreach ($type as $_type) {
if (!\class_exists($_type, $callAutoload) &&
!\interface_exists($_type, $callAutoload)) {
if (!class_exists($_type, $callAutoload) &&
!interface_exists($_type, $callAutoload)) {
throw new RuntimeException(
\sprintf(
sprintf(
'Cannot stub or mock class or interface "%s" which does not exist',
$_type
)
);
}
}
} elseif (!\class_exists($type, $callAutoload) && !\interface_exists($type, $callAutoload)) {
} elseif (!class_exists($type, $callAutoload) && !interface_exists($type, $callAutoload)) {
throw new RuntimeException(
\sprintf(
sprintf(
'Cannot stub or mock class or interface "%s" which does not exist',
$type
)
@@ -108,9 +153,9 @@ final class Generator
if (null !== $methods) {
foreach ($methods as $method) {
if (!\preg_match('~[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*~', (string) $method)) {
if (!preg_match('~[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*~', (string) $method)) {
throw new RuntimeException(
\sprintf(
sprintf(
'Cannot stub or mock method with invalid name "%s"',
$method
)
@@ -118,22 +163,22 @@ final class Generator
}
}
if ($methods !== \array_unique($methods)) {
if ($methods !== array_unique($methods)) {
throw new RuntimeException(
\sprintf(
sprintf(
'Cannot stub or mock using a method list that contains duplicates: "%s" (duplicate: "%s")',
\implode(', ', $methods),
\implode(', ', \array_unique(\array_diff_assoc($methods, \array_unique($methods))))
implode(', ', $methods),
implode(', ', array_unique(array_diff_assoc($methods, array_unique($methods))))
)
);
}
}
if ($mockClassName !== '' && \class_exists($mockClassName, false)) {
if ($mockClassName !== '' && class_exists($mockClassName, false)) {
try {
$reflector = new \ReflectionClass($mockClassName);
$reflector = new ReflectionClass($mockClassName);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
@@ -144,7 +189,7 @@ final class Generator
if (!$reflector->implementsInterface(MockObject::class)) {
throw new RuntimeException(
\sprintf(
sprintf(
'Class "%s" already exists.',
$mockClassName
)
@@ -183,7 +228,7 @@ final class Generator
/**
* Returns a mock object for the specified abstract class with all abstract
* methods of the class mocked. Concrete methods to mock can be specified with
* the $mockedMethods parameter
* the $mockedMethods parameter.
*
* @psalm-template RealInstanceType of object
* @psalm-param class-string<RealInstanceType> $originalClassName
@@ -193,12 +238,12 @@ final class Generator
*/
public function getMockForAbstractClass(string $originalClassName, array $arguments = [], string $mockClassName = '', bool $callOriginalConstructor = true, bool $callOriginalClone = true, bool $callAutoload = true, array $mockedMethods = null, bool $cloneArguments = true): MockObject
{
if (\class_exists($originalClassName, $callAutoload) ||
\interface_exists($originalClassName, $callAutoload)) {
if (class_exists($originalClassName, $callAutoload) ||
interface_exists($originalClassName, $callAutoload)) {
try {
$reflector = new \ReflectionClass($originalClassName);
$reflector = new ReflectionClass($originalClassName);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
@@ -210,7 +255,7 @@ final class Generator
$methods = $mockedMethods;
foreach ($reflector->getMethods() as $method) {
if ($method->isAbstract() && !\in_array($method->getName(), $methods ?? [], true)) {
if ($method->isAbstract() && !in_array($method->getName(), $methods ?? [], true)) {
$methods[] = $method->getName();
}
}
@@ -232,7 +277,7 @@ final class Generator
}
throw new RuntimeException(
\sprintf('Class "%s" does not exist.', $originalClassName)
sprintf('Class "%s" does not exist.', $originalClassName)
);
}
@@ -245,9 +290,9 @@ final class Generator
*/
public function getMockForTrait(string $traitName, array $arguments = [], string $mockClassName = '', bool $callOriginalConstructor = true, bool $callOriginalClone = true, bool $callAutoload = true, array $mockedMethods = null, bool $cloneArguments = true): MockObject
{
if (!\trait_exists($traitName, $callAutoload)) {
if (!trait_exists($traitName, $callAutoload)) {
throw new RuntimeException(
\sprintf(
sprintf(
'Trait "%s" does not exist.',
$traitName
)
@@ -283,9 +328,9 @@ final class Generator
*/
public function getObjectForTrait(string $traitName, string $traitClassName = '', bool $callAutoload = true, bool $callOriginalConstructor = false, array $arguments = []): object
{
if (!\trait_exists($traitName, $callAutoload)) {
if (!trait_exists($traitName, $callAutoload)) {
throw new RuntimeException(
\sprintf(
sprintf(
'Trait "%s" does not exist.',
$traitName
)
@@ -322,8 +367,8 @@ final class Generator
public function generate($type, array $methods = null, string $mockClassName = '', bool $callOriginalClone = true, bool $callAutoload = true, bool $cloneArguments = true, bool $callOriginalMethods = false): MockClass
{
if (\is_array($type)) {
\sort($type);
if (is_array($type)) {
sort($type);
}
if ($mockClassName !== '') {
@@ -338,12 +383,12 @@ final class Generator
);
}
$key = \md5(
\is_array($type) ? \implode('_', $type) : $type .
\serialize($methods) .
\serialize($callOriginalClone) .
\serialize($cloneArguments) .
\serialize($callOriginalMethods)
$key = md5(
is_array($type) ? implode('_', $type) : $type .
serialize($methods) .
serialize($callOriginalClone) .
serialize($cloneArguments) .
serialize($callOriginalMethods)
);
if (!isset(self::$cache[$key])) {
@@ -366,19 +411,19 @@ final class Generator
*/
public function generateClassFromWsdl(string $wsdlFile, string $className, array $methods = [], array $options = []): string
{
if (!\extension_loaded('soap')) {
if (!extension_loaded('soap')) {
throw new RuntimeException(
'The SOAP extension is required to generate a mock object from WSDL.'
);
}
$options = \array_merge($options, ['cache_wsdl' => \WSDL_CACHE_NONE]);
$options = array_merge($options, ['cache_wsdl' => WSDL_CACHE_NONE]);
try {
$client = new \SoapClient($wsdlFile, $options);
$_methods = \array_unique($client->__getFunctions());
$client = new SoapClient($wsdlFile, $options);
$_methods = array_unique($client->__getFunctions());
unset($client);
} catch (\SoapFault $e) {
} catch (SoapFault $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
@@ -386,32 +431,38 @@ final class Generator
);
}
\sort($_methods);
sort($_methods);
$methodTemplate = $this->getTemplate('wsdl_method.tpl');
$methodsBuffer = '';
foreach ($_methods as $method) {
\preg_match_all('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\(/', $method, $matches, \PREG_OFFSET_CAPTURE);
$lastFunction = \array_pop($matches[0]);
preg_match_all('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\(/', $method, $matches, PREG_OFFSET_CAPTURE);
$lastFunction = array_pop($matches[0]);
$nameStart = $lastFunction[1];
$nameEnd = $nameStart + \strlen($lastFunction[0]) - 1;
$name = \str_replace('(', '', $lastFunction[0]);
$nameEnd = $nameStart + strlen($lastFunction[0]) - 1;
$name = str_replace('(', '', $lastFunction[0]);
if (empty($methods) || \in_array($name, $methods, true)) {
$args = \explode(
if (empty($methods) || in_array($name, $methods, true)) {
$args = explode(
',',
\str_replace(')', '', \substr($method, $nameEnd + 1))
str_replace(')', '', substr($method, $nameEnd + 1))
);
foreach (\range(0, \count($args) - 1) as $i) {
$args[$i] = \substr($args[$i], \strpos($args[$i], '$'));
foreach (range(0, count($args) - 1) as $i) {
$parameterStart = strpos($args[$i], '$');
if (!$parameterStart) {
continue;
}
$args[$i] = substr($args[$i], $parameterStart);
}
$methodTemplate->setVar(
[
'method_name' => $name,
'arguments' => \implode(', ', $args),
'arguments' => implode(', ', $args),
]
);
@@ -430,10 +481,10 @@ final class Generator
$classTemplate = $this->getTemplate('wsdl_class.tpl');
$namespace = '';
if (\strpos($className, '\\') !== false) {
$parts = \explode('\\', $className);
$className = \array_pop($parts);
$namespace = 'namespace ' . \implode('\\', $parts) . ';' . "\n\n";
if (strpos($className, '\\') !== false) {
$parts = explode('\\', $className);
$className = array_pop($parts);
$namespace = 'namespace ' . implode('\\', $parts) . ';' . "\n\n";
}
$classTemplate->setVar(
@@ -457,9 +508,9 @@ final class Generator
public function getClassMethods(string $className): array
{
try {
$class = new \ReflectionClass($className);
$class = new ReflectionClass($className);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
@@ -487,9 +538,9 @@ final class Generator
public function mockClassMethods(string $className, bool $callOriginalMethods, bool $cloneArguments): array
{
try {
$class = new \ReflectionClass($className);
$class = new ReflectionClass($className);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
@@ -517,9 +568,9 @@ final class Generator
public function mockInterfaceMethods(string $interfaceName, bool $cloneArguments): array
{
try {
$class = new \ReflectionClass($interfaceName);
$class = new ReflectionClass($interfaceName);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
@@ -540,14 +591,14 @@ final class Generator
/**
* @psalm-param class-string $interfaceName
*
* @return \ReflectionMethod[]
* @return ReflectionMethod[]
*/
private function userDefinedInterfaceMethods(string $interfaceName): array
{
try {
// @codeCoverageIgnoreStart
$interface = new \ReflectionClass($interfaceName);
} catch (\ReflectionException $e) {
$interface = new ReflectionClass($interfaceName);
} catch (ReflectionException $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
@@ -574,13 +625,13 @@ final class Generator
$className = $mockClass->generate();
if ($callOriginalConstructor) {
if (\count($arguments) === 0) {
if (count($arguments) === 0) {
$object = new $className;
} else {
try {
$class = new \ReflectionClass($className);
$class = new ReflectionClass($className);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
@@ -600,14 +651,14 @@ final class Generator
}
if ($callOriginalMethods) {
if (!\is_object($proxyTarget)) {
if (\count($arguments) === 0) {
if (!is_object($proxyTarget)) {
if (count($arguments) === 0) {
$proxyTarget = new $type;
} else {
try {
$class = new \ReflectionClass($type);
$class = new ReflectionClass($type);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
@@ -646,13 +697,13 @@ final class Generator
$class = null;
$mockMethods = new MockMethodSet;
if (\is_array($type)) {
if (is_array($type)) {
$interfaceMethods = [];
foreach ($type as $_type) {
if (!\interface_exists($_type, $callAutoload)) {
if (!interface_exists($_type, $callAutoload)) {
throw new RuntimeException(
\sprintf(
sprintf(
'Interface "%s" does not exist.',
$_type
)
@@ -662,9 +713,9 @@ final class Generator
$additionalInterfaces[] = $_type;
try {
$typeClass = new \ReflectionClass($_type);
$typeClass = new ReflectionClass($_type);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
@@ -674,9 +725,9 @@ final class Generator
// @codeCoverageIgnoreEnd
foreach ($this->getClassMethods($_type) as $method) {
if (\in_array($method, $interfaceMethods, true)) {
if (in_array($method, $interfaceMethods, true)) {
throw new RuntimeException(
\sprintf(
sprintf(
'Duplicate method "%s" not allowed.',
$method
)
@@ -686,7 +737,7 @@ final class Generator
try {
$methodReflection = $typeClass->getMethod($method);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
@@ -714,9 +765,9 @@ final class Generator
'Mock_'
);
if (\class_exists($mockClassName['fullClassName'], $callAutoload)) {
if (class_exists($mockClassName['fullClassName'], $callAutoload)) {
$isClass = true;
} elseif (\interface_exists($mockClassName['fullClassName'], $callAutoload)) {
} elseif (interface_exists($mockClassName['fullClassName'], $callAutoload)) {
$isInterface = true;
}
@@ -734,9 +785,9 @@ final class Generator
$mockedCloneMethod = true;
} else {
try {
$class = new \ReflectionClass($mockClassName['fullClassName']);
$class = new ReflectionClass($mockClassName['fullClassName']);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
@@ -747,7 +798,7 @@ final class Generator
if ($class->isFinal()) {
throw new RuntimeException(
\sprintf(
sprintf(
'Class "%s" is declared "final" and cannot be mocked.',
$mockClassName['fullClassName']
)
@@ -755,15 +806,15 @@ final class Generator
}
// @see https://github.com/sebastianbergmann/phpunit/issues/2995
if ($isInterface && $class->implementsInterface(\Throwable::class)) {
$actualClassName = \Exception::class;
if ($isInterface && $class->implementsInterface(Throwable::class)) {
$actualClassName = Exception::class;
$additionalInterfaces[] = $class->getName();
$isInterface = false;
try {
$class = new \ReflectionClass($actualClassName);
$class = new ReflectionClass($actualClassName);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
@@ -779,7 +830,7 @@ final class Generator
try {
$classMethod = $class->getMethod($methodName);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
@@ -806,13 +857,13 @@ final class Generator
}
// @see https://github.com/sebastianbergmann/phpunit-mock-objects/issues/103
if ($isInterface && $class->implementsInterface(\Traversable::class) &&
!$class->implementsInterface(\Iterator::class) &&
!$class->implementsInterface(\IteratorAggregate::class)) {
$additionalInterfaces[] = \Iterator::class;
if ($isInterface && $class->implementsInterface(Traversable::class) &&
!$class->implementsInterface(Iterator::class) &&
!$class->implementsInterface(IteratorAggregate::class)) {
$additionalInterfaces[] = Iterator::class;
$mockMethods->addMethods(
...$this->mockClassMethods(\Iterator::class, $callOriginalMethods, $cloneArguments)
...$this->mockClassMethods(Iterator::class, $callOriginalMethods, $cloneArguments)
);
}
@@ -820,7 +871,7 @@ final class Generator
try {
$cloneMethod = $class->getMethod('__clone');
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
@@ -853,13 +904,13 @@ final class Generator
);
}
if (\is_array($explicitMethods)) {
if (is_array($explicitMethods)) {
foreach ($explicitMethods as $methodName) {
if ($class !== null && $class->hasMethod($methodName)) {
try {
$method = $class->getMethod($methodName);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
@@ -896,17 +947,17 @@ final class Generator
$method = '';
if (!$mockMethods->hasMethod('method') && (!isset($class) || !$class->hasMethod('method'))) {
$method = \PHP_EOL . ' use \PHPUnit\Framework\MockObject\Method;';
$method = PHP_EOL . ' use \PHPUnit\Framework\MockObject\Method;';
}
$cloneTrait = '';
if ($mockedCloneMethod) {
$cloneTrait = \PHP_EOL . ' use \PHPUnit\Framework\MockObject\MockedCloneMethod;';
$cloneTrait = PHP_EOL . ' use \PHPUnit\Framework\MockObject\MockedCloneMethod;';
}
if ($unmockedCloneMethod) {
$cloneTrait = \PHP_EOL . ' use \PHPUnit\Framework\MockObject\UnmockedCloneMethod;';
$cloneTrait = PHP_EOL . ' use \PHPUnit\Framework\MockObject\UnmockedCloneMethod;';
}
$classTemplate->setVar(
@@ -937,19 +988,19 @@ final class Generator
*/
private function generateClassName($type, string $className, string $prefix): array
{
if (\is_array($type)) {
$type = \implode('_', $type);
if (is_array($type)) {
$type = implode('_', $type);
}
if ($type[0] === '\\') {
$type = \substr($type, 1);
$type = substr($type, 1);
}
$classNameParts = \explode('\\', $type);
$classNameParts = explode('\\', $type);
if (\count($classNameParts) > 1) {
$type = \array_pop($classNameParts);
$namespaceName = \implode('\\', $classNameParts);
if (count($classNameParts) > 1) {
$type = array_pop($classNameParts);
$namespaceName = implode('\\', $classNameParts);
$fullClassName = $namespaceName . '\\' . $type;
} else {
$namespaceName = '';
@@ -959,8 +1010,8 @@ final class Generator
if ($className === '') {
do {
$className = $prefix . $type . '_' .
\substr(\md5((string) \mt_rand()), 0, 8);
} while (\class_exists($className, false));
substr(md5((string) mt_rand()), 0, 8);
} while (class_exists($className, false));
}
return [
@@ -976,16 +1027,16 @@ final class Generator
$buffer = 'class ';
$additionalInterfaces[] = MockObject::class;
$interfaces = \implode(', ', $additionalInterfaces);
$interfaces = implode(', ', $additionalInterfaces);
if ($isInterface) {
$buffer .= \sprintf(
$buffer .= sprintf(
'%s implements %s',
$mockClassName['className'],
$interfaces
);
if (!\in_array($mockClassName['originalClassName'], $additionalInterfaces, true)) {
if (!in_array($mockClassName['originalClassName'], $additionalInterfaces, true)) {
$buffer .= ', ';
if (!empty($mockClassName['namespaceName'])) {
@@ -995,7 +1046,7 @@ final class Generator
$buffer .= $mockClassName['originalClassName'];
}
} else {
$buffer .= \sprintf(
$buffer .= sprintf(
'%s extends %s%s implements %s',
$mockClassName['className'],
!empty($mockClassName['namespaceName']) ? $mockClassName['namespaceName'] . '\\' : '',
@@ -1007,7 +1058,7 @@ final class Generator
return $buffer;
}
private function canMockMethod(\ReflectionMethod $method): bool
private function canMockMethod(ReflectionMethod $method): bool
{
return !($this->isConstructor($method) || $method->isFinal() || $method->isPrivate() || $this->isMethodNameBlacklisted($method->getName()));
}
@@ -1017,12 +1068,12 @@ final class Generator
return isset(self::BLACKLISTED_METHOD_NAMES[$name]);
}
private function getTemplate(string $template): \Text_Template
private function getTemplate(string $template): Text_Template
{
$filename = __DIR__ . \DIRECTORY_SEPARATOR . 'Generator' . \DIRECTORY_SEPARATOR . $template;
$filename = __DIR__ . DIRECTORY_SEPARATOR . 'Generator' . DIRECTORY_SEPARATOR . $template;
if (!isset(self::$templates[$filename])) {
self::$templates[$filename] = new \Text_Template($filename);
self::$templates[$filename] = new Text_Template($filename);
}
return self::$templates[$filename];
@@ -1031,19 +1082,19 @@ final class Generator
/**
* @see https://github.com/sebastianbergmann/phpunit/issues/4139#issuecomment-605409765
*/
private function isConstructor(\ReflectionMethod $method): bool
private function isConstructor(ReflectionMethod $method): bool
{
$methodName = \strtolower($method->getName());
$methodName = strtolower($method->getName());
if ($methodName === '__construct') {
return true;
}
if (\PHP_MAJOR_VERSION >= 8) {
if (PHP_MAJOR_VERSION >= 8) {
return false;
}
$className = \strtolower($method->getDeclaringClass()->getName());
$className = strtolower($method->getDeclaringClass()->getName());
return $methodName === $className;
}

View File

@@ -9,9 +9,18 @@
*/
namespace PHPUnit\Framework\MockObject;
use function array_map;
use function implode;
use function is_object;
use function ltrim;
use function sprintf;
use function strpos;
use function strtolower;
use function substr;
use PHPUnit\Framework\SelfDescribing;
use PHPUnit\Util\Type;
use SebastianBergmann\Exporter\Exporter;
use stdClass;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
@@ -61,14 +70,14 @@ final class Invocation implements SelfDescribing
$this->object = $object;
$this->proxiedCall = $proxiedCall;
$returnType = \ltrim($returnType, ': ');
$returnType = ltrim($returnType, ': ');
if (\strtolower($methodName) === '__tostring') {
if (strtolower($methodName) === '__tostring') {
$returnType = 'string';
}
if (\strpos($returnType, '?') === 0) {
$returnType = \substr($returnType, 1);
if (strpos($returnType, '?') === 0) {
$returnType = substr($returnType, 1);
$this->isReturnTypeNullable = true;
}
@@ -79,7 +88,7 @@ final class Invocation implements SelfDescribing
}
foreach ($this->parameters as $key => $value) {
if (\is_object($value)) {
if (is_object($value)) {
$this->parameters[$key] = $this->cloneObject($value);
}
}
@@ -111,7 +120,7 @@ final class Invocation implements SelfDescribing
return;
}
switch (\strtolower($this->returnType)) {
switch (strtolower($this->returnType)) {
case '':
case 'void':
return;
@@ -132,11 +141,11 @@ final class Invocation implements SelfDescribing
return [];
case 'object':
return new \stdClass;
return new stdClass;
case 'callable':
case 'closure':
return function (): void {
return static function (): void {
};
case 'traversable':
@@ -159,18 +168,18 @@ final class Invocation implements SelfDescribing
{
$exporter = new Exporter;
return \sprintf(
return sprintf(
'%s::%s(%s)%s',
$this->className,
$this->methodName,
\implode(
implode(
', ',
\array_map(
array_map(
[$exporter, 'shortenedExport'],
$this->parameters
)
),
$this->returnType ? \sprintf(': %s', $this->returnType) : ''
$this->returnType ? sprintf(': %s', $this->returnType) : ''
);
}

View File

@@ -9,10 +9,13 @@
*/
namespace PHPUnit\Framework\MockObject;
use function sprintf;
use function strtolower;
use Exception;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\MockObject\Builder\InvocationMocker;
use PHPUnit\Framework\MockObject\Rule\InvocationOrder;
use Throwable;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
@@ -40,7 +43,7 @@ final class InvocationHandler
private $returnValueGeneration;
/**
* @var \Throwable
* @var Throwable
*/
private $deferredError;
@@ -143,14 +146,14 @@ final class InvocationHandler
if (!$this->returnValueGeneration) {
$exception = new ExpectationFailedException(
\sprintf(
sprintf(
'Return value inference disabled and no expectation set up for %s::%s()',
$invocation->getClassName(),
$invocation->getMethodName()
)
);
if (\strtolower($invocation->getMethodName()) === '__tostring') {
if (strtolower($invocation->getMethodName()) === '__tostring') {
$this->deferredError = $exception;
return '';

View File

@@ -9,6 +9,10 @@
*/
namespace PHPUnit\Framework\MockObject;
use function assert;
use function implode;
use function sprintf;
use Exception;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\MockObject\Rule\AnyInvokedCount;
use PHPUnit\Framework\MockObject\Rule\AnyParameters;
@@ -100,9 +104,9 @@ final class Matcher
}
/**
* @throws \Exception
* @throws RuntimeException
* @throws Exception
* @throws ExpectationFailedException
* @throws RuntimeException
*/
public function invoked(Invocation $invocation)
{
@@ -117,13 +121,13 @@ final class Matcher
if (!$matcher) {
throw new RuntimeException(
\sprintf(
sprintf(
'No builder found for match builder identification <%s>',
$this->afterMatchBuilderId
)
);
}
\assert($matcher instanceof self);
assert($matcher instanceof self);
if ($matcher->invocationRule->hasBeenInvoked()) {
$this->afterMatchBuilderIsInvoked = true;
@@ -138,7 +142,7 @@ final class Matcher
}
} catch (ExpectationFailedException $e) {
throw new ExpectationFailedException(
\sprintf(
sprintf(
"Expectation failed for %s when %s\n%s",
$this->methodNameRule->toString(),
$this->invocationRule->toString(),
@@ -156,9 +160,9 @@ final class Matcher
}
/**
* @throws RuntimeException
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws ExpectationFailedException
* @throws RuntimeException
*/
public function matches(Invocation $invocation): bool
{
@@ -169,13 +173,13 @@ final class Matcher
if (!$matcher) {
throw new RuntimeException(
\sprintf(
sprintf(
'No builder found for match builder identification <%s>',
$this->afterMatchBuilderId
)
);
}
\assert($matcher instanceof self);
assert($matcher instanceof self);
if (!$matcher->invocationRule->hasBeenInvoked()) {
return false;
@@ -196,7 +200,7 @@ final class Matcher
}
} catch (ExpectationFailedException $e) {
throw new ExpectationFailedException(
\sprintf(
sprintf(
"Expectation failed for %s when %s\n%s",
$this->methodNameRule->toString(),
$this->invocationRule->toString(),
@@ -210,9 +214,9 @@ final class Matcher
}
/**
* @throws RuntimeException
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws ExpectationFailedException
* @throws RuntimeException
*/
public function verify(): void
{
@@ -235,7 +239,7 @@ final class Matcher
}
} catch (ExpectationFailedException $e) {
throw new ExpectationFailedException(
\sprintf(
sprintf(
"Expectation failed for %s when %s.\n%s",
$this->methodNameRule->toString(),
$this->invocationRule->toString(),
@@ -269,6 +273,6 @@ final class Matcher
$list[] = 'will ' . $this->stub->toString();
}
return \implode(' ', $list);
return implode(' ', $list);
}
}

View File

@@ -9,6 +9,9 @@
*/
namespace PHPUnit\Framework\MockObject;
use function is_string;
use function sprintf;
use function strtolower;
use PHPUnit\Framework\Constraint\Constraint;
/**
@@ -28,7 +31,7 @@ final class MethodNameConstraint extends Constraint
public function toString(): string
{
return \sprintf(
return sprintf(
'is "%s"',
$this->methodName
);
@@ -36,10 +39,10 @@ final class MethodNameConstraint extends Constraint
protected function matches($other): bool
{
if (!\is_string($other)) {
if (!is_string($other)) {
return false;
}
return \strtolower($this->methodName) === \strtolower($other);
return strtolower($this->methodName) === strtolower($other);
}
}

View File

@@ -9,7 +9,12 @@
*/
namespace PHPUnit\Framework\MockObject;
use function array_diff;
use function array_merge;
use function sprintf;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use ReflectionException;
/**
* @psalm-template MockedType
@@ -196,14 +201,14 @@ final class MockBuilder
if ($methods === null) {
$this->methods = $methods;
} else {
$this->methods = \array_merge($this->methods ?? [], $methods);
$this->methods = array_merge($this->methods ?? [], $methods);
}
return $this;
}
/**
* Specifies the subset of methods to mock, requiring each to exist in the class
* Specifies the subset of methods to mock, requiring each to exist in the class.
*
* @param string[] $methods
*
@@ -220,9 +225,9 @@ final class MockBuilder
}
try {
$reflector = new \ReflectionClass($this->type);
$reflector = new ReflectionClass($this->type);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
@@ -234,7 +239,7 @@ final class MockBuilder
foreach ($methods as $method) {
if (!$reflector->hasMethod($method)) {
throw new RuntimeException(
\sprintf(
sprintf(
'Trying to set mock method "%s" with onlyMethods, but it does not exist in class "%s". Use addMethods() for methods that don\'t exist in the class.',
$method,
$this->type
@@ -243,13 +248,13 @@ final class MockBuilder
}
}
$this->methods = \array_merge($this->methods ?? [], $methods);
$this->methods = array_merge($this->methods ?? [], $methods);
return $this;
}
/**
* Specifies methods that don't exist in the class which you want to mock
* Specifies methods that don't exist in the class which you want to mock.
*
* @param string[] $methods
*
@@ -266,9 +271,9 @@ final class MockBuilder
}
try {
$reflector = new \ReflectionClass($this->type);
$reflector = new ReflectionClass($this->type);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new RuntimeException(
$e->getMessage(),
(int) $e->getCode(),
@@ -280,7 +285,7 @@ final class MockBuilder
foreach ($methods as $method) {
if ($reflector->hasMethod($method)) {
throw new RuntimeException(
\sprintf(
sprintf(
'Trying to set mock method "%s" with addMethods(), but it exists in class "%s". Use onlyMethods() for methods that exist in the class.',
$method,
$this->type
@@ -289,7 +294,7 @@ final class MockBuilder
}
}
$this->methods = \array_merge($this->methods ?? [], $methods);
$this->methods = array_merge($this->methods ?? [], $methods);
return $this;
}
@@ -300,7 +305,7 @@ final class MockBuilder
public function setMethodsExcept(array $methods = []): self
{
return $this->setMethods(
\array_diff(
array_diff(
$this->generator->getClassMethods($this->type),
$methods
)

View File

@@ -9,6 +9,9 @@
*/
namespace PHPUnit\Framework\MockObject;
use function call_user_func;
use function class_exists;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
@@ -38,10 +41,10 @@ final class MockClass implements MockType
public function generate(): string
{
if (!\class_exists($this->mockName, false)) {
if (!class_exists($this->mockName, false)) {
eval($this->classCode);
\call_user_func(
call_user_func(
[
$this->mockName,
'__phpunit_initConfigurableMethods',

View File

@@ -9,10 +9,23 @@
*/
namespace PHPUnit\Framework\MockObject;
use const DIRECTORY_SEPARATOR;
use function implode;
use function is_string;
use function preg_match;
use function preg_replace;
use function sprintf;
use function substr_count;
use function trim;
use function var_export;
use ReflectionException;
use ReflectionMethod;
use ReflectionNamedType;
use SebastianBergmann\Type\ObjectType;
use SebastianBergmann\Type\Type;
use SebastianBergmann\Type\UnknownType;
use SebastianBergmann\Type\VoidType;
use Text_Template;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
@@ -20,7 +33,7 @@ use SebastianBergmann\Type\VoidType;
final class MockMethod
{
/**
* @var \Text_Template[]
* @var Text_Template[]
*/
private static $templates = [];
@@ -87,7 +100,7 @@ final class MockMethod
/**
* @throws RuntimeException
*/
public static function fromReflection(\ReflectionMethod $method, bool $callOriginalMethod, bool $cloneArguments): self
public static function fromReflection(ReflectionMethod $method, bool $callOriginalMethod, bool $cloneArguments): self
{
if ($method->isPrivate()) {
$modifier = 'private';
@@ -109,9 +122,9 @@ final class MockMethod
$docComment = $method->getDocComment();
if (\is_string($docComment) &&
\preg_match('#\*[ \t]*+@deprecated[ \t]*+(.*?)\r?+\n[ \t]*+\*(?:[ \t]*+@|/$)#s', $docComment, $deprecation)) {
$deprecation = \trim(\preg_replace('#[ \t]*\r?\n[ \t]*+\*[ \t]*+#', ' ', $deprecation[1]));
if (is_string($docComment) &&
preg_match('#\*[ \t]*+@deprecated[ \t]*+(.*?)\r?+\n[ \t]*+\*(?:[ \t]*+@|/$)#s', $docComment, $deprecation)) {
$deprecation = trim(preg_replace('#[ \t]*\r?\n[ \t]*+\*[ \t]*+#', ' ', $deprecation[1]));
} else {
$deprecation = null;
}
@@ -179,12 +192,12 @@ final class MockMethod
if ($this->static) {
$templateFile = 'mocked_static_method.tpl';
} elseif ($this->returnType instanceof VoidType) {
$templateFile = \sprintf(
$templateFile = sprintf(
'%s_method_void.tpl',
$this->callOriginalMethod ? 'proxied' : 'mocked'
);
} else {
$templateFile = \sprintf(
$templateFile = sprintf(
'%s_method.tpl',
$this->callOriginalMethod ? 'proxied' : 'mocked'
);
@@ -197,7 +210,7 @@ final class MockMethod
$deprecationTemplate = $this->getTemplate('deprecation.tpl');
$deprecationTemplate->setVar([
'deprecation' => \var_export($deprecation, true),
'deprecation' => var_export($deprecation, true),
]);
$deprecation = $deprecationTemplate->render();
@@ -210,7 +223,7 @@ final class MockMethod
'arguments_decl' => $this->argumentsForDeclaration,
'arguments_call' => $this->argumentsForCall,
'return_declaration' => $this->returnType->getReturnTypeDeclaration(),
'arguments_count' => !empty($this->argumentsForCall) ? \substr_count($this->argumentsForCall, ',') + 1 : 0,
'arguments_count' => !empty($this->argumentsForCall) ? substr_count($this->argumentsForCall, ',') + 1 : 0,
'class_name' => $this->className,
'method_name' => $this->methodName,
'modifier' => $this->modifier,
@@ -228,12 +241,12 @@ final class MockMethod
return $this->returnType;
}
private function getTemplate(string $template): \Text_Template
private function getTemplate(string $template): Text_Template
{
$filename = __DIR__ . \DIRECTORY_SEPARATOR . 'Generator' . \DIRECTORY_SEPARATOR . $template;
$filename = __DIR__ . DIRECTORY_SEPARATOR . 'Generator' . DIRECTORY_SEPARATOR . $template;
if (!isset(self::$templates[$filename])) {
self::$templates[$filename] = new \Text_Template($filename);
self::$templates[$filename] = new Text_Template($filename);
}
return self::$templates[$filename];
@@ -244,7 +257,7 @@ final class MockMethod
*
* @throws RuntimeException
*/
private static function getMethodParametersForDeclaration(\ReflectionMethod $method): string
private static function getMethodParametersForDeclaration(ReflectionMethod $method): string
{
$parameters = [];
@@ -268,7 +281,7 @@ final class MockMethod
if ($parameter->hasType()) {
$type = $parameter->getType();
if ($type instanceof \ReflectionNamedType) {
if ($type instanceof ReflectionNamedType) {
$typeName = $type->getName();
}
}
@@ -276,7 +289,7 @@ final class MockMethod
if ($parameter->isVariadic()) {
$name = '...' . $name;
} elseif ($parameter->isDefaultValueAvailable()) {
$default = ' = ' . \var_export($parameter->getDefaultValue(), true);
$default = ' = ' . var_export($parameter->getDefaultValue(), true);
} elseif ($parameter->isOptional()) {
$default = ' = null';
}
@@ -300,15 +313,15 @@ final class MockMethod
$parameters[] = $nullable . $typeDeclaration . $reference . $name . $default;
}
return \implode(', ', $parameters);
return implode(', ', $parameters);
}
/**
* Returns the parameters of a function or method.
*
* @throws \ReflectionException
* @throws ReflectionException
*/
private static function getMethodParametersForCall(\ReflectionMethod $method): string
private static function getMethodParametersForCall(ReflectionMethod $method): string
{
$parameters = [];
@@ -333,10 +346,10 @@ final class MockMethod
}
}
return \implode(', ', $parameters);
return implode(', ', $parameters);
}
private static function deriveReturnType(\ReflectionMethod $method): Type
private static function deriveReturnType(ReflectionMethod $method): Type
{
$returnType = $method->getReturnType();
@@ -355,7 +368,7 @@ final class MockMethod
if ($parentClass === false) {
throw new RuntimeException(
\sprintf(
sprintf(
'Cannot mock %s::%s because "parent" return type declaration is used but %s does not have a parent class',
$method->getDeclaringClass()->getName(),
$method->getName(),

View File

@@ -9,6 +9,10 @@
*/
namespace PHPUnit\Framework\MockObject;
use function array_key_exists;
use function array_values;
use function strtolower;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
@@ -22,7 +26,7 @@ final class MockMethodSet
public function addMethods(MockMethod ...$methods): void
{
foreach ($methods as $method) {
$this->methods[\strtolower($method->getName())] = $method;
$this->methods[strtolower($method->getName())] = $method;
}
}
@@ -31,11 +35,11 @@ final class MockMethodSet
*/
public function asArray(): array
{
return \array_values($this->methods);
return array_values($this->methods);
}
public function hasMethod(string $methodName): bool
{
return \array_key_exists(\strtolower($methodName), $this->methods);
return array_key_exists(strtolower($methodName), $this->methods);
}
}

View File

@@ -9,6 +9,8 @@
*/
namespace PHPUnit\Framework\MockObject;
use function class_exists;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
@@ -32,7 +34,7 @@ final class MockTrait implements MockType
public function generate(): string
{
if (!\class_exists($this->mockName, false)) {
if (!class_exists($this->mockName, false)) {
eval($this->classCode);
}

View File

@@ -9,6 +9,10 @@
*/
namespace PHPUnit\Framework\MockObject\Rule;
use function count;
use function gettype;
use function is_iterable;
use function sprintf;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\Constraint\IsEqual;
use PHPUnit\Framework\ExpectationFailedException;
@@ -36,12 +40,12 @@ final class ConsecutiveParameters implements ParametersRule
public function __construct(array $parameterGroups)
{
foreach ($parameterGroups as $index => $parameters) {
if (!\is_iterable($parameters)) {
if (!is_iterable($parameters)) {
throw new InvalidParameterGroupException(
\sprintf(
sprintf(
'Parameter group #%d must be an array or Traversable, got %s',
$index,
\gettype($parameters)
gettype($parameters)
)
);
}
@@ -62,13 +66,13 @@ final class ConsecutiveParameters implements ParametersRule
}
/**
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws ExpectationFailedException
*/
public function apply(BaseInvocation $invocation): void
{
$this->invocations[] = $invocation;
$callIndex = \count($this->invocations) - 1;
$callIndex = count($this->invocations) - 1;
$this->verifyInvocation($invocation, $callIndex);
}
@@ -85,12 +89,12 @@ final class ConsecutiveParameters implements ParametersRule
}
/**
* Verify a single invocation
* Verify a single invocation.
*
* @param int $callIndex
*
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws ExpectationFailedException
*/
private function verifyInvocation(BaseInvocation $invocation, $callIndex): void
{
@@ -107,9 +111,9 @@ final class ConsecutiveParameters implements ParametersRule
$parameters = $this->parameterGroups[$callIndex];
if (\count($invocation->getParameters()) < \count($parameters)) {
if (count($invocation->getParameters()) < count($parameters)) {
throw new ExpectationFailedException(
\sprintf(
sprintf(
'Parameter count for invocation %s is too low.',
$invocation->toString()
)
@@ -119,7 +123,7 @@ final class ConsecutiveParameters implements ParametersRule
foreach ($parameters as $i => $parameter) {
$parameter->evaluate(
$invocation->getParameters()[$i],
\sprintf(
sprintf(
'Parameter %s for invocation #%d %s does not match expected ' .
'value.',
$i,

View File

@@ -9,6 +9,7 @@
*/
namespace PHPUnit\Framework\MockObject\Rule;
use function count;
use PHPUnit\Framework\MockObject\Invocation as BaseInvocation;
use PHPUnit\Framework\MockObject\Verifiable;
use PHPUnit\Framework\SelfDescribing;
@@ -25,12 +26,12 @@ abstract class InvocationOrder implements SelfDescribing, Verifiable
public function getInvocationCount(): int
{
return \count($this->invocations);
return count($this->invocations);
}
public function hasBeenInvoked(): bool
{
return \count($this->invocations) > 0;
return count($this->invocations) > 0;
}
final public function invoked(BaseInvocation $invocation)

View File

@@ -9,6 +9,7 @@
*/
namespace PHPUnit\Framework\MockObject\Rule;
use function sprintf;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\MockObject\Invocation as BaseInvocation;
@@ -57,7 +58,7 @@ class InvokedAtIndex extends InvocationOrder
{
if ($this->currentIndex < $this->sequenceIndex) {
throw new ExpectationFailedException(
\sprintf(
sprintf(
'The expected invocation at index %s was never reached.',
$this->sequenceIndex
)

View File

@@ -9,6 +9,7 @@
*/
namespace PHPUnit\Framework\MockObject\Rule;
use function sprintf;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\MockObject\Invocation as BaseInvocation;
@@ -57,7 +58,7 @@ final class InvokedCount extends InvocationOrder
if ($count !== $this->expectedCount) {
throw new ExpectationFailedException(
\sprintf(
sprintf(
'Method was expected to be called %d times, ' .
'actually called %d times.',
$this->expectedCount,
@@ -89,7 +90,7 @@ final class InvokedCount extends InvocationOrder
break;
default:
$message .= \sprintf(
$message .= sprintf(
'was not expected to be called more than %d times.',
$this->expectedCount
);

View File

@@ -9,6 +9,7 @@
*/
namespace PHPUnit\Framework\MockObject\Rule;
use function is_string;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\InvalidArgumentException;
use PHPUnit\Framework\MockObject\Invocation as BaseInvocation;
@@ -31,7 +32,7 @@ final class MethodName
*/
public function __construct($constraint)
{
if (\is_string($constraint)) {
if (is_string($constraint)) {
$constraint = new MethodNameConstraint($constraint);
}

View File

@@ -9,6 +9,10 @@
*/
namespace PHPUnit\Framework\MockObject\Rule;
use function count;
use function get_class;
use function sprintf;
use Exception;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\Constraint\IsAnything;
use PHPUnit\Framework\Constraint\IsEqual;
@@ -67,7 +71,7 @@ final class Parameters implements ParametersRule
}
/**
* @throws \Exception
* @throws Exception
*/
public function apply(BaseInvocation $invocation): void
{
@@ -88,8 +92,8 @@ final class Parameters implements ParametersRule
* does the rule will get the invoked() method called which should check
* if an expectation is met.
*
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws ExpectationFailedException
*/
public function verify(): void
{
@@ -97,8 +101,8 @@ final class Parameters implements ParametersRule
}
/**
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws ExpectationFailedException
*/
private function doVerify(): bool
{
@@ -110,27 +114,27 @@ final class Parameters implements ParametersRule
throw new ExpectationFailedException('Mocked method does not exist.');
}
if (\count($this->invocation->getParameters()) < \count($this->parameters)) {
if (count($this->invocation->getParameters()) < count($this->parameters)) {
$message = 'Parameter count for invocation %s is too low.';
// The user called `->with($this->anything())`, but may have meant
// `->withAnyParameters()`.
//
// @see https://github.com/sebastianbergmann/phpunit-mock-objects/issues/199
if (\count($this->parameters) === 1 &&
\get_class($this->parameters[0]) === IsAnything::class) {
if (count($this->parameters) === 1 &&
get_class($this->parameters[0]) === IsAnything::class) {
$message .= "\nTo allow 0 or more parameters with any value, omit ->with() or use ->withAnyParameters() instead.";
}
throw new ExpectationFailedException(
\sprintf($message, $this->invocation->toString())
sprintf($message, $this->invocation->toString())
);
}
foreach ($this->parameters as $i => $parameter) {
$parameter->evaluate(
$this->invocation->getParameters()[$i],
\sprintf(
sprintf(
'Parameter %s for invocation %s does not match expected ' .
'value.',
$i,

View File

@@ -9,6 +9,8 @@
*/
namespace PHPUnit\Framework\MockObject\Stub;
use function array_shift;
use function sprintf;
use PHPUnit\Framework\MockObject\Invocation;
use SebastianBergmann\Exporter\Exporter;
@@ -34,7 +36,7 @@ final class ConsecutiveCalls implements Stub
public function invoke(Invocation $invocation)
{
$this->value = \array_shift($this->stack);
$this->value = array_shift($this->stack);
if ($this->value instanceof Stub) {
$this->value = $this->value->invoke($invocation);
@@ -47,7 +49,7 @@ final class ConsecutiveCalls implements Stub
{
$exporter = new Exporter;
return \sprintf(
return sprintf(
'return user-specified value %s',
$exporter->export($this->value)
);

View File

@@ -9,8 +9,10 @@
*/
namespace PHPUnit\Framework\MockObject\Stub;
use function sprintf;
use PHPUnit\Framework\MockObject\Invocation;
use SebastianBergmann\Exporter\Exporter;
use Throwable;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
@@ -19,13 +21,13 @@ final class Exception implements Stub
{
private $exception;
public function __construct(\Throwable $exception)
public function __construct(Throwable $exception)
{
$this->exception = $exception;
}
/**
* @throws \Throwable
* @throws Throwable
*/
public function invoke(Invocation $invocation): void
{
@@ -36,7 +38,7 @@ final class Exception implements Stub
{
$exporter = new Exporter;
return \sprintf(
return sprintf(
'raise user-specified exception %s',
$exporter->export($this->exception)
);

View File

@@ -9,6 +9,7 @@
*/
namespace PHPUnit\Framework\MockObject\Stub;
use function sprintf;
use PHPUnit\Framework\MockObject\Invocation;
/**
@@ -35,6 +36,6 @@ final class ReturnArgument implements Stub
public function toString(): string
{
return \sprintf('return argument #%d', $this->argumentIndex);
return sprintf('return argument #%d', $this->argumentIndex);
}
}

View File

@@ -9,6 +9,11 @@
*/
namespace PHPUnit\Framework\MockObject\Stub;
use function call_user_func_array;
use function get_class;
use function is_array;
use function is_object;
use function sprintf;
use PHPUnit\Framework\MockObject\Invocation;
/**
@@ -25,21 +30,21 @@ final class ReturnCallback implements Stub
public function invoke(Invocation $invocation)
{
return \call_user_func_array($this->callback, $invocation->getParameters());
return call_user_func_array($this->callback, $invocation->getParameters());
}
public function toString(): string
{
if (\is_array($this->callback)) {
if (\is_object($this->callback[0])) {
$class = \get_class($this->callback[0]);
if (is_array($this->callback)) {
if (is_object($this->callback[0])) {
$class = get_class($this->callback[0]);
$type = '->';
} else {
$class = $this->callback[0];
$type = '::';
}
return \sprintf(
return sprintf(
'return result of user defined callback %s%s%s() with the ' .
'passed arguments',
$class,

View File

@@ -9,6 +9,7 @@
*/
namespace PHPUnit\Framework\MockObject\Stub;
use function sprintf;
use PHPUnit\Framework\MockObject\Invocation;
use SebastianBergmann\Exporter\Exporter;
@@ -36,7 +37,7 @@ final class ReturnReference implements Stub
{
$exporter = new Exporter;
return \sprintf(
return sprintf(
'return user-specified reference %s',
$exporter->export($this->reference)
);

View File

@@ -9,6 +9,7 @@
*/
namespace PHPUnit\Framework\MockObject\Stub;
use function sprintf;
use PHPUnit\Framework\MockObject\Invocation;
use SebastianBergmann\Exporter\Exporter;
@@ -36,7 +37,7 @@ final class ReturnStub implements Stub
{
$exporter = new Exporter;
return \sprintf(
return sprintf(
'return user-specified value %s',
$exporter->export($this->value)
);

View File

@@ -9,6 +9,9 @@
*/
namespace PHPUnit\Framework\MockObject\Stub;
use function array_pop;
use function count;
use function is_array;
use PHPUnit\Framework\MockObject\Invocation;
/**
@@ -28,14 +31,14 @@ final class ReturnValueMap implements Stub
public function invoke(Invocation $invocation)
{
$parameterCount = \count($invocation->getParameters());
$parameterCount = count($invocation->getParameters());
foreach ($this->valueMap as $map) {
if (!\is_array($map) || $parameterCount !== (\count($map) - 1)) {
if (!is_array($map) || $parameterCount !== (count($map) - 1)) {
continue;
}
$return = \array_pop($map);
$return = array_pop($map);
if ($invocation->getParameters() === $map) {
return $return;

View File

@@ -9,22 +9,29 @@
*/
namespace PHPUnit\Framework;
use function assert;
use function count;
use function get_class;
use function sprintf;
use function trim;
use PHPUnit\Util\Filter;
use PHPUnit\Util\InvalidDataSetException;
use PHPUnit\Util\Test as TestUtil;
use ReflectionClass;
use Throwable;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class TestBuilder
{
public function build(\ReflectionClass $theClass, string $methodName): Test
public function build(ReflectionClass $theClass, string $methodName): Test
{
$className = $theClass->getName();
if (!$theClass->isInstantiable()) {
return new WarningTestCase(
\sprintf('Cannot instantiate class "%s".', $className)
sprintf('Cannot instantiate class "%s".', $className)
);
}
@@ -57,7 +64,7 @@ final class TestBuilder
$parameters = $constructor->getParameters();
// TestCase() or TestCase($name)
if (\count($parameters) < 2) {
if (count($parameters) < 2) {
$test = $this->buildTestWithoutData($className);
} // TestCase($name, $data)
else {
@@ -67,7 +74,7 @@ final class TestBuilder
$methodName
);
} catch (IncompleteTestError $e) {
$message = \sprintf(
$message = sprintf(
"Test for %s::%s marked incomplete by data provider\n%s",
$className,
$methodName,
@@ -76,7 +83,7 @@ final class TestBuilder
$data = new IncompleteTestCase($className, $methodName, $message);
} catch (SkippedTestError $e) {
$message = \sprintf(
$message = sprintf(
"Test for %s::%s skipped by data provider\n%s",
$className,
$methodName,
@@ -84,8 +91,8 @@ final class TestBuilder
);
$data = new SkippedTestCase($className, $methodName, $message);
} catch (\Throwable $t) {
$message = \sprintf(
} catch (Throwable $t) {
$message = sprintf(
"The data provider specified for %s::%s is invalid.\n%s",
$className,
$methodName,
@@ -155,7 +162,7 @@ final class TestBuilder
foreach ($data as $_dataName => $_data) {
$_test = new $className($methodName, $_data, $_dataName);
\assert($_test instanceof TestCase);
assert($_test instanceof TestCase);
$this->configureTestCase(
$_test,
@@ -206,25 +213,25 @@ final class TestBuilder
}
}
private function throwableToString(\Throwable $t): string
private function throwableToString(Throwable $t): string
{
$message = $t->getMessage();
if (empty(\trim($message))) {
if (empty(trim($message))) {
$message = '<no message>';
}
if ($t instanceof InvalidDataSetException) {
return \sprintf(
return sprintf(
"%s\n%s",
$message,
Filter::getFilteredStacktrace($t)
);
}
return \sprintf(
return sprintf(
"%s: %s\n%s",
\get_class($t),
get_class($t),
$message,
Filter::getFilteredStacktrace($t)
);

View File

@@ -9,6 +9,58 @@
*/
namespace PHPUnit\Framework;
use const LC_ALL;
use const LC_COLLATE;
use const LC_CTYPE;
use const LC_MESSAGES;
use const LC_MONETARY;
use const LC_NUMERIC;
use const LC_TIME;
use const PATHINFO_FILENAME;
use const PHP_EOL;
use const PHP_URL_PATH;
use function array_filter;
use function array_flip;
use function array_keys;
use function array_merge;
use function array_unique;
use function array_values;
use function assert;
use function basename;
use function call_user_func;
use function chdir;
use function class_exists;
use function clearstatcache;
use function count;
use function defined;
use function explode;
use function get_class;
use function get_include_path;
use function getcwd;
use function implode;
use function in_array;
use function ini_set;
use function is_array;
use function is_int;
use function is_object;
use function is_string;
use function libxml_clear_errors;
use function method_exists;
use function ob_end_clean;
use function ob_get_contents;
use function ob_get_level;
use function ob_start;
use function parse_url;
use function pathinfo;
use function preg_replace;
use function serialize;
use function setlocale;
use function sprintf;
use function strlen;
use function strpos;
use function substr;
use function trim;
use function var_export;
use DeepCopy\DeepCopy;
use PHPUnit\Framework\Constraint\Exception as ExceptionConstraint;
use PHPUnit\Framework\Constraint\ExceptionCode;
@@ -46,6 +98,8 @@ use Prophecy\Exception\Prediction\PredictionException;
use Prophecy\Prophecy\MethodProphecy;
use Prophecy\Prophecy\ObjectProphecy;
use Prophecy\Prophet;
use ReflectionClass;
use ReflectionException;
use SebastianBergmann\Comparator\Comparator;
use SebastianBergmann\Comparator\Factory as ComparatorFactory;
use SebastianBergmann\Diff\Differ;
@@ -54,10 +108,12 @@ use SebastianBergmann\GlobalState\Blacklist;
use SebastianBergmann\GlobalState\Restorer;
use SebastianBergmann\GlobalState\Snapshot;
use SebastianBergmann\ObjectEnumerator\Enumerator;
use Text_Template;
use Throwable;
abstract class TestCase extends Assert implements SelfDescribing, Test
{
private const LOCALE_CATEGORIES = [\LC_ALL, \LC_COLLATE, \LC_CTYPE, \LC_MONETARY, \LC_NUMERIC, \LC_TIME];
private const LOCALE_CATEGORIES = [LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_TIME];
/**
* @var ?bool
@@ -375,7 +431,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
return new ReturnSelfStub;
}
public static function throwException(\Throwable $exception): ExceptionStub
public static function throwException(Throwable $exception): ExceptionStub
{
return new ExceptionStub($exception);
}
@@ -438,9 +494,9 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
public function toString(): string
{
try {
$class = new \ReflectionClass($this);
$class = new ReflectionClass($this);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
@@ -449,7 +505,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
}
// @codeCoverageIgnoreEnd
$buffer = \sprintf(
$buffer = sprintf(
'%s::%s',
$class->name,
$this->getName(false)
@@ -523,7 +579,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
*/
public function expectExceptionObject(\Exception $exception): void
{
$this->expectException(\get_class($exception));
$this->expectException(get_class($exception));
$this->expectExceptionMessage($exception->getMessage());
$this->expectExceptionCode($exception->getCode());
}
@@ -619,14 +675,14 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
* Runs the test case and collects the results in a TestResult object.
* If no TestResult object is passed a new one will be created.
*
* @throws CodeCoverageException
* @throws UtilException
* @throws \SebastianBergmann\CodeCoverage\CoveredCodeNotExecutedException
* @throws \SebastianBergmann\CodeCoverage\InvalidArgumentException
* @throws \SebastianBergmann\CodeCoverage\MissingCoversAnnotationException
* @throws \SebastianBergmann\CodeCoverage\RuntimeException
* @throws \SebastianBergmann\CodeCoverage\UnintentionallyCoveredCodeException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws CodeCoverageException
* @throws UtilException
*/
public function run(TestResult $result = null): TestResult
{
@@ -648,9 +704,9 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
$runEntireClass = $this->runClassInSeparateProcess && !$this->runTestInSeparateProcess;
try {
$class = new \ReflectionClass($this);
$class = new ReflectionClass($this);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
@@ -660,11 +716,11 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
// @codeCoverageIgnoreEnd
if ($runEntireClass) {
$template = new \Text_Template(
$template = new Text_Template(
__DIR__ . '/../Util/PHP/Template/TestCaseClass.tpl'
);
} else {
$template = new \Text_Template(
$template = new Text_Template(
__DIR__ . '/../Util/PHP/Template/TestCaseMethod.tpl'
);
}
@@ -678,7 +734,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
$constants = '';
if (!empty($GLOBALS['__PHPUNIT_BOOTSTRAP'])) {
$globals = '$GLOBALS[\'__PHPUNIT_BOOTSTRAP\'] = ' . \var_export($GLOBALS['__PHPUNIT_BOOTSTRAP'], true) . ";\n";
$globals = '$GLOBALS[\'__PHPUNIT_BOOTSTRAP\'] = ' . var_export($GLOBALS['__PHPUNIT_BOOTSTRAP'], true) . ";\n";
} else {
$globals = '';
}
@@ -694,14 +750,14 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
$isStrictAboutTodoAnnotatedTests = $result->isStrictAboutTodoAnnotatedTests() ? 'true' : 'false';
$isStrictAboutResourceUsageDuringSmallTests = $result->isStrictAboutResourceUsageDuringSmallTests() ? 'true' : 'false';
if (\defined('PHPUNIT_COMPOSER_INSTALL')) {
$composerAutoload = \var_export(PHPUNIT_COMPOSER_INSTALL, true);
if (defined('PHPUNIT_COMPOSER_INSTALL')) {
$composerAutoload = var_export(PHPUNIT_COMPOSER_INSTALL, true);
} else {
$composerAutoload = '\'\'';
}
if (\defined('__PHPUNIT_PHAR__')) {
$phar = \var_export(__PHPUNIT_PHAR__, true);
if (defined('__PHPUNIT_PHAR__')) {
$phar = var_export(__PHPUNIT_PHAR__, true);
} else {
$phar = '\'\'';
}
@@ -712,11 +768,11 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
$codeCoverageFilter = null;
}
$data = \var_export(\serialize($this->data), true);
$dataName = \var_export($this->dataName, true);
$dependencyInput = \var_export(\serialize($this->dependencyInput), true);
$includePath = \var_export(\get_include_path(), true);
$codeCoverageFilter = \var_export(\serialize($codeCoverageFilter), true);
$data = var_export(serialize($this->data), true);
$dataName = var_export($this->dataName, true);
$dependencyInput = var_export(serialize($this->dependencyInput), true);
$includePath = var_export(get_include_path(), true);
$codeCoverageFilter = var_export(serialize($codeCoverageFilter), true);
// must do these fixes because TestCaseMethod.tpl has unserialize('{data}') in it, and we can't break BC
// the lines above used to use addcslashes() rather than var_export(), which breaks null byte escape sequences
$data = "'." . $data . ".'";
@@ -779,7 +835,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
*/
public function getMockBuilder($className): MockBuilder
{
if (!\is_string($className)) {
if (!is_string($className)) {
$this->addWarning('Passing an array of interface names to getMockBuilder() for creating a test double that implements multiple interfaces is deprecated and will no longer be supported in PHPUnit 9.');
}
@@ -811,7 +867,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
*/
public function doubledTypes(): array
{
return \array_unique($this->doubledTypes);
return array_unique($this->doubledTypes);
}
/**
@@ -919,7 +975,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
return $this->output;
}
return (string) \ob_get_contents();
return (string) ob_get_contents();
}
/**
@@ -951,7 +1007,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
*/
public function hasExpectationOnOutput(): bool
{
return \is_string($this->outputExpectedString) || \is_string($this->outputExpectedRegex) || $this->outputRetrievedForAssertion;
return is_string($this->outputExpectedString) || is_string($this->outputExpectedRegex) || $this->outputRetrievedForAssertion;
}
/**
@@ -997,7 +1053,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
}
/**
* @throws \Throwable
* @throws Throwable
*
* @internal This method is not covered by the backward compatibility promise for PHPUnit
*/
@@ -1007,8 +1063,8 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
$this->snapshotGlobalState();
$this->startOutputBuffering();
\clearstatcache();
$currentWorkingDirectory = \getcwd();
clearstatcache();
$currentWorkingDirectory = getcwd();
$hookMethods = TestUtil::getHookMethods(static::class);
@@ -1038,9 +1094,9 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
if (!empty($this->warnings)) {
throw new Warning(
\implode(
implode(
"\n",
\array_unique($this->warnings)
array_unique($this->warnings)
)
);
}
@@ -1061,7 +1117,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
} catch (PredictionException $e) {
$this->status = BaseTestRunner::STATUS_FAILURE;
$this->statusMessage = $e->getMessage();
} catch (\Throwable $_e) {
} catch (Throwable $_e) {
$e = $_e;
$this->status = BaseTestRunner::STATUS_ERROR;
$this->statusMessage = $_e->getMessage();
@@ -1084,7 +1140,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
}
}
}
} catch (\Throwable $_e) {
} catch (Throwable $_e) {
$e = $e ?? $_e;
}
@@ -1099,17 +1155,17 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
$this->statusMessage = $_e->getMessage();
}
\clearstatcache();
clearstatcache();
if ($currentWorkingDirectory !== \getcwd()) {
\chdir($currentWorkingDirectory);
if ($currentWorkingDirectory !== getcwd()) {
chdir($currentWorkingDirectory);
}
$this->restoreGlobalState();
$this->unregisterCustomComparators();
$this->cleanupIniSettings();
$this->cleanupLocaleSettings();
\libxml_clear_errors();
libxml_clear_errors();
// Perform assertion on output.
if (!isset($e)) {
@@ -1119,7 +1175,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
} elseif ($this->outputExpectedString !== null) {
$this->assertEquals($this->outputExpectedString, $this->output);
}
} catch (\Throwable $_e) {
} catch (Throwable $_e) {
$e = $_e;
}
}
@@ -1165,7 +1221,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
*/
public function hasDependencies(): bool
{
return \count($this->dependencies) > 0;
return count($this->dependencies) > 0;
}
/**
@@ -1335,7 +1391,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
*/
public function dataDescription(): string
{
return \is_string($this->dataName) ? $this->dataName : '';
return is_string($this->dataName) ? $this->dataName : '';
}
/**
@@ -1356,16 +1412,16 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
$buffer = '';
if (!empty($this->data)) {
if (\is_int($this->dataName)) {
$buffer .= \sprintf(' with data set #%d', $this->dataName);
if (is_int($this->dataName)) {
$buffer .= sprintf(' with data set #%d', $this->dataName);
} else {
$buffer .= \sprintf(' with data set "%s"', $this->dataName);
$buffer .= sprintf(' with data set "%s"', $this->dataName);
}
$exporter = new Exporter;
if ($includeData) {
$buffer .= \sprintf(' (%s)', $exporter->shortenedRecursiveExport($this->data));
$exporter = new Exporter;
$buffer .= sprintf(' (%s)', $exporter->shortenedRecursiveExport($this->data));
}
}
@@ -1393,27 +1449,27 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
/**
* Override to run the test and assert its state.
*
* @throws \SebastianBergmann\ObjectEnumerator\InvalidArgumentException
* @throws AssertionFailedError
* @throws Exception
* @throws ExpectationFailedException
* @throws \SebastianBergmann\ObjectEnumerator\InvalidArgumentException
* @throws \Throwable
* @throws Throwable
*/
protected function runTest()
{
if (\trim($this->name) === '') {
if (trim($this->name) === '') {
throw new Exception(
'PHPUnit\Framework\TestCase::$name must be a non-blank string.'
);
}
$testArguments = \array_merge($this->data, $this->dependencyInput);
$testArguments = array_merge($this->data, $this->dependencyInput);
$this->registerMockObjectsFromTestArguments($testArguments);
try {
$testResult = $this->{$this->name}(...\array_values($testArguments));
} catch (\Throwable $exception) {
$testResult = $this->{$this->name}(...array_values($testArguments));
} catch (Throwable $exception) {
if (!$this->checkExceptionExpectations($exception)) {
throw $exception;
}
@@ -1472,7 +1528,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
$this->numAssertions++;
throw new AssertionFailedError(
\sprintf(
sprintf(
'Failed asserting that exception with message "%s" is thrown',
$this->expectedExceptionMessage
)
@@ -1481,7 +1537,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
$this->numAssertions++;
throw new AssertionFailedError(
\sprintf(
sprintf(
'Failed asserting that exception with message matching "%s" is thrown',
$this->expectedExceptionMessageRegExp
)
@@ -1490,7 +1546,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
$this->numAssertions++;
throw new AssertionFailedError(
\sprintf(
sprintf(
'Failed asserting that exception with code "%s" is thrown',
$this->expectedExceptionCode
)
@@ -1509,13 +1565,13 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
*/
protected function iniSet(string $varName, string $newValue): void
{
$currentValue = \ini_set($varName, $newValue);
$currentValue = ini_set($varName, $newValue);
if ($currentValue !== false) {
$this->iniSettings[$varName] = $currentValue;
} else {
throw new Exception(
\sprintf(
sprintf(
'INI setting "%s" could not be set to "%s".',
$varName,
$newValue
@@ -1532,27 +1588,27 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
*/
protected function setLocale(...$args): void
{
if (\count($args) < 2) {
if (count($args) < 2) {
throw new Exception;
}
[$category, $locale] = $args;
if (\defined('LC_MESSAGES')) {
$categories[] = \LC_MESSAGES;
if (defined('LC_MESSAGES')) {
$categories[] = LC_MESSAGES;
}
if (!\in_array($category, self::LOCALE_CATEGORIES, true)) {
if (!in_array($category, self::LOCALE_CATEGORIES, true)) {
throw new Exception;
}
if (!\is_array($locale) && !\is_string($locale)) {
if (!is_array($locale) && !is_string($locale)) {
throw new Exception;
}
$this->locale[$category] = \setlocale($category, 0);
$this->locale[$category] = setlocale($category, 0);
$result = \setlocale(...$args);
$result = setlocale(...$args);
if ($result === false) {
throw new Exception(
@@ -1586,7 +1642,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
*/
protected function createMock($originalClassName): MockObject
{
if (!\is_string($originalClassName)) {
if (!is_string($originalClassName)) {
$this->addWarning('Passing an array of interface names to createMock() for creating a test double that implements multiple interfaces is deprecated and will no longer be supported in PHPUnit 9.');
}
@@ -1630,16 +1686,16 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
*/
protected function createPartialMock($originalClassName, array $methods): MockObject
{
if (!\is_string($originalClassName)) {
if (!is_string($originalClassName)) {
$this->addWarning('Passing an array of interface names to createPartialMock() for creating a test double that implements multiple interfaces is deprecated and will no longer be supported in PHPUnit 9.');
}
$class_names = \is_array($originalClassName) ? $originalClassName : [$originalClassName];
$class_names = is_array($originalClassName) ? $originalClassName : [$originalClassName];
foreach ($class_names as $class_name) {
$reflection = new \ReflectionClass($class_name);
$reflection = new ReflectionClass($class_name);
$mockedMethodsThatDontExist = \array_filter(
$mockedMethodsThatDontExist = array_filter(
$methods,
static function (string $method) use ($reflection) {
return !$reflection->hasMethod($method);
@@ -1648,9 +1704,9 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
if ($mockedMethodsThatDontExist) {
$this->addWarning(
\sprintf(
sprintf(
'createPartialMock called with method(s) %s that do not exist in %s. This will not be allowed in future versions of PHPUnit.',
\implode(', ', $mockedMethodsThatDontExist),
implode(', ', $mockedMethodsThatDontExist),
$class_name
)
);
@@ -1711,7 +1767,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
$cloneArguments
);
return \get_class($mock);
return get_class($mock);
}
/**
@@ -1769,11 +1825,11 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
$this->recordDoubledType('SoapClient');
if ($originalClassName === '') {
$fileName = \pathinfo(\basename(\parse_url($wsdlFile, \PHP_URL_PATH)), \PATHINFO_FILENAME);
$originalClassName = \preg_replace('/\W/', '', $fileName);
$fileName = pathinfo(basename(parse_url($wsdlFile, PHP_URL_PATH)), PATHINFO_FILENAME);
$originalClassName = preg_replace('/\W/', '', $fileName);
}
if (!\class_exists($originalClassName)) {
if (!class_exists($originalClassName)) {
eval(
$this->getMockObjectGenerator()->generateClassFromWsdl(
$wsdlFile,
@@ -1867,7 +1923,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
*/
protected function prophesize($classOrInterface = null): ObjectProphecy
{
if (\is_string($classOrInterface)) {
if (is_string($classOrInterface)) {
$this->recordDoubledType($classOrInterface);
}
@@ -1905,9 +1961,9 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
/**
* This method is called when a test method did not execute successfully.
*
* @throws \Throwable
* @throws Throwable
*/
protected function onNotSuccessfulTest(\Throwable $t): void
protected function onNotSuccessfulTest(Throwable $t): void
{
throw $t;
}
@@ -1944,13 +2000,13 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
}
/**
* @throws Warning
* @throws SkippedTestError
* @throws SyntheticSkippedError
* @throws Warning
*/
private function checkRequirements(): void
{
if (!$this->name || !\method_exists($this, $this->name)) {
if (!$this->name || !method_exists($this, $this->name)) {
return;
}
@@ -1960,12 +2016,12 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
);
if (!empty($missingRequirements)) {
$this->markTestSkipped(\implode(\PHP_EOL, $missingRequirements));
$this->markTestSkipped(implode(PHP_EOL, $missingRequirements));
}
}
/**
* @throws \Throwable
* @throws Throwable
*/
private function verifyMockObjects(): void
{
@@ -1986,9 +2042,9 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
foreach ($this->prophet->getProphecies() as $objectProphecy) {
foreach ($objectProphecy->getMethodProphecies() as $methodProphecies) {
foreach ($methodProphecies as $methodProphecy) {
\assert($methodProphecy instanceof MethodProphecy);
assert($methodProphecy instanceof MethodProphecy);
$this->numAssertions += \count($methodProphecy->getCheckedPredictions());
$this->numAssertions += count($methodProphecy->getCheckedPredictions());
}
}
}
@@ -2000,17 +2056,17 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
{
if (!empty($this->dependencies) && !$this->inIsolation) {
$passed = $this->result->passed();
$passedKeys = \array_keys($passed);
$passedKeys = array_keys($passed);
foreach ($passedKeys as $key => $value) {
$pos = \strpos($value, ' with data set');
$pos = strpos($value, ' with data set');
if ($pos !== false) {
$passedKeys[$key] = \substr($value, 0, $pos);
$passedKeys[$key] = substr($value, 0, $pos);
}
}
$passedKeys = \array_flip(\array_unique($passedKeys));
$passedKeys = array_flip(array_unique($passedKeys));
foreach ($this->dependencies as $dependency) {
$deepClone = false;
@@ -2022,23 +2078,23 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
return false;
}
if (\strpos($dependency, 'clone ') === 0) {
if (strpos($dependency, 'clone ') === 0) {
$deepClone = true;
$dependency = \substr($dependency, \strlen('clone '));
} elseif (\strpos($dependency, '!clone ') === 0) {
$dependency = substr($dependency, strlen('clone '));
} elseif (strpos($dependency, '!clone ') === 0) {
$deepClone = false;
$dependency = \substr($dependency, \strlen('!clone '));
$dependency = substr($dependency, strlen('!clone '));
}
if (\strpos($dependency, 'shallowClone ') === 0) {
if (strpos($dependency, 'shallowClone ') === 0) {
$shallowClone = true;
$dependency = \substr($dependency, \strlen('shallowClone '));
} elseif (\strpos($dependency, '!shallowClone ') === 0) {
$dependency = substr($dependency, strlen('shallowClone '));
} elseif (strpos($dependency, '!shallowClone ') === 0) {
$shallowClone = false;
$dependency = \substr($dependency, \strlen('!shallowClone '));
$dependency = substr($dependency, strlen('!shallowClone '));
}
if (\strpos($dependency, '::') === false) {
if (strpos($dependency, '::') === false) {
$dependency = static::class . '::' . $dependency;
}
@@ -2095,7 +2151,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
$this->result->addError(
$this,
new SkippedTestError(
\sprintf('This method has an invalid @depends annotation.')
'This method has an invalid @depends annotation.'
),
0
);
@@ -2112,7 +2168,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
$this->result->addError(
$this,
new SkippedTestError(
\sprintf(
sprintf(
'This test depends on "%s" to pass.',
$dependency
)
@@ -2132,7 +2188,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
$this->result->addWarning(
$this,
new Warning(
\sprintf(
sprintf(
'This test depends on "%s" which does not exist.',
$dependency
)
@@ -2157,10 +2213,10 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
private function startOutputBuffering(): void
{
\ob_start();
ob_start();
$this->outputBufferingActive = true;
$this->outputBufferingLevel = \ob_get_level();
$this->outputBufferingLevel = ob_get_level();
}
/**
@@ -2168,9 +2224,9 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
*/
private function stopOutputBuffering(): void
{
if (\ob_get_level() !== $this->outputBufferingLevel) {
while (\ob_get_level() >= $this->outputBufferingLevel) {
\ob_end_clean();
if (ob_get_level() !== $this->outputBufferingLevel) {
while (ob_get_level() >= $this->outputBufferingLevel) {
ob_end_clean();
}
throw new RiskyTestError(
@@ -2178,16 +2234,16 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
);
}
$this->output = \ob_get_contents();
$this->output = ob_get_contents();
if ($this->outputCallback !== false) {
$this->output = (string) \call_user_func($this->outputCallback, $this->output);
$this->output = (string) call_user_func($this->outputCallback, $this->output);
}
\ob_end_clean();
ob_end_clean();
$this->outputBufferingActive = false;
$this->outputBufferingLevel = \ob_get_level();
$this->outputBufferingLevel = ob_get_level();
}
private function snapshotGlobalState(): void
@@ -2201,8 +2257,8 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
}
/**
* @throws RiskyTestError
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws RiskyTestError
*/
private function restoreGlobalState(): void
{
@@ -2246,7 +2302,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
$blacklist->addGlobalVariable($globalVariable);
}
if (!\defined('PHPUNIT_TESTSUITE')) {
if (!defined('PHPUNIT_TESTSUITE')) {
$blacklist->addClassNamePrefix('PHPUnit');
$blacklist->addClassNamePrefix('SebastianBergmann\CodeCoverage');
$blacklist->addClassNamePrefix('SebastianBergmann\FileIterator');
@@ -2281,8 +2337,8 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
}
/**
* @throws RiskyTestError
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws RiskyTestError
*/
private function compareGlobalStateSnapshots(Snapshot $before, Snapshot $after): void
{
@@ -2353,11 +2409,11 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
}
}
if (!\is_array($this->testResult) && !\is_object($this->testResult)) {
if (!is_array($this->testResult) && !is_object($this->testResult)) {
return true;
}
return !\in_array($mock, $enumerator->enumerate($this->testResult), true);
return !in_array($mock, $enumerator->enumerate($this->testResult), true);
}
/**
@@ -2381,7 +2437,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
}
$this->registerMockObject($testArgument);
} elseif (\is_array($testArgument) && !\in_array($testArgument, $visited, true)) {
} elseif (is_array($testArgument) && !in_array($testArgument, $visited, true)) {
$visited[] = $testArgument;
$this->registerMockObjectsFromTestArguments(
@@ -2416,7 +2472,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
private function cleanupIniSettings(): void
{
foreach ($this->iniSettings as $varName => $oldValue) {
\ini_set($varName, $oldValue);
ini_set($varName, $oldValue);
}
$this->iniSettings = [];
@@ -2425,7 +2481,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
private function cleanupLocaleSettings(): void
{
foreach ($this->locale as $category => $locale) {
\setlocale($category, $locale);
setlocale($category, $locale);
}
$this->locale = [];
@@ -2434,7 +2490,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
/**
* @throws Exception
*/
private function checkExceptionExpectations(\Throwable $throwable): bool
private function checkExceptionExpectations(Throwable $throwable): bool
{
$result = false;
@@ -2446,11 +2502,11 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
$result = false;
}
if (\is_string($this->expectedException)) {
if (is_string($this->expectedException)) {
try {
$reflector = new \ReflectionClass($this->expectedException);
$reflector = new ReflectionClass($this->expectedException);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
@@ -2480,13 +2536,13 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
*/
private function recordDoubledType($originalClassName): void
{
if (\is_string($originalClassName)) {
if (is_string($originalClassName)) {
$this->doubledTypes[] = $originalClassName;
}
if (\is_array($originalClassName)) {
if (is_array($originalClassName)) {
foreach ($originalClassName as $_originalClassName) {
if (\is_string($_originalClassName)) {
if (is_string($_originalClassName)) {
$this->doubledTypes[] = $_originalClassName;
}
}
@@ -2495,15 +2551,15 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
private function isCallableTestMethod(string $dependency): bool
{
[$className, $methodName] = \explode('::', $dependency);
[$className, $methodName] = explode('::', $dependency);
if (!\class_exists($className)) {
if (!class_exists($className)) {
return false;
}
try {
$class = new \ReflectionClass($className);
} catch (\ReflectionException $e) {
$class = new ReflectionClass($className);
} catch (ReflectionException $e) {
return false;
}
@@ -2517,7 +2573,7 @@ abstract class TestCase extends Assert implements SelfDescribing, Test
try {
$method = $class->getMethod($methodName);
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
return false;
}

View File

@@ -9,6 +9,9 @@
*/
namespace PHPUnit\Framework;
use function get_class;
use function sprintf;
use function trim;
use PHPUnit\Framework\Error\Error;
use Throwable;
@@ -49,7 +52,7 @@ final class TestFailure
}
if (!empty($buffer)) {
$buffer = \trim($buffer) . "\n";
$buffer = trim($buffer) . "\n";
}
return $buffer;
@@ -63,7 +66,7 @@ final class TestFailure
return $e->getClassName() . ': ' . $e->getMessage() . "\n";
}
return \get_class($e) . ': ' . $e->getMessage() . "\n";
return get_class($e) . ': ' . $e->getMessage() . "\n";
}
/**
@@ -76,7 +79,7 @@ final class TestFailure
if ($failedTest instanceof SelfDescribing) {
$this->testName = $failedTest->toString();
} else {
$this->testName = \get_class($failedTest);
$this->testName = get_class($failedTest);
}
if (!$failedTest instanceof TestCase || !$failedTest->isInIsolation()) {
@@ -91,7 +94,7 @@ final class TestFailure
*/
public function toString(): string
{
return \sprintf(
return sprintf(
'%s: %s',
$this->testName,
$this->thrownException->getMessage()

View File

@@ -9,6 +9,8 @@
*/
namespace PHPUnit\Framework;
use Throwable;
/**
* @deprecated Use the `TestHook` interfaces instead
*/
@@ -19,7 +21,7 @@ interface TestListener
*
* @deprecated Use `AfterTestErrorHook::executeAfterTestError` instead
*/
public function addError(Test $test, \Throwable $t, float $time): void;
public function addError(Test $test, Throwable $t, float $time): void;
/**
* A warning occurred.
@@ -40,21 +42,21 @@ interface TestListener
*
* @deprecated Use `AfterIncompleteTestHook::executeAfterIncompleteTest` instead
*/
public function addIncompleteTest(Test $test, \Throwable $t, float $time): void;
public function addIncompleteTest(Test $test, Throwable $t, float $time): void;
/**
* Risky test.
*
* @deprecated Use `AfterRiskyTestHook::executeAfterRiskyTest` instead
*/
public function addRiskyTest(Test $test, \Throwable $t, float $time): void;
public function addRiskyTest(Test $test, Throwable $t, float $time): void;
/**
* Skipped test.
*
* @deprecated Use `AfterSkippedTestHook::executeAfterSkippedTest` instead
*/
public function addSkippedTest(Test $test, \Throwable $t, float $time): void;
public function addSkippedTest(Test $test, Throwable $t, float $time): void;
/**
* A test suite started.

View File

@@ -9,12 +9,14 @@
*/
namespace PHPUnit\Framework;
use Throwable;
/**
* @deprecated The `TestListener` interface is deprecated
*/
trait TestListenerDefaultImplementation
{
public function addError(Test $test, \Throwable $t, float $time): void
public function addError(Test $test, Throwable $t, float $time): void
{
}
@@ -26,15 +28,15 @@ trait TestListenerDefaultImplementation
{
}
public function addIncompleteTest(Test $test, \Throwable $t, float $time): void
public function addIncompleteTest(Test $test, Throwable $t, float $time): void
{
}
public function addRiskyTest(Test $test, \Throwable $t, float $time): void
public function addRiskyTest(Test $test, Throwable $t, float $time): void
{
}
public function addSkippedTest(Test $test, \Throwable $t, float $time): void
public function addSkippedTest(Test $test, Throwable $t, float $time): void
{
}

View File

@@ -9,6 +9,16 @@
*/
namespace PHPUnit\Framework;
use const PHP_EOL;
use function class_exists;
use function count;
use function extension_loaded;
use function function_exists;
use function get_class;
use function sprintf;
use function xdebug_get_monitored_functions;
use function xdebug_start_function_monitor;
use function xdebug_stop_function_monitor;
use AssertionError;
use Countable;
use Error;
@@ -17,6 +27,8 @@ use PHPUnit\Util\Blacklist;
use PHPUnit\Util\ErrorHandler;
use PHPUnit\Util\Printer;
use PHPUnit\Util\Test as TestUtil;
use ReflectionClass;
use ReflectionException;
use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\CoveredCodeNotExecutedException as OriginalCoveredCodeNotExecutedException;
use SebastianBergmann\CodeCoverage\Exception as OriginalCodeCoverageException;
@@ -405,7 +417,7 @@ final class TestResult implements Countable
public function startTest(Test $test): void
{
$this->lastTestFailed = false;
$this->runTests += \count($test);
$this->runTests += count($test);
foreach ($this->listeners as $listener) {
$listener->startTest($test);
@@ -424,7 +436,7 @@ final class TestResult implements Countable
}
if (!$this->lastTestFailed && $test instanceof TestCase) {
$class = \get_class($test);
$class = get_class($test);
$key = $class . '::' . $test->getName();
$this->passed[$key] = [
@@ -452,7 +464,7 @@ final class TestResult implements Countable
*/
public function riskyCount(): int
{
return \count($this->risky);
return count($this->risky);
}
/**
@@ -468,11 +480,11 @@ final class TestResult implements Countable
*/
public function notImplementedCount(): int
{
return \count($this->notImplemented);
return count($this->notImplemented);
}
/**
* Returns an array of TestFailure objects for the risky tests
* Returns an array of TestFailure objects for the risky tests.
*
* @return TestFailure[]
*/
@@ -482,7 +494,7 @@ final class TestResult implements Countable
}
/**
* Returns an array of TestFailure objects for the incomplete tests
* Returns an array of TestFailure objects for the incomplete tests.
*
* @return TestFailure[]
*/
@@ -504,11 +516,11 @@ final class TestResult implements Countable
*/
public function skippedCount(): int
{
return \count($this->skipped);
return count($this->skipped);
}
/**
* Returns an array of TestFailure objects for the skipped tests
* Returns an array of TestFailure objects for the skipped tests.
*
* @return TestFailure[]
*/
@@ -522,11 +534,11 @@ final class TestResult implements Countable
*/
public function errorCount(): int
{
return \count($this->errors);
return count($this->errors);
}
/**
* Returns an array of TestFailure objects for the errors
* Returns an array of TestFailure objects for the errors.
*
* @return TestFailure[]
*/
@@ -540,11 +552,11 @@ final class TestResult implements Countable
*/
public function failureCount(): int
{
return \count($this->failures);
return count($this->failures);
}
/**
* Returns an array of TestFailure objects for the failures
* Returns an array of TestFailure objects for the failures.
*
* @return TestFailure[]
*/
@@ -558,11 +570,11 @@ final class TestResult implements Countable
*/
public function warningCount(): int
{
return \count($this->warnings);
return count($this->warnings);
}
/**
* Returns an array of TestFailure objects for the warnings
* Returns an array of TestFailure objects for the warnings.
*
* @return TestFailure[]
*/
@@ -598,13 +610,13 @@ final class TestResult implements Countable
/**
* Runs a TestCase.
*
* @throws \SebastianBergmann\CodeCoverage\InvalidArgumentException
* @throws \SebastianBergmann\CodeCoverage\RuntimeException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws CodeCoverageException
* @throws OriginalCoveredCodeNotExecutedException
* @throws OriginalMissingCoversAnnotationException
* @throws UnintentionallyCoveredCodeException
* @throws \SebastianBergmann\CodeCoverage\InvalidArgumentException
* @throws \SebastianBergmann\CodeCoverage\RuntimeException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
public function run(Test $test): void
{
@@ -649,11 +661,11 @@ final class TestResult implements Countable
$monitorFunctions = $this->beStrictAboutResourceUsageDuringSmallTests &&
!$test instanceof WarningTestCase &&
$test->getSize() == \PHPUnit\Util\Test::SMALL &&
\function_exists('xdebug_start_function_monitor');
function_exists('xdebug_start_function_monitor');
if ($monitorFunctions) {
/* @noinspection ForgottenDebugOutputInspection */
\xdebug_start_function_monitor(ResourceOperations::getFunctions());
xdebug_start_function_monitor(ResourceOperations::getFunctions());
}
Timer::start();
@@ -662,7 +674,7 @@ final class TestResult implements Countable
if (!$test instanceof WarningTestCase &&
$this->enforceTimeLimit &&
($this->defaultTimeLimit || $test->getSize() != \PHPUnit\Util\Test::UNKNOWN) &&
\extension_loaded('pcntl') && \class_exists(Invoker::class)) {
extension_loaded('pcntl') && class_exists(Invoker::class)) {
switch ($test->getSize()) {
case \PHPUnit\Util\Test::SMALL:
$_timeout = $this->timeoutForSmallTests;
@@ -723,7 +735,7 @@ final class TestResult implements Countable
$frame = $e->getTrace()[0];
$e = new AssertionFailedError(
\sprintf(
sprintf(
'%s in %s:%s',
$e->getMessage(),
$frame['file'],
@@ -746,17 +758,17 @@ final class TestResult implements Countable
$blacklist = new Blacklist;
/** @noinspection ForgottenDebugOutputInspection */
$functions = \xdebug_get_monitored_functions();
$functions = xdebug_get_monitored_functions();
/* @noinspection ForgottenDebugOutputInspection */
\xdebug_stop_function_monitor();
xdebug_stop_function_monitor();
foreach ($functions as $function) {
if (!$blacklist->isBlacklisted($function['filename'])) {
$this->addFailure(
$test,
new RiskyTestError(
\sprintf(
sprintf(
'%s() used in %s:%s',
$function['function'],
$function['filename'],
@@ -782,12 +794,12 @@ final class TestResult implements Countable
if ($append && $test instanceof TestCase) {
try {
$linesToBeCovered = \PHPUnit\Util\Test::getLinesToBeCovered(
\get_class($test),
get_class($test),
$test->getName(false)
);
$linesToBeUsed = \PHPUnit\Util\Test::getLinesToBeUsed(
\get_class($test),
get_class($test),
$test->getName(false)
);
} catch (InvalidCoversTargetException $cce) {
@@ -812,7 +824,7 @@ final class TestResult implements Countable
$test,
new UnintentionallyCoveredCodeError(
'This test executed code that is not listed as code to be covered or used:' .
\PHP_EOL . $cce->getMessage()
PHP_EOL . $cce->getMessage()
),
$time
);
@@ -821,7 +833,7 @@ final class TestResult implements Countable
$test,
new CoveredCodeNotExecutedException(
'This test did not execute all the code that is listed as code to be covered:' .
\PHP_EOL . $cce->getMessage()
PHP_EOL . $cce->getMessage()
),
$time
);
@@ -858,9 +870,9 @@ final class TestResult implements Countable
!$test->doesNotPerformAssertions() &&
$test->getNumAssertions() == 0) {
try {
$reflected = new \ReflectionClass($test);
$reflected = new ReflectionClass($test);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
@@ -875,7 +887,7 @@ final class TestResult implements Countable
try {
$reflected = $reflected->getMethod($name);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
@@ -888,7 +900,7 @@ final class TestResult implements Countable
$this->addFailure(
$test,
new RiskyTestError(
\sprintf(
sprintf(
"This test did not perform any assertions\n\n%s:%d",
$reflected->getFileName(),
$reflected->getStartLine()
@@ -902,7 +914,7 @@ final class TestResult implements Countable
$this->addFailure(
$test,
new RiskyTestError(
\sprintf(
sprintf(
'This test is annotated with "@doesNotPerformAssertions" but performed %d assertions',
$test->getNumAssertions()
)
@@ -913,7 +925,7 @@ final class TestResult implements Countable
$this->addFailure(
$test,
new OutputError(
\sprintf(
sprintf(
'This test printed output: %s',
$test->getActualOutput()
)
@@ -1140,7 +1152,7 @@ final class TestResult implements Countable
}
/**
* Enables or disables the stopping for defects: error, failure, warning
* Enables or disables the stopping for defects: error, failure, warning.
*/
public function stopOnDefect(bool $flag): void
{
@@ -1174,7 +1186,7 @@ final class TestResult implements Countable
}
/**
* Sets the default timeout for tests
* Sets the default timeout for tests.
*/
public function setDefaultTimeLimit(int $timeout): void
{

View File

@@ -9,16 +9,42 @@
*/
namespace PHPUnit\Framework;
use const PHP_EOL;
use function array_diff;
use function array_keys;
use function array_merge;
use function basename;
use function call_user_func;
use function class_exists;
use function count;
use function dirname;
use function file_exists;
use function get_declared_classes;
use function implode;
use function is_bool;
use function is_object;
use function is_string;
use function method_exists;
use function preg_match;
use function preg_quote;
use function sprintf;
use function substr;
use Iterator;
use IteratorAggregate;
use PHPUnit\Runner\BaseTestRunner;
use PHPUnit\Runner\Filter\Factory;
use PHPUnit\Runner\PhptTestCase;
use PHPUnit\Util\FileLoader;
use PHPUnit\Util\Test as TestUtil;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use Throwable;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
class TestSuite implements \IteratorAggregate, SelfDescribing, Test
class TestSuite implements IteratorAggregate, SelfDescribing, Test
{
/**
* Enable or disable the backup and restoration of the $GLOBALS array.
@@ -100,7 +126,7 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
private $declaredClasses;
/**
* Constructs a new TestSuite:
* Constructs a new TestSuite:.
*
* - PHPUnit\Framework\TestSuite() constructs an empty TestSuite.
*
@@ -116,31 +142,31 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
* name of an existing class) or constructs an empty TestSuite
* with the given name.
*
* @param \ReflectionClass|string $theClass
* @param ReflectionClass|string $theClass
*
* @throws Exception
*/
public function __construct($theClass = '', string $name = '')
{
if (!\is_string($theClass) && !$theClass instanceof \ReflectionClass) {
if (!is_string($theClass) && !$theClass instanceof ReflectionClass) {
throw InvalidArgumentException::create(
1,
'ReflectionClass object or string'
);
}
$this->declaredClasses = \get_declared_classes();
$this->declaredClasses = get_declared_classes();
if (!$theClass instanceof \ReflectionClass) {
if (\class_exists($theClass, true)) {
if (!$theClass instanceof ReflectionClass) {
if (class_exists($theClass, true)) {
if ($name === '') {
$name = $theClass;
}
try {
$theClass = new \ReflectionClass($theClass);
$theClass = new ReflectionClass($theClass);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
@@ -173,7 +199,7 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
!$constructor->isPublic()) {
$this->addTest(
new WarningTestCase(
\sprintf(
sprintf(
'Class "%s" has no public constructor.',
$theClass->getName()
)
@@ -202,7 +228,7 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
if (empty($this->tests)) {
$this->addTest(
new WarningTestCase(
\sprintf(
sprintf(
'No tests found in class "%s".',
$theClass->getName()
)
@@ -229,9 +255,9 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
public function addTest(Test $test, $groups = []): void
{
try {
$class = new \ReflectionClass($test);
$class = new ReflectionClass($test);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
@@ -275,18 +301,18 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
*/
public function addTestSuite($testClass): void
{
if (!(\is_object($testClass) || (\is_string($testClass) && \class_exists($testClass)))) {
if (!(is_object($testClass) || (is_string($testClass) && class_exists($testClass)))) {
throw InvalidArgumentException::create(
1,
'class name or object'
);
}
if (!\is_object($testClass)) {
if (!is_object($testClass)) {
try {
$testClass = new \ReflectionClass($testClass);
$testClass = new ReflectionClass($testClass);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
@@ -298,7 +324,7 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
if ($testClass instanceof self) {
$this->addTest($testClass);
} elseif ($testClass instanceof \ReflectionClass) {
} elseif ($testClass instanceof ReflectionClass) {
$suiteMethod = false;
if (!$testClass->isAbstract() && $testClass->hasMethod(BaseTestRunner::SUITE_METHODNAME)) {
@@ -307,7 +333,7 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
BaseTestRunner::SUITE_METHODNAME
);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
@@ -345,7 +371,7 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
*/
public function addTestFile(string $filename): void
{
if (\file_exists($filename) && \substr($filename, -5) === '.phpt') {
if (file_exists($filename) && substr($filename, -5) === '.phpt') {
$this->addTest(
new PhptTestCase($filename)
);
@@ -356,7 +382,7 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
// The given file may contain further stub classes in addition to the
// test class itself. Figure out the actual test class.
$filename = FileLoader::checkAndLoad($filename);
$newClasses = \array_diff(\get_declared_classes(), $this->declaredClasses);
$newClasses = array_diff(get_declared_classes(), $this->declaredClasses);
// The diff is empty in case a parent class (with test methods) is added
// AFTER a child class that inherited from it. To account for that case,
@@ -366,23 +392,23 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
// On the assumption that test classes are defined first in files,
// process discovered classes in approximate LIFO order, so as to
// avoid unnecessary reflection.
$this->foundClasses = \array_merge($newClasses, $this->foundClasses);
$this->declaredClasses = \get_declared_classes();
$this->foundClasses = array_merge($newClasses, $this->foundClasses);
$this->declaredClasses = get_declared_classes();
}
// The test class's name must match the filename, either in full, or as
// a PEAR/PSR-0 prefixed short name ('NameSpace_ShortName'), or as a
// PSR-1 local short name ('NameSpace\ShortName'). The comparison must be
// anchored to prevent false-positive matches (e.g., 'OtherShortName').
$shortName = \basename($filename, '.php');
$shortNameRegEx = '/(?:^|_|\\\\)' . \preg_quote($shortName, '/') . '$/';
$shortName = basename($filename, '.php');
$shortNameRegEx = '/(?:^|_|\\\\)' . preg_quote($shortName, '/') . '$/';
foreach ($this->foundClasses as $i => $className) {
if (\preg_match($shortNameRegEx, $className)) {
if (preg_match($shortNameRegEx, $className)) {
try {
$class = new \ReflectionClass($className);
$class = new ReflectionClass($className);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
@@ -402,9 +428,9 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
foreach ($newClasses as $className) {
try {
$class = new \ReflectionClass($className);
$class = new ReflectionClass($className);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
@@ -413,7 +439,7 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
}
// @codeCoverageIgnoreEnd
if (\dirname($class->getFileName()) === __DIR__) {
if (dirname($class->getFileName()) === __DIR__) {
continue;
}
@@ -424,7 +450,7 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
BaseTestRunner::SUITE_METHODNAME
);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
@@ -469,7 +495,7 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
$numTests = 0;
foreach ($this as $test) {
$numTests += \count($test);
$numTests += count($test);
}
$this->cachedNumTests = $numTests;
@@ -490,7 +516,7 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
*/
public function getGroups(): array
{
return \array_keys($this->groups);
return array_keys($this->groups);
}
public function getGroupDetails(): array
@@ -499,7 +525,7 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
}
/**
* Set tests groups of the test case
* Set tests groups of the test case.
*/
public function setGroupDetails(array $groups): void
{
@@ -524,7 +550,7 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
$result = $this->createResult();
}
if (\count($this) === 0) {
if (count($this) === 0) {
return $result;
}
@@ -537,13 +563,13 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
try {
foreach ($hookMethods['beforeClass'] as $beforeClassMethod) {
if ($this->testCase &&
\class_exists($this->name, false) &&
\method_exists($this->name, $beforeClassMethod)) {
class_exists($this->name, false) &&
method_exists($this->name, $beforeClassMethod)) {
if ($missingRequirements = TestUtil::getMissingRequirements($this->name, $beforeClassMethod)) {
$this->markTestSuiteSkipped(\implode(\PHP_EOL, $missingRequirements));
$this->markTestSuiteSkipped(implode(PHP_EOL, $missingRequirements));
}
\call_user_func([$this->name, $beforeClassMethod]);
call_user_func([$this->name, $beforeClassMethod]);
}
}
} catch (SkippedTestSuiteError $error) {
@@ -556,7 +582,7 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
$result->endTestSuite($this);
return $result;
} catch (\Throwable $t) {
} catch (Throwable $t) {
$errorAdded = false;
foreach ($this->tests() as $test) {
@@ -604,13 +630,13 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
try {
foreach ($hookMethods['afterClass'] as $afterClassMethod) {
if ($this->testCase &&
\class_exists($this->name, false) &&
\method_exists($this->name, $afterClassMethod)) {
\call_user_func([$this->name, $afterClassMethod]);
class_exists($this->name, false) &&
method_exists($this->name, $afterClassMethod)) {
call_user_func([$this->name, $afterClassMethod]);
}
}
} catch (\Throwable $t) {
$message = "Exception in {$this->name}::{$afterClassMethod}" . \PHP_EOL . $t->getMessage();
} catch (Throwable $t) {
$message = "Exception in {$this->name}::{$afterClassMethod}" . PHP_EOL . $t->getMessage();
$error = new SyntheticError($message, 0, $t->getFile(), $t->getLine(), $t->getTrace());
$placeholderTest = clone $test;
@@ -657,7 +683,7 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
}
/**
* Set tests of the test suite
* Set tests of the test suite.
*
* @param Test[] $tests
*/
@@ -685,7 +711,7 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
*/
public function setBeStrictAboutChangesToGlobalState($beStrictAboutChangesToGlobalState): void
{
if (null === $this->beStrictAboutChangesToGlobalState && \is_bool($beStrictAboutChangesToGlobalState)) {
if (null === $this->beStrictAboutChangesToGlobalState && is_bool($beStrictAboutChangesToGlobalState)) {
$this->beStrictAboutChangesToGlobalState = $beStrictAboutChangesToGlobalState;
}
}
@@ -695,7 +721,7 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
*/
public function setBackupGlobals($backupGlobals): void
{
if (null === $this->backupGlobals && \is_bool($backupGlobals)) {
if (null === $this->backupGlobals && is_bool($backupGlobals)) {
$this->backupGlobals = $backupGlobals;
}
}
@@ -705,7 +731,7 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
*/
public function setBackupStaticAttributes($backupStaticAttributes): void
{
if (null === $this->backupStaticAttributes && \is_bool($backupStaticAttributes)) {
if (null === $this->backupStaticAttributes && is_bool($backupStaticAttributes)) {
$this->backupStaticAttributes = $backupStaticAttributes;
}
}
@@ -713,7 +739,7 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
/**
* Returns an iterator for this test suite.
*/
public function getIterator(): \Iterator
public function getIterator(): Iterator
{
$iterator = new TestSuiteIterator($this);
@@ -746,7 +772,7 @@ class TestSuite implements \IteratorAggregate, SelfDescribing, Test
/**
* @throws Exception
*/
protected function addTestMethod(\ReflectionClass $class, \ReflectionMethod $method): void
protected function addTestMethod(ReflectionClass $class, ReflectionMethod $method): void
{
if (!TestUtil::isTestMethod($method)) {
return;

View File

@@ -9,10 +9,14 @@
*/
namespace PHPUnit\Framework;
use function assert;
use function count;
use RecursiveIterator;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class TestSuiteIterator implements \RecursiveIterator
final class TestSuiteIterator implements RecursiveIterator
{
/**
* @var int
@@ -36,7 +40,7 @@ final class TestSuiteIterator implements \RecursiveIterator
public function valid(): bool
{
return $this->position < \count($this->tests);
return $this->position < count($this->tests);
}
public function key(): int
@@ -67,7 +71,7 @@ final class TestSuiteIterator implements \RecursiveIterator
$current = $this->current();
\assert($current instanceof TestSuite);
assert($current instanceof TestSuite);
return new self($current);
}

View File

@@ -9,9 +9,13 @@
*/
namespace PHPUnit\Runner;
use function is_dir;
use function is_file;
use PHPUnit\Framework\Exception;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestSuite;
use ReflectionClass;
use ReflectionException;
use SebastianBergmann\FileIterator\Facade as FileIteratorFacade;
/**
@@ -83,7 +87,7 @@ abstract class BaseTestRunner
*/
public function getTest(string $suiteClassName, string $suiteClassFile = '', $suffixes = ''): ?Test
{
if (empty($suiteClassFile) && \is_dir($suiteClassName) && !\is_file($suiteClassName . '.php')) {
if (empty($suiteClassFile) && is_dir($suiteClassName) && !is_file($suiteClassName . '.php')) {
/** @var string[] $files */
$files = (new FileIteratorFacade)->getFilesAsArray(
$suiteClassName,
@@ -119,7 +123,7 @@ abstract class BaseTestRunner
}
$test = $suiteMethod->invoke(null, $testClass->getName());
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
try {
$test = new TestSuite($testClass);
} catch (Exception $e) {
@@ -136,7 +140,7 @@ abstract class BaseTestRunner
/**
* Returns the loaded ReflectionClass for a suite name.
*/
protected function loadSuiteClass(string $suiteClassName, string $suiteClassFile = ''): \ReflectionClass
protected function loadSuiteClass(string $suiteClassName, string $suiteClassFile = ''): ReflectionClass
{
return $this->getLoader()->load($suiteClassName, $suiteClassFile);
}

View File

@@ -9,13 +9,29 @@
*/
namespace PHPUnit\Runner;
use const DIRECTORY_SEPARATOR;
use function assert;
use function defined;
use function dirname;
use function file_get_contents;
use function file_put_contents;
use function in_array;
use function is_dir;
use function is_file;
use function is_float;
use function is_int;
use function is_string;
use function serialize;
use function sprintf;
use function unserialize;
use PHPUnit\Util\ErrorHandler;
use PHPUnit\Util\Filesystem;
use Serializable;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class DefaultTestResultCache implements \Serializable, TestResultCache
final class DefaultTestResultCache implements Serializable, TestResultCache
{
/**
* @var string
@@ -23,7 +39,7 @@ final class DefaultTestResultCache implements \Serializable, TestResultCache
public const DEFAULT_RESULT_CACHE_FILENAME = '.phpunit.result.cache';
/**
* Provide extra protection against incomplete or corrupt caches
* Provide extra protection against incomplete or corrupt caches.
*
* @var int[]
*/
@@ -37,14 +53,14 @@ final class DefaultTestResultCache implements \Serializable, TestResultCache
];
/**
* Path and filename for result cache file
* Path and filename for result cache file.
*
* @var string
*/
private $cacheFilename;
/**
* The list of defective tests
* The list of defective tests.
*
* <code>
* // Mark a test skipped
@@ -56,7 +72,7 @@ final class DefaultTestResultCache implements \Serializable, TestResultCache
private $defects = [];
/**
* The list of execution duration of suites and tests (in seconds)
* The list of execution duration of suites and tests (in seconds).
*
* <code>
* // Record running time for test
@@ -69,9 +85,9 @@ final class DefaultTestResultCache implements \Serializable, TestResultCache
public function __construct(?string $filepath = null)
{
if ($filepath !== null && \is_dir($filepath)) {
if ($filepath !== null && is_dir($filepath)) {
// cache path provided, use default cache filename in that location
$filepath .= \DIRECTORY_SEPARATOR . self::DEFAULT_RESULT_CACHE_FILENAME;
$filepath .= DIRECTORY_SEPARATOR . self::DEFAULT_RESULT_CACHE_FILENAME;
}
$this->cacheFilename = $filepath ?? $_ENV['PHPUNIT_RESULT_CACHE'] ?? self::DEFAULT_RESULT_CACHE_FILENAME;
@@ -90,22 +106,22 @@ final class DefaultTestResultCache implements \Serializable, TestResultCache
*/
public function saveToFile(): void
{
if (\defined('PHPUNIT_TESTSUITE_RESULTCACHE')) {
if (defined('PHPUNIT_TESTSUITE_RESULTCACHE')) {
return;
}
if (!Filesystem::createDirectory(\dirname($this->cacheFilename))) {
if (!Filesystem::createDirectory(dirname($this->cacheFilename))) {
throw new Exception(
\sprintf(
sprintf(
'Cannot create directory "%s" for result cache file',
$this->cacheFilename
)
);
}
\file_put_contents(
file_put_contents(
$this->cacheFilename,
\serialize($this)
serialize($this)
);
}
@@ -135,11 +151,11 @@ final class DefaultTestResultCache implements \Serializable, TestResultCache
{
$this->clear();
if (!\is_file($this->cacheFilename)) {
if (!is_file($this->cacheFilename)) {
return;
}
$cacheData = @\file_get_contents($this->cacheFilename);
$cacheData = @file_get_contents($this->cacheFilename);
// @codeCoverageIgnoreStart
if ($cacheData === false) {
@@ -149,7 +165,7 @@ final class DefaultTestResultCache implements \Serializable, TestResultCache
$cache = ErrorHandler::invokeIgnoringWarnings(
static function () use ($cacheData) {
return @\unserialize($cacheData, ['allowed_classes' => [self::class]]);
return @unserialize($cacheData, ['allowed_classes' => [self::class]]);
}
);
@@ -182,7 +198,7 @@ final class DefaultTestResultCache implements \Serializable, TestResultCache
public function serialize(): string
{
return \serialize([
return serialize([
'defects' => $this->defects,
'times' => $this->times,
]);
@@ -193,22 +209,22 @@ final class DefaultTestResultCache implements \Serializable, TestResultCache
*/
public function unserialize($serialized): void
{
$data = \unserialize($serialized);
$data = unserialize($serialized);
if (isset($data['times'])) {
foreach ($data['times'] as $testName => $testTime) {
\assert(\is_string($testName));
\assert(\is_float($testTime));
assert(is_string($testName));
assert(is_float($testTime));
$this->times[$testName] = $testTime;
}
}
if (isset($data['defects'])) {
foreach ($data['defects'] as $testName => $testResult) {
\assert(\is_string($testName));
\assert(\is_int($testResult));
assert(is_string($testName));
assert(is_int($testResult));
if (\in_array($testResult, self::ALLOWED_CACHE_TEST_STATUSES, true)) {
if (in_array($testResult, self::ALLOWED_CACHE_TEST_STATUSES, true)) {
$this->defects[$testName] = $testResult;
}
}

View File

@@ -9,9 +9,11 @@
*/
namespace PHPUnit\Runner;
use RuntimeException;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class Exception extends \RuntimeException implements \PHPUnit\Exception
final class Exception extends RuntimeException implements \PHPUnit\Exception
{
}

View File

@@ -9,6 +9,8 @@
*/
namespace PHPUnit\Runner\Filter;
use function in_array;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
@@ -16,6 +18,6 @@ final class ExcludeGroupFilterIterator extends GroupFilterIterator
{
protected function doAccept(string $hash): bool
{
return !\in_array($hash, $this->groupTests, true);
return !in_array($hash, $this->groupTests, true);
}
}

View File

@@ -9,10 +9,12 @@
*/
namespace PHPUnit\Runner\Filter;
use function sprintf;
use FilterIterator;
use InvalidArgumentException;
use Iterator;
use PHPUnit\Framework\TestSuite;
use RecursiveFilterIterator;
use ReflectionClass;
/**
@@ -30,9 +32,9 @@ final class Factory
*/
public function addFilter(ReflectionClass $filter, $args): void
{
if (!$filter->isSubclassOf(\RecursiveFilterIterator::class)) {
if (!$filter->isSubclassOf(RecursiveFilterIterator::class)) {
throw new InvalidArgumentException(
\sprintf(
sprintf(
'Class "%s" does not extend RecursiveFilterIterator',
$filter->name
)

View File

@@ -9,6 +9,10 @@
*/
namespace PHPUnit\Runner\Filter;
use function array_map;
use function array_merge;
use function in_array;
use function spl_object_hash;
use PHPUnit\Framework\TestSuite;
use RecursiveFilterIterator;
use RecursiveIterator;
@@ -28,13 +32,13 @@ abstract class GroupFilterIterator extends RecursiveFilterIterator
parent::__construct($iterator);
foreach ($suite->getGroupDetails() as $group => $tests) {
if (\in_array((string) $group, $groups, true)) {
$testHashes = \array_map(
if (in_array((string) $group, $groups, true)) {
$testHashes = array_map(
'spl_object_hash',
$tests
);
$this->groupTests = \array_merge($this->groupTests, $testHashes);
$this->groupTests = array_merge($this->groupTests, $testHashes);
}
}
}
@@ -47,7 +51,7 @@ abstract class GroupFilterIterator extends RecursiveFilterIterator
return true;
}
return $this->doAccept(\spl_object_hash($test));
return $this->doAccept(spl_object_hash($test));
}
abstract protected function doAccept(string $hash);

View File

@@ -9,6 +9,8 @@
*/
namespace PHPUnit\Runner\Filter;
use function in_array;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
@@ -16,6 +18,6 @@ final class IncludeGroupFilterIterator extends GroupFilterIterator
{
protected function doAccept(string $hash): bool
{
return \in_array($hash, $this->groupTests, true);
return in_array($hash, $this->groupTests, true);
}
}

View File

@@ -9,6 +9,12 @@
*/
namespace PHPUnit\Runner\Filter;
use function end;
use function implode;
use function preg_match;
use function sprintf;
use function str_replace;
use Exception;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Framework\WarningTestCase;
use PHPUnit\Util\RegularExpression;
@@ -36,7 +42,7 @@ final class NameFilterIterator extends RecursiveFilterIterator
private $filterMax;
/**
* @throws \Exception
* @throws Exception
*/
public function __construct(RecursiveIterator $iterator, string $filter)
{
@@ -61,15 +67,15 @@ final class NameFilterIterator extends RecursiveFilterIterator
if ($test instanceof WarningTestCase) {
$name = $test->getMessage();
} elseif ($tmp[0] !== '') {
$name = \implode('::', $tmp);
$name = implode('::', $tmp);
} else {
$name = $tmp[1];
}
$accepted = @\preg_match($this->filter, $name, $matches);
$accepted = @preg_match($this->filter, $name, $matches);
if ($accepted && isset($this->filterMax)) {
$set = \end($matches);
$set = end($matches);
$accepted = $set >= $this->filterMin && $set <= $this->filterMax;
}
@@ -77,7 +83,7 @@ final class NameFilterIterator extends RecursiveFilterIterator
}
/**
* @throws \Exception
* @throws Exception
*/
private function setFilter(string $filter): void
{
@@ -85,9 +91,9 @@ final class NameFilterIterator extends RecursiveFilterIterator
// Handles:
// * testAssertEqualsSucceeds#4
// * testAssertEqualsSucceeds#4-8
if (\preg_match('/^(.*?)#(\d+)(?:-(\d+))?$/', $filter, $matches)) {
if (preg_match('/^(.*?)#(\d+)(?:-(\d+))?$/', $filter, $matches)) {
if (isset($matches[3]) && $matches[2] < $matches[3]) {
$filter = \sprintf(
$filter = sprintf(
'%s.*with data set #(\d+)$',
$matches[1]
);
@@ -95,7 +101,7 @@ final class NameFilterIterator extends RecursiveFilterIterator
$this->filterMin = (int) $matches[2];
$this->filterMax = (int) $matches[3];
} else {
$filter = \sprintf(
$filter = sprintf(
'%s.*with data set #%s$',
$matches[1],
$matches[2]
@@ -104,8 +110,8 @@ final class NameFilterIterator extends RecursiveFilterIterator
} // Handles:
// * testDetermineJsonError@JSON_ERROR_NONE
// * testDetermineJsonError@JSON.*
elseif (\preg_match('/^(.*?)@(.+)$/', $filter, $matches)) {
$filter = \sprintf(
elseif (preg_match('/^(.*?)@(.+)$/', $filter, $matches)) {
$filter = sprintf(
'%s.*with data set "%s"$',
$matches[1],
$matches[2]
@@ -114,9 +120,9 @@ final class NameFilterIterator extends RecursiveFilterIterator
// Escape delimiters in regular expression. Do NOT use preg_quote,
// to keep magic characters.
$filter = \sprintf(
$filter = sprintf(
'/%s/i',
\str_replace(
str_replace(
'/',
'\\/',
$filter

View File

@@ -15,6 +15,7 @@ use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Framework\Warning;
use PHPUnit\Util\Test as TestUtil;
use Throwable;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
@@ -47,7 +48,7 @@ final class TestListenerAdapter implements TestListener
$this->lastTestWasNotSuccessful = false;
}
public function addError(Test $test, \Throwable $t, float $time): void
public function addError(Test $test, Throwable $t, float $time): void
{
foreach ($this->hooks as $hook) {
if ($hook instanceof AfterTestErrorHook) {
@@ -80,7 +81,7 @@ final class TestListenerAdapter implements TestListener
$this->lastTestWasNotSuccessful = true;
}
public function addIncompleteTest(Test $test, \Throwable $t, float $time): void
public function addIncompleteTest(Test $test, Throwable $t, float $time): void
{
foreach ($this->hooks as $hook) {
if ($hook instanceof AfterIncompleteTestHook) {
@@ -91,7 +92,7 @@ final class TestListenerAdapter implements TestListener
$this->lastTestWasNotSuccessful = true;
}
public function addRiskyTest(Test $test, \Throwable $t, float $time): void
public function addRiskyTest(Test $test, Throwable $t, float $time): void
{
foreach ($this->hooks as $hook) {
if ($hook instanceof AfterRiskyTestHook) {
@@ -102,7 +103,7 @@ final class TestListenerAdapter implements TestListener
$this->lastTestWasNotSuccessful = true;
}
public function addSkippedTest(Test $test, \Throwable $t, float $time): void
public function addSkippedTest(Test $test, Throwable $t, float $time): void
{
foreach ($this->hooks as $hook) {
if ($hook instanceof AfterSkippedTestHook) {

View File

@@ -9,6 +9,40 @@
*/
namespace PHPUnit\Runner;
use const DEBUG_BACKTRACE_IGNORE_ARGS;
use const DIRECTORY_SEPARATOR;
use function array_merge;
use function basename;
use function debug_backtrace;
use function defined;
use function dirname;
use function explode;
use function extension_loaded;
use function file;
use function file_exists;
use function file_get_contents;
use function file_put_contents;
use function is_array;
use function is_file;
use function is_readable;
use function is_string;
use function ltrim;
use function phpversion;
use function preg_match;
use function preg_replace;
use function preg_split;
use function realpath;
use function rtrim;
use function sprintf;
use function str_replace;
use function strncasecmp;
use function strpos;
use function substr;
use function trim;
use function unlink;
use function unserialize;
use function var_export;
use function version_compare;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\ExpectationFailedException;
@@ -51,9 +85,9 @@ final class PhptTestCase implements SelfDescribing, Test
*/
public function __construct(string $filename, AbstractPhpProcess $phpUtil = null)
{
if (!\is_file($filename)) {
if (!is_file($filename)) {
throw new Exception(
\sprintf(
sprintf(
'File "%s" does not exist.',
$filename
)
@@ -75,13 +109,13 @@ final class PhptTestCase implements SelfDescribing, Test
/**
* Runs a test and collects its result in a TestResult instance.
*
* @throws Exception
* @throws \SebastianBergmann\CodeCoverage\CoveredCodeNotExecutedException
* @throws \SebastianBergmann\CodeCoverage\InvalidArgumentException
* @throws \SebastianBergmann\CodeCoverage\MissingCoversAnnotationException
* @throws \SebastianBergmann\CodeCoverage\RuntimeException
* @throws \SebastianBergmann\CodeCoverage\UnintentionallyCoveredCodeException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws Exception
*/
public function run(TestResult $result = null): TestResult
{
@@ -127,7 +161,7 @@ final class PhptTestCase implements SelfDescribing, Test
}
if (isset($sections['XFAIL'])) {
$xfail = \trim($sections['XFAIL']);
$xfail = trim($sections['XFAIL']);
}
if (isset($sections['STDIN'])) {
@@ -169,7 +203,7 @@ final class PhptTestCase implements SelfDescribing, Test
}
$hint = $this->getLocationHintFromDiff($diff, $sections);
$trace = \array_merge($hint, \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS));
$trace = array_merge($hint, debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS));
$failure = new PHPTAssertionFailedError(
$e->getMessage(),
0,
@@ -239,18 +273,18 @@ final class PhptTestCase implements SelfDescribing, Test
*/
private function parseIniSection($content, $ini = []): array
{
if (\is_string($content)) {
$content = \explode("\n", \trim($content));
if (is_string($content)) {
$content = explode("\n", trim($content));
}
foreach ($content as $setting) {
if (\strpos($setting, '=') === false) {
if (strpos($setting, '=') === false) {
continue;
}
$setting = \explode('=', $setting, 2);
$name = \trim($setting[0]);
$value = \trim($setting[1]);
$setting = explode('=', $setting, 2);
$name = trim($setting[0]);
$value = trim($setting[1]);
if ($name === 'extension' || $name === 'zend_extension') {
if (!isset($ini[$name])) {
@@ -272,8 +306,8 @@ final class PhptTestCase implements SelfDescribing, Test
{
$env = [];
foreach (\explode("\n", \trim($content)) as $e) {
$e = \explode('=', \trim($e), 2);
foreach (explode("\n", trim($content)) as $e) {
$e = explode('=', trim($e), 2);
if (!empty($e[0]) && isset($e[1])) {
$env[$e[0]] = $e[1];
@@ -284,9 +318,9 @@ final class PhptTestCase implements SelfDescribing, Test
}
/**
* @throws ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
* @throws Exception
* @throws ExpectationFailedException
*/
private function assertPhptExpectation(array $sections, string $output): void
{
@@ -296,11 +330,11 @@ final class PhptTestCase implements SelfDescribing, Test
'EXPECTREGEX' => 'assertRegExp',
];
$actual = \preg_replace('/\r\n/', "\n", \trim($output));
$actual = preg_replace('/\r\n/', "\n", trim($output));
foreach ($assertions as $sectionName => $sectionAssertion) {
if (isset($sections[$sectionName])) {
$sectionContent = \preg_replace('/\r\n/', "\n", \trim($sections[$sectionName]));
$sectionContent = preg_replace('/\r\n/', "\n", trim($sections[$sectionName]));
$expected = $sectionName === 'EXPECTREGEX' ? "/{$sectionContent}/" : $sectionContent;
if ($expected === null) {
@@ -328,15 +362,15 @@ final class PhptTestCase implements SelfDescribing, Test
$skipif = $this->render($sections['SKIPIF']);
$jobResult = $this->phpUtil->runJob($skipif, $this->stringifyIni($settings));
if (!\strncasecmp('skip', \ltrim($jobResult['stdout']), 4)) {
if (!strncasecmp('skip', ltrim($jobResult['stdout']), 4)) {
$message = '';
if (\preg_match('/^\s*skip\s*(.+)\s*/i', $jobResult['stdout'], $skipMatch)) {
$message = \substr($skipMatch[1], 2);
if (preg_match('/^\s*skip\s*(.+)\s*/i', $jobResult['stdout'], $skipMatch)) {
$message = substr($skipMatch[1], 2);
}
$hint = $this->getLocationHint($message, $sections, 'SKIPIF');
$trace = \array_merge($hint, \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS));
$trace = array_merge($hint, debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS));
$result->addFailure(
$this,
new SyntheticSkippedError($message, 0, $trace[0]['file'], $trace[0]['line'], $trace),
@@ -389,10 +423,10 @@ final class PhptTestCase implements SelfDescribing, Test
$lineNr = 0;
foreach (\file($this->filename) as $line) {
foreach (file($this->filename) as $line) {
$lineNr++;
if (\preg_match('/^--([_A-Z]+)--/', $line, $result)) {
if (preg_match('/^--([_A-Z]+)--/', $line, $result)) {
$section = $result[1];
$sections[$section] = '';
$sections[$section . '_offset'] = $lineNr;
@@ -408,7 +442,7 @@ final class PhptTestCase implements SelfDescribing, Test
}
if (isset($sections['FILEEOF'])) {
$sections['FILE'] = \rtrim($sections['FILEEOF'], "\r\n");
$sections['FILE'] = rtrim($sections['FILEEOF'], "\r\n");
unset($sections['FILEEOF']);
}
@@ -440,16 +474,16 @@ final class PhptTestCase implements SelfDescribing, Test
'EXPECTF',
'EXPECTREGEX',
];
$testDirectory = \dirname($this->filename) . \DIRECTORY_SEPARATOR;
$testDirectory = dirname($this->filename) . DIRECTORY_SEPARATOR;
foreach ($allowSections as $section) {
if (isset($sections[$section . '_EXTERNAL'])) {
$externalFilename = \trim($sections[$section . '_EXTERNAL']);
$externalFilename = trim($sections[$section . '_EXTERNAL']);
if (!\is_file($testDirectory . $externalFilename) ||
!\is_readable($testDirectory . $externalFilename)) {
if (!is_file($testDirectory . $externalFilename) ||
!is_readable($testDirectory . $externalFilename)) {
throw new Exception(
\sprintf(
sprintf(
'Could not load --%s-- %s for PHPT file',
$section . '_EXTERNAL',
$testDirectory . $externalFilename
@@ -457,7 +491,7 @@ final class PhptTestCase implements SelfDescribing, Test
);
}
$sections[$section] = \file_get_contents($testDirectory . $externalFilename);
$sections[$section] = file_get_contents($testDirectory . $externalFilename);
}
}
}
@@ -474,7 +508,7 @@ final class PhptTestCase implements SelfDescribing, Test
];
foreach ($requiredSections as $section) {
if (\is_array($section)) {
if (is_array($section)) {
$foundSection = false;
foreach ($section as $anySection) {
@@ -502,13 +536,13 @@ final class PhptTestCase implements SelfDescribing, Test
private function render(string $code): string
{
return \str_replace(
return str_replace(
[
'__DIR__',
'__FILE__',
],
[
"'" . \dirname($this->filename) . "'",
"'" . dirname($this->filename) . "'",
"'" . $this->filename . "'",
],
$code
@@ -517,8 +551,8 @@ final class PhptTestCase implements SelfDescribing, Test
private function getCoverageFiles(): array
{
$baseDir = \dirname(\realpath($this->filename)) . \DIRECTORY_SEPARATOR;
$basename = \basename($this->filename, 'phpt');
$baseDir = dirname(realpath($this->filename)) . DIRECTORY_SEPARATOR;
$basename = basename($this->filename, 'phpt');
return [
'coverage' => $baseDir . $basename . 'coverage',
@@ -536,20 +570,20 @@ final class PhptTestCase implements SelfDescribing, Test
$composerAutoload = '\'\'';
if (\defined('PHPUNIT_COMPOSER_INSTALL') && !\defined('PHPUNIT_TESTSUITE')) {
$composerAutoload = \var_export(PHPUNIT_COMPOSER_INSTALL, true);
if (defined('PHPUNIT_COMPOSER_INSTALL') && !defined('PHPUNIT_TESTSUITE')) {
$composerAutoload = var_export(PHPUNIT_COMPOSER_INSTALL, true);
}
$phar = '\'\'';
if (\defined('__PHPUNIT_PHAR__')) {
$phar = \var_export(__PHPUNIT_PHAR__, true);
if (defined('__PHPUNIT_PHAR__')) {
$phar = var_export(__PHPUNIT_PHAR__, true);
}
$globals = '';
if (!empty($GLOBALS['__PHPUNIT_BOOTSTRAP'])) {
$globals = '$GLOBALS[\'__PHPUNIT_BOOTSTRAP\'] = ' . \var_export(
$globals = '$GLOBALS[\'__PHPUNIT_BOOTSTRAP\'] = ' . var_export(
$GLOBALS['__PHPUNIT_BOOTSTRAP'],
true
) . ";\n";
@@ -565,7 +599,7 @@ final class PhptTestCase implements SelfDescribing, Test
]
);
\file_put_contents($files['job'], $job);
file_put_contents($files['job'], $job);
$job = $template->render();
}
@@ -574,11 +608,11 @@ final class PhptTestCase implements SelfDescribing, Test
$coverage = [];
$files = $this->getCoverageFiles();
if (\file_exists($files['coverage'])) {
$buffer = @\file_get_contents($files['coverage']);
if (file_exists($files['coverage'])) {
$buffer = @file_get_contents($files['coverage']);
if ($buffer !== false) {
$coverage = @\unserialize($buffer);
$coverage = @unserialize($buffer);
if ($coverage === false) {
$coverage = [];
@@ -587,7 +621,7 @@ final class PhptTestCase implements SelfDescribing, Test
}
foreach ($files as $file) {
@\unlink($file);
@unlink($file);
}
return $coverage;
@@ -598,7 +632,7 @@ final class PhptTestCase implements SelfDescribing, Test
$settings = [];
foreach ($ini as $key => $value) {
if (\is_array($value)) {
if (is_array($value)) {
foreach ($value as $val) {
$settings[] = $key . '=' . $val;
}
@@ -618,8 +652,8 @@ final class PhptTestCase implements SelfDescribing, Test
$previousLine = '';
$block = 'message';
foreach (\preg_split('/\r\n|\r|\n/', $message) as $line) {
$line = \trim($line);
foreach (preg_split('/\r\n|\r|\n/', $message) as $line) {
$line = trim($line);
if ($block === 'message' && $line === '--- Expected') {
$block = 'expected';
@@ -630,13 +664,13 @@ final class PhptTestCase implements SelfDescribing, Test
}
if ($block === 'diff') {
if (\strpos($line, '+') === 0) {
if (strpos($line, '+') === 0) {
$needle = $this->getCleanDiffLine($previousLine);
break;
}
if (\strpos($line, '-') === 0) {
if (strpos($line, '-') === 0) {
$needle = $this->getCleanDiffLine($line);
break;
@@ -653,7 +687,7 @@ final class PhptTestCase implements SelfDescribing, Test
private function getCleanDiffLine(string $line): string
{
if (\preg_match('/^[\-+]([\'\"]?)(.*)\1$/', $line, $matches)) {
if (preg_match('/^[\-+]([\'\"]?)(.*)\1$/', $line, $matches)) {
$line = $matches[2];
}
@@ -662,11 +696,11 @@ final class PhptTestCase implements SelfDescribing, Test
private function getLocationHint(string $needle, array $sections, ?string $sectionName = null): array
{
$needle = \trim($needle);
$needle = trim($needle);
if (empty($needle)) {
return [[
'file' => \realpath($this->filename),
'file' => realpath($this->filename),
'line' => 1,
]];
}
@@ -688,15 +722,15 @@ final class PhptTestCase implements SelfDescribing, Test
}
if (isset($sections[$section . '_EXTERNAL'])) {
$externalFile = \trim($sections[$section . '_EXTERNAL']);
$externalFile = trim($sections[$section . '_EXTERNAL']);
return [
[
'file' => \realpath(\dirname($this->filename) . \DIRECTORY_SEPARATOR . $externalFile),
'file' => realpath(dirname($this->filename) . DIRECTORY_SEPARATOR . $externalFile),
'line' => 1,
],
[
'file' => \realpath($this->filename),
'file' => realpath($this->filename),
'line' => ($sections[$section . '_EXTERNAL_offset'] ?? 0) + 1,
],
];
@@ -705,10 +739,10 @@ final class PhptTestCase implements SelfDescribing, Test
$sectionOffset = $sections[$section . '_offset'] ?? 0;
$offset = $sectionOffset + 1;
foreach (\preg_split('/\r\n|\r|\n/', $sections[$section]) as $line) {
if (\strpos($line, $needle) !== false) {
foreach (preg_split('/\r\n|\r|\n/', $sections[$section]) as $line) {
if (strpos($line, $needle) !== false) {
return [[
'file' => \realpath($this->filename),
'file' => realpath($this->filename),
'line' => $offset,
]];
}
@@ -719,14 +753,14 @@ final class PhptTestCase implements SelfDescribing, Test
if ($sectionName) {
// String not found in specified section, show user the start of the named section
return [[
'file' => \realpath($this->filename),
'file' => realpath($this->filename),
'line' => $sectionOffset,
]];
}
// No section specified, show user start of code
return [[
'file' => \realpath($this->filename),
'file' => realpath($this->filename),
'line' => 1,
]];
}
@@ -756,7 +790,7 @@ final class PhptTestCase implements SelfDescribing, Test
'report_zend_debug=0',
];
if (\extension_loaded('pcov')) {
if (extension_loaded('pcov')) {
if ($collectCoverage) {
$settings[] = 'pcov.enabled=1';
} else {
@@ -764,8 +798,8 @@ final class PhptTestCase implements SelfDescribing, Test
}
}
if (\extension_loaded('xdebug')) {
if (\version_compare(\phpversion('xdebug'), '3', '>=')) {
if (extension_loaded('xdebug')) {
if (version_compare(phpversion('xdebug'), '3', '>=')) {
if ($collectCoverage) {
$settings[] = 'xdebug.mode=coverage';
} else {

View File

@@ -9,6 +9,9 @@
*/
namespace PHPUnit\Runner;
use function preg_match;
use function round;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
@@ -33,14 +36,14 @@ final class ResultCacheExtension implements AfterIncompleteTestHook, AfterLastTe
{
$testName = $this->getTestName($test);
$this->cache->setTime($testName, \round($time, 3));
$this->cache->setTime($testName, round($time, 3));
}
public function executeAfterIncompleteTest(string $test, string $message, float $time): void
{
$testName = $this->getTestName($test);
$this->cache->setTime($testName, \round($time, 3));
$this->cache->setTime($testName, round($time, 3));
$this->cache->setState($testName, BaseTestRunner::STATUS_INCOMPLETE);
}
@@ -48,7 +51,7 @@ final class ResultCacheExtension implements AfterIncompleteTestHook, AfterLastTe
{
$testName = $this->getTestName($test);
$this->cache->setTime($testName, \round($time, 3));
$this->cache->setTime($testName, round($time, 3));
$this->cache->setState($testName, BaseTestRunner::STATUS_RISKY);
}
@@ -56,7 +59,7 @@ final class ResultCacheExtension implements AfterIncompleteTestHook, AfterLastTe
{
$testName = $this->getTestName($test);
$this->cache->setTime($testName, \round($time, 3));
$this->cache->setTime($testName, round($time, 3));
$this->cache->setState($testName, BaseTestRunner::STATUS_SKIPPED);
}
@@ -64,7 +67,7 @@ final class ResultCacheExtension implements AfterIncompleteTestHook, AfterLastTe
{
$testName = $this->getTestName($test);
$this->cache->setTime($testName, \round($time, 3));
$this->cache->setTime($testName, round($time, 3));
$this->cache->setState($testName, BaseTestRunner::STATUS_ERROR);
}
@@ -72,7 +75,7 @@ final class ResultCacheExtension implements AfterIncompleteTestHook, AfterLastTe
{
$testName = $this->getTestName($test);
$this->cache->setTime($testName, \round($time, 3));
$this->cache->setTime($testName, round($time, 3));
$this->cache->setState($testName, BaseTestRunner::STATUS_FAILURE);
}
@@ -80,7 +83,7 @@ final class ResultCacheExtension implements AfterIncompleteTestHook, AfterLastTe
{
$testName = $this->getTestName($test);
$this->cache->setTime($testName, \round($time, 3));
$this->cache->setTime($testName, round($time, 3));
$this->cache->setState($testName, BaseTestRunner::STATUS_WARNING);
}
@@ -98,7 +101,7 @@ final class ResultCacheExtension implements AfterIncompleteTestHook, AfterLastTe
{
$matches = [];
if (\preg_match('/^(?<name>\S+::\S+)(?:(?<dataname> with data set (?:#\d+|"[^"]+"))\s\()?/', $test, $matches)) {
if (preg_match('/^(?<name>\S+::\S+)(?:(?<dataname> with data set (?:#\d+|"[^"]+"))\s\()?/', $test, $matches)) {
$test = $matches['name'] . ($matches['dataname'] ?? '');
}

View File

@@ -9,9 +9,20 @@
*/
namespace PHPUnit\Runner;
use function array_diff;
use function array_values;
use function class_exists;
use function get_declared_classes;
use function realpath;
use function sprintf;
use function str_replace;
use function strlen;
use function substr;
use PHPUnit\Framework\TestCase;
use PHPUnit\Util\FileLoader;
use PHPUnit\Util\Filesystem;
use ReflectionClass;
use ReflectionException;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
@@ -19,12 +30,12 @@ use PHPUnit\Util\Filesystem;
final class StandardTestSuiteLoader implements TestSuiteLoader
{
/**
* @throws Exception
* @throws \PHPUnit\Framework\Exception
* @throws Exception
*/
public function load(string $suiteClassName, string $suiteClassFile = ''): \ReflectionClass
public function load(string $suiteClassName, string $suiteClassFile = ''): ReflectionClass
{
$suiteClassName = \str_replace('.php', '', $suiteClassName);
$suiteClassName = str_replace('.php', '', $suiteClassName);
$filename = null;
if (empty($suiteClassFile)) {
@@ -33,24 +44,24 @@ final class StandardTestSuiteLoader implements TestSuiteLoader
);
}
if (!\class_exists($suiteClassName, false)) {
$loadedClasses = \get_declared_classes();
if (!class_exists($suiteClassName, false)) {
$loadedClasses = get_declared_classes();
$filename = FileLoader::checkAndLoad($suiteClassFile);
$loadedClasses = \array_values(
\array_diff(\get_declared_classes(), $loadedClasses)
$loadedClasses = array_values(
array_diff(get_declared_classes(), $loadedClasses)
);
}
if (!empty($loadedClasses) && !\class_exists($suiteClassName, false)) {
$offset = 0 - \strlen($suiteClassName);
if (!empty($loadedClasses) && !class_exists($suiteClassName, false)) {
$offset = 0 - strlen($suiteClassName);
foreach ($loadedClasses as $loadedClass) {
try {
$class = new \ReflectionClass($loadedClass);
$class = new ReflectionClass($loadedClass);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
@@ -59,7 +70,7 @@ final class StandardTestSuiteLoader implements TestSuiteLoader
}
// @codeCoverageIgnoreEnd
if (\substr($loadedClass, $offset) === $suiteClassName &&
if (substr($loadedClass, $offset) === $suiteClassName &&
$class->getFileName() == $filename) {
$suiteClassName = $loadedClass;
@@ -68,14 +79,14 @@ final class StandardTestSuiteLoader implements TestSuiteLoader
}
}
if (!empty($loadedClasses) && !\class_exists($suiteClassName, false)) {
if (!empty($loadedClasses) && !class_exists($suiteClassName, false)) {
$testCaseClass = TestCase::class;
foreach ($loadedClasses as $loadedClass) {
try {
$class = new \ReflectionClass($loadedClass);
$class = new ReflectionClass($loadedClass);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
@@ -90,7 +101,7 @@ final class StandardTestSuiteLoader implements TestSuiteLoader
$suiteClassName = $loadedClass;
$testCaseClass = $loadedClass;
if ($classFile == \realpath($suiteClassFile)) {
if ($classFile == realpath($suiteClassFile)) {
break;
}
}
@@ -99,7 +110,7 @@ final class StandardTestSuiteLoader implements TestSuiteLoader
try {
$method = $class->getMethod('suite');
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
@@ -111,7 +122,7 @@ final class StandardTestSuiteLoader implements TestSuiteLoader
if (!$method->isAbstract() && $method->isPublic() && $method->isStatic()) {
$suiteClassName = $loadedClass;
if ($classFile == \realpath($suiteClassFile)) {
if ($classFile == realpath($suiteClassFile)) {
break;
}
}
@@ -119,11 +130,11 @@ final class StandardTestSuiteLoader implements TestSuiteLoader
}
}
if (\class_exists($suiteClassName, false)) {
if (class_exists($suiteClassName, false)) {
try {
$class = new \ReflectionClass($suiteClassName);
$class = new ReflectionClass($suiteClassName);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
} catch (ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
@@ -132,13 +143,13 @@ final class StandardTestSuiteLoader implements TestSuiteLoader
}
// @codeCoverageIgnoreEnd
if ($class->getFileName() == \realpath($suiteClassFile)) {
if ($class->getFileName() == realpath($suiteClassFile)) {
return $class;
}
}
throw new Exception(
\sprintf(
sprintf(
"Class '%s' could not be found in '%s'.",
$suiteClassName,
$suiteClassFile
@@ -146,7 +157,7 @@ final class StandardTestSuiteLoader implements TestSuiteLoader
);
}
public function reload(\ReflectionClass $aClass): \ReflectionClass
public function reload(ReflectionClass $aClass): ReflectionClass
{
return $aClass;
}

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