diff --git a/.gitattributes b/.gitattributes index 4962be9f930..6c37affab5f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,16 +1,16 @@ -/.docker export-ignore -/.github export-ignore -/.phive export-ignore -/.psalm export-ignore -/build export-ignore -/tools export-ignore -/tools/* binary -/tests export-ignore -/.editorconfig export-ignore -/.gitattributes export-ignore -/.gitignore export-ignore -/.php_cs.dist export-ignore -/build.xml export-ignore -/phpunit.xml export-ignore +/.docker export-ignore +/.github export-ignore +/.phive export-ignore +/.psalm export-ignore +/build export-ignore +/tools export-ignore +/tools/* binary +/tests export-ignore +/.editorconfig export-ignore +/.gitattributes export-ignore +/.gitignore export-ignore +/.php-cs-fixer.dist.php export-ignore +/build.xml export-ignore +/phpunit.xml export-ignore *.php diff=php diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 097f9af56da..e4f59854f1b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,7 +23,7 @@ jobs: coverage: none - name: Run friendsofphp/php-cs-fixer - run: ./tools/php-cs-fixer fix --diff-format=udiff --dry-run --show-progress=dots --using-cache=no --verbose + run: ./tools/php-cs-fixer fix --dry-run --show-progress=dots --using-cache=no --verbose type-checker: name: Type Checker @@ -106,6 +106,8 @@ jobs: - 7.2 - 7.3 - 7.4 + - 8.0 + - 8.1 dependencies: - lowest @@ -123,17 +125,17 @@ jobs: uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php-version }} - coverage: pcov + coverage: xdebug extensions: dom, json, libxml, mbstring, pdo_sqlite, soap, xml, xmlwriter ini-values: assert.exception=1, zend.assertions=1 - name: Determine composer cache directory on Linux if: matrix.os == 'ubuntu-latest' - run: echo "::set-env name=COMPOSER_CACHE_DIR::$(./tools/composer config cache-dir)" + run: echo "COMPOSER_CACHE_DIR=$(tools/composer config cache-dir)" >> $GITHUB_ENV - name: Determine composer cache directory on Windows if: matrix.os == 'windows-latest' - run: ECHO "::set-env name=COMPOSER_CACHE_DIR::~\AppData\Local\Composer" + run: echo "COMPOSER_CACHE_DIR=~\AppData\Local\Composer" | Out-File -FilePath $env:GITHUB_ENV -Append - name: Cache dependencies installed with composer uses: actions/cache@v2 diff --git a/.gitignore b/.gitignore index a16a6520180..249c99fde98 100644 --- a/.gitignore +++ b/.gitignore @@ -13,13 +13,14 @@ /build/tmp # PHP-CS-Fixer -/.php_cs -/.php_cs.cache +/.php-cs-fixer.php +/.php-cs-fixer.cache # Psalm /.psalm/cache # PHPUnit +/.phpunit.cache .phpunit.result.cache # Temporary files generated by PHPT test runner diff --git a/.phive/phars.xml b/.phive/phars.xml index 7e1828e1a05..ce8ad12e8b9 100644 --- a/.phive/phars.xml +++ b/.phive/phars.xml @@ -1,10 +1,11 @@ - - + + - - + + + diff --git a/.php_cs.dist b/.php-cs-fixer.dist.php similarity index 68% rename from .php_cs.dist rename to .php-cs-fixer.dist.php index a5f20daa38c..2fb96e9ab0c 100644 --- a/.php_cs.dist +++ b/.php-cs-fixer.dist.php @@ -11,21 +11,27 @@ $finder = PhpCsFixer\Finder::create() ->files() ->in(__DIR__ . '/src') - ->in(__DIR__ . '/tests/_files') ->in(__DIR__ . '/tests/basic') ->in(__DIR__ . '/tests/end-to-end') ->in(__DIR__ . '/tests/fail') ->in(__DIR__ . '/tests/unit') + ->in(__DIR__ . '/tests/_files') ->notName('*.phpt') - ->notName('ClassWithAllPossibleReturnTypes.php'); + ->notName('ClassWithAllPossibleReturnTypes.php') + ->notName('ClassWithUnionReturnTypes.php') + ->notName('ClassWithStaticReturnTypes.php') + ->notName('ValueObjectWithEqualsMethodWithUnionReturnType.php') + ->notName('ValueObjectWithEqualsMethodThatHasUnionParameterType.php'); -return PhpCsFixer\Config::create() - ->setFinder($finder) +$config = new PhpCsFixer\Config; +$config->setFinder($finder) ->setRiskyAllowed(true) ->setRules([ 'align_multiline_comment' => true, 'array_indentation' => true, + 'array_push' => true, 'array_syntax' => ['syntax' => 'short'], + 'backtick_to_shell_exec' => true, 'binary_operator_spaces' => [ 'operators' => [ '=' => 'align_single_space_minimal', @@ -39,7 +45,6 @@ 'continue', 'declare', 'default', - 'die', 'do', 'exit', 'for', @@ -60,50 +65,78 @@ ], 'braces' => true, 'cast_spaces' => true, - 'class_attributes_separation' => ['elements' => ['const', 'method', 'property']], + 'class_attributes_separation' => [ + 'elements' => [ + 'const' => 'one', + 'method' => 'one', + 'property' => 'one' + ] + ], + 'class_definition' => true, + 'clean_namespace' => true, 'combine_consecutive_issets' => true, 'combine_consecutive_unsets' => true, + 'combine_nested_dirname' => true, 'compact_nullable_typehint' => true, 'concat_space' => ['spacing' => 'one'], 'constant_case' => true, 'declare_equal_normalize' => ['space' => 'none'], 'declare_strict_types' => true, 'dir_constant' => true, + 'echo_tag_syntax' => true, 'elseif' => true, 'encoding' => true, + 'ereg_to_preg' => true, 'explicit_indirect_variable' => true, 'explicit_string_variable' => true, + 'fopen_flag_order' => true, 'full_opening_tag' => true, 'fully_qualified_strict_types' => true, 'function_declaration' => true, + 'function_to_constant' => true, + 'function_typehint_space' => true, + 'global_namespace_import' => [ + 'import_classes' => true, + 'import_constants' => true, + 'import_functions' => true, + ], 'header_comment' => ['header' => $header, 'separate' => 'none'], 'heredoc_to_nowdoc' => true, + 'implode_call' => true, + 'include' => true, 'increment_style' => [ 'style' => PhpCsFixer\Fixer\Operator\IncrementStyleFixer::STYLE_POST, ], 'indentation_type' => true, 'is_null' => true, + 'lambda_not_used_import' => true, 'line_ending' => true, 'list_syntax' => ['syntax' => 'short'], 'logical_operators' => true, + 'lowercase_cast' => true, 'lowercase_keywords' => true, 'lowercase_static_reference' => true, 'magic_constant_casing' => true, 'magic_method_casing' => true, - 'method_argument_space' => ['ensure_fully_multiline' => true], + 'method_argument_space' => [ + 'on_multiline' => 'ensure_fully_multiline', + ], 'modernize_types_casting' => true, 'multiline_comment_opening_closing' => true, 'multiline_whitespace_before_semicolons' => true, - 'native_constant_invocation' => true, - 'native_function_casing' => true, - 'native_function_invocation' => true, + 'native_constant_invocation' => false, + 'native_function_casing' => false, + 'native_function_invocation' => false, 'native_function_type_declaration_casing' => true, 'new_with_braces' => false, 'no_alias_functions' => true, + 'no_alias_language_construct_call' => true, 'no_alternative_syntax' => true, + 'no_binary_string' => true, 'no_blank_lines_after_class_opening' => true, 'no_blank_lines_after_phpdoc' => true, 'no_blank_lines_before_namespace' => true, + 'no_break_comment' => true, 'no_closing_tag' => true, 'no_empty_comment' => true, 'no_empty_phpdoc' => true, @@ -117,7 +150,6 @@ 'no_null_property_initialization' => true, 'no_php4_constructor' => true, 'no_short_bool_cast' => true, - 'no_short_echo_tag' => true, 'no_singleline_whitespace_before_semicolons' => true, 'no_spaces_after_function_name' => true, 'no_spaces_around_offset' => true, @@ -130,19 +162,26 @@ 'no_trailing_comma_in_singleline_array' => true, 'no_trailing_whitespace' => true, 'no_trailing_whitespace_in_comment' => true, + 'no_trailing_whitespace_in_string' => true, 'no_unneeded_control_parentheses' => true, 'no_unneeded_curly_braces' => true, 'no_unneeded_final_method' => true, 'no_unreachable_default_argument_value' => true, + 'no_unset_cast' => true, 'no_unset_on_property' => true, 'no_unused_imports' => true, 'no_useless_else' => true, 'no_useless_return' => true, + 'no_useless_sprintf' => true, 'no_whitespace_before_comma_in_array' => true, 'no_whitespace_in_blank_line' => true, 'non_printable_character' => true, 'normalize_index_brace' => true, 'object_operator_without_whitespace' => true, + 'operator_linebreak' => [ + 'only_booleans' => true, + 'position' => 'end', + ], 'ordered_class_elements' => [ 'order' => [ 'use_trait', @@ -167,28 +206,54 @@ 'method_private_static', ], ], - 'ordered_imports' => true, + 'ordered_imports' => [ + 'imports_order' => [ + PhpCsFixer\Fixer\Import\OrderedImportsFixer::IMPORT_TYPE_CONST, + PhpCsFixer\Fixer\Import\OrderedImportsFixer::IMPORT_TYPE_FUNCTION, + PhpCsFixer\Fixer\Import\OrderedImportsFixer::IMPORT_TYPE_CLASS, + ] + ], 'ordered_interfaces' => [ 'direction' => 'ascend', 'order' => 'alpha', ], + 'ordered_traits' => true, + 'php_unit_set_up_tear_down_visibility' => true, + 'php_unit_test_case_static_method_calls' => [ + 'call_type' => 'this', + ], 'phpdoc_add_missing_param_annotation' => false, 'phpdoc_align' => true, 'phpdoc_annotation_without_dot' => true, 'phpdoc_indent' => true, + 'phpdoc_inline_tag_normalizer' => true, 'phpdoc_no_access' => true, + 'phpdoc_no_alias_tag' => true, 'phpdoc_no_empty_return' => true, 'phpdoc_no_package' => true, + 'phpdoc_no_useless_inheritdoc' => true, 'phpdoc_order' => true, + 'phpdoc_order_by_value' => [ + 'annotations' => [ + 'covers', + 'dataProvider', + 'throws', + 'uses', + ], + ], 'phpdoc_return_self_reference' => true, 'phpdoc_scalar' => true, 'phpdoc_separation' => true, 'phpdoc_single_line_var_spacing' => true, + 'phpdoc_summary' => true, + 'phpdoc_tag_casing' => true, + 'phpdoc_tag_type' => true, 'phpdoc_to_comment' => true, 'phpdoc_trim' => true, 'phpdoc_trim_consecutive_blank_line_separation' => true, 'phpdoc_types' => ['groups' => ['simple', 'meta']], 'phpdoc_types_order' => true, + 'phpdoc_var_annotation_correct_order' => true, 'phpdoc_var_without_name' => true, 'pow_to_exponentiation' => true, 'protected_to_private' => true, @@ -202,13 +267,29 @@ 'simple_to_complex_string_variable' => true, 'simplified_null_return' => false, 'single_blank_line_at_eof' => true, + 'single_class_element_per_statement' => true, 'single_import_per_statement' => true, 'single_line_after_imports' => true, 'single_quote' => true, + 'single_space_after_construct' => true, + 'single_trait_insert_per_statement' => true, + 'space_after_semicolon' => true, + 'standardize_increment' => true, 'standardize_not_equals' => true, + 'static_lambda' => true, 'strict_param' => true, + 'string_line_ending' => true, + 'switch_case_semicolon_to_colon' => true, + 'switch_case_space' => true, + 'switch_continue_to_break' => true, + 'ternary_operator_spaces' => true, + 'ternary_to_elvis_operator' => true, 'ternary_to_null_coalescing' => true, - 'trailing_comma_in_multiline_array' => true, + 'trailing_comma_in_multiline' => [ + 'elements' => [ + 'arrays' + ] + ], 'trim_array_spaces' => true, 'unary_operator_spaces' => true, 'visibility_required' => [ @@ -221,3 +302,5 @@ 'void_return' => true, 'whitespace_after_comma_in_array' => true, ]); + +return $config; diff --git a/.psalm/baseline.xml b/.psalm/baseline.xml index 6985682470b..b7f71a9ffb1 100644 --- a/.psalm/baseline.xml +++ b/.psalm/baseline.xml @@ -1,37 +1,423 @@ - + - $expectedElement->childNodes->item($i) $actualElement->childNodes->item($i) + $expectedElement->childNodes->item($i) + + Attribute + Attribute + TraversableContains + new ArraySubset($subset, $checkForObjectIdentity) + new Attribute($constraint, $attributeName) + new TraversableContains($value, $checkForObjectIdentity, $checkForNonObjectIdentity) + + + static::readAttribute($actualClassOrObject, $actualAttributeName) + static::readAttribute($actualClassOrObject, $actualAttributeName) + static::readAttribute($actualClassOrObject, $actualAttributeName) + static::readAttribute($actualClassOrObject, $actualAttributeName) + static::readAttribute($actualClassOrObject, $actualAttributeName) + static::readAttribute($actualClassOrObject, $actualAttributeName) + static::readAttribute($actualClassOrObject, $actualAttributeName) + static::readAttribute($actualClassOrObject, $actualAttributeName) + static::readAttribute($classOrObject, $attributeName) + static::readAttribute($classOrObject, $attributeName) + static::readAttribute($classOrObject, $attributeName) + static::readAttribute($classOrObject, $attributeName) + static::readAttribute($haystackClassOrObject, $haystackAttributeName) + static::readAttribute($haystackClassOrObject, $haystackAttributeName) + static::readAttribute($haystackClassOrObject, $haystackAttributeName) + static::readAttribute($haystackClassOrObject, $haystackAttributeName) + static::readAttribute($haystackClassOrObject, $haystackAttributeName) + static::readAttribute($haystackClassOrObject, $haystackAttributeName) + static::readAttribute($haystackClassOrObject, $haystackAttributeName) + static::readAttribute($haystackClassOrObject, $haystackAttributeName) + + + !$actual instanceof Countable && !is_iterable($actual) + !$actual instanceof Countable && !is_iterable($actual) + !$expected instanceof Countable && !is_iterable($expected) + !$expected instanceof Countable && !is_iterable($expected) + !$haystack instanceof Countable && !is_iterable($haystack) + !$haystack instanceof Countable && !is_iterable($haystack) + $array instanceof ArrayAccess + $array instanceof ArrayAccess + $array instanceof ArrayAccess + $subset instanceof ArrayAccess + is_array($array) || $array instanceof ArrayAccess + is_array($array) || $array instanceof ArrayAccess + is_array($array) || $array instanceof ArrayAccess + is_array($subset) || $subset instanceof ArrayAccess + is_int($key) || is_string($key) + is_int($key) || is_string($key) + is_object($object) + is_object($object) + is_object($object) + is_string($key) + is_string($key) + + + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $attributeName + $condition + $condition + $condition + $condition + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $haystack + $haystack + $needle + $needle + $needle + $needle + $needle + $needle + $prefix + $value + $value + $value + $value + $value + $value + $value + $value + $value + $value + $value + + + getObjectAttribute + getStaticAttribute + readAttribute + + + new IsType($expected) + new IsType($expected) + new IsType($type) + new IsType(IsType::TYPE_ARRAY) + new IsType(IsType::TYPE_ARRAY) + new IsType(IsType::TYPE_BOOL) + new IsType(IsType::TYPE_BOOL) + new IsType(IsType::TYPE_CALLABLE) + new IsType(IsType::TYPE_CALLABLE) + new IsType(IsType::TYPE_FLOAT) + new IsType(IsType::TYPE_FLOAT) + new IsType(IsType::TYPE_INT) + new IsType(IsType::TYPE_INT) + new IsType(IsType::TYPE_ITERABLE) + new IsType(IsType::TYPE_ITERABLE) + new IsType(IsType::TYPE_NUMERIC) + new IsType(IsType::TYPE_NUMERIC) + new IsType(IsType::TYPE_OBJECT) + new IsType(IsType::TYPE_OBJECT) + new IsType(IsType::TYPE_RESOURCE) + new IsType(IsType::TYPE_RESOURCE) + new IsType(IsType::TYPE_SCALAR) + new IsType(IsType::TYPE_SCALAR) + new IsType(IsType::TYPE_STRING) + new IsType(IsType::TYPE_STRING) + new TraversableContainsOnly($className, false) + new TraversableContainsOnly($type) + self::assertInternalTypeReplacement($expected, false) + self::assertInternalTypeReplacement($expected, true) + static::assertThat($haystack, $constraint, $message) + static::assertThat($haystack, $constraint, $message) + - $subset $expected $expected + $subset + + assert($step['object'] instanceof TestCase) + + + is_object($classOrObject) + + + !$attribute + + + Attribute + Attribute + TraversableContains + + + Assert::assertArraySubset(...\func_get_args()) + Assert::assertAttributeContains(...\func_get_args()) + Assert::assertAttributeContainsOnly(...\func_get_args()) + Assert::assertAttributeCount(...\func_get_args()) + Assert::assertAttributeEmpty(...\func_get_args()) + Assert::assertAttributeEquals(...\func_get_args()) + Assert::assertAttributeGreaterThan(...\func_get_args()) + Assert::assertAttributeGreaterThanOrEqual(...\func_get_args()) + Assert::assertAttributeInstanceOf(...\func_get_args()) + Assert::assertAttributeInternalType(...\func_get_args()) + Assert::assertAttributeLessThan(...\func_get_args()) + Assert::assertAttributeLessThanOrEqual(...\func_get_args()) + Assert::assertAttributeNotContains(...\func_get_args()) + Assert::assertAttributeNotContainsOnly(...\func_get_args()) + Assert::assertAttributeNotCount(...\func_get_args()) + Assert::assertAttributeNotEmpty(...\func_get_args()) + Assert::assertAttributeNotEquals(...\func_get_args()) + Assert::assertAttributeNotInstanceOf(...\func_get_args()) + Assert::assertAttributeNotInternalType(...\func_get_args()) + Assert::assertAttributeNotSame(...\func_get_args()) + Assert::assertAttributeSame(...\func_get_args()) + Assert::assertInternalType(...\func_get_args()) + Assert::assertNotInternalType(...\func_get_args()) + Assert::attribute(...\func_get_args()) + Assert::attributeEqualTo(...\func_get_args()) + Assert::contains(...\func_get_args()) + + + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $actual + $attributeName + $callback + $condition + $condition + $condition + $condition + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $expected + $haystack + $haystack + $key + $needle + $needle + $needle + $needle + $needle + $needle + $prefix + $value + $value + $value + $value + $value + $value + $value + $value + $value + $value + $value + $value + + + Assert::logicalAnd(...\func_get_args()) + Assert::anything(...\func_get_args()) - Assert::isTrue(...\func_get_args()) + Assert::directoryExists(...\func_get_args()) + Assert::fileExists(...\func_get_args()) + Assert::isEmpty(...\func_get_args()) Assert::isFalse(...\func_get_args()) - Assert::isJson(...\func_get_args()) - Assert::isNull(...\func_get_args()) Assert::isFinite(...\func_get_args()) Assert::isInfinite(...\func_get_args()) + Assert::isJson(...\func_get_args()) Assert::isNan(...\func_get_args()) - Assert::isEmpty(...\func_get_args()) - Assert::isWritable(...\func_get_args()) + Assert::isNull(...\func_get_args()) Assert::isReadable(...\func_get_args()) - Assert::directoryExists(...\func_get_args()) - Assert::fileExists(...\func_get_args()) + Assert::isTrue(...\func_get_args()) + Assert::isWritable(...\func_get_args()) + + + $other + + + evaluate + + + $other instanceof Traversable + + + + + Composite + parent::__construct($constraint) + + + + $other + + + evaluate + + + + + + + + + + + $other + + + evaluate + + + + + $this->exporter === null + + + $other + + + evaluate + + $this->getCountOf($other) + + $other instanceof Traversable + + + + + Filter::getFilteredStacktrace($other) + @@ -42,12 +428,41 @@ $other + + (string) $other->getMessage() + $other + + + $other + + + evaluate + + + + + $other + $value + + + evaluate + + + + + $other + $value + + + evaluate + + $this->className @@ -62,6 +477,50 @@ bool + + is_string($resource) + + + + + $constraint instanceof Constraint + + + $other + + + evaluate + + + + + $other + + + evaluate + + + + + $constraint instanceof Constraint + + + $other + + + evaluate + + + + + $constraint instanceof Constraint + + + $other + + + evaluate + @@ -72,11 +531,58 @@ "--- Expected\n+++ Actual\n" + + $text + + + new Differ("--- Expected\n+++ Actual\n") + + + + + throw InvalidArgumentException::create(1, 'non-empty string'); + + + + + $value + + + + + $value + + + + + $value + + + + + $other + + + evaluate + $className + + DataProviderTestSuite + DataProviderTestSuite + + + + + $code + $message + + + Filter::getFilteredStacktrace($this) + @@ -84,24 +590,130 @@ + + Filter::getFilteredStacktrace($this) + $t->getPrevious() + + + $backupGlobals + + + + + id + + + + + $arguments + $id + $id + $nextValues + $value + + + new Rule\ConsecutiveParameters($arguments) + new Rule\MethodName($constraint) + new Rule\Parameters($arguments) + registerMatcher + + + + + $nextValues + $value + + + + + $arguments + + + + + $value + + - + + $className $className $className - $interfaceName $className + $interfaceName + + !is_array($methods) && null !== $methods + !is_array($type) && !is_string($type) + MockObject&RealInstanceType - - \strpos($args[$i], '$') - + + new $className + + + $type + $type + + + getObject + + + generateMock + generateMock + new Text_Template($filename) + throw InvalidArgumentException::create(1, 'array or string'); + throw InvalidArgumentException::create(2, 'array'); + throw new RuntimeException($exception->getMessage()); + + + + + static function () { + + + + + throw $this->deferredError; + + + $deferredError + + + $this->deferredError + + + + + $this->methodNameRule === null + $this->methodNameRule === null + $this->methodNameRule === null + $this->parametersRule === null + + + invoked + + + $methodNameRule + $parametersRule + $stub + + + $this->invocationRule !== null + $this->methodNameRule !== null + $this->methodNameRule !== null + $this->parametersRule !== null + $this->parametersRule !== null + $this->parametersRule !== null + $this->stub + $this->stub !== null + @@ -109,6 +721,9 @@ $this->type $this->type + + setMethods + $object $object @@ -119,66 +734,391 @@ MockObject&MockedType MockObject&MockedType + + getClassMethods + $type + + new Text_Template($filename) + self::getMethodParametersForCall($method) + allowsNull + + getName + getName + getName + + + + + $originalObject + $invocation === null + + + invoked + invokedDo + + + + + $constraint instanceof Constraint + + + evaluate + + + + $this->invocation === null + null + + $invocation + $parameterVerificationResult + + + (bool) $this->parameterVerificationResult + + + isset($this->parameterVerificationResult) + + + + + invoke + + + + + $argumentIndex + + + invoke + + + + + $callback + + + $callback + + + invoke + + + + + $reference + + + invoke + + + + + invoke + + + + + $value + + + invoke + + + + + invoke + + + + + invoke + + + + + $backupGlobals + + + + + $data + + + buildTestWithoutData + + + Filter::getFilteredStacktrace($t) + Filter::getFilteredStacktrace($t) + throw new Exception('No valid test provided.'); + $class_name $this->expectedException + + setMethods + + + $this->backupStaticAttributes === null + $this->mockObjectGenerator === null + $this->name === null + $this->prophet === null + $this->runClassInSeparateProcess === null + $this->runTestInSeparateProcess === null + $this->snapshot instanceof Snapshot + '' + is_int($this->dataName) + $header - \get_class($mock) $mockObject + get_class($mock) - class-string<MockObject&RealInstanceType> MockObject&RealInstanceType + class-string<MockObject&RealInstanceType> - - null + + $args + $args + $callback + $result + $value + + + getResult + runTest + + + endTest + endTest + endTest + generateClassFromWsdl + getMock + getMock + getMock + getMock + getMock + getMockForAbstractClass + getMockForTrait + getObjectForTrait + new Differ($header) + + $beStrictAboutChangesToGlobalState null + null + null $categories + + $backupStaticAttributes + $mockObjectGenerator + $outputBufferingLevel + $outputExpectedRegex + $outputExpectedString + $prophet + $result + $runClassInSeparateProcess + $runTestInSeparateProcess + $snapshot + + + $methodProphecies + + + (bool) $this->backupStaticAttributes + + + $this instanceof PhptTestCase + + + $this->outputExpectedRegex !== null + $this->outputExpectedString !== null + $this->prophet !== null + is_string($_originalClassName) + is_string($this->dataName) + is_string($this->outputExpectedRegex) + is_string($this->outputExpectedString) + - + + $test + + + TestListener + TestListener + TestListener[] + private $listeners = []; + + + addWarning + endTest + startTest + + + $this->listeners + + + $this->topTestSuite === null + + + + $codeCoverage + $topTestSuite + + + stop + + + $linesToBeCovered + + + $_timeout + $_timeout + $e + $e + $e $isAnyCoverageRequired + + $this->codeCoverage !== null + $this->codeCoverage !== null + + + $e + Invoker + TimeoutException + + + addToAssertionCount + addToAssertionCount + doesNotPerformAssertions + doesNotPerformAssertions + getActualOutput + getName + getNumAssertions + getNumAssertions + getNumAssertions + getNumAssertions + getSize + getSize + getSize + hasOutput + runBare + $className $className - + + !is_string($theClass) && !$theClass instanceof ReflectionClass + is_string($testClass) + null === $this->backupGlobals + null === $this->backupStaticAttributes + null === $this->beStrictAboutChangesToGlobalState + + + new PhptTestCase($filename) + + + $afterClassMethod $afterClassMethod + $test + + $backupGlobals + $backupStaticAttributes + $beStrictAboutChangesToGlobalState + $iteratorFilter + + + $this->iteratorFilter !== null + is_bool($backupGlobals) + is_bool($backupStaticAttributes) + is_bool($beStrictAboutChangesToGlobalState) + null === $this->backupGlobals && is_bool($backupGlobals) + null === $this->backupStaticAttributes && is_bool($backupStaticAttributes) + null === $this->beStrictAboutChangesToGlobalState && is_bool($beStrictAboutChangesToGlobalState) + + + + + $backupGlobals + + + + + $args + + + + + doAccept + + + current + + + + + $filterMax + $filterMin + + + $accepted && isset($this->filterMax) + + + current + + + + + TestListenerAdapter + + + $lastTestWasNotSuccessful + + + private function parseIniSection($content, $ini = []): array + + + $content + $ini + + + append + $sections['FILEEOF'] @@ -190,29 +1130,56 @@ + + $carry + $left + $left + $left + $right + $right + $right + $test + $test + - \strpos($test->getName(), '::') + strpos($test->getName(), '::') + + $order === self::ORDER_DURATION && $this->cache !== null + $orderDefects === self::ORDER_DEFECTS_FIRST && $this->cache !== null + $this->cache !== null + $this->cache !== null + getName + $printerClass $suite $suite $suite - $printerClass - + + private $warnings = []; + $class->newInstance($outputStream) + + $warnings + + + doRun + handleListTests + handleListTestsXml + null|Printer|string - \strrpos($this->arguments['test'], '.') + strrpos($this->arguments['test'], '.') $suite @@ -220,56 +1187,243 @@ $suite $suite + + $testSuite !== null + + + require $file + require $loaderFile + require $printerFile + new static + + $matches + $option['desc'] $option['desc'] + + + ResultPrinter + + + $maxColumn + $numTestsWidth + ResultPrinter + ResultPrinter + + + + Printer&TestListener + + + addListener + addListener + addListener + addListener + addListener + addListener + addListener + addListener + flushListeners + + + $this->loader === null + $this->printer === null + + + $e + $e + $e + $e + $e + + + + addFilter + addFilter + addFilter + printResult + process + process + process + reorderTestsInSuite + $loader - + $whitelistFromConfigurationFile + $whitelistFromOption + + $printer + + + assert($this->printer instanceof CliTestDoxPrinter) + + + $this->printer !== null + + + require_once $extension['file'] + require_once $listener['file'] + - + + throw new SkippedTestError; + + + (string) $matches['value'][$i] + + + self::$directories === null + Invoker + + + $matches + $matches + + $extension $listener - $testSuiteNodes->item(0) $testSuiteNode + $testSuiteNodes->item(0) getAttribute getAttribute + + (string) $argument->textContent + (string) $const->getAttribute('name') + (string) $const->getAttribute('value') + (string) $directoryNode->getAttribute('group') + (string) $directoryNode->getAttribute('prefix') + (string) $directoryNode->getAttribute('prefix') + (string) $directoryNode->getAttribute('suffix') + (string) $directoryNode->getAttribute('suffix') + (string) $directoryNode->textContent + (string) $directoryNode->textContent + (string) $element->getAttribute('class') + (string) $element->getAttribute('file') + (string) $excludeNode->textContent + (string) $file->textContent + (string) $fileNode->textContent + (string) $group->textContent + (string) $group->textContent + (string) $includePath->textContent + (string) $ini->getAttribute('name') + (string) $ini->getAttribute('value') + (string) $log->getAttribute('highLowerBound') + (string) $log->getAttribute('lowUpperBound') + (string) $log->getAttribute('showOnlySummary') + (string) $log->getAttribute('showUncoveredFiles') + (string) $log->getAttribute('target') + (string) $log->getAttribute('threshold') + (string) $log->getAttribute('type') + (string) $node->getAttribute('phpVersion') + (string) $node->getAttribute('phpVersionOperator') + (string) $root->getAttribute('backupGlobals') + (string) $root->getAttribute('backupStaticAttributes') + (string) $root->getAttribute('beStrictAboutChangesToGlobalState') + (string) $root->getAttribute('beStrictAboutCoversAnnotation') + (string) $root->getAttribute('beStrictAboutOutputDuringTests') + (string) $root->getAttribute('beStrictAboutResourceUsageDuringSmallTests') + (string) $root->getAttribute('beStrictAboutTestsThatDoNotTestAnything') + (string) $root->getAttribute('beStrictAboutTodoAnnotatedTests') + (string) $root->getAttribute('bootstrap') + (string) $root->getAttribute('cacheResult') + (string) $root->getAttribute('cacheResultFile') + (string) $root->getAttribute('cacheTokens') + (string) $root->getAttribute('columns') + (string) $root->getAttribute('convertDeprecationsToExceptions') + (string) $root->getAttribute('convertErrorsToExceptions') + (string) $root->getAttribute('convertNoticesToExceptions') + (string) $root->getAttribute('convertWarningsToExceptions') + (string) $root->getAttribute('defaultTimeLimit') + (string) $root->getAttribute('disableCodeCoverageIgnore') + (string) $root->getAttribute('enforceTimeLimit') + (string) $root->getAttribute('failOnRisky') + (string) $root->getAttribute('failOnWarning') + (string) $root->getAttribute('forceCoversAnnotation') + (string) $root->getAttribute('ignoreDeprecatedCodeUnitsFromCodeCoverage') + (string) $root->getAttribute('noInteraction') + (string) $root->getAttribute('printerFile') + (string) $root->getAttribute('processIsolation') + (string) $root->getAttribute('registerMockObjectsFromTestArgumentsRecursively') + (string) $root->getAttribute('resolveDependencies') + (string) $root->getAttribute('reverseDefectList') + (string) $root->getAttribute('stderr') + (string) $root->getAttribute('stopOnDefect') + (string) $root->getAttribute('stopOnError') + (string) $root->getAttribute('stopOnFailure') + (string) $root->getAttribute('stopOnIncomplete') + (string) $root->getAttribute('stopOnRisky') + (string) $root->getAttribute('stopOnSkipped') + (string) $root->getAttribute('stopOnWarning') + (string) $root->getAttribute('testSuiteLoaderFile') + (string) $root->getAttribute('testdox') + (string) $root->getAttribute('timeoutForLargeTests') + (string) $root->getAttribute('timeoutForMediumTests') + (string) $root->getAttribute('timeoutForSmallTests') + (string) $root->getAttribute('verbose') + (string) $testSuiteNode->getAttribute('name') + (string) $var->getAttribute('name') + (string) $var->getAttribute('value') + + + assert($directoryNode instanceof DOMElement) + assert($fileNode instanceof DOMElement) + - hasAttribute getAttribute - hasAttribute getAttribute getAttribute getAttribute getAttribute + hasAttribute + hasAttribute + + $errorNumber + $errorString + + + invokeIgnoringWarnings + + + + + include_once $filename + + + + + $file + $frame + $prefix + @@ -277,25 +1431,60 @@ $i $i + + $i + 1 + + + $long_options[$i + 1] + $long_options + + $variable + $constants['user'] + + + $json + + $suite->getName() + + JUnit + + + $this->currentTestCase === null + $this->currentTestCase === null + $this->currentTestCase === null + $this->testSuiteTimes + + $type + + + Filter::getFilteredStacktrace($t) + Filter::getFilteredStacktrace($t) + parent::__construct($out) + null + + $currentTestCase + JUnit + JUnit + getName getName @@ -305,8 +1494,32 @@ $className - - getName + + TeamCity + + + $actualString === null + $expectedString === null + + + $testName + $value + + + Filter::getFilteredStacktrace($t) + + + $flowId + $startedTestName + TeamCity + TeamCity + TeamCity + TeamCity + + + $previous->getPrevious() + + getName getName getName @@ -317,18 +1530,24 @@ - $this->getException($warnings[0]) $this->getException($failures[0]) + $this->getException($warnings[0]) $exception + + $errfile + $errline + $errno + $errstr + Exception - \strrpos($key, "\0") + strrpos($key, "\0") $childResult->getCodeCoverage() @@ -337,10 +1556,29 @@ merge - setResult addToAssertionCount + setResult + + + $pipe + + + $tempFile + + + $_SERVER + + + [] + + + + + WindowsPhpProcess + + $out[1] @@ -351,52 +1589,174 @@ $out + + $out + $outTarget + + + $this->out + $this->out + $this->out + - \array_flip($lineNumbers) + array_flip($lineNumbers) + + sanitizeVersionNumber + + + forClassName + forMethod + forMethod + forMethod + requirements + requirements + + + CliTestDoxPrinter + + + \PHPUnit\Util\Filter::getFilteredStacktrace($t) + - $prefix['start'] - $prefix['message'] - $prefix['diff'] $prefix['default'] - $prefix['trace'] + $prefix['diff'] $prefix['last'] + $prefix['message'] + $prefix['start'] + $prefix['trace'] + + self::STATUS_STYLES[$result['status']]['message'] + + + CliTestDoxPrinter + CliTestDoxPrinter + CliTestDoxPrinter + CliTestDoxPrinter + + + HtmlResultPrinter + + + $name + $this->currentTestClassPrettified + + HtmlResultPrinter + HtmlResultPrinter + HtmlResultPrinter + $value + + $useColor + + + + is_string($value) + + + + + ResultPrinter + + + $name + + + $testStatus + ResultPrinter + ResultPrinter + + + TestDoxPrinter + + + $numberOfColumns + + + \PHPUnit\Util\Filter::getFilteredStacktrace($t) + + + TestDoxPrinter + TestDoxPrinter + TestDoxPrinter + TestDoxPrinter + getName + + + TextResultPrinter + + + $name + + + TextResultPrinter + TextResultPrinter + TextResultPrinter + + + + + XmlResultPrinter + + + + XmlResultPrinter + XmlResultPrinter + + $suite->getIterator() + + + ensureOperatorIsValid + + $item + + is_string($actual) + + + new $className + (new DOMDocument)->importNode($element, true) + + xmlToVariable + + DOMElement + + (string) $entry->getAttribute('key') + diff --git a/.psalm/config.xml b/.psalm/config.xml index f8db545fd8e..e21bb50705f 100644 --- a/.psalm/config.xml +++ b/.psalm/config.xml @@ -3,9 +3,13 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="https://getpsalm.org/schema/config" xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd" + resolveFromConfigFile="false" cacheDirectory=".psalm/cache" - errorBaseline=".psalm/baseline.xml" totallyTyped="false" + checkForThrowsDocblock="true" + findUnusedVariablesAndParams="false" + findUnusedCode="false" + errorBaseline=".psalm/baseline.xml" > @@ -13,43 +17,4 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/.psalm/static-analysis.xml b/.psalm/static-analysis.xml index 8d921fe9f19..0da93df020f 100644 --- a/.psalm/static-analysis.xml +++ b/.psalm/static-analysis.xml @@ -3,6 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="https://getpsalm.org/schema/config" xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd" + resolveFromConfigFile="false" totallyTyped="true" > @@ -13,39 +14,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ChangeLog-8.5.md b/ChangeLog-8.5.md index eaf36f17acd..1906aa42aae 100644 --- a/ChangeLog-8.5.md +++ b/ChangeLog-8.5.md @@ -2,10 +2,67 @@ 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.9] - 2020-MM-DD +## [8.5.16] - 2021-MM-DD + +### Changed + +* The test result cache (the storage for which is implemented in `PHPUnit\Runner\DefaultTestResultCache`) no longer uses PHP's `serialize()` and `unserialize()` function for persistence. It now uses a versioned JSON format instead that is independent of PHP implementation details (see [#3581](https://github.com/sebastianbergmann/phpunit/issues/3581) and [#4662](https://github.com/sebastianbergmann/phpunit/pull/4662) for examples why this is a problem). When PHPUnit tries to load the test result cache from a file that does not exist, or from a file that does not contain data in JSON format, or from a file that contains data in a JSON format version other than the one uses by the currently running PHPUnit version, then this is considered to be a "cache miss". An empty `DefaultTestResultCache` object is created in this case. This should also prevent PHPUnit from crashing when trying to load a test result cache file created by a different version of PHPUnit (see [#4580](https://github.com/sebastianbergmann/phpunit/issues/4580) for example). + +### Fixed + +* [#4663](https://github.com/sebastianbergmann/phpunit/issues/4663): `TestCase::expectError()` works on PHP 7.3, but not on PHP >= 7.4 + +## [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 + +* Running tests in isolated processes did not work with PHP 8 on Windows + +## [8.5.12] - 2020-11-30 + +### Changed + +* Changed PHP version constraint in `composer.json` from `^7.2` to `>=7.2` to allow the installation of PHPUnit 8.5 on PHP 8. Please note that the code coverage functionality is not available for PHPUnit 8.5 on PHP 8. + +### Fixed + +* [#4529](https://github.com/sebastianbergmann/phpunit/issues/4529): Debug mode of Xdebug 2 is not disabled for PHPT tests + +## [8.5.11] - 2020-11-27 + +### Changed + +* Bumped required version of `phpunit/php-code-coverage` + +## [8.5.10] - 2020-11-27 + +### Added + +* Support for Xdebug 3 + +### Fixed + +* [#4516](https://github.com/sebastianbergmann/phpunit/issues/4516): `phpunit/phpunit-selenium` does not work with PHPUnit 8.5.9 + +## [8.5.9] - 2020-11-10 ### Fixed +* [#3965](https://github.com/sebastianbergmann/phpunit/issues/3965): Process Isolation throws exceptions when PHPDBG is used * [#4470](https://github.com/sebastianbergmann/phpunit/pull/4470): Infinite recursion when `--static-backup --strict-global-state` is used ## [8.5.8] - 2020-06-22 @@ -83,7 +140,14 @@ 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.9]: https://github.com/sebastianbergmann/phpunit/compare/8.5.8...8.5 +[8.5.16]: https://github.com/sebastianbergmann/phpunit/compare/8.5.15...8.5 +[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 +[8.5.10]: https://github.com/sebastianbergmann/phpunit/compare/8.5.9...8.5.10 +[8.5.9]: https://github.com/sebastianbergmann/phpunit/compare/8.5.8...8.5.9 [8.5.8]: https://github.com/sebastianbergmann/phpunit/compare/8.5.7...8.5.8 [8.5.7]: https://github.com/sebastianbergmann/phpunit/compare/8.5.6...8.5.7 [8.5.6]: https://github.com/sebastianbergmann/phpunit/compare/8.5.5...8.5.6 diff --git a/LICENSE b/LICENSE index 3b0d45c9f92..0e3c9a0d586 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ PHPUnit -Copyright (c) 2001-2020, Sebastian Bergmann . +Copyright (c) 2001-2021, Sebastian Bergmann . All rights reserved. Redistribution and use in source and binary forms, with or without diff --git a/build.xml b/build.xml index 3675b1aeb23..028527645c9 100644 --- a/build.xml +++ b/build.xml @@ -445,10 +445,6 @@ - - - - diff --git a/build/templates/binary-phar-autoload.php.in b/build/templates/binary-phar-autoload.php.in index 483ee605a48..45a8fbaa935 100644 --- a/build/templates/binary-phar-autoload.php.in +++ b/build/templates/binary-phar-autoload.php.in @@ -5,7 +5,7 @@ if (version_compare('7.2.0', PHP_VERSION, '>')) { STDERR, sprintf( 'PHPUnit X.Y.Z by Sebastian Bergmann and contributors.' . PHP_EOL . PHP_EOL . - '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 diff --git a/composer.json b/composer.json index 91ac3ef7aa9..86f7b21ee88 100644 --- a/composer.json +++ b/composer.json @@ -21,7 +21,7 @@ }, "prefer-stable": true, "require": { - "php": "^7.2", + "php": ">=7.2", "ext-dom": "*", "ext-json": "*", "ext-libxml": "*", @@ -30,10 +30,10 @@ "ext-xmlwriter": "*", "doctrine/instantiator": "^1.3.1", "myclabs/deep-copy": "^1.10.0", - "phar-io/manifest": "^1.0.3", - "phar-io/version": "^2.0.1", + "phar-io/manifest": "^2.0.1", + "phar-io/version": "^3.0.2", "phpspec/prophecy": "^1.10.3", - "phpunit/php-code-coverage": "^7.0.10", + "phpunit/php-code-coverage": "^7.0.12", "phpunit/php-file-iterator": "^2.0.2", "phpunit/php-text-template": "^1.2.1", "phpunit/php-timer": "^2.1.2", diff --git a/phpunit b/phpunit index d8393f83790..be046cc9271 100755 --- a/phpunit +++ b/phpunit @@ -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 diff --git a/src/Exception.php b/src/Exception.php index 075a31596a4..4e7c33353b8 100644 --- a/src/Exception.php +++ b/src/Exception.php @@ -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 { } diff --git a/src/Framework/Assert.php b/src/Framework/Assert.php index 4b3f7c55c08..030f1a5ac46 100644 --- a/src/Framework/Assert.php +++ b/src/Framework/Assert.php @@ -9,8 +9,33 @@ */ namespace PHPUnit\Framework; +use const DEBUG_BACKTRACE_IGNORE_ARGS; +use const PHP_EOL; +use function array_key_exists; +use function array_shift; +use function array_unshift; +use function assert; +use function class_exists; +use function count; +use function debug_backtrace; +use function explode; +use function file_get_contents; +use function func_get_args; +use function implode; +use function interface_exists; +use function is_array; +use function is_bool; +use function is_int; +use function is_iterable; +use function is_object; +use function is_string; +use function preg_match; +use function preg_split; +use function sprintf; +use function strpos; use ArrayAccess; use Countable; +use DOMAttr; use DOMDocument; use DOMElement; use PHPUnit\Framework\Constraint\ArrayHasKey; @@ -58,6 +83,8 @@ use PHPUnit\Framework\Constraint\TraversableContainsOnly; use PHPUnit\Util\Type; use PHPUnit\Util\Xml; +use ReflectionClass; +use ReflectionException; use ReflectionObject; use Traversable; @@ -77,20 +104,20 @@ abstract class Assert * @param int|string $key * @param array|ArrayAccess $array * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ public static function assertArrayHasKey($key, $array, string $message = ''): void { - if (!(\is_int($key) || \is_string($key))) { + if (!(is_int($key) || is_string($key))) { throw InvalidArgumentException::create( 1, 'integer or string' ); } - if (!(\is_array($array) || $array instanceof ArrayAccess)) { + if (!(is_array($array) || $array instanceof ArrayAccess)) { throw InvalidArgumentException::create( 2, 'array or ArrayAccess' @@ -108,9 +135,9 @@ public static function assertArrayHasKey($key, $array, string $message = ''): vo * @param array|ArrayAccess $subset * @param array|ArrayAccess $array * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @codeCoverageIgnore * @@ -120,14 +147,14 @@ public static function assertArraySubset($subset, $array, bool $checkForObjectId { self::createWarning('assertArraySubset() is deprecated and will be removed in PHPUnit 9.'); - if (!(\is_array($subset) || $subset instanceof ArrayAccess)) { + if (!(is_array($subset) || $subset instanceof ArrayAccess)) { throw InvalidArgumentException::create( 1, 'array or ArrayAccess' ); } - if (!(\is_array($array) || $array instanceof ArrayAccess)) { + if (!(is_array($array) || $array instanceof ArrayAccess)) { throw InvalidArgumentException::create( 2, 'array or ArrayAccess' @@ -145,20 +172,20 @@ public static function assertArraySubset($subset, $array, bool $checkForObjectId * @param int|string $key * @param array|ArrayAccess $array * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ public static function assertArrayNotHasKey($key, $array, string $message = ''): void { - if (!(\is_int($key) || \is_string($key))) { + if (!(is_int($key) || is_string($key))) { throw InvalidArgumentException::create( 1, 'integer or string' ); } - if (!(\is_array($array) || $array instanceof ArrayAccess)) { + if (!(is_array($array) || $array instanceof ArrayAccess)) { throw InvalidArgumentException::create( 2, 'array or ArrayAccess' @@ -175,14 +202,14 @@ public static function assertArrayNotHasKey($key, $array, string $message = ''): /** * Asserts that a haystack contains a needle. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ public static function assertContains($needle, $haystack, string $message = '', bool $ignoreCase = false, bool $checkForObjectIdentity = true, bool $checkForNonObjectIdentity = false): void { // @codeCoverageIgnoreStart - if (\is_string($haystack)) { + if (is_string($haystack)) { self::createWarning('Using assertContains() with string haystacks is deprecated and will not be supported in PHPUnit 9. Refactor your test to use assertStringContainsString() or assertStringContainsStringIgnoringCase() instead.'); } @@ -199,15 +226,15 @@ public static function assertContains($needle, $haystack, string $message = '', } // @codeCoverageIgnoreEnd - if (\is_array($haystack) || - (\is_object($haystack) && $haystack instanceof Traversable)) { + if (is_array($haystack) || + (is_object($haystack) && $haystack instanceof Traversable)) { $constraint = new TraversableContains( $needle, $checkForObjectIdentity, $checkForNonObjectIdentity ); - } elseif (\is_string($haystack)) { - if (!\is_string($needle)) { + } elseif (is_string($haystack)) { + if (!is_string($needle)) { throw InvalidArgumentException::create( 1, 'string' @@ -241,9 +268,9 @@ public static function assertContainsEquals($needle, iterable $haystack, string * * @param object|string $haystackClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -265,14 +292,14 @@ public static function assertAttributeContains($needle, string $haystackAttribut /** * Asserts that a haystack does not contain a needle. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ public static function assertNotContains($needle, $haystack, string $message = '', bool $ignoreCase = false, bool $checkForObjectIdentity = true, bool $checkForNonObjectIdentity = false): void { // @codeCoverageIgnoreStart - if (\is_string($haystack)) { + if (is_string($haystack)) { self::createWarning('Using assertNotContains() with string haystacks is deprecated and will not be supported in PHPUnit 9. Refactor your test to use assertStringNotContainsString() or assertStringNotContainsStringIgnoringCase() instead.'); } @@ -289,8 +316,8 @@ public static function assertNotContains($needle, $haystack, string $message = ' } // @codeCoverageIgnoreEnd - if (\is_array($haystack) || - (\is_object($haystack) && $haystack instanceof Traversable)) { + if (is_array($haystack) || + (is_object($haystack) && $haystack instanceof Traversable)) { $constraint = new LogicalNot( new TraversableContains( $needle, @@ -298,8 +325,8 @@ public static function assertNotContains($needle, $haystack, string $message = ' $checkForNonObjectIdentity ) ); - } elseif (\is_string($haystack)) { - if (!\is_string($needle)) { + } elseif (is_string($haystack)) { + if (!is_string($needle)) { throw InvalidArgumentException::create( 1, 'string' @@ -335,9 +362,9 @@ public static function assertNotContainsEquals($needle, iterable $haystack, stri * * @param object|string $haystackClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -359,8 +386,8 @@ public static function assertAttributeNotContains($needle, string $haystackAttri /** * Asserts that a haystack contains only values of a given type. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertContainsOnly(string $type, iterable $haystack, ?bool $isNativeType = null, string $message = ''): void { @@ -381,8 +408,8 @@ public static function assertContainsOnly(string $type, iterable $haystack, ?boo /** * Asserts that a haystack contains only instances of a given class name. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertContainsOnlyInstancesOf(string $className, iterable $haystack, string $message = ''): void { @@ -403,9 +430,9 @@ public static function assertContainsOnlyInstancesOf(string $className, iterable * @param object|string $haystackClassOrObject * @param bool $isNativeType * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -425,8 +452,8 @@ public static function assertAttributeContainsOnly(string $type, string $haystac /** * Asserts that a haystack does not contain only values of a given type. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertNotContainsOnly(string $type, iterable $haystack, ?bool $isNativeType = null, string $message = ''): void { @@ -454,9 +481,9 @@ public static function assertNotContainsOnly(string $type, iterable $haystack, ? * @param object|string $haystackClassOrObject * @param bool $isNativeType * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -478,13 +505,13 @@ public static function assertAttributeNotContainsOnly(string $type, string $hays * * @param Countable|iterable $haystack * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ public static function assertCount(int $expectedCount, $haystack, string $message = ''): void { - if (!$haystack instanceof Countable && !\is_iterable($haystack)) { + if (!$haystack instanceof Countable && !is_iterable($haystack)) { throw InvalidArgumentException::create(2, 'countable or iterable'); } @@ -501,9 +528,9 @@ public static function assertCount(int $expectedCount, $haystack, string $messag * * @param object|string $haystackClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -524,13 +551,13 @@ public static function assertAttributeCount(int $expectedCount, string $haystack * * @param Countable|iterable $haystack * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ public static function assertNotCount(int $expectedCount, $haystack, string $message = ''): void { - if (!$haystack instanceof Countable && !\is_iterable($haystack)) { + if (!$haystack instanceof Countable && !is_iterable($haystack)) { throw InvalidArgumentException::create(2, 'countable or iterable'); } @@ -547,9 +574,9 @@ public static function assertNotCount(int $expectedCount, $haystack, string $mes * * @param object|string $haystackClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -568,8 +595,8 @@ public static function assertAttributeNotCount(int $expectedCount, string $hayst /** * Asserts that two variables are equal. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertEquals($expected, $actual, string $message = '', float $delta = 0.0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false): void { @@ -605,8 +632,8 @@ public static function assertEquals($expected, $actual, string $message = '', fl /** * Asserts that two variables are equal (canonicalizing). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertEqualsCanonicalizing($expected, $actual, string $message = ''): void { @@ -624,8 +651,8 @@ public static function assertEqualsCanonicalizing($expected, $actual, string $me /** * Asserts that two variables are equal (ignoring case). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertEqualsIgnoringCase($expected, $actual, string $message = ''): void { @@ -643,8 +670,8 @@ public static function assertEqualsIgnoringCase($expected, $actual, string $mess /** * Asserts that two variables are equal (with delta). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertEqualsWithDelta($expected, $actual, float $delta, string $message = ''): void { @@ -661,9 +688,9 @@ public static function assertEqualsWithDelta($expected, $actual, float $delta, s * * @param object|string $actualClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -691,8 +718,8 @@ public static function assertAttributeEquals($expected, string $actualAttributeN * @param bool $canonicalize * @param bool $ignoreCase * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertNotEquals($expected, $actual, string $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false): void { @@ -730,8 +757,8 @@ public static function assertNotEquals($expected, $actual, string $message = '', /** * Asserts that two variables are not equal (canonicalizing). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertNotEqualsCanonicalizing($expected, $actual, string $message = ''): void { @@ -751,8 +778,8 @@ public static function assertNotEqualsCanonicalizing($expected, $actual, string /** * Asserts that two variables are not equal (ignoring case). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertNotEqualsIgnoringCase($expected, $actual, string $message = ''): void { @@ -772,8 +799,8 @@ public static function assertNotEqualsIgnoringCase($expected, $actual, string $m /** * Asserts that two variables are not equal (with delta). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertNotEqualsWithDelta($expected, $actual, float $delta, string $message = ''): void { @@ -792,9 +819,9 @@ public static function assertNotEqualsWithDelta($expected, $actual, float $delta * * @param object|string $actualClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -817,8 +844,8 @@ public static function assertAttributeNotEquals($expected, string $actualAttribu /** * Asserts that a variable is empty. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert empty $actual */ @@ -833,9 +860,9 @@ public static function assertEmpty($actual, string $message = ''): void * * @param object|string $haystackClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -853,8 +880,8 @@ public static function assertAttributeEmpty(string $haystackAttributeName, $hays /** * Asserts that a variable is not empty. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !empty $actual */ @@ -869,9 +896,9 @@ public static function assertNotEmpty($actual, string $message = ''): void * * @param object|string $haystackClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -889,8 +916,8 @@ public static function assertAttributeNotEmpty(string $haystackAttributeName, $h /** * Asserts that a value is greater than another value. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertGreaterThan($expected, $actual, string $message = ''): void { @@ -902,9 +929,9 @@ public static function assertGreaterThan($expected, $actual, string $message = ' * * @param object|string $actualClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -923,8 +950,8 @@ public static function assertAttributeGreaterThan($expected, string $actualAttri /** * Asserts that a value is greater than or equal to another value. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertGreaterThanOrEqual($expected, $actual, string $message = ''): void { @@ -940,9 +967,9 @@ public static function assertGreaterThanOrEqual($expected, $actual, string $mess * * @param object|string $actualClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -961,8 +988,8 @@ public static function assertAttributeGreaterThanOrEqual($expected, string $actu /** * Asserts that a value is smaller than another value. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertLessThan($expected, $actual, string $message = ''): void { @@ -974,9 +1001,9 @@ public static function assertLessThan($expected, $actual, string $message = ''): * * @param object|string $actualClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -995,8 +1022,8 @@ public static function assertAttributeLessThan($expected, string $actualAttribut /** * Asserts that a value is smaller than or equal to another value. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertLessThanOrEqual($expected, $actual, string $message = ''): void { @@ -1008,9 +1035,9 @@ public static function assertLessThanOrEqual($expected, $actual, string $message * * @param object|string $actualClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -1030,8 +1057,8 @@ public static function assertAttributeLessThanOrEqual($expected, string $actualA * Asserts that the contents of one file is equal to the contents of another * file. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertFileEquals(string $expected, string $actual, string $message = '', bool $canonicalize = false, bool $ignoreCase = false): void { @@ -1049,22 +1076,22 @@ public static function assertFileEquals(string $expected, string $actual, string static::assertFileExists($actual, $message); $constraint = new IsEqual( - \file_get_contents($expected), + file_get_contents($expected), 0.0, 10, $canonicalize, $ignoreCase ); - static::assertThat(\file_get_contents($actual), $constraint, $message); + static::assertThat(file_get_contents($actual), $constraint, $message); } /** * Asserts that the contents of one file is equal to the contents of another * file (canonicalizing). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertFileEqualsCanonicalizing(string $expected, string $actual, string $message = ''): void { @@ -1072,21 +1099,21 @@ public static function assertFileEqualsCanonicalizing(string $expected, string $ static::assertFileExists($actual, $message); $constraint = new IsEqual( - \file_get_contents($expected), + file_get_contents($expected), 0.0, 10, true ); - static::assertThat(\file_get_contents($actual), $constraint, $message); + static::assertThat(file_get_contents($actual), $constraint, $message); } /** * Asserts that the contents of one file is equal to the contents of another * file (ignoring case). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertFileEqualsIgnoringCase(string $expected, string $actual, string $message = ''): void { @@ -1094,22 +1121,22 @@ public static function assertFileEqualsIgnoringCase(string $expected, string $ac static::assertFileExists($actual, $message); $constraint = new IsEqual( - \file_get_contents($expected), + file_get_contents($expected), 0.0, 10, false, true ); - static::assertThat(\file_get_contents($actual), $constraint, $message); + static::assertThat(file_get_contents($actual), $constraint, $message); } /** * Asserts that the contents of one file is not equal to the contents of * another file. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertFileNotEquals(string $expected, string $actual, string $message = '', bool $canonicalize = false, bool $ignoreCase = false): void { @@ -1128,7 +1155,7 @@ public static function assertFileNotEquals(string $expected, string $actual, str $constraint = new LogicalNot( new IsEqual( - \file_get_contents($expected), + file_get_contents($expected), 0.0, 10, $canonicalize, @@ -1136,15 +1163,15 @@ public static function assertFileNotEquals(string $expected, string $actual, str ) ); - static::assertThat(\file_get_contents($actual), $constraint, $message); + static::assertThat(file_get_contents($actual), $constraint, $message); } /** * Asserts that the contents of one file is not equal to the contents of another * file (canonicalizing). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertFileNotEqualsCanonicalizing(string $expected, string $actual, string $message = ''): void { @@ -1153,22 +1180,22 @@ public static function assertFileNotEqualsCanonicalizing(string $expected, strin $constraint = new LogicalNot( new IsEqual( - \file_get_contents($expected), + file_get_contents($expected), 0.0, 10, true ) ); - static::assertThat(\file_get_contents($actual), $constraint, $message); + static::assertThat(file_get_contents($actual), $constraint, $message); } /** * Asserts that the contents of one file is not equal to the contents of another * file (ignoring case). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertFileNotEqualsIgnoringCase(string $expected, string $actual, string $message = ''): void { @@ -1177,7 +1204,7 @@ public static function assertFileNotEqualsIgnoringCase(string $expected, string $constraint = new LogicalNot( new IsEqual( - \file_get_contents($expected), + file_get_contents($expected), 0.0, 10, false, @@ -1185,15 +1212,15 @@ public static function assertFileNotEqualsIgnoringCase(string $expected, string ) ); - static::assertThat(\file_get_contents($actual), $constraint, $message); + static::assertThat(file_get_contents($actual), $constraint, $message); } /** * Asserts that the contents of a string is equal * to the contents of a file. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertStringEqualsFile(string $expectedFile, string $actualString, string $message = '', bool $canonicalize = false, bool $ignoreCase = false): void { @@ -1210,7 +1237,7 @@ public static function assertStringEqualsFile(string $expectedFile, string $actu static::assertFileExists($expectedFile, $message); $constraint = new IsEqual( - \file_get_contents($expectedFile), + file_get_contents($expectedFile), 0.0, 10, $canonicalize, @@ -1224,15 +1251,15 @@ public static function assertStringEqualsFile(string $expectedFile, string $actu * Asserts that the contents of a string is equal * to the contents of a file (canonicalizing). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertStringEqualsFileCanonicalizing(string $expectedFile, string $actualString, string $message = ''): void { static::assertFileExists($expectedFile, $message); $constraint = new IsEqual( - \file_get_contents($expectedFile), + file_get_contents($expectedFile), 0.0, 10, true @@ -1245,15 +1272,15 @@ public static function assertStringEqualsFileCanonicalizing(string $expectedFile * Asserts that the contents of a string is equal * to the contents of a file (ignoring case). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertStringEqualsFileIgnoringCase(string $expectedFile, string $actualString, string $message = ''): void { static::assertFileExists($expectedFile, $message); $constraint = new IsEqual( - \file_get_contents($expectedFile), + file_get_contents($expectedFile), 0.0, 10, false, @@ -1267,8 +1294,8 @@ public static function assertStringEqualsFileIgnoringCase(string $expectedFile, * Asserts that the contents of a string is not equal * to the contents of a file. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertStringNotEqualsFile(string $expectedFile, string $actualString, string $message = '', bool $canonicalize = false, bool $ignoreCase = false): void { @@ -1286,7 +1313,7 @@ public static function assertStringNotEqualsFile(string $expectedFile, string $a $constraint = new LogicalNot( new IsEqual( - \file_get_contents($expectedFile), + file_get_contents($expectedFile), 0.0, 10, $canonicalize, @@ -1301,8 +1328,8 @@ public static function assertStringNotEqualsFile(string $expectedFile, string $a * Asserts that the contents of a string is not equal * to the contents of a file (canonicalizing). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertStringNotEqualsFileCanonicalizing(string $expectedFile, string $actualString, string $message = ''): void { @@ -1310,7 +1337,7 @@ public static function assertStringNotEqualsFileCanonicalizing(string $expectedF $constraint = new LogicalNot( new IsEqual( - \file_get_contents($expectedFile), + file_get_contents($expectedFile), 0.0, 10, true @@ -1324,8 +1351,8 @@ public static function assertStringNotEqualsFileCanonicalizing(string $expectedF * Asserts that the contents of a string is not equal * to the contents of a file (ignoring case). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertStringNotEqualsFileIgnoringCase(string $expectedFile, string $actualString, string $message = ''): void { @@ -1333,7 +1360,7 @@ public static function assertStringNotEqualsFileIgnoringCase(string $expectedFil $constraint = new LogicalNot( new IsEqual( - \file_get_contents($expectedFile), + file_get_contents($expectedFile), 0.0, 10, false, @@ -1347,8 +1374,8 @@ public static function assertStringNotEqualsFileIgnoringCase(string $expectedFil /** * Asserts that a file/dir is readable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertIsReadable(string $filename, string $message = ''): void { @@ -1358,8 +1385,8 @@ public static function assertIsReadable(string $filename, string $message = ''): /** * Asserts that a file/dir exists and is not readable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertNotIsReadable(string $filename, string $message = ''): void { @@ -1369,8 +1396,8 @@ public static function assertNotIsReadable(string $filename, string $message = ' /** * Asserts that a file/dir exists and is writable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertIsWritable(string $filename, string $message = ''): void { @@ -1380,8 +1407,8 @@ public static function assertIsWritable(string $filename, string $message = ''): /** * Asserts that a file/dir exists and is not writable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertNotIsWritable(string $filename, string $message = ''): void { @@ -1391,8 +1418,8 @@ public static function assertNotIsWritable(string $filename, string $message = ' /** * Asserts that a directory exists. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertDirectoryExists(string $directory, string $message = ''): void { @@ -1402,8 +1429,8 @@ public static function assertDirectoryExists(string $directory, string $message /** * Asserts that a directory does not exist. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertDirectoryNotExists(string $directory, string $message = ''): void { @@ -1413,8 +1440,8 @@ public static function assertDirectoryNotExists(string $directory, string $messa /** * Asserts that a directory exists and is readable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertDirectoryIsReadable(string $directory, string $message = ''): void { @@ -1425,8 +1452,8 @@ public static function assertDirectoryIsReadable(string $directory, string $mess /** * Asserts that a directory exists and is not readable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertDirectoryNotIsReadable(string $directory, string $message = ''): void { @@ -1437,8 +1464,8 @@ public static function assertDirectoryNotIsReadable(string $directory, string $m /** * Asserts that a directory exists and is writable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertDirectoryIsWritable(string $directory, string $message = ''): void { @@ -1449,8 +1476,8 @@ public static function assertDirectoryIsWritable(string $directory, string $mess /** * Asserts that a directory exists and is not writable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertDirectoryNotIsWritable(string $directory, string $message = ''): void { @@ -1461,8 +1488,8 @@ public static function assertDirectoryNotIsWritable(string $directory, string $m /** * Asserts that a file exists. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertFileExists(string $filename, string $message = ''): void { @@ -1472,8 +1499,8 @@ public static function assertFileExists(string $filename, string $message = ''): /** * Asserts that a file does not exist. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertFileNotExists(string $filename, string $message = ''): void { @@ -1483,8 +1510,8 @@ public static function assertFileNotExists(string $filename, string $message = ' /** * Asserts that a file exists and is readable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertFileIsReadable(string $file, string $message = ''): void { @@ -1495,8 +1522,8 @@ public static function assertFileIsReadable(string $file, string $message = ''): /** * Asserts that a file exists and is not readable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertFileNotIsReadable(string $file, string $message = ''): void { @@ -1507,8 +1534,8 @@ public static function assertFileNotIsReadable(string $file, string $message = ' /** * Asserts that a file exists and is writable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertFileIsWritable(string $file, string $message = ''): void { @@ -1519,8 +1546,8 @@ public static function assertFileIsWritable(string $file, string $message = ''): /** * Asserts that a file exists and is not writable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertFileNotIsWritable(string $file, string $message = ''): void { @@ -1531,8 +1558,8 @@ public static function assertFileNotIsWritable(string $file, string $message = ' /** * Asserts that a condition is true. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert true $condition */ @@ -1544,8 +1571,8 @@ public static function assertTrue($condition, string $message = ''): void /** * Asserts that a condition is not true. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !true $condition */ @@ -1557,8 +1584,8 @@ public static function assertNotTrue($condition, string $message = ''): void /** * Asserts that a condition is false. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert false $condition */ @@ -1570,8 +1597,8 @@ public static function assertFalse($condition, string $message = ''): void /** * Asserts that a condition is not false. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !false $condition */ @@ -1583,8 +1610,8 @@ public static function assertNotFalse($condition, string $message = ''): void /** * Asserts that a variable is null. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert null $actual */ @@ -1596,8 +1623,8 @@ public static function assertNull($actual, string $message = ''): void /** * Asserts that a variable is not null. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !null $actual */ @@ -1609,8 +1636,8 @@ public static function assertNotNull($actual, string $message = ''): void /** * Asserts that a variable is finite. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertFinite($actual, string $message = ''): void { @@ -1620,8 +1647,8 @@ public static function assertFinite($actual, string $message = ''): void /** * Asserts that a variable is infinite. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertInfinite($actual, string $message = ''): void { @@ -1631,8 +1658,8 @@ public static function assertInfinite($actual, string $message = ''): void /** * Asserts that a variable is nan. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertNan($actual, string $message = ''): void { @@ -1642,9 +1669,9 @@ public static function assertNan($actual, string $message = ''): void /** * Asserts that a class has a specified attribute. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ public static function assertClassHasAttribute(string $attributeName, string $className, string $message = ''): void { @@ -1652,7 +1679,7 @@ public static function assertClassHasAttribute(string $attributeName, string $cl throw InvalidArgumentException::create(1, 'valid attribute name'); } - if (!\class_exists($className)) { + if (!class_exists($className)) { throw InvalidArgumentException::create(2, 'class name'); } @@ -1662,9 +1689,9 @@ public static function assertClassHasAttribute(string $attributeName, string $cl /** * Asserts that a class does not have a specified attribute. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ public static function assertClassNotHasAttribute(string $attributeName, string $className, string $message = ''): void { @@ -1672,7 +1699,7 @@ public static function assertClassNotHasAttribute(string $attributeName, string throw InvalidArgumentException::create(1, 'valid attribute name'); } - if (!\class_exists($className)) { + if (!class_exists($className)) { throw InvalidArgumentException::create(2, 'class name'); } @@ -1688,9 +1715,9 @@ public static function assertClassNotHasAttribute(string $attributeName, string /** * Asserts that a class has a specified static attribute. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ public static function assertClassHasStaticAttribute(string $attributeName, string $className, string $message = ''): void { @@ -1698,7 +1725,7 @@ public static function assertClassHasStaticAttribute(string $attributeName, stri throw InvalidArgumentException::create(1, 'valid attribute name'); } - if (!\class_exists($className)) { + if (!class_exists($className)) { throw InvalidArgumentException::create(2, 'class name'); } @@ -1712,9 +1739,9 @@ public static function assertClassHasStaticAttribute(string $attributeName, stri /** * Asserts that a class does not have a specified static attribute. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ public static function assertClassNotHasStaticAttribute(string $attributeName, string $className, string $message = ''): void { @@ -1722,7 +1749,7 @@ public static function assertClassNotHasStaticAttribute(string $attributeName, s throw InvalidArgumentException::create(1, 'valid attribute name'); } - if (!\class_exists($className)) { + if (!class_exists($className)) { throw InvalidArgumentException::create(2, 'class name'); } @@ -1740,9 +1767,9 @@ public static function assertClassNotHasStaticAttribute(string $attributeName, s * * @param object $object * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ public static function assertObjectHasAttribute(string $attributeName, $object, string $message = ''): void { @@ -1750,7 +1777,7 @@ public static function assertObjectHasAttribute(string $attributeName, $object, throw InvalidArgumentException::create(1, 'valid attribute name'); } - if (!\is_object($object)) { + if (!is_object($object)) { throw InvalidArgumentException::create(2, 'object'); } @@ -1766,9 +1793,9 @@ public static function assertObjectHasAttribute(string $attributeName, $object, * * @param object $object * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ public static function assertObjectNotHasAttribute(string $attributeName, $object, string $message = ''): void { @@ -1776,7 +1803,7 @@ public static function assertObjectNotHasAttribute(string $attributeName, $objec throw InvalidArgumentException::create(1, 'valid attribute name'); } - if (!\is_object($object)) { + if (!is_object($object)) { throw InvalidArgumentException::create(2, 'object'); } @@ -1794,8 +1821,8 @@ public static function assertObjectNotHasAttribute(string $attributeName, $objec * Used on objects, it asserts that two variables reference * the same object. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-template ExpectedType * @psalm-param ExpectedType $expected @@ -1816,9 +1843,9 @@ public static function assertSame($expected, $actual, string $message = ''): voi * * @param object|string $actualClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -1839,12 +1866,12 @@ public static function assertAttributeSame($expected, string $actualAttributeNam * Used on objects, it asserts that two variables do not reference * the same object. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertNotSame($expected, $actual, string $message = ''): void { - if (\is_bool($expected) && \is_bool($actual)) { + if (is_bool($expected) && is_bool($actual)) { static::assertNotEquals($expected, $actual, $message); } @@ -1863,9 +1890,9 @@ public static function assertNotSame($expected, $actual, string $message = ''): * * @param object|string $actualClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -1884,17 +1911,17 @@ public static function assertAttributeNotSame($expected, string $actualAttribute /** * Asserts that a variable is of a given type. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @psalm-template ExpectedType of object * @psalm-param class-string $expected - * @psalm-assert ExpectedType $actual + * @psalm-assert =ExpectedType $actual */ public static function assertInstanceOf(string $expected, $actual, string $message = ''): void { - if (!\class_exists($expected) && !\interface_exists($expected)) { + if (!class_exists($expected) && !interface_exists($expected)) { throw InvalidArgumentException::create(1, 'class or interface name'); } @@ -1910,9 +1937,9 @@ public static function assertInstanceOf(string $expected, $actual, string $messa * * @param object|string $classOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -1933,9 +1960,9 @@ public static function assertAttributeInstanceOf(string $expected, string $attri /** * Asserts that a variable is not of a given type. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @psalm-template ExpectedType of object * @psalm-param class-string $expected @@ -1943,7 +1970,7 @@ public static function assertAttributeInstanceOf(string $expected, string $attri */ public static function assertNotInstanceOf(string $expected, $actual, string $message = ''): void { - if (!\class_exists($expected) && !\interface_exists($expected)) { + if (!class_exists($expected) && !interface_exists($expected)) { throw InvalidArgumentException::create(1, 'class or interface name'); } @@ -1961,9 +1988,9 @@ public static function assertNotInstanceOf(string $expected, $actual, string $me * * @param object|string $classOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -1984,15 +2011,20 @@ public static function assertAttributeNotInstanceOf(string $expected, string $at /** * Asserts that a variable is of a given type. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3369 * @codeCoverageIgnore */ public static function assertInternalType(string $expected, $actual, string $message = ''): void { - self::createWarning('assertInternalType() is deprecated and will be removed in PHPUnit 9. Refactor your test to use assertIsArray(), assertIsBool(), assertIsFloat(), assertIsInt(), assertIsNumeric(), assertIsObject(), assertIsResource(), assertIsString(), assertIsScalar(), assertIsCallable(), or assertIsIterable() instead.'); + self::createWarning( + sprintf( + 'assertInternalType() is deprecated and will be removed in PHPUnit 9. Refactor your test to use %s() instead.', + self::assertInternalTypeReplacement($expected, false) + ) + ); static::assertThat( $actual, @@ -2006,9 +2038,9 @@ public static function assertInternalType(string $expected, $actual, string $mes * * @param object|string $classOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -2027,8 +2059,8 @@ public static function assertAttributeInternalType(string $expected, string $att /** * Asserts that a variable is of type array. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert array $actual */ @@ -2044,8 +2076,8 @@ public static function assertIsArray($actual, string $message = ''): void /** * Asserts that a variable is of type bool. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert bool $actual */ @@ -2061,8 +2093,8 @@ public static function assertIsBool($actual, string $message = ''): void /** * Asserts that a variable is of type float. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert float $actual */ @@ -2078,8 +2110,8 @@ public static function assertIsFloat($actual, string $message = ''): void /** * Asserts that a variable is of type int. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert int $actual */ @@ -2095,8 +2127,8 @@ public static function assertIsInt($actual, string $message = ''): void /** * Asserts that a variable is of type numeric. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert numeric $actual */ @@ -2112,8 +2144,8 @@ public static function assertIsNumeric($actual, string $message = ''): void /** * Asserts that a variable is of type object. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert object $actual */ @@ -2129,8 +2161,8 @@ public static function assertIsObject($actual, string $message = ''): void /** * Asserts that a variable is of type resource. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert resource $actual */ @@ -2146,8 +2178,8 @@ public static function assertIsResource($actual, string $message = ''): void /** * Asserts that a variable is of type string. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert string $actual */ @@ -2163,8 +2195,8 @@ public static function assertIsString($actual, string $message = ''): void /** * Asserts that a variable is of type scalar. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert scalar $actual */ @@ -2180,8 +2212,8 @@ public static function assertIsScalar($actual, string $message = ''): void /** * Asserts that a variable is of type callable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert callable $actual */ @@ -2197,8 +2229,8 @@ public static function assertIsCallable($actual, string $message = ''): void /** * Asserts that a variable is of type iterable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert iterable $actual */ @@ -2214,15 +2246,20 @@ public static function assertIsIterable($actual, string $message = ''): void /** * Asserts that a variable is not of a given type. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3369 * @codeCoverageIgnore */ public static function assertNotInternalType(string $expected, $actual, string $message = ''): void { - self::createWarning('assertNotInternalType() is deprecated and will be removed in PHPUnit 9. Refactor your test to use assertIsNotArray(), assertIsNotBool(), assertIsNotFloat(), assertIsNotInt(), assertIsNotNumeric(), assertIsNotObject(), assertIsNotResource(), assertIsNotString(), assertIsNotScalar(), assertIsNotCallable(), or assertIsNotIterable() instead.'); + self::createWarning( + sprintf( + 'assertNotInternalType() is deprecated and will be removed in PHPUnit 9. Refactor your test to use %s() instead.', + self::assertInternalTypeReplacement($expected, true) + ) + ); static::assertThat( $actual, @@ -2236,8 +2273,8 @@ public static function assertNotInternalType(string $expected, $actual, string $ /** * Asserts that a variable is not of type array. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !array $actual */ @@ -2253,8 +2290,8 @@ public static function assertIsNotArray($actual, string $message = ''): void /** * Asserts that a variable is not of type bool. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !bool $actual */ @@ -2270,8 +2307,8 @@ public static function assertIsNotBool($actual, string $message = ''): void /** * Asserts that a variable is not of type float. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !float $actual */ @@ -2287,8 +2324,8 @@ public static function assertIsNotFloat($actual, string $message = ''): void /** * Asserts that a variable is not of type int. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !int $actual */ @@ -2304,8 +2341,8 @@ public static function assertIsNotInt($actual, string $message = ''): void /** * Asserts that a variable is not of type numeric. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !numeric $actual */ @@ -2321,8 +2358,8 @@ public static function assertIsNotNumeric($actual, string $message = ''): void /** * Asserts that a variable is not of type object. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !object $actual */ @@ -2338,8 +2375,8 @@ public static function assertIsNotObject($actual, string $message = ''): void /** * Asserts that a variable is not of type resource. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !resource $actual */ @@ -2355,8 +2392,8 @@ public static function assertIsNotResource($actual, string $message = ''): void /** * Asserts that a variable is not of type string. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !string $actual */ @@ -2372,8 +2409,8 @@ public static function assertIsNotString($actual, string $message = ''): void /** * Asserts that a variable is not of type scalar. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !scalar $actual */ @@ -2389,8 +2426,8 @@ public static function assertIsNotScalar($actual, string $message = ''): void /** * Asserts that a variable is not of type callable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !callable $actual */ @@ -2406,8 +2443,8 @@ public static function assertIsNotCallable($actual, string $message = ''): void /** * Asserts that a variable is not of type iterable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !iterable $actual */ @@ -2425,9 +2462,9 @@ public static function assertIsNotIterable($actual, string $message = ''): void * * @param object|string $classOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -2446,8 +2483,8 @@ public static function assertAttributeNotInternalType(string $expected, string $ /** * Asserts that a string matches a given regular expression. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertRegExp(string $pattern, string $string, string $message = ''): void { @@ -2457,8 +2494,8 @@ public static function assertRegExp(string $pattern, string $string, string $mes /** * Asserts that a string does not match a given regular expression. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertNotRegExp(string $pattern, string $string, string $message = ''): void { @@ -2478,17 +2515,17 @@ public static function assertNotRegExp(string $pattern, string $string, string $ * @param Countable|iterable $expected * @param Countable|iterable $actual * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ public static function assertSameSize($expected, $actual, string $message = ''): void { - if (!$expected instanceof Countable && !\is_iterable($expected)) { + if (!$expected instanceof Countable && !is_iterable($expected)) { throw InvalidArgumentException::create(1, 'countable or iterable'); } - if (!$actual instanceof Countable && !\is_iterable($actual)) { + if (!$actual instanceof Countable && !is_iterable($actual)) { throw InvalidArgumentException::create(2, 'countable or iterable'); } @@ -2506,17 +2543,17 @@ public static function assertSameSize($expected, $actual, string $message = ''): * @param Countable|iterable $expected * @param Countable|iterable $actual * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ public static function assertNotSameSize($expected, $actual, string $message = ''): void { - if (!$expected instanceof Countable && !\is_iterable($expected)) { + if (!$expected instanceof Countable && !is_iterable($expected)) { throw InvalidArgumentException::create(1, 'countable or iterable'); } - if (!$actual instanceof Countable && !\is_iterable($actual)) { + if (!$actual instanceof Countable && !is_iterable($actual)) { throw InvalidArgumentException::create(2, 'countable or iterable'); } @@ -2532,8 +2569,8 @@ public static function assertNotSameSize($expected, $actual, string $message = ' /** * Asserts that a string matches a given format string. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertStringMatchesFormat(string $format, string $string, string $message = ''): void { @@ -2543,8 +2580,8 @@ public static function assertStringMatchesFormat(string $format, string $string, /** * Asserts that a string does not match a given format string. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertStringNotMatchesFormat(string $format, string $string, string $message = ''): void { @@ -2560,8 +2597,8 @@ public static function assertStringNotMatchesFormat(string $format, string $stri /** * Asserts that a string matches a given format file. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertStringMatchesFormatFile(string $formatFile, string $string, string $message = ''): void { @@ -2570,7 +2607,7 @@ public static function assertStringMatchesFormatFile(string $formatFile, string static::assertThat( $string, new StringMatchesFormatDescription( - \file_get_contents($formatFile) + file_get_contents($formatFile) ), $message ); @@ -2579,8 +2616,8 @@ public static function assertStringMatchesFormatFile(string $formatFile, string /** * Asserts that a string does not match a given format string. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertStringNotMatchesFormatFile(string $formatFile, string $string, string $message = ''): void { @@ -2590,7 +2627,7 @@ public static function assertStringNotMatchesFormatFile(string $formatFile, stri $string, new LogicalNot( new StringMatchesFormatDescription( - \file_get_contents($formatFile) + file_get_contents($formatFile) ) ), $message @@ -2600,8 +2637,8 @@ public static function assertStringNotMatchesFormatFile(string $formatFile, stri /** * Asserts that a string starts with a given prefix. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertStringStartsWith(string $prefix, string $string, string $message = ''): void { @@ -2614,8 +2651,8 @@ public static function assertStringStartsWith(string $prefix, string $string, st * @param string $prefix * @param string $string * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertStringStartsNotWith($prefix, $string, string $message = ''): void { @@ -2629,8 +2666,8 @@ public static function assertStringStartsNotWith($prefix, $string, string $messa } /** - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertStringContainsString(string $needle, string $haystack, string $message = ''): void { @@ -2640,8 +2677,8 @@ public static function assertStringContainsString(string $needle, string $haysta } /** - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertStringContainsStringIgnoringCase(string $needle, string $haystack, string $message = ''): void { @@ -2651,8 +2688,8 @@ public static function assertStringContainsStringIgnoringCase(string $needle, st } /** - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertStringNotContainsString(string $needle, string $haystack, string $message = ''): void { @@ -2662,8 +2699,8 @@ public static function assertStringNotContainsString(string $needle, string $hay } /** - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertStringNotContainsStringIgnoringCase(string $needle, string $haystack, string $message = ''): void { @@ -2675,8 +2712,8 @@ public static function assertStringNotContainsStringIgnoringCase(string $needle, /** * Asserts that a string ends with a given suffix. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertStringEndsWith(string $suffix, string $string, string $message = ''): void { @@ -2686,8 +2723,8 @@ public static function assertStringEndsWith(string $suffix, string $string, stri /** * Asserts that a string ends not with a given suffix. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertStringEndsNotWith(string $suffix, string $string, string $message = ''): void { @@ -2703,9 +2740,9 @@ public static function assertStringEndsNotWith(string $suffix, string $string, s /** * Asserts that two XML files are equal. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ public static function assertXmlFileEqualsXmlFile(string $expectedFile, string $actualFile, string $message = ''): void { @@ -2718,9 +2755,9 @@ public static function assertXmlFileEqualsXmlFile(string $expectedFile, string $ /** * Asserts that two XML files are not equal. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ public static function assertXmlFileNotEqualsXmlFile(string $expectedFile, string $actualFile, string $message = ''): void { @@ -2735,9 +2772,9 @@ public static function assertXmlFileNotEqualsXmlFile(string $expectedFile, strin * * @param DOMDocument|string $actualXml * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ public static function assertXmlStringEqualsXmlFile(string $expectedFile, $actualXml, string $message = ''): void { @@ -2752,9 +2789,9 @@ public static function assertXmlStringEqualsXmlFile(string $expectedFile, $actua * * @param DOMDocument|string $actualXml * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ public static function assertXmlStringNotEqualsXmlFile(string $expectedFile, $actualXml, string $message = ''): void { @@ -2770,9 +2807,9 @@ public static function assertXmlStringNotEqualsXmlFile(string $expectedFile, $ac * @param DOMDocument|string $expectedXml * @param DOMDocument|string $actualXml * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ public static function assertXmlStringEqualsXmlString($expectedXml, $actualXml, string $message = ''): void { @@ -2788,9 +2825,9 @@ public static function assertXmlStringEqualsXmlString($expectedXml, $actualXml, * @param DOMDocument|string $expectedXml * @param DOMDocument|string $actualXml * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ public static function assertXmlStringNotEqualsXmlString($expectedXml, $actualXml, string $message = ''): void { @@ -2803,9 +2840,9 @@ public static function assertXmlStringNotEqualsXmlString($expectedXml, $actualXm /** * Asserts that a hierarchy of DOMElements matches. * + * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws AssertionFailedError * @throws ExpectationFailedException - * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ public static function assertEqualXMLStructure(DOMElement $expectedElement, DOMElement $actualElement, bool $checkAttributes = false, string $message = ''): void { @@ -2822,7 +2859,7 @@ public static function assertEqualXMLStructure(DOMElement $expectedElement, DOME static::assertSame( $expectedElement->attributes->length, $actualElement->attributes->length, - \sprintf( + sprintf( '%s%sNumber of attributes on node "%s" does not match', $message, !empty($message) ? "\n" : '', @@ -2834,11 +2871,11 @@ public static function assertEqualXMLStructure(DOMElement $expectedElement, DOME $expectedAttribute = $expectedElement->attributes->item($i); $actualAttribute = $actualElement->attributes->getNamedItem($expectedAttribute->name); - \assert($expectedAttribute instanceof \DOMAttr); + assert($expectedAttribute instanceof DOMAttr); if (!$actualAttribute) { static::fail( - \sprintf( + sprintf( '%s%sCould not find attribute "%s" on node "%s"', $message, !empty($message) ? "\n" : '', @@ -2856,7 +2893,7 @@ public static function assertEqualXMLStructure(DOMElement $expectedElement, DOME static::assertSame( $expectedElement->childNodes->length, $actualElement->childNodes->length, - \sprintf( + sprintf( '%s%sNumber of child nodes of "%s" differs', $message, !empty($message) ? "\n" : '', @@ -2877,12 +2914,12 @@ public static function assertEqualXMLStructure(DOMElement $expectedElement, DOME /** * Evaluates a PHPUnit\Framework\Constraint matcher object. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertThat($value, Constraint $constraint, string $message = ''): void { - self::$count += \count($constraint); + self::$count += count($constraint); $constraint->evaluate($value, $message); } @@ -2890,8 +2927,8 @@ public static function assertThat($value, Constraint $constraint, string $messag /** * Asserts that a string is a valid JSON string. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertJson(string $actualJson, string $message = ''): void { @@ -2901,8 +2938,8 @@ public static function assertJson(string $actualJson, string $message = ''): voi /** * Asserts that two given JSON encoded objects or arrays are equal. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertJsonStringEqualsJsonString(string $expectedJson, string $actualJson, string $message = ''): void { @@ -2918,8 +2955,8 @@ public static function assertJsonStringEqualsJsonString(string $expectedJson, st * @param string $expectedJson * @param string $actualJson * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertJsonStringNotEqualsJsonString($expectedJson, $actualJson, string $message = ''): void { @@ -2938,13 +2975,13 @@ public static function assertJsonStringNotEqualsJsonString($expectedJson, $actua /** * Asserts that the generated JSON encoded object and the content of the given file are equal. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertJsonStringEqualsJsonFile(string $expectedFile, string $actualJson, string $message = ''): void { static::assertFileExists($expectedFile, $message); - $expectedJson = \file_get_contents($expectedFile); + $expectedJson = file_get_contents($expectedFile); static::assertJson($expectedJson, $message); static::assertJson($actualJson, $message); @@ -2955,13 +2992,13 @@ public static function assertJsonStringEqualsJsonFile(string $expectedFile, stri /** * Asserts that the generated JSON encoded object and the content of the given file are not equal. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertJsonStringNotEqualsJsonFile(string $expectedFile, string $actualJson, string $message = ''): void { static::assertFileExists($expectedFile, $message); - $expectedJson = \file_get_contents($expectedFile); + $expectedJson = file_get_contents($expectedFile); static::assertJson($expectedJson, $message); static::assertJson($actualJson, $message); @@ -2978,16 +3015,16 @@ public static function assertJsonStringNotEqualsJsonFile(string $expectedFile, s /** * Asserts that two JSON files are equal. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertJsonFileEqualsJsonFile(string $expectedFile, string $actualFile, string $message = ''): void { static::assertFileExists($expectedFile, $message); static::assertFileExists($actualFile, $message); - $actualJson = \file_get_contents($actualFile); - $expectedJson = \file_get_contents($expectedFile); + $actualJson = file_get_contents($actualFile); + $expectedJson = file_get_contents($expectedFile); static::assertJson($expectedJson, $message); static::assertJson($actualJson, $message); @@ -3005,16 +3042,16 @@ public static function assertJsonFileEqualsJsonFile(string $expectedFile, string /** * Asserts that two JSON files are not equal. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public static function assertJsonFileNotEqualsJsonFile(string $expectedFile, string $actualFile, string $message = ''): void { static::assertFileExists($expectedFile, $message); static::assertFileExists($actualFile, $message); - $actualJson = \file_get_contents($actualFile); - $expectedJson = \file_get_contents($expectedFile); + $actualJson = file_get_contents($actualFile); + $expectedJson = file_get_contents($expectedFile); static::assertJson($expectedJson, $message); static::assertJson($actualJson, $message); @@ -3034,7 +3071,7 @@ public static function assertJsonFileNotEqualsJsonFile(string $expectedFile, str */ public static function logicalAnd(): LogicalAnd { - $constraints = \func_get_args(); + $constraints = func_get_args(); $constraint = new LogicalAnd; $constraint->setConstraints($constraints); @@ -3044,7 +3081,7 @@ public static function logicalAnd(): LogicalAnd public static function logicalOr(): LogicalOr { - $constraints = \func_get_args(); + $constraints = func_get_args(); $constraint = new LogicalOr; $constraint->setConstraints($constraints); @@ -3059,7 +3096,7 @@ public static function logicalNot(Constraint $constraint): LogicalNot public static function logicalXor(): LogicalXor { - $constraints = \func_get_args(); + $constraints = func_get_args(); $constraint = new LogicalXor; $constraint->setConstraints($constraints); @@ -3077,6 +3114,13 @@ public static function isTrue(): IsTrue return new IsTrue; } + /** + * @psalm-template CallbackInput of mixed + * + * @psalm-param callable(CallbackInput $callback): bool $callback + * + * @psalm-return Callback + */ public static function callback(callable $callback): Callback { return new Callback($callback); @@ -3328,8 +3372,8 @@ public static function readAttribute($classOrObject, string $attributeName) throw InvalidArgumentException::create(2, 'valid attribute name'); } - if (\is_string($classOrObject)) { - if (!\class_exists($classOrObject)) { + if (is_string($classOrObject)) { + if (!class_exists($classOrObject)) { throw InvalidArgumentException::create( 1, 'class name' @@ -3342,7 +3386,7 @@ public static function readAttribute($classOrObject, string $attributeName) ); } - if (\is_object($classOrObject)) { + if (is_object($classOrObject)) { return static::getObjectAttribute( $classOrObject, $attributeName @@ -3368,7 +3412,7 @@ public static function getStaticAttribute(string $className, string $attributeNa { self::createWarning('getStaticAttribute() is deprecated and will be removed in PHPUnit 9.'); - if (!\class_exists($className)) { + if (!class_exists($className)) { throw InvalidArgumentException::create(1, 'class name'); } @@ -3377,9 +3421,9 @@ public static function getStaticAttribute(string $className, string $attributeNa } try { - $class = new \ReflectionClass($className); + $class = new ReflectionClass($className); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -3391,7 +3435,7 @@ public static function getStaticAttribute(string $className, string $attributeNa while ($class) { $attributes = $class->getStaticProperties(); - if (\array_key_exists($attributeName, $attributes)) { + if (array_key_exists($attributeName, $attributes)) { return $attributes[$attributeName]; } @@ -3399,7 +3443,7 @@ public static function getStaticAttribute(string $className, string $attributeNa } throw new Exception( - \sprintf( + sprintf( 'Attribute "%s" not found in class.', $attributeName ) @@ -3421,7 +3465,7 @@ public static function getObjectAttribute($object, string $attributeName) { self::createWarning('getObjectAttribute() is deprecated and will be removed in PHPUnit 9.'); - if (!\is_object($object)) { + if (!is_object($object)) { throw InvalidArgumentException::create(1, 'object'); } @@ -3444,12 +3488,12 @@ public static function getObjectAttribute($object, string $attributeName) $attribute->setAccessible(false); return $value; - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { } } while ($reflector = $reflector->getParentClass()); throw new Exception( - \sprintf( + sprintf( 'Attribute "%s" not found in object.', $attributeName ) @@ -3479,8 +3523,8 @@ public static function markTestIncomplete(string $message = ''): void public static function markTestSkipped(string $message = ''): void { if ($hint = self::detectLocationHint($message)) { - $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS); - \array_unshift($trace, $hint); + $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); + array_unshift($trace, $hint); throw new SyntheticSkippedError($hint['message'], 0, $hint['file'], (int) $hint['line'], $trace); } @@ -3507,10 +3551,10 @@ public static function resetCount(): void private static function detectLocationHint(string $message): ?array { $hint = null; - $lines = \preg_split('/\r\n|\r|\n/', $message); + $lines = preg_split('/\r\n|\r|\n/', $message); - while (\strpos($lines[0], '__OFFSET') !== false) { - $offset = \explode('=', \array_shift($lines)); + while (strpos($lines[0], '__OFFSET') !== false) { + $offset = explode('=', array_shift($lines)); if ($offset[0] === '__OFFSET_FILE') { $hint['file'] = $offset[1]; @@ -3522,7 +3566,7 @@ private static function detectLocationHint(string $message): ?array } if ($hint) { - $hint['message'] = \implode(\PHP_EOL, $lines); + $hint['message'] = implode(PHP_EOL, $lines); } return $hint; @@ -3530,12 +3574,12 @@ private static function detectLocationHint(string $message): ?array private static function isValidObjectAttributeName(string $attributeName): bool { - return (bool) \preg_match('/[^\x00-\x1f\x7f-\x9f]+/', $attributeName); + return (bool) preg_match('/[^\x00-\x1f\x7f-\x9f]+/', $attributeName); } private static function isValidClassAttributeName(string $attributeName): bool { - return (bool) \preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $attributeName); + return (bool) preg_match('/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $attributeName); } /** @@ -3543,9 +3587,9 @@ private static function isValidClassAttributeName(string $attributeName): bool */ private static function createWarning(string $warning): void { - foreach (\debug_backtrace() as $step) { + foreach (debug_backtrace() as $step) { if (isset($step['object']) && $step['object'] instanceof TestCase) { - \assert($step['object'] instanceof TestCase); + assert($step['object'] instanceof TestCase); $step['object']->addWarning($warning); @@ -3553,4 +3597,59 @@ private static function createWarning(string $warning): void } } } + + /** + * @throws Exception + */ + private static function assertInternalTypeReplacement(string $type, bool $not): string + { + switch ($type) { + case 'numeric': + return 'assertIs' . ($not ? 'Not' : '') . 'Numeric'; + + case 'integer': + case 'int': + return 'assertIs' . ($not ? 'Not' : '') . 'Int'; + + case 'double': + case 'float': + case 'real': + return 'assertIs' . ($not ? 'Not' : '') . 'Float'; + + case 'string': + return 'assertIs' . ($not ? 'Not' : '') . 'String'; + + case 'boolean': + case 'bool': + return 'assertIs' . ($not ? 'Not' : '') . 'Bool'; + + case 'null': + return 'assert' . ($not ? 'Not' : '') . 'Null'; + + case 'array': + return 'assertIs' . ($not ? 'Not' : '') . 'Array'; + + case 'object': + return 'assertIs' . ($not ? 'Not' : '') . 'Object'; + + case 'resource': + return 'assertIs' . ($not ? 'Not' : '') . 'Resource'; + + case 'scalar': + return 'assertIs' . ($not ? 'Not' : '') . 'Scalar'; + + case 'callable': + return 'assertIs' . ($not ? 'Not' : '') . 'Callable'; + + case 'iterable': + return 'assertIs' . ($not ? 'Not' : '') . 'Iterable'; + } + + throw new Exception( + sprintf( + '"%s" is not a type supported by assertInternalType() / assertNotInternalType()', + $type + ) + ); + } } diff --git a/src/Framework/Assert/Functions.php b/src/Framework/Assert/Functions.php index 6112ecb334b..6af388b2cdc 100644 --- a/src/Framework/Assert/Functions.php +++ b/src/Framework/Assert/Functions.php @@ -64,16 +64,16 @@ use PHPUnit\Framework\MockObject\Stub\ReturnStub; use PHPUnit\Framework\MockObject\Stub\ReturnValueMap as ReturnValueMapStub; -if (!\function_exists('PHPUnit\Framework\assertArrayHasKey')) { +if (!function_exists('PHPUnit\Framework\assertArrayHasKey')) { /** * Asserts that an array has a specified key. * * @param int|string $key * @param array|ArrayAccess $array * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @see Assert::assertArrayHasKey */ @@ -83,16 +83,16 @@ function assertArrayHasKey($key, $array, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertArraySubset')) { +if (!function_exists('PHPUnit\Framework\assertArraySubset')) { /** * Asserts that an array has a specified subset. * * @param array|ArrayAccess $subset * @param array|ArrayAccess $array * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @codeCoverageIgnore * @@ -105,16 +105,16 @@ function assertArraySubset($subset, $array, bool $checkForObjectIdentity = false } } -if (!\function_exists('PHPUnit\Framework\assertArrayNotHasKey')) { +if (!function_exists('PHPUnit\Framework\assertArrayNotHasKey')) { /** * Asserts that an array does not have a specified key. * * @param int|string $key * @param array|ArrayAccess $array * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @see Assert::assertArrayNotHasKey */ @@ -124,13 +124,13 @@ function assertArrayNotHasKey($key, $array, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertContains')) { +if (!function_exists('PHPUnit\Framework\assertContains')) { /** * Asserts that a haystack contains a needle. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @see Assert::assertContains */ @@ -140,23 +140,23 @@ function assertContains($needle, $haystack, string $message = '', bool $ignoreCa } } -if (!\function_exists('PHPUnit\Framework\assertContainsEquals')) { +if (!function_exists('PHPUnit\Framework\assertContainsEquals')) { function assertContainsEquals($needle, iterable $haystack, string $message = ''): void { Assert::assertContainsEquals(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\assertAttributeContains')) { +if (!function_exists('PHPUnit\Framework\assertAttributeContains')) { /** * Asserts that a haystack that is stored in a static attribute of a class * or an attribute of an object contains a needle. * * @param object|string $haystackClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -169,13 +169,13 @@ function assertAttributeContains($needle, string $haystackAttributeName, $haysta } } -if (!\function_exists('PHPUnit\Framework\assertNotContains')) { +if (!function_exists('PHPUnit\Framework\assertNotContains')) { /** * Asserts that a haystack does not contain a needle. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @see Assert::assertNotContains */ @@ -185,23 +185,23 @@ function assertNotContains($needle, $haystack, string $message = '', bool $ignor } } -if (!\function_exists('PHPUnit\Framework\assertNotContainsEquals')) { +if (!function_exists('PHPUnit\Framework\assertNotContainsEquals')) { function assertNotContainsEquals($needle, iterable $haystack, string $message = ''): void { Assert::assertNotContainsEquals(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\assertAttributeNotContains')) { +if (!function_exists('PHPUnit\Framework\assertAttributeNotContains')) { /** * Asserts that a haystack that is stored in a static attribute of a class * or an attribute of an object does not contain a needle. * * @param object|string $haystackClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -214,12 +214,12 @@ function assertAttributeNotContains($needle, string $haystackAttributeName, $hay } } -if (!\function_exists('PHPUnit\Framework\assertContainsOnly')) { +if (!function_exists('PHPUnit\Framework\assertContainsOnly')) { /** * Asserts that a haystack contains only values of a given type. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertContainsOnly */ @@ -229,12 +229,12 @@ function assertContainsOnly(string $type, iterable $haystack, ?bool $isNativeTyp } } -if (!\function_exists('PHPUnit\Framework\assertContainsOnlyInstancesOf')) { +if (!function_exists('PHPUnit\Framework\assertContainsOnlyInstancesOf')) { /** * Asserts that a haystack contains only instances of a given class name. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertContainsOnlyInstancesOf */ @@ -244,7 +244,7 @@ function assertContainsOnlyInstancesOf(string $className, iterable $haystack, st } } -if (!\function_exists('PHPUnit\Framework\assertAttributeContainsOnly')) { +if (!function_exists('PHPUnit\Framework\assertAttributeContainsOnly')) { /** * Asserts that a haystack that is stored in a static attribute of a class * or an attribute of an object contains only values of a given type. @@ -252,9 +252,9 @@ function assertContainsOnlyInstancesOf(string $className, iterable $haystack, st * @param object|string $haystackClassOrObject * @param bool $isNativeType * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -267,12 +267,12 @@ function assertAttributeContainsOnly(string $type, string $haystackAttributeName } } -if (!\function_exists('PHPUnit\Framework\assertNotContainsOnly')) { +if (!function_exists('PHPUnit\Framework\assertNotContainsOnly')) { /** * Asserts that a haystack does not contain only values of a given type. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertNotContainsOnly */ @@ -282,7 +282,7 @@ function assertNotContainsOnly(string $type, iterable $haystack, ?bool $isNative } } -if (!\function_exists('PHPUnit\Framework\assertAttributeNotContainsOnly')) { +if (!function_exists('PHPUnit\Framework\assertAttributeNotContainsOnly')) { /** * Asserts that a haystack that is stored in a static attribute of a class * or an attribute of an object does not contain only values of a given @@ -291,9 +291,9 @@ function assertNotContainsOnly(string $type, iterable $haystack, ?bool $isNative * @param object|string $haystackClassOrObject * @param bool $isNativeType * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -306,15 +306,15 @@ function assertAttributeNotContainsOnly(string $type, string $haystackAttributeN } } -if (!\function_exists('PHPUnit\Framework\assertCount')) { +if (!function_exists('PHPUnit\Framework\assertCount')) { /** * Asserts the number of elements of an array, Countable or Traversable. * * @param Countable|iterable $haystack * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @see Assert::assertCount */ @@ -324,16 +324,16 @@ function assertCount(int $expectedCount, $haystack, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertAttributeCount')) { +if (!function_exists('PHPUnit\Framework\assertAttributeCount')) { /** * Asserts the number of elements of an array, Countable or Traversable * that is stored in an attribute. * * @param object|string $haystackClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -346,15 +346,15 @@ function assertAttributeCount(int $expectedCount, string $haystackAttributeName, } } -if (!\function_exists('PHPUnit\Framework\assertNotCount')) { +if (!function_exists('PHPUnit\Framework\assertNotCount')) { /** * Asserts the number of elements of an array, Countable or Traversable. * * @param Countable|iterable $haystack * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @see Assert::assertNotCount */ @@ -364,16 +364,16 @@ function assertNotCount(int $expectedCount, $haystack, string $message = ''): vo } } -if (!\function_exists('PHPUnit\Framework\assertAttributeNotCount')) { +if (!function_exists('PHPUnit\Framework\assertAttributeNotCount')) { /** * Asserts the number of elements of an array, Countable or Traversable * that is stored in an attribute. * * @param object|string $haystackClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -386,12 +386,12 @@ function assertAttributeNotCount(int $expectedCount, string $haystackAttributeNa } } -if (!\function_exists('PHPUnit\Framework\assertEquals')) { +if (!function_exists('PHPUnit\Framework\assertEquals')) { /** * Asserts that two variables are equal. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertEquals */ @@ -401,12 +401,12 @@ function assertEquals($expected, $actual, string $message = '', float $delta = 0 } } -if (!\function_exists('PHPUnit\Framework\assertEqualsCanonicalizing')) { +if (!function_exists('PHPUnit\Framework\assertEqualsCanonicalizing')) { /** * Asserts that two variables are equal (canonicalizing). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertEqualsCanonicalizing */ @@ -416,12 +416,12 @@ function assertEqualsCanonicalizing($expected, $actual, string $message = ''): v } } -if (!\function_exists('PHPUnit\Framework\assertEqualsIgnoringCase')) { +if (!function_exists('PHPUnit\Framework\assertEqualsIgnoringCase')) { /** * Asserts that two variables are equal (ignoring case). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertEqualsIgnoringCase */ @@ -431,12 +431,12 @@ function assertEqualsIgnoringCase($expected, $actual, string $message = ''): voi } } -if (!\function_exists('PHPUnit\Framework\assertEqualsWithDelta')) { +if (!function_exists('PHPUnit\Framework\assertEqualsWithDelta')) { /** * Asserts that two variables are equal (with delta). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertEqualsWithDelta */ @@ -446,15 +446,15 @@ function assertEqualsWithDelta($expected, $actual, float $delta, string $message } } -if (!\function_exists('PHPUnit\Framework\assertAttributeEquals')) { +if (!function_exists('PHPUnit\Framework\assertAttributeEquals')) { /** * Asserts that a variable is equal to an attribute of an object. * * @param object|string $actualClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -467,7 +467,7 @@ function assertAttributeEquals($expected, string $actualAttributeName, $actualCl } } -if (!\function_exists('PHPUnit\Framework\assertNotEquals')) { +if (!function_exists('PHPUnit\Framework\assertNotEquals')) { /** * Asserts that two variables are not equal. * @@ -476,8 +476,8 @@ function assertAttributeEquals($expected, string $actualAttributeName, $actualCl * @param bool $canonicalize * @param bool $ignoreCase * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertNotEquals */ @@ -487,12 +487,12 @@ function assertNotEquals($expected, $actual, string $message = '', $delta = 0.0, } } -if (!\function_exists('PHPUnit\Framework\assertNotEqualsCanonicalizing')) { +if (!function_exists('PHPUnit\Framework\assertNotEqualsCanonicalizing')) { /** * Asserts that two variables are not equal (canonicalizing). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertNotEqualsCanonicalizing */ @@ -502,12 +502,12 @@ function assertNotEqualsCanonicalizing($expected, $actual, string $message = '') } } -if (!\function_exists('PHPUnit\Framework\assertNotEqualsIgnoringCase')) { +if (!function_exists('PHPUnit\Framework\assertNotEqualsIgnoringCase')) { /** * Asserts that two variables are not equal (ignoring case). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertNotEqualsIgnoringCase */ @@ -517,12 +517,12 @@ function assertNotEqualsIgnoringCase($expected, $actual, string $message = ''): } } -if (!\function_exists('PHPUnit\Framework\assertNotEqualsWithDelta')) { +if (!function_exists('PHPUnit\Framework\assertNotEqualsWithDelta')) { /** * Asserts that two variables are not equal (with delta). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertNotEqualsWithDelta */ @@ -532,15 +532,15 @@ function assertNotEqualsWithDelta($expected, $actual, float $delta, string $mess } } -if (!\function_exists('PHPUnit\Framework\assertAttributeNotEquals')) { +if (!function_exists('PHPUnit\Framework\assertAttributeNotEquals')) { /** * Asserts that a variable is not equal to an attribute of an object. * * @param object|string $actualClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -553,12 +553,12 @@ function assertAttributeNotEquals($expected, string $actualAttributeName, $actua } } -if (!\function_exists('PHPUnit\Framework\assertEmpty')) { +if (!function_exists('PHPUnit\Framework\assertEmpty')) { /** * Asserts that a variable is empty. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert empty $actual * @@ -570,16 +570,16 @@ function assertEmpty($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertAttributeEmpty')) { +if (!function_exists('PHPUnit\Framework\assertAttributeEmpty')) { /** * Asserts that a static attribute of a class or an attribute of an object * is empty. * * @param object|string $haystackClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -592,12 +592,12 @@ function assertAttributeEmpty(string $haystackAttributeName, $haystackClassOrObj } } -if (!\function_exists('PHPUnit\Framework\assertNotEmpty')) { +if (!function_exists('PHPUnit\Framework\assertNotEmpty')) { /** * Asserts that a variable is not empty. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !empty $actual * @@ -609,16 +609,16 @@ function assertNotEmpty($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertAttributeNotEmpty')) { +if (!function_exists('PHPUnit\Framework\assertAttributeNotEmpty')) { /** * Asserts that a static attribute of a class or an attribute of an object * is not empty. * * @param object|string $haystackClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -631,12 +631,12 @@ function assertAttributeNotEmpty(string $haystackAttributeName, $haystackClassOr } } -if (!\function_exists('PHPUnit\Framework\assertGreaterThan')) { +if (!function_exists('PHPUnit\Framework\assertGreaterThan')) { /** * Asserts that a value is greater than another value. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertGreaterThan */ @@ -646,15 +646,15 @@ function assertGreaterThan($expected, $actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertAttributeGreaterThan')) { +if (!function_exists('PHPUnit\Framework\assertAttributeGreaterThan')) { /** * Asserts that an attribute is greater than another value. * * @param object|string $actualClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -667,12 +667,12 @@ function assertAttributeGreaterThan($expected, string $actualAttributeName, $act } } -if (!\function_exists('PHPUnit\Framework\assertGreaterThanOrEqual')) { +if (!function_exists('PHPUnit\Framework\assertGreaterThanOrEqual')) { /** * Asserts that a value is greater than or equal to another value. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertGreaterThanOrEqual */ @@ -682,15 +682,15 @@ function assertGreaterThanOrEqual($expected, $actual, string $message = ''): voi } } -if (!\function_exists('PHPUnit\Framework\assertAttributeGreaterThanOrEqual')) { +if (!function_exists('PHPUnit\Framework\assertAttributeGreaterThanOrEqual')) { /** * Asserts that an attribute is greater than or equal to another value. * * @param object|string $actualClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -703,12 +703,12 @@ function assertAttributeGreaterThanOrEqual($expected, string $actualAttributeNam } } -if (!\function_exists('PHPUnit\Framework\assertLessThan')) { +if (!function_exists('PHPUnit\Framework\assertLessThan')) { /** * Asserts that a value is smaller than another value. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertLessThan */ @@ -718,15 +718,15 @@ function assertLessThan($expected, $actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertAttributeLessThan')) { +if (!function_exists('PHPUnit\Framework\assertAttributeLessThan')) { /** * Asserts that an attribute is smaller than another value. * * @param object|string $actualClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -739,12 +739,12 @@ function assertAttributeLessThan($expected, string $actualAttributeName, $actual } } -if (!\function_exists('PHPUnit\Framework\assertLessThanOrEqual')) { +if (!function_exists('PHPUnit\Framework\assertLessThanOrEqual')) { /** * Asserts that a value is smaller than or equal to another value. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertLessThanOrEqual */ @@ -754,15 +754,15 @@ function assertLessThanOrEqual($expected, $actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertAttributeLessThanOrEqual')) { +if (!function_exists('PHPUnit\Framework\assertAttributeLessThanOrEqual')) { /** * Asserts that an attribute is smaller than or equal to another value. * * @param object|string $actualClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -775,13 +775,13 @@ function assertAttributeLessThanOrEqual($expected, string $actualAttributeName, } } -if (!\function_exists('PHPUnit\Framework\assertFileEquals')) { +if (!function_exists('PHPUnit\Framework\assertFileEquals')) { /** * Asserts that the contents of one file is equal to the contents of another * file. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertFileEquals */ @@ -791,13 +791,13 @@ function assertFileEquals(string $expected, string $actual, string $message = '' } } -if (!\function_exists('PHPUnit\Framework\assertFileEqualsCanonicalizing')) { +if (!function_exists('PHPUnit\Framework\assertFileEqualsCanonicalizing')) { /** * Asserts that the contents of one file is equal to the contents of another * file (canonicalizing). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertFileEqualsCanonicalizing */ @@ -807,13 +807,13 @@ function assertFileEqualsCanonicalizing(string $expected, string $actual, string } } -if (!\function_exists('PHPUnit\Framework\assertFileEqualsIgnoringCase')) { +if (!function_exists('PHPUnit\Framework\assertFileEqualsIgnoringCase')) { /** * Asserts that the contents of one file is equal to the contents of another * file (ignoring case). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertFileEqualsIgnoringCase */ @@ -823,13 +823,13 @@ function assertFileEqualsIgnoringCase(string $expected, string $actual, string $ } } -if (!\function_exists('PHPUnit\Framework\assertFileNotEquals')) { +if (!function_exists('PHPUnit\Framework\assertFileNotEquals')) { /** * Asserts that the contents of one file is not equal to the contents of * another file. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertFileNotEquals */ @@ -839,13 +839,13 @@ function assertFileNotEquals(string $expected, string $actual, string $message = } } -if (!\function_exists('PHPUnit\Framework\assertFileNotEqualsCanonicalizing')) { +if (!function_exists('PHPUnit\Framework\assertFileNotEqualsCanonicalizing')) { /** * Asserts that the contents of one file is not equal to the contents of another * file (canonicalizing). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertFileNotEqualsCanonicalizing */ @@ -855,13 +855,13 @@ function assertFileNotEqualsCanonicalizing(string $expected, string $actual, str } } -if (!\function_exists('PHPUnit\Framework\assertFileNotEqualsIgnoringCase')) { +if (!function_exists('PHPUnit\Framework\assertFileNotEqualsIgnoringCase')) { /** * Asserts that the contents of one file is not equal to the contents of another * file (ignoring case). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertFileNotEqualsIgnoringCase */ @@ -871,13 +871,13 @@ function assertFileNotEqualsIgnoringCase(string $expected, string $actual, strin } } -if (!\function_exists('PHPUnit\Framework\assertStringEqualsFile')) { +if (!function_exists('PHPUnit\Framework\assertStringEqualsFile')) { /** * Asserts that the contents of a string is equal * to the contents of a file. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertStringEqualsFile */ @@ -887,13 +887,13 @@ function assertStringEqualsFile(string $expectedFile, string $actualString, stri } } -if (!\function_exists('PHPUnit\Framework\assertStringEqualsFileCanonicalizing')) { +if (!function_exists('PHPUnit\Framework\assertStringEqualsFileCanonicalizing')) { /** * Asserts that the contents of a string is equal * to the contents of a file (canonicalizing). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertStringEqualsFileCanonicalizing */ @@ -903,13 +903,13 @@ function assertStringEqualsFileCanonicalizing(string $expectedFile, string $actu } } -if (!\function_exists('PHPUnit\Framework\assertStringEqualsFileIgnoringCase')) { +if (!function_exists('PHPUnit\Framework\assertStringEqualsFileIgnoringCase')) { /** * Asserts that the contents of a string is equal * to the contents of a file (ignoring case). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertStringEqualsFileIgnoringCase */ @@ -919,13 +919,13 @@ function assertStringEqualsFileIgnoringCase(string $expectedFile, string $actual } } -if (!\function_exists('PHPUnit\Framework\assertStringNotEqualsFile')) { +if (!function_exists('PHPUnit\Framework\assertStringNotEqualsFile')) { /** * Asserts that the contents of a string is not equal * to the contents of a file. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertStringNotEqualsFile */ @@ -935,13 +935,13 @@ function assertStringNotEqualsFile(string $expectedFile, string $actualString, s } } -if (!\function_exists('PHPUnit\Framework\assertStringNotEqualsFileCanonicalizing')) { +if (!function_exists('PHPUnit\Framework\assertStringNotEqualsFileCanonicalizing')) { /** * Asserts that the contents of a string is not equal * to the contents of a file (canonicalizing). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertStringNotEqualsFileCanonicalizing */ @@ -951,13 +951,13 @@ function assertStringNotEqualsFileCanonicalizing(string $expectedFile, string $a } } -if (!\function_exists('PHPUnit\Framework\assertStringNotEqualsFileIgnoringCase')) { +if (!function_exists('PHPUnit\Framework\assertStringNotEqualsFileIgnoringCase')) { /** * Asserts that the contents of a string is not equal * to the contents of a file (ignoring case). * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertStringNotEqualsFileIgnoringCase */ @@ -967,12 +967,12 @@ function assertStringNotEqualsFileIgnoringCase(string $expectedFile, string $act } } -if (!\function_exists('PHPUnit\Framework\assertIsReadable')) { +if (!function_exists('PHPUnit\Framework\assertIsReadable')) { /** * Asserts that a file/dir is readable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertIsReadable */ @@ -982,12 +982,12 @@ function assertIsReadable(string $filename, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertNotIsReadable')) { +if (!function_exists('PHPUnit\Framework\assertNotIsReadable')) { /** * Asserts that a file/dir exists and is not readable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertNotIsReadable */ @@ -997,12 +997,12 @@ function assertNotIsReadable(string $filename, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsWritable')) { +if (!function_exists('PHPUnit\Framework\assertIsWritable')) { /** * Asserts that a file/dir exists and is writable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertIsWritable */ @@ -1012,12 +1012,12 @@ function assertIsWritable(string $filename, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertNotIsWritable')) { +if (!function_exists('PHPUnit\Framework\assertNotIsWritable')) { /** * Asserts that a file/dir exists and is not writable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertNotIsWritable */ @@ -1027,12 +1027,12 @@ function assertNotIsWritable(string $filename, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertDirectoryExists')) { +if (!function_exists('PHPUnit\Framework\assertDirectoryExists')) { /** * Asserts that a directory exists. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertDirectoryExists */ @@ -1042,12 +1042,12 @@ function assertDirectoryExists(string $directory, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertDirectoryNotExists')) { +if (!function_exists('PHPUnit\Framework\assertDirectoryNotExists')) { /** * Asserts that a directory does not exist. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertDirectoryNotExists */ @@ -1057,12 +1057,12 @@ function assertDirectoryNotExists(string $directory, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertDirectoryIsReadable')) { +if (!function_exists('PHPUnit\Framework\assertDirectoryIsReadable')) { /** * Asserts that a directory exists and is readable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertDirectoryIsReadable */ @@ -1072,12 +1072,12 @@ function assertDirectoryIsReadable(string $directory, string $message = ''): voi } } -if (!\function_exists('PHPUnit\Framework\assertDirectoryNotIsReadable')) { +if (!function_exists('PHPUnit\Framework\assertDirectoryNotIsReadable')) { /** * Asserts that a directory exists and is not readable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertDirectoryNotIsReadable */ @@ -1087,12 +1087,12 @@ function assertDirectoryNotIsReadable(string $directory, string $message = ''): } } -if (!\function_exists('PHPUnit\Framework\assertDirectoryIsWritable')) { +if (!function_exists('PHPUnit\Framework\assertDirectoryIsWritable')) { /** * Asserts that a directory exists and is writable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertDirectoryIsWritable */ @@ -1102,12 +1102,12 @@ function assertDirectoryIsWritable(string $directory, string $message = ''): voi } } -if (!\function_exists('PHPUnit\Framework\assertDirectoryNotIsWritable')) { +if (!function_exists('PHPUnit\Framework\assertDirectoryNotIsWritable')) { /** * Asserts that a directory exists and is not writable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertDirectoryNotIsWritable */ @@ -1117,12 +1117,12 @@ function assertDirectoryNotIsWritable(string $directory, string $message = ''): } } -if (!\function_exists('PHPUnit\Framework\assertFileExists')) { +if (!function_exists('PHPUnit\Framework\assertFileExists')) { /** * Asserts that a file exists. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertFileExists */ @@ -1132,12 +1132,12 @@ function assertFileExists(string $filename, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertFileNotExists')) { +if (!function_exists('PHPUnit\Framework\assertFileNotExists')) { /** * Asserts that a file does not exist. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertFileNotExists */ @@ -1147,12 +1147,12 @@ function assertFileNotExists(string $filename, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertFileIsReadable')) { +if (!function_exists('PHPUnit\Framework\assertFileIsReadable')) { /** * Asserts that a file exists and is readable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertFileIsReadable */ @@ -1162,12 +1162,12 @@ function assertFileIsReadable(string $file, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertFileNotIsReadable')) { +if (!function_exists('PHPUnit\Framework\assertFileNotIsReadable')) { /** * Asserts that a file exists and is not readable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertFileNotIsReadable */ @@ -1177,12 +1177,12 @@ function assertFileNotIsReadable(string $file, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertFileIsWritable')) { +if (!function_exists('PHPUnit\Framework\assertFileIsWritable')) { /** * Asserts that a file exists and is writable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertFileIsWritable */ @@ -1192,12 +1192,12 @@ function assertFileIsWritable(string $file, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertFileNotIsWritable')) { +if (!function_exists('PHPUnit\Framework\assertFileNotIsWritable')) { /** * Asserts that a file exists and is not writable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertFileNotIsWritable */ @@ -1207,12 +1207,12 @@ function assertFileNotIsWritable(string $file, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertTrue')) { +if (!function_exists('PHPUnit\Framework\assertTrue')) { /** * Asserts that a condition is true. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert true $condition * @@ -1224,12 +1224,12 @@ function assertTrue($condition, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertNotTrue')) { +if (!function_exists('PHPUnit\Framework\assertNotTrue')) { /** * Asserts that a condition is not true. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !true $condition * @@ -1241,12 +1241,12 @@ function assertNotTrue($condition, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertFalse')) { +if (!function_exists('PHPUnit\Framework\assertFalse')) { /** * Asserts that a condition is false. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert false $condition * @@ -1258,12 +1258,12 @@ function assertFalse($condition, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertNotFalse')) { +if (!function_exists('PHPUnit\Framework\assertNotFalse')) { /** * Asserts that a condition is not false. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !false $condition * @@ -1275,12 +1275,12 @@ function assertNotFalse($condition, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertNull')) { +if (!function_exists('PHPUnit\Framework\assertNull')) { /** * Asserts that a variable is null. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert null $actual * @@ -1292,12 +1292,12 @@ function assertNull($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertNotNull')) { +if (!function_exists('PHPUnit\Framework\assertNotNull')) { /** * Asserts that a variable is not null. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !null $actual * @@ -1309,12 +1309,12 @@ function assertNotNull($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertFinite')) { +if (!function_exists('PHPUnit\Framework\assertFinite')) { /** * Asserts that a variable is finite. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertFinite */ @@ -1324,12 +1324,12 @@ function assertFinite($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertInfinite')) { +if (!function_exists('PHPUnit\Framework\assertInfinite')) { /** * Asserts that a variable is infinite. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertInfinite */ @@ -1339,12 +1339,12 @@ function assertInfinite($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertNan')) { +if (!function_exists('PHPUnit\Framework\assertNan')) { /** * Asserts that a variable is nan. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertNan */ @@ -1354,13 +1354,13 @@ function assertNan($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertClassHasAttribute')) { +if (!function_exists('PHPUnit\Framework\assertClassHasAttribute')) { /** * Asserts that a class has a specified attribute. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @see Assert::assertClassHasAttribute */ @@ -1370,13 +1370,13 @@ function assertClassHasAttribute(string $attributeName, string $className, strin } } -if (!\function_exists('PHPUnit\Framework\assertClassNotHasAttribute')) { +if (!function_exists('PHPUnit\Framework\assertClassNotHasAttribute')) { /** * Asserts that a class does not have a specified attribute. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @see Assert::assertClassNotHasAttribute */ @@ -1386,13 +1386,13 @@ function assertClassNotHasAttribute(string $attributeName, string $className, st } } -if (!\function_exists('PHPUnit\Framework\assertClassHasStaticAttribute')) { +if (!function_exists('PHPUnit\Framework\assertClassHasStaticAttribute')) { /** * Asserts that a class has a specified static attribute. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @see Assert::assertClassHasStaticAttribute */ @@ -1402,13 +1402,13 @@ function assertClassHasStaticAttribute(string $attributeName, string $className, } } -if (!\function_exists('PHPUnit\Framework\assertClassNotHasStaticAttribute')) { +if (!function_exists('PHPUnit\Framework\assertClassNotHasStaticAttribute')) { /** * Asserts that a class does not have a specified static attribute. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @see Assert::assertClassNotHasStaticAttribute */ @@ -1418,15 +1418,15 @@ function assertClassNotHasStaticAttribute(string $attributeName, string $classNa } } -if (!\function_exists('PHPUnit\Framework\assertObjectHasAttribute')) { +if (!function_exists('PHPUnit\Framework\assertObjectHasAttribute')) { /** * Asserts that an object has a specified attribute. * * @param object $object * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @see Assert::assertObjectHasAttribute */ @@ -1436,15 +1436,15 @@ function assertObjectHasAttribute(string $attributeName, $object, string $messag } } -if (!\function_exists('PHPUnit\Framework\assertObjectNotHasAttribute')) { +if (!function_exists('PHPUnit\Framework\assertObjectNotHasAttribute')) { /** * Asserts that an object does not have a specified attribute. * * @param object $object * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @see Assert::assertObjectNotHasAttribute */ @@ -1454,14 +1454,14 @@ function assertObjectNotHasAttribute(string $attributeName, $object, string $mes } } -if (!\function_exists('PHPUnit\Framework\assertSame')) { +if (!function_exists('PHPUnit\Framework\assertSame')) { /** * Asserts that two variables have the same type and value. * Used on objects, it asserts that two variables reference * the same object. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-template ExpectedType * @psalm-param ExpectedType $expected @@ -1475,16 +1475,16 @@ function assertSame($expected, $actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertAttributeSame')) { +if (!function_exists('PHPUnit\Framework\assertAttributeSame')) { /** * Asserts that a variable and an attribute of an object have the same type * and value. * * @param object|string $actualClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -1497,14 +1497,14 @@ function assertAttributeSame($expected, string $actualAttributeName, $actualClas } } -if (!\function_exists('PHPUnit\Framework\assertNotSame')) { +if (!function_exists('PHPUnit\Framework\assertNotSame')) { /** * Asserts that two variables do not have the same type and value. * Used on objects, it asserts that two variables do not reference * the same object. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertNotSame */ @@ -1514,16 +1514,16 @@ function assertNotSame($expected, $actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertAttributeNotSame')) { +if (!function_exists('PHPUnit\Framework\assertAttributeNotSame')) { /** * Asserts that a variable and an attribute of an object do not have the * same type and value. * * @param object|string $actualClassOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -1536,17 +1536,17 @@ function assertAttributeNotSame($expected, string $actualAttributeName, $actualC } } -if (!\function_exists('PHPUnit\Framework\assertInstanceOf')) { +if (!function_exists('PHPUnit\Framework\assertInstanceOf')) { /** * Asserts that a variable is of a given type. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @psalm-template ExpectedType of object * @psalm-param class-string $expected - * @psalm-assert ExpectedType $actual + * @psalm-assert =ExpectedType $actual * * @see Assert::assertInstanceOf */ @@ -1556,15 +1556,15 @@ function assertInstanceOf(string $expected, $actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertAttributeInstanceOf')) { +if (!function_exists('PHPUnit\Framework\assertAttributeInstanceOf')) { /** * Asserts that an attribute is of a given type. * * @param object|string $classOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -1579,13 +1579,13 @@ function assertAttributeInstanceOf(string $expected, string $attributeName, $cla } } -if (!\function_exists('PHPUnit\Framework\assertNotInstanceOf')) { +if (!function_exists('PHPUnit\Framework\assertNotInstanceOf')) { /** * Asserts that a variable is not of a given type. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @psalm-template ExpectedType of object * @psalm-param class-string $expected @@ -1599,15 +1599,15 @@ function assertNotInstanceOf(string $expected, $actual, string $message = ''): v } } -if (!\function_exists('PHPUnit\Framework\assertAttributeNotInstanceOf')) { +if (!function_exists('PHPUnit\Framework\assertAttributeNotInstanceOf')) { /** * Asserts that an attribute is of a given type. * * @param object|string $classOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -1622,12 +1622,12 @@ function assertAttributeNotInstanceOf(string $expected, string $attributeName, $ } } -if (!\function_exists('PHPUnit\Framework\assertInternalType')) { +if (!function_exists('PHPUnit\Framework\assertInternalType')) { /** * Asserts that a variable is of a given type. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3369 * @codeCoverageIgnore @@ -1640,15 +1640,15 @@ function assertInternalType(string $expected, $actual, string $message = ''): vo } } -if (!\function_exists('PHPUnit\Framework\assertAttributeInternalType')) { +if (!function_exists('PHPUnit\Framework\assertAttributeInternalType')) { /** * Asserts that an attribute is of a given type. * * @param object|string $classOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -1661,12 +1661,12 @@ function assertAttributeInternalType(string $expected, string $attributeName, $c } } -if (!\function_exists('PHPUnit\Framework\assertIsArray')) { +if (!function_exists('PHPUnit\Framework\assertIsArray')) { /** * Asserts that a variable is of type array. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert array $actual * @@ -1678,12 +1678,12 @@ function assertIsArray($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsBool')) { +if (!function_exists('PHPUnit\Framework\assertIsBool')) { /** * Asserts that a variable is of type bool. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert bool $actual * @@ -1695,12 +1695,12 @@ function assertIsBool($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsFloat')) { +if (!function_exists('PHPUnit\Framework\assertIsFloat')) { /** * Asserts that a variable is of type float. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert float $actual * @@ -1712,12 +1712,12 @@ function assertIsFloat($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsInt')) { +if (!function_exists('PHPUnit\Framework\assertIsInt')) { /** * Asserts that a variable is of type int. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert int $actual * @@ -1729,12 +1729,12 @@ function assertIsInt($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsNumeric')) { +if (!function_exists('PHPUnit\Framework\assertIsNumeric')) { /** * Asserts that a variable is of type numeric. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert numeric $actual * @@ -1746,12 +1746,12 @@ function assertIsNumeric($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsObject')) { +if (!function_exists('PHPUnit\Framework\assertIsObject')) { /** * Asserts that a variable is of type object. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert object $actual * @@ -1763,12 +1763,12 @@ function assertIsObject($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsResource')) { +if (!function_exists('PHPUnit\Framework\assertIsResource')) { /** * Asserts that a variable is of type resource. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert resource $actual * @@ -1780,12 +1780,12 @@ function assertIsResource($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsString')) { +if (!function_exists('PHPUnit\Framework\assertIsString')) { /** * Asserts that a variable is of type string. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert string $actual * @@ -1797,12 +1797,12 @@ function assertIsString($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsScalar')) { +if (!function_exists('PHPUnit\Framework\assertIsScalar')) { /** * Asserts that a variable is of type scalar. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert scalar $actual * @@ -1814,12 +1814,12 @@ function assertIsScalar($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsCallable')) { +if (!function_exists('PHPUnit\Framework\assertIsCallable')) { /** * Asserts that a variable is of type callable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert callable $actual * @@ -1831,12 +1831,12 @@ function assertIsCallable($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsIterable')) { +if (!function_exists('PHPUnit\Framework\assertIsIterable')) { /** * Asserts that a variable is of type iterable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert iterable $actual * @@ -1848,12 +1848,12 @@ function assertIsIterable($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertNotInternalType')) { +if (!function_exists('PHPUnit\Framework\assertNotInternalType')) { /** * Asserts that a variable is not of a given type. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3369 * @codeCoverageIgnore @@ -1866,12 +1866,12 @@ function assertNotInternalType(string $expected, $actual, string $message = ''): } } -if (!\function_exists('PHPUnit\Framework\assertIsNotArray')) { +if (!function_exists('PHPUnit\Framework\assertIsNotArray')) { /** * Asserts that a variable is not of type array. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !array $actual * @@ -1883,12 +1883,12 @@ function assertIsNotArray($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsNotBool')) { +if (!function_exists('PHPUnit\Framework\assertIsNotBool')) { /** * Asserts that a variable is not of type bool. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !bool $actual * @@ -1900,12 +1900,12 @@ function assertIsNotBool($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsNotFloat')) { +if (!function_exists('PHPUnit\Framework\assertIsNotFloat')) { /** * Asserts that a variable is not of type float. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !float $actual * @@ -1917,12 +1917,12 @@ function assertIsNotFloat($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsNotInt')) { +if (!function_exists('PHPUnit\Framework\assertIsNotInt')) { /** * Asserts that a variable is not of type int. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !int $actual * @@ -1934,12 +1934,12 @@ function assertIsNotInt($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsNotNumeric')) { +if (!function_exists('PHPUnit\Framework\assertIsNotNumeric')) { /** * Asserts that a variable is not of type numeric. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !numeric $actual * @@ -1951,12 +1951,12 @@ function assertIsNotNumeric($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsNotObject')) { +if (!function_exists('PHPUnit\Framework\assertIsNotObject')) { /** * Asserts that a variable is not of type object. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !object $actual * @@ -1968,12 +1968,12 @@ function assertIsNotObject($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsNotResource')) { +if (!function_exists('PHPUnit\Framework\assertIsNotResource')) { /** * Asserts that a variable is not of type resource. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !resource $actual * @@ -1985,12 +1985,12 @@ function assertIsNotResource($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsNotString')) { +if (!function_exists('PHPUnit\Framework\assertIsNotString')) { /** * Asserts that a variable is not of type string. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !string $actual * @@ -2002,12 +2002,12 @@ function assertIsNotString($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsNotScalar')) { +if (!function_exists('PHPUnit\Framework\assertIsNotScalar')) { /** * Asserts that a variable is not of type scalar. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !scalar $actual * @@ -2019,12 +2019,12 @@ function assertIsNotScalar($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsNotCallable')) { +if (!function_exists('PHPUnit\Framework\assertIsNotCallable')) { /** * Asserts that a variable is not of type callable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !callable $actual * @@ -2036,12 +2036,12 @@ function assertIsNotCallable($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertIsNotIterable')) { +if (!function_exists('PHPUnit\Framework\assertIsNotIterable')) { /** * Asserts that a variable is not of type iterable. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @psalm-assert !iterable $actual * @@ -2053,15 +2053,15 @@ function assertIsNotIterable($actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertAttributeNotInternalType')) { +if (!function_exists('PHPUnit\Framework\assertAttributeNotInternalType')) { /** * Asserts that an attribute is of a given type. * * @param object|string $classOrObject * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @deprecated https://github.com/sebastianbergmann/phpunit/issues/3338 * @codeCoverageIgnore @@ -2074,12 +2074,12 @@ function assertAttributeNotInternalType(string $expected, string $attributeName, } } -if (!\function_exists('PHPUnit\Framework\assertRegExp')) { +if (!function_exists('PHPUnit\Framework\assertRegExp')) { /** * Asserts that a string matches a given regular expression. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertRegExp */ @@ -2089,12 +2089,12 @@ function assertRegExp(string $pattern, string $string, string $message = ''): vo } } -if (!\function_exists('PHPUnit\Framework\assertNotRegExp')) { +if (!function_exists('PHPUnit\Framework\assertNotRegExp')) { /** * Asserts that a string does not match a given regular expression. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertNotRegExp */ @@ -2104,7 +2104,7 @@ function assertNotRegExp(string $pattern, string $string, string $message = ''): } } -if (!\function_exists('PHPUnit\Framework\assertSameSize')) { +if (!function_exists('PHPUnit\Framework\assertSameSize')) { /** * Assert that the size of two arrays (or `Countable` or `Traversable` objects) * is the same. @@ -2112,9 +2112,9 @@ function assertNotRegExp(string $pattern, string $string, string $message = ''): * @param Countable|iterable $expected * @param Countable|iterable $actual * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @see Assert::assertSameSize */ @@ -2124,7 +2124,7 @@ function assertSameSize($expected, $actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertNotSameSize')) { +if (!function_exists('PHPUnit\Framework\assertNotSameSize')) { /** * Assert that the size of two arrays (or `Countable` or `Traversable` objects) * is not the same. @@ -2132,9 +2132,9 @@ function assertSameSize($expected, $actual, string $message = ''): void * @param Countable|iterable $expected * @param Countable|iterable $actual * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @see Assert::assertNotSameSize */ @@ -2144,12 +2144,12 @@ function assertNotSameSize($expected, $actual, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertStringMatchesFormat')) { +if (!function_exists('PHPUnit\Framework\assertStringMatchesFormat')) { /** * Asserts that a string matches a given format string. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertStringMatchesFormat */ @@ -2159,12 +2159,12 @@ function assertStringMatchesFormat(string $format, string $string, string $messa } } -if (!\function_exists('PHPUnit\Framework\assertStringNotMatchesFormat')) { +if (!function_exists('PHPUnit\Framework\assertStringNotMatchesFormat')) { /** * Asserts that a string does not match a given format string. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertStringNotMatchesFormat */ @@ -2174,12 +2174,12 @@ function assertStringNotMatchesFormat(string $format, string $string, string $me } } -if (!\function_exists('PHPUnit\Framework\assertStringMatchesFormatFile')) { +if (!function_exists('PHPUnit\Framework\assertStringMatchesFormatFile')) { /** * Asserts that a string matches a given format file. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertStringMatchesFormatFile */ @@ -2189,12 +2189,12 @@ function assertStringMatchesFormatFile(string $formatFile, string $string, strin } } -if (!\function_exists('PHPUnit\Framework\assertStringNotMatchesFormatFile')) { +if (!function_exists('PHPUnit\Framework\assertStringNotMatchesFormatFile')) { /** * Asserts that a string does not match a given format string. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertStringNotMatchesFormatFile */ @@ -2204,12 +2204,12 @@ function assertStringNotMatchesFormatFile(string $formatFile, string $string, st } } -if (!\function_exists('PHPUnit\Framework\assertStringStartsWith')) { +if (!function_exists('PHPUnit\Framework\assertStringStartsWith')) { /** * Asserts that a string starts with a given prefix. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertStringStartsWith */ @@ -2219,15 +2219,15 @@ function assertStringStartsWith(string $prefix, string $string, string $message } } -if (!\function_exists('PHPUnit\Framework\assertStringStartsNotWith')) { +if (!function_exists('PHPUnit\Framework\assertStringStartsNotWith')) { /** * Asserts that a string starts not with a given prefix. * * @param string $prefix * @param string $string * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertStringStartsNotWith */ @@ -2237,10 +2237,10 @@ function assertStringStartsNotWith($prefix, $string, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertStringContainsString')) { +if (!function_exists('PHPUnit\Framework\assertStringContainsString')) { /** - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertStringContainsString */ @@ -2250,10 +2250,10 @@ function assertStringContainsString(string $needle, string $haystack, string $me } } -if (!\function_exists('PHPUnit\Framework\assertStringContainsStringIgnoringCase')) { +if (!function_exists('PHPUnit\Framework\assertStringContainsStringIgnoringCase')) { /** - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertStringContainsStringIgnoringCase */ @@ -2263,10 +2263,10 @@ function assertStringContainsStringIgnoringCase(string $needle, string $haystack } } -if (!\function_exists('PHPUnit\Framework\assertStringNotContainsString')) { +if (!function_exists('PHPUnit\Framework\assertStringNotContainsString')) { /** - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertStringNotContainsString */ @@ -2276,10 +2276,10 @@ function assertStringNotContainsString(string $needle, string $haystack, string } } -if (!\function_exists('PHPUnit\Framework\assertStringNotContainsStringIgnoringCase')) { +if (!function_exists('PHPUnit\Framework\assertStringNotContainsStringIgnoringCase')) { /** - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertStringNotContainsStringIgnoringCase */ @@ -2289,12 +2289,12 @@ function assertStringNotContainsStringIgnoringCase(string $needle, string $hayst } } -if (!\function_exists('PHPUnit\Framework\assertStringEndsWith')) { +if (!function_exists('PHPUnit\Framework\assertStringEndsWith')) { /** * Asserts that a string ends with a given suffix. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertStringEndsWith */ @@ -2304,12 +2304,12 @@ function assertStringEndsWith(string $suffix, string $string, string $message = } } -if (!\function_exists('PHPUnit\Framework\assertStringEndsNotWith')) { +if (!function_exists('PHPUnit\Framework\assertStringEndsNotWith')) { /** * Asserts that a string ends not with a given suffix. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertStringEndsNotWith */ @@ -2319,13 +2319,13 @@ function assertStringEndsNotWith(string $suffix, string $string, string $message } } -if (!\function_exists('PHPUnit\Framework\assertXmlFileEqualsXmlFile')) { +if (!function_exists('PHPUnit\Framework\assertXmlFileEqualsXmlFile')) { /** * Asserts that two XML files are equal. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @see Assert::assertXmlFileEqualsXmlFile */ @@ -2335,13 +2335,13 @@ function assertXmlFileEqualsXmlFile(string $expectedFile, string $actualFile, st } } -if (!\function_exists('PHPUnit\Framework\assertXmlFileNotEqualsXmlFile')) { +if (!function_exists('PHPUnit\Framework\assertXmlFileNotEqualsXmlFile')) { /** * Asserts that two XML files are not equal. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @see Assert::assertXmlFileNotEqualsXmlFile */ @@ -2351,15 +2351,15 @@ function assertXmlFileNotEqualsXmlFile(string $expectedFile, string $actualFile, } } -if (!\function_exists('PHPUnit\Framework\assertXmlStringEqualsXmlFile')) { +if (!function_exists('PHPUnit\Framework\assertXmlStringEqualsXmlFile')) { /** * Asserts that two XML documents are equal. * * @param DOMDocument|string $actualXml * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @see Assert::assertXmlStringEqualsXmlFile */ @@ -2369,15 +2369,15 @@ function assertXmlStringEqualsXmlFile(string $expectedFile, $actualXml, string $ } } -if (!\function_exists('PHPUnit\Framework\assertXmlStringNotEqualsXmlFile')) { +if (!function_exists('PHPUnit\Framework\assertXmlStringNotEqualsXmlFile')) { /** * Asserts that two XML documents are not equal. * * @param DOMDocument|string $actualXml * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @see Assert::assertXmlStringNotEqualsXmlFile */ @@ -2387,16 +2387,16 @@ function assertXmlStringNotEqualsXmlFile(string $expectedFile, $actualXml, strin } } -if (!\function_exists('PHPUnit\Framework\assertXmlStringEqualsXmlString')) { +if (!function_exists('PHPUnit\Framework\assertXmlStringEqualsXmlString')) { /** * Asserts that two XML documents are equal. * * @param DOMDocument|string $expectedXml * @param DOMDocument|string $actualXml * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @see Assert::assertXmlStringEqualsXmlString */ @@ -2406,16 +2406,16 @@ function assertXmlStringEqualsXmlString($expectedXml, $actualXml, string $messag } } -if (!\function_exists('PHPUnit\Framework\assertXmlStringNotEqualsXmlString')) { +if (!function_exists('PHPUnit\Framework\assertXmlStringNotEqualsXmlString')) { /** * Asserts that two XML documents are not equal. * * @param DOMDocument|string $expectedXml * @param DOMDocument|string $actualXml * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException * * @see Assert::assertXmlStringNotEqualsXmlString */ @@ -2425,13 +2425,13 @@ function assertXmlStringNotEqualsXmlString($expectedXml, $actualXml, string $mes } } -if (!\function_exists('PHPUnit\Framework\assertEqualXMLStructure')) { +if (!function_exists('PHPUnit\Framework\assertEqualXMLStructure')) { /** * Asserts that a hierarchy of DOMElements matches. * + * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws AssertionFailedError * @throws ExpectationFailedException - * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * * @see Assert::assertEqualXMLStructure */ @@ -2441,12 +2441,12 @@ function assertEqualXMLStructure(DOMElement $expectedElement, DOMElement $actual } } -if (!\function_exists('PHPUnit\Framework\assertThat')) { +if (!function_exists('PHPUnit\Framework\assertThat')) { /** * Evaluates a PHPUnit\Framework\Constraint matcher object. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertThat */ @@ -2456,12 +2456,12 @@ function assertThat($value, Constraint $constraint, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertJson')) { +if (!function_exists('PHPUnit\Framework\assertJson')) { /** * Asserts that a string is a valid JSON string. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertJson */ @@ -2471,12 +2471,12 @@ function assertJson(string $actualJson, string $message = ''): void } } -if (!\function_exists('PHPUnit\Framework\assertJsonStringEqualsJsonString')) { +if (!function_exists('PHPUnit\Framework\assertJsonStringEqualsJsonString')) { /** * Asserts that two given JSON encoded objects or arrays are equal. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertJsonStringEqualsJsonString */ @@ -2486,15 +2486,15 @@ function assertJsonStringEqualsJsonString(string $expectedJson, string $actualJs } } -if (!\function_exists('PHPUnit\Framework\assertJsonStringNotEqualsJsonString')) { +if (!function_exists('PHPUnit\Framework\assertJsonStringNotEqualsJsonString')) { /** * Asserts that two given JSON encoded objects or arrays are not equal. * * @param string $expectedJson * @param string $actualJson * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertJsonStringNotEqualsJsonString */ @@ -2504,12 +2504,12 @@ function assertJsonStringNotEqualsJsonString($expectedJson, $actualJson, string } } -if (!\function_exists('PHPUnit\Framework\assertJsonStringEqualsJsonFile')) { +if (!function_exists('PHPUnit\Framework\assertJsonStringEqualsJsonFile')) { /** * Asserts that the generated JSON encoded object and the content of the given file are equal. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertJsonStringEqualsJsonFile */ @@ -2519,12 +2519,12 @@ function assertJsonStringEqualsJsonFile(string $expectedFile, string $actualJson } } -if (!\function_exists('PHPUnit\Framework\assertJsonStringNotEqualsJsonFile')) { +if (!function_exists('PHPUnit\Framework\assertJsonStringNotEqualsJsonFile')) { /** * Asserts that the generated JSON encoded object and the content of the given file are not equal. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertJsonStringNotEqualsJsonFile */ @@ -2534,12 +2534,12 @@ function assertJsonStringNotEqualsJsonFile(string $expectedFile, string $actualJ } } -if (!\function_exists('PHPUnit\Framework\assertJsonFileEqualsJsonFile')) { +if (!function_exists('PHPUnit\Framework\assertJsonFileEqualsJsonFile')) { /** * Asserts that two JSON files are equal. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertJsonFileEqualsJsonFile */ @@ -2549,12 +2549,12 @@ function assertJsonFileEqualsJsonFile(string $expectedFile, string $actualFile, } } -if (!\function_exists('PHPUnit\Framework\assertJsonFileNotEqualsJsonFile')) { +if (!function_exists('PHPUnit\Framework\assertJsonFileNotEqualsJsonFile')) { /** * Asserts that two JSON files are not equal. * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * * @see Assert::assertJsonFileNotEqualsJsonFile */ @@ -2564,308 +2564,308 @@ function assertJsonFileNotEqualsJsonFile(string $expectedFile, string $actualFil } } -if (!\function_exists('PHPUnit\Framework\logicalAnd')) { +if (!function_exists('PHPUnit\Framework\logicalAnd')) { function logicalAnd(): LogicalAnd { return Assert::logicalAnd(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\logicalOr')) { +if (!function_exists('PHPUnit\Framework\logicalOr')) { function logicalOr(): LogicalOr { return Assert::logicalOr(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\logicalNot')) { +if (!function_exists('PHPUnit\Framework\logicalNot')) { function logicalNot(Constraint $constraint): LogicalNot { return Assert::logicalNot(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\logicalXor')) { +if (!function_exists('PHPUnit\Framework\logicalXor')) { function logicalXor(): LogicalXor { return Assert::logicalXor(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\anything')) { +if (!function_exists('PHPUnit\Framework\anything')) { function anything(): IsAnything { return Assert::anything(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\isTrue')) { +if (!function_exists('PHPUnit\Framework\isTrue')) { function isTrue(): IsTrue { return Assert::isTrue(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\callback')) { +if (!function_exists('PHPUnit\Framework\callback')) { function callback(callable $callback): Callback { return Assert::callback(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\isFalse')) { +if (!function_exists('PHPUnit\Framework\isFalse')) { function isFalse(): IsFalse { return Assert::isFalse(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\isJson')) { +if (!function_exists('PHPUnit\Framework\isJson')) { function isJson(): IsJson { return Assert::isJson(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\isNull')) { +if (!function_exists('PHPUnit\Framework\isNull')) { function isNull(): IsNull { return Assert::isNull(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\isFinite')) { +if (!function_exists('PHPUnit\Framework\isFinite')) { function isFinite(): IsFinite { return Assert::isFinite(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\isInfinite')) { +if (!function_exists('PHPUnit\Framework\isInfinite')) { function isInfinite(): IsInfinite { return Assert::isInfinite(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\isNan')) { +if (!function_exists('PHPUnit\Framework\isNan')) { function isNan(): IsNan { return Assert::isNan(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\attribute')) { +if (!function_exists('PHPUnit\Framework\attribute')) { function attribute(Constraint $constraint, string $attributeName): Attribute { return Assert::attribute(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\contains')) { +if (!function_exists('PHPUnit\Framework\contains')) { function contains($value, bool $checkForObjectIdentity = true, bool $checkForNonObjectIdentity = false): TraversableContains { return Assert::contains(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\containsEqual')) { +if (!function_exists('PHPUnit\Framework\containsEqual')) { function containsEqual($value): TraversableContainsEqual { return Assert::containsEqual(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\containsIdentical')) { +if (!function_exists('PHPUnit\Framework\containsIdentical')) { function containsIdentical($value): TraversableContainsIdentical { return Assert::containsIdentical(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\containsOnly')) { +if (!function_exists('PHPUnit\Framework\containsOnly')) { function containsOnly(string $type): TraversableContainsOnly { return Assert::containsOnly(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\containsOnlyInstancesOf')) { +if (!function_exists('PHPUnit\Framework\containsOnlyInstancesOf')) { function containsOnlyInstancesOf(string $className): TraversableContainsOnly { return Assert::containsOnlyInstancesOf(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\arrayHasKey')) { +if (!function_exists('PHPUnit\Framework\arrayHasKey')) { function arrayHasKey($key): ArrayHasKey { return Assert::arrayHasKey(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\equalTo')) { +if (!function_exists('PHPUnit\Framework\equalTo')) { function equalTo($value, float $delta = 0.0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false): IsEqual { return Assert::equalTo(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\attributeEqualTo')) { +if (!function_exists('PHPUnit\Framework\attributeEqualTo')) { function attributeEqualTo(string $attributeName, $value, float $delta = 0.0, int $maxDepth = 10, bool $canonicalize = false, bool $ignoreCase = false): Attribute { return Assert::attributeEqualTo(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\isEmpty')) { +if (!function_exists('PHPUnit\Framework\isEmpty')) { function isEmpty(): IsEmpty { return Assert::isEmpty(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\isWritable')) { +if (!function_exists('PHPUnit\Framework\isWritable')) { function isWritable(): IsWritable { return Assert::isWritable(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\isReadable')) { +if (!function_exists('PHPUnit\Framework\isReadable')) { function isReadable(): IsReadable { return Assert::isReadable(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\directoryExists')) { +if (!function_exists('PHPUnit\Framework\directoryExists')) { function directoryExists(): DirectoryExists { return Assert::directoryExists(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\fileExists')) { +if (!function_exists('PHPUnit\Framework\fileExists')) { function fileExists(): FileExists { return Assert::fileExists(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\greaterThan')) { +if (!function_exists('PHPUnit\Framework\greaterThan')) { function greaterThan($value): GreaterThan { return Assert::greaterThan(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\greaterThanOrEqual')) { +if (!function_exists('PHPUnit\Framework\greaterThanOrEqual')) { function greaterThanOrEqual($value): LogicalOr { return Assert::greaterThanOrEqual(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\classHasAttribute')) { +if (!function_exists('PHPUnit\Framework\classHasAttribute')) { function classHasAttribute(string $attributeName): ClassHasAttribute { return Assert::classHasAttribute(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\classHasStaticAttribute')) { +if (!function_exists('PHPUnit\Framework\classHasStaticAttribute')) { function classHasStaticAttribute(string $attributeName): ClassHasStaticAttribute { return Assert::classHasStaticAttribute(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\objectHasAttribute')) { +if (!function_exists('PHPUnit\Framework\objectHasAttribute')) { function objectHasAttribute($attributeName): ObjectHasAttribute { return Assert::objectHasAttribute(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\identicalTo')) { +if (!function_exists('PHPUnit\Framework\identicalTo')) { function identicalTo($value): IsIdentical { return Assert::identicalTo(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\isInstanceOf')) { +if (!function_exists('PHPUnit\Framework\isInstanceOf')) { function isInstanceOf(string $className): IsInstanceOf { return Assert::isInstanceOf(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\isType')) { +if (!function_exists('PHPUnit\Framework\isType')) { function isType(string $type): IsType { return Assert::isType(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\lessThan')) { +if (!function_exists('PHPUnit\Framework\lessThan')) { function lessThan($value): LessThan { return Assert::lessThan(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\lessThanOrEqual')) { +if (!function_exists('PHPUnit\Framework\lessThanOrEqual')) { function lessThanOrEqual($value): LogicalOr { return Assert::lessThanOrEqual(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\matchesRegularExpression')) { +if (!function_exists('PHPUnit\Framework\matchesRegularExpression')) { function matchesRegularExpression(string $pattern): RegularExpression { return Assert::matchesRegularExpression(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\matches')) { +if (!function_exists('PHPUnit\Framework\matches')) { function matches(string $string): StringMatchesFormatDescription { return Assert::matches(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\stringStartsWith')) { +if (!function_exists('PHPUnit\Framework\stringStartsWith')) { function stringStartsWith($prefix): StringStartsWith { return Assert::stringStartsWith(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\stringContains')) { +if (!function_exists('PHPUnit\Framework\stringContains')) { function stringContains(string $string, bool $case = true): StringContains { return Assert::stringContains(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\stringEndsWith')) { +if (!function_exists('PHPUnit\Framework\stringEndsWith')) { function stringEndsWith(string $suffix): StringEndsWith { return Assert::stringEndsWith(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\countOf')) { +if (!function_exists('PHPUnit\Framework\countOf')) { function countOf(int $count): Count { return Assert::countOf(...\func_get_args()); } } -if (!\function_exists('PHPUnit\Framework\any')) { +if (!function_exists('PHPUnit\Framework\any')) { /** * Returns a matcher that matches when the method is executed * zero or more times. @@ -2876,7 +2876,7 @@ function any(): AnyInvokedCountMatcher } } -if (!\function_exists('PHPUnit\Framework\never')) { +if (!function_exists('PHPUnit\Framework\never')) { /** * Returns a matcher that matches when the method is never executed. */ @@ -2886,7 +2886,7 @@ function never(): InvokedCountMatcher } } -if (!\function_exists('PHPUnit\Framework\atLeast')) { +if (!function_exists('PHPUnit\Framework\atLeast')) { /** * Returns a matcher that matches when the method is executed * at least N times. @@ -2899,7 +2899,7 @@ function atLeast(int $requiredInvocations): InvokedAtLeastCountMatcher } } -if (!\function_exists('PHPUnit\Framework\atLeastOnce')) { +if (!function_exists('PHPUnit\Framework\atLeastOnce')) { /** * Returns a matcher that matches when the method is executed at least once. */ @@ -2909,7 +2909,7 @@ function atLeastOnce(): InvokedAtLeastOnceMatcher } } -if (!\function_exists('PHPUnit\Framework\once')) { +if (!function_exists('PHPUnit\Framework\once')) { /** * Returns a matcher that matches when the method is executed exactly once. */ @@ -2919,7 +2919,7 @@ function once(): InvokedCountMatcher } } -if (!\function_exists('PHPUnit\Framework\exactly')) { +if (!function_exists('PHPUnit\Framework\exactly')) { /** * Returns a matcher that matches when the method is executed * exactly $count times. @@ -2930,7 +2930,7 @@ function exactly(int $count): InvokedCountMatcher } } -if (!\function_exists('PHPUnit\Framework\atMost')) { +if (!function_exists('PHPUnit\Framework\atMost')) { /** * Returns a matcher that matches when the method is executed * at most N times. @@ -2941,7 +2941,7 @@ function atMost(int $allowedInvocations): InvokedAtMostCountMatcher } } -if (!\function_exists('PHPUnit\Framework\at')) { +if (!function_exists('PHPUnit\Framework\at')) { /** * Returns a matcher that matches when the method is executed * at the given index. @@ -2952,35 +2952,35 @@ function at(int $index): InvokedAtIndexMatcher } } -if (!\function_exists('PHPUnit\Framework\returnValue')) { +if (!function_exists('PHPUnit\Framework\returnValue')) { function returnValue($value): ReturnStub { return new ReturnStub($value); } } -if (!\function_exists('PHPUnit\Framework\returnValueMap')) { +if (!function_exists('PHPUnit\Framework\returnValueMap')) { function returnValueMap(array $valueMap): ReturnValueMapStub { return new ReturnValueMapStub($valueMap); } } -if (!\function_exists('PHPUnit\Framework\returnArgument')) { +if (!function_exists('PHPUnit\Framework\returnArgument')) { function returnArgument(int $argumentIndex): ReturnArgumentStub { return new ReturnArgumentStub($argumentIndex); } } -if (!\function_exists('PHPUnit\Framework\returnCallback')) { +if (!function_exists('PHPUnit\Framework\returnCallback')) { function returnCallback($callback): ReturnCallbackStub { return new ReturnCallbackStub($callback); } } -if (!\function_exists('PHPUnit\Framework\returnSelf')) { +if (!function_exists('PHPUnit\Framework\returnSelf')) { /** * Returns the current object. * @@ -2992,14 +2992,14 @@ function returnSelf(): ReturnSelfStub } } -if (!\function_exists('PHPUnit\Framework\throwException')) { +if (!function_exists('PHPUnit\Framework\throwException')) { function throwException(Throwable $exception): ExceptionStub { return new ExceptionStub($exception); } } -if (!\function_exists('PHPUnit\Framework\onConsecutiveCalls')) { +if (!function_exists('PHPUnit\Framework\onConsecutiveCalls')) { function onConsecutiveCalls(): ConsecutiveCallsStub { $args = \func_get_args(); diff --git a/src/Framework/Constraint/ArrayHasKey.php b/src/Framework/Constraint/ArrayHasKey.php index eab5a49e9c5..0ba5be92a40 100644 --- a/src/Framework/Constraint/ArrayHasKey.php +++ b/src/Framework/Constraint/ArrayHasKey.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Framework\Constraint; +use function array_key_exists; +use function is_array; use ArrayAccess; /** @@ -52,8 +54,8 @@ public function toString(): string */ 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 @@ protected function matches($other): bool } /** - * 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. diff --git a/src/Framework/Constraint/ArraySubset.php b/src/Framework/Constraint/ArraySubset.php index a60c26150ed..34c61e3d40d 100644 --- a/src/Framework/Constraint/ArraySubset.php +++ b/src/Framework/Constraint/ArraySubset.php @@ -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 @@ public function __construct(iterable $subset, bool $strict = false) } /** - * 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 @@ public function __construct(iterable $subset, bool $strict = false) * 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 @@ public function evaluate($other, string $description = '', bool $returnResult = $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 @@ public function evaluate($other, string $description = '', bool $returnResult = $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 @@ public function toString(): string } /** - * 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 @@ protected function failureDescription($other): string 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 diff --git a/src/Framework/Constraint/Attribute.php b/src/Framework/Constraint/Attribute.php index 36b05321830..ad4e2f98455 100644 --- a/src/Framework/Constraint/Attribute.php +++ b/src/Framework/Constraint/Attribute.php @@ -31,7 +31,7 @@ public function __construct(Constraint $constraint, string $attributeName) } /** - * 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 @@ public function __construct(Constraint $constraint, string $attributeName) * 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 @@ public function toString(): string } /** - * 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. diff --git a/src/Framework/Constraint/Callback.php b/src/Framework/Constraint/Callback.php index f537d0996aa..7a619b61185 100644 --- a/src/Framework/Constraint/Callback.php +++ b/src/Framework/Constraint/Callback.php @@ -11,14 +11,19 @@ /** * 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 @@ public function toString(): string * 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); } } diff --git a/src/Framework/Constraint/ClassHasAttribute.php b/src/Framework/Constraint/ClassHasAttribute.php index 2a3fd8c0bdb..c42964cf56a 100644 --- a/src/Framework/Constraint/ClassHasAttribute.php +++ b/src/Framework/Constraint/ClassHasAttribute.php @@ -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 @@ public function __construct(string $attributeName) */ public function toString(): string { - return \sprintf( + return sprintf( 'has attribute "%s"', $this->attributeName ); @@ -49,9 +54,9 @@ public function toString(): string 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 @@ protected function matches($other): bool } /** - * 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 @@ protected function matches($other): bool */ 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() ); } diff --git a/src/Framework/Constraint/ClassHasStaticAttribute.php b/src/Framework/Constraint/ClassHasStaticAttribute.php index 8afe69282e0..16e2917f6e6 100644 --- a/src/Framework/Constraint/ClassHasStaticAttribute.php +++ b/src/Framework/Constraint/ClassHasStaticAttribute.php @@ -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 @@ public function toString(): string 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(), diff --git a/src/Framework/Constraint/Composite.php b/src/Framework/Constraint/Composite.php index ffb8ff9f455..c9074ead60c 100644 --- a/src/Framework/Constraint/Composite.php +++ b/src/Framework/Constraint/Composite.php @@ -9,6 +9,7 @@ */ namespace PHPUnit\Framework\Constraint; +use function count; use PHPUnit\Framework\ExpectationFailedException; /** @@ -28,7 +29,7 @@ public function __construct(Constraint $innerConstraint) } /** - * 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 @@ public function __construct(Constraint $innerConstraint) * 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 @@ public function evaluate($other, string $description = '', bool $returnResult = */ public function count(): int { - return \count($this->innerConstraint); + return count($this->innerConstraint); } protected function innerConstraint(): Constraint diff --git a/src/Framework/Constraint/Constraint.php b/src/Framework/Constraint/Constraint.php index de8de05cc09..52972b13253 100644 --- a/src/Framework/Constraint/Constraint.php +++ b/src/Framework/Constraint/Constraint.php @@ -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 @@ protected function matches($other): bool } /** - * 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 @@ protected function fail($other, $description, ComparisonFailure $comparisonFailu } /** - * 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 @@ protected function additionalFailureDescription($other): string } /** - * 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. diff --git a/src/Framework/Constraint/Count.php b/src/Framework/Constraint/Count.php index 3ac1a7c9615..944d90800a9 100644 --- a/src/Framework/Constraint/Count.php +++ b/src/Framework/Constraint/Count.php @@ -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 @@ public function __construct(int $expected) public function toString(): string { - return \sprintf( + return sprintf( 'count matches %d', $this->expectedCount ); @@ -49,11 +54,11 @@ protected function matches($other): bool */ 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 @@ protected function getCountOf($other): ?int } 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 @@ protected function getCountOfGenerator(Generator $generator): int */ protected function failureDescription($other): string { - return \sprintf( + return sprintf( 'actual size %d matches expected size %d', $this->getCountOf($other), $this->expectedCount diff --git a/src/Framework/Constraint/DirectoryExists.php b/src/Framework/Constraint/DirectoryExists.php index fe7ead8c801..ecdad816ff1 100644 --- a/src/Framework/Constraint/DirectoryExists.php +++ b/src/Framework/Constraint/DirectoryExists.php @@ -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 @@ public function toString(): string */ 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 @@ protected function matches($other): bool */ protected function failureDescription($other): string { - return \sprintf( + return sprintf( 'directory "%s" exists', $other ); diff --git a/src/Framework/Constraint/Exception.php b/src/Framework/Constraint/Exception.php index 6a77c1dc458..5119071e04f 100644 --- a/src/Framework/Constraint/Exception.php +++ b/src/Framework/Constraint/Exception.php @@ -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 @@ public function __construct(string $className) */ public function toString(): string { - return \sprintf( + return sprintf( 'exception of type "%s"', $this->className ); @@ -47,7 +49,7 @@ protected function matches($other): bool } /** - * 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 @@ protected function failureDescription($other): string . "\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 ); diff --git a/src/Framework/Constraint/ExceptionCode.php b/src/Framework/Constraint/ExceptionCode.php index d664f5ec4b2..682f48cb367 100644 --- a/src/Framework/Constraint/ExceptionCode.php +++ b/src/Framework/Constraint/ExceptionCode.php @@ -9,6 +9,9 @@ */ namespace PHPUnit\Framework\Constraint; +use function sprintf; +use Throwable; + final class ExceptionCode extends Constraint { /** @@ -33,7 +36,7 @@ public function toString(): string * 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 @@ protected function matches($other): bool } /** - * 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 @@ protected function matches($other): bool */ 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) diff --git a/src/Framework/Constraint/ExceptionMessage.php b/src/Framework/Constraint/ExceptionMessage.php index 18b7a1d7c86..4836b150571 100644 --- a/src/Framework/Constraint/ExceptionMessage.php +++ b/src/Framework/Constraint/ExceptionMessage.php @@ -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 @@ public function toString(): string * 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 @@ protected function matches($other): bool 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 @@ protected function matches($other): bool 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 diff --git a/src/Framework/Constraint/ExceptionMessageRegularExpression.php b/src/Framework/Constraint/ExceptionMessageRegularExpression.php index 747353d3b1e..1b03482f7b1 100644 --- a/src/Framework/Constraint/ExceptionMessageRegularExpression.php +++ b/src/Framework/Constraint/ExceptionMessageRegularExpression.php @@ -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 @@ public function toString(): string * * @param \PHPUnit\Framework\Exception $other * - * @throws \Exception * @throws \PHPUnit\Framework\Exception + * @throws Exception */ protected function matches($other): bool { @@ -51,7 +53,7 @@ protected function matches($other): bool } /** - * 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 @@ protected function matches($other): bool */ protected function failureDescription($other): string { - return \sprintf( + return sprintf( "exception message '%s' matches '%s'", $other->getMessage(), $this->expectedMessageRegExp diff --git a/src/Framework/Constraint/FileExists.php b/src/Framework/Constraint/FileExists.php index b62f9fa3255..8637359a527 100644 --- a/src/Framework/Constraint/FileExists.php +++ b/src/Framework/Constraint/FileExists.php @@ -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 @@ public function toString(): string */ 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 @@ protected function matches($other): bool */ protected function failureDescription($other): string { - return \sprintf( + return sprintf( 'file "%s" exists', $other ); diff --git a/src/Framework/Constraint/IsAnything.php b/src/Framework/Constraint/IsAnything.php index f1a9e7d5555..0407ef1e218 100644 --- a/src/Framework/Constraint/IsAnything.php +++ b/src/Framework/Constraint/IsAnything.php @@ -17,7 +17,7 @@ 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. diff --git a/src/Framework/Constraint/IsEmpty.php b/src/Framework/Constraint/IsEmpty.php index 26db5b456f5..555afa7633c 100644 --- a/src/Framework/Constraint/IsEmpty.php +++ b/src/Framework/Constraint/IsEmpty.php @@ -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 @@ public function toString(): string */ 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 @@ protected function matches($other): bool */ 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() ); diff --git a/src/Framework/Constraint/IsEqual.php b/src/Framework/Constraint/IsEqual.php index 3306de70cd1..bf90a783848 100644 --- a/src/Framework/Constraint/IsEqual.php +++ b/src/Framework/Constraint/IsEqual.php @@ -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 @@ public function __construct($value, float $delta = 0.0, int $maxDepth = 10, bool } /** - * 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 @@ public function evaluate($other, string $description = '', bool $returnResult = } throw new ExpectationFailedException( - \trim($description . "\n" . $f->getMessage()), + trim($description . "\n" . $f->getMessage()), $f ); } @@ -111,25 +115,25 @@ public function toString(): string { $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 '; } - 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 diff --git a/src/Framework/Constraint/IsFinite.php b/src/Framework/Constraint/IsFinite.php index b36f7656e1e..ed727d59787 100644 --- a/src/Framework/Constraint/IsFinite.php +++ b/src/Framework/Constraint/IsFinite.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Framework\Constraint; +use function is_finite; + /** * Constraint that accepts finite. */ @@ -30,6 +32,6 @@ public function toString(): string */ protected function matches($other): bool { - return \is_finite($other); + return is_finite($other); } } diff --git a/src/Framework/Constraint/IsIdentical.php b/src/Framework/Constraint/IsIdentical.php index df3daba5954..ed0d6f4c6f5 100644 --- a/src/Framework/Constraint/IsIdentical.php +++ b/src/Framework/Constraint/IsIdentical.php @@ -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 @@ public function __construct($value) } /** - * 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 @@ public function __construct($value) * 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 @@ public function evaluate($other, string $description = '', bool $returnResult = $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 @@ public function evaluate($other, string $description = '', bool $returnResult = */ 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 @@ public function toString(): string */ 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'; } diff --git a/src/Framework/Constraint/IsInfinite.php b/src/Framework/Constraint/IsInfinite.php index 03b991cf8a6..0ada7f1bdfb 100644 --- a/src/Framework/Constraint/IsInfinite.php +++ b/src/Framework/Constraint/IsInfinite.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Framework\Constraint; +use function is_infinite; + /** * Constraint that accepts infinite. */ @@ -30,6 +32,6 @@ public function toString(): string */ protected function matches($other): bool { - return \is_infinite($other); + return is_infinite($other); } } diff --git a/src/Framework/Constraint/IsInstanceOf.php b/src/Framework/Constraint/IsInstanceOf.php index 1e86461765a..02631f8f469 100644 --- a/src/Framework/Constraint/IsInstanceOf.php +++ b/src/Framework/Constraint/IsInstanceOf.php @@ -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 @@ public function __construct(string $className) */ public function toString(): string { - return \sprintf( + return sprintf( 'is instance of %s "%s"', $this->getType(), $this->className @@ -51,7 +55,7 @@ protected function matches($other): bool } /** - * 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 @@ protected function matches($other): bool */ 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 @@ protected function failureDescription($other): string 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'; diff --git a/src/Framework/Constraint/IsJson.php b/src/Framework/Constraint/IsJson.php index 72316284963..e10e6c1d86b 100644 --- a/src/Framework/Constraint/IsJson.php +++ b/src/Framework/Constraint/IsJson.php @@ -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 @@ protected function matches($other): bool return false; } - \json_decode($other); + json_decode($other); - if (\json_last_error()) { + if (json_last_error()) { return false; } @@ -44,7 +48,7 @@ protected function matches($other): bool } /** - * 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 @@ protected function failureDescription($other): string 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 diff --git a/src/Framework/Constraint/IsNan.php b/src/Framework/Constraint/IsNan.php index cc4563177df..9dde4c6f402 100644 --- a/src/Framework/Constraint/IsNan.php +++ b/src/Framework/Constraint/IsNan.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Framework\Constraint; +use function is_nan; + /** * Constraint that accepts nan. */ @@ -30,6 +32,6 @@ public function toString(): string */ protected function matches($other): bool { - return \is_nan($other); + return is_nan($other); } } diff --git a/src/Framework/Constraint/IsReadable.php b/src/Framework/Constraint/IsReadable.php index c9d56ef9718..bcf8274e845 100644 --- a/src/Framework/Constraint/IsReadable.php +++ b/src/Framework/Constraint/IsReadable.php @@ -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 @@ public function toString(): string */ 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 @@ protected function matches($other): bool */ protected function failureDescription($other): string { - return \sprintf( + return sprintf( '"%s" is readable', $other ); diff --git a/src/Framework/Constraint/IsType.php b/src/Framework/Constraint/IsType.php index 03654f42648..977be34bc12 100644 --- a/src/Framework/Constraint/IsType.php +++ b/src/Framework/Constraint/IsType.php @@ -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 @@ public function __construct(string $type) { 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 @@ public function __construct(string $type) */ public function toString(): string { - return \sprintf( + return sprintf( 'is of type "%s"', $this->type ); @@ -143,57 +158,57 @@ protected function matches($other): bool { 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); } } } diff --git a/src/Framework/Constraint/IsWritable.php b/src/Framework/Constraint/IsWritable.php index 95d3185b2fd..8dd86b562ba 100644 --- a/src/Framework/Constraint/IsWritable.php +++ b/src/Framework/Constraint/IsWritable.php @@ -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 @@ public function toString(): string */ 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 @@ protected function matches($other): bool */ protected function failureDescription($other): string { - return \sprintf( + return sprintf( '"%s" is writable', $other ); diff --git a/src/Framework/Constraint/JsonMatches.php b/src/Framework/Constraint/JsonMatches.php index 0a4f6c2476d..818a0ee3a18 100644 --- a/src/Framework/Constraint/JsonMatches.php +++ b/src/Framework/Constraint/JsonMatches.php @@ -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 @@ public function __construct(string $value) */ public function toString(): string { - return \sprintf( + return sprintf( 'matches JSON string "%s"', $this->value ); @@ -65,15 +67,15 @@ protected function matches($other): bool } /** - * 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 @@ protected function fail($other, $description, ComparisonFailure $comparisonFailu } $comparisonFailure = new ComparisonFailure( - \json_decode($this->value), - \json_decode($other), + json_decode($this->value), + json_decode($other), Json::prettify($recodedValue), Json::prettify($recodedOther), false, diff --git a/src/Framework/Constraint/JsonMatchesErrorMessageProvider.php b/src/Framework/Constraint/JsonMatchesErrorMessageProvider.php index 0c76cad7197..2d28c27618e 100644 --- a/src/Framework/Constraint/JsonMatchesErrorMessageProvider.php +++ b/src/Framework/Constraint/JsonMatchesErrorMessageProvider.php @@ -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 @@ public static function determineJsonError(string $error, string $prefix = ''): ? */ public static function translateTypeToPrefix(string $type): string { - switch (\strtolower($type)) { + switch (strtolower($type)) { case 'expected': $prefix = 'Expected value JSON decode error - '; diff --git a/src/Framework/Constraint/LogicalAnd.php b/src/Framework/Constraint/LogicalAnd.php index 0e9a94b8d83..6714bf69479 100644 --- a/src/Framework/Constraint/LogicalAnd.php +++ b/src/Framework/Constraint/LogicalAnd.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Framework\Constraint; +use function array_values; +use function count; use PHPUnit\Framework\ExpectationFailedException; /** @@ -25,7 +27,7 @@ public static function fromConstraints(Constraint ...$constraints): self { $constraint = new self; - $constraint->constraints = \array_values($constraints); + $constraint->constraints = array_values($constraints); return $constraint; } @@ -52,7 +54,7 @@ public function setConstraints(array $constraints): void } /** - * 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 @@ public function setConstraints(array $constraints): void * 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 @@ public function count(): int $count = 0; foreach ($this->constraints as $constraint) { - $count += \count($constraint); + $count += count($constraint); } return $count; diff --git a/src/Framework/Constraint/LogicalNot.php b/src/Framework/Constraint/LogicalNot.php index 873c5fd22c3..544725281a7 100644 --- a/src/Framework/Constraint/LogicalNot.php +++ b/src/Framework/Constraint/LogicalNot.php @@ -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 @@ public static function negate(string $string): string '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 @@ public static function negate(string $string): string $string ); } else { - $negatedString = \str_replace( + $negatedString = str_replace( $positives, $negatives, $string @@ -87,7 +91,7 @@ public function __construct($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 @@ public function __construct($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 @@ public function evaluate($other, string $description = '', bool $returnResult = */ 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 @@ public function toString(): string */ 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 @@ public function count(): int */ protected function failureDescription($other): string { - switch (\get_class($this->constraint)) { + switch (get_class($this->constraint)) { case LogicalAnd::class: case self::class: case LogicalOr::class: diff --git a/src/Framework/Constraint/LogicalOr.php b/src/Framework/Constraint/LogicalOr.php index 0362d39075f..98bd8664833 100644 --- a/src/Framework/Constraint/LogicalOr.php +++ b/src/Framework/Constraint/LogicalOr.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Framework\Constraint; +use function array_values; +use function count; use PHPUnit\Framework\ExpectationFailedException; /** @@ -25,7 +27,7 @@ public static function fromConstraints(Constraint ...$constraints): self { $constraint = new self; - $constraint->constraints = \array_values($constraints); + $constraint->constraints = array_values($constraints); return $constraint; } @@ -49,7 +51,7 @@ public function setConstraints(array $constraints): void } /** - * 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 @@ public function setConstraints(array $constraints): void * 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 @@ public function count(): int $count = 0; foreach ($this->constraints as $constraint) { - $count += \count($constraint); + $count += count($constraint); } return $count; diff --git a/src/Framework/Constraint/LogicalXor.php b/src/Framework/Constraint/LogicalXor.php index de7f871cfa6..12cfff877d0 100644 --- a/src/Framework/Constraint/LogicalXor.php +++ b/src/Framework/Constraint/LogicalXor.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Framework\Constraint; +use function array_values; +use function count; use PHPUnit\Framework\ExpectationFailedException; /** @@ -25,7 +27,7 @@ public static function fromConstraints(Constraint ...$constraints): self { $constraint = new self; - $constraint->constraints = \array_values($constraints); + $constraint->constraints = array_values($constraints); return $constraint; } @@ -49,7 +51,7 @@ public function setConstraints(array $constraints): void } /** - * 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 @@ public function setConstraints(array $constraints): void * 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 @@ public function count(): int $count = 0; foreach ($this->constraints as $constraint) { - $count += \count($constraint); + $count += count($constraint); } return $count; diff --git a/src/Framework/Constraint/RegularExpression.php b/src/Framework/Constraint/RegularExpression.php index 178b637dc5b..963bfd05d17 100644 --- a/src/Framework/Constraint/RegularExpression.php +++ b/src/Framework/Constraint/RegularExpression.php @@ -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 @@ public function __construct(string $pattern) */ public function toString(): string { - return \sprintf( + return sprintf( 'matches PCRE pattern "%s"', $this->pattern ); @@ -49,6 +52,6 @@ public function toString(): string */ protected function matches($other): bool { - return \preg_match($this->pattern, $other) > 0; + return preg_match($this->pattern, $other) > 0; } } diff --git a/src/Framework/Constraint/StringContains.php b/src/Framework/Constraint/StringContains.php index 791fccc4d3c..54606364c64 100644 --- a/src/Framework/Constraint/StringContains.php +++ b/src/Framework/Constraint/StringContains.php @@ -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 @@ public function __construct(string $string, bool $ignoreCase = false) 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 @@ protected function matches($other): bool } 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; } } diff --git a/src/Framework/Constraint/StringEndsWith.php b/src/Framework/Constraint/StringEndsWith.php index c4c3c143817..ed11b01d17d 100644 --- a/src/Framework/Constraint/StringEndsWith.php +++ b/src/Framework/Constraint/StringEndsWith.php @@ -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 @@ public function toString(): string */ protected function matches($other): bool { - return \substr($other, 0 - \strlen($this->suffix)) === $this->suffix; + return substr($other, 0 - strlen($this->suffix)) === $this->suffix; } } diff --git a/src/Framework/Constraint/StringMatchesFormatDescription.php b/src/Framework/Constraint/StringMatchesFormatDescription.php index ab7e622fe6c..f2324bb3f44 100644 --- a/src/Framework/Constraint/StringMatchesFormatDescription.php +++ b/src/Framework/Constraint/StringMatchesFormatDescription.php @@ -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 @@ protected function failureDescription($other): string 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 @@ private function createPatternFromFormat(string $string): string private function convertNewlines($text): string { - return \preg_replace('/\r\n/', "\n", $text); + return preg_replace('/\r\n/', "\n", $text); } } diff --git a/src/Framework/Constraint/StringStartsWith.php b/src/Framework/Constraint/StringStartsWith.php index 27c100a0cf8..a80a3f6b004 100644 --- a/src/Framework/Constraint/StringStartsWith.php +++ b/src/Framework/Constraint/StringStartsWith.php @@ -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 @@ public function toString(): string */ protected function matches($other): bool { - return \strpos((string) $other, $this->prefix) === 0; + return strpos((string) $other, $this->prefix) === 0; } } diff --git a/src/Framework/Constraint/TraversableContains.php b/src/Framework/Constraint/TraversableContains.php index be663177af1..1cae5a30659 100644 --- a/src/Framework/Constraint/TraversableContains.php +++ b/src/Framework/Constraint/TraversableContains.php @@ -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 @@ public function __construct($value, bool $checkForObjectIdentity = true, bool $c */ 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 @@ protected function matches($other): bool 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 @@ protected function matches($other): bool } /** - * 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 @@ protected function matches($other): bool */ 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() ); } diff --git a/src/Framework/Constraint/TraversableContainsEqual.php b/src/Framework/Constraint/TraversableContainsEqual.php index 495795e394b..1357332f180 100644 --- a/src/Framework/Constraint/TraversableContainsEqual.php +++ b/src/Framework/Constraint/TraversableContainsEqual.php @@ -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 @@ public function __construct($value) */ 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 @@ protected function matches($other): bool } /** - * 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 @@ protected function matches($other): bool */ 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() ); } diff --git a/src/Framework/Constraint/TraversableContainsIdentical.php b/src/Framework/Constraint/TraversableContainsIdentical.php index aead4b13dd4..b455629acb7 100644 --- a/src/Framework/Constraint/TraversableContainsIdentical.php +++ b/src/Framework/Constraint/TraversableContainsIdentical.php @@ -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 @@ public function __construct($value) */ 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 @@ protected function matches($other): bool } /** - * 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 @@ protected function matches($other): bool */ 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() ); } diff --git a/src/Framework/Constraint/TraversableContainsOnly.php b/src/Framework/Constraint/TraversableContainsOnly.php index 2191ae668be..a78cfcd8fe2 100644 --- a/src/Framework/Constraint/TraversableContainsOnly.php +++ b/src/Framework/Constraint/TraversableContainsOnly.php @@ -44,7 +44,7 @@ public function __construct(string $type, bool $isNativeType = true) } /** - * 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 @@ public function __construct(string $type, bool $isNativeType = true) * 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) { diff --git a/src/Framework/DataProviderTestSuite.php b/src/Framework/DataProviderTestSuite.php index a65dc34c372..2769a2dc2ed 100644 --- a/src/Framework/DataProviderTestSuite.php +++ b/src/Framework/DataProviderTestSuite.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Framework; +use function count; +use function explode; use PHPUnit\Util\Test as TestUtil; /** @@ -44,17 +46,17 @@ public function getDependencies(): array 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); } diff --git a/src/Framework/Exception/Exception.php b/src/Framework/Exception/Exception.php index 838c736d2eb..0b21e6de300 100644 --- a/src/Framework/Exception/Exception.php +++ b/src/Framework/Exception/Exception.php @@ -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 @@ * * @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 @@ public function __toString(): string public function __sleep(): array { - return \array_keys(\get_object_vars($this)); + return array_keys(get_object_vars($this)); } /** diff --git a/src/Framework/Exception/ExpectationFailedException.php b/src/Framework/Exception/ExpectationFailedException.php index f7d7a9c7453..b9a595a88c4 100644 --- a/src/Framework/Exception/ExpectationFailedException.php +++ b/src/Framework/Exception/ExpectationFailedException.php @@ -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; diff --git a/src/Framework/Exception/InvalidArgumentException.php b/src/Framework/Exception/InvalidArgumentException.php index b3fa7d35f44..aec29f432a4 100644 --- a/src/Framework/Exception/InvalidArgumentException.php +++ b/src/Framework/Exception/InvalidArgumentException.php @@ -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 ) ); diff --git a/src/Framework/ExceptionWrapper.php b/src/Framework/ExceptionWrapper.php index 130525e4b24..ec7415372eb 100644 --- a/src/Framework/ExceptionWrapper.php +++ b/src/Framework/ExceptionWrapper.php @@ -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 @@ public function setOriginalException(Throwable $t): void { $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 @@ public function getOriginalException(): ?Throwable /** * 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; diff --git a/src/Framework/IncompleteTestCase.php b/src/Framework/IncompleteTestCase.php index e6562485747..ee1e3e9fe03 100644 --- a/src/Framework/IncompleteTestCase.php +++ b/src/Framework/IncompleteTestCase.php @@ -29,11 +29,6 @@ final class IncompleteTestCase extends TestCase */ protected $runTestInSeparateProcess = false; - /** - * @var bool - */ - protected $useErrorHandler = false; - /** * @var string */ diff --git a/src/Framework/MockObject/Api/Method.php b/src/Framework/MockObject/Api/Method.php index 77d17701ce6..f6df7533c1f 100644 --- a/src/Framework/MockObject/Api/Method.php +++ b/src/Framework/MockObject/Api/Method.php @@ -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 @@ public function method() { $expects = $this->expects(new AnyInvokedCount); - return \call_user_func_array( + return call_user_func_array( [$expects, 'method'], - \func_get_args() + func_get_args() ); } } diff --git a/src/Framework/MockObject/Builder/InvocationMocker.php b/src/Framework/MockObject/Builder/InvocationMocker.php index 717002537cf..ee4dd20a667 100644 --- a/src/Framework/MockObject/Builder/InvocationMocker.php +++ b/src/Framework/MockObject/Builder/InvocationMocker.php @@ -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\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 @@ public function will(Stub $stub): Identity 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 @@ public function willReturnOnConsecutiveCalls(...$values): self return $this->will($stub); } - public function willThrowException(\Throwable $exception): self + public function willThrowException(Throwable $exception): self { $stub = new Exception($exception); @@ -205,16 +216,16 @@ public function method($constraint): self ); } - $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 @@ private function ensureTypeOfReturnValues(array $values): void 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() ) ); diff --git a/src/Framework/MockObject/Builder/InvocationStubber.php b/src/Framework/MockObject/Builder/InvocationStubber.php index cb2e0ac22c9..c0e51b00e75 100644 --- a/src/Framework/MockObject/Builder/InvocationStubber.php +++ b/src/Framework/MockObject/Builder/InvocationStubber.php @@ -10,6 +10,7 @@ namespace PHPUnit\Framework\MockObject\Builder; use PHPUnit\Framework\MockObject\Stub\Stub; +use Throwable; interface InvocationStubber { @@ -57,5 +58,5 @@ public function willReturnSelf()/*: self */; public function willReturnOnConsecutiveCalls(...$values)/*: self */; /** @return self */ - public function willThrowException(\Throwable $exception)/*: self */; + public function willThrowException(Throwable $exception)/*: self */; } diff --git a/src/Framework/MockObject/Builder/Match.php b/src/Framework/MockObject/Builder/Match_.php similarity index 95% rename from src/Framework/MockObject/Builder/Match.php rename to src/Framework/MockObject/Builder/Match_.php index d343eacfb80..6cec73ae97d 100644 --- a/src/Framework/MockObject/Builder/Match.php +++ b/src/Framework/MockObject/Builder/Match_.php @@ -12,7 +12,7 @@ /** * @internal This class is not covered by the backward compatibility promise for PHPUnit */ -interface Match extends Stub +interface Match_ extends Stub { /** * Defines the expectation which must occur before the current is valid. diff --git a/src/Framework/MockObject/Builder/ParametersMatch.php b/src/Framework/MockObject/Builder/ParametersMatch.php index ae16d79882a..6f5fecdd31c 100644 --- a/src/Framework/MockObject/Builder/ParametersMatch.php +++ b/src/Framework/MockObject/Builder/ParametersMatch.php @@ -12,7 +12,7 @@ /** * @internal This class is not covered by the backward compatibility promise for PHPUnit */ -interface ParametersMatch extends Match +interface ParametersMatch extends Match_ { /** * Sets the parameters to match for, each parameter to this function will diff --git a/src/Framework/MockObject/Exception/Exception.php b/src/Framework/MockObject/Exception/Exception.php index 7307fbaea86..5880bc033ec 100644 --- a/src/Framework/MockObject/Exception/Exception.php +++ b/src/Framework/MockObject/Exception/Exception.php @@ -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 { } diff --git a/src/Framework/MockObject/Generator.php b/src/Framework/MockObject/Generator.php index a0b16710647..e0e1d5bc360 100644 --- a/src/Framework/MockObject/Generator.php +++ b/src/Framework/MockObject/Generator.php @@ -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 @@ public function getMock($type, $methods = [], array $arguments = [], string $moc $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 @@ static function ($type) { } 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 @@ static function ($type) { 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 @@ static function ($type) { } } - 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 @@ static function ($type) { if (!$reflector->implementsInterface(MockObject::class)) { throw new RuntimeException( - \sprintf( + sprintf( 'Class "%s" already exists.', $mockClassName ) @@ -183,7 +228,7 @@ static function ($type) { /** * 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 $originalClassName @@ -193,12 +238,12 @@ static function ($type) { */ 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 @@ public function getMockForAbstractClass(string $originalClassName, array $argume $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 @@ public function getMockForAbstractClass(string $originalClassName, array $argume } throw new RuntimeException( - \sprintf('Class "%s" does not exist.', $originalClassName) + sprintf('Class "%s" does not exist.', $originalClassName) ); } @@ -245,9 +290,9 @@ public function getMockForAbstractClass(string $originalClassName, array $argume */ 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 @@ public function getMockForTrait(string $traitName, array $arguments = [], string */ 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 @@ public function getObjectForTrait(string $traitName, string $traitClassName = '' 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 @@ public function generate($type, array $methods = null, string $mockClassName = ' ); } - $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 @@ public function generate($type, array $methods = null, string $mockClassName = ' */ 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 @@ public function generateClassFromWsdl(string $wsdlFile, string $className, array ); } - \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 @@ public function generateClassFromWsdl(string $wsdlFile, string $className, array $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 @@ public function generateClassFromWsdl(string $wsdlFile, string $className, array 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 @@ public function getClassMethods(string $className): array 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 @@ public function mockClassMethods(string $className, bool $callOriginalMethods, b 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 @@ public function mockInterfaceMethods(string $interfaceName, bool $cloneArguments /** * @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 @@ private function getObject(MockType $mockClass, $type = '', bool $callOriginalCo $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 @@ private function getObject(MockType $mockClass, $type = '', bool $callOriginalCo } 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 @@ private function generateMock($type, ?array $explicitMethods, string $mockClassN $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 @@ private function generateMock($type, ?array $explicitMethods, string $mockClassN $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 @@ private function generateMock($type, ?array $explicitMethods, string $mockClassN // @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 @@ private function generateMock($type, ?array $explicitMethods, string $mockClassN try { $methodReflection = $typeClass->getMethod($method); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new RuntimeException( $e->getMessage(), (int) $e->getCode(), @@ -714,9 +765,9 @@ private function generateMock($type, ?array $explicitMethods, string $mockClassN '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 @@ private function generateMock($type, ?array $explicitMethods, string $mockClassN $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 @@ private function generateMock($type, ?array $explicitMethods, string $mockClassN if ($class->isFinal()) { throw new RuntimeException( - \sprintf( + sprintf( 'Class "%s" is declared "final" and cannot be mocked.', $mockClassName['fullClassName'] ) @@ -755,15 +806,15 @@ private function generateMock($type, ?array $explicitMethods, string $mockClassN } // @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 @@ private function generateMock($type, ?array $explicitMethods, string $mockClassN try { $classMethod = $class->getMethod($methodName); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new RuntimeException( $e->getMessage(), (int) $e->getCode(), @@ -806,13 +857,13 @@ private function generateMock($type, ?array $explicitMethods, string $mockClassN } // @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 @@ private function generateMock($type, ?array $explicitMethods, string $mockClassN try { $cloneMethod = $class->getMethod('__clone'); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new RuntimeException( $e->getMessage(), (int) $e->getCode(), @@ -853,13 +904,13 @@ private function generateMock($type, ?array $explicitMethods, string $mockClassN ); } - 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 @@ private function generateMock($type, ?array $explicitMethods, string $mockClassN $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 @@ private function generateMock($type, ?array $explicitMethods, string $mockClassN */ 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 @@ private function generateClassName($type, string $className, string $prefix): ar 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 @@ private function generateMockClassDeclaration(array $mockClassName, bool $isInte $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 @@ private function generateMockClassDeclaration(array $mockClassName, bool $isInte $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 @@ private function generateMockClassDeclaration(array $mockClassName, bool $isInte 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 @@ private function isMethodNameBlacklisted(string $name): bool 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 @@ private function getTemplate(string $template): \Text_Template /** * @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; } diff --git a/src/Framework/MockObject/Invocation.php b/src/Framework/MockObject/Invocation.php index 228cf0d88dd..bedfebf1be3 100644 --- a/src/Framework/MockObject/Invocation.php +++ b/src/Framework/MockObject/Invocation.php @@ -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 @@ public function __construct(string $className, string $methodName, array $parame $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 @@ public function __construct(string $className, string $methodName, array $parame } foreach ($this->parameters as $key => $value) { - if (\is_object($value)) { + if (is_object($value)) { $this->parameters[$key] = $this->cloneObject($value); } } @@ -111,7 +120,7 @@ public function generateReturnValue() return; } - switch (\strtolower($this->returnType)) { + switch (strtolower($this->returnType)) { case '': case 'void': return; @@ -132,11 +141,11 @@ public function generateReturnValue() 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 @@ public function toString(): string { $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) : '' ); } diff --git a/src/Framework/MockObject/InvocationHandler.php b/src/Framework/MockObject/InvocationHandler.php index cd1ea0d622d..77d7825a236 100644 --- a/src/Framework/MockObject/InvocationHandler.php +++ b/src/Framework/MockObject/InvocationHandler.php @@ -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 @@ public function invoke(Invocation $invocation) 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 ''; diff --git a/src/Framework/MockObject/Matcher.php b/src/Framework/MockObject/Matcher.php index 6179eeb30f4..2b1cd8c86cf 100644 --- a/src/Framework/MockObject/Matcher.php +++ b/src/Framework/MockObject/Matcher.php @@ -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 @@ public function setAfterMatchBuilderId(string $id): void } /** - * @throws \Exception - * @throws RuntimeException + * @throws Exception * @throws ExpectationFailedException + * @throws RuntimeException */ public function invoked(Invocation $invocation) { @@ -117,13 +121,13 @@ public function invoked(Invocation $invocation) 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 @@ public function invoked(Invocation $invocation) } } 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 @@ public function invoked(Invocation $invocation) } /** - * @throws RuntimeException - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException + * @throws RuntimeException */ public function matches(Invocation $invocation): bool { @@ -169,13 +173,13 @@ public function matches(Invocation $invocation): bool 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 @@ public function matches(Invocation $invocation): bool } } 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 @@ public function matches(Invocation $invocation): bool } /** - * @throws RuntimeException - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException + * @throws RuntimeException */ public function verify(): void { @@ -235,7 +239,7 @@ public function verify(): void } } 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 @@ public function toString(): string $list[] = 'will ' . $this->stub->toString(); } - return \implode(' ', $list); + return implode(' ', $list); } } diff --git a/src/Framework/MockObject/MethodNameConstraint.php b/src/Framework/MockObject/MethodNameConstraint.php index 18e57724002..3082ab384c9 100644 --- a/src/Framework/MockObject/MethodNameConstraint.php +++ b/src/Framework/MockObject/MethodNameConstraint.php @@ -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 @@ public function __construct(string $methodName) public function toString(): string { - return \sprintf( + return sprintf( 'is "%s"', $this->methodName ); @@ -36,10 +39,10 @@ public function toString(): string 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); } } diff --git a/src/Framework/MockObject/MockBuilder.php b/src/Framework/MockObject/MockBuilder.php index 3eeb36a0b60..6ff2b264ed2 100644 --- a/src/Framework/MockObject/MockBuilder.php +++ b/src/Framework/MockObject/MockBuilder.php @@ -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 @@ public function setMethods(?array $methods = null): self 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 @@ public function onlyMethods(array $methods): self } 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 @@ public function onlyMethods(array $methods): self 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 @@ public function onlyMethods(array $methods): self } } - $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 @@ public function addMethods(array $methods): self } 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 @@ public function addMethods(array $methods): self 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 @@ public function addMethods(array $methods): self } } - $this->methods = \array_merge($this->methods ?? [], $methods); + $this->methods = array_merge($this->methods ?? [], $methods); return $this; } @@ -300,7 +305,7 @@ public function addMethods(array $methods): self public function setMethodsExcept(array $methods = []): self { return $this->setMethods( - \array_diff( + array_diff( $this->generator->getClassMethods($this->type), $methods ) diff --git a/src/Framework/MockObject/MockClass.php b/src/Framework/MockObject/MockClass.php index 938db87fa9e..4aaac1b4315 100644 --- a/src/Framework/MockObject/MockClass.php +++ b/src/Framework/MockObject/MockClass.php @@ -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 @@ public function __construct(string $classCode, string $mockName, array $configur 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', diff --git a/src/Framework/MockObject/MockMethod.php b/src/Framework/MockObject/MockMethod.php index a5efa7aca8e..1aa728f1a95 100644 --- a/src/Framework/MockObject/MockMethod.php +++ b/src/Framework/MockObject/MockMethod.php @@ -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 @@ 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 @@ public static function fromReflection(\ReflectionMethod $method, bool $callOrigi $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; } @@ -121,8 +134,8 @@ public static function fromReflection(\ReflectionMethod $method, bool $callOrigi $method->getName(), $cloneArguments, $modifier, - self::getMethodParameters($method), - self::getMethodParameters($method, true), + self::getMethodParametersForDeclaration($method), + self::getMethodParametersForCall($method), self::deriveReturnType($method), $reference, $callOriginalMethod, @@ -179,12 +192,12 @@ public function generateCode(): string 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 @@ public function generateCode(): string $deprecationTemplate = $this->getTemplate('deprecation.tpl'); $deprecationTemplate->setVar([ - 'deprecation' => \var_export($deprecation, true), + 'deprecation' => var_export($deprecation, true), ]); $deprecation = $deprecationTemplate->render(); @@ -210,7 +223,7 @@ public function generateCode(): string '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 @@ public function getReturnType(): Type 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 @@ private function getTemplate(string $template): \Text_Template * * @throws RuntimeException */ - private static function getMethodParameters(\ReflectionMethod $method, bool $forCall = false): string + private static function getMethodParametersForDeclaration(ReflectionMethod $method): string { $parameters = []; @@ -258,71 +271,38 @@ private static function getMethodParameters(\ReflectionMethod $method, bool $for $name = '$arg' . $i; } - if ($parameter->isVariadic()) { - if ($forCall) { - continue; - } - - $name = '...' . $name; - } - $nullable = ''; $default = ''; $reference = ''; $typeDeclaration = ''; + $type = null; + $typeName = null; - if (!$forCall) { - if ($parameter->hasType() && $parameter->allowsNull()) { - $nullable = '?'; + if ($parameter->hasType()) { + $type = $parameter->getType(); + + if ($type instanceof ReflectionNamedType) { + $typeName = $type->getName(); } + } + + if ($parameter->isVariadic()) { + $name = '...' . $name; + } elseif ($parameter->isDefaultValueAvailable()) { + $default = ' = ' . var_export($parameter->getDefaultValue(), true); + } elseif ($parameter->isOptional()) { + $default = ' = null'; + } - if ($parameter->hasType()) { - $type = $parameter->getType(); - - if ($type instanceof \ReflectionNamedType && $type->getName() !== 'self') { - $typeDeclaration = $type->getName() . ' '; - } else { - try { - $class = $parameter->getClass(); - // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { - throw new RuntimeException( - \sprintf( - 'Cannot mock %s::%s() because a class or ' . - 'interface used in the signature is not loaded', - $method->getDeclaringClass()->getName(), - $method->getName() - ), - 0, - $e - ); - } - // @codeCoverageIgnoreEnd - - if ($class !== null) { - $typeDeclaration = $class->getName() . ' '; - } - } + if ($type !== null) { + if ($typeName !== 'mixed' && $parameter->allowsNull()) { + $nullable = '?'; } - if (!$parameter->isVariadic()) { - if ($parameter->isDefaultValueAvailable()) { - try { - $value = \var_export($parameter->getDefaultValue(), true); - // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { - throw new RuntimeException( - $e->getMessage(), - (int) $e->getCode(), - $e - ); - } - // @codeCoverageIgnoreEnd - - $default = ' = ' . $value; - } elseif ($parameter->isOptional()) { - $default = ' = null'; - } + if ($typeName === 'self') { + $typeDeclaration = $method->getDeclaringClass()->getName() . ' '; + } elseif ($typeName !== null) { + $typeDeclaration = $typeName . ' '; } } @@ -333,10 +313,43 @@ private static function getMethodParameters(\ReflectionMethod $method, bool $for $parameters[] = $nullable . $typeDeclaration . $reference . $name . $default; } - return \implode(', ', $parameters); + return implode(', ', $parameters); + } + + /** + * Returns the parameters of a function or method. + * + * @throws ReflectionException + */ + private static function getMethodParametersForCall(ReflectionMethod $method): string + { + $parameters = []; + + foreach ($method->getParameters() as $i => $parameter) { + $name = '$' . $parameter->getName(); + + /* Note: PHP extensions may use empty names for reference arguments + * or "..." for methods taking a variable number of arguments. + */ + if ($name === '$' || $name === '$...') { + $name = '$arg' . $i; + } + + if ($parameter->isVariadic()) { + continue; + } + + if ($parameter->isPassedByReference()) { + $parameters[] = '&' . $name; + } else { + $parameters[] = $name; + } + } + + return implode(', ', $parameters); } - private static function deriveReturnType(\ReflectionMethod $method): Type + private static function deriveReturnType(ReflectionMethod $method): Type { $returnType = $method->getReturnType(); @@ -355,7 +368,7 @@ private static function deriveReturnType(\ReflectionMethod $method): Type 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(), diff --git a/src/Framework/MockObject/MockMethodSet.php b/src/Framework/MockObject/MockMethodSet.php index 939437e23a9..1c78963c08b 100644 --- a/src/Framework/MockObject/MockMethodSet.php +++ b/src/Framework/MockObject/MockMethodSet.php @@ -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 @@ public function addMethods(MockMethod ...$methods): void */ 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); } } diff --git a/src/Framework/MockObject/MockTrait.php b/src/Framework/MockObject/MockTrait.php index 3ced88991f6..7b9f45003cb 100644 --- a/src/Framework/MockObject/MockTrait.php +++ b/src/Framework/MockObject/MockTrait.php @@ -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 @@ public function __construct(string $classCode, string $mockName) public function generate(): string { - if (!\class_exists($this->mockName, false)) { + if (!class_exists($this->mockName, false)) { eval($this->classCode); } diff --git a/src/Framework/MockObject/Rule/ConsecutiveParameters.php b/src/Framework/MockObject/Rule/ConsecutiveParameters.php index 3a1f52828c5..9cb8137d1b8 100644 --- a/src/Framework/MockObject/Rule/ConsecutiveParameters.php +++ b/src/Framework/MockObject/Rule/ConsecutiveParameters.php @@ -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 @@ public function toString(): string } /** - * @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 @@ public function verify(): void } /** - * 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 @@ private function verifyInvocation(BaseInvocation $invocation, $callIndex): void $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 @@ private function verifyInvocation(BaseInvocation $invocation, $callIndex): void foreach ($parameters as $i => $parameter) { $parameter->evaluate( $invocation->getParameters()[$i], - \sprintf( + sprintf( 'Parameter %s for invocation #%d %s does not match expected ' . 'value.', $i, diff --git a/src/Framework/MockObject/Rule/InvocationOrder.php b/src/Framework/MockObject/Rule/InvocationOrder.php index 1df95e578d4..90aa49350de 100644 --- a/src/Framework/MockObject/Rule/InvocationOrder.php +++ b/src/Framework/MockObject/Rule/InvocationOrder.php @@ -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) diff --git a/src/Framework/MockObject/Rule/InvokedAtIndex.php b/src/Framework/MockObject/Rule/InvokedAtIndex.php index 070ffee36a7..3d8446c9398 100644 --- a/src/Framework/MockObject/Rule/InvokedAtIndex.php +++ b/src/Framework/MockObject/Rule/InvokedAtIndex.php @@ -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 @@ public function verify(): void { if ($this->currentIndex < $this->sequenceIndex) { throw new ExpectationFailedException( - \sprintf( + sprintf( 'The expected invocation at index %s was never reached.', $this->sequenceIndex ) diff --git a/src/Framework/MockObject/Rule/InvokedCount.php b/src/Framework/MockObject/Rule/InvokedCount.php index 37beffc4d95..188326c91f5 100644 --- a/src/Framework/MockObject/Rule/InvokedCount.php +++ b/src/Framework/MockObject/Rule/InvokedCount.php @@ -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 @@ public function verify(): void 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 @@ protected function invokedDo(BaseInvocation $invocation): void break; default: - $message .= \sprintf( + $message .= sprintf( 'was not expected to be called more than %d times.', $this->expectedCount ); diff --git a/src/Framework/MockObject/Rule/MethodName.php b/src/Framework/MockObject/Rule/MethodName.php index efca2ba8b65..39fb3333262 100644 --- a/src/Framework/MockObject/Rule/MethodName.php +++ b/src/Framework/MockObject/Rule/MethodName.php @@ -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); } diff --git a/src/Framework/MockObject/Rule/Parameters.php b/src/Framework/MockObject/Rule/Parameters.php index 2fa58c61520..3f1cc53ae0d 100644 --- a/src/Framework/MockObject/Rule/Parameters.php +++ b/src/Framework/MockObject/Rule/Parameters.php @@ -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 @@ public function toString(): string } /** - * @throws \Exception + * @throws Exception */ public function apply(BaseInvocation $invocation): void { @@ -88,8 +92,8 @@ public function apply(BaseInvocation $invocation): void * 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 @@ public function verify(): void } /** - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ private function doVerify(): bool { @@ -110,27 +114,27 @@ private function doVerify(): bool 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, diff --git a/src/Framework/MockObject/Stub/ConsecutiveCalls.php b/src/Framework/MockObject/Stub/ConsecutiveCalls.php index d1d7bdb36dd..0dcf386b3fb 100644 --- a/src/Framework/MockObject/Stub/ConsecutiveCalls.php +++ b/src/Framework/MockObject/Stub/ConsecutiveCalls.php @@ -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 @@ public function __construct(array $stack) 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 @@ public function toString(): string { $exporter = new Exporter; - return \sprintf( + return sprintf( 'return user-specified value %s', $exporter->export($this->value) ); diff --git a/src/Framework/MockObject/Stub/Exception.php b/src/Framework/MockObject/Stub/Exception.php index 11913c6dddb..5d64c96a500 100644 --- a/src/Framework/MockObject/Stub/Exception.php +++ b/src/Framework/MockObject/Stub/Exception.php @@ -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 @@ public function toString(): string { $exporter = new Exporter; - return \sprintf( + return sprintf( 'raise user-specified exception %s', $exporter->export($this->exception) ); diff --git a/src/Framework/MockObject/Stub/ReturnArgument.php b/src/Framework/MockObject/Stub/ReturnArgument.php index bf0af3fe240..c7b3f8f410a 100644 --- a/src/Framework/MockObject/Stub/ReturnArgument.php +++ b/src/Framework/MockObject/Stub/ReturnArgument.php @@ -9,6 +9,7 @@ */ namespace PHPUnit\Framework\MockObject\Stub; +use function sprintf; use PHPUnit\Framework\MockObject\Invocation; /** @@ -35,6 +36,6 @@ public function invoke(Invocation $invocation) public function toString(): string { - return \sprintf('return argument #%d', $this->argumentIndex); + return sprintf('return argument #%d', $this->argumentIndex); } } diff --git a/src/Framework/MockObject/Stub/ReturnCallback.php b/src/Framework/MockObject/Stub/ReturnCallback.php index aa6dffbc22d..e02181e90b5 100644 --- a/src/Framework/MockObject/Stub/ReturnCallback.php +++ b/src/Framework/MockObject/Stub/ReturnCallback.php @@ -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 @@ public function __construct($callback) 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, diff --git a/src/Framework/MockObject/Stub/ReturnReference.php b/src/Framework/MockObject/Stub/ReturnReference.php index 0dd9476de8b..0d288cebe07 100644 --- a/src/Framework/MockObject/Stub/ReturnReference.php +++ b/src/Framework/MockObject/Stub/ReturnReference.php @@ -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 @@ public function toString(): string { $exporter = new Exporter; - return \sprintf( + return sprintf( 'return user-specified reference %s', $exporter->export($this->reference) ); diff --git a/src/Framework/MockObject/Stub/ReturnStub.php b/src/Framework/MockObject/Stub/ReturnStub.php index caaf4bc2811..fbcd0a07a80 100644 --- a/src/Framework/MockObject/Stub/ReturnStub.php +++ b/src/Framework/MockObject/Stub/ReturnStub.php @@ -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 @@ public function toString(): string { $exporter = new Exporter; - return \sprintf( + return sprintf( 'return user-specified value %s', $exporter->export($this->value) ); diff --git a/src/Framework/MockObject/Stub/ReturnValueMap.php b/src/Framework/MockObject/Stub/ReturnValueMap.php index b44035a70fa..5fcd3a09adf 100644 --- a/src/Framework/MockObject/Stub/ReturnValueMap.php +++ b/src/Framework/MockObject/Stub/ReturnValueMap.php @@ -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 @@ public function __construct(array $valueMap) 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; diff --git a/src/Framework/SkippedTestCase.php b/src/Framework/SkippedTestCase.php index b88dca362ee..51c00619c54 100644 --- a/src/Framework/SkippedTestCase.php +++ b/src/Framework/SkippedTestCase.php @@ -29,11 +29,6 @@ final class SkippedTestCase extends TestCase */ protected $runTestInSeparateProcess = false; - /** - * @var bool - */ - protected $useErrorHandler = false; - /** * @var string */ diff --git a/src/Framework/TestBuilder.php b/src/Framework/TestBuilder.php index a4b9ab55b3a..583a9f2c485 100644 --- a/src/Framework/TestBuilder.php +++ b/src/Framework/TestBuilder.php @@ -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 @@ public function build(\ReflectionClass $theClass, string $methodName): Test $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 @@ public function build(\ReflectionClass $theClass, string $methodName): Test $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 @@ public function build(\ReflectionClass $theClass, string $methodName): Test $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 @@ public function build(\ReflectionClass $theClass, string $methodName): Test ); $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 @@ private function buildDataProviderTestSuite( 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 @@ private function configureTestCase( } } - private function throwableToString(\Throwable $t): string + private function throwableToString(Throwable $t): string { $message = $t->getMessage(); - if (empty(\trim($message))) { + if (empty(trim($message))) { $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) ); diff --git a/src/Framework/TestCase.php b/src/Framework/TestCase.php index 756ff419c59..1223ca0c857 100644 --- a/src/Framework/TestCase.php +++ b/src/Framework/TestCase.php @@ -9,11 +9,64 @@ */ 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; use PHPUnit\Framework\Constraint\ExceptionMessage; use PHPUnit\Framework\Constraint\ExceptionMessageRegularExpression; +use PHPUnit\Framework\Constraint\LogicalOr; use PHPUnit\Framework\Error\Deprecated; use PHPUnit\Framework\Error\Error; use PHPUnit\Framework\Error\Notice; @@ -46,6 +99,8 @@ 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 +109,12 @@ 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 +432,7 @@ public static function returnSelf(): ReturnSelfStub return new ReturnSelfStub; } - public static function throwException(\Throwable $exception): ExceptionStub + public static function throwException(Throwable $exception): ExceptionStub { return new ExceptionStub($exception); } @@ -438,9 +495,9 @@ protected function tearDown(): void 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 +506,7 @@ public function toString(): string } // @codeCoverageIgnoreEnd - $buffer = \sprintf( + $buffer = sprintf( '%s::%s', $class->name, $this->getName(false) @@ -523,7 +580,7 @@ public function expectExceptionMessageRegExp(string $regularExpression): void */ 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 +676,14 @@ public function hasFailed(): bool * 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 +705,9 @@ public function run(TestResult $result = null): TestResult $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 +717,11 @@ public function run(TestResult $result = null): TestResult // @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 +735,7 @@ public function run(TestResult $result = null): TestResult $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 +751,14 @@ public function run(TestResult $result = null): TestResult $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 +769,11 @@ public function run(TestResult $result = null): TestResult $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 +836,7 @@ public function run(TestResult $result = null): TestResult */ 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 +868,7 @@ public function setUseErrorHandler(bool $useErrorHandler): void */ public function doubledTypes(): array { - return \array_unique($this->doubledTypes); + return array_unique($this->doubledTypes); } /** @@ -836,7 +893,7 @@ public function setGroups(array $groups): void public function getAnnotations(): array { return TestUtil::parseTestMethodAnnotations( - \get_class($this), + static::class, $this->name ); } @@ -865,7 +922,7 @@ public function getName(bool $withDataSet = true): string public function getSize(): int { return TestUtil::getSize( - \get_class($this), + static::class, $this->getName(false) ); } @@ -919,7 +976,7 @@ public function getActualOutput(): string return $this->output; } - return (string) \ob_get_contents(); + return (string) ob_get_contents(); } /** @@ -951,7 +1008,7 @@ public function doesNotPerformAssertions(): bool */ 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 +1054,7 @@ public function setRegisterMockObjectsFromTestArgumentsRecursively(bool $flag): } /** - * @throws \Throwable + * @throws Throwable * * @internal This method is not covered by the backward compatibility promise for PHPUnit */ @@ -1007,10 +1064,10 @@ public function runBare(): void $this->snapshotGlobalState(); $this->startOutputBuffering(); - \clearstatcache(); - $currentWorkingDirectory = \getcwd(); + clearstatcache(); + $currentWorkingDirectory = getcwd(); - $hookMethods = TestUtil::getHookMethods(\get_class($this)); + $hookMethods = TestUtil::getHookMethods(static::class); $hasMetRequirements = false; @@ -1038,9 +1095,9 @@ public function runBare(): void if (!empty($this->warnings)) { throw new Warning( - \implode( + implode( "\n", - \array_unique($this->warnings) + array_unique($this->warnings) ) ); } @@ -1061,7 +1118,7 @@ public function runBare(): void } 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 +1141,7 @@ public function runBare(): void } } } - } catch (\Throwable $_e) { + } catch (Throwable $_e) { $e = $e ?? $_e; } @@ -1099,17 +1156,17 @@ public function runBare(): void $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 +1176,7 @@ public function runBare(): void } elseif ($this->outputExpectedString !== null) { $this->assertEquals($this->outputExpectedString, $this->output); } - } catch (\Throwable $_e) { + } catch (Throwable $_e) { $e = $_e; } } @@ -1165,7 +1222,7 @@ public function getDependencies(): array */ public function hasDependencies(): bool { - return \count($this->dependencies) > 0; + return count($this->dependencies) > 0; } /** @@ -1335,7 +1392,7 @@ public function usesDataProvider(): bool */ public function dataDescription(): string { - return \is_string($this->dataName) ? $this->dataName : ''; + return is_string($this->dataName) ? $this->dataName : ''; } /** @@ -1356,16 +1413,16 @@ public function getDataSetAsString(bool $includeData = true): string $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,38 +1450,48 @@ public function addWarning(string $warning): void /** * 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; } if ($this->expectedException !== null) { - $this->assertThat( - $exception, - new ExceptionConstraint( - $this->expectedException - ) - ); + if ($this->expectedException === Error::class) { + $this->assertThat( + $exception, + LogicalOr::fromConstraints( + new ExceptionConstraint(Error::class), + new ExceptionConstraint(\Error::class) + ) + ); + } else { + $this->assertThat( + $exception, + new ExceptionConstraint( + $this->expectedException + ) + ); + } } if ($this->expectedExceptionMessage !== null) { @@ -1472,7 +1539,7 @@ protected function runTest() $this->numAssertions++; throw new AssertionFailedError( - \sprintf( + sprintf( 'Failed asserting that exception with message "%s" is thrown', $this->expectedExceptionMessage ) @@ -1481,7 +1548,7 @@ protected function runTest() $this->numAssertions++; throw new AssertionFailedError( - \sprintf( + sprintf( 'Failed asserting that exception with message matching "%s" is thrown', $this->expectedExceptionMessageRegExp ) @@ -1490,7 +1557,7 @@ protected function runTest() $this->numAssertions++; throw new AssertionFailedError( - \sprintf( + sprintf( 'Failed asserting that exception with code "%s" is thrown', $this->expectedExceptionCode ) @@ -1509,13 +1576,13 @@ protected function runTest() */ 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 +1599,27 @@ protected function iniSet(string $varName, string $newValue): void */ 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 +1653,7 @@ protected function createStub(string $originalClassName): Stub */ 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 +1697,16 @@ protected function createConfiguredMock($originalClassName, array $configuration */ 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 +1715,9 @@ static function (string $method) use ($reflection) { 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 +1778,7 @@ protected function getMockClass($originalClassName, $methods = [], array $argume $cloneArguments ); - return \get_class($mock); + return get_class($mock); } /** @@ -1769,11 +1836,11 @@ protected function getMockFromWsdl($wsdlFile, $originalClassName = '', $mockClas $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 +1934,7 @@ protected function getObjectForTrait($traitName, array $arguments = [], $traitCl */ protected function prophesize($classOrInterface = null): ObjectProphecy { - if (\is_string($classOrInterface)) { + if (is_string($classOrInterface)) { $this->recordDoubledType($classOrInterface); } @@ -1905,9 +1972,9 @@ protected function assertPostConditions(): void /** * 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; } @@ -1920,7 +1987,7 @@ private function setExpectedExceptionFromAnnotation(): void try { $expectedException = TestUtil::getExpectedException( - \get_class($this), + static::class, $this->name ); @@ -1944,28 +2011,28 @@ private function setExpectedExceptionFromAnnotation(): void } /** - * @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; } $missingRequirements = TestUtil::getMissingRequirements( - \get_class($this), + static::class, $this->name ); 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 +2053,9 @@ private function verifyMockObjects(): void 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()); } } } @@ -1999,19 +2066,18 @@ private function verifyMockObjects(): void private function handleDependencies(): bool { if (!empty($this->dependencies) && !$this->inIsolation) { - $className = \get_class($this); $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; @@ -2023,24 +2089,24 @@ private function handleDependencies(): bool 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) { - $dependency = $className . '::' . $dependency; + if (strpos($dependency, '::') === false) { + $dependency = static::class . '::' . $dependency; } if (!isset($passedKeys[$dependency])) { @@ -2096,7 +2162,7 @@ private function markSkippedForNotSpecifyingDependency(): void $this->result->addError( $this, new SkippedTestError( - \sprintf('This method has an invalid @depends annotation.') + 'This method has an invalid @depends annotation.' ), 0 ); @@ -2113,7 +2179,7 @@ private function markSkippedForMissingDependency(string $dependency): void $this->result->addError( $this, new SkippedTestError( - \sprintf( + sprintf( 'This test depends on "%s" to pass.', $dependency ) @@ -2133,7 +2199,7 @@ private function warnAboutDependencyThatDoesNotExist(string $dependency): void $this->result->addWarning( $this, new Warning( - \sprintf( + sprintf( 'This test depends on "%s" which does not exist.', $dependency ) @@ -2158,10 +2224,10 @@ private function getMockObjectGenerator(): MockGenerator private function startOutputBuffering(): void { - \ob_start(); + ob_start(); $this->outputBufferingActive = true; - $this->outputBufferingLevel = \ob_get_level(); + $this->outputBufferingLevel = ob_get_level(); } /** @@ -2169,9 +2235,9 @@ private function startOutputBuffering(): void */ 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( @@ -2179,16 +2245,16 @@ private function stopOutputBuffering(): void ); } - $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 @@ -2202,8 +2268,8 @@ private function snapshotGlobalState(): void } /** - * @throws RiskyTestError * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws RiskyTestError */ private function restoreGlobalState(): void { @@ -2247,7 +2313,7 @@ private function createGlobalStateSnapshot(bool $backupGlobals): Snapshot $blacklist->addGlobalVariable($globalVariable); } - if (!\defined('PHPUNIT_TESTSUITE')) { + if (!defined('PHPUNIT_TESTSUITE')) { $blacklist->addClassNamePrefix('PHPUnit'); $blacklist->addClassNamePrefix('SebastianBergmann\CodeCoverage'); $blacklist->addClassNamePrefix('SebastianBergmann\FileIterator'); @@ -2282,8 +2348,8 @@ private function createGlobalStateSnapshot(bool $backupGlobals): Snapshot } /** - * @throws RiskyTestError * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws RiskyTestError */ private function compareGlobalStateSnapshots(Snapshot $before, Snapshot $after): void { @@ -2354,11 +2420,11 @@ private function shouldInvocationMockerBeReset(MockObject $mock): bool } } - 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); } /** @@ -2382,7 +2448,7 @@ private function registerMockObjectsFromTestArguments(array $testArguments, arra } $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( @@ -2417,7 +2483,7 @@ private function unregisterCustomComparators(): void private function cleanupIniSettings(): void { foreach ($this->iniSettings as $varName => $oldValue) { - \ini_set($varName, $oldValue); + ini_set($varName, $oldValue); } $this->iniSettings = []; @@ -2426,7 +2492,7 @@ private function cleanupIniSettings(): void private function cleanupLocaleSettings(): void { foreach ($this->locale as $category => $locale) { - \setlocale($category, $locale); + setlocale($category, $locale); } $this->locale = []; @@ -2435,7 +2501,7 @@ private function cleanupLocaleSettings(): void /** * @throws Exception */ - private function checkExceptionExpectations(\Throwable $throwable): bool + private function checkExceptionExpectations(Throwable $throwable): bool { $result = false; @@ -2447,11 +2513,11 @@ private function checkExceptionExpectations(\Throwable $throwable): bool $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(), @@ -2481,13 +2547,13 @@ private function runInSeparateProcess(): bool */ 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; } } @@ -2496,15 +2562,15 @@ private function recordDoubledType($originalClassName): void 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; } @@ -2518,7 +2584,7 @@ private function isCallableTestMethod(string $dependency): bool try { $method = $class->getMethod($methodName); - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { return false; } diff --git a/src/Framework/TestFailure.php b/src/Framework/TestFailure.php index 6fe25f5ee8b..5849d36ede8 100644 --- a/src/Framework/TestFailure.php +++ b/src/Framework/TestFailure.php @@ -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 @@ public static function exceptionToString(Throwable $e): string } if (!empty($buffer)) { - $buffer = \trim($buffer) . "\n"; + $buffer = trim($buffer) . "\n"; } return $buffer; @@ -63,7 +66,7 @@ public static function exceptionToString(Throwable $e): string return $e->getClassName() . ': ' . $e->getMessage() . "\n"; } - return \get_class($e) . ': ' . $e->getMessage() . "\n"; + return get_class($e) . ': ' . $e->getMessage() . "\n"; } /** @@ -76,7 +79,7 @@ public function __construct(Test $failedTest, $t) 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 @@ public function __construct(Test $failedTest, $t) */ public function toString(): string { - return \sprintf( + return sprintf( '%s: %s', $this->testName, $this->thrownException->getMessage() diff --git a/src/Framework/TestListener.php b/src/Framework/TestListener.php index 039015169f9..96ce4eec737 100644 --- a/src/Framework/TestListener.php +++ b/src/Framework/TestListener.php @@ -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 @@ public function addFailure(Test $test, AssertionFailedError $e, float $time): vo * * @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. diff --git a/src/Framework/TestListenerDefaultImplementation.php b/src/Framework/TestListenerDefaultImplementation.php index 9c080af942f..7c99f5cb240 100644 --- a/src/Framework/TestListenerDefaultImplementation.php +++ b/src/Framework/TestListenerDefaultImplementation.php @@ -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 @@ public function addFailure(Test $test, AssertionFailedError $e, float $time): vo { } - 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 { } diff --git a/src/Framework/TestResult.php b/src/Framework/TestResult.php index 2be7678db16..8c333b54075 100644 --- a/src/Framework/TestResult.php +++ b/src/Framework/TestResult.php @@ -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\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 @@ public function endTestSuite(TestSuite $suite): void 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 @@ public function endTest(Test $test, float $time): void } 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 @@ public function allHarmless(): bool */ public function riskyCount(): int { - return \count($this->risky); + return count($this->risky); } /** @@ -468,11 +480,11 @@ public function allCompletelyImplemented(): bool */ 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 @@ public function risky(): array } /** - * 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 @@ public function noneSkipped(): bool */ 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 @@ public function skipped(): array */ 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 @@ public function errors(): array */ 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 @@ public function failures(): array */ 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 @@ public function getCollectCodeCoverageInformation(): bool /** * 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 @@ public function run(Test $test): void $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 @@ public function run(Test $test): void 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 @@ public function run(Test $test): void $frame = $e->getTrace()[0]; $e = new AssertionFailedError( - \sprintf( + sprintf( '%s in %s:%s', $e->getMessage(), $frame['file'], @@ -746,17 +758,17 @@ public function run(Test $test): void $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 @@ public function run(Test $test): void 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 @@ public function run(Test $test): void $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 @@ public function run(Test $test): void $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 @@ public function run(Test $test): void !$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 @@ public function run(Test $test): void try { $reflected = $reflected->getMethod($name); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -888,7 +900,7 @@ public function run(Test $test): void $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 @@ public function run(Test $test): void $this->addFailure( $test, new RiskyTestError( - \sprintf( + sprintf( 'This test is annotated with "@doesNotPerformAssertions" but performed %d assertions', $test->getNumAssertions() ) @@ -913,7 +925,7 @@ public function run(Test $test): void $this->addFailure( $test, new OutputError( - \sprintf( + sprintf( 'This test printed output: %s', $test->getActualOutput() ) @@ -1140,7 +1152,7 @@ public function stopOnSkipped(bool $flag): void } /** - * 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 @@ public function wasSuccessfulAndNoTestIsRiskyOrSkippedOrIncomplete(): bool } /** - * Sets the default timeout for tests + * Sets the default timeout for tests. */ public function setDefaultTimeLimit(int $timeout): void { diff --git a/src/Framework/TestSuite.php b/src/Framework/TestSuite.php index c0f84e12b1a..144cb6f1b8b 100644 --- a/src/Framework/TestSuite.php +++ b/src/Framework/TestSuite.php @@ -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 @@ public function __construct($theClass = '', string $name = '') !$constructor->isPublic()) { $this->addTest( new WarningTestCase( - \sprintf( + sprintf( 'Class "%s" has no public constructor.', $theClass->getName() ) @@ -202,7 +228,7 @@ public function __construct($theClass = '', string $name = '') if (empty($this->tests)) { $this->addTest( new WarningTestCase( - \sprintf( + sprintf( 'No tests found in class "%s".', $theClass->getName() ) @@ -229,9 +255,9 @@ public function toString(): string 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 @@ public function addTest(Test $test, $groups = []): void */ 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 @@ public function addTestSuite($testClass): void 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 @@ public function addTestSuite($testClass): void BaseTestRunner::SUITE_METHODNAME ); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -345,7 +371,7 @@ public function addTestSuite($testClass): void */ 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 @@ public function addTestFile(string $filename): void // 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 @@ public function addTestFile(string $filename): void // 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 @@ public function addTestFile(string $filename): void 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 @@ public function addTestFile(string $filename): void } // @codeCoverageIgnoreEnd - if (\dirname($class->getFileName()) === __DIR__) { + if (dirname($class->getFileName()) === __DIR__) { continue; } @@ -424,7 +450,7 @@ public function addTestFile(string $filename): void BaseTestRunner::SUITE_METHODNAME ); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -469,7 +495,7 @@ public function count(bool $preferCache = false): int $numTests = 0; foreach ($this as $test) { - $numTests += \count($test); + $numTests += count($test); } $this->cachedNumTests = $numTests; @@ -490,7 +516,7 @@ public function getName(): string */ public function getGroups(): array { - return \array_keys($this->groups); + return array_keys($this->groups); } public function getGroupDetails(): array @@ -499,7 +525,7 @@ public function getGroupDetails(): array } /** - * Set tests groups of the test case + * Set tests groups of the test case. */ public function setGroupDetails(array $groups): void { @@ -524,7 +550,7 @@ public function run(TestResult $result = null): TestResult $result = $this->createResult(); } - if (\count($this) === 0) { + if (count($this) === 0) { return $result; } @@ -537,13 +563,13 @@ public function run(TestResult $result = null): TestResult 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 @@ public function run(TestResult $result = null): TestResult $result->endTestSuite($this); return $result; - } catch (\Throwable $t) { + } catch (Throwable $t) { $errorAdded = false; foreach ($this->tests() as $test) { @@ -604,13 +630,13 @@ public function run(TestResult $result = null): TestResult 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 @@ public function tests(): array } /** - * Set tests of the test suite + * Set tests of the test suite. * * @param Test[] $tests */ @@ -685,7 +711,7 @@ public function markTestSuiteSkipped($message = ''): void */ 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 @@ public function setBeStrictAboutChangesToGlobalState($beStrictAboutChangesToGlob */ 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 @@ public function setBackupGlobals($backupGlobals): void */ 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 @@ public function setBackupStaticAttributes($backupStaticAttributes): void /** * Returns an iterator for this test suite. */ - public function getIterator(): \Iterator + public function getIterator(): Iterator { $iterator = new TestSuiteIterator($this); @@ -746,8 +772,12 @@ protected function createResult(): TestResult /** * @throws Exception */ - protected function addTestMethod(\ReflectionClass $class, \ReflectionMethod $method): void + protected function addTestMethod(ReflectionClass $class, ReflectionMethod $method): void { + if (!TestUtil::isTestMethod($method)) { + return; + } + $methodName = $method->getName(); $test = (new TestBuilder)->build($class, $methodName); diff --git a/src/Framework/TestSuiteIterator.php b/src/Framework/TestSuiteIterator.php index 804048afab6..e351622f39c 100644 --- a/src/Framework/TestSuiteIterator.php +++ b/src/Framework/TestSuiteIterator.php @@ -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 @@ public function rewind(): void public function valid(): bool { - return $this->position < \count($this->tests); + return $this->position < count($this->tests); } public function key(): int @@ -67,7 +71,7 @@ public function getChildren(): self $current = $this->current(); - \assert($current instanceof TestSuite); + assert($current instanceof TestSuite); return new self($current); } diff --git a/src/Framework/WarningTestCase.php b/src/Framework/WarningTestCase.php index 8070c01290a..e1e41bc44b9 100644 --- a/src/Framework/WarningTestCase.php +++ b/src/Framework/WarningTestCase.php @@ -29,22 +29,15 @@ final class WarningTestCase extends TestCase */ protected $runTestInSeparateProcess = false; - /** - * @var bool - */ - protected $useErrorHandler = false; - /** * @var string */ private $message; - /** - * @param string $message - */ - public function __construct($message = '') + public function __construct(string $message = '') { $this->message = $message; + parent::__construct('Warning'); } diff --git a/src/Runner/BaseTestRunner.php b/src/Runner/BaseTestRunner.php index 8efe1cf7fc0..3e5e0f71c4a 100644 --- a/src/Runner/BaseTestRunner.php +++ b/src/Runner/BaseTestRunner.php @@ -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 @@ public function getLoader(): TestSuiteLoader */ 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 @@ public function getTest(string $suiteClassName, string $suiteClassFile = '', $su } $test = $suiteMethod->invoke(null, $testClass->getName()); - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { try { $test = new TestSuite($testClass); } catch (Exception $e) { @@ -136,7 +140,7 @@ public function getTest(string $suiteClassName, string $suiteClassFile = '', $su /** * 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); } diff --git a/src/Runner/DefaultTestResultCache.php b/src/Runner/DefaultTestResultCache.php index a56ceabab28..19278cc0603 100644 --- a/src/Runner/DefaultTestResultCache.php +++ b/src/Runner/DefaultTestResultCache.php @@ -9,25 +9,34 @@ */ namespace PHPUnit\Runner; -use PHPUnit\Util\ErrorHandler; +use const DIRECTORY_SEPARATOR; +use const LOCK_EX; +use function assert; +use function dirname; +use function file_get_contents; +use function file_put_contents; +use function in_array; +use function is_array; +use function is_dir; +use function is_file; +use function json_decode; +use function json_encode; use PHPUnit\Util\Filesystem; /** * @internal This class is not covered by the backward compatibility promise for PHPUnit */ -final class DefaultTestResultCache implements \Serializable, TestResultCache +final class DefaultTestResultCache implements TestResultCache { /** - * @var string + * @var int */ - public const DEFAULT_RESULT_CACHE_FILENAME = '.phpunit.result.cache'; + private const VERSION = 1; /** - * Provide extra protection against incomplete or corrupt caches - * - * @var int[] + * @psalm-var list */ - private const ALLOWED_CACHE_TEST_STATUSES = [ + private const ALLOWED_TEST_STATUSES = [ BaseTestRunner::STATUS_SKIPPED, BaseTestRunner::STATUS_INCOMPLETE, BaseTestRunner::STATUS_FAILURE, @@ -37,83 +46,41 @@ final class DefaultTestResultCache implements \Serializable, TestResultCache ]; /** - * Path and filename for result cache file - * + * @var string + */ + private const DEFAULT_RESULT_CACHE_FILENAME = '.phpunit.result.cache'; + + /** * @var string */ private $cacheFilename; /** - * The list of defective tests - * - * - * // Mark a test skipped - * $this->defects[$testName] = BaseTestRunner::TEST_SKIPPED; - * - * - * @var array + * @psalm-var array */ private $defects = []; /** - * The list of execution duration of suites and tests (in seconds) - * - * - * // Record running time for test - * $this->times[$testName] = 1.234; - * - * - * @var array + * @psalm-var array */ private $times = []; public function __construct(?string $filepath = null) { - if ($filepath !== null && \is_dir($filepath)) { - // cache path provided, use default cache filename in that location - $filepath .= \DIRECTORY_SEPARATOR . self::DEFAULT_RESULT_CACHE_FILENAME; + if ($filepath !== null && is_dir($filepath)) { + $filepath .= DIRECTORY_SEPARATOR . self::DEFAULT_RESULT_CACHE_FILENAME; } $this->cacheFilename = $filepath ?? $_ENV['PHPUNIT_RESULT_CACHE'] ?? self::DEFAULT_RESULT_CACHE_FILENAME; } - /** - * @throws Exception - */ - public function persist(): void - { - $this->saveToFile(); - } - - /** - * @throws Exception - */ - public function saveToFile(): void + public function setState(string $testName, int $state): void { - if (\defined('PHPUNIT_TESTSUITE_RESULTCACHE')) { + if (!in_array($state, self::ALLOWED_TEST_STATUSES, true)) { return; } - if (!Filesystem::createDirectory(\dirname($this->cacheFilename))) { - throw new Exception( - \sprintf( - 'Cannot create directory "%s" for result cache file', - $this->cacheFilename - ) - ); - } - - \file_put_contents( - $this->cacheFilename, - \serialize($this) - ); - } - - public function setState(string $testName, int $state): void - { - if ($state !== BaseTestRunner::STATUS_PASSED) { - $this->defects[$testName] = $state; - } + $this->defects[$testName] = $state; } public function getState(string $testName): int @@ -133,85 +100,58 @@ public function getTime(string $testName): float public function load(): void { - $this->clear(); - - if (!\is_file($this->cacheFilename)) { - return; - } - - $cacheData = @\file_get_contents($this->cacheFilename); - - // @codeCoverageIgnoreStart - if ($cacheData === false) { + if (!is_file($this->cacheFilename)) { return; } - // @codeCoverageIgnoreEnd - $cache = ErrorHandler::invokeIgnoringWarnings( - static function () use ($cacheData) { - return @\unserialize($cacheData, ['allowed_classes' => [self::class]]); - } + $data = json_decode( + file_get_contents($this->cacheFilename), + true ); - if ($cache === false) { + if ($data === null) { return; } - if ($cache instanceof self) { - /* @var DefaultTestResultCache $cache */ - $cache->copyStateToCache($this); - } - } - - public function copyStateToCache(self $targetCache): void - { - foreach ($this->defects as $name => $state) { - $targetCache->setState($name, $state); + if (!isset($data['version'])) { + return; } - foreach ($this->times as $name => $time) { - $targetCache->setTime($name, $time); + if ($data['version'] !== self::VERSION) { + return; } - } - public function clear(): void - { - $this->defects = []; - $this->times = []; - } + assert(isset($data['defects']) && is_array($data['defects'])); + assert(isset($data['times']) && is_array($data['times'])); - public function serialize(): string - { - return \serialize([ - 'defects' => $this->defects, - 'times' => $this->times, - ]); + $this->defects = $data['defects']; + $this->times = $data['times']; } /** - * @param string $serialized + * @throws Exception */ - public function unserialize($serialized): void + public function persist(): void { - $data = \unserialize($serialized); - - if (isset($data['times'])) { - foreach ($data['times'] as $testName => $testTime) { - \assert(\is_string($testName)); - \assert(\is_float($testTime)); - $this->times[$testName] = $testTime; - } + if (!Filesystem::createDirectory(dirname($this->cacheFilename))) { + throw new Exception( + sprintf( + 'Cannot create directory "%s" for result cache file', + $this->cacheFilename + ) + ); } - if (isset($data['defects'])) { - foreach ($data['defects'] as $testName => $testResult) { - \assert(\is_string($testName)); - \assert(\is_int($testResult)); - - if (\in_array($testResult, self::ALLOWED_CACHE_TEST_STATUSES, true)) { - $this->defects[$testName] = $testResult; - } - } - } + file_put_contents( + $this->cacheFilename, + json_encode( + [ + 'version' => self::VERSION, + 'defects' => $this->defects, + 'times' => $this->times, + ] + ), + LOCK_EX + ); } } diff --git a/src/Runner/Exception.php b/src/Runner/Exception.php index 44705f5675e..adcd1155806 100644 --- a/src/Runner/Exception.php +++ b/src/Runner/Exception.php @@ -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 { } diff --git a/src/Runner/Filter/ExcludeGroupFilterIterator.php b/src/Runner/Filter/ExcludeGroupFilterIterator.php index d8a8643684f..4b26e5716e9 100644 --- a/src/Runner/Filter/ExcludeGroupFilterIterator.php +++ b/src/Runner/Filter/ExcludeGroupFilterIterator.php @@ -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); } } diff --git a/src/Runner/Filter/Factory.php b/src/Runner/Filter/Factory.php index 4072ad23b06..82dc1b7e0f6 100644 --- a/src/Runner/Filter/Factory.php +++ b/src/Runner/Filter/Factory.php @@ -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 ) diff --git a/src/Runner/Filter/GroupFilterIterator.php b/src/Runner/Filter/GroupFilterIterator.php index 1d778a6f984..42ca77a3812 100644 --- a/src/Runner/Filter/GroupFilterIterator.php +++ b/src/Runner/Filter/GroupFilterIterator.php @@ -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 @@ public function __construct(RecursiveIterator $iterator, array $groups, TestSuit 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 @@ public function accept(): bool return true; } - return $this->doAccept(\spl_object_hash($test)); + return $this->doAccept(spl_object_hash($test)); } abstract protected function doAccept(string $hash); diff --git a/src/Runner/Filter/IncludeGroupFilterIterator.php b/src/Runner/Filter/IncludeGroupFilterIterator.php index 5f004f9ad4e..0346c60131a 100644 --- a/src/Runner/Filter/IncludeGroupFilterIterator.php +++ b/src/Runner/Filter/IncludeGroupFilterIterator.php @@ -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); } } diff --git a/src/Runner/Filter/NameFilterIterator.php b/src/Runner/Filter/NameFilterIterator.php index a26665d7ad2..d90054d84c6 100644 --- a/src/Runner/Filter/NameFilterIterator.php +++ b/src/Runner/Filter/NameFilterIterator.php @@ -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 @@ public function accept(): bool 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 @@ public function accept(): bool } /** - * @throws \Exception + * @throws Exception */ private function setFilter(string $filter): void { @@ -85,9 +91,9 @@ private function setFilter(string $filter): void // 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 @@ private function setFilter(string $filter): void $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 @@ private function setFilter(string $filter): void } // 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,11 +120,14 @@ private function setFilter(string $filter): void // Escape delimiters in regular expression. Do NOT use preg_quote, // to keep magic characters. - $filter = \sprintf('/%s/i', \str_replace( - '/', - '\\/', - $filter - )); + $filter = sprintf( + '/%s/i', + str_replace( + '/', + '\\/', + $filter + ) + ); } $this->filter = $filter; diff --git a/src/Runner/Hook/TestListenerAdapter.php b/src/Runner/Hook/TestListenerAdapter.php index a4dfa4b472f..60fbfba3187 100644 --- a/src/Runner/Hook/TestListenerAdapter.php +++ b/src/Runner/Hook/TestListenerAdapter.php @@ -15,6 +15,7 @@ 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 @@ public function startTest(Test $test): void $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 @@ public function addFailure(Test $test, AssertionFailedError $e, float $time): vo $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 @@ public function addIncompleteTest(Test $test, \Throwable $t, float $time): void $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 @@ public function addRiskyTest(Test $test, \Throwable $t, float $time): void $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) { diff --git a/src/Runner/PhptTestCase.php b/src/Runner/PhptTestCase.php index 52922975144..da7e49e718a 100644 --- a/src/Runner/PhptTestCase.php +++ b/src/Runner/PhptTestCase.php @@ -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; @@ -29,32 +63,6 @@ */ final class PhptTestCase implements SelfDescribing, Test { - /** - * @var string[] - */ - private const SETTINGS = [ - 'allow_url_fopen=1', - 'auto_append_file=', - 'auto_prepend_file=', - 'disable_functions=', - 'display_errors=1', - 'docref_ext=.html', - 'docref_root=', - 'error_append_string=', - 'error_prepend_string=', - 'error_reporting=-1', - 'html_errors=0', - 'log_errors=0', - 'magic_quotes_runtime=0', - 'open_basedir=', - 'output_buffering=Off', - 'output_handler=', - 'report_memleaks=0', - 'report_zend_debug=0', - 'safe_mode=0', - 'xdebug.default_enable=0', - ]; - /** * @var string */ @@ -77,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 ) @@ -101,13 +109,13 @@ public function count(): int /** * 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 +135,7 @@ public function run(TestResult $result = null): TestResult $code = $this->render($sections['FILE']); $xfail = false; - $settings = $this->parseIniSection(self::SETTINGS); + $settings = $this->parseIniSection($this->settings($result->getCollectCodeCoverageInformation())); $result->startTest($this); @@ -153,7 +161,7 @@ public function run(TestResult $result = null): TestResult } if (isset($sections['XFAIL'])) { - $xfail = \trim($sections['XFAIL']); + $xfail = trim($sections['XFAIL']); } if (isset($sections['STDIN'])) { @@ -195,7 +203,7 @@ public function run(TestResult $result = null): TestResult } $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, @@ -215,7 +223,7 @@ public function run(TestResult $result = null): TestResult $result->addFailure($this, new IncompleteTestError('XFAIL section but test passes'), $time); } - $this->runClean($sections); + $this->runClean($sections, $result->getCollectCodeCoverageInformation()); $result->endTest($this, $time); @@ -265,18 +273,18 @@ public function hasOutput(): bool */ 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])) { @@ -298,8 +306,8 @@ private function parseEnvSection(string $content): array { $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]; @@ -310,9 +318,9 @@ private function parseEnvSection(string $content): array } /** - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException * @throws Exception + * @throws ExpectationFailedException */ private function assertPhptExpectation(array $sections, string $output): void { @@ -322,11 +330,11 @@ private function assertPhptExpectation(array $sections, string $output): void '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) { @@ -354,15 +362,15 @@ private function runSkip(array &$sections, TestResult $result, array $settings): $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), @@ -376,7 +384,7 @@ private function runSkip(array &$sections, TestResult $result, array $settings): return false; } - private function runClean(array &$sections): void + private function runClean(array &$sections, bool $collectCoverage): void { $this->phpUtil->setStdin(''); $this->phpUtil->setArgs(''); @@ -384,7 +392,7 @@ private function runClean(array &$sections): void if (isset($sections['CLEAN'])) { $cleanCode = $this->render($sections['CLEAN']); - $this->phpUtil->runJob($cleanCode, self::SETTINGS); + $this->phpUtil->runJob($cleanCode, $this->settings($collectCoverage)); } } @@ -415,10 +423,10 @@ private function parse(): array $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; @@ -434,7 +442,7 @@ private function parse(): array } if (isset($sections['FILEEOF'])) { - $sections['FILE'] = \rtrim($sections['FILEEOF'], "\r\n"); + $sections['FILE'] = rtrim($sections['FILEEOF'], "\r\n"); unset($sections['FILEEOF']); } @@ -466,16 +474,16 @@ private function parseExternal(array &$sections): void '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 @@ -483,7 +491,7 @@ private function parseExternal(array &$sections): void ); } - $sections[$section] = \file_get_contents($testDirectory . $externalFilename); + $sections[$section] = file_get_contents($testDirectory . $externalFilename); } } } @@ -500,7 +508,7 @@ private function validate(array &$sections): bool ]; foreach ($requiredSections as $section) { - if (\is_array($section)) { + if (is_array($section)) { $foundSection = false; foreach ($section as $anySection) { @@ -528,13 +536,13 @@ private function validate(array &$sections): bool private function render(string $code): string { - return \str_replace( + return str_replace( [ '__DIR__', '__FILE__', ], [ - "'" . \dirname($this->filename) . "'", + "'" . dirname($this->filename) . "'", "'" . $this->filename . "'", ], $code @@ -543,8 +551,8 @@ private function render(string $code): string 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', @@ -562,20 +570,20 @@ private function renderForCoverage(string &$job): void $composerAutoload = '\'\''; - if (\defined('PHPUNIT_COMPOSER_INSTALL') && !\defined('PHPUNIT_TESTSUITE')) { - $composerAutoload = \var_export(PHPUNIT_COMPOSER_INSTALL, true); + if (defined('PHPUNIT_COMPOSER_INSTALL')) { + $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"; @@ -591,7 +599,7 @@ private function renderForCoverage(string &$job): void ] ); - \file_put_contents($files['job'], $job); + file_put_contents($files['job'], $job); $job = $template->render(); } @@ -600,11 +608,11 @@ private function cleanupForCoverage(): array $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 = []; @@ -613,7 +621,7 @@ private function cleanupForCoverage(): array } foreach ($files as $file) { - @\unlink($file); + @unlink($file); } return $coverage; @@ -624,7 +632,7 @@ private function stringifyIni(array $ini): array $settings = []; foreach ($ini as $key => $value) { - if (\is_array($value)) { + if (is_array($value)) { foreach ($value as $val) { $settings[] = $key . '=' . $val; } @@ -644,8 +652,8 @@ private function getLocationHintFromDiff(string $message, array $sections): arra $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'; @@ -656,13 +664,13 @@ private function getLocationHintFromDiff(string $message, array $sections): arra } 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; @@ -679,7 +687,7 @@ private function getLocationHintFromDiff(string $message, array $sections): arra private function getCleanDiffLine(string $line): string { - if (\preg_match('/^[\-+]([\'\"]?)(.*)\1$/', $line, $matches)) { + if (preg_match('/^[\-+]([\'\"]?)(.*)\1$/', $line, $matches)) { $line = $matches[2]; } @@ -688,11 +696,11 @@ private function getCleanDiffLine(string $line): string 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, ]]; } @@ -714,15 +722,15 @@ private function getLocationHint(string $needle, array $sections, ?string $secti } 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, ], ]; @@ -731,10 +739,10 @@ private function getLocationHint(string $needle, array $sections, ?string $secti $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, ]]; } @@ -745,15 +753,67 @@ private function getLocationHint(string $needle, array $sections, ?string $secti 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, ]]; } + + /** + * @psalm-return list + */ + private function settings(bool $collectCoverage): array + { + $settings = [ + 'allow_url_fopen=1', + 'auto_append_file=', + 'auto_prepend_file=', + 'disable_functions=', + 'display_errors=1', + 'docref_ext=.html', + 'docref_root=', + 'error_append_string=', + 'error_prepend_string=', + 'error_reporting=-1', + 'html_errors=0', + 'log_errors=0', + 'open_basedir=', + 'output_buffering=Off', + 'output_handler=', + 'report_memleaks=0', + 'report_zend_debug=0', + ]; + + if (extension_loaded('pcov')) { + if ($collectCoverage) { + $settings[] = 'pcov.enabled=1'; + } else { + $settings[] = 'pcov.enabled=0'; + } + } + + if (extension_loaded('xdebug')) { + if (version_compare(phpversion('xdebug'), '3', '>=')) { + if ($collectCoverage) { + $settings[] = 'xdebug.mode=coverage'; + } else { + $settings[] = 'xdebug.mode=off'; + } + } else { + $settings[] = 'xdebug.default_enable=0'; + + if ($collectCoverage) { + $settings[] = 'xdebug.coverage_enable=1'; + } + } + } + + return $settings; + } } diff --git a/src/Runner/ResultCacheExtension.php b/src/Runner/ResultCacheExtension.php index f9a9b13f505..31d7610e2bc 100644 --- a/src/Runner/ResultCacheExtension.php +++ b/src/Runner/ResultCacheExtension.php @@ -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 @@ public function executeAfterSuccessfulTest(string $test, float $time): void { $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 @@ public function executeAfterRiskyTest(string $test, string $message, float $time { $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 @@ public function executeAfterSkippedTest(string $test, string $message, float $ti { $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 @@ public function executeAfterTestError(string $test, string $message, float $time { $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 @@ public function executeAfterTestFailure(string $test, string $message, float $ti { $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 @@ public function executeAfterTestWarning(string $test, string $message, float $ti { $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 @@ private function getTestName(string $test): string { $matches = []; - if (\preg_match('/^(?\S+::\S+)(?:(? with data set (?:#\d+|"[^"]+"))\s\()?/', $test, $matches)) { + if (preg_match('/^(?\S+::\S+)(?:(? with data set (?:#\d+|"[^"]+"))\s\()?/', $test, $matches)) { $test = $matches['name'] . ($matches['dataname'] ?? ''); } diff --git a/src/Runner/StandardTestSuiteLoader.php b/src/Runner/StandardTestSuiteLoader.php index e7651a4b5ff..b658dfcc42e 100644 --- a/src/Runner/StandardTestSuiteLoader.php +++ b/src/Runner/StandardTestSuiteLoader.php @@ -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 @@ 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 @@ public function load(string $suiteClassName, string $suiteClassFile = ''): \Refl ); } - 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 @@ public function load(string $suiteClassName, string $suiteClassFile = ''): \Refl } // @codeCoverageIgnoreEnd - if (\substr($loadedClass, $offset) === $suiteClassName && + if (substr($loadedClass, $offset) === $suiteClassName && $class->getFileName() == $filename) { $suiteClassName = $loadedClass; @@ -68,14 +79,14 @@ public function load(string $suiteClassName, string $suiteClassFile = ''): \Refl } } - 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 @@ public function load(string $suiteClassName, string $suiteClassFile = ''): \Refl $suiteClassName = $loadedClass; $testCaseClass = $loadedClass; - if ($classFile == \realpath($suiteClassFile)) { + if ($classFile == realpath($suiteClassFile)) { break; } } @@ -99,7 +110,7 @@ public function load(string $suiteClassName, string $suiteClassFile = ''): \Refl try { $method = $class->getMethod('suite'); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -111,7 +122,7 @@ public function load(string $suiteClassName, string $suiteClassFile = ''): \Refl if (!$method->isAbstract() && $method->isPublic() && $method->isStatic()) { $suiteClassName = $loadedClass; - if ($classFile == \realpath($suiteClassFile)) { + if ($classFile == realpath($suiteClassFile)) { break; } } @@ -119,11 +130,11 @@ public function load(string $suiteClassName, string $suiteClassFile = ''): \Refl } } - 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 @@ public function load(string $suiteClassName, string $suiteClassFile = ''): \Refl } // @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 @@ public function load(string $suiteClassName, string $suiteClassFile = ''): \Refl ); } - public function reload(\ReflectionClass $aClass): \ReflectionClass + public function reload(ReflectionClass $aClass): ReflectionClass { return $aClass; } diff --git a/src/Runner/TestSuiteSorter.php b/src/Runner/TestSuiteSorter.php index e23a0611c33..f44b92ced28 100644 --- a/src/Runner/TestSuiteSorter.php +++ b/src/Runner/TestSuiteSorter.php @@ -9,6 +9,20 @@ */ namespace PHPUnit\Runner; +use function array_intersect; +use function array_map; +use function array_merge; +use function array_reduce; +use function array_reverse; +use function array_splice; +use function count; +use function get_class; +use function in_array; +use function max; +use function shuffle; +use function strpos; +use function substr; +use function usort; use PHPUnit\Framework\DataProviderTestSuite; use PHPUnit\Framework\Test; use PHPUnit\Framework\TestCase; @@ -46,7 +60,7 @@ final class TestSuiteSorter public const ORDER_DURATION = 4; /** - * Order tests by @size annotation 'small', 'medium', 'large' + * Order tests by @size annotation 'small', 'medium', 'large'. * * @var int */ @@ -104,8 +118,8 @@ public static function getTestSorterUID(Test $test): string if ($test instanceof TestCase) { $testName = $test->getName(true); - if (\strpos($testName, '::') === false) { - $testName = \get_class($test) . '::' . $testName; + if (strpos($testName, '::') === false) { + $testName = get_class($test) . '::' . $testName; } return $testName; @@ -120,8 +134,8 @@ public function __construct(?TestResultCache $cache = null) } /** - * @throws Exception * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws Exception */ public function reorderTestsInSuite(Test $suite, int $order, bool $resolveDependencies, int $orderDefects, bool $isRootTestSuite = true): void { @@ -133,7 +147,7 @@ public function reorderTestsInSuite(Test $suite, int $order, bool $resolveDepend self::ORDER_SIZE, ]; - if (!\in_array($order, $allowedOrders, true)) { + if (!in_array($order, $allowedOrders, true)) { throw new Exception( '$order must be one of TestSuiteSorter::ORDER_[DEFAULT|REVERSED|RANDOMIZED|DURATION|SIZE]' ); @@ -144,7 +158,7 @@ public function reorderTestsInSuite(Test $suite, int $order, bool $resolveDepend self::ORDER_DEFECTS_FIRST, ]; - if (!\in_array($orderDefects, $allowedOrderDefects, true)) { + if (!in_array($orderDefects, $allowedOrderDefects, true)) { throw new Exception( '$orderDefects must be one of TestSuiteSorter::ORDER_DEFAULT, TestSuiteSorter::ORDER_DEFECTS_FIRST' ); @@ -221,7 +235,7 @@ private function addSuiteToDefectSortOrder(TestSuite $suite): void if (!isset($this->defectSortOrder[$testname])) { $this->defectSortOrder[$testname] = self::DEFECT_SORT_WEIGHT[$this->cache->getState($testname)]; - $max = \max($max, $this->defectSortOrder[$testname]); + $max = max($max, $this->defectSortOrder[$testname]); } } @@ -230,7 +244,7 @@ private function addSuiteToDefectSortOrder(TestSuite $suite): void private function suiteOnlyContainsTests(TestSuite $suite): bool { - return \array_reduce( + return array_reduce( $suite->tests(), static function ($carry, $test) { return $carry && ($test instanceof TestCase || $test instanceof DataProviderTestSuite); @@ -241,19 +255,19 @@ static function ($carry, $test) { private function reverse(array $tests): array { - return \array_reverse($tests); + return array_reverse($tests); } private function randomize(array $tests): array { - \shuffle($tests); + shuffle($tests); return $tests; } private function sortDefectsFirst(array $tests): array { - \usort( + usort( $tests, /** * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException @@ -268,7 +282,7 @@ function ($left, $right) { private function sortByDuration(array $tests): array { - \usort( + usort( $tests, /** * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException @@ -283,7 +297,7 @@ function ($left, $right) { private function sortBySize(array $tests): array { - \usort( + usort( $tests, /** * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException @@ -300,7 +314,7 @@ function ($left, $right) { * Comparator callback function to sort tests for "reach failure as fast as possible": * 1. sort tests by defect weight defined in self::DEFECT_SORT_WEIGHT * 2. when tests are equally defective, sort the fastest to the front - * 3. do not reorder successful tests + * 3. do not reorder successful tests. * * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ @@ -333,7 +347,7 @@ private function cmpDuration(Test $a, Test $b): int } /** - * Compares test size for sorting tests small->medium->large->unknown + * Compares test size for sorting tests small->medium->large->unknown. */ private function cmpSize(Test $a, Test $b): int { @@ -368,7 +382,7 @@ private function resolveDependencies(array $tests): array $i = 0; do { - $todoNames = \array_map( + $todoNames = array_map( /** * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ @@ -378,15 +392,15 @@ static function ($test) { $tests ); - if (!$tests[$i]->hasDependencies() || empty(\array_intersect($this->getNormalizedDependencyNames($tests[$i]), $todoNames))) { - $newTestOrder = \array_merge($newTestOrder, \array_splice($tests, $i, 1)); + if (!$tests[$i]->hasDependencies() || empty(array_intersect($this->getNormalizedDependencyNames($tests[$i]), $todoNames))) { + $newTestOrder = array_merge($newTestOrder, array_splice($tests, $i, 1)); $i = 0; } else { $i++; } - } while (!empty($tests) && ($i < \count($tests))); + } while (!empty($tests) && ($i < count($tests))); - return \array_merge($newTestOrder, $tests); + return array_merge($newTestOrder, $tests); } /** @@ -397,14 +411,14 @@ static function ($test) { private function getNormalizedDependencyNames($test): array { if ($test instanceof DataProviderTestSuite) { - $testClass = \substr($test->getName(), 0, \strpos($test->getName(), '::')); + $testClass = substr($test->getName(), 0, strpos($test->getName(), '::')); } else { - $testClass = \get_class($test); + $testClass = get_class($test); } - $names = \array_map( + $names = array_map( static function ($name) use ($testClass) { - return \strpos($name, '::') === false ? $testClass . '::' . $name : $name; + return strpos($name, '::') === false ? $testClass . '::' . $name : $name; }, $test->getDependencies() ); @@ -424,7 +438,7 @@ private function calculateTestExecutionOrder(Test $suite): array if (!($test instanceof TestSuite)) { $tests[] = self::getTestSorterUID($test); } else { - $tests = \array_merge($tests, $this->calculateTestExecutionOrder($test)); + $tests = array_merge($tests, $this->calculateTestExecutionOrder($test)); } } } diff --git a/src/Runner/Version.php b/src/Runner/Version.php index 763c4115d84..263210ab8a8 100644 --- a/src/Runner/Version.php +++ b/src/Runner/Version.php @@ -9,6 +9,11 @@ */ namespace PHPUnit\Runner; +use function array_slice; +use function dirname; +use function explode; +use function implode; +use function strpos; use SebastianBergmann\Version as VersionId; final class Version @@ -33,7 +38,7 @@ public static function id(): string } if (self::$version === '') { - self::$version = (new VersionId('8.5.8', \dirname(__DIR__, 2)))->getVersion(); + self::$version = (new VersionId('8.5.15', dirname(__DIR__, 2)))->getVersion(); } return self::$version; @@ -41,13 +46,13 @@ public static function id(): string public static function series(): string { - if (\strpos(self::id(), '-')) { - $version = \explode('-', self::id())[0]; + if (strpos(self::id(), '-')) { + $version = explode('-', self::id())[0]; } else { $version = self::id(); } - return \implode('.', \array_slice(\explode('.', $version), 0, 2)); + return implode('.', array_slice(explode('.', $version), 0, 2)); } public static function getVersionString(): string @@ -57,7 +62,7 @@ public static function getVersionString(): string public static function getReleaseChannel(): string { - if (\strpos(self::$pharVersion, '-') !== false) { + if (strpos(self::$pharVersion, '-') !== false) { return '-nightly'; } diff --git a/src/TextUI/Command.php b/src/TextUI/Command.php index 0fdf15a5023..7c245d89090 100644 --- a/src/TextUI/Command.php +++ b/src/TextUI/Command.php @@ -9,6 +9,37 @@ */ namespace PHPUnit\TextUI; +use const PATH_SEPARATOR; +use const PHP_EOL; +use const STDIN; +use function array_keys; +use function assert; +use function class_exists; +use function explode; +use function extension_loaded; +use function fgets; +use function file_exists; +use function file_get_contents; +use function file_put_contents; +use function getcwd; +use function ini_get; +use function ini_set; +use function is_callable; +use function is_dir; +use function is_file; +use function is_numeric; +use function is_string; +use function printf; +use function realpath; +use function sort; + +use function sprintf; +use function str_replace; +use function stream_resolve_include_path; +use function strrpos; +use function substr; +use function trim; +use function version_compare; use PharIo\Manifest\ApplicationName; use PharIo\Manifest\Exception as ManifestException; use PharIo\Manifest\ManifestLoader; @@ -31,8 +62,9 @@ use PHPUnit\Util\TestDox\CliTestDoxPrinter; use PHPUnit\Util\TextTestListRenderer; use PHPUnit\Util\XmlTestListRenderer; +use ReflectionClass; +use ReflectionException; use SebastianBergmann\FileIterator\Facade as FileIteratorFacade; - use Throwable; /** @@ -203,7 +235,7 @@ public function run(array $argv, bool $exit = true): int try { $result = $runner->doRun($suite, $this->arguments, $this->warnings, $exit); } catch (Exception $e) { - print $e->getMessage() . \PHP_EOL; + print $e->getMessage() . PHP_EOL; } $return = TestRunner::FAILURE_EXIT; @@ -280,7 +312,7 @@ protected function handleArguments(array $argv): void $this->options = Getopt::parse( $argv, 'd:c:hv', - \array_keys($this->longOptions) + array_keys($this->longOptions) ); } catch (Exception $t) { $this->exitWithErrorMessage($t->getMessage()); @@ -314,7 +346,7 @@ protected function handleArguments(array $argv): void break; case '--columns': - if (\is_numeric($option[1])) { + if (is_numeric($option[1])) { $this->arguments['columns'] = (int) $option[1]; } elseif ($option[1] === 'max') { $this->arguments['columns'] = 'max'; @@ -365,13 +397,13 @@ protected function handleArguments(array $argv): void break; case 'd': - $ini = \explode('=', $option[1]); + $ini = explode('=', $option[1]); if (isset($ini[0])) { if (isset($ini[1])) { - \ini_set($ini[0], $ini[1]); + ini_set($ini[0], $ini[1]); } else { - \ini_set($ini[0], '1'); + ini_set($ini[0], '1'); } } @@ -403,16 +435,16 @@ protected function handleArguments(array $argv): void case '--generate-configuration': $this->printVersionString(); - print 'Generating phpunit.xml in ' . \getcwd() . \PHP_EOL . \PHP_EOL; + print 'Generating phpunit.xml in ' . getcwd() . PHP_EOL . PHP_EOL; print 'Bootstrap script (relative to path shown above; default: vendor/autoload.php): '; - $bootstrapScript = \trim(\fgets(\STDIN)); + $bootstrapScript = trim(fgets(STDIN)); print 'Tests directory (relative to path shown above; default: tests): '; - $testsDirectory = \trim(\fgets(\STDIN)); + $testsDirectory = trim(fgets(STDIN)); print 'Source directory (relative to path shown above; default: src): '; - $src = \trim(\fgets(\STDIN)); + $src = trim(fgets(STDIN)); if ($bootstrapScript === '') { $bootstrapScript = 'vendor/autoload.php'; @@ -428,7 +460,7 @@ protected function handleArguments(array $argv): void $generator = new ConfigurationGenerator; - \file_put_contents( + file_put_contents( 'phpunit.xml', $generator->generateDefaultConfiguration( Version::series(), @@ -438,19 +470,19 @@ protected function handleArguments(array $argv): void ) ); - print \PHP_EOL . 'Generated phpunit.xml in ' . \getcwd() . \PHP_EOL; + print PHP_EOL . 'Generated phpunit.xml in ' . getcwd() . PHP_EOL; exit(TestRunner::SUCCESS_EXIT); break; case '--group': - $this->arguments['groups'] = \explode(',', $option[1]); + $this->arguments['groups'] = explode(',', $option[1]); break; case '--exclude-group': - $this->arguments['excludeGroups'] = \explode( + $this->arguments['excludeGroups'] = explode( ',', $option[1] ); @@ -458,7 +490,7 @@ protected function handleArguments(array $argv): void break; case '--test-suffix': - $this->arguments['testSuffixes'] = \explode( + $this->arguments['testSuffixes'] = explode( ',', $option[1] ); @@ -586,7 +618,7 @@ protected function handleArguments(array $argv): void break; case '--testdox-group': - $this->arguments['testdoxGroups'] = \explode( + $this->arguments['testdoxGroups'] = explode( ',', $option[1] ); @@ -594,7 +626,7 @@ protected function handleArguments(array $argv): void break; case '--testdox-exclude-group': - $this->arguments['testdoxExcludeGroups'] = \explode( + $this->arguments['testdoxExcludeGroups'] = explode( ',', $option[1] ); @@ -658,7 +690,7 @@ protected function handleArguments(array $argv): void break; case '--atleast-version': - if (\version_compare(Version::id(), $option[1], '>=')) { + if (version_compare(Version::id(), $option[1], '>=')) { exit(TestRunner::SUCCESS_EXIT); } @@ -764,7 +796,7 @@ protected function handleArguments(array $argv): void break; default: - $optionName = \str_replace('--', '', $option[0]); + $optionName = str_replace('--', '', $option[0]); $handler = null; @@ -774,7 +806,7 @@ protected function handleArguments(array $argv): void $handler = $this->longOptions[$optionName . '=']; } - if (isset($handler) && \is_callable([$this, $handler])) { + if (isset($handler) && is_callable([$this, $handler])) { $this->{$handler}($option[1]); } } @@ -787,10 +819,10 @@ protected function handleArguments(array $argv): void } if (isset($this->options[1][0]) && - \substr($this->options[1][0], -5, 5) !== '.phpt' && - \substr($this->options[1][0], -4, 4) !== '.php' && - \substr($this->options[1][0], -1, 1) !== '/' && - !\is_dir($this->options[1][0])) { + substr($this->options[1][0], -5, 5) !== '.phpt' && + substr($this->options[1][0], -4, 4) !== '.php' && + substr($this->options[1][0], -1, 1) !== '/' && + !is_dir($this->options[1][0])) { $this->warnings[] = 'Invocation with class name is deprecated'; } @@ -800,11 +832,11 @@ protected function handleArguments(array $argv): void } if (isset($this->options[1][1])) { - $testFile = \realpath($this->options[1][1]); + $testFile = realpath($this->options[1][1]); if ($testFile === false) { $this->exitWithErrorMessage( - \sprintf( + sprintf( 'Cannot open file "%s".', $this->options[1][1] ) @@ -816,16 +848,16 @@ protected function handleArguments(array $argv): void } if (isset($this->arguments['test']) && - \is_file($this->arguments['test']) && - \strrpos($this->arguments['test'], '.') !== false && - \substr($this->arguments['test'], -5, 5) !== '.phpt') { - $this->arguments['testFile'] = \realpath($this->arguments['test']); - $this->arguments['test'] = \substr($this->arguments['test'], 0, \strrpos($this->arguments['test'], '.')); + is_file($this->arguments['test']) && + strrpos($this->arguments['test'], '.') !== false && + substr($this->arguments['test'], -5, 5) !== '.phpt') { + $this->arguments['testFile'] = realpath($this->arguments['test']); + $this->arguments['test'] = substr($this->arguments['test'], 0, strrpos($this->arguments['test'], '.')); } if (isset($this->arguments['test']) && - \is_string($this->arguments['test']) && - \substr($this->arguments['test'], -5, 5) === '.phpt') { + is_string($this->arguments['test']) && + substr($this->arguments['test'], -5, 5) === '.phpt') { $suite = new TestSuite; $suite->addTestFile($this->arguments['test']); $this->arguments['test'] = $suite; @@ -833,9 +865,9 @@ protected function handleArguments(array $argv): void } if (isset($includePath)) { - \ini_set( + ini_set( 'include_path', - $includePath . \PATH_SEPARATOR . \ini_get('include_path') + $includePath . PATH_SEPARATOR . ini_get('include_path') ); } @@ -844,24 +876,24 @@ protected function handleArguments(array $argv): void } if (isset($this->arguments['configuration']) && - \is_dir($this->arguments['configuration'])) { + is_dir($this->arguments['configuration'])) { $configurationFile = $this->arguments['configuration'] . '/phpunit.xml'; - if (\file_exists($configurationFile)) { - $this->arguments['configuration'] = \realpath( + if (file_exists($configurationFile)) { + $this->arguments['configuration'] = realpath( $configurationFile ); - } elseif (\file_exists($configurationFile . '.dist')) { - $this->arguments['configuration'] = \realpath( + } elseif (file_exists($configurationFile . '.dist')) { + $this->arguments['configuration'] = realpath( $configurationFile . '.dist' ); } } elseif (!isset($this->arguments['configuration']) && $this->arguments['useDefaultConfiguration']) { - if (\file_exists('phpunit.xml')) { - $this->arguments['configuration'] = \realpath('phpunit.xml'); - } elseif (\file_exists('phpunit.xml.dist')) { - $this->arguments['configuration'] = \realpath( + if (file_exists('phpunit.xml')) { + $this->arguments['configuration'] = realpath('phpunit.xml'); + } elseif (file_exists('phpunit.xml.dist')) { + $this->arguments['configuration'] = realpath( 'phpunit.xml.dist' ); } @@ -873,7 +905,7 @@ protected function handleArguments(array $argv): void $this->arguments['configuration'] ); } catch (Throwable $t) { - print $t->getMessage() . \PHP_EOL; + print $t->getMessage() . PHP_EOL; exit(TestRunner::FAILURE_EXIT); } @@ -898,7 +930,7 @@ protected function handleArguments(array $argv): void $this->arguments['stderr'] = $phpunitConfiguration['stderr']; } - if (isset($phpunitConfiguration['extensionsDirectory']) && !isset($this->arguments['noExtensions']) && \extension_loaded('phar')) { + if (isset($phpunitConfiguration['extensionsDirectory']) && !isset($this->arguments['noExtensions']) && extension_loaded('phar')) { $this->handleExtensions($phpunitConfiguration['extensionsDirectory']); } @@ -940,7 +972,7 @@ protected function handleArguments(array $argv): void } if (isset($this->arguments['printer']) && - \is_string($this->arguments['printer'])) { + is_string($this->arguments['printer'])) { $this->arguments['printer'] = $this->handlePrinter($this->arguments['printer']); } @@ -956,25 +988,25 @@ protected function handleArguments(array $argv): void */ protected function handleLoader(string $loaderClass, string $loaderFile = ''): ?TestSuiteLoader { - if (!\class_exists($loaderClass, false)) { + if (!class_exists($loaderClass, false)) { if ($loaderFile == '') { $loaderFile = Filesystem::classNameToFilename( $loaderClass ); } - $loaderFile = \stream_resolve_include_path($loaderFile); + $loaderFile = stream_resolve_include_path($loaderFile); if ($loaderFile) { require $loaderFile; } } - if (\class_exists($loaderClass, false)) { + if (class_exists($loaderClass, false)) { try { - $class = new \ReflectionClass($loaderClass); + $class = new ReflectionClass($loaderClass); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -986,7 +1018,7 @@ protected function handleLoader(string $loaderClass, string $loaderFile = ''): ? if ($class->implementsInterface(TestSuiteLoader::class) && $class->isInstantiable()) { $object = $class->newInstance(); - \assert($object instanceof TestSuiteLoader); + assert($object instanceof TestSuiteLoader); return $object; } @@ -997,7 +1029,7 @@ protected function handleLoader(string $loaderClass, string $loaderFile = ''): ? } $this->exitWithErrorMessage( - \sprintf( + sprintf( 'Could not use "%s" as loader.', $loaderClass ) @@ -1013,23 +1045,23 @@ protected function handleLoader(string $loaderClass, string $loaderFile = ''): ? */ protected function handlePrinter(string $printerClass, string $printerFile = '') { - if (!\class_exists($printerClass, false)) { + if (!class_exists($printerClass, false)) { if ($printerFile == '') { $printerFile = Filesystem::classNameToFilename( $printerClass ); } - $printerFile = \stream_resolve_include_path($printerFile); + $printerFile = stream_resolve_include_path($printerFile); if ($printerFile) { require $printerFile; } } - if (!\class_exists($printerClass)) { + if (!class_exists($printerClass)) { $this->exitWithErrorMessage( - \sprintf( + sprintf( 'Could not use "%s" as printer: class does not exist', $printerClass ) @@ -1037,9 +1069,9 @@ protected function handlePrinter(string $printerClass, string $printerFile = '') } try { - $class = new \ReflectionClass($printerClass); + $class = new ReflectionClass($printerClass); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -1050,7 +1082,7 @@ protected function handlePrinter(string $printerClass, string $printerFile = '') if (!$class->implementsInterface(TestListener::class)) { $this->exitWithErrorMessage( - \sprintf( + sprintf( 'Could not use "%s" as printer: class does not implement %s', $printerClass, TestListener::class @@ -1060,7 +1092,7 @@ protected function handlePrinter(string $printerClass, string $printerFile = '') if (!$class->isSubclassOf(Printer::class)) { $this->exitWithErrorMessage( - \sprintf( + sprintf( 'Could not use "%s" as printer: class does not extend %s', $printerClass, Printer::class @@ -1070,7 +1102,7 @@ protected function handlePrinter(string $printerClass, string $printerFile = '') if (!$class->isInstantiable()) { $this->exitWithErrorMessage( - \sprintf( + sprintf( 'Could not use "%s" as printer: class cannot be instantiated', $printerClass ) @@ -1102,17 +1134,17 @@ protected function handleVersionCheck(): void { $this->printVersionString(); - $latestVersion = \file_get_contents('https://phar.phpunit.de/latest-version-of/phpunit'); - $isOutdated = \version_compare($latestVersion, Version::id(), '>'); + $latestVersion = file_get_contents('https://phar.phpunit.de/latest-version-of/phpunit'); + $isOutdated = version_compare($latestVersion, Version::id(), '>'); if ($isOutdated) { - \printf( - 'You are not using the latest version of PHPUnit.' . \PHP_EOL . - 'The latest version is PHPUnit %s.' . \PHP_EOL, + printf( + 'You are not using the latest version of PHPUnit.' . PHP_EOL . + 'The latest version is PHPUnit %s.' . PHP_EOL, $latestVersion ); } else { - print 'You are using the latest version of PHPUnit.' . \PHP_EOL; + print 'You are using the latest version of PHPUnit.' . PHP_EOL; } exit(TestRunner::SUCCESS_EXIT); @@ -1140,7 +1172,7 @@ private function printVersionString(): void return; } - print Version::getVersionString() . \PHP_EOL . \PHP_EOL; + print Version::getVersionString() . PHP_EOL . PHP_EOL; $this->versionStringPrinted = true; } @@ -1149,7 +1181,7 @@ private function exitWithErrorMessage(string $message): void { $this->printVersionString(); - print $message . \PHP_EOL; + print $message . PHP_EOL; exit(TestRunner::FAILURE_EXIT); } @@ -1157,7 +1189,7 @@ private function exitWithErrorMessage(string $message): void private function handleExtensions(string $directory): void { foreach ((new FileIteratorFacade)->getFilesAsArray($directory, '.phar') as $file) { - if (!\file_exists('phar://' . $file . '/manifest.xml')) { + if (!file_exists('phar://' . $file . '/manifest.xml')) { $this->arguments['notLoadedExtensions'][] = $file . ' is not an extension for PHPUnit'; continue; @@ -1187,7 +1219,7 @@ private function handleExtensions(string $directory): void require $file; - $this->arguments['loadedExtensions'][] = $manifest->getName() . ' ' . $manifest->getVersion()->getVersionString(); + $this->arguments['loadedExtensions'][] = $manifest->getName()->asString() . ' ' . $manifest->getVersion()->getVersionString(); } } @@ -1195,14 +1227,14 @@ private function handleListGroups(TestSuite $suite, bool $exit): int { $this->printVersionString(); - print 'Available test group(s):' . \PHP_EOL; + print 'Available test group(s):' . PHP_EOL; $groups = $suite->getGroups(); - \sort($groups); + sort($groups); foreach ($groups as $group) { - \printf( - ' - %s' . \PHP_EOL, + printf( + ' - %s' . PHP_EOL, $group ); } @@ -1221,15 +1253,15 @@ private function handleListSuites(bool $exit): int { $this->printVersionString(); - print 'Available test suite(s):' . \PHP_EOL; + print 'Available test suite(s):' . PHP_EOL; $configuration = Configuration::getInstance( $this->arguments['configuration'] ); foreach ($configuration->getTestSuiteNames() as $suiteName) { - \printf( - ' - %s' . \PHP_EOL, + printf( + ' - %s' . PHP_EOL, $suiteName ); } @@ -1268,10 +1300,10 @@ private function handleListTestsXml(TestSuite $suite, string $target, bool $exit $renderer = new XmlTestListRenderer; - \file_put_contents($target, $renderer->render($suite)); + file_put_contents($target, $renderer->render($suite)); - \printf( - 'Wrote list of tests that would have been run to %s' . \PHP_EOL, + printf( + 'Wrote list of tests that would have been run to %s' . PHP_EOL, $target ); @@ -1284,7 +1316,7 @@ private function handleListTestsXml(TestSuite $suite, string $target, bool $exit private function handleOrderByOption(string $value): void { - foreach (\explode(',', $value) as $order) { + foreach (explode(',', $value) as $order) { switch ($order) { case 'default': $this->arguments['executionOrder'] = TestSuiteSorter::ORDER_DEFAULT; diff --git a/src/TextUI/Exception.php b/src/TextUI/Exception.php index a660a873376..7c261e58e7f 100644 --- a/src/TextUI/Exception.php +++ b/src/TextUI/Exception.php @@ -9,9 +9,11 @@ */ namespace PHPUnit\TextUI; +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 { } diff --git a/src/TextUI/Help.php b/src/TextUI/Help.php index 4d3fd4121ff..f5af31147fa 100644 --- a/src/TextUI/Help.php +++ b/src/TextUI/Help.php @@ -9,6 +9,15 @@ */ namespace PHPUnit\TextUI; +use const PHP_EOL; +use function count; +use function explode; +use function max; +use function preg_replace_callback; +use function str_pad; +use function str_repeat; +use function strlen; +use function wordwrap; use PHPUnit\Util\Color; use SebastianBergmann\Environment\Console; @@ -159,7 +168,7 @@ public function __construct(?int $width = null, ?bool $withColor = null) foreach (self::HELP_TEXT as $options) { foreach ($options as $option) { if (isset($option['arg'])) { - $this->maxArgLength = \max($this->maxArgLength, isset($option['arg']) ? \strlen($option['arg']) : 0); + $this->maxArgLength = max($this->maxArgLength, isset($option['arg']) ? strlen($option['arg']) : 0); } } } @@ -168,7 +177,7 @@ public function __construct(?int $width = null, ?bool $withColor = null) } /** - * Write the help file to the CLI, adapting width and colors to the console + * Write the help file to the CLI, adapting width and colors to the console. */ public function writeToConsole(): void { @@ -182,65 +191,65 @@ public function writeToConsole(): void private function writePlaintext(): void { foreach (self::HELP_TEXT as $section => $options) { - print "{$section}:" . \PHP_EOL; + print "{$section}:" . PHP_EOL; if ($section !== 'Usage') { - print \PHP_EOL; + print PHP_EOL; } foreach ($options as $option) { if (isset($option['spacer'])) { - print \PHP_EOL; + print PHP_EOL; } if (isset($option['text'])) { - print self::LEFT_MARGIN . $option['text'] . \PHP_EOL; + print self::LEFT_MARGIN . $option['text'] . PHP_EOL; } if (isset($option['arg'])) { - $arg = \str_pad($option['arg'], $this->maxArgLength); - print self::LEFT_MARGIN . $arg . ' ' . $option['desc'] . \PHP_EOL; + $arg = str_pad($option['arg'], $this->maxArgLength); + print self::LEFT_MARGIN . $arg . ' ' . $option['desc'] . PHP_EOL; } } - print \PHP_EOL; + print PHP_EOL; } } private function writeWithColor(): void { foreach (self::HELP_TEXT as $section => $options) { - print Color::colorize('fg-yellow', "{$section}:") . \PHP_EOL; + print Color::colorize('fg-yellow', "{$section}:") . PHP_EOL; foreach ($options as $option) { if (isset($option['spacer'])) { - print \PHP_EOL; + print PHP_EOL; } if (isset($option['text'])) { - print self::LEFT_MARGIN . $option['text'] . \PHP_EOL; + print self::LEFT_MARGIN . $option['text'] . PHP_EOL; } if (isset($option['arg'])) { - $arg = Color::colorize('fg-green', \str_pad($option['arg'], $this->maxArgLength)); - $arg = \preg_replace_callback( + $arg = Color::colorize('fg-green', str_pad($option['arg'], $this->maxArgLength)); + $arg = preg_replace_callback( '/(<[^>]+>)/', static function ($matches) { return Color::colorize('fg-cyan', $matches[0]); }, $arg ); - $desc = \explode(\PHP_EOL, \wordwrap($option['desc'], $this->maxDescLength, \PHP_EOL)); + $desc = explode(PHP_EOL, wordwrap($option['desc'], $this->maxDescLength, PHP_EOL)); - print self::LEFT_MARGIN . $arg . ' ' . $desc[0] . \PHP_EOL; + print self::LEFT_MARGIN . $arg . ' ' . $desc[0] . PHP_EOL; - for ($i = 1; $i < \count($desc); $i++) { - print \str_repeat(' ', $this->maxArgLength + 3) . $desc[$i] . \PHP_EOL; + for ($i = 1; $i < count($desc); $i++) { + print str_repeat(' ', $this->maxArgLength + 3) . $desc[$i] . PHP_EOL; } } } - print \PHP_EOL; + print PHP_EOL; } } } diff --git a/src/TextUI/ResultPrinter.php b/src/TextUI/ResultPrinter.php index 32a0aa48dfb..c4d06b3d243 100644 --- a/src/TextUI/ResultPrinter.php +++ b/src/TextUI/ResultPrinter.php @@ -9,6 +9,21 @@ */ namespace PHPUnit\TextUI; +use const PHP_EOL; +use function array_map; +use function array_reverse; +use function count; +use function floor; +use function implode; +use function in_array; +use function is_int; +use function max; +use function preg_split; +use function sprintf; +use function str_pad; +use function str_repeat; +use function strlen; +use function vsprintf; use PHPUnit\Framework\AssertionFailedError; use PHPUnit\Framework\Exception; use PHPUnit\Framework\InvalidArgumentException; @@ -24,6 +39,7 @@ use PHPUnit\Util\Printer; use SebastianBergmann\Environment\Console; use SebastianBergmann\Timer\Timer; +use Throwable; /** * @internal This class is not covered by the backward compatibility promise for PHPUnit @@ -125,14 +141,14 @@ public function __construct($out = null, bool $verbose = false, string $colors = { parent::__construct($out); - if (!\in_array($colors, self::AVAILABLE_COLORS, true)) { + if (!in_array($colors, self::AVAILABLE_COLORS, true)) { throw InvalidArgumentException::create( 3, - \vsprintf('value from "%s", "%s" or "%s"', self::AVAILABLE_COLORS) + vsprintf('value from "%s", "%s" or "%s"', self::AVAILABLE_COLORS) ); } - if (!\is_int($numberOfColumns) && $numberOfColumns !== 'max') { + if (!is_int($numberOfColumns) && $numberOfColumns !== 'max') { throw InvalidArgumentException::create(5, 'integer or "max"'); } @@ -177,7 +193,7 @@ public function printResult(TestResult $result): void /** * An error occurred. */ - public function addError(Test $test, \Throwable $t, float $time): void + public function addError(Test $test, Throwable $t, float $time): void { $this->writeProgressWithColor('fg-red, bold', 'E'); $this->lastTestFailed = true; @@ -204,7 +220,7 @@ public function addWarning(Test $test, Warning $e, float $time): void /** * Incomplete test. */ - public function addIncompleteTest(Test $test, \Throwable $t, float $time): void + public function addIncompleteTest(Test $test, Throwable $t, float $time): void { $this->writeProgressWithColor('fg-yellow, bold', 'I'); $this->lastTestFailed = true; @@ -213,7 +229,7 @@ public function addIncompleteTest(Test $test, \Throwable $t, float $time): void /** * Risky test. */ - public function addRiskyTest(Test $test, \Throwable $t, float $time): void + public function addRiskyTest(Test $test, Throwable $t, float $time): void { $this->writeProgressWithColor('fg-yellow, bold', 'R'); $this->lastTestFailed = true; @@ -222,7 +238,7 @@ public function addRiskyTest(Test $test, \Throwable $t, float $time): void /** * Skipped test. */ - public function addSkippedTest(Test $test, \Throwable $t, float $time): void + public function addSkippedTest(Test $test, Throwable $t, float $time): void { $this->writeProgressWithColor('fg-cyan, bold', 'S'); $this->lastTestFailed = true; @@ -234,9 +250,9 @@ public function addSkippedTest(Test $test, \Throwable $t, float $time): void public function startTestSuite(TestSuite $suite): void { if ($this->numTests == -1) { - $this->numTests = \count($suite); - $this->numTestsWidth = \strlen((string) $this->numTests); - $this->maxColumn = $this->numberOfColumns - \strlen(' / (XXX%)') - (2 * $this->numTestsWidth); + $this->numTests = count($suite); + $this->numTestsWidth = strlen((string) $this->numTests); + $this->maxColumn = $this->numberOfColumns - strlen(' / (XXX%)') - (2 * $this->numTestsWidth); } } @@ -254,7 +270,7 @@ public function startTest(Test $test): void { if ($this->debug) { $this->write( - \sprintf( + sprintf( "Test '%s' started\n", \PHPUnit\Util\Test::describeAsString($test) ) @@ -269,7 +285,7 @@ public function endTest(Test $test, float $time): void { if ($this->debug) { $this->write( - \sprintf( + sprintf( "Test '%s' ended\n", \PHPUnit\Util\Test::describeAsString($test) ) @@ -295,7 +311,7 @@ public function endTest(Test $test, float $time): void protected function printDefects(array $defects, string $type): void { - $count = \count($defects); + $count = count($defects); if ($count == 0) { return; @@ -306,7 +322,7 @@ protected function printDefects(array $defects, string $type): void } $this->write( - \sprintf( + sprintf( "There %s %d %s%s:\n", ($count == 1) ? 'was' : 'were', $count, @@ -318,7 +334,7 @@ protected function printDefects(array $defects, string $type): void $i = 1; if ($this->reverse) { - $defects = \array_reverse($defects); + $defects = array_reverse($defects); } foreach ($defects as $defect) { @@ -337,7 +353,7 @@ protected function printDefect(TestFailure $defect, int $count): void protected function printDefectHeader(TestFailure $defect, int $count): void { $this->write( - \sprintf( + sprintf( "\n%d) %s\n", $count, $defect->getTestName() @@ -390,14 +406,14 @@ protected function printSkipped(TestResult $result): void */ protected function printHeader(TestResult $result): void { - if (\count($result) > 0) { - $this->write(\PHP_EOL . \PHP_EOL . Timer::resourceUsage() . \PHP_EOL . \PHP_EOL); + if (count($result) > 0) { + $this->write(PHP_EOL . PHP_EOL . Timer::resourceUsage() . PHP_EOL . PHP_EOL); } } protected function printFooter(TestResult $result): void { - if (\count($result) === 0) { + if (count($result) === 0) { $this->writeWithColor( 'fg-black, bg-yellow', 'No tests executed!' @@ -409,10 +425,10 @@ protected function printFooter(TestResult $result): void if ($result->wasSuccessfulAndNoTestIsRiskyOrSkippedOrIncomplete()) { $this->writeWithColor( 'fg-black, bg-green', - \sprintf( + sprintf( 'OK (%d test%s, %d assertion%s)', - \count($result), - (\count($result) == 1) ? '' : 's', + count($result), + (count($result) == 1) ? '' : 's', $this->numAssertions, ($this->numAssertions == 1) ? '' : 's' ) @@ -459,7 +475,7 @@ protected function printFooter(TestResult $result): void } } - $this->writeCountString(\count($result), 'Tests', $color, true); + $this->writeCountString(count($result), 'Tests', $color, true); $this->writeCountString($this->numAssertions, 'Assertions', $color, true); $this->writeCountString($result->errorCount(), 'Errors', $color); $this->writeCountString($result->failureCount(), 'Failures', $color); @@ -482,16 +498,16 @@ protected function writeProgress(string $progress): void if ($this->column == $this->maxColumn || $this->numTestsRun == $this->numTests) { if ($this->numTestsRun == $this->numTests) { - $this->write(\str_repeat(' ', $this->maxColumn - $this->column)); + $this->write(str_repeat(' ', $this->maxColumn - $this->column)); } $this->write( - \sprintf( + sprintf( ' %' . $this->numTestsWidth . 'd / %' . $this->numTestsWidth . 'd (%3s%%)', $this->numTestsRun, $this->numTests, - \floor(($this->numTestsRun / $this->numTests) * 100) + floor(($this->numTestsRun / $this->numTests) * 100) ) ); @@ -517,16 +533,16 @@ protected function colorizeTextBox(string $color, string $buffer): string return $buffer; } - $lines = \preg_split('/\r\n|\r|\n/', $buffer); - $padding = \max(\array_map('\strlen', $lines)); + $lines = preg_split('/\r\n|\r|\n/', $buffer); + $padding = max(array_map('\strlen', $lines)); $styledLines = []; foreach ($lines as $line) { - $styledLines[] = Color::colorize($color, \str_pad($line, $padding)); + $styledLines[] = Color::colorize($color, str_pad($line, $padding)); } - return \implode(\PHP_EOL, $styledLines); + return implode(PHP_EOL, $styledLines); } /** @@ -537,7 +553,7 @@ protected function writeWithColor(string $color, string $buffer, bool $lf = true $this->write($this->colorizeTextBox($color, $buffer)); if ($lf) { - $this->write(\PHP_EOL); + $this->write(PHP_EOL); } } @@ -557,7 +573,7 @@ private function writeCountString(int $count, string $name, string $color, bool if ($always || $count > 0) { $this->writeWithColor( $color, - \sprintf( + sprintf( '%s%s: %d', !$first ? ', ' : '', $name, diff --git a/src/TextUI/TestRunner.php b/src/TextUI/TestRunner.php index c2e72dad235..017b63a63f3 100644 --- a/src/TextUI/TestRunner.php +++ b/src/TextUI/TestRunner.php @@ -9,6 +9,27 @@ */ namespace PHPUnit\TextUI; +use const PHP_EOL; +use const PHP_MAJOR_VERSION; +use const PHP_SAPI; +use function array_diff; +use function assert; +use function class_exists; +use function count; +use function dirname; +use function extension_loaded; +use function file_put_contents; +use function htmlspecialchars; +use function ini_get; +use function is_int; +use function is_string; +use function is_subclass_of; +use function mt_srand; +use function range; +use function realpath; +use function sprintf; +use function strpos; +use function time; use PHPUnit\Framework\Exception; use PHPUnit\Framework\Test; use PHPUnit\Framework\TestCase; @@ -42,6 +63,8 @@ use PHPUnit\Util\TestDox\TextResultPrinter; use PHPUnit\Util\TestDox\XmlResultPrinter; use PHPUnit\Util\XdebugFilterScriptGenerator; +use ReflectionClass; +use ReflectionException; use SebastianBergmann\CodeCoverage\CodeCoverage; use SebastianBergmann\CodeCoverage\Exception as CodeCoverageException; use SebastianBergmann\CodeCoverage\Filter as CodeCoverageFilter; @@ -125,7 +148,7 @@ public function doRun(Test $suite, array $arguments = [], array $warnings = [], $this->handleConfiguration($arguments); - if (\is_int($arguments['columns']) && $arguments['columns'] < 16) { + if (is_int($arguments['columns']) && $arguments['columns'] < 16) { $arguments['columns'] = 16; $tooFewColumnsRequested = true; } @@ -149,7 +172,7 @@ public function doRun(Test $suite, array $arguments = [], array $warnings = [], } if ($arguments['executionOrder'] === TestSuiteSorter::ORDER_RANDOMIZED) { - \mt_srand($arguments['randomOrderSeed']); + mt_srand($arguments['randomOrderSeed']); } if ($arguments['cacheResult']) { @@ -162,10 +185,10 @@ public function doRun(Test $suite, array $arguments = [], array $warnings = [], $arguments['cacheResultFile'] = null; - $cacheResultFile = \realpath($cacheLocation); + $cacheResultFile = realpath($cacheLocation); if ($cacheResultFile !== false) { - $arguments['cacheResultFile'] = \dirname($cacheResultFile); + $arguments['cacheResultFile'] = dirname($cacheResultFile); } } @@ -187,11 +210,11 @@ public function doRun(Test $suite, array $arguments = [], array $warnings = [], unset($sorter); } - if (\is_int($arguments['repeat']) && $arguments['repeat'] > 0) { + if (is_int($arguments['repeat']) && $arguments['repeat'] > 0) { $_suite = new TestSuite; /* @noinspection PhpUnusedLocalVariableInspection */ - foreach (\range(1, $arguments['repeat']) as $step) { + foreach (range(1, $arguments['repeat']) as $step) { $_suite->addTest($suite); } @@ -271,11 +294,11 @@ public function doRun(Test $suite, array $arguments = [], array $warnings = [], if (isset($arguments['printer'])) { if ($arguments['printer'] instanceof Printer && $arguments['printer'] instanceof TestListener) { $this->printer = $arguments['printer']; - } elseif (\is_string($arguments['printer']) && \class_exists($arguments['printer'], false)) { + } elseif (is_string($arguments['printer']) && class_exists($arguments['printer'], false)) { try { - new \ReflectionClass($arguments['printer']); + new ReflectionClass($arguments['printer']); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -284,7 +307,7 @@ public function doRun(Test $suite, array $arguments = [], array $warnings = [], } // @codeCoverageIgnoreEnd - if (\is_subclass_of($arguments['printer'], ResultPrinter::class)) { + if (is_subclass_of($arguments['printer'], ResultPrinter::class)) { $this->printer = $this->createPrinter($arguments['printer'], $arguments); } } @@ -294,7 +317,7 @@ public function doRun(Test $suite, array $arguments = [], array $warnings = [], } if (isset($originalExecutionOrder) && $this->printer instanceof CliTestDoxPrinter) { - \assert($this->printer instanceof CliTestDoxPrinter); + assert($this->printer instanceof CliTestDoxPrinter); $this->printer->setOriginalExecutionOrder($originalExecutionOrder); $this->printer->setShowProgressAnimation(!$arguments['noInteraction']); @@ -356,10 +379,10 @@ public function doRun(Test $suite, array $arguments = [], array $warnings = [], ); foreach ($arguments['configuration']->getValidationErrors() as $line => $errors) { - $this->write(\sprintf("\n Line %d:\n", $line)); + $this->write(sprintf("\n Line %d:\n", $line)); foreach ($errors as $msg) { - $this->write(\sprintf(" - %s\n", $msg)); + $this->write(sprintf(" - %s\n", $msg)); } } @@ -451,7 +474,7 @@ public function doRun(Test $suite, array $arguments = [], array $warnings = [], $codeCoverageReports = 0; } - if ($codeCoverageReports > 0 && !$this->runtime->canCollectCodeCoverage()) { + if ($codeCoverageReports > 0 && PHP_MAJOR_VERSION < 8 && !$this->runtime->canCollectCodeCoverage()) { $this->writeMessage('Error', 'No code coverage driver is available'); $codeCoverageReports = 0; @@ -503,65 +526,71 @@ public function doRun(Test $suite, array $arguments = [], array $warnings = [], } if ($codeCoverageReports > 0) { - try { - $codeCoverage = new CodeCoverage( - null, - $this->codeCoverageFilter - ); - - $codeCoverage->setUnintentionallyCoveredSubclassesWhitelist( - [Comparator::class] - ); + if (PHP_MAJOR_VERSION >= 8) { + $this->writeMessage('Error', 'This version of PHPUnit does not support code coverage on PHP 8'); - $codeCoverage->setCheckForUnintentionallyCoveredCode( - $arguments['strictCoverage'] - ); + $codeCoverageReports = 0; + } else { + try { + $codeCoverage = new CodeCoverage( + null, + $this->codeCoverageFilter + ); - $codeCoverage->setCheckForMissingCoversAnnotation( - $arguments['strictCoverage'] - ); + $codeCoverage->setUnintentionallyCoveredSubclassesWhitelist( + [Comparator::class] + ); - if (isset($arguments['forceCoversAnnotation'])) { - $codeCoverage->setForceCoversAnnotation( - $arguments['forceCoversAnnotation'] + $codeCoverage->setCheckForUnintentionallyCoveredCode( + $arguments['strictCoverage'] ); - } - if (isset($arguments['ignoreDeprecatedCodeUnitsFromCodeCoverage'])) { - $codeCoverage->setIgnoreDeprecatedCode( - $arguments['ignoreDeprecatedCodeUnitsFromCodeCoverage'] + $codeCoverage->setCheckForMissingCoversAnnotation( + $arguments['strictCoverage'] ); - } - if (isset($arguments['disableCodeCoverageIgnore'])) { - $codeCoverage->setDisableIgnoredLines(true); - } + if (isset($arguments['forceCoversAnnotation'])) { + $codeCoverage->setForceCoversAnnotation( + $arguments['forceCoversAnnotation'] + ); + } - if (!empty($filterConfiguration['whitelist'])) { - $codeCoverage->setAddUncoveredFilesFromWhitelist( - $filterConfiguration['whitelist']['addUncoveredFilesFromWhitelist'] - ); + if (isset($arguments['ignoreDeprecatedCodeUnitsFromCodeCoverage'])) { + $codeCoverage->setIgnoreDeprecatedCode( + $arguments['ignoreDeprecatedCodeUnitsFromCodeCoverage'] + ); + } - $codeCoverage->setProcessUncoveredFilesFromWhitelist( - $filterConfiguration['whitelist']['processUncoveredFilesFromWhitelist'] - ); - } + if (isset($arguments['disableCodeCoverageIgnore'])) { + $codeCoverage->setDisableIgnoredLines(true); + } + + if (!empty($filterConfiguration['whitelist'])) { + $codeCoverage->setAddUncoveredFilesFromWhitelist( + $filterConfiguration['whitelist']['addUncoveredFilesFromWhitelist'] + ); + + $codeCoverage->setProcessUncoveredFilesFromWhitelist( + $filterConfiguration['whitelist']['processUncoveredFilesFromWhitelist'] + ); + } + + if (!$this->codeCoverageFilter->hasWhitelist()) { + if (!$whitelistFromConfigurationFile && !$whitelistFromOption) { + $this->writeMessage('Error', 'No whitelist is configured, no code coverage will be generated.'); + } else { + $this->writeMessage('Error', 'Incorrect whitelist config, no code coverage will be generated.'); + } + + $codeCoverageReports = 0; - if (!$this->codeCoverageFilter->hasWhitelist()) { - if (!$whitelistFromConfigurationFile && !$whitelistFromOption) { - $this->writeMessage('Error', 'No whitelist is configured, no code coverage will be generated.'); - } else { - $this->writeMessage('Error', 'Incorrect whitelist config, no code coverage will be generated.'); + unset($codeCoverage); } + } catch (CodeCoverageException $e) { + $this->writeMessage('Error', $e->getMessage()); $codeCoverageReports = 0; - - unset($codeCoverage); } - } catch (CodeCoverageException $e) { - $this->writeMessage('Error', $e->getMessage()); - - $codeCoverageReports = 0; } } @@ -570,15 +599,15 @@ public function doRun(Test $suite, array $arguments = [], array $warnings = [], $script = (new XdebugFilterScriptGenerator)->generate($filterConfiguration['whitelist']); - if ($arguments['xdebugFilterFile'] !== 'php://stdout' && $arguments['xdebugFilterFile'] !== 'php://stderr' && !Filesystem::createDirectory(\dirname($arguments['xdebugFilterFile']))) { - $this->write(\sprintf('Cannot write Xdebug filter script to %s ' . \PHP_EOL, $arguments['xdebugFilterFile'])); + if ($arguments['xdebugFilterFile'] !== 'php://stdout' && $arguments['xdebugFilterFile'] !== 'php://stderr' && !Filesystem::createDirectory(dirname($arguments['xdebugFilterFile']))) { + $this->write(sprintf('Cannot write Xdebug filter script to %s ' . PHP_EOL, $arguments['xdebugFilterFile'])); exit(self::EXCEPTION_EXIT); } - \file_put_contents($arguments['xdebugFilterFile'], $script); + file_put_contents($arguments['xdebugFilterFile'], $script); - $this->write(\sprintf('Wrote Xdebug filter script to %s ' . \PHP_EOL, $arguments['xdebugFilterFile'])); + $this->write(sprintf('Wrote Xdebug filter script to %s ' . PHP_EOL, $arguments['xdebugFilterFile'])); exit(self::SUCCESS_EXIT); } @@ -599,11 +628,11 @@ public function doRun(Test $suite, array $arguments = [], array $warnings = [], $result->beStrictAboutResourceUsageDuringSmallTests($arguments['beStrictAboutResourceUsageDuringSmallTests']); if ($arguments['enforceTimeLimit'] === true) { - if (!\class_exists(Invoker::class)) { + if (!class_exists(Invoker::class)) { $this->writeMessage('Error', 'Package phpunit/php-invoker is required for enforcing time limits'); } - if (!\extension_loaded('pcntl') || \strpos(\ini_get('disable_functions'), 'pcntl') !== false) { + if (!extension_loaded('pcntl') || strpos(ini_get('disable_functions'), 'pcntl') !== false) { $this->writeMessage('Error', 'PHP extension pcntl is required for enforcing time limits'); } } @@ -676,7 +705,7 @@ public function doRun(Test $suite, array $arguments = [], array $warnings = [], $writer = new HtmlReport( $arguments['reportLowUpperBound'], $arguments['reportHighLowerBound'], - \sprintf( + sprintf( ' and PHPUnit %s', Version::id() ) @@ -797,7 +826,7 @@ public function addExtension(Hook $extension): void */ protected function runFailed(string $message): void { - $this->write($message . \PHP_EOL); + $this->write($message . PHP_EOL); exit(self::FAILURE_EXIT); } @@ -809,8 +838,8 @@ private function createTestResult(): TestResult private function write(string $buffer): void { - if (\PHP_SAPI !== 'cli' && \PHP_SAPI !== 'phpdbg') { - $buffer = \htmlspecialchars($buffer); + if (PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg') { + $buffer = htmlspecialchars($buffer); } if ($this->printer !== null) { @@ -1030,17 +1059,17 @@ private function handleConfiguration(array &$arguments): void } if (!empty($groupConfiguration['exclude']) && !isset($arguments['excludeGroups'])) { - $arguments['excludeGroups'] = \array_diff($groupConfiguration['exclude'], $groupCliArgs); + $arguments['excludeGroups'] = array_diff($groupConfiguration['exclude'], $groupCliArgs); } foreach ($arguments['configuration']->getExtensionConfiguration() as $extension) { - if ($extension['file'] !== '' && !\class_exists($extension['class'], false)) { + if ($extension['file'] !== '' && !class_exists($extension['class'], false)) { require_once $extension['file']; } - if (!\class_exists($extension['class'])) { + if (!class_exists($extension['class'])) { throw new Exception( - \sprintf( + sprintf( 'Class "%s" does not exist', $extension['class'] ) @@ -1048,9 +1077,9 @@ private function handleConfiguration(array &$arguments): void } try { - $extensionClass = new \ReflectionClass($extension['class']); + $extensionClass = new ReflectionClass($extension['class']); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -1061,14 +1090,14 @@ private function handleConfiguration(array &$arguments): void if (!$extensionClass->implementsInterface(Hook::class)) { throw new Exception( - \sprintf( + sprintf( 'Class "%s" does not implement a PHPUnit\Runner\Hook interface', $extension['class'] ) ); } - if (\count($extension['arguments']) === 0) { + if (count($extension['arguments']) === 0) { $extensionObject = $extensionClass->newInstance(); } else { $extensionObject = $extensionClass->newInstanceArgs( @@ -1076,19 +1105,19 @@ private function handleConfiguration(array &$arguments): void ); } - \assert($extensionObject instanceof Hook); + assert($extensionObject instanceof Hook); $this->addExtension($extensionObject); } foreach ($arguments['configuration']->getListenerConfiguration() as $listener) { - if ($listener['file'] !== '' && !\class_exists($listener['class'], false)) { + if ($listener['file'] !== '' && !class_exists($listener['class'], false)) { require_once $listener['file']; } - if (!\class_exists($listener['class'])) { + if (!class_exists($listener['class'])) { throw new Exception( - \sprintf( + sprintf( 'Class "%s" does not exist', $listener['class'] ) @@ -1096,9 +1125,9 @@ private function handleConfiguration(array &$arguments): void } try { - $listenerClass = new \ReflectionClass($listener['class']); + $listenerClass = new ReflectionClass($listener['class']); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -1109,14 +1138,14 @@ private function handleConfiguration(array &$arguments): void if (!$listenerClass->implementsInterface(TestListener::class)) { throw new Exception( - \sprintf( + sprintf( 'Class "%s" does not implement the PHPUnit\Framework\TestListener interface', $listener['class'] ) ); } - if (\count($listener['arguments']) === 0) { + if (count($listener['arguments']) === 0) { $listener = new $listener['class']; } else { $listener = $listenerClass->newInstanceArgs( @@ -1234,7 +1263,7 @@ private function handleConfiguration(array &$arguments): void $arguments['noInteraction'] = $arguments['noInteraction'] ?? false; $arguments['processIsolation'] = $arguments['processIsolation'] ?? false; $arguments['processUncoveredFilesFromWhitelist'] = $arguments['processUncoveredFilesFromWhitelist'] ?? false; - $arguments['randomOrderSeed'] = $arguments['randomOrderSeed'] ?? \time(); + $arguments['randomOrderSeed'] = $arguments['randomOrderSeed'] ?? time(); $arguments['registerMockObjectsFromTestArgumentsRecursively'] = $arguments['registerMockObjectsFromTestArgumentsRecursively'] ?? false; $arguments['repeat'] = $arguments['repeat'] ?? false; $arguments['reportHighLowerBound'] = $arguments['reportHighLowerBound'] ?? 90; @@ -1270,21 +1299,21 @@ private function processSuiteFilters(TestSuite $suite, array $arguments): void if (!empty($arguments['excludeGroups'])) { $filterFactory->addFilter( - new \ReflectionClass(ExcludeGroupFilterIterator::class), + new ReflectionClass(ExcludeGroupFilterIterator::class), $arguments['excludeGroups'] ); } if (!empty($arguments['groups'])) { $filterFactory->addFilter( - new \ReflectionClass(IncludeGroupFilterIterator::class), + new ReflectionClass(IncludeGroupFilterIterator::class), $arguments['groups'] ); } if ($arguments['filter']) { $filterFactory->addFilter( - new \ReflectionClass(NameFilterIterator::class), + new ReflectionClass(NameFilterIterator::class), $arguments['filter'] ); } @@ -1299,7 +1328,7 @@ private function writeMessage(string $type, string $message): void } $this->write( - \sprintf( + sprintf( "%-15s%s\n", $type . ':', $message @@ -1331,7 +1360,7 @@ private function createPrinter(string $class, array $arguments): Printer private function codeCoverageGenerationStart(string $format): void { $this->printer->write( - \sprintf( + sprintf( "\nGenerating code coverage report in %s format ... ", $format ) @@ -1343,7 +1372,7 @@ private function codeCoverageGenerationStart(string $format): void private function codeCoverageGenerationSucceeded(): void { $this->printer->write( - \sprintf( + sprintf( "done [%s]\n", Timer::secondsToTimeString(Timer::stop()) ) @@ -1353,7 +1382,7 @@ private function codeCoverageGenerationSucceeded(): void private function codeCoverageGenerationFailed(\Exception $e): void { $this->printer->write( - \sprintf( + sprintf( "failed [%s]\n%s\n", Timer::secondsToTimeString(Timer::stop()), $e->getMessage() diff --git a/src/Util/Annotation/DocBlock.php b/src/Util/Annotation/DocBlock.php index 9d36c8be3a5..024c19b1134 100644 --- a/src/Util/Annotation/DocBlock.php +++ b/src/Util/Annotation/DocBlock.php @@ -9,12 +9,54 @@ */ namespace PHPUnit\Util\Annotation; +use const JSON_ERROR_NONE; +use const PREG_OFFSET_CAPTURE; +use function array_filter; +use function array_key_exists; +use function array_map; +use function array_merge; +use function array_pop; +use function array_slice; +use function array_values; +use function constant; +use function count; +use function defined; +use function explode; +use function file; +use function implode; +use function is_array; +use function is_int; +use function is_numeric; +use function is_string; +use function json_decode; +use function json_last_error; +use function json_last_error_msg; +use function preg_match; +use function preg_match_all; +use function preg_replace; +use function preg_split; +use function realpath; +use function rtrim; +use function sprintf; +use function str_replace; +use function strlen; +use function strpos; +use function strtolower; +use function substr; +use function substr_count; +use function trim; use PharIo\Version\VersionConstraintParser; use PHPUnit\Framework\InvalidDataProviderException; use PHPUnit\Framework\SkippedTestError; use PHPUnit\Framework\Warning; use PHPUnit\Util\Exception; use PHPUnit\Util\InvalidDataSetException; +use ReflectionClass; +use ReflectionException; +use ReflectionFunctionAbstract; +use ReflectionMethod; +use Reflector; +use Traversable; /** * This is an abstraction around a PHPUnit-specific docBlock, @@ -86,7 +128,7 @@ final class DocBlock */ private $className; - public static function ofClass(\ReflectionClass $class): self + public static function ofClass(ReflectionClass $class): self { $className = $class->getName(); @@ -105,7 +147,7 @@ public static function ofClass(\ReflectionClass $class): self /** * @psalm-param class-string $classNameInHierarchy */ - public static function ofMethod(\ReflectionMethod $method, string $classNameInHierarchy): self + public static function ofMethod(ReflectionMethod $method, string $classNameInHierarchy): self { return new self( (string) $method->getDocComment(), @@ -161,20 +203,20 @@ public function requirements(): array $recordedSettings = []; $extensionVersions = []; $recordedOffsets = [ - '__FILE' => \realpath($this->fileName), + '__FILE' => realpath($this->fileName), ]; // Split docblock into lines and rewind offset to start of docblock - $lines = \preg_split('/\r\n|\r|\n/', $this->docComment); - $offset -= \count($lines); + $lines = preg_split('/\r\n|\r|\n/', $this->docComment); + $offset -= count($lines); foreach ($lines as $line) { - if (\preg_match(self::REGEX_REQUIRES_OS, $line, $matches)) { + if (preg_match(self::REGEX_REQUIRES_OS, $line, $matches)) { $requires[$matches['name']] = $matches['value']; $recordedOffsets[$matches['name']] = $offset; } - if (\preg_match(self::REGEX_REQUIRES_VERSION, $line, $matches)) { + if (preg_match(self::REGEX_REQUIRES_VERSION, $line, $matches)) { $requires[$matches['name']] = [ 'version' => $matches['version'], 'operator' => $matches['operator'], @@ -182,7 +224,7 @@ public function requirements(): array $recordedOffsets[$matches['name']] = $offset; } - if (\preg_match(self::REGEX_REQUIRES_VERSION_CONSTRAINT, $line, $matches)) { + if (preg_match(self::REGEX_REQUIRES_VERSION_CONSTRAINT, $line, $matches)) { if (!empty($requires[$matches['name']])) { $offset++; @@ -193,7 +235,7 @@ public function requirements(): array $versionConstraintParser = new VersionConstraintParser; $requires[$matches['name'] . '_constraint'] = [ - 'constraint' => $versionConstraintParser->parse(\trim($matches['constraint'])), + 'constraint' => $versionConstraintParser->parse(trim($matches['constraint'])), ]; $recordedOffsets[$matches['name'] . '_constraint'] = $offset; } catch (\PharIo\Version\Exception $e) { @@ -202,12 +244,12 @@ public function requirements(): array } } - if (\preg_match(self::REGEX_REQUIRES_SETTING, $line, $matches)) { + if (preg_match(self::REGEX_REQUIRES_SETTING, $line, $matches)) { $recordedSettings[$matches['setting']] = $matches['value']; $recordedOffsets['__SETTING_' . $matches['setting']] = $offset; } - if (\preg_match(self::REGEX_REQUIRES, $line, $matches)) { + if (preg_match(self::REGEX_REQUIRES, $line, $matches)) { $name = $matches['name'] . 's'; if (!isset($requires[$name])) { @@ -228,10 +270,10 @@ public function requirements(): array $offset++; } - return $this->parsedRequirements = \array_merge( + return $this->parsedRequirements = array_merge( $requires, ['__OFFSET' => $recordedOffsets], - \array_filter([ + array_filter([ 'setting' => $recordedSettings, 'extension_versions' => $extensionVersions, ]) @@ -250,9 +292,9 @@ public function requirements(): array */ public function expectedException() { - $docComment = (string) \substr($this->docComment, 3, -2); + $docComment = (string) substr($this->docComment, 3, -2); - if (1 !== \preg_match(self::REGEX_EXPECTED_EXCEPTION, $docComment, $matches)) { + if (1 !== preg_match(self::REGEX_EXPECTED_EXCEPTION, $docComment, $matches)) { return false; } @@ -264,7 +306,7 @@ public function expectedException() $messageRegExp = ''; if (isset($matches[2])) { - $message = \trim($matches[2]); + $message = trim($matches[2]); } elseif (isset($annotations['expectedExceptionMessage'])) { $message = $this->parseAnnotationContent($annotations['expectedExceptionMessage'][0]); } @@ -279,10 +321,10 @@ public function expectedException() $code = $this->parseAnnotationContent($annotations['expectedExceptionCode'][0]); } - if (\is_numeric($code)) { + if (is_numeric($code)) { $code = (int) $code; - } elseif (\is_string($code) && \defined($code)) { - $code = (int) \constant($code); + } elseif (is_string($code) && defined($code)) { + $code = (int) constant($code); } return [ @@ -312,11 +354,11 @@ public function getProvidedData(): ?array } foreach ($data as $key => $value) { - if (!\is_array($value)) { + if (!is_array($value)) { throw new InvalidDataSetException( - \sprintf( + sprintf( 'Data set %s is invalid.', - \is_int($key) ? '#' . $key : '"' . $key . '"' + is_int($key) ? '#' . $key : '"' . $key . '"' ) ); } @@ -330,16 +372,16 @@ public function getProvidedData(): ?array */ public function getInlineAnnotations(): array { - $code = \file($this->fileName); + $code = file($this->fileName); $lineNumber = $this->startLine; $startLine = $this->startLine - 1; $endLine = $this->endLine - 1; - $codeLines = \array_slice($code, $startLine, $endLine - $startLine + 1); + $codeLines = array_slice($code, $startLine, $endLine - $startLine + 1); $annotations = []; foreach ($codeLines as $line) { - if (\preg_match('#/\*\*?\s*@(?P[A-Za-z_-]+)(?:[ \t]+(?P.*?))?[ \t]*\r?\*/$#m', $line, $matches)) { - $annotations[\strtolower($matches['name'])] = [ + if (preg_match('#/\*\*?\s*@(?P[A-Za-z_-]+)(?:[ \t]+(?P.*?))?[ \t]*\r?\*/$#m', $line, $matches)) { + $annotations[strtolower($matches['name'])] = [ 'line' => $lineNumber, 'value' => $matches['value'], ]; @@ -358,28 +400,28 @@ public function symbolAnnotations(): array public function isHookToBeExecutedBeforeClass(): bool { - return $this->isMethod - && false !== \strpos($this->docComment, '@beforeClass'); + return $this->isMethod && + false !== strpos($this->docComment, '@beforeClass'); } public function isHookToBeExecutedAfterClass(): bool { - return $this->isMethod - && false !== \strpos($this->docComment, '@afterClass'); + return $this->isMethod && + false !== strpos($this->docComment, '@afterClass'); } public function isToBeExecutedBeforeTest(): bool { - return 1 === \preg_match('/@before\b/', $this->docComment); + return 1 === preg_match('/@before\b/', $this->docComment); } public function isToBeExecutedAfterTest(): bool { - return 1 === \preg_match('/@after\b/', $this->docComment); + return 1 === preg_match('/@after\b/', $this->docComment); } /** - * Parse annotation content to use constant/class constant values + * Parse annotation content to use constant/class constant values. * * Constants are specified using a starting '@'. For example: @ClassName::CONST_NAME * @@ -387,9 +429,9 @@ public function isToBeExecutedAfterTest(): bool */ private function parseAnnotationContent(string $message): string { - if (\defined($message) && - (\strpos($message, '::') !== false && \substr_count($message, '::') + 1 === 2)) { - return \constant($message); + if (defined($message) && + (strpos($message, '::') !== false && substr_count($message, '::') + 1 === 2)) { + return constant($message); } return $message; @@ -404,38 +446,38 @@ private function getDataFromDataProviderAnnotation(string $docComment): ?array $methodName = $this->name; } - if (!\preg_match_all(self::REGEX_DATA_PROVIDER, $docComment, $matches)) { + if (!preg_match_all(self::REGEX_DATA_PROVIDER, $docComment, $matches)) { return null; } $result = []; foreach ($matches[1] as $match) { - $dataProviderMethodNameNamespace = \explode('\\', $match); - $leaf = \explode('::', \array_pop($dataProviderMethodNameNamespace)); - $dataProviderMethodName = \array_pop($leaf); + $dataProviderMethodNameNamespace = explode('\\', $match); + $leaf = explode('::', array_pop($dataProviderMethodNameNamespace)); + $dataProviderMethodName = array_pop($leaf); if (empty($dataProviderMethodNameNamespace)) { $dataProviderMethodNameNamespace = ''; } else { - $dataProviderMethodNameNamespace = \implode('\\', $dataProviderMethodNameNamespace) . '\\'; + $dataProviderMethodNameNamespace = implode('\\', $dataProviderMethodNameNamespace) . '\\'; } if (empty($leaf)) { $dataProviderClassName = $className; } else { /** @psalm-var class-string $dataProviderClassName */ - $dataProviderClassName = $dataProviderMethodNameNamespace . \array_pop($leaf); + $dataProviderClassName = $dataProviderMethodNameNamespace . array_pop($leaf); } try { - $dataProviderClass = new \ReflectionClass($dataProviderClassName); + $dataProviderClass = new ReflectionClass($dataProviderClassName); $dataProviderMethod = $dataProviderClass->getMethod( $dataProviderMethodName ); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -456,16 +498,16 @@ private function getDataFromDataProviderAnnotation(string $docComment): ?array $data = $dataProviderMethod->invoke($object, $methodName); } - if ($data instanceof \Traversable) { + if ($data instanceof Traversable) { $origData = $data; $data = []; foreach ($origData as $key => $value) { - if (\is_int($key)) { + if (is_int($key)) { $data[] = $value; - } elseif (\array_key_exists($key, $data)) { + } elseif (array_key_exists($key, $data)) { throw new InvalidDataProviderException( - \sprintf( + sprintf( 'The key "%s" has already been defined in the data provider "%s".', $key, $match @@ -477,8 +519,8 @@ private function getDataFromDataProviderAnnotation(string $docComment): ?array } } - if (\is_array($data)) { - $result = \array_merge($result, $data); + if (is_array($data)) { + $result = array_merge($result, $data); } } @@ -492,26 +534,26 @@ private function getDataFromTestWithAnnotation(string $docComment): ?array { $docComment = $this->cleanUpMultiLineAnnotation($docComment); - if (!\preg_match(self::REGEX_TEST_WITH, $docComment, $matches, \PREG_OFFSET_CAPTURE)) { + if (!preg_match(self::REGEX_TEST_WITH, $docComment, $matches, PREG_OFFSET_CAPTURE)) { return null; } - $offset = \strlen($matches[0][0]) + $matches[0][1]; - $annotationContent = \substr($docComment, $offset); + $offset = strlen($matches[0][0]) + $matches[0][1]; + $annotationContent = substr($docComment, $offset); $data = []; - foreach (\explode("\n", $annotationContent) as $candidateRow) { - $candidateRow = \trim($candidateRow); + foreach (explode("\n", $annotationContent) as $candidateRow) { + $candidateRow = trim($candidateRow); if ($candidateRow[0] !== '[') { break; } - $dataSet = \json_decode($candidateRow, true); + $dataSet = json_decode($candidateRow, true); - if (\json_last_error() !== \JSON_ERROR_NONE) { + if (json_last_error() !== JSON_ERROR_NONE) { throw new Exception( - 'The data set for the @testWith annotation cannot be parsed: ' . \json_last_error_msg() + 'The data set for the @testWith annotation cannot be parsed: ' . json_last_error_msg() ); } @@ -528,22 +570,22 @@ private function getDataFromTestWithAnnotation(string $docComment): ?array private function cleanUpMultiLineAnnotation(string $docComment): string { //removing initial ' * ' for docComment - $docComment = \str_replace("\r\n", "\n", $docComment); - $docComment = \preg_replace('/' . '\n' . '\s*' . '\*' . '\s?' . '/', "\n", $docComment); - $docComment = (string) \substr($docComment, 0, -1); + $docComment = str_replace("\r\n", "\n", $docComment); + $docComment = preg_replace('/' . '\n' . '\s*' . '\*' . '\s?' . '/', "\n", $docComment); + $docComment = (string) substr($docComment, 0, -1); - return \rtrim($docComment, "\n"); + return rtrim($docComment, "\n"); } /** @return array> */ private static function parseDocBlock(string $docBlock): array { // Strip away the docblock header and footer to ease parsing of one line annotations - $docBlock = (string) \substr($docBlock, 3, -2); + $docBlock = (string) substr($docBlock, 3, -2); $annotations = []; - if (\preg_match_all('/@(?P[A-Za-z_-]+)(?:[ \t]+(?P.*?))?[ \t]*\r?$/m', $docBlock, $matches)) { - $numMatches = \count($matches[0]); + if (preg_match_all('/@(?P[A-Za-z_-]+)(?:[ \t]+(?P.*?))?[ \t]*\r?$/m', $docBlock, $matches)) { + $numMatches = count($matches[0]); for ($i = 0; $i < $numMatches; $i++) { $annotations[$matches['name'][$i]][] = (string) $matches['value'][$i]; @@ -553,24 +595,24 @@ private static function parseDocBlock(string $docBlock): array return $annotations; } - /** @param \ReflectionClass|\ReflectionFunctionAbstract $reflector */ - private static function extractAnnotationsFromReflector(\Reflector $reflector): array + /** @param ReflectionClass|ReflectionFunctionAbstract $reflector */ + private static function extractAnnotationsFromReflector(Reflector $reflector): array { $annotations = []; - if ($reflector instanceof \ReflectionClass) { - $annotations = \array_merge( + if ($reflector instanceof ReflectionClass) { + $annotations = array_merge( $annotations, - ...\array_map( - function (\ReflectionClass $trait): array { + ...array_map( + static function (ReflectionClass $trait): array { return self::parseDocBlock((string) $trait->getDocComment()); }, - \array_values($reflector->getTraits()) + array_values($reflector->getTraits()) ) ); } - return \array_merge( + return array_merge( $annotations, self::parseDocBlock((string) $reflector->getDocComment()) ); diff --git a/src/Util/Annotation/Registry.php b/src/Util/Annotation/Registry.php index 0706ba3237f..8df14cfc0ce 100644 --- a/src/Util/Annotation/Registry.php +++ b/src/Util/Annotation/Registry.php @@ -9,7 +9,11 @@ */ namespace PHPUnit\Util\Annotation; +use function array_key_exists; use PHPUnit\Util\Exception; +use ReflectionClass; +use ReflectionException; +use ReflectionMethod; /** * Reflection information, and therefore DocBlock information, is static within @@ -43,14 +47,14 @@ private function __construct() */ public function forClassName(string $class): DocBlock { - if (\array_key_exists($class, $this->classDocBlocks)) { + if (array_key_exists($class, $this->classDocBlocks)) { return $this->classDocBlocks[$class]; } try { - $reflection = new \ReflectionClass($class); + $reflection = new ReflectionClass($class); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -73,9 +77,9 @@ public function forMethod(string $classInHierarchy, string $method): DocBlock } try { - $reflection = new \ReflectionMethod($classInHierarchy, $method); + $reflection = new ReflectionMethod($classInHierarchy, $method); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), diff --git a/src/Util/Blacklist.php b/src/Util/Blacklist.php index 3915cd6b8bd..dd89dcd552d 100644 --- a/src/Util/Blacklist.php +++ b/src/Util/Blacklist.php @@ -9,6 +9,12 @@ */ namespace PHPUnit\Util; +use const DIRECTORY_SEPARATOR; +use function class_exists; +use function defined; +use function dirname; +use function strpos; +use function sys_get_temp_dir; use Composer\Autoload\ClassLoader; use DeepCopy\DeepCopy; use Doctrine\Instantiator\Instantiator; @@ -20,6 +26,8 @@ use phpDocumentor\Reflection\Type; use PHPUnit\Framework\TestCase; use Prophecy\Prophet; +use ReflectionClass; +use ReflectionException; use SebastianBergmann\CodeCoverage\CodeCoverage; use SebastianBergmann\CodeUnitReverseLookup\Wizard; use SebastianBergmann\Comparator\Comparator; @@ -158,14 +166,14 @@ public function getBlacklistedDirectories(): array */ public function isBlacklisted(string $file): bool { - if (\defined('PHPUNIT_TESTSUITE')) { + if (defined('PHPUNIT_TESTSUITE')) { return false; } $this->initialize(); foreach (self::$directories as $directory) { - if (\strpos($file, $directory) === 0) { + if (strpos($file, $directory) === 0) { return true; } } @@ -182,14 +190,14 @@ private function initialize(): void self::$directories = []; foreach (self::$blacklistedClassNames as $className => $parent) { - if (!\class_exists($className)) { + if (!class_exists($className)) { continue; } try { - $directory = (new \ReflectionClass($className))->getFileName(); + $directory = (new ReflectionClass($className))->getFileName(); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -199,17 +207,17 @@ private function initialize(): void // @codeCoverageIgnoreEnd for ($i = 0; $i < $parent; $i++) { - $directory = \dirname($directory); + $directory = dirname($directory); } self::$directories[] = $directory; } // Hide process isolation workaround on Windows. - if (\DIRECTORY_SEPARATOR === '\\') { + if (DIRECTORY_SEPARATOR === '\\') { // tempnam() prefix is limited to first 3 chars. // @see https://php.net/manual/en/function.tempnam.php - self::$directories[] = \sys_get_temp_dir() . '\\PHP'; + self::$directories[] = sys_get_temp_dir() . '\\PHP'; } } } diff --git a/src/Util/Color.php b/src/Util/Color.php index dab4e318bba..a756953b66e 100644 --- a/src/Util/Color.php +++ b/src/Util/Color.php @@ -9,6 +9,20 @@ */ namespace PHPUnit\Util; +use const DIRECTORY_SEPARATOR; +use function array_keys; +use function array_map; +use function array_values; +use function count; +use function explode; +use function implode; +use function min; +use function preg_replace; +use function preg_replace_callback; +use function sprintf; +use function strtr; +use function trim; + /** * @internal This class is not covered by the backward compatibility promise for PHPUnit */ @@ -63,11 +77,11 @@ final class Color public static function colorize(string $color, string $buffer): string { - if (\trim($buffer) === '') { + if (trim($buffer) === '') { return $buffer; } - $codes = \array_map('\trim', \explode(',', $color)); + $codes = array_map('\trim', explode(',', $color)); $styles = []; foreach ($codes as $code) { @@ -80,7 +94,7 @@ public static function colorize(string $color, string $buffer): string return $buffer; } - return self::optimizeColor(\sprintf("\x1b[%sm", \implode(';', $styles)) . $buffer . "\x1b[0m"); + return self::optimizeColor(sprintf("\x1b[%sm", implode(';', $styles)) . $buffer . "\x1b[0m"); } public static function colorizePath(string $path, ?string $prevPath = null, bool $colorizeFilename = false): string @@ -89,18 +103,18 @@ public static function colorizePath(string $path, ?string $prevPath = null, bool $prevPath = ''; } - $path = \explode(\DIRECTORY_SEPARATOR, $path); - $prevPath = \explode(\DIRECTORY_SEPARATOR, $prevPath); + $path = explode(DIRECTORY_SEPARATOR, $path); + $prevPath = explode(DIRECTORY_SEPARATOR, $prevPath); - for ($i = 0; $i < \min(\count($path), \count($prevPath)); $i++) { + for ($i = 0; $i < min(count($path), count($prevPath)); $i++) { if ($path[$i] == $prevPath[$i]) { $path[$i] = self::dim($path[$i]); } } if ($colorizeFilename) { - $last = \count($path) - 1; - $path[$last] = \preg_replace_callback( + $last = count($path) - 1; + $path[$last] = preg_replace_callback( '/([\-_\.]+|phpt$)/', static function ($matches) { return self::dim($matches[0]); @@ -109,12 +123,12 @@ static function ($matches) { ); } - return self::optimizeColor(\implode(self::dim(\DIRECTORY_SEPARATOR), $path)); + return self::optimizeColor(implode(self::dim(DIRECTORY_SEPARATOR), $path)); } public static function dim(string $buffer): string { - if (\trim($buffer) === '') { + if (trim($buffer) === '') { return $buffer; } @@ -125,8 +139,8 @@ public static function visualizeWhitespace(string $buffer, bool $visualizeEOL = { $replaceMap = $visualizeEOL ? self::WHITESPACE_EOL_MAP : self::WHITESPACE_MAP; - return \preg_replace_callback('/\s+/', static function ($matches) use ($replaceMap) { - return self::dim(\strtr($matches[0], $replaceMap)); + return preg_replace_callback('/\s+/', static function ($matches) use ($replaceMap) { + return self::dim(strtr($matches[0], $replaceMap)); }, $buffer); } @@ -138,6 +152,6 @@ private static function optimizeColor(string $buffer): string "/(\e\\[[^m]*m)+(\e\\[0m)/" => '$2', ]; - return \preg_replace(\array_keys($patterns), \array_values($patterns), $buffer); + return preg_replace(array_keys($patterns), array_values($patterns), $buffer); } } diff --git a/src/Util/Configuration.php b/src/Util/Configuration.php index 10ad144b7b3..dfc4e241fe2 100644 --- a/src/Util/Configuration.php +++ b/src/Util/Configuration.php @@ -9,8 +9,44 @@ */ namespace PHPUnit\Util; +use const DIRECTORY_SEPARATOR; +use const PATH_SEPARATOR; +use const PHP_VERSION; +use function assert; +use function constant; +use function count; +use function define; +use function defined; +use function dirname; +use function explode; +use function file_exists; +use function file_get_contents; +use function getenv; +use function implode; +use function in_array; +use function ini_get; +use function ini_set; +use function is_numeric; +use function libxml_clear_errors; +use function libxml_get_errors; +use function libxml_use_internal_errors; +use function preg_match; +use function putenv; +use function realpath; +use function sprintf; +use function stream_resolve_include_path; +use function strlen; +use function strpos; +use function strtolower; +use function strtoupper; +use function substr; +use function trim; +use function version_compare; +use DOMDocument; use DOMElement; +use DOMNodeList; use DOMXPath; +use LibXMLError; use PHPUnit\Framework\Exception; use PHPUnit\Framework\TestSuite; use PHPUnit\Runner\TestSuiteSorter; @@ -29,7 +65,7 @@ final class Configuration private static $instances = []; /** - * @var \DOMDocument + * @var DOMDocument */ private $document; @@ -44,7 +80,7 @@ final class Configuration private $filename; /** - * @var \LibXMLError[] + * @var LibXMLError[] */ private $errors = []; @@ -55,11 +91,11 @@ final class Configuration */ public static function getInstance(string $filename): self { - $realPath = \realpath($filename); + $realPath = realpath($filename); if ($realPath === false) { throw new Exception( - \sprintf( + sprintf( 'Could not read "%s".', $filename ) @@ -96,7 +132,7 @@ private function __clone() public function hasValidationErrors(): bool { - return \count($this->errors) > 0; + return count($this->errors) > 0; } public function getValidationErrors(): array @@ -107,7 +143,7 @@ public function getValidationErrors(): array if (!isset($result[$error->line])) { $result[$error->line] = []; } - $result[$error->line][] = \trim($error->message); + $result[$error->line][] = trim($error->message); } return $result; @@ -236,7 +272,7 @@ public function getLoggingConfiguration(): array $result = []; foreach ($this->xpath->query('logging/log') as $log) { - \assert($log instanceof DOMElement); + assert($log instanceof DOMElement); $type = (string) $log->getAttribute('type'); $target = (string) $log->getAttribute('target'); @@ -318,7 +354,7 @@ public function getPHPConfiguration(): array } foreach ($this->xpath->query('php/ini') as $ini) { - \assert($ini instanceof DOMElement); + assert($ini instanceof DOMElement); $name = (string) $ini->getAttribute('name'); $value = (string) $ini->getAttribute('value'); @@ -327,7 +363,7 @@ public function getPHPConfiguration(): array } foreach ($this->xpath->query('php/const') as $const) { - \assert($const instanceof DOMElement); + assert($const instanceof DOMElement); $name = (string) $const->getAttribute('name'); $value = (string) $const->getAttribute('value'); @@ -337,7 +373,7 @@ public function getPHPConfiguration(): array foreach (['var', 'env', 'post', 'get', 'cookie', 'server', 'files', 'request'] as $array) { foreach ($this->xpath->query('php/' . $array) as $var) { - \assert($var instanceof DOMElement); + assert($var instanceof DOMElement); $name = (string) $var->getAttribute('name'); $value = (string) $var->getAttribute('value'); @@ -372,52 +408,42 @@ public function handlePHPConfiguration(): void $configuration = $this->getPHPConfiguration(); if (!empty($configuration['include_path'])) { - \ini_set( + ini_set( 'include_path', - \implode(\PATH_SEPARATOR, $configuration['include_path']) . - \PATH_SEPARATOR . - \ini_get('include_path') + implode(PATH_SEPARATOR, $configuration['include_path']) . + PATH_SEPARATOR . + ini_get('include_path') ); } foreach ($configuration['ini'] as $name => $data) { $value = $data['value']; - if (\defined($value)) { - $value = (string) \constant($value); + if (defined($value)) { + $value = (string) constant($value); } - \ini_set($name, $value); + ini_set($name, $value); } foreach ($configuration['const'] as $name => $data) { $value = $data['value']; - if (!\defined($name)) { - \define($name, $value); + if (!defined($name)) { + define($name, $value); } } - foreach (['var', 'post', 'get', 'cookie', 'server', 'files', 'request'] as $array) { - /* - * @see https://github.com/sebastianbergmann/phpunit/issues/277 - */ - switch ($array) { - case 'var': - $target = &$GLOBALS; - - break; - - case 'server': - $target = &$_SERVER; - - break; + foreach ($configuration['var'] as $name => $data) { + $GLOBALS[$name] = $data['value']; + } - default: - $target = &$GLOBALS['_' . \strtoupper($array)]; + foreach ($configuration['server'] as $name => $data) { + $_SERVER[$name] = $data['value']; + } - break; - } + foreach (['post', 'get', 'cookie', 'files', 'request'] as $array) { + $target = &$GLOBALS['_' . strtoupper($array)]; foreach ($configuration[$array] as $name => $data) { $target[$name] = $data['value']; @@ -428,11 +454,11 @@ public function handlePHPConfiguration(): void $value = $data['value']; $force = $data['force'] ?? false; - if ($force || \getenv($name) === false) { - \putenv("{$name}={$value}"); + if ($force || getenv($name) === false) { + putenv("{$name}={$value}"); } - $value = \getenv($name); + $value = getenv($name); if (!isset($_ENV[$name])) { $_ENV[$name] = $value; @@ -793,7 +819,7 @@ public function getPHPUnitConfiguration(): array } if ($root->hasAttribute('executionOrder')) { - foreach (\explode(',', $root->getAttribute('executionOrder')) as $order) { + foreach (explode(',', $root->getAttribute('executionOrder')) as $order) { switch ($order) { case 'default': $result['executionOrder'] = TestSuiteSorter::ORDER_DEFAULT; @@ -902,24 +928,24 @@ public function getTestSuiteNames(): array private function validateConfigurationAgainstSchema(): void { - $original = \libxml_use_internal_errors(true); + $original = libxml_use_internal_errors(true); $xsdFilename = __DIR__ . '/../../phpunit.xsd'; - if (\defined('__PHPUNIT_PHAR_ROOT__')) { + if (defined('__PHPUNIT_PHAR_ROOT__')) { $xsdFilename = __PHPUNIT_PHAR_ROOT__ . '/phpunit.xsd'; } - $this->document->schemaValidate($xsdFilename); - $this->errors = \libxml_get_errors(); - \libxml_clear_errors(); - \libxml_use_internal_errors($original); + $this->document->schemaValidateSource(file_get_contents($xsdFilename)); + $this->errors = libxml_get_errors(); + libxml_clear_errors(); + libxml_use_internal_errors($original); } /** * Collects and returns the configuration arguments from the PHPUnit - * XML configuration + * XML configuration. */ - private function getConfigurationArguments(\DOMNodeList $nodes): array + private function getConfigurationArguments(DOMNodeList $nodes): array { $arguments = []; @@ -976,12 +1002,12 @@ private function getTestSuite(DOMElement $testSuiteNode, string $testSuiteFilter } $fileIteratorFacade = new FileIteratorFacade; - $testSuiteFilter = $testSuiteFilter ? \explode(',', $testSuiteFilter) : []; + $testSuiteFilter = $testSuiteFilter ? explode(',', $testSuiteFilter) : []; foreach ($testSuiteNode->getElementsByTagName('directory') as $directoryNode) { - \assert($directoryNode instanceof DOMElement); + assert($directoryNode instanceof DOMElement); - if (!empty($testSuiteFilter) && !\in_array($directoryNode->parentNode->getAttribute('name'), $testSuiteFilter, true)) { + if (!empty($testSuiteFilter) && !in_array($directoryNode->parentNode->getAttribute('name'), $testSuiteFilter, true)) { continue; } @@ -1006,9 +1032,9 @@ private function getTestSuite(DOMElement $testSuiteNode, string $testSuiteFilter } foreach ($testSuiteNode->getElementsByTagName('file') as $fileNode) { - \assert($fileNode instanceof DOMElement); + assert($fileNode instanceof DOMElement); - if (!empty($testSuiteFilter) && !\in_array($fileNode->parentNode->getAttribute('name'), $testSuiteFilter, true)) { + if (!empty($testSuiteFilter) && !in_array($fileNode->parentNode->getAttribute('name'), $testSuiteFilter, true)) { continue; } @@ -1040,7 +1066,7 @@ private function getTestSuite(DOMElement $testSuiteNode, string $testSuiteFilter private function satisfiesPhpVersion(DOMElement $node): bool { - $phpVersion = \PHP_VERSION; + $phpVersion = PHP_VERSION; $phpVersionOperator = '>='; if ($node->hasAttribute('phpVersion')) { @@ -1051,13 +1077,13 @@ private function satisfiesPhpVersion(DOMElement $node): bool $phpVersionOperator = (string) $node->getAttribute('phpVersionOperator'); } - return \version_compare(\PHP_VERSION, $phpVersion, (new VersionComparisonOperator($phpVersionOperator))->asString()); + return version_compare(PHP_VERSION, $phpVersion, (new VersionComparisonOperator($phpVersionOperator))->asString()); } /** * if $value is 'false' or 'true', this returns the value that $value represents. * Otherwise, returns $default, which may be a string in rare cases. - * See PHPUnit\Util\ConfigurationTest::testPHPConfigurationIsReadCorrectly + * See PHPUnit\Util\ConfigurationTest::testPHPConfigurationIsReadCorrectly. * * @param bool|string $default * @@ -1065,11 +1091,11 @@ private function satisfiesPhpVersion(DOMElement $node): bool */ private function getBoolean(string $value, $default) { - if (\strtolower($value) === 'false') { + if (strtolower($value) === 'false') { return false; } - if (\strtolower($value) === 'true') { + if (strtolower($value) === 'true') { return true; } @@ -1078,7 +1104,7 @@ private function getBoolean(string $value, $default) private function getInteger(string $value, int $default): int { - if (\is_numeric($value)) { + if (is_numeric($value)) { return (int) $value; } @@ -1090,7 +1116,7 @@ private function readFilterDirectories(string $query): array $directories = []; foreach ($this->xpath->query($query) as $directoryNode) { - \assert($directoryNode instanceof DOMElement); + assert($directoryNode instanceof DOMElement); $directoryPath = (string) $directoryNode->textContent; @@ -1129,9 +1155,9 @@ private function readFilterFiles(string $query): array private function toAbsolutePath(string $path, bool $useIncludePath = false): string { - $path = \trim($path); + $path = trim($path); - if (\strpos($path, '/') === 0) { + if (strpos($path, '/') === 0) { return $path; } @@ -1143,19 +1169,19 @@ private function toAbsolutePath(string $path, bool $useIncludePath = false): str // - C:\windows // - C:/windows // - c:/windows - if (\defined('PHP_WINDOWS_VERSION_BUILD') && - ($path[0] === '\\' || (\strlen($path) >= 3 && \preg_match('#^[A-Z]\:[/\\\]#i', \substr($path, 0, 3))))) { + if (defined('PHP_WINDOWS_VERSION_BUILD') && + ($path[0] === '\\' || (strlen($path) >= 3 && preg_match('#^[A-Z]\:[/\\\]#i', substr($path, 0, 3))))) { return $path; } - if (\strpos($path, '://') !== false) { + if (strpos($path, '://') !== false) { return $path; } - $file = \dirname($this->filename) . \DIRECTORY_SEPARATOR . $path; + $file = dirname($this->filename) . DIRECTORY_SEPARATOR . $path; - if ($useIncludePath && !\file_exists($file)) { - $includePathFile = \stream_resolve_include_path($path); + if ($useIncludePath && !file_exists($file)) { + $includePathFile = stream_resolve_include_path($path); if ($includePathFile) { $file = $includePathFile; diff --git a/src/Util/ConfigurationGenerator.php b/src/Util/ConfigurationGenerator.php index 5367df92d19..f312922487e 100644 --- a/src/Util/ConfigurationGenerator.php +++ b/src/Util/ConfigurationGenerator.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Util; +use function str_replace; + /** * @internal This class is not covered by the backward compatibility promise for PHPUnit */ @@ -30,7 +32,7 @@ final class ConfigurationGenerator verbose="true"> - {tests_directory} + {tests_directory} @@ -45,7 +47,7 @@ final class ConfigurationGenerator public function generateDefaultConfiguration(string $phpunitVersion, string $bootstrapScript, string $testsDirectory, string $srcDirectory): string { - return \str_replace( + return str_replace( [ '{phpunit_version}', '{bootstrap_script}', diff --git a/src/Util/ErrorHandler.php b/src/Util/ErrorHandler.php index 99e3ae2a6db..61dbbbc1377 100644 --- a/src/Util/ErrorHandler.php +++ b/src/Util/ErrorHandler.php @@ -9,6 +9,16 @@ */ namespace PHPUnit\Util; +use const E_DEPRECATED; +use const E_NOTICE; +use const E_STRICT; +use const E_USER_DEPRECATED; +use const E_USER_NOTICE; +use const E_USER_WARNING; +use const E_WARNING; +use function error_reporting; +use function restore_error_handler; +use function set_error_handler; use PHPUnit\Framework\Error\Deprecated; use PHPUnit\Framework\Error\Error; use PHPUnit\Framework\Error\Notice; @@ -46,9 +56,9 @@ final class ErrorHandler public static function invokeIgnoringWarnings(callable $callable) { - \set_error_handler( + set_error_handler( static function ($errorNumber, $errorString) { - if ($errorNumber === \E_WARNING) { + if ($errorNumber === E_WARNING) { return; } @@ -58,7 +68,7 @@ static function ($errorNumber, $errorString) { $result = $callable(); - \restore_error_handler(); + restore_error_handler(); return $result; } @@ -78,30 +88,30 @@ public function __invoke(int $errorNumber, string $errorString, string $errorFil * * @see https://github.com/sebastianbergmann/phpunit/issues/3739 */ - if (!($errorNumber & \error_reporting())) { + if (!($errorNumber & error_reporting())) { return false; } switch ($errorNumber) { - case \E_NOTICE: - case \E_USER_NOTICE: - case \E_STRICT: + case E_NOTICE: + case E_USER_NOTICE: + case E_STRICT: if (!$this->convertNoticesToExceptions) { return false; } throw new Notice($errorString, $errorNumber, $errorFile, $errorLine); - case \E_WARNING: - case \E_USER_WARNING: + case E_WARNING: + case E_USER_WARNING: if (!$this->convertWarningsToExceptions) { return false; } throw new Warning($errorString, $errorNumber, $errorFile, $errorLine); - case \E_DEPRECATED: - case \E_USER_DEPRECATED: + case E_DEPRECATED: + case E_USER_DEPRECATED: if (!$this->convertDeprecationsToExceptions) { return false; } @@ -123,10 +133,10 @@ public function register(): void return; } - $oldErrorHandler = \set_error_handler($this); + $oldErrorHandler = set_error_handler($this); if ($oldErrorHandler !== null) { - \restore_error_handler(); + restore_error_handler(); return; } @@ -140,6 +150,6 @@ public function unregister(): void return; } - \restore_error_handler(); + restore_error_handler(); } } diff --git a/src/Util/Exception.php b/src/Util/Exception.php index da452f4e557..6bcb3d140a8 100644 --- a/src/Util/Exception.php +++ b/src/Util/Exception.php @@ -9,9 +9,11 @@ */ namespace PHPUnit\Util; +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 { } diff --git a/src/Util/FileLoader.php b/src/Util/FileLoader.php index e600cf5479c..1390d8cf437 100644 --- a/src/Util/FileLoader.php +++ b/src/Util/FileLoader.php @@ -9,6 +9,13 @@ */ namespace PHPUnit\Util; +use const DIRECTORY_SEPARATOR; +use function array_diff; +use function array_keys; +use function fopen; +use function get_defined_vars; +use function sprintf; +use function stream_resolve_include_path; use PHPUnit\Framework\Exception; /** @@ -28,19 +35,19 @@ final class FileLoader */ public static function checkAndLoad(string $filename): string { - $includePathFilename = \stream_resolve_include_path($filename); + $includePathFilename = stream_resolve_include_path($filename); if (!$includePathFilename) { throw new Exception( - \sprintf('Cannot open file "%s".' . "\n", $filename) + sprintf('Cannot open file "%s".' . "\n", $filename) ); } - $localFile = __DIR__ . \DIRECTORY_SEPARATOR . $filename; + $localFile = __DIR__ . DIRECTORY_SEPARATOR . $filename; if ($includePathFilename === $localFile || !self::isReadable($includePathFilename)) { throw new Exception( - \sprintf('Cannot open file "%s".' . "\n", $filename) + sprintf('Cannot open file "%s".' . "\n", $filename) ); } @@ -54,13 +61,13 @@ public static function checkAndLoad(string $filename): string */ public static function load(string $filename): void { - $oldVariableNames = \array_keys(\get_defined_vars()); + $oldVariableNames = array_keys(get_defined_vars()); include_once $filename; - $newVariables = \get_defined_vars(); + $newVariables = get_defined_vars(); - foreach (\array_diff(\array_keys($newVariables), $oldVariableNames) as $variableName) { + foreach (array_diff(array_keys($newVariables), $oldVariableNames) as $variableName) { if ($variableName !== 'oldVariableNames') { $GLOBALS[$variableName] = $newVariables[$variableName]; } @@ -72,6 +79,6 @@ public static function load(string $filename): void */ private static function isReadable(string $filename): bool { - return @\fopen($filename, 'r') !== false; + return @fopen($filename, 'r') !== false; } } diff --git a/src/Util/Filesystem.php b/src/Util/Filesystem.php index 8207a4fffc4..cd0c125f723 100644 --- a/src/Util/Filesystem.php +++ b/src/Util/Filesystem.php @@ -9,6 +9,11 @@ */ namespace PHPUnit\Util; +use const DIRECTORY_SEPARATOR; +use function is_dir; +use function mkdir; +use function str_replace; + /** * @internal This class is not covered by the backward compatibility promise for PHPUnit */ @@ -17,19 +22,19 @@ final class Filesystem /** * Maps class names to source file names: * - PEAR CS: Foo_Bar_Baz -> Foo/Bar/Baz.php - * - Namespace: Foo\Bar\Baz -> Foo/Bar/Baz.php + * - Namespace: Foo\Bar\Baz -> Foo/Bar/Baz.php. */ public static function classNameToFilename(string $className): string { - return \str_replace( + return str_replace( ['_', '\\'], - \DIRECTORY_SEPARATOR, + DIRECTORY_SEPARATOR, $className ) . '.php'; } public static function createDirectory(string $directory): bool { - return !(!\is_dir($directory) && !@\mkdir($directory, 0777, true) && !\is_dir($directory)); + return !(!is_dir($directory) && !@mkdir($directory, 0777, true) && !is_dir($directory)); } } diff --git a/src/Util/Filter.php b/src/Util/Filter.php index d1a8ec64fd8..06f58d55d0e 100644 --- a/src/Util/Filter.php +++ b/src/Util/Filter.php @@ -9,8 +9,16 @@ */ namespace PHPUnit\Util; +use function array_unshift; +use function defined; +use function in_array; +use function is_file; +use function realpath; +use function sprintf; +use function strpos; use PHPUnit\Framework\Exception; use PHPUnit\Framework\SyntheticError; +use Throwable; /** * @internal This class is not covered by the backward compatibility promise for PHPUnit @@ -20,7 +28,7 @@ final class Filter /** * @throws Exception */ - public static function getFilteredStacktrace(\Throwable $t): string + public static function getFilteredStacktrace(Throwable $t): string { $filteredStacktrace = ''; @@ -43,18 +51,18 @@ public static function getFilteredStacktrace(\Throwable $t): string } if (!self::frameExists($eTrace, $eFile, $eLine)) { - \array_unshift( + array_unshift( $eTrace, ['file' => $eFile, 'line' => $eLine] ); } - $prefix = \defined('__PHPUNIT_PHAR_ROOT__') ? __PHPUNIT_PHAR_ROOT__ : false; + $prefix = defined('__PHPUNIT_PHAR_ROOT__') ? __PHPUNIT_PHAR_ROOT__ : false; $blacklist = new Blacklist; foreach ($eTrace as $frame) { if (self::shouldPrintFrame($frame, $prefix, $blacklist)) { - $filteredStacktrace .= \sprintf( + $filteredStacktrace .= sprintf( "%s:%s\n", $frame['file'], $frame['line'] ?? '?' @@ -72,16 +80,16 @@ private static function shouldPrintFrame($frame, $prefix, Blacklist $blacklist): } $file = $frame['file']; - $fileIsNotPrefixed = $prefix === false || \strpos($file, $prefix) !== 0; + $fileIsNotPrefixed = $prefix === false || strpos($file, $prefix) !== 0; // @see https://github.com/sebastianbergmann/phpunit/issues/4033 if (isset($GLOBALS['_SERVER']['SCRIPT_NAME'])) { - $script = \realpath($GLOBALS['_SERVER']['SCRIPT_NAME']); + $script = realpath($GLOBALS['_SERVER']['SCRIPT_NAME']); } else { $script = ''; } - return \is_file($file) && + return is_file($file) && self::fileIsBlacklisted($file, $blacklist) && $fileIsNotPrefixed && $file !== $script; @@ -90,7 +98,7 @@ private static function shouldPrintFrame($frame, $prefix, Blacklist $blacklist): private static function fileIsBlacklisted($file, Blacklist $blacklist): bool { return (empty($GLOBALS['__PHPUNIT_ISOLATION_BLACKLIST']) || - !\in_array($file, $GLOBALS['__PHPUNIT_ISOLATION_BLACKLIST'], true)) && + !in_array($file, $GLOBALS['__PHPUNIT_ISOLATION_BLACKLIST'], true)) && !$blacklist->isBlacklisted($file); } diff --git a/src/Util/Getopt.php b/src/Util/Getopt.php index c8f7daac640..878e2a43fe0 100644 --- a/src/Util/Getopt.php +++ b/src/Util/Getopt.php @@ -9,6 +9,22 @@ */ namespace PHPUnit\Util; +use function array_map; +use function array_merge; +use function array_shift; +use function array_slice; +use function count; +use function current; +use function explode; +use function key; +use function next; +use function preg_replace; +use function reset; +use function sort; +use function strlen; +use function strpos; +use function strstr; +use function substr; use PHPUnit\Framework\Exception; /** @@ -29,48 +45,48 @@ public static function parse(array $args, string $short_options, array $long_opt $non_opts = []; if ($long_options) { - \sort($long_options); + sort($long_options); } if (isset($args[0][0]) && $args[0][0] !== '-') { - \array_shift($args); + array_shift($args); } - \reset($args); + reset($args); - $args = \array_map('trim', $args); + $args = array_map('trim', $args); /* @noinspection ComparisonOperandsOrderInspection */ - while (false !== $arg = \current($args)) { - $i = \key($args); - \next($args); + while (false !== $arg = current($args)) { + $i = key($args); + next($args); if ($arg === '') { continue; } if ($arg === '--') { - $non_opts = \array_merge($non_opts, \array_slice($args, $i + 1)); + $non_opts = array_merge($non_opts, array_slice($args, $i + 1)); break; } - if ($arg[0] !== '-' || (\strlen($arg) > 1 && $arg[1] === '-' && !$long_options)) { + if ($arg[0] !== '-' || (strlen($arg) > 1 && $arg[1] === '-' && !$long_options)) { $non_opts[] = $args[$i]; continue; } - if (\strlen($arg) > 1 && $arg[1] === '-') { + if (strlen($arg) > 1 && $arg[1] === '-') { self::parseLongOption( - \substr($arg, 2), + substr($arg, 2), $long_options, $opts, $args ); } else { self::parseShortOption( - \substr($arg, 1), + substr($arg, 1), $short_options, $opts, $args @@ -86,34 +102,34 @@ public static function parse(array $args, string $short_options, array $long_opt */ private static function parseShortOption(string $arg, string $short_options, array &$opts, array &$args): void { - $argLen = \strlen($arg); + $argLen = strlen($arg); for ($i = 0; $i < $argLen; $i++) { $opt = $arg[$i]; $opt_arg = null; - if ($arg[$i] === ':' || ($spec = \strstr($short_options, $opt)) === false) { + if ($arg[$i] === ':' || ($spec = strstr($short_options, $opt)) === false) { throw new Exception( "unrecognized option -- {$opt}" ); } - if (\strlen($spec) > 1 && $spec[1] === ':') { + if (strlen($spec) > 1 && $spec[1] === ':') { if ($i + 1 < $argLen) { - $opts[] = [$opt, \substr($arg, $i + 1)]; + $opts[] = [$opt, substr($arg, $i + 1)]; break; } - if (!(\strlen($spec) > 2 && $spec[2] === ':')) { + if (!(strlen($spec) > 2 && $spec[2] === ':')) { /* @noinspection ComparisonOperandsOrderInspection */ - if (false === $opt_arg = \current($args)) { + if (false === $opt_arg = current($args)) { throw new Exception( "option requires an argument -- {$opt}" ); } - \next($args); + next($args); } } @@ -126,43 +142,43 @@ private static function parseShortOption(string $arg, string $short_options, arr */ private static function parseLongOption(string $arg, array $long_options, array &$opts, array &$args): void { - $count = \count($long_options); - $list = \explode('=', $arg); + $count = count($long_options); + $list = explode('=', $arg); $opt = $list[0]; $opt_arg = null; - if (\count($list) > 1) { + if (count($list) > 1) { $opt_arg = $list[1]; } - $opt_len = \strlen($opt); + $opt_len = strlen($opt); foreach ($long_options as $i => $long_opt) { - $opt_start = \substr($long_opt, 0, $opt_len); + $opt_start = substr($long_opt, 0, $opt_len); if ($opt_start !== $opt) { continue; } - $opt_rest = \substr($long_opt, $opt_len); + $opt_rest = substr($long_opt, $opt_len); - if ($opt_rest !== '' && $i + 1 < $count && $opt[0] !== '=' && \strpos($long_options[$i + 1], $opt) === 0) { + if ($opt_rest !== '' && $i + 1 < $count && $opt[0] !== '=' && strpos($long_options[$i + 1], $opt) === 0) { throw new Exception( "option --{$opt} is ambiguous" ); } - if (\substr($long_opt, -1) === '=') { + if (substr($long_opt, -1) === '=') { /* @noinspection StrlenInEmptyStringCheckContextInspection */ - if (\substr($long_opt, -2) !== '==' && !\strlen((string) $opt_arg)) { + if (substr($long_opt, -2) !== '==' && !strlen((string) $opt_arg)) { /* @noinspection ComparisonOperandsOrderInspection */ - if (false === $opt_arg = \current($args)) { + if (false === $opt_arg = current($args)) { throw new Exception( "option --{$opt} requires an argument" ); } - \next($args); + next($args); } } elseif ($opt_arg) { throw new Exception( @@ -170,7 +186,7 @@ private static function parseLongOption(string $arg, array $long_options, array ); } - $full_option = '--' . \preg_replace('/={1,2}$/', '', $long_opt); + $full_option = '--' . preg_replace('/={1,2}$/', '', $long_opt); $opts[] = [$full_option, $opt_arg]; return; diff --git a/src/Util/GlobalState.php b/src/Util/GlobalState.php index 7b9e0b9f8d4..0bd52de25ef 100644 --- a/src/Util/GlobalState.php +++ b/src/Util/GlobalState.php @@ -9,6 +9,21 @@ */ namespace PHPUnit\Util; +use function array_keys; +use function count; +use function defined; +use function get_defined_constants; +use function get_included_files; +use function in_array; +use function ini_get_all; +use function is_array; +use function is_file; +use function is_scalar; +use function preg_match; +use function serialize; +use function sprintf; +use function strpos; +use function var_export; use Closure; /** @@ -34,7 +49,7 @@ final class GlobalState */ public static function getIncludedFilesAsString(): string { - return self::processIncludedFilesAsString(\get_included_files()); + return self::processIncludedFilesAsString(get_included_files()); } /** @@ -48,28 +63,28 @@ public static function processIncludedFilesAsString(array $files): string $prefix = false; $result = ''; - if (\defined('__PHPUNIT_PHAR__')) { + if (defined('__PHPUNIT_PHAR__')) { $prefix = 'phar://' . __PHPUNIT_PHAR__ . '/'; } - for ($i = \count($files) - 1; $i > 0; $i--) { + for ($i = count($files) - 1; $i > 0; $i--) { $file = $files[$i]; if (!empty($GLOBALS['__PHPUNIT_ISOLATION_BLACKLIST']) && - \in_array($file, $GLOBALS['__PHPUNIT_ISOLATION_BLACKLIST'], true)) { + in_array($file, $GLOBALS['__PHPUNIT_ISOLATION_BLACKLIST'], true)) { continue; } - if ($prefix !== false && \strpos($file, $prefix) === 0) { + if ($prefix !== false && strpos($file, $prefix) === 0) { continue; } // Skip virtual file system protocols - if (\preg_match('/^(vfs|phpvfs[a-z0-9]+):/', $file)) { + if (preg_match('/^(vfs|phpvfs[a-z0-9]+):/', $file)) { continue; } - if (!$blacklist->isBlacklisted($file) && \is_file($file)) { + if (!$blacklist->isBlacklisted($file) && is_file($file)) { $result = 'require_once \'' . $file . "';\n" . $result; } } @@ -81,8 +96,8 @@ public static function getIniSettingsAsString(): string { $result = ''; - foreach (\ini_get_all(null, false) as $key => $value) { - $result .= \sprintf( + foreach (ini_get_all(null, false) as $key => $value) { + $result .= sprintf( '@ini_set(%s, %s);' . "\n", self::exportVariable($key), self::exportVariable((string) $value) @@ -94,12 +109,12 @@ public static function getIniSettingsAsString(): string public static function getConstantsAsString(): string { - $constants = \get_defined_constants(true); + $constants = get_defined_constants(true); $result = ''; if (isset($constants['user'])) { foreach ($constants['user'] as $name => $value) { - $result .= \sprintf( + $result .= sprintf( 'if (!defined(\'%s\')) define(\'%s\', %s);' . "\n", $name, $name, @@ -116,13 +131,13 @@ public static function getGlobalsAsString(): string $result = ''; foreach (self::SUPER_GLOBAL_ARRAYS as $superGlobalArray) { - if (isset($GLOBALS[$superGlobalArray]) && \is_array($GLOBALS[$superGlobalArray])) { - foreach (\array_keys($GLOBALS[$superGlobalArray]) as $key) { + if (isset($GLOBALS[$superGlobalArray]) && is_array($GLOBALS[$superGlobalArray])) { + foreach (array_keys($GLOBALS[$superGlobalArray]) as $key) { if ($GLOBALS[$superGlobalArray][$key] instanceof Closure) { continue; } - $result .= \sprintf( + $result .= sprintf( '$GLOBALS[\'%s\'][\'%s\'] = %s;' . "\n", $superGlobalArray, $key, @@ -135,9 +150,9 @@ public static function getGlobalsAsString(): string $blacklist = self::SUPER_GLOBAL_ARRAYS; $blacklist[] = 'GLOBALS'; - foreach (\array_keys($GLOBALS) as $key) { - if (!$GLOBALS[$key] instanceof Closure && !\in_array($key, $blacklist, true)) { - $result .= \sprintf( + foreach (array_keys($GLOBALS) as $key) { + if (!$GLOBALS[$key] instanceof Closure && !in_array($key, $blacklist, true)) { + $result .= sprintf( '$GLOBALS[\'%s\'] = %s;' . "\n", $key, self::exportVariable($GLOBALS[$key]) @@ -150,12 +165,12 @@ public static function getGlobalsAsString(): string private static function exportVariable($variable): string { - if (\is_scalar($variable) || $variable === null || - (\is_array($variable) && self::arrayOnlyContainsScalars($variable))) { - return \var_export($variable, true); + if (is_scalar($variable) || $variable === null || + (is_array($variable) && self::arrayOnlyContainsScalars($variable))) { + return var_export($variable, true); } - return 'unserialize(' . \var_export(\serialize($variable), true) . ')'; + return 'unserialize(' . var_export(serialize($variable), true) . ')'; } private static function arrayOnlyContainsScalars(array $array): bool @@ -163,9 +178,9 @@ private static function arrayOnlyContainsScalars(array $array): bool $result = true; foreach ($array as $element) { - if (\is_array($element)) { + if (is_array($element)) { $result = self::arrayOnlyContainsScalars($element); - } elseif (!\is_scalar($element) && $element !== null) { + } elseif (!is_scalar($element) && $element !== null) { $result = false; } diff --git a/src/Util/InvalidDataSetException.php b/src/Util/InvalidDataSetException.php index 228f066cc25..3493d113aae 100644 --- a/src/Util/InvalidDataSetException.php +++ b/src/Util/InvalidDataSetException.php @@ -9,9 +9,11 @@ */ namespace PHPUnit\Util; +use RuntimeException; + /** * @internal This class is not covered by the backward compatibility promise for PHPUnit */ -final class InvalidDataSetException extends \RuntimeException implements \PHPUnit\Exception +final class InvalidDataSetException extends RuntimeException implements \PHPUnit\Exception { } diff --git a/src/Util/Json.php b/src/Util/Json.php index 69164076726..752c1fd600b 100644 --- a/src/Util/Json.php +++ b/src/Util/Json.php @@ -9,6 +9,16 @@ */ namespace PHPUnit\Util; +use const JSON_PRETTY_PRINT; +use const JSON_UNESCAPED_SLASHES; +use const JSON_UNESCAPED_UNICODE; +use function count; +use function is_array; +use function is_object; +use function json_decode; +use function json_encode; +use function json_last_error; +use function ksort; use PHPUnit\Framework\Exception; /** @@ -17,21 +27,21 @@ final class Json { /** - * Prettify json string + * Prettify json string. * * @throws \PHPUnit\Framework\Exception */ public static function prettify(string $json): string { - $decodedJson = \json_decode($json, false); + $decodedJson = json_decode($json, false); - if (\json_last_error()) { + if (json_last_error()) { throw new Exception( 'Cannot prettify invalid json' ); } - return \json_encode($decodedJson, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE); + return json_encode($decodedJson, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); } /** @@ -44,15 +54,15 @@ public static function prettify(string $json): string */ public static function canonicalize(string $json): array { - $decodedJson = \json_decode($json); + $decodedJson = json_decode($json); - if (\json_last_error()) { + if (json_last_error()) { return [true, null]; } self::recursiveSort($decodedJson); - $reencodedJson = \json_encode($decodedJson); + $reencodedJson = json_encode($decodedJson); return [false, $reencodedJson]; } @@ -65,21 +75,21 @@ public static function canonicalize(string $json): array */ private static function recursiveSort(&$json): void { - if (!\is_array($json)) { + if (!is_array($json)) { // If the object is not empty, change it to an associative array // so we can sort the keys (and we will still re-encode it // correctly, since PHP encodes associative arrays as JSON objects.) // But EMPTY objects MUST remain empty objects. (Otherwise we will // re-encode it as a JSON array rather than a JSON object.) // See #2919. - if (\is_object($json) && \count((array) $json) > 0) { + if (is_object($json) && count((array) $json) > 0) { $json = (array) $json; } else { return; } } - \ksort($json); + ksort($json); foreach ($json as $key => &$value) { self::recursiveSort($value); diff --git a/src/Util/Log/JUnit.php b/src/Util/Log/JUnit.php index 4d152a31e5b..710e2c47da0 100644 --- a/src/Util/Log/JUnit.php +++ b/src/Util/Log/JUnit.php @@ -9,6 +9,13 @@ */ namespace PHPUnit\Util\Log; +use function class_exists; +use function get_class; +use function method_exists; +use function sprintf; +use function str_replace; +use DOMDocument; +use DOMElement; use PHPUnit\Framework\AssertionFailedError; use PHPUnit\Framework\ExceptionWrapper; use PHPUnit\Framework\SelfDescribing; @@ -21,6 +28,9 @@ use PHPUnit\Util\Filter; use PHPUnit\Util\Printer; use PHPUnit\Util\Xml; +use ReflectionClass; +use ReflectionException; +use Throwable; /** * @internal This class is not covered by the backward compatibility promise for PHPUnit @@ -28,12 +38,12 @@ final class JUnit extends Printer implements TestListener { /** - * @var \DOMDocument + * @var DOMDocument */ private $document; /** - * @var \DOMElement + * @var DOMElement */ private $root; @@ -43,7 +53,7 @@ final class JUnit extends Printer implements TestListener private $reportRiskyTests = false; /** - * @var \DOMElement[] + * @var DOMElement[] */ private $testSuites = []; @@ -88,7 +98,7 @@ final class JUnit extends Printer implements TestListener private $testSuiteLevel = 0; /** - * @var \DOMElement + * @var DOMElement */ private $currentTestCase; @@ -97,7 +107,7 @@ final class JUnit extends Printer implements TestListener */ public function __construct($out = null, bool $reportRiskyTests = false) { - $this->document = new \DOMDocument('1.0', 'UTF-8'); + $this->document = new DOMDocument('1.0', 'UTF-8'); $this->document->formatOutput = true; $this->root = $this->document->createElement('testsuites'); @@ -121,7 +131,7 @@ public function flush(): void /** * An error occurred. */ - public function addError(Test $test, \Throwable $t, float $time): void + public function addError(Test $test, Throwable $t, float $time): void { $this->doAddFault($test, $t, $time, 'error'); $this->testSuiteErrors[$this->testSuiteLevel]++; @@ -148,7 +158,7 @@ public function addFailure(Test $test, AssertionFailedError $e, float $time): vo /** * Incomplete test. */ - public function addIncompleteTest(Test $test, \Throwable $t, float $time): void + public function addIncompleteTest(Test $test, Throwable $t, float $time): void { $this->doAddSkipped(); } @@ -156,7 +166,7 @@ public function addIncompleteTest(Test $test, \Throwable $t, float $time): void /** * Risky test. */ - public function addRiskyTest(Test $test, \Throwable $t, float $time): void + public function addRiskyTest(Test $test, Throwable $t, float $time): void { if (!$this->reportRiskyTests || $this->currentTestCase === null) { return; @@ -170,7 +180,7 @@ public function addRiskyTest(Test $test, \Throwable $t, float $time): void ) ); - $error->setAttribute('type', \get_class($t)); + $error->setAttribute('type', get_class($t)); $this->currentTestCase->appendChild($error); @@ -180,7 +190,7 @@ public function addRiskyTest(Test $test, \Throwable $t, float $time): void /** * Skipped test. */ - public function addSkippedTest(Test $test, \Throwable $t, float $time): void + public function addSkippedTest(Test $test, Throwable $t, float $time): void { $this->doAddSkipped(); } @@ -193,12 +203,12 @@ public function startTestSuite(TestSuite $suite): void $testSuite = $this->document->createElement('testsuite'); $testSuite->setAttribute('name', $suite->getName()); - if (\class_exists($suite->getName(), false)) { + if (class_exists($suite->getName(), false)) { try { - $class = new \ReflectionClass($suite->getName()); + $class = new ReflectionClass($suite->getName()); $testSuite->setAttribute('file', $class->getFileName()); - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { } } @@ -256,7 +266,7 @@ public function endTestSuite(TestSuite $suite): void $this->testSuites[$this->testSuiteLevel]->setAttribute( 'time', - \sprintf('%F', $this->testSuiteTimes[$this->testSuiteLevel]) + sprintf('%F', $this->testSuiteTimes[$this->testSuiteLevel]) ); if ($this->testSuiteLevel > 1) { @@ -279,7 +289,7 @@ public function startTest(Test $test): void { $usesDataprovider = false; - if (\method_exists($test, 'usesDataProvider')) { + if (method_exists($test, 'usesDataProvider')) { $usesDataprovider = $test->usesDataProvider(); } @@ -287,9 +297,9 @@ public function startTest(Test $test): void $testCase->setAttribute('name', $test->getName()); try { - $class = new \ReflectionClass($test); + $class = new ReflectionClass($test); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -304,7 +314,7 @@ public function startTest(Test $test): void try { $method = $class->getMethod($methodName); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -314,7 +324,7 @@ public function startTest(Test $test): void // @codeCoverageIgnoreEnd $testCase->setAttribute('class', $class->getName()); - $testCase->setAttribute('classname', \str_replace('\\', '.', $class->getName())); + $testCase->setAttribute('classname', str_replace('\\', '.', $class->getName())); $testCase->setAttribute('file', $class->getFileName()); $testCase->setAttribute('line', (string) $method->getStartLine()); } @@ -329,7 +339,7 @@ public function endTest(Test $test, float $time): void { $numAssertions = 0; - if (\method_exists($test, 'getNumAssertions')) { + if (method_exists($test, 'getNumAssertions')) { $numAssertions = $test->getNumAssertions(); } @@ -342,7 +352,7 @@ public function endTest(Test $test, float $time): void $this->currentTestCase->setAttribute( 'time', - \sprintf('%F', $time) + sprintf('%F', $time) ); $this->testSuites[$this->testSuiteLevel]->appendChild( @@ -354,7 +364,7 @@ public function endTest(Test $test, float $time): void $testOutput = ''; - if (\method_exists($test, 'hasOutput') && \method_exists($test, 'getActualOutput')) { + if (method_exists($test, 'hasOutput') && method_exists($test, 'getActualOutput')) { $testOutput = $test->hasOutput() ? $test->getActualOutput() : ''; } @@ -378,7 +388,7 @@ public function getXML(): string return $this->document->saveXML(); } - private function doAddFault(Test $test, \Throwable $t, float $time, $type): void + private function doAddFault(Test $test, Throwable $t, float $time, $type): void { if ($this->currentTestCase === null) { return; @@ -401,7 +411,7 @@ private function doAddFault(Test $test, \Throwable $t, float $time, $type): void if ($t instanceof ExceptionWrapper) { $fault->setAttribute('type', $t->getClassName()); } else { - $fault->setAttribute('type', \get_class($t)); + $fault->setAttribute('type', get_class($t)); } $this->currentTestCase->appendChild($fault); diff --git a/src/Util/Log/TeamCity.php b/src/Util/Log/TeamCity.php index 60d224c901a..695760d9542 100644 --- a/src/Util/Log/TeamCity.php +++ b/src/Util/Log/TeamCity.php @@ -9,6 +9,19 @@ */ namespace PHPUnit\Util\Log; +use function class_exists; +use function count; +use function explode; +use function get_class; +use function getmypid; +use function ini_get; +use function is_bool; +use function is_scalar; +use function method_exists; +use function print_r; +use function round; +use function str_replace; +use function stripos; use PHPUnit\Framework\AssertionFailedError; use PHPUnit\Framework\ExceptionWrapper; use PHPUnit\Framework\ExpectationFailedException; @@ -21,7 +34,10 @@ use PHPUnit\TextUI\ResultPrinter; use PHPUnit\Util\Exception; use PHPUnit\Util\Filter; +use ReflectionClass; +use ReflectionException; use SebastianBergmann\Comparator\ComparisonFailure; +use Throwable; /** * @internal This class is not covered by the backward compatibility promise for PHPUnit @@ -55,7 +71,7 @@ public function printResult(TestResult $result): void /** * An error occurred. */ - public function addError(Test $test, \Throwable $t, float $time): void + public function addError(Test $test, Throwable $t, float $time): void { $this->printEvent( 'testFailed', @@ -73,15 +89,7 @@ public function addError(Test $test, \Throwable $t, float $time): void */ public function addWarning(Test $test, Warning $e, float $time): void { - $this->printEvent( - 'testFailed', - [ - 'name' => $test->getName(), - 'message' => self::getMessage($e), - 'details' => self::getDetails($e), - 'duration' => self::toMilliseconds($time), - ] - ); + $this->write(self::getMessage($e) . PHP_EOL); } /** @@ -126,7 +134,7 @@ public function addFailure(Test $test, AssertionFailedError $e, float $time): vo /** * Incomplete test. */ - public function addIncompleteTest(Test $test, \Throwable $t, float $time): void + public function addIncompleteTest(Test $test, Throwable $t, float $time): void { $this->printIgnoredTest($test->getName(), $t, $time); } @@ -134,7 +142,7 @@ public function addIncompleteTest(Test $test, \Throwable $t, float $time): void /** * Risky test. */ - public function addRiskyTest(Test $test, \Throwable $t, float $time): void + public function addRiskyTest(Test $test, Throwable $t, float $time): void { $this->addError($test, $t, $time); } @@ -142,7 +150,7 @@ public function addRiskyTest(Test $test, \Throwable $t, float $time): void /** * Skipped test. */ - public function addSkippedTest(Test $test, \Throwable $t, float $time): void + public function addSkippedTest(Test $test, Throwable $t, float $time): void { $testName = $test->getName(); @@ -155,7 +163,7 @@ public function addSkippedTest(Test $test, \Throwable $t, float $time): void } } - public function printIgnoredTest($testName, \Throwable $t, float $time): void + public function printIgnoredTest($testName, Throwable $t, float $time): void { $this->printEvent( 'testIgnored', @@ -173,8 +181,8 @@ public function printIgnoredTest($testName, \Throwable $t, float $time): void */ public function startTestSuite(TestSuite $suite): void { - if (\stripos(\ini_get('disable_functions'), 'getmypid') === false) { - $this->flowId = \getmypid(); + if (stripos(ini_get('disable_functions'), 'getmypid') === false) { + $this->flowId = getmypid(); } else { $this->flowId = false; } @@ -184,7 +192,7 @@ public function startTestSuite(TestSuite $suite): void $this->printEvent( 'testCount', - ['count' => \count($suite)] + ['count' => count($suite)] ); } @@ -196,13 +204,13 @@ public function startTestSuite(TestSuite $suite): void $parameters = ['name' => $suiteName]; - if (\class_exists($suiteName, false)) { + if (class_exists($suiteName, false)) { $fileName = self::getFileName($suiteName); $parameters['locationHint'] = "php_qn://{$fileName}::\\{$suiteName}"; } else { - $split = \explode('::', $suiteName); + $split = explode('::', $suiteName); - if (\count($split) === 2 && \class_exists($split[0]) && \method_exists($split[0], $split[1])) { + if (count($split) === 2 && class_exists($split[0]) && method_exists($split[0], $split[1])) { $fileName = self::getFileName($split[0]); $parameters['locationHint'] = "php_qn://{$fileName}::\\{$suiteName}"; $parameters['name'] = $split[1]; @@ -225,10 +233,10 @@ public function endTestSuite(TestSuite $suite): void $parameters = ['name' => $suiteName]; - if (!\class_exists($suiteName, false)) { - $split = \explode('::', $suiteName); + if (!class_exists($suiteName, false)) { + $split = explode('::', $suiteName); - if (\count($split) === 2 && \class_exists($split[0]) && \method_exists($split[0], $split[1])) { + if (count($split) === 2 && class_exists($split[0]) && method_exists($split[0], $split[1])) { $parameters['name'] = $split[1]; } } @@ -246,7 +254,7 @@ public function startTest(Test $test): void $params = ['name' => $testName]; if ($test instanceof TestCase) { - $className = \get_class($test); + $className = get_class($test); $fileName = self::getFileName($className); $params['locationHint'] = "php_qn://{$fileName}::\\{$className}::{$testName}"; } @@ -290,7 +298,7 @@ private function printEvent(string $eventName, array $params = []): void $this->write("]\n"); } - private static function getMessage(\Throwable $t): string + private static function getMessage(Throwable $t): string { $message = ''; @@ -307,7 +315,7 @@ private static function getMessage(\Throwable $t): string return $message . $t->getMessage(); } - private static function getDetails(\Throwable $t): string + private static function getDetails(Throwable $t): string { $stackTrace = Filter::getFilteredStacktrace($t); $previous = $t instanceof ExceptionWrapper ? $t->getPreviousWrapped() : $t->getPrevious(); @@ -321,7 +329,7 @@ private static function getDetails(\Throwable $t): string $previous->getPreviousWrapped() : $previous->getPrevious(); } - return ' ' . \str_replace("\n", "\n ", $stackTrace); + return ' ' . str_replace("\n", "\n ", $stackTrace); } private static function getPrimitiveValueAsString($value): ?string @@ -330,12 +338,12 @@ private static function getPrimitiveValueAsString($value): ?string return 'null'; } - if (\is_bool($value)) { + if (is_bool($value)) { return $value ? 'true' : 'false'; } - if (\is_scalar($value)) { - return \print_r($value, true); + if (is_scalar($value)) { + return print_r($value, true); } return null; @@ -343,7 +351,7 @@ private static function getPrimitiveValueAsString($value): ?string private static function escapeValue(string $text): string { - return \str_replace( + return str_replace( ['|', "'", "\n", "\r", ']', '['], ['||', "|'", '|n', '|r', '|]', '|['], $text @@ -356,9 +364,9 @@ private static function escapeValue(string $text): string private static function getFileName($className): string { try { - return (new \ReflectionClass($className))->getFileName(); + return (new ReflectionClass($className))->getFileName(); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -373,6 +381,6 @@ private static function getFileName($className): string */ private static function toMilliseconds(float $time): int { - return (int) \round($time * 1000); + return (int) round($time * 1000); } } diff --git a/src/Util/PHP/AbstractPhpProcess.php b/src/Util/PHP/AbstractPhpProcess.php index 90978a8f3f9..b5de7144fe2 100644 --- a/src/Util/PHP/AbstractPhpProcess.php +++ b/src/Util/PHP/AbstractPhpProcess.php @@ -9,6 +9,22 @@ */ namespace PHPUnit\Util\PHP; +use const DIRECTORY_SEPARATOR; +use const PHP_SAPI; +use function array_keys; +use function array_merge; +use function assert; +use function escapeshellarg; +use function ini_get_all; +use function restore_error_handler; +use function set_error_handler; +use function sprintf; +use function str_replace; +use function strpos; +use function strrpos; +use function substr; +use function trim; +use function unserialize; use __PHP_Incomplete_Class; use ErrorException; use PHPUnit\Framework\AssertionFailedError; @@ -57,7 +73,7 @@ abstract class AbstractPhpProcess public static function factory(): self { - if (\DIRECTORY_SEPARATOR === '\\') { + if (DIRECTORY_SEPARATOR === '\\') { return new WindowsPhpProcess; } @@ -88,7 +104,7 @@ public function useStderrRedirection(): bool } /** - * Sets the input string to be sent via STDIN + * Sets the input string to be sent via STDIN. */ public function setStdin(string $stdin): void { @@ -96,7 +112,7 @@ public function setStdin(string $stdin): void } /** - * Returns the input string to be sent via STDIN + * Returns the input string to be sent via STDIN. */ public function getStdin(): string { @@ -104,7 +120,7 @@ public function getStdin(): string } /** - * Sets the string of arguments to pass to the php job + * Sets the string of arguments to pass to the php job. */ public function setArgs(string $args): void { @@ -112,7 +128,7 @@ public function setArgs(string $args): void } /** - * Returns the string of arguments to pass to the php job + * Returns the string of arguments to pass to the php job. */ public function getArgs(): string { @@ -120,7 +136,7 @@ public function getArgs(): string } /** - * Sets the array of environment variables to start the child process with + * Sets the array of environment variables to start the child process with. * * @param array $env */ @@ -130,7 +146,7 @@ public function setEnv(array $env): void } /** - * Returns the array of environment variables to start the child process with + * Returns the array of environment variables to start the child process with. */ public function getEnv(): array { @@ -138,7 +154,7 @@ public function getEnv(): array } /** - * Sets the amount of seconds to wait before timing out + * Sets the amount of seconds to wait before timing out. */ public function setTimeout(int $timeout): void { @@ -146,7 +162,7 @@ public function setTimeout(int $timeout): void } /** - * Returns the amount of seconds to wait before timing out + * Returns the amount of seconds to wait before timing out. */ public function getTimeout(): int { @@ -180,24 +196,24 @@ public function getCommand(array $settings, string $file = null): string $command = $this->runtime->getBinary(); if ($this->runtime->hasPCOV()) { - $settings = \array_merge( + $settings = array_merge( $settings, $this->runtime->getCurrentSettings( - \array_keys(\ini_get_all('pcov')) + array_keys(ini_get_all('pcov')) ) ); } elseif ($this->runtime->hasXdebug()) { - $settings = \array_merge( + $settings = array_merge( $settings, $this->runtime->getCurrentSettings( - \array_keys(\ini_get_all('xdebug')) + array_keys(ini_get_all('xdebug')) ) ); } $command .= $this->settingsToParameters($settings); - if (\PHP_SAPI === 'phpdbg') { + if (PHP_SAPI === 'phpdbg') { $command .= ' -qrr'; if (!$file) { @@ -206,7 +222,7 @@ public function getCommand(array $settings, string $file = null): string } if ($file) { - $command .= ' ' . \escapeshellarg($file); + $command .= ' ' . escapeshellarg($file); } if ($this->args) { @@ -233,7 +249,7 @@ protected function settingsToParameters(array $settings): string $buffer = ''; foreach ($settings as $setting) { - $buffer .= ' -d ' . \escapeshellarg($setting); + $buffer .= ' -d ' . escapeshellarg($setting); } return $buffer; @@ -251,11 +267,11 @@ private function processChildResult(Test $test, TestResult $result, string $stdo if (!empty($stderr)) { $result->addError( $test, - new Exception(\trim($stderr)), + new Exception(trim($stderr)), $time ); } else { - \set_error_handler( + set_error_handler( /** * @throws ErrorException */ @@ -265,12 +281,12 @@ static function ($errno, $errstr, $errfile, $errline): void { ); try { - if (\strpos($stdout, "#!/usr/bin/env php\n") === 0) { - $stdout = \substr($stdout, 19); + if (strpos($stdout, "#!/usr/bin/env php\n") === 0) { + $stdout = substr($stdout, 19); } - $childResult = \unserialize(\str_replace("#!/usr/bin/env php\n", '', $stdout)); - \restore_error_handler(); + $childResult = unserialize(str_replace("#!/usr/bin/env php\n", '', $stdout)); + restore_error_handler(); if ($childResult === false) { $result->addFailure( @@ -280,12 +296,12 @@ static function ($errno, $errstr, $errfile, $errline): void { ); } } catch (ErrorException $e) { - \restore_error_handler(); + restore_error_handler(); $childResult = false; $result->addError( $test, - new Exception(\trim($stdout), 0, $e), + new Exception(trim($stdout), 0, $e), $time ); } @@ -301,7 +317,7 @@ static function ($errno, $errstr, $errfile, $errline): void { $test->addToAssertionCount($childResult['numAssertions']); $childResult = $childResult['result']; - \assert($childResult instanceof TestResult); + assert($childResult instanceof TestResult); if ($result->getCollectCodeCoverageInformation()) { $result->getCodeCoverage()->merge( @@ -377,12 +393,12 @@ private function getException(TestFailure $error): Exception $exceptionArray = []; foreach ((array) $exception as $key => $value) { - $key = \substr($key, \strrpos($key, "\0") + 1); + $key = substr($key, strrpos($key, "\0") + 1); $exceptionArray[$key] = $value; } $exception = new SyntheticError( - \sprintf( + sprintf( '%s: %s', $exceptionArray['_PHP_Incomplete_Class_Name'], $exceptionArray['message'] diff --git a/src/Util/PHP/DefaultPhpProcess.php b/src/Util/PHP/DefaultPhpProcess.php index 1d47eafe314..b835043d8ee 100644 --- a/src/Util/PHP/DefaultPhpProcess.php +++ b/src/Util/PHP/DefaultPhpProcess.php @@ -9,6 +9,23 @@ */ namespace PHPUnit\Util\PHP; +use function array_merge; +use function fclose; +use function file_put_contents; +use function fread; +use function fwrite; +use function is_array; +use function is_resource; +use function proc_close; +use function proc_open; +use function proc_terminate; +use function rewind; +use function sprintf; +use function stream_get_contents; +use function stream_select; +use function sys_get_temp_dir; +use function tempnam; +use function unlink; use PHPUnit\Framework\Exception; /** @@ -29,8 +46,8 @@ class DefaultPhpProcess extends AbstractPhpProcess public function runJob(string $job, array $settings = []): array { if ($this->stdin || $this->useTemporaryFile()) { - if (!($this->tempFile = \tempnam(\sys_get_temp_dir(), 'PHPUnit')) || - \file_put_contents($this->tempFile, $job) === false) { + if (!($this->tempFile = tempnam(sys_get_temp_dir(), 'PHPUnit')) || + file_put_contents($this->tempFile, $job) === false) { throw new Exception( 'Unable to write temporary file' ); @@ -43,7 +60,7 @@ public function runJob(string $job, array $settings = []): array } /** - * Returns an array of file handles to be used in place of pipes + * Returns an array of file handles to be used in place of pipes. */ protected function getHandles(): array { @@ -51,7 +68,7 @@ protected function getHandles(): array } /** - * Handles creating the child process and returning the STDOUT and STDERR + * Handles creating the child process and returning the STDOUT and STDERR. * * @throws Exception */ @@ -64,10 +81,10 @@ protected function runProcess(string $job, array $settings): array if ($this->env) { $env = $_SERVER ?? []; unset($env['argv'], $env['argc']); - $env = \array_merge($env, $this->env); + $env = array_merge($env, $this->env); foreach ($env as $envKey => $envVar) { - if (\is_array($envVar)) { + if (is_array($envVar)) { unset($env[$envKey]); } } @@ -79,7 +96,7 @@ protected function runProcess(string $job, array $settings): array 2 => $handles[2] ?? ['pipe', 'w'], ]; - $process = \proc_open( + $process = proc_open( $this->getCommand($settings, $this->tempFile), $pipeSpec, $pipes, @@ -87,7 +104,7 @@ protected function runProcess(string $job, array $settings): array $env ); - if (!\is_resource($process)) { + if (!is_resource($process)) { throw new Exception( 'Unable to spawn worker process' ); @@ -97,7 +114,7 @@ protected function runProcess(string $job, array $settings): array $this->process($pipes[0], $job); } - \fclose($pipes[0]); + fclose($pipes[0]); $stderr = $stdout = ''; @@ -109,17 +126,17 @@ protected function runProcess(string $job, array $settings): array $w = null; $e = null; - $n = @\stream_select($r, $w, $e, $this->timeout); + $n = @stream_select($r, $w, $e, $this->timeout); if ($n === false) { break; } if ($n === 0) { - \proc_terminate($process, 9); + proc_terminate($process, 9); throw new Exception( - \sprintf( + sprintf( 'Job execution aborted after %d seconds', $this->timeout ) @@ -142,10 +159,10 @@ protected function runProcess(string $job, array $settings): array break; } - $line = \fread($pipe, 8192); + $line = fread($pipe, 8192); if ($line === '' || $line === false) { - \fclose($pipes[$pipeOffset]); + fclose($pipes[$pipeOffset]); unset($pipes[$pipeOffset]); } elseif ($pipeOffset === 1) { @@ -162,35 +179,35 @@ protected function runProcess(string $job, array $settings): array } } else { if (isset($pipes[1])) { - $stdout = \stream_get_contents($pipes[1]); + $stdout = stream_get_contents($pipes[1]); - \fclose($pipes[1]); + fclose($pipes[1]); } if (isset($pipes[2])) { - $stderr = \stream_get_contents($pipes[2]); + $stderr = stream_get_contents($pipes[2]); - \fclose($pipes[2]); + fclose($pipes[2]); } } if (isset($handles[1])) { - \rewind($handles[1]); + rewind($handles[1]); - $stdout = \stream_get_contents($handles[1]); + $stdout = stream_get_contents($handles[1]); - \fclose($handles[1]); + fclose($handles[1]); } if (isset($handles[2])) { - \rewind($handles[2]); + rewind($handles[2]); - $stderr = \stream_get_contents($handles[2]); + $stderr = stream_get_contents($handles[2]); - \fclose($handles[2]); + fclose($handles[2]); } - \proc_close($process); + proc_close($process); $this->cleanup(); @@ -199,13 +216,13 @@ protected function runProcess(string $job, array $settings): array protected function process($pipe, string $job): void { - \fwrite($pipe, $job); + fwrite($pipe, $job); } protected function cleanup(): void { if ($this->tempFile) { - \unlink($this->tempFile); + unlink($this->tempFile); } } diff --git a/src/Util/PHP/Template/TestCaseClass.tpl b/src/Util/PHP/Template/TestCaseClass.tpl index c25f63d9e76..5d2ea0252a5 100644 --- a/src/Util/PHP/Template/TestCaseClass.tpl +++ b/src/Util/PHP/Template/TestCaseClass.tpl @@ -60,7 +60,7 @@ function __phpunit_run_isolated_test() ini_set('xdebug.scream', '0'); @rewind(STDOUT); /* @ as not every STDOUT target stream is rewindable */ - if ($stdout = stream_get_contents(STDOUT)) { + if ($stdout = @stream_get_contents(STDOUT)) { $output = $stdout . $output; $streamMetaData = stream_get_meta_data(STDOUT); if (!empty($streamMetaData['stream_type']) && 'STDIO' === $streamMetaData['stream_type']) { diff --git a/src/Util/PHP/Template/TestCaseMethod.tpl b/src/Util/PHP/Template/TestCaseMethod.tpl index 68357eec1bc..9dd6c92034e 100644 --- a/src/Util/PHP/Template/TestCaseMethod.tpl +++ b/src/Util/PHP/Template/TestCaseMethod.tpl @@ -63,7 +63,7 @@ function __phpunit_run_isolated_test() ini_set('xdebug.scream', '0'); @rewind(STDOUT); /* @ as not every STDOUT target stream is rewindable */ - if ($stdout = stream_get_contents(STDOUT)) { + if ($stdout = @stream_get_contents(STDOUT)) { $output = $stdout . $output; $streamMetaData = stream_get_meta_data(STDOUT); if (!empty($streamMetaData['stream_type']) && 'STDIO' === $streamMetaData['stream_type']) { diff --git a/src/Util/PHP/WindowsPhpProcess.php b/src/Util/PHP/WindowsPhpProcess.php index 844a372d10e..9ef9255567f 100644 --- a/src/Util/PHP/WindowsPhpProcess.php +++ b/src/Util/PHP/WindowsPhpProcess.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Util\PHP; +use const PHP_MAJOR_VERSION; +use function tmpfile; use PHPUnit\Framework\Exception; /** @@ -20,7 +22,11 @@ final class WindowsPhpProcess extends DefaultPhpProcess { public function getCommand(array $settings, string $file = null): string { - return '"' . parent::getCommand($settings, $file) . '"'; + if (PHP_MAJOR_VERSION < 8) { + return '"' . parent::getCommand($settings, $file) . '"'; + } + + return parent::getCommand($settings, $file); } /** @@ -28,7 +34,7 @@ public function getCommand(array $settings, string $file = null): string */ protected function getHandles(): array { - if (false === $stdout_handle = \tmpfile()) { + if (false === $stdout_handle = tmpfile()) { throw new Exception( 'A temporary file could not be created; verify that your TEMP environment variable is writable' ); diff --git a/src/Util/Printer.php b/src/Util/Printer.php index 65abb4e2151..c99abfed5b2 100644 --- a/src/Util/Printer.php +++ b/src/Util/Printer.php @@ -9,6 +9,25 @@ */ namespace PHPUnit\Util; +use const ENT_SUBSTITUTE; +use const PHP_SAPI; +use function assert; +use function count; +use function dirname; +use function explode; +use function fclose; +use function fflush; +use function flush; +use function fopen; +use function fsockopen; +use function fwrite; +use function htmlspecialchars; +use function is_resource; +use function is_string; +use function sprintf; +use function str_replace; +use function strncmp; +use function strpos; use PHPUnit\Framework\Exception; /** @@ -46,40 +65,40 @@ public function __construct($out = null) return; } - if (\is_string($out) === false) { + if (is_string($out) === false) { $this->out = $out; return; } - if (\strpos($out, 'socket://') === 0) { - $out = \explode(':', \str_replace('socket://', '', $out)); + if (strpos($out, 'socket://') === 0) { + $out = explode(':', str_replace('socket://', '', $out)); - if (\count($out) !== 2) { + if (count($out) !== 2) { throw new Exception; } - $this->out = \fsockopen($out[0], $out[1]); + $this->out = fsockopen($out[0], $out[1]); } else { - if (\strpos($out, 'php://') === false && !Filesystem::createDirectory(\dirname($out))) { - throw new Exception(\sprintf('Directory "%s" was not created', \dirname($out))); + if (strpos($out, 'php://') === false && !Filesystem::createDirectory(dirname($out))) { + throw new Exception(sprintf('Directory "%s" was not created', dirname($out))); } - $this->out = \fopen($out, 'wt'); + $this->out = fopen($out, 'wt'); } $this->outTarget = $out; } /** - * Flush buffer and close output if it's not to a PHP stream + * Flush buffer and close output if it's not to a PHP stream. */ public function flush(): void { - if ($this->out && \strncmp($this->outTarget, 'php://', 6) !== 0) { - \assert(\is_resource($this->out)); + if ($this->out && strncmp($this->outTarget, 'php://', 6) !== 0) { + assert(is_resource($this->out)); - \fclose($this->out); + fclose($this->out); } } @@ -93,27 +112,27 @@ public function flush(): void public function incrementalFlush(): void { if ($this->out) { - \assert(\is_resource($this->out)); + assert(is_resource($this->out)); - \fflush($this->out); + fflush($this->out); } else { - \flush(); + flush(); } } public function write(string $buffer): void { if ($this->out) { - \assert(\is_resource($this->out)); + assert(is_resource($this->out)); - \fwrite($this->out, $buffer); + fwrite($this->out, $buffer); if ($this->autoFlush) { $this->incrementalFlush(); } } else { - if (\PHP_SAPI !== 'cli' && \PHP_SAPI !== 'phpdbg') { - $buffer = \htmlspecialchars($buffer, \ENT_SUBSTITUTE); + if (PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg') { + $buffer = htmlspecialchars($buffer, ENT_SUBSTITUTE); } print $buffer; diff --git a/src/Util/RegularExpression.php b/src/Util/RegularExpression.php index 582e8c2fca5..167b9215c2c 100644 --- a/src/Util/RegularExpression.php +++ b/src/Util/RegularExpression.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Util; +use function preg_match; + /** * @internal This class is not covered by the backward compatibility promise for PHPUnit */ @@ -21,7 +23,7 @@ public static function safeMatch(string $pattern, string $subject) { return ErrorHandler::invokeIgnoringWarnings( static function () use ($pattern, $subject) { - return \preg_match($pattern, $subject); + return preg_match($pattern, $subject); } ); } diff --git a/src/Util/Test.php b/src/Util/Test.php index bc5d1902c9b..4d0e79db049 100644 --- a/src/Util/Test.php +++ b/src/Util/Test.php @@ -9,6 +9,38 @@ */ namespace PHPUnit\Util; +use const PHP_OS; +use const PHP_VERSION; +use function addcslashes; +use function array_flip; +use function array_key_exists; +use function array_keys; +use function array_merge; +use function array_unique; +use function array_unshift; +use function class_exists; +use function class_implements; +use function class_parents; +use function count; +use function explode; +use function extension_loaded; +use function function_exists; +use function get_class; +use function ini_get; +use function interface_exists; +use function is_array; +use function is_int; +use function method_exists; +use function phpversion; +use function preg_match; +use function preg_replace; +use function range; +use function sprintf; +use function str_replace; +use function strncmp; +use function strpos; +use function trait_exists; +use function version_compare; use PHPUnit\Framework\Assert; use PHPUnit\Framework\CodeCoverageException; use PHPUnit\Framework\InvalidCoversTargetException; @@ -17,6 +49,10 @@ use PHPUnit\Framework\Warning; use PHPUnit\Runner\Version; use PHPUnit\Util\Annotation\Registry; +use ReflectionClass; +use ReflectionException; +use ReflectionFunction; +use ReflectionMethod; use SebastianBergmann\Environment\OperatingSystem; /** @@ -55,14 +91,14 @@ final class Test public static function describe(\PHPUnit\Framework\Test $test): array { if ($test instanceof TestCase) { - return [\get_class($test), $test->getName()]; + return [get_class($test), $test->getName()]; } if ($test instanceof SelfDescribing) { return ['', $test->toString()]; } - return ['', \get_class($test)]; + return ['', get_class($test)]; } public static function describeAsString(\PHPUnit\Framework\Test $test): string @@ -71,7 +107,7 @@ public static function describeAsString(\PHPUnit\Framework\Test $test): string return $test->toString(); } - return \get_class($test); + return get_class($test); } /** @@ -160,15 +196,15 @@ public static function getMissingRequirements(string $className, string $methodN if (!empty($required['PHP'])) { $operator = new VersionComparisonOperator(empty($required['PHP']['operator']) ? '>=' : $required['PHP']['operator']); - if (!\version_compare(\PHP_VERSION, $required['PHP']['version'], $operator->asString())) { - $missing[] = \sprintf('PHP %s %s is required.', $operator->asString(), $required['PHP']['version']); + if (!version_compare(PHP_VERSION, $required['PHP']['version'], $operator->asString())) { + $missing[] = sprintf('PHP %s %s is required.', $operator->asString(), $required['PHP']['version']); $hint = 'PHP'; } } elseif (!empty($required['PHP_constraint'])) { - $version = new \PharIo\Version\Version(self::sanitizeVersionNumber(\PHP_VERSION)); + $version = new \PharIo\Version\Version(self::sanitizeVersionNumber(PHP_VERSION)); if (!$required['PHP_constraint']['constraint']->complies($version)) { - $missing[] = \sprintf( + $missing[] = sprintf( 'PHP version does not match the required constraint %s.', $required['PHP_constraint']['constraint']->asString() ); @@ -182,15 +218,15 @@ public static function getMissingRequirements(string $className, string $methodN $operator = new VersionComparisonOperator(empty($required['PHPUnit']['operator']) ? '>=' : $required['PHPUnit']['operator']); - if (!\version_compare($phpunitVersion, $required['PHPUnit']['version'], $operator->asString())) { - $missing[] = \sprintf('PHPUnit %s %s is required.', $operator->asString(), $required['PHPUnit']['version']); + if (!version_compare($phpunitVersion, $required['PHPUnit']['version'], $operator->asString())) { + $missing[] = sprintf('PHPUnit %s %s is required.', $operator->asString(), $required['PHPUnit']['version']); $hint = $hint ?? 'PHPUnit'; } } elseif (!empty($required['PHPUnit_constraint'])) { $phpunitVersion = new \PharIo\Version\Version(self::sanitizeVersionNumber(Version::id())); if (!$required['PHPUnit_constraint']['constraint']->complies($phpunitVersion)) { - $missing[] = \sprintf( + $missing[] = sprintf( 'PHPUnit version does not match the required constraint %s.', $required['PHPUnit_constraint']['constraint']->asString() ); @@ -200,40 +236,40 @@ public static function getMissingRequirements(string $className, string $methodN } if (!empty($required['OSFAMILY']) && $required['OSFAMILY'] !== (new OperatingSystem)->getFamily()) { - $missing[] = \sprintf('Operating system %s is required.', $required['OSFAMILY']); + $missing[] = sprintf('Operating system %s is required.', $required['OSFAMILY']); $hint = $hint ?? 'OSFAMILY'; } if (!empty($required['OS'])) { - $requiredOsPattern = \sprintf('/%s/i', \addcslashes($required['OS'], '/')); + $requiredOsPattern = sprintf('/%s/i', addcslashes($required['OS'], '/')); - if (!\preg_match($requiredOsPattern, \PHP_OS)) { - $missing[] = \sprintf('Operating system matching %s is required.', $requiredOsPattern); + if (!preg_match($requiredOsPattern, PHP_OS)) { + $missing[] = sprintf('Operating system matching %s is required.', $requiredOsPattern); $hint = $hint ?? 'OS'; } } if (!empty($required['functions'])) { foreach ($required['functions'] as $function) { - $pieces = \explode('::', $function); + $pieces = explode('::', $function); - if (\count($pieces) === 2 && \class_exists($pieces[0]) && \method_exists($pieces[0], $pieces[1])) { + if (count($pieces) === 2 && class_exists($pieces[0]) && method_exists($pieces[0], $pieces[1])) { continue; } - if (\function_exists($function)) { + if (function_exists($function)) { continue; } - $missing[] = \sprintf('Function %s is required.', $function); + $missing[] = sprintf('Function %s is required.', $function); $hint = $hint ?? 'function_' . $function; } } if (!empty($required['setting'])) { foreach ($required['setting'] as $setting => $value) { - if (\ini_get($setting) !== $value) { - $missing[] = \sprintf('Setting "%s" must be "%s".', $setting, $value); + if (ini_get($setting) !== $value) { + $missing[] = sprintf('Setting "%s" must be "%s".', $setting, $value); $hint = $hint ?? '__SETTING_' . $setting; } } @@ -245,8 +281,8 @@ public static function getMissingRequirements(string $className, string $methodN continue; } - if (!\extension_loaded($extension)) { - $missing[] = \sprintf('Extension %s is required.', $extension); + if (!extension_loaded($extension)) { + $missing[] = sprintf('Extension %s is required.', $extension); $hint = $hint ?? 'extension_' . $extension; } } @@ -254,20 +290,20 @@ public static function getMissingRequirements(string $className, string $methodN if (!empty($required['extension_versions'])) { foreach ($required['extension_versions'] as $extension => $req) { - $actualVersion = \phpversion($extension); + $actualVersion = phpversion($extension); $operator = new VersionComparisonOperator(empty($req['operator']) ? '>=' : $req['operator']); - if ($actualVersion === false || !\version_compare($actualVersion, $req['version'], $operator->asString())) { - $missing[] = \sprintf('Extension %s %s %s is required.', $extension, $operator->asString(), $req['version']); + if ($actualVersion === false || !version_compare($actualVersion, $req['version'], $operator->asString())) { + $missing[] = sprintf('Extension %s %s %s is required.', $extension, $operator->asString(), $req['version']); $hint = $hint ?? 'extension_' . $extension; } } } if ($hint && isset($required['__OFFSET'])) { - \array_unshift($missing, '__OFFSET_FILE=' . $required['__OFFSET']['__FILE']); - \array_unshift($missing, '__OFFSET_LINE=' . ($required['__OFFSET'][$hint] ?? 1)); + array_unshift($missing, '__OFFSET_FILE=' . $required['__OFFSET']['__FILE']); + array_unshift($missing, '__OFFSET_LINE=' . ($required['__OFFSET'][$hint] ?? 1)); } return $missing; @@ -358,13 +394,13 @@ public static function getDependencies(string $className, string $methodName): a $dependencies = $annotations['class']['depends'] ?? []; if (isset($annotations['method']['depends'])) { - $dependencies = \array_merge( + $dependencies = array_merge( $dependencies, $annotations['method']['depends'] ); } - return \array_unique($dependencies); + return array_unique($dependencies); } /** @psalm-param class-string $className */ @@ -409,13 +445,13 @@ public static function getGroups(string $className, ?string $methodName = ''): a } } - return \array_unique(\array_merge([], ...$groups)); + return array_unique(array_merge([], ...$groups)); } /** @psalm-param class-string $className */ public static function getSize(string $className, ?string $methodName): int { - $groups = \array_flip(self::getGroups($className, $methodName)); + $groups = array_flip(self::getGroups($className, $methodName)); if (isset($groups['large'])) { return self::LARGE; @@ -467,7 +503,7 @@ public static function getPreserveGlobalStateSettings(string $className, string /** @psalm-param class-string $className */ public static function getHookMethods(string $className): array { - if (!\class_exists($className, false)) { + if (!class_exists($className, false)) { return self::emptyHookMethodsArray(); } @@ -475,7 +511,7 @@ public static function getHookMethods(string $className): array self::$hookMethods[$className] = self::emptyHookMethodsArray(); try { - foreach ((new \ReflectionClass($className))->getMethods() as $method) { + foreach ((new ReflectionClass($className))->getMethods() as $method) { if ($method->getDeclaringClass()->getName() === Assert::class) { continue; } @@ -488,7 +524,7 @@ public static function getHookMethods(string $className): array if ($method->isStatic()) { if ($docBlock->isHookToBeExecutedBeforeClass()) { - \array_unshift( + array_unshift( self::$hookMethods[$className]['beforeClass'], $method->getName() ); @@ -500,7 +536,7 @@ public static function getHookMethods(string $className): array } if ($docBlock->isToBeExecutedBeforeTest()) { - \array_unshift( + array_unshift( self::$hookMethods[$className]['before'], $method->getName() ); @@ -510,24 +546,24 @@ public static function getHookMethods(string $className): array self::$hookMethods[$className]['after'][] = $method->getName(); } } - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { } } return self::$hookMethods[$className]; } - public static function isTestMethod(\ReflectionMethod $method): bool + public static function isTestMethod(ReflectionMethod $method): bool { if (!$method->isPublic()) { return false; } - if (\strpos($method->getName(), 'test') === 0) { + if (strpos($method->getName(), 'test') === 0) { return true; } - return \array_key_exists( + return array_key_exists( 'test', Registry::getInstance()->forMethod( $method->getDeclaringClass()->getName(), @@ -551,9 +587,9 @@ private static function getLinesToBeCoveredOrUsed(string $className, string $met $classShortcut = null; if (!empty($annotations['class'][$mode . 'DefaultClass'])) { - if (\count($annotations['class'][$mode . 'DefaultClass']) > 1) { + if (count($annotations['class'][$mode . 'DefaultClass']) > 1) { throw new CodeCoverageException( - \sprintf( + sprintf( 'More than one @%sClass annotation in class or interface "%s".', $mode, $className @@ -567,23 +603,23 @@ private static function getLinesToBeCoveredOrUsed(string $className, string $met $list = $annotations['class'][$mode] ?? []; if (isset($annotations['method'][$mode])) { - $list = \array_merge($list, $annotations['method'][$mode]); + $list = array_merge($list, $annotations['method'][$mode]); } $codeList = []; - foreach (\array_unique($list) as $element) { - if ($classShortcut && \strncmp($element, '::', 2) === 0) { + foreach (array_unique($list) as $element) { + if ($classShortcut && strncmp($element, '::', 2) === 0) { $element = $classShortcut . $element; } - $element = \preg_replace('/[\s()]+$/', '', $element); - $element = \explode(' ', $element); + $element = preg_replace('/[\s()]+$/', '', $element); + $element = explode(' ', $element); $element = $element[0]; - if ($mode === 'covers' && \interface_exists($element)) { + if ($mode === 'covers' && interface_exists($element)) { throw new InvalidCoversTargetException( - \sprintf( + sprintf( 'Trying to @cover interface "%s".', $element ) @@ -593,7 +629,7 @@ private static function getLinesToBeCoveredOrUsed(string $className, string $met $codeList[] = self::resolveElementToReflectionObjects($element); } - return self::resolveReflectionObjectsToLines(\array_merge([], ...$codeList)); + return self::resolveReflectionObjectsToLines(array_merge([], ...$codeList)); } private static function emptyHookMethodsArray(): array @@ -644,11 +680,11 @@ private static function resolveElementToReflectionObjects(string $element): arra { $codeToCoverList = []; - if (\function_exists($element) && \strpos($element, '\\') !== false) { + if (function_exists($element) && strpos($element, '\\') !== false) { try { - $codeToCoverList[] = new \ReflectionFunction($element); + $codeToCoverList[] = new ReflectionFunction($element); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -656,18 +692,18 @@ private static function resolveElementToReflectionObjects(string $element): arra ); } // @codeCoverageIgnoreEnd - } elseif (\strpos($element, '::') !== false) { - [$className, $methodName] = \explode('::', $element); + } elseif (strpos($element, '::') !== false) { + [$className, $methodName] = explode('::', $element); if (isset($methodName[0]) && $methodName[0] === '<') { $classes = [$className]; foreach ($classes as $className) { - if (!\class_exists($className) && - !\interface_exists($className) && - !\trait_exists($className)) { + if (!class_exists($className) && + !interface_exists($className) && + !trait_exists($className)) { throw new InvalidCoversTargetException( - \sprintf( + sprintf( 'Trying to @cover or @use not existing class or ' . 'interface "%s".', $className @@ -676,9 +712,9 @@ private static function resolveElementToReflectionObjects(string $element): arra } try { - $methods = (new \ReflectionClass($className))->getMethods(); + $methods = (new ReflectionClass($className))->getMethods(); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -690,9 +726,9 @@ private static function resolveElementToReflectionObjects(string $element): arra $inverse = isset($methodName[1]) && $methodName[1] === '!'; $visibility = 'isPublic'; - if (\strpos($methodName, 'protected')) { + if (strpos($methodName, 'protected')) { $visibility = 'isProtected'; - } elseif (\strpos($methodName, 'private')) { + } elseif (strpos($methodName, 'private')) { $visibility = 'isPrivate'; } @@ -708,13 +744,13 @@ private static function resolveElementToReflectionObjects(string $element): arra $classes = [$className]; foreach ($classes as $className) { - if ($className === '' && \function_exists($methodName)) { + if ($className === '' && function_exists($methodName)) { try { - $codeToCoverList[] = new \ReflectionFunction( + $codeToCoverList[] = new ReflectionFunction( $methodName ); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -723,10 +759,10 @@ private static function resolveElementToReflectionObjects(string $element): arra } // @codeCoverageIgnoreEnd } else { - if (!((\class_exists($className) || \interface_exists($className) || \trait_exists($className)) && - \method_exists($className, $methodName))) { + if (!((class_exists($className) || interface_exists($className) || trait_exists($className)) && + method_exists($className, $methodName))) { throw new InvalidCoversTargetException( - \sprintf( + sprintf( 'Trying to @cover or @use not existing method "%s::%s".', $className, $methodName @@ -735,12 +771,12 @@ private static function resolveElementToReflectionObjects(string $element): arra } try { - $codeToCoverList[] = new \ReflectionMethod( + $codeToCoverList[] = new ReflectionMethod( $className, $methodName ); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -754,27 +790,27 @@ private static function resolveElementToReflectionObjects(string $element): arra } else { $extended = false; - if (\strpos($element, '') !== false) { - $element = \str_replace('', '', $element); + if (strpos($element, '') !== false) { + $element = str_replace('', '', $element); $extended = true; } $classes = [$element]; if ($extended) { - $classes = \array_merge( + $classes = array_merge( $classes, - \class_implements($element), - \class_parents($element) + class_implements($element), + class_parents($element) ); } foreach ($classes as $className) { - if (!\class_exists($className) && - !\interface_exists($className) && - !\trait_exists($className)) { + if (!class_exists($className) && + !interface_exists($className) && + !trait_exists($className)) { throw new InvalidCoversTargetException( - \sprintf( + sprintf( 'Trying to @cover or @use not existing class or ' . 'interface "%s".', $className @@ -783,9 +819,9 @@ private static function resolveElementToReflectionObjects(string $element): arra } try { - $codeToCoverList[] = new \ReflectionClass($className); + $codeToCoverList[] = new ReflectionClass($className); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -804,7 +840,7 @@ private static function resolveReflectionObjectsToLines(array $reflectors): arra $result = []; foreach ($reflectors as $reflector) { - if ($reflector instanceof \ReflectionClass) { + if ($reflector instanceof ReflectionClass) { foreach ($reflector->getTraits() as $trait) { $reflectors[] = $trait; } @@ -818,14 +854,14 @@ private static function resolveReflectionObjectsToLines(array $reflectors): arra $result[$filename] = []; } - $result[$filename] = \array_merge( + $result[$filename] = array_merge( $result[$filename], - \range($reflector->getStartLine(), $reflector->getEndLine()) + range($reflector->getStartLine(), $reflector->getEndLine()) ); } foreach ($result as $filename => $lineNumbers) { - $result[$filename] = \array_keys(\array_flip($lineNumbers)); + $result[$filename] = array_keys(array_flip($lineNumbers)); } return $result; @@ -833,11 +869,11 @@ private static function resolveReflectionObjectsToLines(array $reflectors): arra /** * Trims any extensions from version string that follows after - * the .[.] format + * the .[.] format. */ private static function sanitizeVersionNumber(string $version) { - return \preg_replace( + return preg_replace( '/^(\d+\.\d+(?:.\d+)?).*$/', '$1', $version @@ -872,7 +908,7 @@ private static function shouldCoversAnnotationBeUsed(array $annotations): bool * * Zend Framework (http://framework.zend.com/) * - * @link http://github.com/zendframework/zf2 for the canonical source repository + * @see http://github.com/zendframework/zf2 for the canonical source repository * * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License @@ -880,10 +916,10 @@ private static function shouldCoversAnnotationBeUsed(array $annotations): bool private static function mergeArraysRecursively(array $a, array $b): array { foreach ($b as $key => $value) { - if (\array_key_exists($key, $a)) { - if (\is_int($key)) { + if (array_key_exists($key, $a)) { + if (is_int($key)) { $a[] = $value; - } elseif (\is_array($value) && \is_array($a[$key])) { + } elseif (is_array($value) && is_array($a[$key])) { $a[$key] = self::mergeArraysRecursively($a[$key], $value); } else { $a[$key] = $value; diff --git a/src/Util/TestDox/CliTestDoxPrinter.php b/src/Util/TestDox/CliTestDoxPrinter.php index 7347be996ef..49badb8be1e 100644 --- a/src/Util/TestDox/CliTestDoxPrinter.php +++ b/src/Util/TestDox/CliTestDoxPrinter.php @@ -9,6 +9,18 @@ */ namespace PHPUnit\Util\TestDox; +use const PHP_EOL; +use function array_map; +use function ceil; +use function count; +use function explode; +use function get_class; +use function implode; +use function preg_match; +use function sprintf; +use function strlen; +use function strpos; +use function trim; use PHPUnit\Framework\Test; use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestResult; @@ -16,6 +28,7 @@ use PHPUnit\Runner\PhptTestCase; use PHPUnit\Util\Color; use SebastianBergmann\Timer\Timer; +use Throwable; /** * @internal This class is not covered by the backward compatibility promise for PHPUnit @@ -23,7 +36,7 @@ class CliTestDoxPrinter extends TestDoxPrinter { /** - * The default Testdox left margin for messages is a vertical line + * The default Testdox left margin for messages is a vertical line. */ private const PREFIX_SIMPLE = [ 'default' => '│', @@ -35,7 +48,7 @@ class CliTestDoxPrinter extends TestDoxPrinter ]; /** - * Colored Testdox use box-drawing for a more textured map of the message + * Colored Testdox use box-drawing for a more textured map of the message. */ private const PREFIX_DECORATED = [ 'default' => '│', @@ -123,16 +136,16 @@ protected function printHeader(TestResult $result): void protected function formatClassName(Test $test): string { if ($test instanceof TestCase) { - return $this->prettifier->prettifyTestClass(\get_class($test)); + return $this->prettifier->prettifyTestClass(get_class($test)); } - return \get_class($test); + return get_class($test); } /** * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ - protected function registerTestResult(Test $test, ?\Throwable $t, int $status, float $time, bool $verbose): void + protected function registerTestResult(Test $test, ?Throwable $t, int $status, float $time, bool $verbose): void { if ($status !== BaseTestRunner::STATUS_PASSED) { $this->nonSuccessfulTestResults[] = $this->testIndex; @@ -158,12 +171,12 @@ protected function writeTestResult(array $prevResult, array $result): void // spacer line for new suite headers and after verbose messages if ($prevResult['testName'] !== '' && (!empty($prevResult['message']) || $prevResult['className'] !== $result['className'])) { - $this->write(\PHP_EOL); + $this->write(PHP_EOL); } // suite header if ($prevResult['className'] !== $result['className']) { - $this->write($this->colorizeTextBox('underlined', $result['className']) . \PHP_EOL); + $this->write($this->colorizeTextBox('underlined', $result['className']) . PHP_EOL); } // test result line @@ -174,8 +187,8 @@ protected function writeTestResult(array $prevResult, array $result): void } $style = self::STATUS_STYLES[$result['status']]; - $line = \sprintf( - ' %s %s%s' . \PHP_EOL, + $line = sprintf( + ' %s %s%s' . PHP_EOL, $this->colorizeTextBox($style['color'], $style['symbol']), $testName, $this->verbose ? ' ' . $this->formatRuntime($result['time'], $style['color']) : '' @@ -187,14 +200,14 @@ protected function writeTestResult(array $prevResult, array $result): void $this->write($result['message']); } - protected function formatThrowable(\Throwable $t, ?int $status = null): string + protected function formatThrowable(Throwable $t, ?int $status = null): string { - return \trim(\PHPUnit\Framework\TestFailure::exceptionToString($t)); + return trim(\PHPUnit\Framework\TestFailure::exceptionToString($t)); } protected function colorizeMessageAndDiff(string $style, string $buffer): array { - $lines = $buffer ? \array_map('\rtrim', \explode(\PHP_EOL, $buffer)) : []; + $lines = $buffer ? array_map('\rtrim', explode(PHP_EOL, $buffer)) : []; $message = []; $diff = []; $insideDiff = false; @@ -207,9 +220,9 @@ protected function colorizeMessageAndDiff(string $style, string $buffer): array if (!$insideDiff) { $message[] = $line; } else { - if (\strpos($line, '-') === 0) { + if (strpos($line, '-') === 0) { $line = Color::colorize('fg-red', Color::visualizeWhitespace($line, true)); - } elseif (\strpos($line, '+') === 0) { + } elseif (strpos($line, '+') === 0) { $line = Color::colorize('fg-green', Color::visualizeWhitespace($line, true)); } elseif ($line === '@@ @@') { $line = Color::colorize('fg-cyan', $line); @@ -217,16 +230,16 @@ protected function colorizeMessageAndDiff(string $style, string $buffer): array $diff[] = $line; } } - $diff = \implode(\PHP_EOL, $diff); + $diff = implode(PHP_EOL, $diff); if (!empty($message)) { - $message = $this->colorizeTextBox($style, \implode(\PHP_EOL, $message)); + $message = $this->colorizeTextBox($style, implode(PHP_EOL, $message)); } return [$message, $diff]; } - protected function formatStacktrace(\Throwable $t): string + protected function formatStacktrace(Throwable $t): string { $trace = \PHPUnit\Util\Filter::getFilteredStacktrace($t); @@ -237,8 +250,8 @@ protected function formatStacktrace(\Throwable $t): string $lines = []; $prevPath = ''; - foreach (\explode(\PHP_EOL, $trace) as $line) { - if (\preg_match('/^(.*):(\d+)$/', $line, $matches)) { + foreach (explode(PHP_EOL, $trace) as $line) { + if (preg_match('/^(.*):(\d+)$/', $line, $matches)) { $lines[] = Color::colorizePath($matches[1], $prevPath) . Color::dim(':') . Color::colorize('fg-blue', $matches[2]) . @@ -250,10 +263,10 @@ protected function formatStacktrace(\Throwable $t): string } } - return \implode('', $lines); + return implode('', $lines); } - protected function formatTestResultMessage(\Throwable $t, array $result, ?string $prefix = null): string + protected function formatTestResultMessage(Throwable $t, array $result, ?string $prefix = null): string { $message = $this->formatThrowable($t, $result['status']); $diff = ''; @@ -273,29 +286,29 @@ protected function formatTestResultMessage(\Throwable $t, array $result, ?string if ($this->colors) { $color = self::STATUS_STYLES[$result['status']]['color'] ?? ''; - $prefix = \array_map(static function ($p) use ($color) { + $prefix = array_map(static function ($p) use ($color) { return Color::colorize($color, $p); }, self::PREFIX_DECORATED); } $trace = $this->formatStacktrace($t); - $out = $this->prefixLines($prefix['start'], \PHP_EOL) . \PHP_EOL; + $out = $this->prefixLines($prefix['start'], PHP_EOL) . PHP_EOL; if ($message) { - $out .= $this->prefixLines($prefix['message'], $message . \PHP_EOL) . \PHP_EOL; + $out .= $this->prefixLines($prefix['message'], $message . PHP_EOL) . PHP_EOL; } if ($diff) { - $out .= $this->prefixLines($prefix['diff'], $diff . \PHP_EOL) . \PHP_EOL; + $out .= $this->prefixLines($prefix['diff'], $diff . PHP_EOL) . PHP_EOL; } if ($trace) { if ($message || $diff) { - $out .= $this->prefixLines($prefix['default'], \PHP_EOL) . \PHP_EOL; + $out .= $this->prefixLines($prefix['default'], PHP_EOL) . PHP_EOL; } - $out .= $this->prefixLines($prefix['trace'], $trace . \PHP_EOL) . \PHP_EOL; + $out .= $this->prefixLines($prefix['trace'], $trace . PHP_EOL) . PHP_EOL; } - $out .= $this->prefixLines($prefix['last'], \PHP_EOL) . \PHP_EOL; + $out .= $this->prefixLines($prefix['last'], PHP_EOL) . PHP_EOL; return $out; } @@ -303,7 +316,7 @@ protected function formatTestResultMessage(\Throwable $t, array $result, ?string protected function drawSpinner(): void { if ($this->colors) { - $id = $this->spinState % \count(self::SPINNER_ICONS); + $id = $this->spinState % count(self::SPINNER_ICONS); $this->write(self::SPINNER_ICONS[$id]); } } @@ -311,22 +324,22 @@ protected function drawSpinner(): void protected function undrawSpinner(): void { if ($this->colors) { - $id = $this->spinState % \count(self::SPINNER_ICONS); - $this->write("\e[1K\e[" . \strlen(self::SPINNER_ICONS[$id]) . 'D'); + $id = $this->spinState % count(self::SPINNER_ICONS); + $this->write("\e[1K\e[" . strlen(self::SPINNER_ICONS[$id]) . 'D'); } } private function formatRuntime(float $time, string $color = ''): string { if (!$this->colors) { - return \sprintf('[%.2f ms]', $time * 1000); + return sprintf('[%.2f ms]', $time * 1000); } if ($time > 1) { $color = 'fg-magenta'; } - return Color::colorize($color, ' ' . (int) \ceil($time * 1000) . ' ' . Color::dim('ms')); + return Color::colorize($color, ' ' . (int) ceil($time * 1000) . ' ' . Color::dim('ms')); } private function printNonSuccessfulTestsSummary(int $numberOfExecutedTests): void @@ -335,7 +348,7 @@ private function printNonSuccessfulTestsSummary(int $numberOfExecutedTests): voi return; } - if ((\count($this->nonSuccessfulTestResults) / $numberOfExecutedTests) >= 0.7) { + if ((count($this->nonSuccessfulTestResults) / $numberOfExecutedTests) >= 0.7) { return; } diff --git a/src/Util/TestDox/HtmlResultPrinter.php b/src/Util/TestDox/HtmlResultPrinter.php index 41ed1a32419..c57480327a2 100644 --- a/src/Util/TestDox/HtmlResultPrinter.php +++ b/src/Util/TestDox/HtmlResultPrinter.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Util\TestDox; +use function sprintf; + /** * @internal This class is not covered by the backward compatibility promise for PHPUnit */ @@ -90,7 +92,7 @@ protected function startRun(): void protected function startClass(string $name): void { $this->write( - \sprintf( + sprintf( self::CLASS_HEADER, $name, $this->currentTestClassPrettified @@ -104,7 +106,7 @@ protected function startClass(string $name): void protected function onTest($name, bool $success = true): void { $this->write( - \sprintf( + sprintf( "
  • %s %s
  • \n", $success ? '#555753' : '#ef2929', $success ? '✓' : '❌', diff --git a/src/Util/TestDox/NamePrettifier.php b/src/Util/TestDox/NamePrettifier.php index ddf2fed14b4..b7da1c2daaa 100644 --- a/src/Util/TestDox/NamePrettifier.php +++ b/src/Util/TestDox/NamePrettifier.php @@ -9,10 +9,43 @@ */ namespace PHPUnit\Util\TestDox; +use function array_key_exists; +use function array_keys; +use function array_map; +use function array_pop; +use function array_values; +use function explode; +use function get_class; +use function gettype; +use function implode; +use function in_array; +use function is_bool; +use function is_float; +use function is_int; +use function is_numeric; +use function is_object; +use function is_scalar; +use function is_string; +use function mb_strtolower; +use function ord; +use function preg_quote; +use function preg_replace; +use function range; +use function sprintf; +use function str_replace; +use function strlen; +use function strpos; +use function strtolower; +use function strtoupper; +use function substr; +use function trim; use PHPUnit\Framework\TestCase; use PHPUnit\Util\Color; use PHPUnit\Util\Exception as UtilException; use PHPUnit\Util\Test; +use ReflectionException; +use ReflectionMethod; +use ReflectionObject; use SebastianBergmann\Exporter\Exporter; /** @@ -52,17 +85,17 @@ public function prettifyTestClass(string $className): string // ignore, determine className by parsing the provided name } - $parts = \explode('\\', $className); - $className = \array_pop($parts); + $parts = explode('\\', $className); + $className = array_pop($parts); - if (\substr($className, -1 * \strlen('Test')) === 'Test') { - $className = \substr($className, 0, \strlen($className) - \strlen('Test')); + if (substr($className, -1 * strlen('Test')) === 'Test') { + $className = substr($className, 0, strlen($className) - strlen('Test')); } - if (\strpos($className, 'Tests') === 0) { - $className = \substr($className, \strlen('Tests')); - } elseif (\strpos($className, 'Test') === 0) { - $className = \substr($className, \strlen('Test')); + if (strpos($className, 'Tests') === 0) { + $className = substr($className, strlen('Tests')); + } elseif (strpos($className, 'Test') === 0) { + $className = substr($className, strlen('Test')); } if (empty($className)) { @@ -71,7 +104,7 @@ public function prettifyTestClass(string $className): string if (!empty($parts)) { $parts[] = $className; - $fullyQualifiedName = \implode('\\', $parts); + $fullyQualifiedName = implode('\\', $parts); } else { $fullyQualifiedName = $className; } @@ -79,8 +112,8 @@ public function prettifyTestClass(string $className): string $result = ''; $wasLowerCase = false; - foreach (\range(0, \strlen($className) - 1) as $i) { - $isLowerCase = \mb_strtolower($className[$i], 'UTF-8') === $className[$i]; + foreach (range(0, strlen($className) - 1) as $i) { + $isLowerCase = mb_strtolower($className[$i], 'UTF-8') === $className[$i]; if ($wasLowerCase && !$isLowerCase) { $result .= ' '; @@ -111,18 +144,18 @@ public function prettifyTestCase(TestCase $test): string $annotationWithPlaceholders = false; $callback = static function (string $variable): string { - return \sprintf('/%s(?=\b)/', \preg_quote($variable, '/')); + return sprintf('/%s(?=\b)/', preg_quote($variable, '/')); }; if (isset($annotations['method']['testdox'][0])) { $result = $annotations['method']['testdox'][0]; - if (\strpos($result, '$') !== false) { + if (strpos($result, '$') !== false) { $annotation = $annotations['method']['testdox'][0]; $providedData = $this->mapTestMethodParameterNamesToProvidedDataValues($test); - $variables = \array_map($callback, \array_keys($providedData)); + $variables = array_map($callback, array_keys($providedData)); - $result = \trim(\preg_replace($variables, $providedData, $annotation)); + $result = trim(preg_replace($variables, $providedData, $annotation)); $annotationWithPlaceholders = true; } @@ -143,7 +176,7 @@ public function prettifyDataSet(TestCase $test): string return $test->getDataSetAsString(false); } - if (\is_int($test->dataName())) { + if (is_int($test->dataName())) { $data = Color::dim(' with data set ') . Color::colorize('fg-cyan', (string) $test->dataName()); } else { $data = Color::dim(' with ') . Color::colorize('fg-cyan', Color::visualizeWhitespace((string) $test->dataName())); @@ -163,37 +196,37 @@ public function prettifyTestMethod(string $name): string return $buffer; } - $string = (string) \preg_replace('#\d+$#', '', $name, -1, $count); + $string = (string) preg_replace('#\d+$#', '', $name, -1, $count); - if (\in_array($string, $this->strings, true)) { + if (in_array($string, $this->strings, true)) { $name = $string; } elseif ($count === 0) { $this->strings[] = $string; } - if (\strpos($name, 'test_') === 0) { - $name = \substr($name, 5); - } elseif (\strpos($name, 'test') === 0) { - $name = \substr($name, 4); + if (strpos($name, 'test_') === 0) { + $name = substr($name, 5); + } elseif (strpos($name, 'test') === 0) { + $name = substr($name, 4); } if ($name === '') { return $buffer; } - $name[0] = \strtoupper($name[0]); + $name[0] = strtoupper($name[0]); - if (\strpos($name, '_') !== false) { - return \trim(\str_replace('_', ' ', $name)); + if (strpos($name, '_') !== false) { + return trim(str_replace('_', ' ', $name)); } $wasNumeric = false; - foreach (\range(0, \strlen($name) - 1) as $i) { - if ($i > 0 && \ord($name[$i]) >= 65 && \ord($name[$i]) <= 90) { - $buffer .= ' ' . \strtolower($name[$i]); + foreach (range(0, strlen($name) - 1) as $i) { + if ($i > 0 && ord($name[$i]) >= 65 && ord($name[$i]) <= 90) { + $buffer .= ' ' . strtolower($name[$i]); } else { - $isNumeric = \is_numeric($name[$i]); + $isNumeric = is_numeric($name[$i]); if (!$wasNumeric && $isNumeric) { $buffer .= ' '; @@ -217,9 +250,9 @@ public function prettifyTestMethod(string $name): string private function mapTestMethodParameterNamesToProvidedDataValues(TestCase $test): array { try { - $reflector = new \ReflectionMethod(\get_class($test), $test->getName(false)); + $reflector = new ReflectionMethod(get_class($test), $test->getName(false)); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new UtilException( $e->getMessage(), (int) $e->getCode(), @@ -229,17 +262,17 @@ private function mapTestMethodParameterNamesToProvidedDataValues(TestCase $test) // @codeCoverageIgnoreEnd $providedData = []; - $providedDataValues = \array_values($test->getProvidedData()); + $providedDataValues = array_values($test->getProvidedData()); $i = 0; $providedData['$_dataName'] = $test->dataName(); foreach ($reflector->getParameters() as $parameter) { - if (!\array_key_exists($i, $providedDataValues) && $parameter->isDefaultValueAvailable()) { + if (!array_key_exists($i, $providedDataValues) && $parameter->isDefaultValueAvailable()) { try { $providedDataValues[$i] = $parameter->getDefaultValue(); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new UtilException( $e->getMessage(), (int) $e->getCode(), @@ -251,25 +284,25 @@ private function mapTestMethodParameterNamesToProvidedDataValues(TestCase $test) $value = $providedDataValues[$i++] ?? null; - if (\is_object($value)) { - $reflector = new \ReflectionObject($value); + if (is_object($value)) { + $reflector = new ReflectionObject($value); if ($reflector->hasMethod('__toString')) { $value = (string) $value; } else { - $value = \get_class($value); + $value = get_class($value); } } - if (!\is_scalar($value)) { - $value = \gettype($value); + if (!is_scalar($value)) { + $value = gettype($value); } - if (\is_bool($value) || \is_int($value) || \is_float($value)) { + if (is_bool($value) || is_int($value) || is_float($value)) { $value = (new Exporter)->export($value); } - if (\is_string($value) && $value === '') { + if (is_string($value) && $value === '') { if ($this->useColor) { $value = Color::colorize('dim,underlined', 'empty'); } else { @@ -281,7 +314,7 @@ private function mapTestMethodParameterNamesToProvidedDataValues(TestCase $test) } if ($this->useColor) { - $providedData = \array_map(static function ($value) { + $providedData = array_map(static function ($value) { return Color::colorize('fg-cyan', Color::visualizeWhitespace((string) $value, true)); }, $providedData); } diff --git a/src/Util/TestDox/ResultPrinter.php b/src/Util/TestDox/ResultPrinter.php index 72e6451b8e1..1c2a5c93d85 100644 --- a/src/Util/TestDox/ResultPrinter.php +++ b/src/Util/TestDox/ResultPrinter.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Util\TestDox; +use function get_class; +use function in_array; use PHPUnit\Framework\AssertionFailedError; use PHPUnit\Framework\Test; use PHPUnit\Framework\TestCase; @@ -18,6 +20,7 @@ use PHPUnit\Framework\WarningTestCase; use PHPUnit\Runner\BaseTestRunner; use PHPUnit\Util\Printer; +use Throwable; /** * @internal This class is not covered by the backward compatibility promise for PHPUnit @@ -124,7 +127,7 @@ public function flush(): void /** * An error occurred. */ - public function addError(Test $test, \Throwable $t, float $time): void + public function addError(Test $test, Throwable $t, float $time): void { if (!$this->isOfInterest($test)) { return; @@ -163,7 +166,7 @@ public function addFailure(Test $test, AssertionFailedError $e, float $time): vo /** * Incomplete test. */ - public function addIncompleteTest(Test $test, \Throwable $t, float $time): void + public function addIncompleteTest(Test $test, Throwable $t, float $time): void { if (!$this->isOfInterest($test)) { return; @@ -176,7 +179,7 @@ public function addIncompleteTest(Test $test, \Throwable $t, float $time): void /** * Risky test. */ - public function addRiskyTest(Test $test, \Throwable $t, float $time): void + public function addRiskyTest(Test $test, Throwable $t, float $time): void { if (!$this->isOfInterest($test)) { return; @@ -189,7 +192,7 @@ public function addRiskyTest(Test $test, \Throwable $t, float $time): void /** * Skipped test. */ - public function addSkippedTest(Test $test, \Throwable $t, float $time): void + public function addSkippedTest(Test $test, Throwable $t, float $time): void { if (!$this->isOfInterest($test)) { return; @@ -224,7 +227,7 @@ public function startTest(Test $test): void return; } - $class = \get_class($test); + $class = get_class($test); if ($this->testClass !== $class) { if ($this->testClass !== '') { @@ -316,7 +319,7 @@ private function isOfInterest(Test $test): bool if (!empty($this->groups)) { foreach ($test->getGroups() as $group) { - if (\in_array($group, $this->groups, true)) { + if (in_array($group, $this->groups, true)) { return true; } } @@ -326,7 +329,7 @@ private function isOfInterest(Test $test): bool if (!empty($this->excludeGroups)) { foreach ($test->getGroups() as $group) { - if (\in_array($group, $this->excludeGroups, true)) { + if (in_array($group, $this->excludeGroups, true)) { return false; } } diff --git a/src/Util/TestDox/TestDoxPrinter.php b/src/Util/TestDox/TestDoxPrinter.php index 401777edf51..c19ba2699d4 100644 --- a/src/Util/TestDox/TestDoxPrinter.php +++ b/src/Util/TestDox/TestDoxPrinter.php @@ -9,6 +9,12 @@ */ namespace PHPUnit\Util\TestDox; +use const PHP_EOL; +use function array_map; +use function get_class; +use function implode; +use function preg_split; +use function trim; use PHPUnit\Framework\AssertionFailedError; use PHPUnit\Framework\Test; use PHPUnit\Framework\TestCase; @@ -19,6 +25,7 @@ use PHPUnit\Runner\PhptTestCase; use PHPUnit\Runner\TestSuiteSorter; use PHPUnit\TextUI\ResultPrinter; +use Throwable; /** * @internal This class is not covered by the backward compatibility promise for PHPUnit @@ -120,7 +127,7 @@ public function endTest(Test $test, float $time): void /** * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ - public function addError(Test $test, \Throwable $t, float $time): void + public function addError(Test $test, Throwable $t, float $time): void { $this->registerTestResult($test, $t, BaseTestRunner::STATUS_ERROR, $time, true); } @@ -144,7 +151,7 @@ public function addFailure(Test $test, AssertionFailedError $e, float $time): vo /** * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ - public function addIncompleteTest(Test $test, \Throwable $t, float $time): void + public function addIncompleteTest(Test $test, Throwable $t, float $time): void { $this->registerTestResult($test, $t, BaseTestRunner::STATUS_INCOMPLETE, $time, false); } @@ -152,7 +159,7 @@ public function addIncompleteTest(Test $test, \Throwable $t, float $time): void /** * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ - public function addRiskyTest(Test $test, \Throwable $t, float $time): void + public function addRiskyTest(Test $test, Throwable $t, float $time): void { $this->registerTestResult($test, $t, BaseTestRunner::STATUS_RISKY, $time, false); } @@ -160,7 +167,7 @@ public function addRiskyTest(Test $test, \Throwable $t, float $time): void /** * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ - public function addSkippedTest(Test $test, \Throwable $t, float $time): void + public function addSkippedTest(Test $test, Throwable $t, float $time): void { $this->registerTestResult($test, $t, BaseTestRunner::STATUS_SKIPPED, $time, false); } @@ -178,7 +185,7 @@ public function flush(): void /** * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException */ - protected function registerTestResult(Test $test, ?\Throwable $t, int $status, float $time, bool $verbose): void + protected function registerTestResult(Test $test, ?Throwable $t, int $status, float $time, bool $verbose): void { $testName = TestSuiteSorter::getTestSorterUID($test); @@ -207,7 +214,7 @@ protected function formatTestName(Test $test): string protected function formatClassName(Test $test): string { - return \get_class($test); + return get_class($test); } protected function testHasPassed(): bool @@ -327,12 +334,12 @@ protected function getTestResultByName(?string $testName): array return []; } - protected function formatThrowable(\Throwable $t, ?int $status = null): string + protected function formatThrowable(Throwable $t, ?int $status = null): string { - $message = \trim(\PHPUnit\Framework\TestFailure::exceptionToString($t)); + $message = trim(\PHPUnit\Framework\TestFailure::exceptionToString($t)); if ($message) { - $message .= \PHP_EOL . \PHP_EOL . $this->formatStacktrace($t); + $message .= PHP_EOL . PHP_EOL . $this->formatStacktrace($t); } else { $message = $this->formatStacktrace($t); } @@ -340,12 +347,12 @@ protected function formatThrowable(\Throwable $t, ?int $status = null): string return $message; } - protected function formatStacktrace(\Throwable $t): string + protected function formatStacktrace(Throwable $t): string { return \PHPUnit\Util\Filter::getFilteredStacktrace($t); } - protected function formatTestResultMessage(\Throwable $t, array $result, string $prefix = '│'): string + protected function formatTestResultMessage(Throwable $t, array $result, string $prefix = '│'): string { $message = $this->formatThrowable($t, $result['status']); @@ -362,15 +369,15 @@ protected function formatTestResultMessage(\Throwable $t, array $result, string protected function prefixLines(string $prefix, string $message): string { - $message = \trim($message); + $message = trim($message); - return \implode( - \PHP_EOL, - \array_map( + return implode( + PHP_EOL, + array_map( static function (string $text) use ($prefix) { return ' ' . $prefix . ($text ? ' ' . $text : ''); }, - \preg_split('/\r\n|\r|\n/', $message) + preg_split('/\r\n|\r|\n/', $message) ) ); } diff --git a/src/Util/TestDox/XmlResultPrinter.php b/src/Util/TestDox/XmlResultPrinter.php index e4344fc2534..7a8d7d76920 100644 --- a/src/Util/TestDox/XmlResultPrinter.php +++ b/src/Util/TestDox/XmlResultPrinter.php @@ -9,6 +9,9 @@ */ namespace PHPUnit\Util\TestDox; +use function array_filter; +use function get_class; +use function implode; use DOMDocument; use DOMElement; use PHPUnit\Framework\AssertionFailedError; @@ -19,6 +22,9 @@ use PHPUnit\Framework\TestSuite; use PHPUnit\Framework\Warning; use PHPUnit\Util\Printer; +use ReflectionClass; +use ReflectionException; +use Throwable; /** * @internal This class is not covered by the backward compatibility promise for PHPUnit @@ -41,7 +47,7 @@ final class XmlResultPrinter extends Printer implements TestListener private $prettifier; /** - * @var null|\Throwable + * @var null|Throwable */ private $exception; @@ -76,7 +82,7 @@ public function flush(): void /** * An error occurred. */ - public function addError(Test $test, \Throwable $t, float $time): void + public function addError(Test $test, Throwable $t, float $time): void { $this->exception = $t; } @@ -99,21 +105,21 @@ public function addFailure(Test $test, AssertionFailedError $e, float $time): vo /** * Incomplete test. */ - public function addIncompleteTest(Test $test, \Throwable $t, float $time): void + public function addIncompleteTest(Test $test, Throwable $t, float $time): void { } /** * Risky test. */ - public function addRiskyTest(Test $test, \Throwable $t, float $time): void + public function addRiskyTest(Test $test, Throwable $t, float $time): void { } /** * Skipped test. */ - public function addSkippedTest(Test $test, \Throwable $t, float $time): void + public function addSkippedTest(Test $test, Throwable $t, float $time): void { } @@ -150,7 +156,7 @@ public function endTest(Test $test, float $time): void return; } - $groups = \array_filter( + $groups = array_filter( $test->getGroups(), static function ($group) { return !($group === 'small' || $group === 'medium' || $group === 'large'); @@ -159,14 +165,14 @@ static function ($group) { $testNode = $this->document->createElement('test'); - $testNode->setAttribute('className', \get_class($test)); + $testNode->setAttribute('className', get_class($test)); $testNode->setAttribute('methodName', $test->getName()); - $testNode->setAttribute('prettifiedClassName', $this->prettifier->prettifyTestClass(\get_class($test))); + $testNode->setAttribute('prettifiedClassName', $this->prettifier->prettifyTestClass(get_class($test))); $testNode->setAttribute('prettifiedMethodName', $this->prettifier->prettifyTestCase($test)); $testNode->setAttribute('status', (string) $test->getStatus()); $testNode->setAttribute('time', (string) $time); $testNode->setAttribute('size', (string) $test->getSize()); - $testNode->setAttribute('groups', \implode(',', $groups)); + $testNode->setAttribute('groups', implode(',', $groups)); foreach ($groups as $group) { $groupNode = $this->document->createElement('group'); @@ -202,7 +208,7 @@ static function ($group) { $testNode->appendChild($testDoubleNode); } - $inlineAnnotations = \PHPUnit\Util\Test::getInlineAnnotations(\get_class($test), $test->getName(false)); + $inlineAnnotations = \PHPUnit\Util\Test::getInlineAnnotations(get_class($test), $test->getName(false)); if (isset($inlineAnnotations['given'], $inlineAnnotations['when'], $inlineAnnotations['then'])) { $testNode->setAttribute('given', $inlineAnnotations['given']['value']); @@ -221,9 +227,9 @@ static function ($group) { } try { - $file = (new \ReflectionClass($test))->getFileName(); + $file = (new ReflectionClass($test))->getFileName(); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), diff --git a/src/Util/TextTestListRenderer.php b/src/Util/TextTestListRenderer.php index 500038044f0..67168a67f31 100644 --- a/src/Util/TextTestListRenderer.php +++ b/src/Util/TextTestListRenderer.php @@ -9,9 +9,14 @@ */ namespace PHPUnit\Util; +use const PHP_EOL; +use function get_class; +use function sprintf; +use function str_replace; use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestSuite; use PHPUnit\Runner\PhptTestCase; +use RecursiveIteratorIterator; /** * @internal This class is not covered by the backward compatibility promise for PHPUnit @@ -23,14 +28,14 @@ final class TextTestListRenderer */ public function render(TestSuite $suite): string { - $buffer = 'Available test(s):' . \PHP_EOL; + $buffer = 'Available test(s):' . PHP_EOL; - foreach (new \RecursiveIteratorIterator($suite->getIterator()) as $test) { + foreach (new RecursiveIteratorIterator($suite->getIterator()) as $test) { if ($test instanceof TestCase) { - $name = \sprintf( + $name = sprintf( '%s::%s', - \get_class($test), - \str_replace(' with data set ', '', $test->getName()) + get_class($test), + str_replace(' with data set ', '', $test->getName()) ); } elseif ($test instanceof PhptTestCase) { $name = $test->getName(); @@ -38,8 +43,8 @@ public function render(TestSuite $suite): string continue; } - $buffer .= \sprintf( - ' - %s' . \PHP_EOL, + $buffer .= sprintf( + ' - %s' . PHP_EOL, $name ); } diff --git a/src/Util/Type.php b/src/Util/Type.php index e17583029e6..01a6b1931e9 100644 --- a/src/Util/Type.php +++ b/src/Util/Type.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Util; +use Throwable; + /** * @internal This class is not covered by the backward compatibility promise for PHPUnit */ @@ -41,7 +43,7 @@ public static function isCloneable(object $object): bool { try { $clone = clone $object; - } catch (\Throwable $t) { + } catch (Throwable $t) { return false; } diff --git a/src/Util/VersionComparisonOperator.php b/src/Util/VersionComparisonOperator.php index 15ff52b9779..ab65dbf359a 100644 --- a/src/Util/VersionComparisonOperator.php +++ b/src/Util/VersionComparisonOperator.php @@ -9,6 +9,9 @@ */ namespace PHPUnit\Util; +use function in_array; +use function sprintf; + /** * @internal This class is not covered by the backward compatibility promise for PHPUnit * @psalm-immutable @@ -42,9 +45,9 @@ public function asString(): string */ private function ensureOperatorIsValid(string $operator): void { - if (!\in_array($operator, ['<', 'lt', '<=', 'le', '>', 'gt', '>=', 'ge', '==', '=', 'eq', '!=', '<>', 'ne'], true)) { + if (!in_array($operator, ['<', 'lt', '<=', 'le', '>', 'gt', '>=', 'ge', '==', '=', 'eq', '!=', '<>', 'ne'], true)) { throw new Exception( - \sprintf( + sprintf( '"%s" is not a valid version_compare() operator', $operator ) diff --git a/src/Util/XdebugFilterScriptGenerator.php b/src/Util/XdebugFilterScriptGenerator.php index 2230e2937c1..fc351019296 100644 --- a/src/Util/XdebugFilterScriptGenerator.php +++ b/src/Util/XdebugFilterScriptGenerator.php @@ -9,6 +9,14 @@ */ namespace PHPUnit\Util; +use const DIRECTORY_SEPARATOR; +use function addslashes; +use function array_map; +use function implode; +use function is_string; +use function realpath; +use function sprintf; + /** * @internal This class is not covered by the backward compatibility promise for PHPUnit */ @@ -18,9 +26,9 @@ public function generate(array $filterData): string { $items = $this->getWhitelistItems($filterData); - $files = \array_map( + $files = array_map( static function ($item) { - return \sprintf( + return sprintf( " '%s'", $item ); @@ -28,7 +36,7 @@ static function ($item) { $items ); - $files = \implode(",\n", $files); + $files = implode(",\n", $files); return <<preserveWhiteSpace = false; - $internal = \libxml_use_internal_errors(true); + $internal = libxml_use_internal_errors(true); $message = ''; - $reporting = \error_reporting(0); + $reporting = error_reporting(0); if ($filename !== '') { // Required for XInclude @@ -86,21 +107,21 @@ public static function load($actual, bool $isHtml = false, string $filename = '' $document->xinclude(); } - foreach (\libxml_get_errors() as $error) { + foreach (libxml_get_errors() as $error) { $message .= "\n" . $error->message; } - \libxml_use_internal_errors($internal); - \error_reporting($reporting); + libxml_use_internal_errors($internal); + error_reporting($reporting); if (isset($cwd)) { - @\chdir($cwd); + @chdir($cwd); } if ($loaded === false || ($strict && $message !== '')) { if ($filename !== '') { throw new Exception( - \sprintf( + sprintf( 'Could not load "%s".%s', $filename, $message !== '' ? "\n" . $message : '' @@ -125,14 +146,14 @@ public static function load($actual, bool $isHtml = false, string $filename = '' */ public static function loadFile(string $filename, bool $isHtml = false, bool $xinclude = false, bool $strict = false): DOMDocument { - $reporting = \error_reporting(0); - $contents = \file_get_contents($filename); + $reporting = error_reporting(0); + $contents = file_get_contents($filename); - \error_reporting($reporting); + error_reporting($reporting); if ($contents === false) { throw new Exception( - \sprintf( + sprintf( 'Could not read "%s".', $filename ) @@ -154,7 +175,7 @@ public static function removeCharacterDataNodes(DOMNode $node): void } /** - * Escapes a string for the use in XML documents + * Escapes a string for the use in XML documents. * * Any Unicode character is allowed, excluding the surrogate blocks, FFFE, * and FFFF (not even as character reference). @@ -163,12 +184,12 @@ public static function removeCharacterDataNodes(DOMNode $node): void */ public static function prepareString(string $string): string { - return \preg_replace( + return preg_replace( '/[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]/', '', - \htmlspecialchars( + htmlspecialchars( self::convertToUtf8($string), - \ENT_QUOTES + ENT_QUOTES ) ); } @@ -219,11 +240,11 @@ public static function xmlToVariable(DOMElement $element) } try { - \assert(\class_exists($className)); + assert(class_exists($className)); - $variable = (new \ReflectionClass($className))->newInstanceArgs($constructorArgs); + $variable = (new ReflectionClass($className))->newInstanceArgs($constructorArgs); // @codeCoverageIgnoreStart - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { throw new Exception( $e->getMessage(), (int) $e->getCode(), @@ -247,7 +268,7 @@ public static function xmlToVariable(DOMElement $element) case 'string': $variable = $element->textContent; - \settype($variable, $element->tagName); + settype($variable, $element->tagName); break; } @@ -258,7 +279,7 @@ public static function xmlToVariable(DOMElement $element) private static function convertToUtf8(string $string): string { if (!self::isUtf8($string)) { - $string = \mb_convert_encoding($string, 'UTF-8'); + $string = mb_convert_encoding($string, 'UTF-8'); } return $string; @@ -266,23 +287,23 @@ private static function convertToUtf8(string $string): string private static function isUtf8(string $string): bool { - $length = \strlen($string); + $length = strlen($string); for ($i = 0; $i < $length; $i++) { - if (\ord($string[$i]) < 0x80) { + if (ord($string[$i]) < 0x80) { $n = 0; - } elseif ((\ord($string[$i]) & 0xE0) === 0xC0) { + } elseif ((ord($string[$i]) & 0xE0) === 0xC0) { $n = 1; - } elseif ((\ord($string[$i]) & 0xF0) === 0xE0) { + } elseif ((ord($string[$i]) & 0xF0) === 0xE0) { $n = 2; - } elseif ((\ord($string[$i]) & 0xF0) === 0xF0) { + } elseif ((ord($string[$i]) & 0xF0) === 0xF0) { $n = 3; } else { return false; } for ($j = 0; $j < $n; $j++) { - if ((++$i === $length) || ((\ord($string[$i]) & 0xC0) !== 0x80)) { + if ((++$i === $length) || ((ord($string[$i]) & 0xC0) !== 0x80)) { return false; } } diff --git a/src/Util/XmlTestListRenderer.php b/src/Util/XmlTestListRenderer.php index 20dd7b34ea8..d92e1fe2623 100644 --- a/src/Util/XmlTestListRenderer.php +++ b/src/Util/XmlTestListRenderer.php @@ -9,9 +9,14 @@ */ namespace PHPUnit\Util; +use function get_class; +use function implode; +use function str_replace; use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestSuite; use PHPUnit\Runner\PhptTestCase; +use RecursiveIteratorIterator; +use XMLWriter; /** * @internal This class is not covered by the backward compatibility promise for PHPUnit @@ -23,7 +28,7 @@ final class XmlTestListRenderer */ public function render(TestSuite $suite): string { - $writer = new \XMLWriter; + $writer = new XMLWriter; $writer->openMemory(); $writer->setIndent(true); @@ -32,27 +37,27 @@ public function render(TestSuite $suite): string $currentTestCase = null; - foreach (new \RecursiveIteratorIterator($suite->getIterator()) as $test) { + foreach (new RecursiveIteratorIterator($suite->getIterator()) as $test) { if ($test instanceof TestCase) { - if (\get_class($test) !== $currentTestCase) { + if (get_class($test) !== $currentTestCase) { if ($currentTestCase !== null) { $writer->endElement(); } $writer->startElement('testCaseClass'); - $writer->writeAttribute('name', \get_class($test)); + $writer->writeAttribute('name', get_class($test)); - $currentTestCase = \get_class($test); + $currentTestCase = get_class($test); } $writer->startElement('testCaseMethod'); $writer->writeAttribute('name', $test->getName(false)); - $writer->writeAttribute('groups', \implode(',', $test->getGroups())); + $writer->writeAttribute('groups', implode(',', $test->getGroups())); if (!empty($test->getDataSetAsString(false))) { $writer->writeAttribute( 'dataSet', - \str_replace( + str_replace( ' with data set ', '', $test->getDataSetAsString(false) diff --git a/tests/_files/DataProviderIssue2922/FirstTest.php b/tests/_files/DataProviderIssue2922/FirstTest.php index 6740e385975..e5bd84e5e42 100644 --- a/tests/_files/DataProviderIssue2922/FirstTest.php +++ b/tests/_files/DataProviderIssue2922/FirstTest.php @@ -9,6 +9,7 @@ */ namespace Foo\DataProviderIssue2922; +use Exception; use PHPUnit\Framework\TestCase; /** @@ -26,6 +27,6 @@ public function testFirst($x): void public function provide(): void { - throw new \Exception; + throw new Exception; } } diff --git a/tests/_files/DataproviderExecutionOrderTest_result_cache.txt b/tests/_files/DataproviderExecutionOrderTest_result_cache.txt index 452a1f85776..fab6a5a9fd1 100644 --- a/tests/_files/DataproviderExecutionOrderTest_result_cache.txt +++ b/tests/_files/DataproviderExecutionOrderTest_result_cache.txt @@ -1 +1 @@ -C:37:"PHPUnit\Runner\DefaultTestResultCache":2119:{a:2:{s:7:"defects";a:5:{s:60:"tests/end-to-end/regression/GitHub/3396/issue-3396-test.phpt";i:3;s:88:"MultiDependencyExecutionOrderTest::testAddNumbersWithADataprovider with data set "1+1=3"";i:3;s:92:"MultiDependencyExecutionOrderTest::testAddMoreNumbersWithADataprovider with data set "1+1=3"";i:3;s:85:"DataproviderExecutionOrderTest::testAddNumbersWithADataprovider with data set "1+1=3"";i:3;s:89:"DataproviderExecutionOrderTest::testAddMoreNumbersWithADataprovider with data set "1+1=3"";i:3;}s:5:"times";a:17:{s:60:"tests/end-to-end/regression/GitHub/3396/issue-3396-test.phpt";d:0.115;s:63:"MultiDependencyExecutionOrderTest::testFirstTestThatAlwaysWorks";d:0;s:88:"MultiDependencyExecutionOrderTest::testAddNumbersWithADataprovider with data set "1+2=3"";d:0;s:88:"MultiDependencyExecutionOrderTest::testAddNumbersWithADataprovider with data set "2+1=3"";d:0;s:88:"MultiDependencyExecutionOrderTest::testAddNumbersWithADataprovider with data set "1+1=3"";d:0.003;s:69:"MultiDependencyExecutionOrderTest::testTestInTheMiddleThatAlwaysWorks";d:0;s:92:"MultiDependencyExecutionOrderTest::testAddMoreNumbersWithADataprovider with data set "1+2=3"";d:0;s:92:"MultiDependencyExecutionOrderTest::testAddMoreNumbersWithADataprovider with data set "2+1=3"";d:0;s:92:"MultiDependencyExecutionOrderTest::testAddMoreNumbersWithADataprovider with data set "1+1=3"";d:0;s:60:"DataproviderExecutionOrderTest::testFirstTestThatAlwaysWorks";d:0.002;s:85:"DataproviderExecutionOrderTest::testAddNumbersWithADataprovider with data set "1+2=3"";d:0;s:85:"DataproviderExecutionOrderTest::testAddNumbersWithADataprovider with data set "2+1=3"";d:0;s:85:"DataproviderExecutionOrderTest::testAddNumbersWithADataprovider with data set "1+1=3"";d:0.001;s:66:"DataproviderExecutionOrderTest::testTestInTheMiddleThatAlwaysWorks";d:0;s:89:"DataproviderExecutionOrderTest::testAddMoreNumbersWithADataprovider with data set "1+2=3"";d:0;s:89:"DataproviderExecutionOrderTest::testAddMoreNumbersWithADataprovider with data set "2+1=3"";d:0;s:89:"DataproviderExecutionOrderTest::testAddMoreNumbersWithADataprovider with data set "1+1=3"";d:0;}}} +{"version":1,"defects":{"tests\/end-to-end\/regression\/GitHub\/3396\/issue-3396-test.phpt":3,"MultiDependencyExecutionOrderTest::testAddNumbersWithADataprovider with data set \"1+1=3\"":3,"MultiDependencyExecutionOrderTest::testAddMoreNumbersWithADataprovider with data set \"1+1=3\"":3,"DataproviderExecutionOrderTest::testAddNumbersWithADataprovider with data set \"1+1=3\"":3,"DataproviderExecutionOrderTest::testAddMoreNumbersWithADataprovider with data set \"1+1=3\"":3},"times":{"tests\/end-to-end\/regression\/GitHub\/3396\/issue-3396-test.phpt":0.115,"MultiDependencyExecutionOrderTest::testFirstTestThatAlwaysWorks":0,"MultiDependencyExecutionOrderTest::testAddNumbersWithADataprovider with data set \"1+2=3\"":0,"MultiDependencyExecutionOrderTest::testAddNumbersWithADataprovider with data set \"2+1=3\"":0,"MultiDependencyExecutionOrderTest::testAddNumbersWithADataprovider with data set \"1+1=3\"":0.003,"MultiDependencyExecutionOrderTest::testTestInTheMiddleThatAlwaysWorks":0,"MultiDependencyExecutionOrderTest::testAddMoreNumbersWithADataprovider with data set \"1+2=3\"":0,"MultiDependencyExecutionOrderTest::testAddMoreNumbersWithADataprovider with data set \"2+1=3\"":0,"MultiDependencyExecutionOrderTest::testAddMoreNumbersWithADataprovider with data set \"1+1=3\"":0,"DataproviderExecutionOrderTest::testFirstTestThatAlwaysWorks":0.002,"DataproviderExecutionOrderTest::testAddNumbersWithADataprovider with data set \"1+2=3\"":0,"DataproviderExecutionOrderTest::testAddNumbersWithADataprovider with data set \"2+1=3\"":0,"DataproviderExecutionOrderTest::testAddNumbersWithADataprovider with data set \"1+1=3\"":0.001,"DataproviderExecutionOrderTest::testTestInTheMiddleThatAlwaysWorks":0,"DataproviderExecutionOrderTest::testAddMoreNumbersWithADataprovider with data set \"1+2=3\"":0,"DataproviderExecutionOrderTest::testAddMoreNumbersWithADataprovider with data set \"2+1=3\"":0,"DataproviderExecutionOrderTest::testAddMoreNumbersWithADataprovider with data set \"1+1=3\"":0}} \ No newline at end of file diff --git a/tests/_files/ExceptionNamespaceTest.php b/tests/_files/ExceptionNamespaceTest.php index 5b03394fbc8..244fcd6d565 100644 --- a/tests/_files/ExceptionNamespaceTest.php +++ b/tests/_files/ExceptionNamespaceTest.php @@ -12,14 +12,14 @@ class ExceptionNamespaceTest extends \PHPUnit\Framework\TestCase { /** - * Exception message + * Exception message. * * @var string */ public const ERROR_MESSAGE = 'Exception namespace message'; /** - * Exception code + * Exception code. * * @var int */ diff --git a/tests/_files/ExceptionTest.php b/tests/_files/ExceptionTest.php index 2d9fbcfb98c..b9b923d267b 100644 --- a/tests/_files/ExceptionTest.php +++ b/tests/_files/ExceptionTest.php @@ -12,21 +12,21 @@ class ExceptionTest extends TestCase { /** - * Exception message + * Exception message. * * @var string */ public const ERROR_MESSAGE = 'Exception message'; /** - * Exception message + * Exception message. * * @var string */ public const ERROR_MESSAGE_REGEX = '#regex#'; /** - * Exception code + * Exception code. * * @var int */ diff --git a/tests/_files/FatalTest.php b/tests/_files/FatalTest.php index 8eefc04aa8b..2f85e50c2b6 100644 --- a/tests/_files/FatalTest.php +++ b/tests/_files/FatalTest.php @@ -13,7 +13,7 @@ class FatalTest extends TestCase { public function testFatalError(): void { - if (\extension_loaded('xdebug')) { + if (\extension_loaded('xdebug') && \version_compare(\phpversion('xdebug'), '3', '<')) { \xdebug_disable(); } diff --git a/tests/_files/SingletonClass.php b/tests/_files/SingletonClass.php index 9d897ce2eff..5526d512685 100644 --- a/tests/_files/SingletonClass.php +++ b/tests/_files/SingletonClass.php @@ -17,11 +17,12 @@ protected function __construct() { } - private function __sleep(): array + public function __sleep(): array { + return []; } - private function __wakeup(): void + public function __wakeup(): void { } diff --git a/tests/_files/configuration_execution_order_options.xml b/tests/_files/configuration_execution_order_options.xml index 98e4bbe29e0..da1f091b0c6 100644 --- a/tests/_files/configuration_execution_order_options.xml +++ b/tests/_files/configuration_execution_order_options.xml @@ -1,8 +1,4 @@ - - - - diff --git a/tests/basic/unit/SetUpBeforeClassTest.php b/tests/basic/unit/SetUpBeforeClassTest.php index 5205322089d..f9355a1d61f 100644 --- a/tests/basic/unit/SetUpBeforeClassTest.php +++ b/tests/basic/unit/SetUpBeforeClassTest.php @@ -9,10 +9,11 @@ */ namespace PHPUnit\SelfTest\Basic; +use Exception; use PHPUnit\Framework\TestCase; /** - * Class SetUpBeforeClassTest + * Class SetUpBeforeClassTest. * * Behaviour to test: * - setUpBeforeClass() errors do reach the user @@ -28,12 +29,12 @@ class SetUpBeforeClassTest extends TestCase { public static function setUpBeforeClass(): void { - throw new \Exception('forcing an Exception in setUpBeforeClass()'); + throw new Exception('forcing an Exception in setUpBeforeClass()'); } - public function setUp(): void + protected function setUp(): void { - throw new \Exception('setUp() should never have been run'); + throw new Exception('setUp() should never have been run'); } public function testOne(): void diff --git a/tests/basic/unit/SetUpTest.php b/tests/basic/unit/SetUpTest.php index 65b565eb403..c0b4daa1fe9 100644 --- a/tests/basic/unit/SetUpTest.php +++ b/tests/basic/unit/SetUpTest.php @@ -10,9 +10,10 @@ namespace PHPUnit\SelfTest\Basic; use PHPUnit\Framework\TestCase; +use RuntimeException; /** - * Class SetUpBeforeClassTest + * Class SetUpBeforeClassTest. * * Behaviour to test: * - setUp() errors reacht he the user @@ -24,9 +25,9 @@ */ class SetUpTest extends TestCase { - public function setUp(): void + protected function setUp(): void { - throw new \RuntimeException('throw exception in setUp'); + throw new RuntimeException('throw exception in setUp'); } public function testOneWithSetUpException(): void diff --git a/tests/basic/unit/StatusTest.php b/tests/basic/unit/StatusTest.php index 1c9f575b69d..cadfd4e68b0 100644 --- a/tests/basic/unit/StatusTest.php +++ b/tests/basic/unit/StatusTest.php @@ -9,8 +9,10 @@ */ namespace PHPUnit\SelfTest\Basic; +use AnInterface; use PHPUnit\Framework\TestCase; use PHPUnit\Framework\Warning; +use RuntimeException; /** * @covers Foo @@ -23,7 +25,7 @@ class StatusTest extends TestCase { public function testSuccess(): void { - $this->createMock(\AnInterface::class); + $this->createMock(AnInterface::class); $this->assertTrue(true); } @@ -35,7 +37,7 @@ public function testFailure(): void public function testError(): void { - throw new \RuntimeException; + throw new RuntimeException; } public function testIncomplete(): void @@ -69,7 +71,7 @@ public function testFailureWithMessage(): void public function testErrorWithMessage(): void { - throw new \RuntimeException('error with custom message'); + throw new RuntimeException('error with custom message'); } public function testIncompleteWithMessage(): void diff --git a/tests/basic/unit/TearDownAfterClassTest.php b/tests/basic/unit/TearDownAfterClassTest.php index 12ee296e345..2866a85eb93 100644 --- a/tests/basic/unit/TearDownAfterClassTest.php +++ b/tests/basic/unit/TearDownAfterClassTest.php @@ -9,10 +9,11 @@ */ namespace PHPUnit\SelfTest\Basic; +use Exception; use PHPUnit\Framework\TestCase; /** - * Class TearDownAfterClassTest + * Class TearDownAfterClassTest. * * Behaviour to test: * - tearDownAfterClass() errors do reach the user @@ -23,7 +24,7 @@ class TearDownAfterClassTest extends TestCase { public static function tearDownAfterClass(): void { - throw new \Exception('forcing an Exception in tearDownAfterClass()'); + throw new Exception('forcing an Exception in tearDownAfterClass()'); } public function testOne(): void diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 32786972bd3..e49f348c171 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -7,11 +7,15 @@ * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -if (!\defined('TEST_FILES_PATH')) { - \define('TEST_FILES_PATH', __DIR__ . \DIRECTORY_SEPARATOR . '_files' . \DIRECTORY_SEPARATOR); +if (!defined('PHPUNIT_COMPOSER_INSTALL')) { + define('PHPUNIT_COMPOSER_INSTALL', dirname(__DIR__) . '/vendor/autoload.php'); } -\ini_set('precision', '14'); -\ini_set('serialize_precision', '14'); +if (!defined('TEST_FILES_PATH')) { + define('TEST_FILES_PATH', __DIR__ . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR); +} + +ini_set('precision', '14'); +ini_set('serialize_precision', '14'); -require_once __DIR__ . '/../vendor/autoload.php'; +require_once PHPUNIT_COMPOSER_INSTALL; diff --git a/tests/end-to-end/_files/Extension.php b/tests/end-to-end/_files/Extension.php index e3ae29db24f..ab1355977b9 100644 --- a/tests/end-to-end/_files/Extension.php +++ b/tests/end-to-end/_files/Extension.php @@ -9,6 +9,9 @@ */ namespace PHPUnit\Test; +use const PHP_EOL; +use function count; +use function func_get_args; use PHPUnit\Runner\AfterIncompleteTestHook; use PHPUnit\Runner\AfterLastTestHook; use PHPUnit\Runner\AfterRiskyTestHook; @@ -27,67 +30,67 @@ final class Extension implements AfterIncompleteTestHook, AfterLastTestHook, Aft public function __construct() { - $this->amountOfInjectedArguments = \count(\func_get_args()); + $this->amountOfInjectedArguments = count(func_get_args()); } public function tellAmountOfInjectedArguments(): void { - print __METHOD__ . ': ' . $this->amountOfInjectedArguments . \PHP_EOL; + print __METHOD__ . ': ' . $this->amountOfInjectedArguments . PHP_EOL; } public function executeBeforeFirstTest(): void { $this->tellAmountOfInjectedArguments(); - print __METHOD__ . \PHP_EOL; + print __METHOD__ . PHP_EOL; } public function executeBeforeTest(string $test): void { - print __METHOD__ . ': ' . $test . \PHP_EOL; + print __METHOD__ . ': ' . $test . PHP_EOL; } public function executeAfterTest(string $test, float $time): void { - print __METHOD__ . ': ' . $test . \PHP_EOL; + print __METHOD__ . ': ' . $test . PHP_EOL; } public function executeAfterSuccessfulTest(string $test, float $time): void { - print __METHOD__ . ': ' . $test . \PHP_EOL; + print __METHOD__ . ': ' . $test . PHP_EOL; } public function executeAfterIncompleteTest(string $test, string $message, float $time): void { - print __METHOD__ . ': ' . $test . ': ' . $message . \PHP_EOL; + print __METHOD__ . ': ' . $test . ': ' . $message . PHP_EOL; } public function executeAfterRiskyTest(string $test, string $message, float $time): void { - print __METHOD__ . ': ' . $test . ': ' . $message . \PHP_EOL; + print __METHOD__ . ': ' . $test . ': ' . $message . PHP_EOL; } public function executeAfterSkippedTest(string $test, string $message, float $time): void { - print __METHOD__ . ': ' . $test . ': ' . $message . \PHP_EOL; + print __METHOD__ . ': ' . $test . ': ' . $message . PHP_EOL; } public function executeAfterTestError(string $test, string $message, float $time): void { - print __METHOD__ . ': ' . $test . ': ' . $message . \PHP_EOL; + print __METHOD__ . ': ' . $test . ': ' . $message . PHP_EOL; } public function executeAfterTestFailure(string $test, string $message, float $time): void { - print __METHOD__ . ': ' . $test . ': ' . $message . \PHP_EOL; + print __METHOD__ . ': ' . $test . ': ' . $message . PHP_EOL; } public function executeAfterTestWarning(string $test, string $message, float $time): void { - print __METHOD__ . ': ' . $test . ': ' . $message . \PHP_EOL; + print __METHOD__ . ': ' . $test . ': ' . $message . PHP_EOL; } public function executeAfterLastTest(): void { - print __METHOD__ . \PHP_EOL; + print __METHOD__ . PHP_EOL; } } diff --git a/tests/end-to-end/abstract-test-class.phpt b/tests/end-to-end/abstract-test-class.phpt index 84884795ea4..36a1e6afdea 100644 --- a/tests/end-to-end/abstract-test-class.phpt +++ b/tests/end-to-end/abstract-test-class.phpt @@ -2,9 +2,10 @@ phpunit ../../_files/AbstractTest.php --FILE-- isFinal()) { + print 'skip: PHP < 8.1 required'; +} +--FILE-- +generate( + 'Baz', + [], + 'MockBaz', + true, + true +); + +print $mock->getClassCode(); +--EXPECT-- +declare(strict_types=1); + +class MockBaz extends Exception implements Baz, PHPUnit\Framework\MockObject\MockObject +{ + use \PHPUnit\Framework\MockObject\Api; + use \PHPUnit\Framework\MockObject\Method; + + public function foo(): string + { + $__phpunit_arguments = []; + $__phpunit_count = func_num_args(); + + if ($__phpunit_count > 0) { + $__phpunit_arguments_tmp = func_get_args(); + + for ($__phpunit_i = 0; $__phpunit_i < $__phpunit_count; $__phpunit_i++) { + $__phpunit_arguments[] = $__phpunit_arguments_tmp[$__phpunit_i]; + } + } + + $__phpunit_result = $this->__phpunit_getInvocationHandler()->invoke( + new \PHPUnit\Framework\MockObject\Invocation( + 'Bar', 'foo', $__phpunit_arguments, ': string', $this, true + ) + ); + + return $__phpunit_result; + } +} diff --git a/tests/end-to-end/mock-objects/generator/3967.phpt b/tests/end-to-end/mock-objects/generator/3967.phpt index 982c6e92ee3..6072e222f48 100644 --- a/tests/end-to-end/mock-objects/generator/3967.phpt +++ b/tests/end-to-end/mock-objects/generator/3967.phpt @@ -1,5 +1,10 @@ --TEST-- https://github.com/sebastianbergmann/phpunit/issues/3967 +--SKIPIF-- +isFinal()) { + print 'skip: PHP >= 8.1 required'; +} --FILE-- assertEquals($GLOBALS[static::PID_VARIABLE], \getmypid()); + $this->assertEquals($GLOBALS[static::PID_VARIABLE], getmypid()); } public function testMethod2WithItsBeforeAndAfter(): void { - $this->assertEquals($GLOBALS[static::PID_VARIABLE], \getmypid()); + $this->assertEquals($GLOBALS[static::PID_VARIABLE], getmypid()); } } diff --git a/tests/end-to-end/regression/GitHub/2731.phpt b/tests/end-to-end/regression/GitHub/2731.phpt index b4cc5983a04..f9aada816f3 100644 --- a/tests/end-to-end/regression/GitHub/2731.phpt +++ b/tests/end-to-end/regression/GitHub/2731.phpt @@ -2,8 +2,9 @@ GH-2731: Empty exception message cannot be expected --FILE-- assertTrue(true); } /** @@ -25,6 +25,6 @@ public function testFirstWithoutDependencies(): void */ public function testSecondThatDependsOnFirstAndDataprovider($value): void { - self::assertTrue(true); + $this->assertTrue(true); } } diff --git a/tests/end-to-end/regression/GitHub/3093/issue-3093-test.phpt b/tests/end-to-end/regression/GitHub/3093/issue-3093-test.phpt index 6a6b912b720..0878e66c2f2 100644 --- a/tests/end-to-end/regression/GitHub/3093/issue-3093-test.phpt +++ b/tests/end-to-end/regression/GitHub/3093/issue-3093-test.phpt @@ -2,9 +2,10 @@ https://github.com/sebastianbergmann/phpunit/issues/3093 --FILE-- + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +use PHPUnit\Framework\TestCase; + +final class Issue4663Test extends TestCase +{ + public function testTestThatExpectsAnErrorPassesWhenTheErrorOccurs(): void + { + $this->expectError(); + + implode('', [new stdClass]); + } +} diff --git a/tests/end-to-end/regression/GitHub/498.phpt b/tests/end-to-end/regression/GitHub/498.phpt index 71ac2f6f5d9..576c334f3fc 100644 --- a/tests/end-to-end/regression/GitHub/498.phpt +++ b/tests/end-to-end/regression/GitHub/498.phpt @@ -2,10 +2,11 @@ GH-498: The test methods won't be run if a dataProvider throws Exception and --group is added in command line --FILE-- = 8) { } --FILE-- + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace PHPUnit\StaticAnalysis; + +use PHPUnit\Framework\TestCase; + +/** @see https://www.youtube.com/watch?v=rXwMrBb2x1Q */ +interface SayHello +{ + public function hey(string $toPerson): string; +} + +/** @small */ +final class TestUsingCallbacks extends TestCase +{ + public function testWillSayHelloAndCheckCallbackInput(): void + { + $mock = $this->createMock(SayHello::class); + + $mock + ->expects(self::once()) + ->method('hey') + ->with(self::callback(static function (string $input): bool { + self::assertStringContainsString('Joe', $input); + + return true; + })) + ->willReturn('Hey Joe!'); + + self::assertSame('Hey Joe!', $mock->hey('Joe')); + } + + public function testWillSayHelloAndCheckCallbackWithoutAnyInput(): void + { + $mock = $this->createMock(SayHello::class); + + $mock + ->expects(self::once()) + ->method('hey') + ->with(self::callback(static function (): bool { + return true; + })) + ->willReturn('Hey Joe!'); + + self::assertSame('Hey Joe!', $mock->hey('Joe')); + } +} diff --git a/tests/unit/Framework/Assert/FunctionsTest.php b/tests/unit/Framework/Assert/FunctionsTest.php index 4c2b7ce2d1d..12d03e75a8a 100644 --- a/tests/unit/Framework/Assert/FunctionsTest.php +++ b/tests/unit/Framework/Assert/FunctionsTest.php @@ -9,15 +9,19 @@ */ namespace PHPUnit\Framework; +use function array_reduce; +use function file_get_contents; +use function preg_match_all; + final class FunctionsTest extends TestCase { private static $globalAssertionFunctions = []; public static function setUpBeforeClass(): void { - \preg_match_all( + preg_match_all( '/function (assert[^ \(]+)/', - \file_get_contents( + file_get_contents( __DIR__ . '/../../../../src/Framework/Assert/Functions.php' ), $matches @@ -40,17 +44,17 @@ public function testGlobalFunctionsFileContainsAllStaticAssertions(string $metho public function provideStaticAssertionMethodNames(): array { - \preg_match_all( + preg_match_all( '/public static function (assert[^ \(]+)/', - \file_get_contents( + file_get_contents( __DIR__ . '/../../../../src/Framework/Assert.php' ), $matches ); - return \array_reduce( + return array_reduce( $matches[1], - function (array $functionNames, string $functionName) { + static function (array $functionNames, string $functionName) { $functionNames[$functionName] = [$functionName]; return $functionNames; diff --git a/tests/unit/Framework/AssertTest.php b/tests/unit/Framework/AssertTest.php index 2948eb1fe02..1e9fc1af9cb 100644 --- a/tests/unit/Framework/AssertTest.php +++ b/tests/unit/Framework/AssertTest.php @@ -9,7 +9,36 @@ */ namespace PHPUnit\Framework; +use const DIRECTORY_SEPARATOR; +use const INF; +use const NAN; +use const PHP_OS_FAMILY; +use function acos; +use function array_merge; +use function chmod; +use function file_get_contents; +use function fopen; +use function json_encode; +use function log; +use function octdec; +use function sys_get_temp_dir; +use function tempnam; +use function unlink; +use ArrayIterator; +use ArrayObject; +use Author; +use Book; +use ClassWithNonPublicAttributes; +use ClassWithToString; +use DateTime; +use DateTimeZone; +use DOMDocument; use PHPUnit\Util\Xml; +use SampleArrayAccess; +use SampleClass; +use SplObjectStorage; +use stdClass; +use Struct; /** * @small @@ -37,16 +66,16 @@ public function testFail(): void public function testAssertContainsOnlyInstancesOf(): void { - $test = [new \Book, new \Book]; + $test = [new Book, new Book]; - $this->assertContainsOnlyInstancesOf(\Book::class, $test); - $this->assertContainsOnlyInstancesOf(\stdClass::class, [new \stdClass]); + $this->assertContainsOnlyInstancesOf(Book::class, $test); + $this->assertContainsOnlyInstancesOf(stdClass::class, [new stdClass]); - $test2 = [new \Author('Test')]; + $test2 = [new Author('Test')]; $this->expectException(AssertionFailedError::class); - $this->assertContainsOnlyInstancesOf(\Book::class, $test2); + $this->assertContainsOnlyInstancesOf(Book::class, $test2); } public function testAssertArrayHasKeyThrowsExceptionForInvalidFirstArgument(): void @@ -115,7 +144,7 @@ public function testAssertArrayNotHasStringKey(): void public function testAssertArrayHasKeyAcceptsArrayObjectValue(): void { - $array = new \ArrayObject; + $array = new ArrayObject; $array['foo'] = 'bar'; $this->assertArrayHasKey('foo', $array); @@ -123,7 +152,7 @@ public function testAssertArrayHasKeyAcceptsArrayObjectValue(): void public function testAssertArrayHasKeyProperlyFailsWithArrayObjectValue(): void { - $array = new \ArrayObject; + $array = new ArrayObject; $array['bar'] = 'bar'; $this->expectException(AssertionFailedError::class); @@ -133,7 +162,7 @@ public function testAssertArrayHasKeyProperlyFailsWithArrayObjectValue(): void public function testAssertArrayHasKeyAcceptsArrayAccessValue(): void { - $array = new \SampleArrayAccess; + $array = new SampleArrayAccess; $array['foo'] = 'bar'; $this->assertArrayHasKey('foo', $array); @@ -141,7 +170,7 @@ public function testAssertArrayHasKeyAcceptsArrayAccessValue(): void public function testAssertArrayHasKeyProperlyFailsWithArrayAccessValue(): void { - $array = new \SampleArrayAccess; + $array = new SampleArrayAccess; $array['bar'] = 'bar'; $this->expectException(AssertionFailedError::class); @@ -151,7 +180,7 @@ public function testAssertArrayHasKeyProperlyFailsWithArrayAccessValue(): void public function testAssertArrayNotHasKeyAcceptsArrayAccessValue(): void { - $array = new \ArrayObject; + $array = new ArrayObject; $array['foo'] = 'bar'; $this->assertArrayNotHasKey('bar', $array); @@ -159,7 +188,7 @@ public function testAssertArrayNotHasKeyAcceptsArrayAccessValue(): void public function testAssertArrayNotHasKeyPropertlyFailsWithArrayAccessValue(): void { - $array = new \ArrayObject; + $array = new ArrayObject; $array['bar'] = 'bar'; $this->expectException(AssertionFailedError::class); @@ -187,7 +216,7 @@ public function testAssertArrayNotContainsOnlyIntegers(): void public function testAssertArrayContainsOnlyStdClass(): void { - $this->assertContainsOnly('StdClass', [new \stdClass]); + $this->assertContainsOnly('StdClass', [new stdClass]); $this->expectException(AssertionFailedError::class); @@ -200,13 +229,13 @@ public function testAssertArrayNotContainsOnlyStdClass(): void $this->expectException(AssertionFailedError::class); - $this->assertNotContainsOnly('StdClass', [new \stdClass]); + $this->assertNotContainsOnly('StdClass', [new stdClass]); } public function equalProvider(): array { // same |= equal - return \array_merge($this->equalValues(), $this->sameValues()); + return array_merge($this->equalValues(), $this->sameValues()); } public function notEqualProvider() @@ -223,14 +252,14 @@ public function notSameProvider(): array { // not equal |= not same // equal, ¬same |= not same - return \array_merge($this->notEqualValues(), $this->equalValues()); + return array_merge($this->notEqualValues(), $this->equalValues()); } /** * @dataProvider equalProvider * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public function testAssertEqualsSucceeds($a, $b): void { @@ -240,8 +269,8 @@ public function testAssertEqualsSucceeds($a, $b): void /** * @dataProvider notEqualProvider * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public function testAssertEqualsFails($a, $b): void { @@ -253,8 +282,8 @@ public function testAssertEqualsFails($a, $b): void /** * @dataProvider notEqualProvider * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public function testAssertNotEqualsSucceeds($a, $b): void { @@ -265,8 +294,8 @@ public function testAssertNotEqualsSucceeds($a, $b): void * @testdox assertNotEquals($a, $b) with delta $delta, canoicalize $canonicalize, ignoreCase $ignoreCase * @dataProvider equalProvider * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public function testAssertNotEqualsFails($a, $b): void { @@ -279,8 +308,8 @@ public function testAssertNotEqualsFails($a, $b): void * @testdox assertNotSame($a, $b) fails * @dataProvider sameProvider * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public function testAssertSameSucceeds($a, $b): void { @@ -291,8 +320,8 @@ public function testAssertSameSucceeds($a, $b): void * @testdox assertNotSame($a, $b) * @dataProvider notSameProvider * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public function testAssertSameFails($a, $b): void { @@ -305,8 +334,8 @@ public function testAssertSameFails($a, $b): void * @testdox assertSame($a, $b) fails * @dataProvider notSameProvider * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public function testAssertNotSameSucceeds($a, $b): void { @@ -317,8 +346,8 @@ public function testAssertNotSameSucceeds($a, $b): void * @testdox assertSame($a, $b) * @dataProvider sameProvider * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public function testAssertNotSameFails($a, $b): void { @@ -361,14 +390,14 @@ public function testAssertXmlStringEqualsXmlFile(): void { $this->assertXmlStringEqualsXmlFile( TEST_FILES_PATH . 'foo.xml', - \file_get_contents(TEST_FILES_PATH . 'foo.xml') + file_get_contents(TEST_FILES_PATH . 'foo.xml') ); $this->expectException(AssertionFailedError::class); $this->assertXmlStringEqualsXmlFile( TEST_FILES_PATH . 'foo.xml', - \file_get_contents(TEST_FILES_PATH . 'bar.xml') + file_get_contents(TEST_FILES_PATH . 'bar.xml') ); } @@ -376,14 +405,14 @@ public function testXmlStringNotEqualsXmlFile(): void { $this->assertXmlStringNotEqualsXmlFile( TEST_FILES_PATH . 'foo.xml', - \file_get_contents(TEST_FILES_PATH . 'bar.xml') + file_get_contents(TEST_FILES_PATH . 'bar.xml') ); $this->expectException(AssertionFailedError::class); $this->assertXmlStringNotEqualsXmlFile( TEST_FILES_PATH . 'foo.xml', - \file_get_contents(TEST_FILES_PATH . 'foo.xml') + file_get_contents(TEST_FILES_PATH . 'foo.xml') ); } @@ -439,10 +468,10 @@ public function testAssertXmlStringNotEqualsXmlString(): void public function testXMLStructureIsSame(): void { - $expected = new \DOMDocument; + $expected = new DOMDocument; $expected->load(TEST_FILES_PATH . 'structureExpected.xml'); - $actual = new \DOMDocument; + $actual = new DOMDocument; $actual->load(TEST_FILES_PATH . 'structureExpected.xml'); $this->assertEqualXMLStructure( @@ -454,10 +483,10 @@ public function testXMLStructureIsSame(): void public function testXMLStructureWrongNumberOfAttributes(): void { - $expected = new \DOMDocument; + $expected = new DOMDocument; $expected->load(TEST_FILES_PATH . 'structureExpected.xml'); - $actual = new \DOMDocument; + $actual = new DOMDocument; $actual->load(TEST_FILES_PATH . 'structureWrongNumberOfAttributes.xml'); $this->expectException(ExpectationFailedException::class); @@ -471,10 +500,10 @@ public function testXMLStructureWrongNumberOfAttributes(): void public function testXMLStructureWrongNumberOfNodes(): void { - $expected = new \DOMDocument; + $expected = new DOMDocument; $expected->load(TEST_FILES_PATH . 'structureExpected.xml'); - $actual = new \DOMDocument; + $actual = new DOMDocument; $actual->load(TEST_FILES_PATH . 'structureWrongNumberOfNodes.xml'); $this->expectException(ExpectationFailedException::class); @@ -488,10 +517,10 @@ public function testXMLStructureWrongNumberOfNodes(): void public function testXMLStructureIsSameButDataIsNot(): void { - $expected = new \DOMDocument; + $expected = new DOMDocument; $expected->load(TEST_FILES_PATH . 'structureExpected.xml'); - $actual = new \DOMDocument; + $actual = new DOMDocument; $actual->load(TEST_FILES_PATH . 'structureIsSameButDataIsNot.xml'); $this->assertEqualXMLStructure( @@ -503,10 +532,10 @@ public function testXMLStructureIsSameButDataIsNot(): void public function testXMLStructureAttributesAreSameButValuesAreNot(): void { - $expected = new \DOMDocument; + $expected = new DOMDocument; $expected->load(TEST_FILES_PATH . 'structureExpected.xml'); - $actual = new \DOMDocument; + $actual = new DOMDocument; $actual->load(TEST_FILES_PATH . 'structureAttributesAreSameButValuesAreNot.xml'); $this->assertEqualXMLStructure( @@ -518,10 +547,10 @@ public function testXMLStructureAttributesAreSameButValuesAreNot(): void public function testXMLStructureIgnoreTextNodes(): void { - $expected = new \DOMDocument; + $expected = new DOMDocument; $expected->load(TEST_FILES_PATH . 'structureExpected.xml'); - $actual = new \DOMDocument; + $actual = new DOMDocument; $actual->load(TEST_FILES_PATH . 'structureIgnoreTextNodes.xml'); $this->assertEqualXMLStructure( @@ -551,12 +580,12 @@ public function testAssertIsReadable(): void $this->expectException(AssertionFailedError::class); - $this->assertIsReadable(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); + $this->assertIsReadable(__DIR__ . DIRECTORY_SEPARATOR . 'NotExisting'); } public function testAssertNotIsReadable(): void { - $this->assertNotIsReadable(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); + $this->assertNotIsReadable(__DIR__ . DIRECTORY_SEPARATOR . 'NotExisting'); $this->expectException(AssertionFailedError::class); @@ -569,12 +598,12 @@ public function testAssertIsWritable(): void $this->expectException(AssertionFailedError::class); - $this->assertIsWritable(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); + $this->assertIsWritable(__DIR__ . DIRECTORY_SEPARATOR . 'NotExisting'); } public function testAssertNotIsWritable(): void { - $this->assertNotIsWritable(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); + $this->assertNotIsWritable(__DIR__ . DIRECTORY_SEPARATOR . 'NotExisting'); $this->expectException(AssertionFailedError::class); @@ -587,12 +616,12 @@ public function testAssertDirectoryExists(): void $this->expectException(AssertionFailedError::class); - $this->assertDirectoryExists(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); + $this->assertDirectoryExists(__DIR__ . DIRECTORY_SEPARATOR . 'NotExisting'); } public function testAssertDirectoryNotExists(): void { - $this->assertDirectoryNotExists(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); + $this->assertDirectoryNotExists(__DIR__ . DIRECTORY_SEPARATOR . 'NotExisting'); $this->expectException(AssertionFailedError::class); @@ -605,7 +634,7 @@ public function testAssertDirectoryIsReadable(): void $this->expectException(AssertionFailedError::class); - $this->assertDirectoryIsReadable(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); + $this->assertDirectoryIsReadable(__DIR__ . DIRECTORY_SEPARATOR . 'NotExisting'); } public function testAssertDirectoryIsWritable(): void @@ -614,7 +643,7 @@ public function testAssertDirectoryIsWritable(): void $this->expectException(AssertionFailedError::class); - $this->assertDirectoryIsWritable(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); + $this->assertDirectoryIsWritable(__DIR__ . DIRECTORY_SEPARATOR . 'NotExisting'); } public function testAssertFileExists(): void @@ -623,12 +652,12 @@ public function testAssertFileExists(): void $this->expectException(AssertionFailedError::class); - $this->assertFileExists(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); + $this->assertFileExists(__DIR__ . DIRECTORY_SEPARATOR . 'NotExisting'); } public function testAssertFileNotExists(): void { - $this->assertFileNotExists(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); + $this->assertFileNotExists(__DIR__ . DIRECTORY_SEPARATOR . 'NotExisting'); $this->expectException(AssertionFailedError::class); @@ -641,32 +670,32 @@ public function testAssertFileIsReadable(): void $this->expectException(AssertionFailedError::class); - $this->assertFileIsReadable(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); + $this->assertFileIsReadable(__DIR__ . DIRECTORY_SEPARATOR . 'NotExisting'); } public function testAssertFileIsNotReadable(): void { - if (\PHP_OS_FAMILY === 'Windows') { - self::markTestSkipped('Cannot test this behaviour on Windows'); + if (PHP_OS_FAMILY === 'Windows') { + $this->markTestSkipped('Cannot test this behaviour on Windows'); } - $tempFile = \tempnam( - \sys_get_temp_dir(), + $tempFile = tempnam( + sys_get_temp_dir(), 'unreadable' ); - \chmod($tempFile, \octdec('0')); + chmod($tempFile, octdec('0')); $this->assertFileNotIsReadable($tempFile); - \chmod($tempFile, \octdec('755')); + chmod($tempFile, octdec('755')); try { $this->assertFileNotIsReadable($tempFile); } catch (AssertionFailedError $e) { } - \unlink($tempFile); + unlink($tempFile); } public function testAssertFileIsWritable(): void @@ -675,12 +704,12 @@ public function testAssertFileIsWritable(): void $this->expectException(AssertionFailedError::class); - $this->assertFileIsWritable(__DIR__ . \DIRECTORY_SEPARATOR . 'NotExisting'); + $this->assertFileIsWritable(__DIR__ . DIRECTORY_SEPARATOR . 'NotExisting'); } public function testAssertObjectHasAttribute(): void { - $o = new \Author('Terry Pratchett'); + $o = new Author('Terry Pratchett'); $this->assertObjectHasAttribute('name', $o); @@ -691,7 +720,7 @@ public function testAssertObjectHasAttribute(): void public function testAssertObjectHasAttributeNumericAttribute(): void { - $object = new \stdClass; + $object = new stdClass; $object->{'2020'} = 'Tokyo'; $this->assertObjectHasAttribute('2020', $object); @@ -703,7 +732,7 @@ public function testAssertObjectHasAttributeNumericAttribute(): void public function testAssertObjectHasAttributeMultiByteAttribute(): void { - $object = new \stdClass; + $object = new stdClass; $object->{'東京'} = 2020; $this->assertObjectHasAttribute('東京', $object); @@ -715,7 +744,7 @@ public function testAssertObjectHasAttributeMultiByteAttribute(): void public function testAssertObjectNotHasAttribute(): void { - $o = new \Author('Terry Pratchett'); + $o = new Author('Terry Pratchett'); $this->assertObjectNotHasAttribute('foo', $o); @@ -726,7 +755,7 @@ public function testAssertObjectNotHasAttribute(): void public function testAssertObjectNotHasAttributeNumericAttribute(): void { - $object = new \stdClass; + $object = new stdClass; $object->{'2020'} = 'Tokyo'; $this->assertObjectNotHasAttribute('2018', $object); @@ -738,7 +767,7 @@ public function testAssertObjectNotHasAttributeNumericAttribute(): void public function testAssertObjectNotHasAttributeMultiByteAttribute(): void { - $object = new \stdClass; + $object = new stdClass; $object->{'東京'} = 2020; $this->assertObjectNotHasAttribute('長野', $object); @@ -754,12 +783,12 @@ public function testAssertFinite(): void $this->expectException(AssertionFailedError::class); - $this->assertFinite(\INF); + $this->assertFinite(INF); } public function testAssertInfinite(): void { - $this->assertInfinite(\INF); + $this->assertInfinite(INF); $this->expectException(AssertionFailedError::class); @@ -768,7 +797,7 @@ public function testAssertInfinite(): void public function testAssertNan(): void { - $this->assertNan(\NAN); + $this->assertNan(NAN); $this->expectException(AssertionFailedError::class); @@ -781,12 +810,12 @@ public function testAssertNull(): void $this->expectException(AssertionFailedError::class); - $this->assertNull(new \stdClass); + $this->assertNull(new stdClass); } public function testAssertNotNull(): void { - $this->assertNotNull(new \stdClass); + $this->assertNotNull(new stdClass); $this->expectException(AssertionFailedError::class); @@ -853,13 +882,13 @@ public function testAssertNotRegExp(): void public function testAssertSame(): void { - $o = new \stdClass; + $o = new stdClass; $this->assertSame($o, $o); $this->expectException(AssertionFailedError::class); - $this->assertSame(new \stdClass, new \stdClass); + $this->assertSame(new stdClass, new stdClass); } public function testAssertSame2(): void @@ -875,21 +904,21 @@ public function testAssertSame2(): void public function testAssertNotSame(): void { $this->assertNotSame( - new \stdClass, + new stdClass, null ); $this->assertNotSame( null, - new \stdClass + new stdClass ); $this->assertNotSame( - new \stdClass, - new \stdClass + new stdClass, + new stdClass ); - $o = new \stdClass; + $o = new stdClass; $this->expectException(AssertionFailedError::class); @@ -957,7 +986,7 @@ public function testAssertClassHasAttributeThrowsExceptionIfAttributeNameIsNotVa { $this->expectException(Exception::class); - $this->assertClassHasAttribute('1', \ClassWithNonPublicAttributes::class); + $this->assertClassHasAttribute('1', ClassWithNonPublicAttributes::class); } public function testAssertClassHasAttributeThrowsExceptionIfClassDoesNotExist(): void @@ -971,7 +1000,7 @@ public function testAssertClassNotHasAttributeThrowsExceptionIfAttributeNameIsNo { $this->expectException(Exception::class); - $this->assertClassNotHasAttribute('1', \ClassWithNonPublicAttributes::class); + $this->assertClassNotHasAttribute('1', ClassWithNonPublicAttributes::class); } public function testAssertClassNotHasAttributeThrowsExceptionIfClassDoesNotExist(): void @@ -985,7 +1014,7 @@ public function testAssertClassHasStaticAttributeThrowsExceptionIfAttributeNameI { $this->expectException(Exception::class); - $this->assertClassHasStaticAttribute('1', \ClassWithNonPublicAttributes::class); + $this->assertClassHasStaticAttribute('1', ClassWithNonPublicAttributes::class); } public function testAssertClassHasStaticAttributeThrowsExceptionIfClassDoesNotExist(): void @@ -999,7 +1028,7 @@ public function testAssertClassNotHasStaticAttributeThrowsExceptionIfAttributeNa { $this->expectException(Exception::class); - $this->assertClassNotHasStaticAttribute('1', \ClassWithNonPublicAttributes::class); + $this->assertClassNotHasStaticAttribute('1', ClassWithNonPublicAttributes::class); } public function testAssertClassNotHasStaticAttributeThrowsExceptionIfClassDoesNotExist(): void @@ -1020,7 +1049,7 @@ public function testAssertObjectHasAttributeThrowsExceptionIfAttributeNameIsNotV { $this->expectException(Exception::class); - $this->assertObjectHasAttribute('1', \ClassWithNonPublicAttributes::class); + $this->assertObjectHasAttribute('1', ClassWithNonPublicAttributes::class); } public function testAssertObjectNotHasAttributeThrowsException2(): void @@ -1034,48 +1063,48 @@ public function testAssertObjectNotHasAttributeThrowsExceptionIfAttributeNameIsN { $this->expectException(Exception::class); - $this->assertObjectNotHasAttribute('1', \ClassWithNonPublicAttributes::class); + $this->assertObjectNotHasAttribute('1', ClassWithNonPublicAttributes::class); } public function testClassHasPublicAttribute(): void { - $this->assertClassHasAttribute('publicAttribute', \ClassWithNonPublicAttributes::class); + $this->assertClassHasAttribute('publicAttribute', ClassWithNonPublicAttributes::class); $this->expectException(AssertionFailedError::class); - $this->assertClassHasAttribute('attribute', \ClassWithNonPublicAttributes::class); + $this->assertClassHasAttribute('attribute', ClassWithNonPublicAttributes::class); } public function testClassNotHasPublicAttribute(): void { - $this->assertClassNotHasAttribute('attribute', \ClassWithNonPublicAttributes::class); + $this->assertClassNotHasAttribute('attribute', ClassWithNonPublicAttributes::class); $this->expectException(AssertionFailedError::class); - $this->assertClassNotHasAttribute('publicAttribute', \ClassWithNonPublicAttributes::class); + $this->assertClassNotHasAttribute('publicAttribute', ClassWithNonPublicAttributes::class); } public function testClassHasPublicStaticAttribute(): void { - $this->assertClassHasStaticAttribute('publicStaticAttribute', \ClassWithNonPublicAttributes::class); + $this->assertClassHasStaticAttribute('publicStaticAttribute', ClassWithNonPublicAttributes::class); $this->expectException(AssertionFailedError::class); - $this->assertClassHasStaticAttribute('attribute', \ClassWithNonPublicAttributes::class); + $this->assertClassHasStaticAttribute('attribute', ClassWithNonPublicAttributes::class); } public function testClassNotHasPublicStaticAttribute(): void { - $this->assertClassNotHasStaticAttribute('attribute', \ClassWithNonPublicAttributes::class); + $this->assertClassNotHasStaticAttribute('attribute', ClassWithNonPublicAttributes::class); $this->expectException(AssertionFailedError::class); - $this->assertClassNotHasStaticAttribute('publicStaticAttribute', \ClassWithNonPublicAttributes::class); + $this->assertClassNotHasStaticAttribute('publicStaticAttribute', ClassWithNonPublicAttributes::class); } public function testObjectHasPublicAttribute(): void { - $obj = new \ClassWithNonPublicAttributes; + $obj = new ClassWithNonPublicAttributes; $this->assertObjectHasAttribute('publicAttribute', $obj); @@ -1086,7 +1115,7 @@ public function testObjectHasPublicAttribute(): void public function testObjectNotHasPublicAttribute(): void { - $obj = new \ClassWithNonPublicAttributes; + $obj = new ClassWithNonPublicAttributes; $this->assertObjectNotHasAttribute('attribute', $obj); @@ -1097,7 +1126,7 @@ public function testObjectNotHasPublicAttribute(): void public function testObjectHasOnTheFlyAttribute(): void { - $obj = new \stdClass; + $obj = new stdClass; $obj->foo = 'bar'; $this->assertObjectHasAttribute('foo', $obj); @@ -1109,7 +1138,7 @@ public function testObjectHasOnTheFlyAttribute(): void public function testObjectNotHasOnTheFlyAttribute(): void { - $obj = new \stdClass; + $obj = new stdClass; $obj->foo = 'bar'; $this->assertObjectNotHasAttribute('bar', $obj); @@ -1121,7 +1150,7 @@ public function testObjectNotHasOnTheFlyAttribute(): void public function testObjectHasProtectedAttribute(): void { - $obj = new \ClassWithNonPublicAttributes; + $obj = new ClassWithNonPublicAttributes; $this->assertObjectHasAttribute('protectedAttribute', $obj); @@ -1132,7 +1161,7 @@ public function testObjectHasProtectedAttribute(): void public function testObjectNotHasProtectedAttribute(): void { - $obj = new \ClassWithNonPublicAttributes; + $obj = new ClassWithNonPublicAttributes; $this->assertObjectNotHasAttribute('attribute', $obj); @@ -1143,7 +1172,7 @@ public function testObjectNotHasProtectedAttribute(): void public function testObjectHasPrivateAttribute(): void { - $obj = new \ClassWithNonPublicAttributes; + $obj = new ClassWithNonPublicAttributes; $this->assertObjectHasAttribute('privateAttribute', $obj); @@ -1154,7 +1183,7 @@ public function testObjectHasPrivateAttribute(): void public function testObjectNotHasPrivateAttribute(): void { - $obj = new \ClassWithNonPublicAttributes; + $obj = new ClassWithNonPublicAttributes; $this->assertObjectNotHasAttribute('attribute', $obj); @@ -1245,7 +1274,7 @@ public function testAssertThatContainsOnly(): void public function testAssertThatContainsOnlyInstancesOf(): void { - $this->assertThat([new \Book], $this->containsOnlyInstancesOf(\Book::class)); + $this->assertThat([new Book], $this->containsOnlyInstancesOf(Book::class)); } public function testAssertThatArrayHasKey(): void @@ -1256,7 +1285,7 @@ public function testAssertThatArrayHasKey(): void public function testAssertThatClassHasAttribute(): void { $this->assertThat( - new \ClassWithNonPublicAttributes, + new ClassWithNonPublicAttributes, $this->classHasAttribute('publicAttribute') ); } @@ -1264,7 +1293,7 @@ public function testAssertThatClassHasAttribute(): void public function testAssertThatClassHasStaticAttribute(): void { $this->assertThat( - new \ClassWithNonPublicAttributes, + new ClassWithNonPublicAttributes, $this->classHasStaticAttribute('publicStaticAttribute') ); } @@ -1272,7 +1301,7 @@ public function testAssertThatClassHasStaticAttribute(): void public function testAssertThatObjectHasAttribute(): void { $this->assertThat( - new \ClassWithNonPublicAttributes, + new ClassWithNonPublicAttributes, $this->objectHasAttribute('publicAttribute') ); } @@ -1284,7 +1313,7 @@ public function testAssertThatEqualTo(): void public function testAssertThatIdenticalTo(): void { - $value = new \stdClass; + $value = new stdClass; $constraint = $this->identicalTo($value); $this->assertThat($value, $constraint); @@ -1292,7 +1321,7 @@ public function testAssertThatIdenticalTo(): void public function testAssertThatIsInstanceOf(): void { - $this->assertThat(new \stdClass, $this->isInstanceOf('StdClass')); + $this->assertThat(new stdClass, $this->isInstanceOf('StdClass')); } public function testAssertThatIsType(): void @@ -1339,7 +1368,7 @@ public function testAssertThatCallback(): void { $this->assertThat( null, - $this->callback(function ($other) { + $this->callback(static function ($other) { return true; }) ); @@ -1384,14 +1413,14 @@ public function testAssertStringEqualsFile(): void { $this->assertStringEqualsFile( TEST_FILES_PATH . 'foo.xml', - \file_get_contents(TEST_FILES_PATH . 'foo.xml') + file_get_contents(TEST_FILES_PATH . 'foo.xml') ); $this->expectException(AssertionFailedError::class); $this->assertStringEqualsFile( TEST_FILES_PATH . 'foo.xml', - \file_get_contents(TEST_FILES_PATH . 'bar.xml') + file_get_contents(TEST_FILES_PATH . 'bar.xml') ); } @@ -1399,14 +1428,14 @@ public function testAssertStringEqualsFileIgnoringCase(): void { $this->assertStringEqualsFileIgnoringCase( TEST_FILES_PATH . 'foo.xml', - \file_get_contents(TEST_FILES_PATH . 'fooUppercase.xml') + file_get_contents(TEST_FILES_PATH . 'fooUppercase.xml') ); $this->expectException(AssertionFailedError::class); $this->assertStringEqualsFileIgnoringCase( TEST_FILES_PATH . 'foo.xml', - \file_get_contents(TEST_FILES_PATH . 'bar.xml') + file_get_contents(TEST_FILES_PATH . 'bar.xml') ); } @@ -1414,14 +1443,14 @@ public function testAssertStringNotEqualsFile(): void { $this->assertStringNotEqualsFile( TEST_FILES_PATH . 'foo.xml', - \file_get_contents(TEST_FILES_PATH . 'bar.xml') + file_get_contents(TEST_FILES_PATH . 'bar.xml') ); $this->expectException(AssertionFailedError::class); $this->assertStringNotEqualsFile( TEST_FILES_PATH . 'foo.xml', - \file_get_contents(TEST_FILES_PATH . 'foo.xml') + file_get_contents(TEST_FILES_PATH . 'foo.xml') ); } @@ -1429,14 +1458,14 @@ public function testAssertStringNotEqualsFileIgnoringCase(): void { $this->assertStringNotEqualsFileIgnoringCase( TEST_FILES_PATH . 'foo.xml', - \file_get_contents(TEST_FILES_PATH . 'bar.xml') + file_get_contents(TEST_FILES_PATH . 'bar.xml') ); $this->expectException(AssertionFailedError::class); $this->assertStringNotEqualsFileIgnoringCase( TEST_FILES_PATH . 'foo.xml', - \file_get_contents(TEST_FILES_PATH . 'fooUppercase.xml') + file_get_contents(TEST_FILES_PATH . 'fooUppercase.xml') ); } @@ -1589,11 +1618,11 @@ public function testAssertCount(): void public function testAssertCountTraversable(): void { - $this->assertCount(2, new \ArrayIterator([1, 2])); + $this->assertCount(2, new ArrayIterator([1, 2])); $this->expectException(AssertionFailedError::class); - $this->assertCount(2, new \ArrayIterator([1, 2, 3])); + $this->assertCount(2, new ArrayIterator([1, 2, 3])); } public function testAssertCountThrowsExceptionIfElementIsNotCountable(): void @@ -1706,8 +1735,8 @@ public function testAssertJsonStringEqualsJsonString(): void /** * @dataProvider validInvalidJsonDataprovider * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public function testAssertJsonStringEqualsJsonStringErrorRaised($expected, $actual): void { @@ -1729,8 +1758,8 @@ public function testAssertJsonStringNotEqualsJsonString(): void * @testdox Assert JSON string equals equals JSON string raised $_dataName * @dataProvider validInvalidJsonDataprovider * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public function testAssertJsonStringNotEqualsJsonStringErrorRaised($expected, $actual): void { @@ -1742,7 +1771,7 @@ public function testAssertJsonStringNotEqualsJsonStringErrorRaised($expected, $a public function testAssertJsonStringEqualsJsonFile(): void { $file = TEST_FILES_PATH . 'JsonData/simpleObject.json'; - $actual = \json_encode(['Mascott' => 'Tux']); + $actual = json_encode(['Mascott' => 'Tux']); $message = ''; $this->assertJsonStringEqualsJsonFile($file, $actual, $message); @@ -1751,7 +1780,7 @@ public function testAssertJsonStringEqualsJsonFile(): void public function testAssertJsonStringEqualsJsonFileExpectingExpectationFailedException(): void { $file = TEST_FILES_PATH . 'JsonData/simpleObject.json'; - $actual = \json_encode(['Mascott' => 'Beastie']); + $actual = json_encode(['Mascott' => 'Beastie']); $message = ''; try { @@ -1771,7 +1800,7 @@ public function testAssertJsonStringEqualsJsonFileExpectingExpectationFailedExce public function testAssertJsonStringNotEqualsJsonFile(): void { $file = TEST_FILES_PATH . 'JsonData/simpleObject.json'; - $actual = \json_encode(['Mascott' => 'Beastie']); + $actual = json_encode(['Mascott' => 'Beastie']); $message = ''; $this->assertJsonStringNotEqualsJsonFile($file, $actual, $message); @@ -1798,32 +1827,32 @@ public function testAssertInstanceOfThrowsExceptionIfTypeDoesNotExist(): void { $this->expectException(Exception::class); - $this->assertInstanceOf('ClassThatDoesNotExist', new \stdClass); + $this->assertInstanceOf('ClassThatDoesNotExist', new stdClass); } public function testAssertInstanceOf(): void { - $this->assertInstanceOf(\stdClass::class, new \stdClass); + $this->assertInstanceOf(stdClass::class, new stdClass); $this->expectException(AssertionFailedError::class); - $this->assertInstanceOf(\Exception::class, new \stdClass); + $this->assertInstanceOf(\Exception::class, new stdClass); } public function testAssertNotInstanceOfThrowsExceptionIfTypeDoesNotExist(): void { $this->expectException(Exception::class); - $this->assertNotInstanceOf('ClassThatDoesNotExist', new \stdClass); + $this->assertNotInstanceOf('ClassThatDoesNotExist', new stdClass); } public function testAssertNotInstanceOf(): void { - $this->assertNotInstanceOf(\Exception::class, new \stdClass); + $this->assertNotInstanceOf(\Exception::class, new stdClass); $this->expectException(AssertionFailedError::class); - $this->assertNotInstanceOf(\stdClass::class, new \stdClass); + $this->assertNotInstanceOf(stdClass::class, new stdClass); } public function testAssertStringMatchesFormatFileThrowsExceptionForInvalidArgument(): void @@ -1960,7 +1989,7 @@ public function testNumericTypeCanBeAsserted(): void public function testObjectTypeCanBeAsserted(): void { - $this->assertIsObject(new \stdClass); + $this->assertIsObject(new stdClass); try { $this->assertIsObject(null); @@ -1973,7 +2002,7 @@ public function testObjectTypeCanBeAsserted(): void public function testResourceTypeCanBeAsserted(): void { - $this->assertIsResource(\fopen(__FILE__, 'r')); + $this->assertIsResource(fopen(__FILE__, 'r')); try { $this->assertIsResource(null); @@ -2002,7 +2031,7 @@ public function testScalarTypeCanBeAsserted(): void $this->assertIsScalar(true); try { - $this->assertIsScalar(new \stdClass); + $this->assertIsScalar(new stdClass); } catch (AssertionFailedError $e) { return; } @@ -2012,7 +2041,7 @@ public function testScalarTypeCanBeAsserted(): void public function testCallableTypeCanBeAsserted(): void { - $this->assertIsCallable(function (): void { + $this->assertIsCallable(static function (): void { }); try { @@ -2107,7 +2136,7 @@ public function testNotObjectTypeCanBeAsserted(): void $this->assertIsNotObject(null); try { - $this->assertIsNotObject(new \stdClass); + $this->assertIsNotObject(new stdClass); } catch (AssertionFailedError $e) { return; } @@ -2120,7 +2149,7 @@ public function testNotResourceTypeCanBeAsserted(): void $this->assertIsNotResource(null); try { - $this->assertIsNotResource(\fopen(__FILE__, 'r')); + $this->assertIsNotResource(fopen(__FILE__, 'r')); } catch (AssertionFailedError $e) { return; } @@ -2130,7 +2159,7 @@ public function testNotResourceTypeCanBeAsserted(): void public function testNotScalarTypeCanBeAsserted(): void { - $this->assertIsNotScalar(new \stdClass); + $this->assertIsNotScalar(new stdClass); try { $this->assertIsNotScalar(true); @@ -2159,7 +2188,7 @@ public function testNotCallableTypeCanBeAsserted(): void $this->assertIsNotCallable(null); try { - $this->assertIsNotCallable(function (): void { + $this->assertIsNotCallable(static function (): void { }); } catch (AssertionFailedError $e) { return; @@ -2298,13 +2327,13 @@ public function testStringNotContainsStringCanBeAssertedIgnoringCase(): void public function testIterableContainsSameObjectCanBeAsserted(): void { - $object = new \stdClass; + $object = new stdClass; $iterable = [$object]; $this->assertContains($object, $iterable); try { - $this->assertContains(new \stdClass, $iterable); + $this->assertContains(new stdClass, $iterable); } catch (AssertionFailedError $e) { return; } @@ -2314,10 +2343,10 @@ public function testIterableContainsSameObjectCanBeAsserted(): void public function testIterableNotContainsSameObjectCanBeAsserted(): void { - $object = new \stdClass; + $object = new stdClass; $iterable = [$object]; - $this->assertNotContains(new \stdClass, $iterable); + $this->assertNotContains(new stdClass, $iterable); try { $this->assertNotContains($object, $iterable); @@ -2330,10 +2359,10 @@ public function testIterableNotContainsSameObjectCanBeAsserted(): void public function testIterableContainsEqualObjectCanBeAsserted(): void { - $a = new \stdClass; + $a = new stdClass; $a->foo = 'bar'; - $b = new \stdClass; + $b = new stdClass; $b->foo = 'baz'; $this->assertContainsEquals($a, [$a]); @@ -2349,10 +2378,10 @@ public function testIterableContainsEqualObjectCanBeAsserted(): void public function testIterableNotContainsEqualObjectCanBeAsserted(): void { - $a = new \stdClass; + $a = new stdClass; $a->foo = 'bar'; - $b = new \stdClass; + $b = new stdClass; $b->foo = 'baz'; $this->assertNotContainsEquals($b, [$a]); @@ -2368,9 +2397,9 @@ public function testIterableNotContainsEqualObjectCanBeAsserted(): void protected function sameValues(): array { - $object = new \SampleClass(4, 8, 15); + $object = new SampleClass(4, 8, 15); $file = TEST_FILES_PATH . 'foo.xml'; - $resource = \fopen($file, 'r'); + $resource = fopen($file, 'r'); return [ // null @@ -2382,7 +2411,7 @@ protected function sameValues(): array // floats [2.3, 2.3], [1 / 3, 1 - 2 / 3], - [\log(0), \log(0)], + [log(0), log(0)], // arrays [[], []], [[0 => 1], [0 => 1]], @@ -2398,24 +2427,24 @@ protected function sameValues(): array protected function notEqualValues(): array { // cyclic dependencies - $book1 = new \Book; - $book1->author = new \Author('Terry Pratchett'); + $book1 = new Book; + $book1->author = new Author('Terry Pratchett'); $book1->author->books[] = $book1; - $book2 = new \Book; - $book2->author = new \Author('Terry Pratch'); + $book2 = new Book; + $book2->author = new Author('Terry Pratch'); $book2->author->books[] = $book2; - $book3 = new \Book; + $book3 = new Book; $book3->author = 'Terry Pratchett'; - $book4 = new \stdClass; + $book4 = new stdClass; $book4->author = 'Terry Pratchett'; - $object1 = new \SampleClass(4, 8, 15); - $object2 = new \SampleClass(16, 23, 42); - $object3 = new \SampleClass(4, 8, 15); - $storage1 = new \SplObjectStorage; + $object1 = new SampleClass(4, 8, 15); + $object2 = new SampleClass(16, 23, 42); + $object3 = new SampleClass(4, 8, 15); + $storage1 = new SplObjectStorage; $storage1->attach($object1); - $storage2 = new \SplObjectStorage; + $storage2 = new SplObjectStorage; $storage2->attach($object3); // same content, different object $file = TEST_FILES_PATH . 'foo.xml'; @@ -2434,10 +2463,10 @@ protected function notEqualValues(): array [2.3, 4.2, 0.5], [[2.3], [4.2], 0.5], [[[2.3]], [[4.2]], 0.5], - [new \Struct(2.3), new \Struct(4.2), 0.5], - [[new \Struct(2.3)], [new \Struct(4.2)], 0.5], + [new Struct(2.3), new Struct(4.2), 0.5], + [[new Struct(2.3)], [new Struct(4.2)], 0.5], // NAN - [\NAN, \NAN], + [NAN, NAN], // arrays [[], [0 => 1]], [[0 => 1], []], @@ -2445,12 +2474,12 @@ protected function notEqualValues(): array [[0 => 1, 1 => 2], [0 => 1, 1 => 3]], [['a', 'b' => [1, 2]], ['a', 'b' => [2, 1]]], // objects - [new \SampleClass(4, 8, 15), new \SampleClass(16, 23, 42)], + [new SampleClass(4, 8, 15), new SampleClass(16, 23, 42)], [$object1, $object2], [$book1, $book2], [$book3, $book4], // same content, different class // resources - [\fopen($file, 'r'), \fopen($file, 'r')], + [fopen($file, 'r'), fopen($file, 'r')], // SplObjectStorage [$storage1, $storage2], // DOMDocument @@ -2475,82 +2504,82 @@ protected function notEqualValues(): array Xml::load(' bir '), ], [ - new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/New_York')), - new \DateTime('2013-03-29 03:13:35', new \DateTimeZone('America/New_York')), + new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/New_York')), + new DateTime('2013-03-29 03:13:35', new DateTimeZone('America/New_York')), ], [ - new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/New_York')), - new \DateTime('2013-03-29 03:13:35', new \DateTimeZone('America/New_York')), + new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/New_York')), + new DateTime('2013-03-29 03:13:35', new DateTimeZone('America/New_York')), 3500, ], [ - new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/New_York')), - new \DateTime('2013-03-29 05:13:35', new \DateTimeZone('America/New_York')), + new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/New_York')), + new DateTime('2013-03-29 05:13:35', new DateTimeZone('America/New_York')), 3500, ], [ - new \DateTime('2013-03-29', new \DateTimeZone('America/New_York')), - new \DateTime('2013-03-30', new \DateTimeZone('America/New_York')), + new DateTime('2013-03-29', new DateTimeZone('America/New_York')), + new DateTime('2013-03-30', new DateTimeZone('America/New_York')), ], [ - new \DateTime('2013-03-29', new \DateTimeZone('America/New_York')), - new \DateTime('2013-03-30', new \DateTimeZone('America/New_York')), + new DateTime('2013-03-29', new DateTimeZone('America/New_York')), + new DateTime('2013-03-30', new DateTimeZone('America/New_York')), 43200, ], [ - new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/New_York')), - new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/Chicago')), + new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/New_York')), + new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/Chicago')), ], [ - new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/New_York')), - new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/Chicago')), + new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/New_York')), + new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/Chicago')), 3500, ], [ - new \DateTime('2013-03-30', new \DateTimeZone('America/New_York')), - new \DateTime('2013-03-30', new \DateTimeZone('America/Chicago')), + new DateTime('2013-03-30', new DateTimeZone('America/New_York')), + new DateTime('2013-03-30', new DateTimeZone('America/Chicago')), ], [ - new \DateTime('2013-03-29T05:13:35-0600'), - new \DateTime('2013-03-29T04:13:35-0600'), + new DateTime('2013-03-29T05:13:35-0600'), + new DateTime('2013-03-29T04:13:35-0600'), ], [ - new \DateTime('2013-03-29T05:13:35-0600'), - new \DateTime('2013-03-29T05:13:35-0500'), + new DateTime('2013-03-29T05:13:35-0600'), + new DateTime('2013-03-29T05:13:35-0500'), ], // Exception //array(new Exception('Exception 1'), new Exception('Exception 2')), // different types - [new \SampleClass(4, 8, 15), false], - [false, new \SampleClass(4, 8, 15)], + [new SampleClass(4, 8, 15), false], + [false, new SampleClass(4, 8, 15)], [[0 => 1, 1 => 2], false], [false, [0 => 1, 1 => 2]], - [[], new \stdClass], - [new \stdClass, []], + [[], new stdClass], + [new stdClass, []], // PHP: 0 == 'Foobar' => true! // We want these values to differ [0, 'Foobar'], ['Foobar', 0], - [3, \acos(8)], - [\acos(8), 3], + [3, acos(8)], + [acos(8), 3], ]; } protected function equalValues(): array { // cyclic dependencies - $book1 = new \Book; - $book1->author = new \Author('Terry Pratchett'); + $book1 = new Book; + $book1->author = new Author('Terry Pratchett'); $book1->author->books[] = $book1; - $book2 = new \Book; - $book2->author = new \Author('Terry Pratchett'); + $book2 = new Book; + $book2->author = new Author('Terry Pratchett'); $book2->author->books[] = $book2; - $object1 = new \SampleClass(4, 8, 15); - $object2 = new \SampleClass(4, 8, 15); - $storage1 = new \SplObjectStorage; + $object1 = new SampleClass(4, 8, 15); + $object2 = new SampleClass(4, 8, 15); + $storage1 = new SplObjectStorage; $storage1->attach($object1); - $storage2 = new \SplObjectStorage; + $storage2 = new SplObjectStorage; $storage2->attach($object1); return [ @@ -2580,28 +2609,28 @@ protected function equalValues(): array Xml::load(''), ], [ - new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/New_York')), - new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/New_York')), + new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/New_York')), + new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/New_York')), ], [ - new \DateTime('2013-03-29', new \DateTimeZone('America/New_York')), - new \DateTime('2013-03-29', new \DateTimeZone('America/New_York')), + new DateTime('2013-03-29', new DateTimeZone('America/New_York')), + new DateTime('2013-03-29', new DateTimeZone('America/New_York')), ], [ - new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/New_York')), - new \DateTime('2013-03-29 03:13:35', new \DateTimeZone('America/Chicago')), + new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/New_York')), + new DateTime('2013-03-29 03:13:35', new DateTimeZone('America/Chicago')), ], [ - new \DateTime('2013-03-30', new \DateTimeZone('America/New_York')), - new \DateTime('2013-03-29 23:00:00', new \DateTimeZone('America/Chicago')), + new DateTime('2013-03-30', new DateTimeZone('America/New_York')), + new DateTime('2013-03-29 23:00:00', new DateTimeZone('America/Chicago')), ], [ - new \DateTime('@1364616000'), - new \DateTime('2013-03-29 23:00:00', new \DateTimeZone('America/Chicago')), + new DateTime('@1364616000'), + new DateTime('2013-03-29 23:00:00', new DateTimeZone('America/Chicago')), ], [ - new \DateTime('2013-03-29T05:13:35-0500'), - new \DateTime('2013-03-29T04:13:35-0600'), + new DateTime('2013-03-29T05:13:35-0500'), + new DateTime('2013-03-29T04:13:35-0600'), ], // Exception //array(new Exception('Exception 1'), new Exception('Exception 1')), @@ -2612,8 +2641,8 @@ protected function equalValues(): array ['2.3', 2.3], [(string) (1 / 3), 1 - 2 / 3], [1 / 3, (string) (1 - 2 / 3)], - ['string representation', new \ClassWithToString], - [new \ClassWithToString, 'string representation'], + ['string representation', new ClassWithToString], + [new ClassWithToString, 'string representation'], ]; } } diff --git a/tests/unit/Framework/Constraint/ArraySubsetTest.php b/tests/unit/Framework/Constraint/ArraySubsetTest.php index 2e074fc37e3..c290c9c8a92 100644 --- a/tests/unit/Framework/Constraint/ArraySubsetTest.php +++ b/tests/unit/Framework/Constraint/ArraySubsetTest.php @@ -9,7 +9,11 @@ */ namespace PHPUnit\Framework\Constraint; +use function sprintf; +use ArrayAccessible; +use ArrayObject; use PHPUnit\Framework\ExpectationFailedException; +use Traversable; /** * @small @@ -34,12 +38,12 @@ public static function evaluateDataProvider(): array 'loose array subset and ArrayObject other' => [ 'expected' => true, 'subset' => ['bar' => 0], - 'other' => new \ArrayObject(['foo' => '', 'bar' => '0']), + 'other' => new ArrayObject(['foo' => '', 'bar' => '0']), 'strict' => false, ], 'strict ArrayObject subset and array other' => [ 'expected' => true, - 'subset' => new \ArrayObject(['bar' => 0]), + 'subset' => new ArrayObject(['bar' => 0]), 'other' => ['foo' => '', 'bar' => 0], 'strict' => true, ], @@ -47,13 +51,13 @@ public static function evaluateDataProvider(): array } /** - * @param bool $expected - * @param array|\Traversable $subset - * @param array|\Traversable $other - * @param bool $strict + * @param bool $expected + * @param array|Traversable $subset + * @param array|Traversable $other + * @param bool $strict * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException * @dataProvider evaluateDataProvider */ public function testEvaluate($expected, $subset, $other, $strict): void @@ -65,7 +69,7 @@ public function testEvaluate($expected, $subset, $other, $strict): void public function testEvaluateWithArrayAccess(): void { - $arrayAccess = new \ArrayAccessible(['foo' => 'bar']); + $arrayAccess = new ArrayAccessible(['foo' => 'bar']); $constraint = new ArraySubset(['foo' => 'bar']); @@ -78,7 +82,7 @@ public function testEvaluateFailMessage(): void try { $constraint->evaluate(['baz' => 'bar'], '', false); - $this->fail(\sprintf('Expected %s to be thrown.', ExpectationFailedException::class)); + $this->fail(sprintf('Expected %s to be thrown.', ExpectationFailedException::class)); } catch (ExpectationFailedException $expectedException) { $comparisonFailure = $expectedException->getComparisonFailure(); $this->assertNotNull($comparisonFailure); diff --git a/tests/unit/Framework/Constraint/CallbackTest.php b/tests/unit/Framework/Constraint/CallbackTest.php index 3add01293f7..0e100cee8c8 100644 --- a/tests/unit/Framework/Constraint/CallbackTest.php +++ b/tests/unit/Framework/Constraint/CallbackTest.php @@ -28,11 +28,11 @@ public function callbackReturningTrue() public function testConstraintCallback(): void { - $closureReflect = function ($parameter) { + $closureReflect = static function ($parameter) { return $parameter; }; - $closureWithoutParameter = function () { + $closureWithoutParameter = static function () { return true; }; @@ -56,7 +56,7 @@ public function testConstraintCallback(): void public function testConstraintCallbackFailure(): void { - $constraint = new Callback(function () { + $constraint = new Callback(static function () { return false; }); diff --git a/tests/unit/Framework/Constraint/ClassHasAttributeTest.php b/tests/unit/Framework/Constraint/ClassHasAttributeTest.php index b789fc92770..9c356fdc47b 100644 --- a/tests/unit/Framework/Constraint/ClassHasAttributeTest.php +++ b/tests/unit/Framework/Constraint/ClassHasAttributeTest.php @@ -9,8 +9,10 @@ */ namespace PHPUnit\Framework\Constraint; +use ClassWithNonPublicAttributes; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; +use stdClass; /** * @small @@ -23,13 +25,13 @@ public function testConstraintClassHasAttribute(): void 'privateAttribute' ); - $this->assertTrue($constraint->evaluate(\ClassWithNonPublicAttributes::class, '', true)); - $this->assertFalse($constraint->evaluate(\stdClass::class, '', true)); + $this->assertTrue($constraint->evaluate(ClassWithNonPublicAttributes::class, '', true)); + $this->assertFalse($constraint->evaluate(stdClass::class, '', true)); $this->assertEquals('has attribute "privateAttribute"', $constraint->toString()); $this->assertCount(1, $constraint); try { - $constraint->evaluate(\stdClass::class); + $constraint->evaluate(stdClass::class); } catch (ExpectationFailedException $e) { $this->assertEquals( <<<'EOF' @@ -53,7 +55,7 @@ public function testConstraintClassHasAttribute2(): void ); try { - $constraint->evaluate(\stdClass::class, 'custom message'); + $constraint->evaluate(stdClass::class, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<<'EOF' diff --git a/tests/unit/Framework/Constraint/ClassHasStaticAttributeTest.php b/tests/unit/Framework/Constraint/ClassHasStaticAttributeTest.php index a3b5e0abbf0..fea349a9351 100644 --- a/tests/unit/Framework/Constraint/ClassHasStaticAttributeTest.php +++ b/tests/unit/Framework/Constraint/ClassHasStaticAttributeTest.php @@ -9,8 +9,10 @@ */ namespace PHPUnit\Framework\Constraint; +use ClassWithNonPublicAttributes; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; +use stdClass; /** * @small @@ -21,13 +23,13 @@ public function testConstraintClassHasStaticAttribute(): void { $constraint = new ClassHasStaticAttribute('privateStaticAttribute'); - $this->assertTrue($constraint->evaluate(\ClassWithNonPublicAttributes::class, '', true)); - $this->assertFalse($constraint->evaluate(\stdClass::class, '', true)); + $this->assertTrue($constraint->evaluate(ClassWithNonPublicAttributes::class, '', true)); + $this->assertFalse($constraint->evaluate(stdClass::class, '', true)); $this->assertEquals('has static attribute "privateStaticAttribute"', $constraint->toString()); $this->assertCount(1, $constraint); try { - $constraint->evaluate(\stdClass::class); + $constraint->evaluate(stdClass::class); } catch (ExpectationFailedException $e) { $this->assertEquals( <<<'EOF' @@ -49,7 +51,7 @@ public function testConstraintClassHasStaticAttribute2(): void $constraint = new ClassHasStaticAttribute('foo'); try { - $constraint->evaluate(\stdClass::class, 'custom message'); + $constraint->evaluate(stdClass::class, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<<'EOF' diff --git a/tests/unit/Framework/Constraint/ConstraintTestCase.php b/tests/unit/Framework/Constraint/ConstraintTestCase.php index 059e3b41fc3..82e997c9878 100644 --- a/tests/unit/Framework/Constraint/ConstraintTestCase.php +++ b/tests/unit/Framework/Constraint/ConstraintTestCase.php @@ -9,8 +9,12 @@ */ namespace PHPUnit\Framework\Constraint; +use function preg_replace; +use function sprintf; +use Countable; use PHPUnit\Framework\SelfDescribing; use PHPUnit\Framework\TestCase; +use ReflectionClass; /** * @small @@ -21,12 +25,12 @@ final public function testIsCountable(): void { $className = $this->className(); - $reflection = new \ReflectionClass($className); + $reflection = new ReflectionClass($className); - $this->assertTrue($reflection->implementsInterface(\Countable::class), \sprintf( + $this->assertTrue($reflection->implementsInterface(Countable::class), sprintf( 'Failed to assert that "%s" implements "%s".', $className, - \Countable::class + Countable::class )); } @@ -34,9 +38,9 @@ final public function testIsSelfDescribing(): void { $className = $this->className(); - $reflection = new \ReflectionClass($className); + $reflection = new ReflectionClass($className); - $this->assertTrue($reflection->implementsInterface(SelfDescribing::class), \sprintf( + $this->assertTrue($reflection->implementsInterface(SelfDescribing::class), sprintf( 'Failed to assert that "%s" implements "%s".', $className, SelfDescribing::class @@ -48,7 +52,7 @@ final public function testIsSelfDescribing(): void */ final protected function className(): string { - return \preg_replace( + return preg_replace( '/Test$/', '', static::class diff --git a/tests/unit/Framework/Constraint/CountTest.php b/tests/unit/Framework/Constraint/CountTest.php index fe2880c2eb6..963c7f23d12 100644 --- a/tests/unit/Framework/Constraint/CountTest.php +++ b/tests/unit/Framework/Constraint/CountTest.php @@ -9,8 +9,18 @@ */ namespace PHPUnit\Framework\Constraint; +use DatePeriod; +use EmptyIterator; +use Iterator; +use IteratorAggregate; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; +use TestGeneratorMaker; +use TestIterator; +use TestIterator2; +use TestIteratorAggregate; +use TestIteratorAggregate2; +use Traversable; /** * @small @@ -26,9 +36,9 @@ public function testCount(): void $this->assertTrue($countConstraint->evaluate([], '', true)); $countConstraint = new Count(2); - $it = new \TestIterator([1, 2]); - $ia = new \TestIteratorAggregate($it); - $ia2 = new \TestIteratorAggregate2($ia); + $it = new TestIterator([1, 2]); + $ia = new TestIteratorAggregate($it); + $ia2 = new TestIteratorAggregate2($ia); $this->assertTrue($countConstraint->evaluate($it, '', true)); $this->assertTrue($countConstraint->evaluate($ia, '', true)); @@ -40,7 +50,7 @@ public function testCountDoesNotChangeIteratorKey(): void $countConstraint = new Count(2); // test with 1st implementation of Iterator - $it = new \TestIterator([1, 2]); + $it = new TestIterator([1, 2]); $countConstraint->evaluate($it, '', true); $this->assertEquals(1, $it->current()); @@ -54,7 +64,7 @@ public function testCountDoesNotChangeIteratorKey(): void $this->assertFalse($it->valid()); // test with 2nd implementation of Iterator - $it = new \TestIterator2([1, 2]); + $it = new TestIterator2([1, 2]); $countConstraint = new Count(2); $countConstraint->evaluate($it, '', true); @@ -69,8 +79,8 @@ public function testCountDoesNotChangeIteratorKey(): void $this->assertFalse($it->valid()); // test with IteratorAggregate - $it = new \TestIterator([1, 2]); - $ia = new \TestIteratorAggregate($it); + $it = new TestIterator([1, 2]); + $ia = new TestIteratorAggregate($it); $countConstraint = new Count(2); $countConstraint->evaluate($ia, '', true); @@ -85,9 +95,9 @@ public function testCountDoesNotChangeIteratorKey(): void $this->assertFalse($it->valid()); // test with nested IteratorAggregate - $it = new \TestIterator([1, 2]); - $ia = new \TestIteratorAggregate($it); - $ia2 = new \TestIteratorAggregate2($ia); + $it = new TestIterator([1, 2]); + $ia = new TestIteratorAggregate($it); + $ia2 = new TestIteratorAggregate2($ia); $countConstraint = new Count(2); $countConstraint->evaluate($ia2, '', true); @@ -104,7 +114,7 @@ public function testCountDoesNotChangeIteratorKey(): void public function testCountGeneratorsDoNotRewind(): void { - $generatorMaker = new \TestGeneratorMaker; + $generatorMaker = new TestGeneratorMaker; $countConstraint = new Count(3); @@ -146,11 +156,11 @@ public function testCountTraversable(): void // DatePeriod is used as an object that is Traversable but does not // implement Iterator or IteratorAggregate. The following ISO 8601 // recurring time interval will yield five total DateTime objects. - $datePeriod = new \DatePeriod('R4/2017-05-01T00:00:00Z/P1D'); + $datePeriod = new DatePeriod('R4/2017-05-01T00:00:00Z/P1D'); - $this->assertInstanceOf(\Traversable::class, $datePeriod); - $this->assertNotInstanceOf(\Iterator::class, $datePeriod); - $this->assertNotInstanceOf(\IteratorAggregate::class, $datePeriod); + $this->assertInstanceOf(Traversable::class, $datePeriod); + $this->assertNotInstanceOf(Iterator::class, $datePeriod); + $this->assertNotInstanceOf(IteratorAggregate::class, $datePeriod); $this->assertTrue($countConstraint->evaluate($datePeriod, '', true)); } @@ -186,6 +196,6 @@ public function test_EmptyIterator_is_handled_correctly(): void { $constraint = new Count(0); - $this->assertTrue($constraint->evaluate(new \EmptyIterator, '', true)); + $this->assertTrue($constraint->evaluate(new EmptyIterator, '', true)); } } diff --git a/tests/unit/Framework/Constraint/ExceptionCodeTest.php b/tests/unit/Framework/Constraint/ExceptionCodeTest.php index 173d6213278..c58a0387db2 100644 --- a/tests/unit/Framework/Constraint/ExceptionCodeTest.php +++ b/tests/unit/Framework/Constraint/ExceptionCodeTest.php @@ -9,6 +9,7 @@ */ namespace PHPUnit\Framework\Constraint; +use Exception; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestFailure; @@ -19,7 +20,7 @@ public function testExceptionCodeCanEvaluateExceptions(): void { $exceptionCode = new ExceptionCode(123); - $other = new \Exception('bla', 456); + $other = new Exception('bla', 456); try { $exceptionCode->evaluate($other); diff --git a/tests/unit/Framework/Constraint/ExceptionMessageRegExpTest.php b/tests/unit/Framework/Constraint/ExceptionMessageRegExpTest.php index 83eaaa213a9..05b0d9d88ff 100644 --- a/tests/unit/Framework/Constraint/ExceptionMessageRegExpTest.php +++ b/tests/unit/Framework/Constraint/ExceptionMessageRegExpTest.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Framework\Constraint; +use function ini_set; +use Exception; use PHPUnit\Framework\TestCase; /** @@ -18,18 +20,18 @@ final class ExceptionMessageRegExpTest extends TestCase { public function testRegexMessage(): void { - $this->expectException(\Exception::class); + $this->expectException(Exception::class); $this->expectExceptionMessageMatches('/^A polymorphic \w+ message/'); - throw new \Exception('A polymorphic exception message'); + throw new Exception('A polymorphic exception message'); } public function testRegexMessageExtreme(): void { - $this->expectException(\Exception::class); + $this->expectException(Exception::class); $this->expectExceptionMessageMatches('/^a poly[a-z]+ [a-zA-Z0-9_]+ me(s){2}age$/i'); - throw new \Exception('A polymorphic exception message'); + throw new Exception('A polymorphic exception message'); } /** @@ -38,12 +40,12 @@ public function testRegexMessageExtreme(): void */ public function testMessageXdebugScreamCompatibility(): void { - \ini_set('xdebug.scream', '1'); + ini_set('xdebug.scream', '1'); - $this->expectException(\Exception::class); + $this->expectException(Exception::class); $this->expectExceptionMessageMatches('#Screaming preg_match#'); - throw new \Exception('Screaming preg_match'); + throw new Exception('Screaming preg_match'); } public function testRegExMessageCanBeExportedAsString(): void diff --git a/tests/unit/Framework/Constraint/ExceptionMessageTest.php b/tests/unit/Framework/Constraint/ExceptionMessageTest.php index 0d3daf1e711..60373a83859 100644 --- a/tests/unit/Framework/Constraint/ExceptionMessageTest.php +++ b/tests/unit/Framework/Constraint/ExceptionMessageTest.php @@ -9,6 +9,7 @@ */ namespace PHPUnit\Framework\Constraint; +use Exception; use PHPUnit\Framework\TestCase; /** @@ -18,34 +19,34 @@ final class ExceptionMessageTest extends TestCase { public function testLiteralMessage(): void { - $this->expectException(\Exception::class); + $this->expectException(Exception::class); $this->expectExceptionMessage('A literal exception message'); - throw new \Exception('A literal exception message'); + throw new Exception('A literal exception message'); } public function testPartialMessageBegin(): void { - $this->expectException(\Exception::class); + $this->expectException(Exception::class); $this->expectExceptionMessage('A partial'); - throw new \Exception('A partial exception message'); + throw new Exception('A partial exception message'); } public function testPartialMessageMiddle(): void { - $this->expectException(\Exception::class); + $this->expectException(Exception::class); $this->expectExceptionMessage('partial exception'); - throw new \Exception('A partial exception message'); + throw new Exception('A partial exception message'); } public function testPartialMessageEnd(): void { - $this->expectException(\Exception::class); + $this->expectException(Exception::class); $this->expectExceptionMessage('exception message'); - throw new \Exception('A partial exception message'); + throw new Exception('A partial exception message'); } public function testEmptyMessageExportToString(): void diff --git a/tests/unit/Framework/Constraint/IsEmptyTest.php b/tests/unit/Framework/Constraint/IsEmptyTest.php index fad064e5203..afb3ff919a0 100644 --- a/tests/unit/Framework/Constraint/IsEmptyTest.php +++ b/tests/unit/Framework/Constraint/IsEmptyTest.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Framework\Constraint; +use ArrayObject; +use EmptyIterator; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; @@ -23,8 +25,8 @@ public function testConstraintIsEmpty(): void $this->assertFalse($constraint->evaluate(['foo'], '', true)); $this->assertTrue($constraint->evaluate([], '', true)); - $this->assertFalse($constraint->evaluate(new \ArrayObject(['foo']), '', true)); - $this->assertTrue($constraint->evaluate(new \ArrayObject([]), '', true)); + $this->assertFalse($constraint->evaluate(new ArrayObject(['foo']), '', true)); + $this->assertTrue($constraint->evaluate(new ArrayObject([]), '', true)); $this->assertEquals('is empty', $constraint->toString()); $this->assertCount(1, $constraint); @@ -75,6 +77,6 @@ public function test_EmptyIterator_is_handled_correctly(): void { $constraint = new IsEmpty; - $this->assertTrue($constraint->evaluate(new \EmptyIterator, '', true)); + $this->assertTrue($constraint->evaluate(new EmptyIterator, '', true)); } } diff --git a/tests/unit/Framework/Constraint/IsEqualTest.php b/tests/unit/Framework/Constraint/IsEqualTest.php index d0bf7fadd96..27723a4de37 100644 --- a/tests/unit/Framework/Constraint/IsEqualTest.php +++ b/tests/unit/Framework/Constraint/IsEqualTest.php @@ -9,8 +9,15 @@ */ namespace PHPUnit\Framework\Constraint; +use function preg_replace; +use function spl_object_hash; +use DateTime; +use DateTimeZone; +use DOMDocument; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; +use SplObjectStorage; +use stdClass; /** * @small @@ -74,41 +81,41 @@ public function testConstraintDeltaIsNotZero(): void public function isEqualProvider(): array { - $a = new \stdClass; + $a = new stdClass; $a->foo = 'bar'; - $b = new \stdClass; - $ahash = \spl_object_hash($a); - $bhash = \spl_object_hash($b); + $b = new stdClass; + $ahash = spl_object_hash($a); + $bhash = spl_object_hash($b); - $c = new \stdClass; + $c = new stdClass; $c->foo = 'bar'; $c->int = 1; $c->array = [0, [1], [2], 3]; - $c->related = new \stdClass; + $c->related = new stdClass; $c->related->foo = "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk"; $c->self = $c; $c->c = $c; - $d = new \stdClass; + $d = new stdClass; $d->foo = 'bar'; $d->int = 2; $d->array = [0, [4], [2], 3]; - $d->related = new \stdClass; + $d->related = new stdClass; $d->related->foo = "a\np\nc\nd\ne\nf\ng\nh\ni\nw\nk"; $d->self = $d; $d->c = $c; - $storage1 = new \SplObjectStorage; + $storage1 = new SplObjectStorage; $storage1->attach($a); $storage1->attach($b); - $storage2 = new \SplObjectStorage; + $storage2 = new SplObjectStorage; $storage2->attach($b); - $storage1hash = \spl_object_hash($storage1); - $storage2hash = \spl_object_hash($storage2); + $storage1hash = spl_object_hash($storage1); + $storage2hash = spl_object_hash($storage2); - $dom1 = new \DOMDocument; + $dom1 = new DOMDocument; $dom1->preserveWhiteSpace = false; $dom1->loadXML(''); - $dom2 = new \DOMDocument; + $dom2 = new DOMDocument; $dom2->preserveWhiteSpace = false; $dom2->loadXML(''); @@ -280,8 +287,8 @@ public function isEqualProvider(): array EOF ], [ - new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/New_York')), - new \DateTime('2013-03-29 04:13:35', new \DateTimeZone('America/Chicago')), + new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/New_York')), + new DateTime('2013-03-29 04:13:35', new DateTimeZone('America/Chicago')), <<<'EOF' Failed asserting that two DateTime objects are equal. --- Expected @@ -318,7 +325,7 @@ public function isEqualProvider(): array } /** - * Removes spaces in front of newlines + * Removes spaces in front of newlines. * * @param string $string * @@ -326,6 +333,6 @@ public function isEqualProvider(): array */ private function trimnl($string) { - return \preg_replace('/[ ]*\n/', "\n", $string); + return preg_replace('/[ ]*\n/', "\n", $string); } } diff --git a/tests/unit/Framework/Constraint/IsIdenticalTest.php b/tests/unit/Framework/Constraint/IsIdenticalTest.php index 8b44de859bc..5ee4cddd857 100644 --- a/tests/unit/Framework/Constraint/IsIdenticalTest.php +++ b/tests/unit/Framework/Constraint/IsIdenticalTest.php @@ -11,6 +11,7 @@ use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; +use stdClass; /** * @small @@ -19,8 +20,8 @@ final class IsIdenticalTest extends ConstraintTestCase { public function testConstraintIsIdentical(): void { - $a = new \stdClass; - $b = new \stdClass; + $a = new stdClass; + $b = new stdClass; $constraint = new IsIdentical($a); @@ -49,8 +50,8 @@ public function testConstraintIsIdentical(): void public function testConstraintIsIdentical2(): void { - $a = new \stdClass; - $b = new \stdClass; + $a = new stdClass; + $b = new stdClass; $constraint = new IsIdentical($a); diff --git a/tests/unit/Framework/Constraint/IsInstanceOfTest.php b/tests/unit/Framework/Constraint/IsInstanceOfTest.php index e082665c212..a0d728ec697 100644 --- a/tests/unit/Framework/Constraint/IsInstanceOfTest.php +++ b/tests/unit/Framework/Constraint/IsInstanceOfTest.php @@ -11,6 +11,8 @@ use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; +use ReflectionException; +use stdClass; /** * @small @@ -19,19 +21,19 @@ final class IsInstanceOfTest extends ConstraintTestCase { public function testConstraintInstanceOf(): void { - $constraint = new IsInstanceOf(\stdClass::class); + $constraint = new IsInstanceOf(stdClass::class); - self::assertTrue($constraint->evaluate(new \stdClass, '', true)); + $this->assertTrue($constraint->evaluate(new stdClass, '', true)); } public function testConstraintFailsOnString(): void { - $constraint = new IsInstanceOf(\stdClass::class); + $constraint = new IsInstanceOf(stdClass::class); try { $constraint->evaluate('stdClass'); } catch (ExpectationFailedException $e) { - self::assertSame( + $this->assertSame( <<<'EOT' Failed asserting that 'stdClass' is an instance of class "stdClass". @@ -44,11 +46,11 @@ public function testConstraintFailsOnString(): void public function testCronstraintsThrowsReflectionException(): void { - $this->throwException(new \ReflectionException); + $this->throwException(new ReflectionException); $constraint = new IsInstanceOf(NotExistingClass::class); - self::assertSame( + $this->assertSame( 'is instance of class "PHPUnit\Framework\Constraint\NotExistingClass"', $constraint->toString() ); diff --git a/tests/unit/Framework/Constraint/IsTypeTest.php b/tests/unit/Framework/Constraint/IsTypeTest.php index f5534db2b16..0aebdefe495 100644 --- a/tests/unit/Framework/Constraint/IsTypeTest.php +++ b/tests/unit/Framework/Constraint/IsTypeTest.php @@ -9,9 +9,14 @@ */ namespace PHPUnit\Framework\Constraint; +use function fclose; +use function fopen; +use function is_resource; +use function preg_replace; use PHPUnit\Framework\Assert; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; +use stdClass; /** * @small @@ -28,7 +33,7 @@ public function testConstraintIsType(): void $this->assertCount(1, $constraint); try { - $constraint->evaluate(new \stdClass); + $constraint->evaluate(new stdClass); } catch (ExpectationFailedException $e) { $this->assertStringMatchesFormat( <<<'EOF' @@ -50,7 +55,7 @@ public function testConstraintIsType2(): void $constraint = Assert::isType('string'); try { - $constraint->evaluate(new \stdClass, 'custom message'); + $constraint->evaluate(new stdClass, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertStringMatchesFormat( <<<'EOF' @@ -77,18 +82,18 @@ public function testConstraintIsResourceTypeEvaluatesCorrectlyWithResources($res $this->assertTrue($constraint->evaluate($resource, '', true)); - if (\is_resource($resource)) { - @\fclose($resource); + if (is_resource($resource)) { + @fclose($resource); } } public function resources() { - $fh = \fopen(__FILE__, 'r'); - \fclose($fh); + $fh = fopen(__FILE__, 'r'); + fclose($fh); return [ - 'open resource' => [\fopen(__FILE__, 'r')], + 'open resource' => [fopen(__FILE__, 'r')], 'closed resource' => [$fh], ]; } @@ -127,7 +132,7 @@ public function testTypeCanNotBeAnUndefinedOne(): void } /** - * Removes spaces in front of newlines + * Removes spaces in front of newlines. * * @param string $string * @@ -135,6 +140,6 @@ public function testTypeCanNotBeAnUndefinedOne(): void */ private function trimnl($string) { - return \preg_replace('/[ ]*\n/', "\n", $string); + return preg_replace('/[ ]*\n/', "\n", $string); } } diff --git a/tests/unit/Framework/Constraint/JsonMatchesErrorMessageProviderTest.php b/tests/unit/Framework/Constraint/JsonMatchesErrorMessageProviderTest.php index 0213ffca013..b9219de5d6c 100644 --- a/tests/unit/Framework/Constraint/JsonMatchesErrorMessageProviderTest.php +++ b/tests/unit/Framework/Constraint/JsonMatchesErrorMessageProviderTest.php @@ -9,6 +9,12 @@ */ 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 PHPUnit\Framework\TestCase; /** @@ -20,26 +26,26 @@ public static function determineJsonErrorDataprovider(): array { return [ 'JSON_ERROR_NONE' => [ - null, 'json_error_none', '', + null, JSON_ERROR_NONE, '', ], 'JSON_ERROR_DEPTH' => [ - 'Maximum stack depth exceeded', \JSON_ERROR_DEPTH, '', + 'Maximum stack depth exceeded', JSON_ERROR_DEPTH, '', ], 'prefixed JSON_ERROR_DEPTH' => [ - 'TUX: Maximum stack depth exceeded', \JSON_ERROR_DEPTH, 'TUX: ', + 'TUX: Maximum stack depth exceeded', JSON_ERROR_DEPTH, 'TUX: ', ], 'JSON_ERROR_STATE_MISMatch' => [ - 'Underflow or the modes mismatch', \JSON_ERROR_STATE_MISMATCH, '', + 'Underflow or the modes mismatch', JSON_ERROR_STATE_MISMATCH, '', ], 'JSON_ERROR_CTRL_CHAR' => [ - 'Unexpected control character found', \JSON_ERROR_CTRL_CHAR, '', + 'Unexpected control character found', JSON_ERROR_CTRL_CHAR, '', ], 'JSON_ERROR_SYNTAX' => [ - 'Syntax error, malformed JSON', \JSON_ERROR_SYNTAX, '', + 'Syntax error, malformed JSON', JSON_ERROR_SYNTAX, '', ], 'JSON_ERROR_UTF8`' => [ 'Malformed UTF-8 characters, possibly incorrectly encoded', - \JSON_ERROR_UTF8, + JSON_ERROR_UTF8, '', ], 'Invalid error indicator' => [ diff --git a/tests/unit/Framework/Constraint/JsonMatchesTest.php b/tests/unit/Framework/Constraint/JsonMatchesTest.php index e2ee0648b7d..75ce3bf1b0d 100644 --- a/tests/unit/Framework/Constraint/JsonMatchesTest.php +++ b/tests/unit/Framework/Constraint/JsonMatchesTest.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Framework\Constraint; +use function json_encode; +use function sprintf; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; use PHPUnit\Util\Json; @@ -21,10 +23,10 @@ final class JsonMatchesTest extends ConstraintTestCase public static function evaluateDataprovider(): array { return [ - 'valid JSON' => [true, \json_encode(['Mascott' => 'Tux']), \json_encode(['Mascott' => 'Tux'])], - 'error syntax' => [false, '{"Mascott"::}', \json_encode(['Mascott' => 'Tux'])], - 'error UTF-8' => [false, \json_encode('\xB1\x31'), \json_encode(['Mascott' => 'Tux'])], - 'invalid JSON in class instantiation' => [false, \json_encode(['Mascott' => 'Tux']), '{"Mascott"::}'], + 'valid JSON' => [true, json_encode(['Mascott' => 'Tux']), json_encode(['Mascott' => 'Tux'])], + 'error syntax' => [false, '{"Mascott"::}', json_encode(['Mascott' => 'Tux'])], + 'error UTF-8' => [false, json_encode('\xB1\x31'), json_encode(['Mascott' => 'Tux'])], + 'invalid JSON in class instantiation' => [false, json_encode(['Mascott' => 'Tux']), '{"Mascott"::}'], 'string type not equals number' => [false, '{"age": "5"}', '{"age": 5}'], 'string type not equals boolean' => [false, '{"age": "true"}', '{"age": true}'], 'string type not equals null' => [false, '{"age": "null"}', '{"age": null}'], @@ -42,7 +44,7 @@ public static function evaluateDataprovider(): array public static function evaluateThrowsExpectationFailedExceptionWhenJsonIsValidButDoesNotMatchDataprovider(): array { return [ - 'error UTF-8' => [\json_encode('\xB1\x31'), \json_encode(['Mascott' => 'Tux'])], + 'error UTF-8' => [json_encode('\xB1\x31'), json_encode(['Mascott' => 'Tux'])], 'string type not equals number' => ['{"age": "5"}', '{"age": 5}'], 'string type not equals boolean' => ['{"age": "true"}', '{"age": true}'], 'string type not equals null' => ['{"age": "null"}', '{"age": null}'], @@ -54,8 +56,8 @@ public static function evaluateThrowsExpectationFailedExceptionWhenJsonIsValidBu /** * @dataProvider evaluateDataprovider * - * @throws ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public function testEvaluate($expected, $jsonOther, $jsonValue): void { @@ -67,10 +69,10 @@ public function testEvaluate($expected, $jsonOther, $jsonValue): void /** * @dataProvider evaluateThrowsExpectationFailedExceptionWhenJsonIsValidButDoesNotMatchDataprovider * - * @throws ExpectationFailedException * @throws \PHPUnit\Framework\AssertionFailedError * @throws \PHPUnit\Framework\Exception * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws ExpectationFailedException */ public function testEvaluateThrowsExpectationFailedExceptionWhenJsonIsValidButDoesNotMatch($jsonOther, $jsonValue): void { @@ -78,7 +80,7 @@ public function testEvaluateThrowsExpectationFailedExceptionWhenJsonIsValidButDo try { $constraint->evaluate($jsonOther, '', false); - $this->fail(\sprintf('Expected %s to be thrown.', ExpectationFailedException::class)); + $this->fail(sprintf('Expected %s to be thrown.', ExpectationFailedException::class)); } catch (ExpectationFailedException $expectedException) { $comparisonFailure = $expectedException->getComparisonFailure(); $this->assertNotNull($comparisonFailure); @@ -90,7 +92,7 @@ public function testEvaluateThrowsExpectationFailedExceptionWhenJsonIsValidButDo public function testToString(): void { - $jsonValue = \json_encode(['Mascott' => 'Tux']); + $jsonValue = json_encode(['Mascott' => 'Tux']); $constraint = new JsonMatches($jsonValue); $this->assertEquals('matches JSON string "' . $jsonValue . '"', $constraint->toString()); @@ -102,7 +104,7 @@ public function testFailErrorWithInvalidValueAndOther(): void try { $constraint->evaluate('{"Mascott"::}', '', false); - $this->fail(\sprintf('Expected %s to be thrown.', ExpectationFailedException::class)); + $this->fail(sprintf('Expected %s to be thrown.', ExpectationFailedException::class)); } catch (ExpectationFailedException $e) { $this->assertEquals( <<<'EOF' @@ -121,7 +123,7 @@ public function testFailErrorWithValidValueAndInvalidOther(): void try { $constraint->evaluate('{"Mascott":"Tux"}', '', false); - $this->fail(\sprintf('Expected %s to be thrown.', ExpectationFailedException::class)); + $this->fail(sprintf('Expected %s to be thrown.', ExpectationFailedException::class)); } catch (ExpectationFailedException $e) { $this->assertEquals( <<<'EOF' diff --git a/tests/unit/Framework/Constraint/LogicalAndTest.php b/tests/unit/Framework/Constraint/LogicalAndTest.php index ab3d58d1ea9..22da86ec13d 100644 --- a/tests/unit/Framework/Constraint/LogicalAndTest.php +++ b/tests/unit/Framework/Constraint/LogicalAndTest.php @@ -9,9 +9,19 @@ */ namespace PHPUnit\Framework\Constraint; +use function array_map; +use function array_sum; +use function implode; +use function sprintf; +use CountConstraint; +use FalsyConstraint; +use Generator; +use NamedConstraint; use PHPUnit\Framework\Exception; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; +use stdClass; +use TruthyConstraint; /** * @small @@ -21,15 +31,15 @@ final class LogicalAndTest extends ConstraintTestCase public function testSetConstraintsRejectsInvalidConstraint(): void { $constraints = [ - new \TruthyConstraint, - new \FalsyConstraint, - new \stdClass, + new TruthyConstraint, + new FalsyConstraint, + new stdClass, ]; $constraint = new LogicalAnd; $this->expectException(Exception::class); - $this->expectExceptionMessage(\sprintf( + $this->expectExceptionMessage(sprintf( 'All parameters to %s must be a constraint object.', LogicalAnd::class )); @@ -45,15 +55,15 @@ public function testCountReturnsCountOfComposedConstraints(): void 8, ]; - $constraints = \array_map(function (int $count) { - return \CountConstraint::fromCount($count); + $constraints = array_map(static function (int $count) { + return CountConstraint::fromCount($count); }, $counts); $constraint = new LogicalAnd; $constraint->setConstraints($constraints); - $expected = \array_sum($counts); + $expected = array_sum($counts); $this->assertSame($expected, $constraint->count()); } @@ -66,13 +76,13 @@ public function testToStringReturnsImplodedStringRepresentationOfComposedConstra 'is rich in unsaturated fats', ]; - $constraints = \array_map(function (string $name) { - return \NamedConstraint::fromName($name); + $constraints = array_map(static function (string $name) { + return NamedConstraint::fromName($name); }, $names); $constraint = LogicalAnd::fromConstraints(...$constraints); - $expected = \implode(' and ', $names); + $expected = implode(' and ', $names); $this->assertSame($expected, $constraint->toString()); } @@ -186,16 +196,16 @@ public function testEvaluateReturnsNothingIfAllOfTheComposedConstraintsEvaluateT $this->assertNull($constraint->evaluate('whatever')); } - public function providerFailingConstraints(): \Generator + public function providerFailingConstraints(): Generator { $values = [ 'single' => [ - new \FalsyConstraint, + new FalsyConstraint, ], 'multiple' => [ - new \TruthyConstraint, - new \FalsyConstraint, - new \TruthyConstraint, + new TruthyConstraint, + new FalsyConstraint, + new TruthyConstraint, ], ]; @@ -206,16 +216,16 @@ public function providerFailingConstraints(): \Generator } } - public function providerSucceedingConstraints(): \Generator + public function providerSucceedingConstraints(): Generator { $values = [ 'single' => [ - new \TruthyConstraint, + new TruthyConstraint, ], 'multiple' => [ - new \TruthyConstraint, - new \TruthyConstraint, - new \TruthyConstraint, + new TruthyConstraint, + new TruthyConstraint, + new TruthyConstraint, ], ]; @@ -228,9 +238,9 @@ public function providerSucceedingConstraints(): \Generator private function stringify(array $constraints): string { - return \implode( + return implode( ' and ', - \array_map(function (Constraint $constraint) { + array_map(static function (Constraint $constraint) { return $constraint->toString(); }, $constraints) ); diff --git a/tests/unit/Framework/Constraint/LogicalOrTest.php b/tests/unit/Framework/Constraint/LogicalOrTest.php index 7c090ca4389..dec716d53c2 100644 --- a/tests/unit/Framework/Constraint/LogicalOrTest.php +++ b/tests/unit/Framework/Constraint/LogicalOrTest.php @@ -9,8 +9,17 @@ */ namespace PHPUnit\Framework\Constraint; +use function array_map; +use function array_sum; +use function implode; +use CountConstraint; +use FalsyConstraint; +use Generator; +use NamedConstraint; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; +use stdClass; +use TruthyConstraint; /** * @small @@ -20,14 +29,14 @@ final class LogicalOrTest extends ConstraintTestCase public function testSetConstraintsDecoratesNonConstraintWithIsEqual(): void { $constraints = [ - new \stdClass, + new stdClass, ]; $constraint = new LogicalOr; $constraint->setConstraints($constraints); - $this->assertTrue($constraint->evaluate(new \stdClass, '', true)); + $this->assertTrue($constraint->evaluate(new stdClass, '', true)); } public function testCountReturnsCountOfComposedConstraints(): void @@ -38,15 +47,15 @@ public function testCountReturnsCountOfComposedConstraints(): void 8, ]; - $constraints = \array_map(function (int $count) { - return \CountConstraint::fromCount($count); + $constraints = array_map(static function (int $count) { + return CountConstraint::fromCount($count); }, $counts); $constraint = new LogicalOr; $constraint->setConstraints($constraints); - $expected = \array_sum($counts); + $expected = array_sum($counts); $this->assertSame($expected, $constraint->count()); } @@ -59,15 +68,15 @@ public function testToStringReturnsImplodedStringRepresentationOfComposedConstra 'is rich in unsaturated fats', ]; - $constraints = \array_map(function (string $name) { - return \NamedConstraint::fromName($name); + $constraints = array_map(static function (string $name) { + return NamedConstraint::fromName($name); }, $names); $constraint = new LogicalOr; $constraint->setConstraints($constraints); - $expected = \implode(' or ', $names); + $expected = implode(' or ', $names); $this->assertSame($expected, $constraint->toString()); } @@ -179,18 +188,18 @@ public function testEvaluateReturnsNothingIfAnyOfTheComposedConstraintsEvaluateT $this->assertNull($constraint->evaluate('whatever')); } - public function providerFailingConstraints(): \Generator + public function providerFailingConstraints(): Generator { $values = [ 'single' => [ - new \FalsyConstraint, - new \FalsyConstraint, - new \FalsyConstraint, + new FalsyConstraint, + new FalsyConstraint, + new FalsyConstraint, ], 'multiple' => [ - new \FalsyConstraint, - new \FalsyConstraint, - new \FalsyConstraint, + new FalsyConstraint, + new FalsyConstraint, + new FalsyConstraint, ], ]; @@ -201,16 +210,16 @@ public function providerFailingConstraints(): \Generator } } - public function providerSucceedingConstraints(): \Generator + public function providerSucceedingConstraints(): Generator { $values = [ 'single' => [ - new \TruthyConstraint, + new TruthyConstraint, ], 'multiple' => [ - new \FalsyConstraint, - new \TruthyConstraint, - new \FalsyConstraint, + new FalsyConstraint, + new TruthyConstraint, + new FalsyConstraint, ], ]; @@ -223,9 +232,9 @@ public function providerSucceedingConstraints(): \Generator private function stringify(array $constraints): string { - return \implode( + return implode( ' or ', - \array_map(function (Constraint $constraint) { + array_map(static function (Constraint $constraint) { return $constraint->toString(); }, $constraints) ); diff --git a/tests/unit/Framework/Constraint/LogicalXorTest.php b/tests/unit/Framework/Constraint/LogicalXorTest.php index fd4d7266394..6d13c4feb80 100644 --- a/tests/unit/Framework/Constraint/LogicalXorTest.php +++ b/tests/unit/Framework/Constraint/LogicalXorTest.php @@ -9,6 +9,8 @@ */ namespace Framework\Constraint; +use function array_fill; +use function array_map; use PHPUnit\Framework\Constraint\Constraint; use PHPUnit\Framework\Constraint\LogicalXor; use PHPUnit\Framework\TestCase; @@ -23,7 +25,7 @@ public function testFromConstraintsReturnsConstraint(): void $other = 'Foo'; $count = 5; - $constraints = \array_map(function () use ($other) { + $constraints = array_map(function () use ($other) { static $count = 0; $constraint = $this->getMockBuilder(Constraint::class)->getMock(); @@ -37,7 +39,7 @@ public function testFromConstraintsReturnsConstraint(): void $count++; return $constraint; - }, \array_fill(0, $count, null)); + }, array_fill(0, $count, null)); $constraint = LogicalXor::fromConstraints(...$constraints); diff --git a/tests/unit/Framework/Constraint/ObjectHasAttributeTest.php b/tests/unit/Framework/Constraint/ObjectHasAttributeTest.php index f4bb13679c7..9750b5621ec 100644 --- a/tests/unit/Framework/Constraint/ObjectHasAttributeTest.php +++ b/tests/unit/Framework/Constraint/ObjectHasAttributeTest.php @@ -9,8 +9,10 @@ */ namespace PHPUnit\Framework\Constraint; +use ClassWithNonPublicAttributes; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; +use stdClass; /** * @small @@ -21,13 +23,13 @@ public function testConstraintObjectHasAttribute(): void { $constraint = new ObjectHasAttribute('privateAttribute'); - $this->assertTrue($constraint->evaluate(new \ClassWithNonPublicAttributes, '', true)); - $this->assertFalse($constraint->evaluate(new \stdClass, '', true)); + $this->assertTrue($constraint->evaluate(new ClassWithNonPublicAttributes, '', true)); + $this->assertFalse($constraint->evaluate(new stdClass, '', true)); $this->assertEquals('has attribute "privateAttribute"', $constraint->toString()); $this->assertCount(1, $constraint); try { - $constraint->evaluate(new \stdClass); + $constraint->evaluate(new stdClass); } catch (ExpectationFailedException $e) { $this->assertEquals( <<<'EOF' @@ -49,7 +51,7 @@ public function testConstraintObjectHasAttribute2(): void $constraint = new ObjectHasAttribute('privateAttribute'); try { - $constraint->evaluate(new \stdClass, 'custom message'); + $constraint->evaluate(new stdClass, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<<'EOF' diff --git a/tests/unit/Framework/Constraint/SameSizeTest.php b/tests/unit/Framework/Constraint/SameSizeTest.php index 877c6b80536..1c3e196b39b 100644 --- a/tests/unit/Framework/Constraint/SameSizeTest.php +++ b/tests/unit/Framework/Constraint/SameSizeTest.php @@ -9,8 +9,10 @@ */ namespace PHPUnit\Framework\Constraint; +use ArrayObject; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; +use TestIterator; /** * @small @@ -27,18 +29,18 @@ public function testConstraintSameSizeWithAnArray(): void public function testConstraintSameSizeWithAnIteratorWhichDoesNotImplementCountable(): void { - $constraint = new SameSize(new \TestIterator([1, 2, 3, 4, 5])); + $constraint = new SameSize(new TestIterator([1, 2, 3, 4, 5])); - $this->assertTrue($constraint->evaluate(new \TestIterator([6, 7, 8, 9, 10]), '', true)); - $this->assertFalse($constraint->evaluate(new \TestIterator([1, 2, 3, 4]), '', true)); + $this->assertTrue($constraint->evaluate(new TestIterator([6, 7, 8, 9, 10]), '', true)); + $this->assertFalse($constraint->evaluate(new TestIterator([1, 2, 3, 4]), '', true)); } public function testConstraintSameSizeWithAnObjectImplementingCountable(): void { - $constraint = new SameSize(new \ArrayObject([1, 2, 3, 4, 5])); + $constraint = new SameSize(new ArrayObject([1, 2, 3, 4, 5])); - $this->assertTrue($constraint->evaluate(new \ArrayObject([6, 7, 8, 9, 10]), '', true)); - $this->assertFalse($constraint->evaluate(new \ArrayObject([1, 2, 3, 4]), '', true)); + $this->assertTrue($constraint->evaluate(new ArrayObject([6, 7, 8, 9, 10]), '', true)); + $this->assertFalse($constraint->evaluate(new ArrayObject([1, 2, 3, 4]), '', true)); } public function testConstraintSameSizeFailing(): void diff --git a/tests/unit/Framework/Constraint/StringMatchesFormatDescriptionTest.php b/tests/unit/Framework/Constraint/StringMatchesFormatDescriptionTest.php index 4747023753f..91bc69dc1ae 100644 --- a/tests/unit/Framework/Constraint/StringMatchesFormatDescriptionTest.php +++ b/tests/unit/Framework/Constraint/StringMatchesFormatDescriptionTest.php @@ -9,6 +9,7 @@ */ namespace PHPUnit\Framework\Constraint; +use const DIRECTORY_SEPARATOR; use PHPUnit\Framework\ExpectationFailedException; /** @@ -23,9 +24,9 @@ public function testConstraintStringMatchesDirectorySeparator(): void $this->assertFalse($constraint->evaluate('**', '', true)); $this->assertFalse($constraint->evaluate('*a*', '', true)); - $this->assertTrue($constraint->evaluate('*' . \DIRECTORY_SEPARATOR . '*', '', true)); + $this->assertTrue($constraint->evaluate('*' . DIRECTORY_SEPARATOR . '*', '', true)); - $this->assertEquals('matches PCRE pattern "/^\*\\' . \DIRECTORY_SEPARATOR . '\*$/s"', $constraint->toString()); + $this->assertEquals('matches PCRE pattern "/^\*\\' . DIRECTORY_SEPARATOR . '\*$/s"', $constraint->toString()); $this->assertCount(1, $constraint); } @@ -200,7 +201,7 @@ public function testConstraintStringMatchesEscapedPercent(): void { $constraint = new StringMatchesFormatDescription('%%,%%e,%%s,%%S,%%a,%%A,%%w,%%i,%%d,%%x,%%f,%%c,%%Z,%%%%,%%'); - $this->assertFalse($constraint->evaluate('%%,%' . \DIRECTORY_SEPARATOR . ',%*,%*,%*,%*,% ,%0,%0,%0f0f0f,%1.0,%*,%%Z,%%%%,%%', '', true)); + $this->assertFalse($constraint->evaluate('%%,%' . DIRECTORY_SEPARATOR . ',%*,%*,%*,%*,% ,%0,%0,%0f0f0f,%1.0,%*,%%Z,%%%%,%%', '', true)); $this->assertTrue($constraint->evaluate('%,%e,%s,%S,%a,%A,%w,%i,%d,%x,%f,%c,%Z,%%,%', '', true)); $this->assertEquals('matches PCRE pattern "/^%,%e,%s,%S,%a,%A,%w,%i,%d,%x,%f,%c,%Z,%%,%$/s"', $constraint->toString()); $this->assertCount(1, $constraint); @@ -211,8 +212,8 @@ public function testConstraintStringMatchesEscapedPercentThenPlaceholder(): void $constraint = new StringMatchesFormatDescription('%%%e,%%%s,%%%S,%%%a,%%%A,%%%w,%%%i,%%%d,%%%x,%%%f,%%%c'); $this->assertFalse($constraint->evaluate('%%e,%%s,%%S,%%a,%%A,%%w,%%i,%%d,%%x,%%f,%%c', '', true)); - $this->assertTrue($constraint->evaluate('%' . \DIRECTORY_SEPARATOR . ',%*,%*,%*,%*,% ,%0,%0,%0f0f0f,%1.0,%*', '', true)); - $this->assertEquals('matches PCRE pattern "/^%\\' . \DIRECTORY_SEPARATOR . ',%[^\r\n]+,%[^\r\n]*,%.+,%.*,%\s*,%[+-]?\d+,%\d+,%[0-9a-fA-F]+,%[+-]?\.?\d+\.?\d*(?:[Ee][+-]?\d+)?,%.$/s"', $constraint->toString()); + $this->assertTrue($constraint->evaluate('%' . DIRECTORY_SEPARATOR . ',%*,%*,%*,%*,% ,%0,%0,%0f0f0f,%1.0,%*', '', true)); + $this->assertEquals('matches PCRE pattern "/^%\\' . DIRECTORY_SEPARATOR . ',%[^\r\n]+,%[^\r\n]*,%.+,%.*,%\s*,%[+-]?\d+,%\d+,%[0-9a-fA-F]+,%[+-]?\.?\d+\.?\d*(?:[Ee][+-]?\d+)?,%.$/s"', $constraint->toString()); $this->assertCount(1, $constraint); } diff --git a/tests/unit/Framework/Constraint/TraversableContainsTest.php b/tests/unit/Framework/Constraint/TraversableContainsTest.php index c51d095c6c2..5c524195a4f 100644 --- a/tests/unit/Framework/Constraint/TraversableContainsTest.php +++ b/tests/unit/Framework/Constraint/TraversableContainsTest.php @@ -11,6 +11,8 @@ use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\TestFailure; +use SplObjectStorage; +use stdClass; /** * @small @@ -24,6 +26,9 @@ public function testConstraintTraversableCheckForNonObjectIdentityForDefaultCase $this->assertTrue($constraint->evaluate(['foo'], '', true)); } + /** + * @requires PHP < 8.0 + */ public function testConstraintTraversableCheckForObjectIdentityForDefaultCase(): void { $constraint = new TraversableContains('foo'); @@ -128,7 +133,7 @@ public function testConstraintTraversableEvaluateMethodWithFailExampleWithCustom public function testConstraintTraversableToStringMethodsWithStdClass(): void { - $object = new \stdClass; + $object = new stdClass; $constraint = new TraversableContains($object); $this->assertStringMatchesFormat('contains stdClass Object &%s ()', $constraint->toString()); } @@ -142,10 +147,10 @@ public function testConstraintTraversableToStringMethods(): void public function testConstraintTraversableToStringMethodsWithSplObjectStorage(): void { - $object = new \stdClass; + $object = new stdClass; $constraint = new TraversableContains($object); - $storage = new \SplObjectStorage; + $storage = new SplObjectStorage; $this->assertFalse($constraint->evaluate($storage, '', true)); $storage->attach($object); @@ -154,11 +159,11 @@ public function testConstraintTraversableToStringMethodsWithSplObjectStorage(): public function testConstraintTraversableStdClassForFailSplObjectStorage(): void { - $object = new \stdClass; + $object = new stdClass; $constraint = new TraversableContains($object); try { - $constraint->evaluate(new \SplObjectStorage); + $constraint->evaluate(new SplObjectStorage); } catch (ExpectationFailedException $e) { $this->assertStringMatchesFormat( <<<'EOF' @@ -177,11 +182,11 @@ public function testConstraintTraversableStdClassForFailSplObjectStorage(): void public function testConstraintTraversableStdClassForFailSplObjectStorageWithCustomMessage(): void { - $object = new \stdClass; + $object = new stdClass; $constraint = new TraversableContains($object); try { - $constraint->evaluate(new \SplObjectStorage, 'custom message'); + $constraint->evaluate(new SplObjectStorage, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertStringMatchesFormat( <<<'EOF' diff --git a/tests/unit/Framework/ConstraintTest.php b/tests/unit/Framework/ConstraintTest.php index d76f075df48..755c8a1d33a 100644 --- a/tests/unit/Framework/ConstraintTest.php +++ b/tests/unit/Framework/ConstraintTest.php @@ -9,10 +9,17 @@ */ namespace PHPUnit\Framework; +use function preg_replace; +use ArrayObject; +use ClassWithNonPublicAttributes; +use Countable; +use DummyException; use PHPUnit\Framework\Constraint\Count; use PHPUnit\Framework\Constraint\SameSize; use PHPUnit\Framework\Constraint\TraversableContains; use PHPUnit\Util\Filter; +use stdClass; +use TestIterator; /** * @small @@ -379,8 +386,8 @@ public function testConstraintIsNotEqual2(): void public function testConstraintIsNotIdentical(): void { - $a = new \stdClass; - $b = new \stdClass; + $a = new stdClass; + $b = new stdClass; $constraint = Assert::logicalNot( Assert::identicalTo($a) @@ -411,7 +418,7 @@ public function testConstraintIsNotIdentical(): void public function testConstraintIsNotIdentical2(): void { - $a = new \stdClass; + $a = new stdClass; $constraint = Assert::logicalNot( Assert::identicalTo($a) @@ -465,18 +472,18 @@ public function testConstraintIsInstanceOf(): void { $constraint = Assert::isInstanceOf(\Exception::class); - $this->assertFalse($constraint->evaluate(new \stdClass, '', true)); + $this->assertFalse($constraint->evaluate(new stdClass, '', true)); $this->assertTrue($constraint->evaluate(new \Exception, '', true)); $this->assertEquals('is instance of class "Exception"', $constraint->toString()); $this->assertCount(1, $constraint); - $interfaceConstraint = Assert::isInstanceOf(\Countable::class); - $this->assertFalse($interfaceConstraint->evaluate(new \stdClass, '', true)); - $this->assertTrue($interfaceConstraint->evaluate(new \ArrayObject, '', true)); + $interfaceConstraint = Assert::isInstanceOf(Countable::class); + $this->assertFalse($interfaceConstraint->evaluate(new stdClass, '', true)); + $this->assertTrue($interfaceConstraint->evaluate(new ArrayObject, '', true)); $this->assertEquals('is instance of interface "Countable"', $interfaceConstraint->toString()); try { - $constraint->evaluate(new \stdClass); + $constraint->evaluate(new stdClass); } catch (ExpectationFailedException $e) { $this->assertEquals( <<<'EOF' @@ -498,7 +505,7 @@ public function testConstraintIsInstanceOf2(): void $constraint = Assert::isInstanceOf(\Exception::class); try { - $constraint->evaluate(new \stdClass, 'custom message'); + $constraint->evaluate(new stdClass, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<<'EOF' @@ -519,16 +526,16 @@ public function testConstraintIsInstanceOf2(): void public function testConstraintIsNotInstanceOf(): void { $constraint = Assert::logicalNot( - Assert::isInstanceOf(\stdClass::class) + Assert::isInstanceOf(stdClass::class) ); - $this->assertFalse($constraint->evaluate(new \stdClass, '', true)); + $this->assertFalse($constraint->evaluate(new stdClass, '', true)); $this->assertTrue($constraint->evaluate(new Exception, '', true)); $this->assertEquals('is not instance of class "stdClass"', $constraint->toString()); $this->assertCount(1, $constraint); try { - $constraint->evaluate(new \stdClass); + $constraint->evaluate(new stdClass); } catch (ExpectationFailedException $e) { $this->assertEquals( <<<'EOF' @@ -548,11 +555,11 @@ public function testConstraintIsNotInstanceOf(): void public function testConstraintIsNotInstanceOf2(): void { $constraint = Assert::logicalNot( - Assert::isInstanceOf(\stdClass::class) + Assert::isInstanceOf(stdClass::class) ); try { - $constraint->evaluate(new \stdClass, 'custom message'); + $constraint->evaluate(new stdClass, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<<'EOF' @@ -842,13 +849,13 @@ public function testConstraintClassNotHasAttribute(): void Assert::classHasAttribute('privateAttribute') ); - $this->assertTrue($constraint->evaluate(\stdClass::class, '', true)); - $this->assertFalse($constraint->evaluate(\ClassWithNonPublicAttributes::class, '', true)); + $this->assertTrue($constraint->evaluate(stdClass::class, '', true)); + $this->assertFalse($constraint->evaluate(ClassWithNonPublicAttributes::class, '', true)); $this->assertEquals('does not have attribute "privateAttribute"', $constraint->toString()); $this->assertCount(1, $constraint); try { - $constraint->evaluate(\ClassWithNonPublicAttributes::class); + $constraint->evaluate(ClassWithNonPublicAttributes::class); } catch (ExpectationFailedException $e) { $this->assertEquals( <<<'EOF' @@ -872,7 +879,7 @@ public function testConstraintClassNotHasAttribute2(): void ); try { - $constraint->evaluate(\ClassWithNonPublicAttributes::class, 'custom message'); + $constraint->evaluate(ClassWithNonPublicAttributes::class, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<<'EOF' @@ -896,13 +903,13 @@ public function testConstraintClassNotHasStaticAttribute(): void Assert::classHasStaticAttribute('privateStaticAttribute') ); - $this->assertTrue($constraint->evaluate(\stdClass::class, '', true)); - $this->assertFalse($constraint->evaluate(\ClassWithNonPublicAttributes::class, '', true)); + $this->assertTrue($constraint->evaluate(stdClass::class, '', true)); + $this->assertFalse($constraint->evaluate(ClassWithNonPublicAttributes::class, '', true)); $this->assertEquals('does not have static attribute "privateStaticAttribute"', $constraint->toString()); $this->assertCount(1, $constraint); try { - $constraint->evaluate(\ClassWithNonPublicAttributes::class); + $constraint->evaluate(ClassWithNonPublicAttributes::class); } catch (ExpectationFailedException $e) { $this->assertEquals( <<<'EOF' @@ -926,7 +933,7 @@ public function testConstraintClassNotHasStaticAttribute2(): void ); try { - $constraint->evaluate(\ClassWithNonPublicAttributes::class, 'custom message'); + $constraint->evaluate(ClassWithNonPublicAttributes::class, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<<'EOF' @@ -950,13 +957,13 @@ public function testConstraintObjectNotHasAttribute(): void Assert::objectHasAttribute('privateAttribute') ); - $this->assertTrue($constraint->evaluate(new \stdClass, '', true)); - $this->assertFalse($constraint->evaluate(new \ClassWithNonPublicAttributes, '', true)); + $this->assertTrue($constraint->evaluate(new stdClass, '', true)); + $this->assertFalse($constraint->evaluate(new ClassWithNonPublicAttributes, '', true)); $this->assertEquals('does not have attribute "privateAttribute"', $constraint->toString()); $this->assertCount(1, $constraint); try { - $constraint->evaluate(new \ClassWithNonPublicAttributes); + $constraint->evaluate(new ClassWithNonPublicAttributes); } catch (ExpectationFailedException $e) { $this->assertEquals( <<<'EOF' @@ -980,7 +987,7 @@ public function testConstraintObjectNotHasAttribute2(): void ); try { - $constraint->evaluate(new \ClassWithNonPublicAttributes, 'custom message'); + $constraint->evaluate(new ClassWithNonPublicAttributes, 'custom message'); } catch (ExpectationFailedException $e) { $this->assertEquals( <<<'EOF' @@ -1320,16 +1327,16 @@ public function testConstraintCountWithAnIteratorWhichDoesNotImplementCountable( { $constraint = new Count(5); - $this->assertTrue($constraint->evaluate(new \TestIterator([1, 2, 3, 4, 5]), '', true)); - $this->assertFalse($constraint->evaluate(new \TestIterator([1, 2, 3, 4]), '', true)); + $this->assertTrue($constraint->evaluate(new TestIterator([1, 2, 3, 4, 5]), '', true)); + $this->assertFalse($constraint->evaluate(new TestIterator([1, 2, 3, 4]), '', true)); } public function testConstraintCountWithAnObjectImplementingCountable(): void { $constraint = new Count(5); - $this->assertTrue($constraint->evaluate(new \ArrayObject([1, 2, 3, 4, 5]), '', true)); - $this->assertFalse($constraint->evaluate(new \ArrayObject([1, 2, 3, 4]), '', true)); + $this->assertTrue($constraint->evaluate(new ArrayObject([1, 2, 3, 4, 5]), '', true)); + $this->assertFalse($constraint->evaluate(new ArrayObject([1, 2, 3, 4]), '', true)); } public function testConstraintCountFailing(): void @@ -1405,7 +1412,7 @@ public function testConstraintNotSameSizeFailing(): void public function testConstraintException(): void { $constraint = new Constraint\Exception('FoobarException'); - $exception = new \DummyException('Test'); + $exception = new DummyException('Test'); $stackTrace = Filter::getFilteredStacktrace($exception); try { @@ -1428,7 +1435,7 @@ public function testConstraintException(): void } /** - * Removes spaces in front of newlines + * Removes spaces in front of newlines. * * @param string $string * @@ -1436,6 +1443,6 @@ public function testConstraintException(): void */ private function trimnl($string) { - return \preg_replace('/[ ]*\n/', "\n", $string); + return preg_replace('/[ ]*\n/', "\n", $string); } } diff --git a/tests/unit/Framework/Exception/ExceptionTest.php b/tests/unit/Framework/Exception/ExceptionTest.php index 64ae6cb616b..d38e7444af5 100644 --- a/tests/unit/Framework/Exception/ExceptionTest.php +++ b/tests/unit/Framework/Exception/ExceptionTest.php @@ -13,16 +13,13 @@ class ExceptionTest extends TestCase { public function testExceptionSleep(): void { - $exception = new Exception(); + $actual = (new Exception)->__sleep(); - $expectedArray = [ - 'serializableTrace', - 'message', - 'code', - 'file', - 'line', - ]; - - $this->assertSame($expectedArray, $exception->__sleep()); + $this->assertCount(5, $actual); + $this->assertContains('serializableTrace', $actual); + $this->assertContains('message', $actual); + $this->assertContains('code', $actual); + $this->assertContains('file', $actual); + $this->assertContains('line', $actual); } } diff --git a/tests/unit/Framework/ExceptionWrapperTest.php b/tests/unit/Framework/ExceptionWrapperTest.php index 2d4a1196f1d..b14a3bdc8b0 100644 --- a/tests/unit/Framework/ExceptionWrapperTest.php +++ b/tests/unit/Framework/ExceptionWrapperTest.php @@ -9,6 +9,10 @@ */ namespace PHPUnit\Framework; +use function print_r; +use BadFunctionCallException; +use Exception; + /** * @small */ @@ -19,10 +23,10 @@ final class ExceptionWrapperTest extends TestCase */ public function testGetOriginalException(): void { - $e = new \BadFunctionCallException('custom class exception'); + $e = new BadFunctionCallException('custom class exception'); $wrapper = new ExceptionWrapper($e); - $this->assertInstanceOf(\BadFunctionCallException::class, $wrapper->getOriginalException()); + $this->assertInstanceOf(BadFunctionCallException::class, $wrapper->getOriginalException()); } /** @@ -30,10 +34,10 @@ public function testGetOriginalException(): void */ public function testGetOriginalExceptionWithPrevious(): void { - $e = new \BadFunctionCallException('custom class exception', 0, new \Exception('previous')); + $e = new BadFunctionCallException('custom class exception', 0, new Exception('previous')); $wrapper = new ExceptionWrapper($e); - $this->assertInstanceOf(\BadFunctionCallException::class, $wrapper->getOriginalException()); + $this->assertInstanceOf(BadFunctionCallException::class, $wrapper->getOriginalException()); } /** @@ -41,13 +45,13 @@ public function testGetOriginalExceptionWithPrevious(): void */ public function testNoOriginalExceptionInStacktrace(): void { - $e = new \BadFunctionCallException('custom class exception'); + $e = new BadFunctionCallException('custom class exception'); $wrapper = new ExceptionWrapper($e); // Replace the only mention of "BadFunctionCallException" in wrapper $wrapper->setClassName('MyException'); - $data = \print_r($wrapper, true); + $data = print_r($wrapper, true); $this->assertStringNotContainsString( 'BadFunctionCallException', diff --git a/tests/unit/Framework/IncompleteTestCaseTest.php b/tests/unit/Framework/IncompleteTestCaseTest.php index cdb503c653f..cb000932fcb 100644 --- a/tests/unit/Framework/IncompleteTestCaseTest.php +++ b/tests/unit/Framework/IncompleteTestCaseTest.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Framework; +use function array_shift; +use function sprintf; use PHPUnit\Runner\BaseTestRunner; final class IncompleteTestCaseTest extends TestCase @@ -33,7 +35,7 @@ public function testGetNameReturnsClassAndMethodName(): void $methodName ); - $name = \sprintf( + $name = sprintf( '%s::%s', $className, $methodName @@ -74,9 +76,9 @@ public function testRunMarksTestAsIncomplete(): void $failures = $result->notImplemented(); - $failure = \array_shift($failures); + $failure = array_shift($failures); - $name = \sprintf( + $name = sprintf( '%s::%s', $className, $methodName diff --git a/tests/unit/Framework/MockObject/GeneratorTest.php b/tests/unit/Framework/MockObject/GeneratorTest.php index 4153846963f..a8c0ed50e3b 100644 --- a/tests/unit/Framework/MockObject/GeneratorTest.php +++ b/tests/unit/Framework/MockObject/GeneratorTest.php @@ -14,14 +14,14 @@ /** * @covers \PHPUnit\Framework\MockObject\Generator * - * @uses \PHPUnit\Framework\MockObject\InvocationHandler * @uses \PHPUnit\Framework\MockObject\Builder\InvocationMocker * @uses \PHPUnit\Framework\MockObject\Invocation + * @uses \PHPUnit\Framework\MockObject\InvocationHandler * @uses \PHPUnit\Framework\MockObject\Matcher * @uses \PHPUnit\Framework\MockObject\Rule\InvocationOrder + * @uses \PHPUnit\Framework\MockObject\Rule\InvokedCount * @uses \PHPUnit\Framework\MockObject\Rule\MethodName * @uses \PHPUnit\Framework\MockObject\Stub\ReturnStub - * @uses \PHPUnit\Framework\MockObject\Rule\InvokedCount * * @small */ diff --git a/tests/unit/Framework/MockObject/InvocationHandlerTest.php b/tests/unit/Framework/MockObject/InvocationHandlerTest.php index 59e16b6734a..a5a17f9b670 100644 --- a/tests/unit/Framework/MockObject/InvocationHandlerTest.php +++ b/tests/unit/Framework/MockObject/InvocationHandlerTest.php @@ -10,16 +10,18 @@ namespace PHPUnit\Framework\MockObject; use PHPUnit\Framework\TestCase; +use RuntimeException; +use StringableClass; class InvocationHandlerTest extends TestCase { public function testExceptionThrownIn__ToStringIsDeferred(): void { - $mock = $this->createMock(\StringableClass::class); + $mock = $this->createMock(StringableClass::class); $mock->method('__toString') - ->willThrowException(new \RuntimeException('planned error')); + ->willThrowException(new RuntimeException('planned error')); - $this->expectException(\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('planned error'); $mock->__toString(); } diff --git a/tests/unit/Framework/MockObject/MatcherTest.php b/tests/unit/Framework/MockObject/MatcherTest.php index 48ebb6b3fbe..57e943260a6 100644 --- a/tests/unit/Framework/MockObject/MatcherTest.php +++ b/tests/unit/Framework/MockObject/MatcherTest.php @@ -9,11 +9,13 @@ */ namespace PHPUnit\Framework\MockObject; +use Exception; use PHPUnit\Framework\ExpectationFailedException; use PHPUnit\Framework\MockObject\Rule\InvocationOrder; use PHPUnit\Framework\MockObject\Rule\MethodName; use PHPUnit\Framework\MockObject\Rule\ParametersRule; use PHPUnit\Framework\TestCase; +use stdClass; /** * @covers \PHPUnit\Framework\MockObject\Matcher @@ -23,7 +25,7 @@ class MatcherTest extends TestCase public function testParameterRuleIsAppliedToInvocation(): void { $invocationMatcher = $this->createStub(InvocationOrder::class); - $invocation = new Invocation('Foo', 'bar', [], 'void', new \stdClass); + $invocation = new Invocation('Foo', 'bar', [], 'void', new stdClass); $parameterRule = $this->createMock(ParametersRule::class); $parameterRule->expects($this->once()) @@ -40,7 +42,7 @@ public function testParameterRuleIsAppliedToInvocation(): void public function testParametersRuleTriggersFailOfInvocation(): void { $invocationMatcher = $this->createStub(InvocationOrder::class); - $invocation = new Invocation('Foo', 'bar', [], 'void', new \stdClass); + $invocation = new Invocation('Foo', 'bar', [], 'void', new stdClass); $parameterRule = $this->createStub(ParametersRule::class); $parameterRule->method('apply') @@ -60,13 +62,13 @@ public function testParameterRuleDoesNotInfluenceMatches(): void $invocationMatcher = $this->createStub(InvocationOrder::class); $invocationMatcher->method('matches') ->willReturn(true); - $invocation = new Invocation('Foo', 'bar', [], 'void', new \stdClass); + $invocation = new Invocation('Foo', 'bar', [], 'void', new stdClass); $matcher = new Matcher($invocationMatcher); $matcher->setMethodNameRule(new MethodName('bar')); $parameterRule = $this->createStub(ParametersRule::class); $parameterRule->method('apply') - ->willThrowException(new \Exception('This method should not have been called.')); + ->willThrowException(new Exception('This method should not have been called.')); $matcher->setParametersRule($parameterRule); $this->assertTrue($matcher->matches($invocation)); @@ -75,7 +77,7 @@ public function testParameterRuleDoesNotInfluenceMatches(): void public function testStubIsNotInvokedIfParametersRuleIsViolated(): void { $invocationMatcher = $this->createStub(InvocationOrder::class); - $invocation = new Invocation('Foo', 'bar', [], 'void', new \stdClass); + $invocation = new Invocation('Foo', 'bar', [], 'void', new stdClass); $stub = $this->createMock(Stub\Stub::class); $stub->expects($this->never()) @@ -99,7 +101,7 @@ public function testStubIsNotInvokedIfParametersRuleIsViolated(): void public function testStubIsInvokedIfAllMatchersAndRulesApply(): void { $invocationMatcher = $this->createStub(InvocationOrder::class); - $invocation = new Invocation('Foo', 'bar', [], 'void', new \stdClass); + $invocation = new Invocation('Foo', 'bar', [], 'void', new stdClass); $stub = $this->createMock(Stub\Stub::class); $stub->expects($this->once()) diff --git a/tests/unit/Framework/MockObject/MockClassTest.php b/tests/unit/Framework/MockObject/MockClassTest.php index 1f336bb53e1..9c7c2e6f2f6 100644 --- a/tests/unit/Framework/MockObject/MockClassTest.php +++ b/tests/unit/Framework/MockObject/MockClassTest.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Framework\MockObject; +use function class_exists; +use function file_get_contents; use PHPUnit\Framework\TestCase; use PHPUnit\TestFixture\MockObject\MockClassWithConfigurableMethods; use SebastianBergmann\Type\Type; @@ -21,10 +23,10 @@ public function testGenerateClassFromSource(): void $file = __DIR__ . '/../../../_files/mock-object/MockClassGenerated.tpl'; - $mockClass = new MockClass(\file_get_contents($file), $mockName, []); + $mockClass = new MockClass(file_get_contents($file), $mockName, []); $mockClass->generate(); - $this->assertTrue(\class_exists($mockName)); + $this->assertTrue(class_exists($mockName)); } public function testGenerateReturnsNameOfGeneratedClass(): void diff --git a/tests/unit/Framework/MockObject/MockMethodTest.php b/tests/unit/Framework/MockObject/MockMethodTest.php index 4802da74e90..351aacb05d6 100644 --- a/tests/unit/Framework/MockObject/MockMethodTest.php +++ b/tests/unit/Framework/MockObject/MockMethodTest.php @@ -11,6 +11,8 @@ use PHPUnit\Framework\TestCase; use PHPUnit\TestFixture\MockObject\ClassWithoutParentButParentReturnType; +use ReflectionClass; +use RuntimeException; use SebastianBergmann\Type\UnknownType; /** @@ -42,9 +44,9 @@ public function testGetNameReturnsMethodName(): void */ public function testFailWhenReturnTypeIsParentButThereIsNoParentClass(): void { - $class = new \ReflectionClass(ClassWithoutParentButParentReturnType::class); + $class = new ReflectionClass(ClassWithoutParentButParentReturnType::class); - $this->expectException(\RuntimeException::class); + $this->expectException(RuntimeException::class); MockMethod::fromReflection($class->getMethod('foo'), false, false); } } diff --git a/tests/unit/Framework/MockObject/MockObjectTest.php b/tests/unit/Framework/MockObject/MockObjectTest.php index 8622cb20b1c..1868dbc4c28 100644 --- a/tests/unit/Framework/MockObject/MockObjectTest.php +++ b/tests/unit/Framework/MockObject/MockObjectTest.php @@ -589,7 +589,7 @@ public function testObjectMethodCallWithArgumentCloningEnabled(): void ->method('doSomethingElse') ->will( $this->returnCallback( - function () use (&$actualArguments): void { + static function () use (&$actualArguments): void { $actualArguments = \func_get_args(); } ) @@ -617,7 +617,7 @@ public function testObjectMethodCallWithArgumentCloningDisabled(): void ->method('doSomethingElse') ->will( $this->returnCallback( - function () use (&$actualArguments): void { + static function () use (&$actualArguments): void { $actualArguments = \func_get_args(); } ) @@ -812,7 +812,7 @@ public function testWithAnythingInsteadOfWithAnyParameters(): void } /** - * See https://github.com/sebastianbergmann/phpunit-mock-objects/issues/81 + * See https://github.com/sebastianbergmann/phpunit-mock-objects/issues/81. */ public function testMockArgumentsPassedByReference(): void { @@ -834,7 +834,7 @@ public function testMockArgumentsPassedByReference(): void } /** - * See https://github.com/sebastianbergmann/phpunit-mock-objects/issues/81 + * See https://github.com/sebastianbergmann/phpunit-mock-objects/issues/81. */ public function testMockArgumentsPassedByReference2(): void { @@ -846,7 +846,7 @@ public function testMockArgumentsPassedByReference2(): void $foo->expects($this->any()) ->method('bar') ->will($this->returnCallback( - function (&$a, &$b, $c): void { + static function (&$a, &$b, $c): void { $b = 1; } )); @@ -976,6 +976,7 @@ public function testInvokingStubbedStaticMethodRaisesException(): void /** * @see https://github.com/sebastianbergmann/phpunit-mock-objects/issues/171 * @ticket 171 + * @requires PHP < 8.1 */ public function testStubForClassThatImplementsSerializableCanBeCreatedWithoutInvokingTheConstructor(): void { @@ -1029,7 +1030,7 @@ public function testParameterCallbackConstraintOnlyEvaluatedOnce(): void $callCount = 0; $mock->expects($this->exactly($expectedNumberOfCalls))->method('bar') - ->with($this->callback(function ($argument) use (&$callCount) { + ->with($this->callback(static function ($argument) use (&$callCount) { return $argument === 'call_' . $callCount++; })); diff --git a/tests/unit/Framework/MockObject/MockTraitTest.php b/tests/unit/Framework/MockObject/MockTraitTest.php index 121320a7f5f..bd88ba68619 100644 --- a/tests/unit/Framework/MockObject/MockTraitTest.php +++ b/tests/unit/Framework/MockObject/MockTraitTest.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Framework\MockObject; +use function file_get_contents; +use function trait_exists; use PHPUnit\Framework\TestCase; final class MockTraitTest extends TestCase @@ -19,10 +21,10 @@ public function testGenerateClassFromSource(): void $file = __DIR__ . '/../../../_files/mock-object/MockTraitGenerated.tpl'; - $mockTrait = new MockTrait(\file_get_contents($file), $mockName); + $mockTrait = new MockTrait(file_get_contents($file), $mockName); $mockTrait->generate(); - $this->assertTrue(\trait_exists($mockName)); + $this->assertTrue(trait_exists($mockName)); } public function testGenerateReturnsNameOfGeneratedClass(): void diff --git a/tests/unit/Framework/SkippedTestCaseTest.php b/tests/unit/Framework/SkippedTestCaseTest.php index 46a0dc7c47c..d4017667c6f 100644 --- a/tests/unit/Framework/SkippedTestCaseTest.php +++ b/tests/unit/Framework/SkippedTestCaseTest.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Framework; +use function array_shift; +use function sprintf; use PHPUnit\Runner\BaseTestRunner; final class SkippedTestCaseTest extends TestCase @@ -33,7 +35,7 @@ public function testGetNameReturnsClassAndMethodName(): void $methodName ); - $name = \sprintf( + $name = sprintf( '%s::%s', $className, $methodName @@ -74,9 +76,9 @@ public function testRunMarksTestAsSkipped(): void $failures = $result->skipped(); - $failure = \array_shift($failures); + $failure = array_shift($failures); - $name = \sprintf( + $name = sprintf( '%s::%s', $className, $methodName diff --git a/tests/unit/Framework/TestBuilderTest.php b/tests/unit/Framework/TestBuilderTest.php index 66c7fbd8fbe..09adbc27692 100644 --- a/tests/unit/Framework/TestBuilderTest.php +++ b/tests/unit/Framework/TestBuilderTest.php @@ -9,7 +9,12 @@ */ namespace PHPUnit\Framework; +use function assert; +use EmptyDataProviderTest; +use ModifiedConstructorTestCase; use PHPUnit\Framework\MockObject\MockObject; +use ReflectionClass; +use TestWithAnnotations; /** * @covers \PHPUnit\Framework\TestBuilder @@ -18,12 +23,12 @@ final class TestBuilderTest extends TestCase { public function testCreateTestForConstructorlessTestClass(): void { - $reflector = $this->getMockBuilder(\ReflectionClass::class) + $reflector = $this->getMockBuilder(ReflectionClass::class) ->setConstructorArgs([$this]) ->getMock(); - \assert($reflector instanceof MockObject); - \assert($reflector instanceof \ReflectionClass); + assert($reflector instanceof MockObject); + assert($reflector instanceof ReflectionClass); $reflector->expects($this->once()) ->method('getConstructor') @@ -45,12 +50,12 @@ public function testCreateTestForConstructorlessTestClass(): void public function testCreateTestForNotInstantiableTestClass(): void { - $reflector = $this->getMockBuilder(\ReflectionClass::class) + $reflector = $this->getMockBuilder(ReflectionClass::class) ->setConstructorArgs([$this]) ->getMock(); - \assert($reflector instanceof MockObject); - \assert($reflector instanceof \ReflectionClass); + assert($reflector instanceof MockObject); + assert($reflector instanceof ReflectionClass); $reflector->expects($this->once()) ->method('isInstantiable') @@ -68,13 +73,13 @@ public function testCreateTestForNotInstantiableTestClass(): void public function testCreateTestForTestClassWithModifiedConstructor(): void { - $test = (new TestBuilder)->build(new \ReflectionClass(\ModifiedConstructorTestCase::class), 'testCase'); - $this->assertInstanceOf(\ModifiedConstructorTestCase::class, $test); + $test = (new TestBuilder)->build(new ReflectionClass(ModifiedConstructorTestCase::class), 'testCase'); + $this->assertInstanceOf(ModifiedConstructorTestCase::class, $test); } public function testCreateWithEmptyData(): void { - $test = (new TestBuilder)->build(new \ReflectionClass(\EmptyDataProviderTest::class), 'testCase'); + $test = (new TestBuilder)->build(new ReflectionClass(EmptyDataProviderTest::class), 'testCase'); $this->assertInstanceOf(DataProviderTestSuite::class, $test); /* @var DataProviderTestSuite $test */ $this->assertInstanceOf(SkippedTestCase::class, $test->getGroupDetails()['default'][0]); @@ -85,8 +90,8 @@ public function testCreateWithEmptyData(): void */ public function testWithAnnotations(string $methodName): void { - $test = (new TestBuilder)->build(new \ReflectionClass(\TestWithAnnotations::class), $methodName); - $this->assertInstanceOf(\TestWithAnnotations::class, $test); + $test = (new TestBuilder)->build(new ReflectionClass(TestWithAnnotations::class), $methodName); + $this->assertInstanceOf(TestWithAnnotations::class, $test); } public function provideWithAnnotations(): array @@ -103,7 +108,7 @@ public function provideWithAnnotations(): array */ public function testWithAnnotationsAndDataProvider(string $methodName): void { - $test = (new TestBuilder)->build(new \ReflectionClass(\TestWithAnnotations::class), $methodName); + $test = (new TestBuilder)->build(new ReflectionClass(TestWithAnnotations::class), $methodName); $this->assertInstanceOf(DataProviderTestSuite::class, $test); } diff --git a/tests/unit/Framework/TestCaseTest.php b/tests/unit/Framework/TestCaseTest.php index 75af77ad0da..6720a3435f7 100644 --- a/tests/unit/Framework/TestCaseTest.php +++ b/tests/unit/Framework/TestCaseTest.php @@ -9,10 +9,51 @@ */ namespace PHPUnit\Framework; +use const E_USER_DEPRECATED; +use const E_USER_ERROR; +use const E_USER_NOTICE; +use const E_USER_WARNING; +use const PHP_EOL; +use function get_class; +use function getcwd; +use function ini_get; +use function ini_set; +use function trigger_error; +use ChangeCurrentWorkingDirectoryTest; +use ClassWithScalarTypeDeclarations; +use DoNoAssertionTestCase; +use ExceptionInAssertPostConditionsTest; +use ExceptionInAssertPreConditionsTest; +use ExceptionInSetUpTest; +use ExceptionInTearDownTest; +use ExceptionInTest; +use ExceptionInTestDetectedInTeardown; +use Failure; +use InvalidArgumentException; +use IsolationTest; +use Mockable; +use NoArgTestCaseTest; +use OutputTestCase; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\MockObject\Stub; use PHPUnit\Runner\BaseTestRunner; use PHPUnit\Util\Test as TestUtil; +use RequirementsTest; +use RuntimeException; +use Singleton; +use Success; +use TestAutoreferenced; +use TestError; +use TestIncomplete; +use TestSkipped; +use TestWithDifferentNames; +use TestWithDifferentOutput; +use TestWithDifferentSizes; +use TestWithDifferentStatuses; +use ThrowExceptionTestCase; +use ThrowNoExceptionTestCase; +use TypeError; +use WasRun; /** * @small @@ -61,7 +102,7 @@ public function testCaseToString(): void public function testSuccess(): void { - $test = new \Success; + $test = new Success; $result = $test->run(); $this->assertEquals(BaseTestRunner::STATUS_PASSED, $test->getStatus()); @@ -73,7 +114,7 @@ public function testSuccess(): void public function testFailure(): void { - $test = new \Failure; + $test = new Failure; $result = $test->run(); $this->assertEquals(BaseTestRunner::STATUS_FAILURE, $test->getStatus()); @@ -85,7 +126,7 @@ public function testFailure(): void public function testError(): void { - $test = new \TestError; + $test = new TestError; $result = $test->run(); $this->assertEquals(BaseTestRunner::STATUS_ERROR, $test->getStatus()); @@ -97,7 +138,7 @@ public function testError(): void public function testSkipped(): void { - $test = new \TestSkipped; + $test = new TestSkipped; $result = $test->run(); $this->assertEquals(BaseTestRunner::STATUS_SKIPPED, $test->getStatus()); @@ -110,7 +151,7 @@ public function testSkipped(): void public function testIncomplete(): void { - $test = new \TestIncomplete; + $test = new TestIncomplete; $result = $test->run(); $this->assertEquals(BaseTestRunner::STATUS_INCOMPLETE, $test->getStatus()); @@ -123,7 +164,7 @@ public function testIncomplete(): void public function testExceptionInSetUp(): void { - $test = new \ExceptionInSetUpTest('testSomething'); + $test = new ExceptionInSetUpTest('testSomething'); $test->run(); $this->assertTrue($test->setUp); @@ -135,7 +176,7 @@ public function testExceptionInSetUp(): void public function testExceptionInAssertPreConditions(): void { - $test = new \ExceptionInAssertPreConditionsTest('testSomething'); + $test = new ExceptionInAssertPreConditionsTest('testSomething'); $test->run(); $this->assertTrue($test->setUp); @@ -147,7 +188,7 @@ public function testExceptionInAssertPreConditions(): void public function testExceptionInTest(): void { - $test = new \ExceptionInTest('testSomething'); + $test = new ExceptionInTest('testSomething'); $test->run(); $this->assertTrue($test->setUp); @@ -159,7 +200,7 @@ public function testExceptionInTest(): void public function testExceptionInAssertPostConditions(): void { - $test = new \ExceptionInAssertPostConditionsTest('testSomething'); + $test = new ExceptionInAssertPostConditionsTest('testSomething'); $test->run(); $this->assertTrue($test->setUp); @@ -171,7 +212,7 @@ public function testExceptionInAssertPostConditions(): void public function testExceptionInTearDown(): void { - $test = new \ExceptionInTearDownTest('testSomething'); + $test = new ExceptionInTearDownTest('testSomething'); $test->run(); $this->assertTrue($test->setUp); @@ -185,7 +226,7 @@ public function testExceptionInTearDown(): void public function testExceptionInTestIsDetectedInTeardown(): void { - $test = new \ExceptionInTestDetectedInTeardown('testSomething'); + $test = new ExceptionInTestDetectedInTeardown('testSomething'); $test->run(); $this->assertTrue($test->exceptionDetected); @@ -194,7 +235,7 @@ public function testExceptionInTestIsDetectedInTeardown(): void public function testNoArgTestCasePasses(): void { $result = new TestResult; - $t = new TestSuite(\NoArgTestCaseTest::class); + $t = new TestSuite(NoArgTestCaseTest::class); $t->run($result); @@ -205,7 +246,7 @@ public function testNoArgTestCasePasses(): void public function testWasRun(): void { - $test = new \WasRun; + $test = new WasRun; $test->run(); $this->assertTrue($test->wasRun); @@ -213,8 +254,8 @@ public function testWasRun(): void public function testException(): void { - $test = new \ThrowExceptionTestCase('test'); - $test->expectException(\RuntimeException::class); + $test = new ThrowExceptionTestCase('test'); + $test->expectException(RuntimeException::class); $result = $test->run(); @@ -224,9 +265,9 @@ public function testException(): void public function testExpectExceptionAllowsAccessingExpectedException(): void { - $exception = \RuntimeException::class; + $exception = RuntimeException::class; - $test = new \ThrowExceptionTestCase('test'); + $test = new ThrowExceptionTestCase('test'); $test->expectException($exception); @@ -235,7 +276,7 @@ public function testExpectExceptionAllowsAccessingExpectedException(): void public function testExpectExceptionCodeWithSameCode(): void { - $test = new \ThrowExceptionTestCase('test'); + $test = new ThrowExceptionTestCase('test'); $test->expectExceptionCode(0); @@ -247,7 +288,7 @@ public function testExpectExceptionCodeWithSameCode(): void public function testExpectExceptionCodeWithDifferentCode(): void { - $test = new \ThrowExceptionTestCase('test'); + $test = new ThrowExceptionTestCase('test'); $test->expectExceptionCode(9000); @@ -261,7 +302,7 @@ public function testExpectExceptionCodeAllowsAccessingExpectedExceptionCode(): v { $code = 9000; - $test = new \ThrowExceptionTestCase('test'); + $test = new ThrowExceptionTestCase('test'); $test->expectExceptionCode($code); @@ -270,8 +311,8 @@ public function testExpectExceptionCodeAllowsAccessingExpectedExceptionCode(): v public function testExceptionWithEmptyMessage(): void { - $test = new \ThrowExceptionTestCase('test'); - $test->expectException(\RuntimeException::class); + $test = new ThrowExceptionTestCase('test'); + $test->expectException(RuntimeException::class); $result = $test->run(); @@ -281,8 +322,8 @@ public function testExceptionWithEmptyMessage(): void public function testExceptionWithNullMessage(): void { - $test = new \ThrowExceptionTestCase('test'); - $test->expectException(\RuntimeException::class); + $test = new ThrowExceptionTestCase('test'); + $test->expectException(RuntimeException::class); $result = $test->run(); @@ -292,8 +333,8 @@ public function testExceptionWithNullMessage(): void public function testExceptionWithMessage(): void { - $test = new \ThrowExceptionTestCase('test'); - $test->expectException(\RuntimeException::class); + $test = new ThrowExceptionTestCase('test'); + $test->expectException(RuntimeException::class); $test->expectExceptionMessage('A runtime error occurred'); $result = $test->run(); @@ -304,8 +345,8 @@ public function testExceptionWithMessage(): void public function testExceptionWithWrongMessage(): void { - $test = new \ThrowExceptionTestCase('test'); - $test->expectException(\RuntimeException::class); + $test = new ThrowExceptionTestCase('test'); + $test->expectException(RuntimeException::class); $test->expectExceptionMessage('A logic error occurred'); $result = $test->run(); @@ -322,7 +363,7 @@ public function testExpectExceptionMessageAllowsAccessingExpectedExceptionMessag { $message = 'A runtime error occurred'; - $test = new \ThrowExceptionTestCase('test'); + $test = new ThrowExceptionTestCase('test'); $test->expectExceptionMessage($message); @@ -331,8 +372,8 @@ public function testExpectExceptionMessageAllowsAccessingExpectedExceptionMessag public function testExceptionWithRegexpMessage(): void { - $test = new \ThrowExceptionTestCase('test'); - $test->expectException(\RuntimeException::class); + $test = new ThrowExceptionTestCase('test'); + $test->expectException(RuntimeException::class); $test->expectExceptionMessageMatches('/runtime .*? occurred/'); $result = $test->run(); @@ -345,7 +386,7 @@ public function testExpectExceptionMessageRegExpAllowsAccessingExpectedException { $messageRegExp = '/runtime .*? occurred/'; - $test = new \ThrowExceptionTestCase('test'); + $test = new ThrowExceptionTestCase('test'); $test->expectExceptionMessageMatches($messageRegExp); @@ -354,8 +395,8 @@ public function testExpectExceptionMessageRegExpAllowsAccessingExpectedException public function testExceptionWithWrongRegexpMessage(): void { - $test = new \ThrowExceptionTestCase('test'); - $test->expectException(\RuntimeException::class); + $test = new ThrowExceptionTestCase('test'); + $test->expectException(RuntimeException::class); $test->expectExceptionMessageMatches('/logic .*? occurred/'); $result = $test->run(); @@ -370,8 +411,8 @@ public function testExceptionWithWrongRegexpMessage(): void public function testExceptionWithInvalidRegexpMessage(): void { - $test = new \ThrowExceptionTestCase('test'); - $test->expectException(\RuntimeException::class); + $test = new ThrowExceptionTestCase('test'); + $test->expectException(RuntimeException::class); $test->expectExceptionMessageMatches('#runtime .*? occurred/'); $test->run(); @@ -384,12 +425,12 @@ public function testExceptionWithInvalidRegexpMessage(): void public function testExpectExceptionObjectWithDifferentExceptionClass(): void { - $exception = new \InvalidArgumentException( + $exception = new InvalidArgumentException( 'Cannot compute at this time.', 9000 ); - $test = new \ThrowExceptionTestCase('testWithExpectExceptionObject'); + $test = new ThrowExceptionTestCase('testWithExpectExceptionObject'); $test->expectExceptionObject($exception); @@ -401,12 +442,12 @@ public function testExpectExceptionObjectWithDifferentExceptionClass(): void public function testExpectExceptionObjectWithDifferentExceptionMessage(): void { - $exception = new \RuntimeException( + $exception = new RuntimeException( 'This is fine!', 9000 ); - $test = new \ThrowExceptionTestCase('testWithExpectExceptionObject'); + $test = new ThrowExceptionTestCase('testWithExpectExceptionObject'); $test->expectExceptionObject($exception); @@ -418,12 +459,12 @@ public function testExpectExceptionObjectWithDifferentExceptionMessage(): void public function testExpectExceptionObjectWithDifferentExceptionCode(): void { - $exception = new \RuntimeException( + $exception = new RuntimeException( 'Cannot compute at this time.', 9001 ); - $test = new \ThrowExceptionTestCase('testWithExpectExceptionObject'); + $test = new ThrowExceptionTestCase('testWithExpectExceptionObject'); $test->expectExceptionObject($exception); @@ -435,12 +476,12 @@ public function testExpectExceptionObjectWithDifferentExceptionCode(): void public function testExpectExceptionObjectWithEqualException(): void { - $exception = new \RuntimeException( + $exception = new RuntimeException( 'Cannot compute at this time', 9000 ); - $test = new \ThrowExceptionTestCase('testWithExpectExceptionObject'); + $test = new ThrowExceptionTestCase('testWithExpectExceptionObject'); $test->expectExceptionObject($exception); @@ -452,24 +493,24 @@ public function testExpectExceptionObjectWithEqualException(): void public function testExpectExceptionObjectAllowsAccessingExpectedExceptionDetails(): void { - $exception = new \RuntimeException( + $exception = new RuntimeException( 'Cannot compute at this time', 9000 ); - $test = new \ThrowExceptionTestCase('testWithExpectExceptionObject'); + $test = new ThrowExceptionTestCase('testWithExpectExceptionObject'); $test->expectExceptionObject($exception); - $this->assertSame(\get_class($exception), $test->getExpectedException()); + $this->assertSame(get_class($exception), $test->getExpectedException()); $this->assertSame($exception->getCode(), $test->getExpectedExceptionCode()); $this->assertSame($exception->getMessage(), $test->getExpectedExceptionMessage()); } public function testNoException(): void { - $test = new \ThrowNoExceptionTestCase('test'); - $test->expectException(\RuntimeException::class); + $test = new ThrowNoExceptionTestCase('test'); + $test->expectException(RuntimeException::class); $result = $test->run(); @@ -479,8 +520,8 @@ public function testNoException(): void public function testWrongException(): void { - $test = new \ThrowExceptionTestCase('test'); - $test->expectException(\InvalidArgumentException::class); + $test = new ThrowExceptionTestCase('test'); + $test->expectException(InvalidArgumentException::class); $result = $test->run(); @@ -490,7 +531,7 @@ public function testWrongException(): void public function testDoesNotPerformAssertions(): void { - $test = new \DoNoAssertionTestCase('testNothing'); + $test = new DoNoAssertionTestCase('testNothing'); $test->expectNotToPerformAssertions(); $result = $test->run(); @@ -576,7 +617,7 @@ public function testGlobalsBackupPost(): void */ public function testStaticAttributesBackupPre(): void { - $GLOBALS['singleton'] = \Singleton::getInstance(); + $GLOBALS['singleton'] = Singleton::getInstance(); $GLOBALS['i'] = 'set by testStaticAttributesBackupPre'; $GLOBALS['j'] = 'reset by backup'; @@ -589,7 +630,7 @@ public function testStaticAttributesBackupPre(): void public function testStaticAttributesBackupPost(): void { // Snapshots made by @backupGlobals - $this->assertSame(\Singleton::getInstance(), $GLOBALS['singleton']); + $this->assertSame(Singleton::getInstance(), $GLOBALS['singleton']); $this->assertSame('set by testStaticAttributesBackupPre', $GLOBALS['i']); // Reset global @@ -601,7 +642,7 @@ public function testStaticAttributesBackupPost(): void public function testIsInIsolationReturnsFalse(): void { - $test = new \IsolationTest('testIsInIsolationReturnsFalse'); + $test = new IsolationTest('testIsInIsolationReturnsFalse'); $result = $test->run(); $this->assertCount(1, $result); @@ -610,7 +651,7 @@ public function testIsInIsolationReturnsFalse(): void public function testIsInIsolationReturnsTrue(): void { - $test = new \IsolationTest('testIsInIsolationReturnsTrue'); + $test = new IsolationTest('testIsInIsolationReturnsTrue'); $test->setRunTestInSeparateProcess(true); $result = $test->run(); @@ -620,7 +661,7 @@ public function testIsInIsolationReturnsTrue(): void public function testExpectOutputStringFooActualFoo(): void { - $test = new \OutputTestCase('testExpectOutputStringFooActualFoo'); + $test = new OutputTestCase('testExpectOutputStringFooActualFoo'); $result = $test->run(); $this->assertCount(1, $result); @@ -629,7 +670,7 @@ public function testExpectOutputStringFooActualFoo(): void public function testExpectOutputStringFooActualBar(): void { - $test = new \OutputTestCase('testExpectOutputStringFooActualBar'); + $test = new OutputTestCase('testExpectOutputStringFooActualBar'); $result = $test->run(); $this->assertCount(1, $result); @@ -638,7 +679,7 @@ public function testExpectOutputStringFooActualBar(): void public function testExpectOutputRegexFooActualFoo(): void { - $test = new \OutputTestCase('testExpectOutputRegexFooActualFoo'); + $test = new OutputTestCase('testExpectOutputRegexFooActualFoo'); $result = $test->run(); $this->assertCount(1, $result); @@ -647,7 +688,7 @@ public function testExpectOutputRegexFooActualFoo(): void public function testExpectOutputRegexFooActualBar(): void { - $test = new \OutputTestCase('testExpectOutputRegexFooActualBar'); + $test = new OutputTestCase('testExpectOutputRegexFooActualBar'); $result = $test->run(); $this->assertCount(1, $result); @@ -656,7 +697,7 @@ public function testExpectOutputRegexFooActualBar(): void public function testSkipsIfRequiresHigherVersionOfPHPUnit(): void { - $test = new \RequirementsTest('testAlwaysSkip'); + $test = new RequirementsTest('testAlwaysSkip'); $result = $test->run(); $this->assertEquals(1, $result->skippedCount()); @@ -668,7 +709,7 @@ public function testSkipsIfRequiresHigherVersionOfPHPUnit(): void public function testSkipsIfRequiresHigherVersionOfPHP(): void { - $test = new \RequirementsTest('testAlwaysSkip2'); + $test = new RequirementsTest('testAlwaysSkip2'); $result = $test->run(); $this->assertEquals(1, $result->skippedCount()); @@ -680,7 +721,7 @@ public function testSkipsIfRequiresHigherVersionOfPHP(): void public function testSkipsIfRequiresNonExistingOs(): void { - $test = new \RequirementsTest('testAlwaysSkip3'); + $test = new RequirementsTest('testAlwaysSkip3'); $result = $test->run(); $this->assertEquals(1, $result->skippedCount()); @@ -692,7 +733,7 @@ public function testSkipsIfRequiresNonExistingOs(): void public function testSkipsIfRequiresNonExistingOsFamily(): void { - $test = new \RequirementsTest('testAlwaysSkip4'); + $test = new RequirementsTest('testAlwaysSkip4'); $result = $test->run(); $this->assertEquals(1, $result->skippedCount()); @@ -704,7 +745,7 @@ public function testSkipsIfRequiresNonExistingOsFamily(): void public function testSkipsIfRequiresNonExistingFunction(): void { - $test = new \RequirementsTest('testNine'); + $test = new RequirementsTest('testNine'); $result = $test->run(); $this->assertEquals(1, $result->skippedCount()); @@ -716,7 +757,7 @@ public function testSkipsIfRequiresNonExistingFunction(): void public function testSkipsIfRequiresNonExistingExtension(): void { - $test = new \RequirementsTest('testTen'); + $test = new RequirementsTest('testTen'); $test->run(); $this->assertEquals( @@ -727,7 +768,7 @@ public function testSkipsIfRequiresNonExistingExtension(): void public function testSkipsIfRequiresExtensionWithAMinimumVersion(): void { - $test = new \RequirementsTest('testSpecificExtensionVersion'); + $test = new RequirementsTest('testSpecificExtensionVersion'); $test->run(); $this->assertEquals( @@ -738,18 +779,18 @@ public function testSkipsIfRequiresExtensionWithAMinimumVersion(): void public function testSkipsProvidesMessagesForAllSkippingReasons(): void { - $test = new \RequirementsTest('testAllPossibleRequirements'); + $test = new RequirementsTest('testAllPossibleRequirements'); $test->run(); $this->assertEquals( - 'PHP >= 99-dev is required.' . \PHP_EOL . - 'PHPUnit >= 9-dev is required.' . \PHP_EOL . - 'Operating system matching /DOESNOTEXIST/i is required.' . \PHP_EOL . - 'Function testFuncOne is required.' . \PHP_EOL . - 'Function testFunc2 is required.' . \PHP_EOL . - 'Setting "not_a_setting" must be "Off".' . \PHP_EOL . - 'Extension testExtOne is required.' . \PHP_EOL . - 'Extension testExt2 is required.' . \PHP_EOL . + 'PHP >= 99-dev is required.' . PHP_EOL . + 'PHPUnit >= 9-dev is required.' . PHP_EOL . + 'Operating system matching /DOESNOTEXIST/i is required.' . PHP_EOL . + 'Function testFuncOne is required.' . PHP_EOL . + 'Function testFunc2 is required.' . PHP_EOL . + 'Setting "not_a_setting" must be "Off".' . PHP_EOL . + 'Extension testExtOne is required.' . PHP_EOL . + 'Extension testExt2 is required.' . PHP_EOL . 'Extension testExtThree >= 2.0 is required.', $test->getStatusMessage() ); @@ -757,58 +798,58 @@ public function testSkipsProvidesMessagesForAllSkippingReasons(): void public function testRequiringAnExistingMethodDoesNotSkip(): void { - $test = new \RequirementsTest('testExistingMethod'); + $test = new RequirementsTest('testExistingMethod'); $result = $test->run(); $this->assertEquals(0, $result->skippedCount()); } public function testRequiringAnExistingFunctionDoesNotSkip(): void { - $test = new \RequirementsTest('testExistingFunction'); + $test = new RequirementsTest('testExistingFunction'); $result = $test->run(); $this->assertEquals(0, $result->skippedCount()); } public function testRequiringAnExistingExtensionDoesNotSkip(): void { - $test = new \RequirementsTest('testExistingExtension'); + $test = new RequirementsTest('testExistingExtension'); $result = $test->run(); $this->assertEquals(0, $result->skippedCount()); } public function testRequiringAnExistingOsDoesNotSkip(): void { - $test = new \RequirementsTest('testExistingOs'); + $test = new RequirementsTest('testExistingOs'); $result = $test->run(); $this->assertEquals(0, $result->skippedCount()); } public function testRequiringASetting(): void { - $test = new \RequirementsTest('testSettingDisplayErrorsOn'); + $test = new RequirementsTest('testSettingDisplayErrorsOn'); // Get this so we can return it to whatever it was before the test. - $displayErrorsVal = \ini_get('display_errors'); + $displayErrorsVal = ini_get('display_errors'); - \ini_set('display_errors', 'On'); + ini_set('display_errors', 'On'); $result = $test->run(); $this->assertEquals(0, $result->skippedCount()); - \ini_set('display_errors', 'Off'); + ini_set('display_errors', 'Off'); $result = $test->run(); $this->assertEquals(1, $result->skippedCount()); - \ini_set('display_errors', $displayErrorsVal); + ini_set('display_errors', $displayErrorsVal); } public function testCurrentWorkingDirectoryIsRestored(): void { - $expectedCwd = \getcwd(); + $expectedCwd = getcwd(); - $test = new \ChangeCurrentWorkingDirectoryTest('testSomethingThatChangesTheCwd'); + $test = new ChangeCurrentWorkingDirectoryTest('testSomethingThatChangesTheCwd'); $test->run(); - $this->assertSame($expectedCwd, \getcwd()); + $this->assertSame($expectedCwd, getcwd()); } /** @@ -816,24 +857,24 @@ public function testCurrentWorkingDirectoryIsRestored(): void */ public function testTypeErrorCanBeExpected(): void { - $o = new \ClassWithScalarTypeDeclarations; + $o = new ClassWithScalarTypeDeclarations; - $this->expectException(\TypeError::class); + $this->expectException(TypeError::class); $o->foo(null, null); } public function testCreateMockFromClassName(): void { - $mock = $this->createMock(\Mockable::class); + $mock = $this->createMock(Mockable::class); - $this->assertInstanceOf(\Mockable::class, $mock); + $this->assertInstanceOf(Mockable::class, $mock); $this->assertInstanceOf(MockObject::class, $mock); } public function testCreateMockMocksAllMethods(): void { - $mock = $this->createMock(\Mockable::class); + $mock = $this->createMock(Mockable::class); $this->assertNull($mock->mockableMethod()); $this->assertNull($mock->anotherMockableMethod()); @@ -841,15 +882,15 @@ public function testCreateMockMocksAllMethods(): void public function testCreateStubFromClassName(): void { - $mock = $this->createStub(\Mockable::class); + $mock = $this->createStub(Mockable::class); - $this->assertInstanceOf(\Mockable::class, $mock); + $this->assertInstanceOf(Mockable::class, $mock); $this->assertInstanceOf(Stub::class, $mock); } public function testCreateStubStubsAllMethods(): void { - $mock = $this->createStub(\Mockable::class); + $mock = $this->createStub(Mockable::class); $this->assertNull($mock->mockableMethod()); $this->assertNull($mock->anotherMockableMethod()); @@ -857,8 +898,8 @@ public function testCreateStubStubsAllMethods(): void public function testCreatePartialMockDoesNotMockAllMethods(): void { - /** @var \Mockable $mock */ - $mock = $this->createPartialMock(\Mockable::class, ['mockableMethod']); + /** @var Mockable $mock */ + $mock = $this->createPartialMock(Mockable::class, ['mockableMethod']); $this->assertNull($mock->mockableMethod()); $this->assertTrue($mock->anotherMockableMethod()); @@ -866,8 +907,8 @@ public function testCreatePartialMockDoesNotMockAllMethods(): void public function testCreatePartialMockCanMockNoMethods(): void { - /** @var \Mockable $mock */ - $mock = $this->createPartialMock(\Mockable::class, []); + /** @var Mockable $mock */ + $mock = $this->createPartialMock(Mockable::class, []); $this->assertTrue($mock->mockableMethod()); $this->assertTrue($mock->anotherMockableMethod()); @@ -875,7 +916,7 @@ public function testCreatePartialMockCanMockNoMethods(): void public function testCreatePartialMockWithFakeMethods(): void { - $test = new \TestWithDifferentStatuses('testWithCreatePartialMockWarning'); + $test = new TestWithDifferentStatuses('testWithCreatePartialMockWarning'); $test->run(); @@ -885,7 +926,7 @@ public function testCreatePartialMockWithFakeMethods(): void public function testCreatePartialMockWithRealMethods(): void { - $test = new \TestWithDifferentStatuses('testWithCreatePartialMockPassesNoWarning'); + $test = new TestWithDifferentStatuses('testWithCreatePartialMockPassesNoWarning'); $test->run(); @@ -895,14 +936,14 @@ public function testCreatePartialMockWithRealMethods(): void public function testCreateMockSkipsConstructor(): void { - $mock = $this->createMock(\Mockable::class); + $mock = $this->createMock(Mockable::class); $this->assertNull($mock->constructorArgs); } public function testCreateMockDisablesOriginalClone(): void { - $mock = $this->createMock(\Mockable::class); + $mock = $this->createMock(Mockable::class); $cloned = clone $mock; $this->assertNull($cloned->cloned); @@ -910,14 +951,14 @@ public function testCreateMockDisablesOriginalClone(): void public function testCreateStubSkipsConstructor(): void { - $mock = $this->createStub(\Mockable::class); + $mock = $this->createStub(Mockable::class); $this->assertNull($mock->constructorArgs); } public function testCreateStubDisablesOriginalClone(): void { - $mock = $this->createStub(\Mockable::class); + $mock = $this->createStub(Mockable::class); $cloned = clone $mock; $this->assertNull($cloned->cloned); @@ -925,9 +966,9 @@ public function testCreateStubDisablesOriginalClone(): void public function testConfiguredMockCanBeCreated(): void { - /** @var \Mockable $mock */ + /** @var Mockable $mock */ $mock = $this->createConfiguredMock( - \Mockable::class, + Mockable::class, [ 'mockableMethod' => false, ] @@ -939,7 +980,7 @@ public function testConfiguredMockCanBeCreated(): void public function testProvidingOfAutoreferencedArray(): void { - $test = new \TestAutoreferenced('testJsonEncodeException', $this->getAutoreferencedArray()); + $test = new TestAutoreferenced('testJsonEncodeException', $this->getAutoreferencedArray()); $test->runBare(); $this->assertIsArray($test->myTestData); @@ -952,11 +993,11 @@ public function testProvidingArrayThatMixesObjectsAndScalars(): void $data = [ [123], ['foo'], - [$this->createMock(\Mockable::class)], - [$this->createStub(\Mockable::class)], + [$this->createMock(Mockable::class)], + [$this->createStub(Mockable::class)], ]; - $test = new \TestAutoreferenced('testJsonEncodeException', [$data]); + $test = new TestAutoreferenced('testJsonEncodeException', [$data]); $test->runBare(); $this->assertIsArray($test->myTestData); @@ -965,13 +1006,13 @@ public function testProvidingArrayThatMixesObjectsAndScalars(): void public function testGettingNullTestResultObject(): void { - $test = new \Success; + $test = new Success; $this->assertNull($test->getTestResultObject()); } public function testSizeUnknown(): void { - $test = new \TestWithDifferentSizes('testWithSizeUnknown'); + $test = new TestWithDifferentSizes('testWithSizeUnknown'); $this->assertFalse($test->hasSize()); @@ -984,7 +1025,7 @@ public function testSizeUnknown(): void public function testSizeLarge(): void { - $test = new \TestWithDifferentSizes('testWithSizeLarge'); + $test = new TestWithDifferentSizes('testWithSizeLarge'); $this->assertTrue($test->hasSize()); @@ -997,7 +1038,7 @@ public function testSizeLarge(): void public function testSizeMedium(): void { - $test = new \TestWithDifferentSizes('testWithSizeMedium'); + $test = new TestWithDifferentSizes('testWithSizeMedium'); $this->assertTrue($test->hasSize()); @@ -1010,7 +1051,7 @@ public function testSizeMedium(): void public function testSizeSmall(): void { - $test = new \TestWithDifferentSizes('testWithSizeSmall'); + $test = new TestWithDifferentSizes('testWithSizeSmall'); $this->assertTrue($test->hasSize()); @@ -1025,14 +1066,14 @@ public function testGetNameReturnsMethodName(): void { $methodName = 'testWithName'; - $testCase = new \TestWithDifferentNames($methodName); + $testCase = new TestWithDifferentNames($methodName); $this->assertSame($methodName, $testCase->getName()); } public function testGetNameReturnsEmptyStringAsDefault(): void { - $testCase = new \TestWithDifferentNames(); + $testCase = new TestWithDifferentNames(); $this->assertSame('', $testCase->getName()); } @@ -1042,7 +1083,7 @@ public function testGetNameReturnsEmptyStringAsDefault(): void */ public function testRunBareThrowsExceptionWhenTestHasInvalidName($name): void { - $testCase = new \TestWithDifferentNames($name); + $testCase = new TestWithDifferentNames($name); $this->expectException(Exception::class); $this->expectExceptionMessage('PHPUnit\Framework\TestCase::$name must be a non-blank string.'); @@ -1061,7 +1102,7 @@ public function providerInvalidName(): array public function testHasFailedReturnsFalseWhenTestHasNotRunYet(): void { - $test = new \TestWithDifferentStatuses(); + $test = new TestWithDifferentStatuses(); $this->assertSame(BaseTestRunner::STATUS_UNKNOWN, $test->getStatus()); $this->assertFalse($test->hasFailed()); @@ -1069,7 +1110,7 @@ public function testHasFailedReturnsFalseWhenTestHasNotRunYet(): void public function testHasFailedReturnsTrueWhenTestHasFailed(): void { - $test = new \TestWithDifferentStatuses('testThatFails'); + $test = new TestWithDifferentStatuses('testThatFails'); $test->run(); @@ -1079,7 +1120,7 @@ public function testHasFailedReturnsTrueWhenTestHasFailed(): void public function testHasFailedReturnsTrueWhenTestHasErrored(): void { - $test = new \TestWithDifferentStatuses('testThatErrors'); + $test = new TestWithDifferentStatuses('testThatErrors'); $test->run(); @@ -1089,7 +1130,7 @@ public function testHasFailedReturnsTrueWhenTestHasErrored(): void public function testHasFailedReturnsFalseWhenTestHasPassed(): void { - $test = new \TestWithDifferentStatuses('testThatPasses'); + $test = new TestWithDifferentStatuses('testThatPasses'); $test->run(); @@ -1099,7 +1140,7 @@ public function testHasFailedReturnsFalseWhenTestHasPassed(): void public function testHasFailedReturnsFalseWhenTestHasBeenMarkedAsIncomplete(): void { - $test = new \TestWithDifferentStatuses('testThatIsMarkedAsIncomplete'); + $test = new TestWithDifferentStatuses('testThatIsMarkedAsIncomplete'); $test->run(); @@ -1109,7 +1150,7 @@ public function testHasFailedReturnsFalseWhenTestHasBeenMarkedAsIncomplete(): vo public function testHasFailedReturnsFalseWhenTestHasBeenMarkedAsRisky(): void { - $test = new \TestWithDifferentStatuses('testThatIsMarkedAsRisky'); + $test = new TestWithDifferentStatuses('testThatIsMarkedAsRisky'); $test->run(); @@ -1119,7 +1160,7 @@ public function testHasFailedReturnsFalseWhenTestHasBeenMarkedAsRisky(): void public function testHasFailedReturnsFalseWhenTestHasBeenMarkedAsSkipped(): void { - $test = new \TestWithDifferentStatuses('testThatIsMarkedAsSkipped'); + $test = new TestWithDifferentStatuses('testThatIsMarkedAsSkipped'); $test->run(); @@ -1129,7 +1170,7 @@ public function testHasFailedReturnsFalseWhenTestHasBeenMarkedAsSkipped(): void public function testHasFailedReturnsFalseWhenTestHasEmittedWarning(): void { - $test = new \TestWithDifferentStatuses('testThatAddsAWarning'); + $test = new TestWithDifferentStatuses('testThatAddsAWarning'); $test->run(); @@ -1139,7 +1180,7 @@ public function testHasFailedReturnsFalseWhenTestHasEmittedWarning(): void public function testHasOutputReturnsFalseWhenTestDoesNotGenerateOutput(): void { - $test = new \TestWithDifferentOutput('testThatDoesNotGenerateOutput'); + $test = new TestWithDifferentOutput('testThatDoesNotGenerateOutput'); $test->run(); @@ -1148,7 +1189,7 @@ public function testHasOutputReturnsFalseWhenTestDoesNotGenerateOutput(): void public function testHasOutputReturnsFalseWhenTestExpectsOutputRegex(): void { - $test = new \TestWithDifferentOutput('testThatExpectsOutputRegex'); + $test = new TestWithDifferentOutput('testThatExpectsOutputRegex'); $test->run(); @@ -1157,7 +1198,7 @@ public function testHasOutputReturnsFalseWhenTestExpectsOutputRegex(): void public function testHasOutputReturnsFalseWhenTestExpectsOutputString(): void { - $test = new \TestWithDifferentOutput('testThatExpectsOutputString'); + $test = new TestWithDifferentOutput('testThatExpectsOutputString'); $test->run(); @@ -1166,7 +1207,7 @@ public function testHasOutputReturnsFalseWhenTestExpectsOutputString(): void public function testHasOutputReturnsTrueWhenTestGeneratesOutput(): void { - $test = new \TestWithDifferentOutput('testThatGeneratesOutput'); + $test = new TestWithDifferentOutput('testThatGeneratesOutput'); $test->run(); @@ -1179,7 +1220,7 @@ public function testDeprecationCanBeExpected(): void $this->expectDeprecationMessage('foo'); $this->expectDeprecationMessageMatches('/foo/'); - \trigger_error('foo', \E_USER_DEPRECATED); + trigger_error('foo', E_USER_DEPRECATED); } public function testNoticeCanBeExpected(): void @@ -1188,7 +1229,7 @@ public function testNoticeCanBeExpected(): void $this->expectNoticeMessage('foo'); $this->expectNoticeMessageMatches('/foo/'); - \trigger_error('foo', \E_USER_NOTICE); + trigger_error('foo', E_USER_NOTICE); } public function testWarningCanBeExpected(): void @@ -1197,7 +1238,7 @@ public function testWarningCanBeExpected(): void $this->expectWarningMessage('foo'); $this->expectWarningMessageMatches('/foo/'); - \trigger_error('foo', \E_USER_WARNING); + trigger_error('foo', E_USER_WARNING); } public function testErrorCanBeExpected(): void @@ -1206,7 +1247,7 @@ public function testErrorCanBeExpected(): void $this->expectErrorMessage('foo'); $this->expectErrorMessageMatches('/foo/'); - \trigger_error('foo', \E_USER_ERROR); + trigger_error('foo', E_USER_ERROR); } /** diff --git a/tests/unit/Framework/TestFailureTest.php b/tests/unit/Framework/TestFailureTest.php index ddfb8d9989d..e35bb9cfef2 100644 --- a/tests/unit/Framework/TestFailureTest.php +++ b/tests/unit/Framework/TestFailureTest.php @@ -9,6 +9,7 @@ */ namespace PHPUnit\Framework; +use NotSelfDescribingTest; use PHPUnit\Framework\Error\Error; use SebastianBergmann\Comparator\ComparisonFailure; @@ -37,7 +38,7 @@ public function testToStringForError(): void public function testToStringForNonSelfDescribing(): void { - $test = new \NotSelfDescribingTest(); + $test = new NotSelfDescribingTest(); $exception = new Exception('message'); $failure = new TestFailure($test, $exception); diff --git a/tests/unit/Framework/TestImplementorTest.php b/tests/unit/Framework/TestImplementorTest.php index 24fae3177dd..0d9f72d48ae 100644 --- a/tests/unit/Framework/TestImplementorTest.php +++ b/tests/unit/Framework/TestImplementorTest.php @@ -9,6 +9,10 @@ */ namespace PHPUnit\Framework; +use function count; +use DoubleTestCase; +use Success; + /** * @small */ @@ -18,10 +22,10 @@ public function testSuccessfulRun(): void { $result = new TestResult; - $test = new \DoubleTestCase(new \Success); + $test = new DoubleTestCase(new Success); $test->run($result); - $this->assertCount(\count($test), $result); + $this->assertCount(count($test), $result); $this->assertEquals(0, $result->errorCount()); $this->assertEquals(0, $result->failureCount()); } diff --git a/tests/unit/Framework/TestListenerTest.php b/tests/unit/Framework/TestListenerTest.php index 147e945a6e0..c65917d73e4 100644 --- a/tests/unit/Framework/TestListenerTest.php +++ b/tests/unit/Framework/TestListenerTest.php @@ -9,7 +9,10 @@ */ namespace PHPUnit\Framework; +use Failure; use MyTestListener; +use Success; +use TestError; /** * @small @@ -36,7 +39,7 @@ protected function setUp(): void public function testError(): void { - $test = new \TestError; + $test = new TestError; $test->run($this->result); $this->assertEquals(1, $this->listener->errorCount()); @@ -45,7 +48,7 @@ public function testError(): void public function testFailure(): void { - $test = new \Failure; + $test = new Failure; $test->run($this->result); $this->assertEquals(1, $this->listener->failureCount()); @@ -54,7 +57,7 @@ public function testFailure(): void public function testStartStop(): void { - $test = new \Success; + $test = new Success; $test->run($this->result); $this->assertEquals(1, $this->listener->startCount()); diff --git a/tests/unit/Framework/TestSuiteIteratorTest.php b/tests/unit/Framework/TestSuiteIteratorTest.php index 95dec304c8a..054d2a572d6 100644 --- a/tests/unit/Framework/TestSuiteIteratorTest.php +++ b/tests/unit/Framework/TestSuiteIteratorTest.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Framework; +use EmptyTestCaseTest; + /** * @small */ @@ -46,7 +48,7 @@ public function testValidForNonEmptyTestSuiteInitiallyReturnsTrue(): void public function testCurrentForNonEmptyTestSuiteInitiallyReturnsFirstTest(): void { - $test = new \EmptyTestCaseTest; + $test = new EmptyTestCaseTest; $testSuite = new TestSuite; $testSuite->addTest($test); $subject = new TestSuiteIterator($testSuite); @@ -67,7 +69,7 @@ public function testRewindResetsKeyToZero(): void public function testRewindResetsCurrentToFirstElement(): void { $testSuite = new TestSuite; - $test = new \EmptyTestCaseTest; + $test = new EmptyTestCaseTest; $testSuite->addTest($test); $subject = new TestSuiteIterator($testSuite); $subject->next(); @@ -116,7 +118,7 @@ public function testGetChildrenForCurrentTestThrowsException(): void public function testGetChildrenReturnsNewInstanceWithCurrentTestSuite(): void { $childSuite = new TestSuite; - $test = new \EmptyTestCaseTest; + $test = new EmptyTestCaseTest; $childSuite->addTest($test); $testSuite = new TestSuite; @@ -158,7 +160,7 @@ private function suiteWithEmptyTestCase(): TestSuite { $suite = new TestSuite; - $suite->addTest(new \EmptyTestCaseTest); + $suite->addTest(new EmptyTestCaseTest); return $suite; } diff --git a/tests/unit/Framework/TestSuiteTest.php b/tests/unit/Framework/TestSuiteTest.php index d2d829c9438..1f2771db17b 100644 --- a/tests/unit/Framework/TestSuiteTest.php +++ b/tests/unit/Framework/TestSuiteTest.php @@ -9,6 +9,26 @@ */ namespace PHPUnit\Framework; +use const DIRECTORY_SEPARATOR; +use const PHP_EOL; +use function array_pop; +use BeforeAndAfterTest; +use BeforeClassAndAfterClassTest; +use BeforeClassWithOnlyDataProviderTest; +use DataProviderDependencyTest; +use DataProviderIncompleteTest; +use DataProviderSkippedTest; +use ExceptionInTearDownAfterClassTest; +use InheritedTestCase; +use NoTestCases; +use NotPublicTestCase; +use NotVoidTestCase; +use OneTestCase; +use OverrideTestCase; +use RequirementsClassBeforeClassHookTest; +use TestCaseWithExceptionInHook; +use TestWithTest; + /** * @small */ @@ -35,7 +55,7 @@ protected function tearDown(): void public function testSuiteNameCanBeSameAsExistingNonTestClassName(): void { $suite = new TestSuite('stdClass'); - $suite->addTestSuite(\OneTestCase::class); + $suite->addTestSuite(OneTestCase::class); $suite->run($this->result); $this->assertCount(1, $this->result); @@ -43,7 +63,7 @@ public function testSuiteNameCanBeSameAsExistingNonTestClassName(): void public function testAddTestSuite(): void { - $suite = new TestSuite(\OneTestCase::class); + $suite = new TestSuite(OneTestCase::class); $suite->run($this->result); @@ -52,7 +72,7 @@ public function testAddTestSuite(): void public function testInheritedTests(): void { - $suite = new TestSuite(\InheritedTestCase::class); + $suite = new TestSuite(InheritedTestCase::class); $suite->run($this->result); @@ -62,7 +82,7 @@ public function testInheritedTests(): void public function testNoTestCases(): void { - $suite = new TestSuite(\NoTestCases::class); + $suite = new TestSuite(NoTestCases::class); $suite->run($this->result); @@ -74,21 +94,21 @@ public function testNoTestCases(): void public function testNotPublicTestCase(): void { - $suite = new TestSuite(\NotPublicTestCase::class); + $suite = new TestSuite(NotPublicTestCase::class); $this->assertCount(1, $suite); } public function testNotVoidTestCase(): void { - $suite = new TestSuite(\NotVoidTestCase::class); + $suite = new TestSuite(NotVoidTestCase::class); $this->assertCount(1, $suite); } public function testOneTestCase(): void { - $suite = new TestSuite(\OneTestCase::class); + $suite = new TestSuite(OneTestCase::class); $suite->run($this->result); @@ -100,7 +120,7 @@ public function testOneTestCase(): void public function testShadowedTests(): void { - $suite = new TestSuite(\OverrideTestCase::class); + $suite = new TestSuite(OverrideTestCase::class); $suite->run($this->result); @@ -109,42 +129,42 @@ public function testShadowedTests(): void public function testBeforeClassAndAfterClassAnnotations(): void { - $suite = new TestSuite(\BeforeClassAndAfterClassTest::class); + $suite = new TestSuite(BeforeClassAndAfterClassTest::class); - \BeforeClassAndAfterClassTest::resetProperties(); + BeforeClassAndAfterClassTest::resetProperties(); $suite->run($this->result); - $this->assertEquals(1, \BeforeClassAndAfterClassTest::$beforeClassWasRun, '@beforeClass method was not run once for the whole suite.'); - $this->assertEquals(1, \BeforeClassAndAfterClassTest::$afterClassWasRun, '@afterClass method was not run once for the whole suite.'); + $this->assertEquals(1, BeforeClassAndAfterClassTest::$beforeClassWasRun, '@beforeClass method was not run once for the whole suite.'); + $this->assertEquals(1, BeforeClassAndAfterClassTest::$afterClassWasRun, '@afterClass method was not run once for the whole suite.'); } public function testBeforeClassWithDataProviders(): void { - $suite = new TestSuite(\BeforeClassWithOnlyDataProviderTest::class); + $suite = new TestSuite(BeforeClassWithOnlyDataProviderTest::class); - \BeforeClassWithOnlyDataProviderTest::resetProperties(); + BeforeClassWithOnlyDataProviderTest::resetProperties(); $suite->run($this->result); - $this->assertTrue(\BeforeClassWithOnlyDataProviderTest::$setUpBeforeClassWasCalled, 'setUpBeforeClass method was not run.'); - $this->assertTrue(\BeforeClassWithOnlyDataProviderTest::$beforeClassWasCalled, '@beforeClass method was not run.'); + $this->assertTrue(BeforeClassWithOnlyDataProviderTest::$setUpBeforeClassWasCalled, 'setUpBeforeClass method was not run.'); + $this->assertTrue(BeforeClassWithOnlyDataProviderTest::$beforeClassWasCalled, '@beforeClass method was not run.'); } public function testBeforeAnnotation(): void { - $test = new TestSuite(\BeforeAndAfterTest::class); + $test = new TestSuite(BeforeAndAfterTest::class); - \BeforeAndAfterTest::resetProperties(); + BeforeAndAfterTest::resetProperties(); $test->run(); - $this->assertEquals(2, \BeforeAndAfterTest::$beforeWasRun); - $this->assertEquals(2, \BeforeAndAfterTest::$afterWasRun); + $this->assertEquals(2, BeforeAndAfterTest::$beforeWasRun); + $this->assertEquals(2, BeforeAndAfterTest::$afterWasRun); } public function testTestWithAnnotation(): void { - $test = new TestSuite(\TestWithTest::class); + $test = new TestSuite(TestWithTest::class); - \BeforeAndAfterTest::resetProperties(); + BeforeAndAfterTest::resetProperties(); $result = $test->run(); $this->assertCount(4, $result->passed()); @@ -152,7 +172,7 @@ public function testTestWithAnnotation(): void public function testSkippedTestDataProvider(): void { - $suite = new TestSuite(\DataProviderSkippedTest::class); + $suite = new TestSuite(DataProviderSkippedTest::class); $suite->run($this->result); @@ -162,7 +182,7 @@ public function testSkippedTestDataProvider(): void public function testItErrorsOnlyOnceOnHookException(): void { - $suite = new TestSuite(\TestCaseWithExceptionInHook::class); + $suite = new TestSuite(TestCaseWithExceptionInHook::class); $suite->run($this->result); @@ -173,12 +193,12 @@ public function testItErrorsOnlyOnceOnHookException(): void public function testTestDataProviderDependency(): void { - $suite = new TestSuite(\DataProviderDependencyTest::class); + $suite = new TestSuite(DataProviderDependencyTest::class); $suite->run($this->result); $skipped = $this->result->skipped(); - $lastSkippedResult = \array_pop($skipped); + $lastSkippedResult = array_pop($skipped); $message = $lastSkippedResult->thrownException()->getMessage(); $this->assertStringContainsString('Test for DataProviderDependencyTest::testDependency skipped by data provider', $message); @@ -186,7 +206,7 @@ public function testTestDataProviderDependency(): void public function testIncompleteTestDataProvider(): void { - $suite = new TestSuite(\DataProviderIncompleteTest::class); + $suite = new TestSuite(DataProviderIncompleteTest::class); $suite->run($this->result); @@ -196,7 +216,7 @@ public function testIncompleteTestDataProvider(): void public function testRequirementsBeforeClassHook(): void { - $suite = new TestSuite(\RequirementsClassBeforeClassHookTest::class); + $suite = new TestSuite(RequirementsClassBeforeClassHookTest::class); $suite->run($this->result); @@ -210,7 +230,7 @@ public function testDoNotSkipInheritedClass(): void 'DontSkipInheritedClass' ); - $dir = TEST_FILES_PATH . \DIRECTORY_SEPARATOR . 'Inheritance' . \DIRECTORY_SEPARATOR; + $dir = TEST_FILES_PATH . DIRECTORY_SEPARATOR . 'Inheritance' . DIRECTORY_SEPARATOR; $suite->addTestFile($dir . 'InheritanceA.php'); $suite->addTestFile($dir . 'InheritanceB.php'); @@ -225,7 +245,7 @@ public function testDoNotSkipInheritedClass(): void */ public function testTearDownAfterClassInTestSuite(): void { - $suite = new TestSuite(\ExceptionInTearDownAfterClassTest::class); + $suite = new TestSuite(ExceptionInTearDownAfterClassTest::class); $suite->run($this->result); $this->assertSame(3, $this->result->count()); @@ -234,7 +254,7 @@ public function testTearDownAfterClassInTestSuite(): void $failure = $this->result->failures()[0]; $this->assertSame( - 'Exception in ExceptionInTearDownAfterClassTest::tearDownAfterClass' . \PHP_EOL . + 'Exception in ExceptionInTearDownAfterClassTest::tearDownAfterClass' . PHP_EOL . 'throw Exception in tearDownAfterClass()', $failure->thrownException()->getMessage() ); diff --git a/tests/unit/Runner/DefaultTestResultCacheTest.php b/tests/unit/Runner/DefaultTestResultCacheTest.php index f925ce6fbd1..828e725bd96 100644 --- a/tests/unit/Runner/DefaultTestResultCacheTest.php +++ b/tests/unit/Runner/DefaultTestResultCacheTest.php @@ -9,6 +9,11 @@ */ namespace PHPUnit\Runner; +use function sys_get_temp_dir; +use function tempnam; +use function uniqid; +use function unlink; +use MultiDependencyTest; use PHPUnit\Framework\TestCase; /** @@ -17,18 +22,49 @@ */ final class DefaultTestResultCacheTest extends TestCase { - /** - * @var DefaultTestResultCache - */ - private $subject; + public function testGetTimeForNonExistentTestNameReturnsFloatZero(): void + { + $this->assertSame(0.0, (new DefaultTestResultCache)->getTime('doesNotExist')); + } - protected function setUp(): void + public function testReadsCacheFromProvidedFilename(): void { - $this->subject = new DefaultTestResultCache(); + $cacheFile = TEST_FILES_PATH . '../end-to-end/execution-order/_files/MultiDependencyTest_result_cache.txt'; + $cache = new DefaultTestResultCache($cacheFile); + $cache->load(); + + $this->assertSame(BaseTestRunner::STATUS_UNKNOWN, $cache->getState(MultiDependencyTest::class . '::testOne')); + $this->assertSame(BaseTestRunner::STATUS_SKIPPED, $cache->getState(MultiDependencyTest::class . '::testFive')); } - public function testGetTimeForNonExistentTestNameReturnsFloatZero(): void + public function testDoesClearCacheBeforeLoad(): void { - $this->assertSame(0.0, $this->subject->getTime('doesNotExist')); + $cacheFile = TEST_FILES_PATH . '../end-to-end/execution-order/_files/MultiDependencyTest_result_cache.txt'; + $cache = new DefaultTestResultCache($cacheFile); + $cache->setState('someTest', BaseTestRunner::STATUS_FAILURE); + + $this->assertSame(BaseTestRunner::STATUS_UNKNOWN, $cache->getState(MultiDependencyTest::class . '::testFive')); + + $cache->load(); + + $this->assertSame(BaseTestRunner::STATUS_UNKNOWN, $cache->getState(MultiDependencyTest::class . '::someTest')); + $this->assertSame(BaseTestRunner::STATUS_SKIPPED, $cache->getState(MultiDependencyTest::class . '::testFive')); + } + + public function testCanPersistCacheToFile(): void + { + $cacheFile = tempnam(sys_get_temp_dir(), 'phpunit_'); + $cache = new DefaultTestResultCache($cacheFile); + $testName = 'test' . uniqid('', true); + + $cache->setState($testName, BaseTestRunner::STATUS_SKIPPED); + $cache->persist(); + + $cache = new DefaultTestResultCache($cacheFile); + $cache->load(); + + $this->assertSame(BaseTestRunner::STATUS_SKIPPED, $cache->getState($testName)); + + unlink($cacheFile); } } diff --git a/tests/unit/Runner/Filter/NameFilterIteratorTest.php b/tests/unit/Runner/Filter/NameFilterIteratorTest.php index 3fa64f501a4..94a6ff2f800 100644 --- a/tests/unit/Runner/Filter/NameFilterIteratorTest.php +++ b/tests/unit/Runner/Filter/NameFilterIteratorTest.php @@ -9,6 +9,7 @@ */ namespace PHPUnit\Runner\Filter; +use BankAccountTest; use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestSuite; @@ -30,7 +31,7 @@ public function testCaseInsensitiveMatch(): void private function createFilter(string $filter): NameFilterIterator { $suite = new TestSuite; - $suite->addTest(new \BankAccountTest('testBalanceIsInitiallyZero')); + $suite->addTest(new BankAccountTest('testBalanceIsInitiallyZero')); $iterator = new NameFilterIterator($suite->getIterator(), $filter); diff --git a/tests/unit/Runner/PhptTestCaseTest.php b/tests/unit/Runner/PhptTestCaseTest.php index 4ead9496817..a995382d020 100644 --- a/tests/unit/Runner/PhptTestCaseTest.php +++ b/tests/unit/Runner/PhptTestCaseTest.php @@ -9,6 +9,12 @@ */ namespace PHPUnit\Runner; +use const PHP_EOL; +use function file_put_contents; +use function strtr; +use function sys_get_temp_dir; +use function touch; +use function unlink; use PHPUnit\Framework\TestCase; use PHPUnit\Util\PHP\AbstractPhpProcess; @@ -71,9 +77,9 @@ final class PhptTestCaseTest extends TestCase protected function setUp(): void { - $this->dirname = \sys_get_temp_dir(); + $this->dirname = sys_get_temp_dir(); $this->filename = $this->dirname . '/phpunit.phpt'; - \touch($this->filename); + touch($this->filename); $this->phpProcess = $this->getMockForAbstractClass(AbstractPhpProcess::class, [], '', false); $this->testCase = new PhptTestCase($this->filename, $this->phpProcess); @@ -81,7 +87,7 @@ protected function setUp(): void protected function tearDown(): void { - @\unlink($this->filename); + @unlink($this->filename); $this->phpProcess = null; $this->testCase = null; @@ -101,7 +107,7 @@ public function testShouldRunFileSectionAsTest(): void { $this->setPhpContent($this->ensureCorrectEndOfLine(self::EXPECT_CONTENT)); - $fileSection = '' . \PHP_EOL; + $fileSection = '' . PHP_EOL; $this->phpProcess ->expects($this->once()) @@ -125,7 +131,7 @@ public function testRenderFileSection(): void EOF )); - $renderedCode = "dirname . "' . '" . $this->filename . "'; ?>" . \PHP_EOL; + $renderedCode = "dirname . "' . '" . $this->filename . "'; ?>" . PHP_EOL; $this->phpProcess ->expects($this->once()) @@ -138,13 +144,13 @@ public function testRenderFileSection(): void public function testRenderSkipifSection(): void { - $phptContent = self::EXPECT_CONTENT . \PHP_EOL; - $phptContent .= '--SKIPIF--' . \PHP_EOL; - $phptContent .= "" . \PHP_EOL; + $phptContent = self::EXPECT_CONTENT . PHP_EOL; + $phptContent .= '--SKIPIF--' . PHP_EOL; + $phptContent .= "" . PHP_EOL; $this->setPhpContent($phptContent); - $renderedCode = "filename . "'; ?>" . \PHP_EOL; + $renderedCode = "filename . "'; ?>" . PHP_EOL; $this->phpProcess ->expects($this->at(0)) @@ -157,10 +163,10 @@ public function testRenderSkipifSection(): void public function testShouldRunSkipifSectionWhenExists(): void { - $skipifSection = '' . \PHP_EOL; + $skipifSection = '' . PHP_EOL; - $phptContent = self::EXPECT_CONTENT . \PHP_EOL; - $phptContent .= '--SKIPIF--' . \PHP_EOL; + $phptContent = self::EXPECT_CONTENT . PHP_EOL; + $phptContent .= '--SKIPIF--' . PHP_EOL; $phptContent .= $skipifSection; $this->setPhpContent($phptContent); @@ -176,10 +182,10 @@ public function testShouldRunSkipifSectionWhenExists(): void public function testShouldNotRunTestSectionIfSkipifSectionReturnsOutputWithSkipWord(): void { - $skipifSection = '' . \PHP_EOL; + $skipifSection = '' . PHP_EOL; - $phptContent = self::EXPECT_CONTENT . \PHP_EOL; - $phptContent .= '--SKIPIF--' . \PHP_EOL; + $phptContent = self::EXPECT_CONTENT . PHP_EOL; + $phptContent .= '--SKIPIF--' . PHP_EOL; $phptContent .= $skipifSection; $this->setPhpContent($phptContent); @@ -195,10 +201,10 @@ public function testShouldNotRunTestSectionIfSkipifSectionReturnsOutputWithSkipW public function testShouldRunCleanSectionWhenDefined(): void { - $cleanSection = '' . \PHP_EOL; + $cleanSection = '' . PHP_EOL; - $phptContent = self::EXPECT_CONTENT . \PHP_EOL; - $phptContent .= '--CLEAN--' . \PHP_EOL; + $phptContent = self::EXPECT_CONTENT . PHP_EOL; + $phptContent .= '--CLEAN--' . PHP_EOL; $phptContent .= $cleanSection; $this->setPhpContent($phptContent); @@ -328,11 +334,11 @@ public function testShouldValidateExpectregexSession(): void */ private function setPhpContent($content): void { - \file_put_contents($this->filename, $content); + file_put_contents($this->filename, $content); } /** - * Ensures the correct line ending is used for comparison + * Ensures the correct line ending is used for comparison. * * @param string $content * @@ -340,12 +346,12 @@ private function setPhpContent($content): void */ private function ensureCorrectEndOfLine($content) { - return \strtr( + return strtr( $content, [ - "\r\n" => \PHP_EOL, - "\r" => \PHP_EOL, - "\n" => \PHP_EOL, + "\r\n" => PHP_EOL, + "\r" => PHP_EOL, + "\n" => PHP_EOL, ] ); } diff --git a/tests/unit/Runner/ResultCacheExtensionTest.php b/tests/unit/Runner/ResultCacheExtensionTest.php index aa9db08fee6..1f062230902 100644 --- a/tests/unit/Runner/ResultCacheExtensionTest.php +++ b/tests/unit/Runner/ResultCacheExtensionTest.php @@ -9,10 +9,18 @@ */ namespace PHPUnit\Runner; +use EmptyTestCaseTest; +use Failure; use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCaseTest; use PHPUnit\Framework\TestResult; use PHPUnit\Framework\TestSuite; +use Success; +use TestError; +use TestIncomplete; +use TestRisky; +use TestSkipped; +use TestWarning; /** * @group test-reorder @@ -76,64 +84,64 @@ public function longTestNamesDataprovider(): array public function testError(): void { - $test = new \TestError('test_name'); + $test = new TestError('test_name'); $test->run($this->result); - $this->assertSame(BaseTestRunner::STATUS_ERROR, $this->cache->getState(\TestError::class . '::test_name')); + $this->assertSame(BaseTestRunner::STATUS_ERROR, $this->cache->getState(TestError::class . '::test_name')); } public function testFailure(): void { - $test = new \Failure('test_name'); + $test = new Failure('test_name'); $test->run($this->result); - $this->assertSame(BaseTestRunner::STATUS_FAILURE, $this->cache->getState(\Failure::class . '::test_name')); + $this->assertSame(BaseTestRunner::STATUS_FAILURE, $this->cache->getState(Failure::class . '::test_name')); } public function testSkipped(): void { - $test = new \TestSkipped('test_name'); + $test = new TestSkipped('test_name'); $test->run($this->result); - $this->assertSame(BaseTestRunner::STATUS_SKIPPED, $this->cache->getState(\TestSkipped::class . '::test_name')); + $this->assertSame(BaseTestRunner::STATUS_SKIPPED, $this->cache->getState(TestSkipped::class . '::test_name')); } public function testIncomplete(): void { - $test = new \TestIncomplete('test_name'); + $test = new TestIncomplete('test_name'); $test->run($this->result); - $this->assertSame(BaseTestRunner::STATUS_INCOMPLETE, $this->cache->getState(\TestIncomplete::class . '::test_name')); + $this->assertSame(BaseTestRunner::STATUS_INCOMPLETE, $this->cache->getState(TestIncomplete::class . '::test_name')); } public function testPassedTestsOnlyCacheTime(): void { - $test = new \Success('test_name'); + $test = new Success('test_name'); $test->run($this->result); - $this->assertSame(BaseTestRunner::STATUS_UNKNOWN, $this->cache->getState(\Success::class . '::test_name')); + $this->assertSame(BaseTestRunner::STATUS_UNKNOWN, $this->cache->getState(Success::class . '::test_name')); } public function testWarning(): void { - $test = new \TestWarning('test_name'); + $test = new TestWarning('test_name'); $test->run($this->result); - $this->assertSame(BaseTestRunner::STATUS_WARNING, $this->cache->getState(\TestWarning::class . '::test_name')); + $this->assertSame(BaseTestRunner::STATUS_WARNING, $this->cache->getState(TestWarning::class . '::test_name')); } public function testRisky(): void { - $test = new \TestRisky('test_name'); + $test = new TestRisky('test_name'); $test->run($this->result); - $this->assertSame(BaseTestRunner::STATUS_RISKY, $this->cache->getState(\TestRisky::class . '::test_name')); + $this->assertSame(BaseTestRunner::STATUS_RISKY, $this->cache->getState(TestRisky::class . '::test_name')); } public function testEmptySuite(): void { $suite = new TestSuite; - $suite->addTestSuite(\EmptyTestCaseTest::class); + $suite->addTestSuite(EmptyTestCaseTest::class); $suite->run($this->result); $this->assertSame(BaseTestRunner::STATUS_WARNING, $this->cache->getState('Warning')); diff --git a/tests/unit/Runner/TestResultCacheTest.php b/tests/unit/Runner/TestResultCacheTest.php deleted file mode 100644 index 2c4cf3d4082..00000000000 --- a/tests/unit/Runner/TestResultCacheTest.php +++ /dev/null @@ -1,96 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ -use PHPUnit\Framework\TestCase; -use PHPUnit\Runner\BaseTestRunner; -use PHPUnit\Runner\DefaultTestResultCache; - -/** - * @group test-reorder - * @small - */ -final class TestResultCacheTest extends TestCase -{ - public function testReadsCacheFromProvidedFilename(): void - { - $cacheFile = TEST_FILES_PATH . '../end-to-end/execution-order/_files/MultiDependencyTest_result_cache.txt'; - $cache = new DefaultTestResultCache($cacheFile); - $cache->load(); - - $this->assertSame(BaseTestRunner::STATUS_UNKNOWN, $cache->getState(\MultiDependencyTest::class . '::testOne')); - $this->assertSame(BaseTestRunner::STATUS_SKIPPED, $cache->getState(\MultiDependencyTest::class . '::testFive')); - } - - public function testDoesClearCacheBeforeLoad(): void - { - $cacheFile = TEST_FILES_PATH . '../end-to-end/execution-order/_files/MultiDependencyTest_result_cache.txt'; - $cache = new DefaultTestResultCache($cacheFile); - $cache->setState('someTest', BaseTestRunner::STATUS_FAILURE); - - $this->assertSame(BaseTestRunner::STATUS_UNKNOWN, $cache->getState(\MultiDependencyTest::class . '::testFive')); - - $cache->load(); - - $this->assertSame(BaseTestRunner::STATUS_UNKNOWN, $cache->getState(\MultiDependencyTest::class . '::someTest')); - $this->assertSame(BaseTestRunner::STATUS_SKIPPED, $cache->getState(\MultiDependencyTest::class . '::testFive')); - } - - public function testShouldNotSerializePassedTestsAsDefectButTimeIsStored(): void - { - $cache = new DefaultTestResultCache; - $cache->setState('testOne', BaseTestRunner::STATUS_PASSED); - $cache->setTime('testOne', 123); - - $data = \serialize($cache); - $this->assertSame('C:37:"PHPUnit\Runner\DefaultTestResultCache":64:{a:2:{s:7:"defects";a:0:{}s:5:"times";a:1:{s:7:"testOne";d:123;}}}', $data); - } - - public function testCanPersistCacheToFile(): void - { - // Create a cache with one result and store it - $cacheFile = \tempnam(\sys_get_temp_dir(), 'phpunit_'); - $cache = new DefaultTestResultCache($cacheFile); - $testName = 'test' . \uniqid(); - $cache->setState($testName, BaseTestRunner::STATUS_SKIPPED); - $cache->persist(); - unset($cache); - - // Load the cache we just created - $loadedCache = new DefaultTestResultCache($cacheFile); - $loadedCache->load(); - $this->assertSame(BaseTestRunner::STATUS_SKIPPED, $loadedCache->getState($testName)); - - // Clean up - \unlink($cacheFile); - } - - public function testShouldReturnEmptyCacheWhenFileDoesNotExist(): void - { - $cache = new DefaultTestResultCache('/a/wrong/path/file'); - $cache->load(); - - $this->assertTrue($this->isSerializedEmptyCache(\serialize($cache))); - } - - public function testShouldReturnEmptyCacheFromInvalidFile(): void - { - $cacheFile = \tempnam(\sys_get_temp_dir(), 'phpunit_'); - \file_put_contents($cacheFile, ''); - - $cache = new DefaultTestResultCache($cacheFile); - $cache->load(); - - $this->assertTrue($this->isSerializedEmptyCache(\serialize($cache))); - } - - public function isSerializedEmptyCache(string $data): bool - { - return $data === 'C:37:"PHPUnit\Runner\DefaultTestResultCache":44:{a:2:{s:7:"defects";a:0:{}s:5:"times";a:0:{}}}'; - } -} diff --git a/tests/unit/Runner/TestSuiteSorterTest.php b/tests/unit/Runner/TestSuiteSorterTest.php index 1e20dd0262f..e8dec9bb162 100644 --- a/tests/unit/Runner/TestSuiteSorterTest.php +++ b/tests/unit/Runner/TestSuiteSorterTest.php @@ -9,8 +9,12 @@ */ namespace PHPUnit\Runner; +use function mt_srand; +use EmptyTestCaseTest; +use MultiDependencyTest; use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestSuite; +use TestWithDifferentSizes; /** * @testdox Reordering test execution @@ -20,24 +24,24 @@ final class TestSuiteSorterTest extends TestCase { /** - * Constants to improve clarity of @dataprovider + * Constants to improve clarity of @dataprovider. */ private const IGNORE_DEPENDENCIES = false; private const RESOLVE_DEPENDENCIES = true; private const MULTIDEPENDENCYTEST_EXECUTION_ORDER = [ - \MultiDependencyTest::class . '::testOne', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testFour', - \MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testFive', ]; public function testThrowsExceptionWhenUsingInvalidOrderOption(): void { $suite = new TestSuite; - $suite->addTestSuite(\MultiDependencyTest::class); + $suite->addTestSuite(MultiDependencyTest::class); $sorter = new TestSuiteSorter; $this->expectException(Exception::class); @@ -48,7 +52,7 @@ public function testThrowsExceptionWhenUsingInvalidOrderOption(): void public function testThrowsExceptionWhenUsingInvalidOrderDefectsOption(): void { $suite = new TestSuite; - $suite->addTestSuite(\MultiDependencyTest::class); + $suite->addTestSuite(MultiDependencyTest::class); $sorter = new TestSuiteSorter; $this->expectException(Exception::class); @@ -78,7 +82,7 @@ public function testShouldNotAffectEmptyTestSuite(int $order, bool $resolveDepen public function testBasicExecutionOrderOptions(int $order, bool $resolveDependencies, array $expectedOrder): void { $suite = new TestSuite; - $suite->addTestSuite(\MultiDependencyTest::class); + $suite->addTestSuite(MultiDependencyTest::class); $sorter = new TestSuiteSorter; $sorter->reorderTestsInSuite($suite, $order, $resolveDependencies, TestSuiteSorter::ORDER_DEFAULT); @@ -90,18 +94,18 @@ public function testBasicExecutionOrderOptions(int $order, bool $resolveDependen public function testCanSetRandomizationWithASeed(): void { $suite = new TestSuite; - $suite->addTestSuite(\MultiDependencyTest::class); + $suite->addTestSuite(MultiDependencyTest::class); $sorter = new TestSuiteSorter; - \mt_srand(54321); + mt_srand(54321); $sorter->reorderTestsInSuite($suite, TestSuiteSorter::ORDER_RANDOMIZED, false, TestSuiteSorter::ORDER_DEFAULT); $expectedOrder = [ - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testFour', - \MultiDependencyTest::class . '::testFive', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testOne', ]; $this->assertSame($expectedOrder, $sorter->getExecutionOrder()); @@ -110,18 +114,18 @@ public function testCanSetRandomizationWithASeed(): void public function testCanSetRandomizationWithASeedAndResolveDependencies(): void { $suite = new TestSuite; - $suite->addTestSuite(\MultiDependencyTest::class); + $suite->addTestSuite(MultiDependencyTest::class); $sorter = new TestSuiteSorter; - \mt_srand(54321); + mt_srand(54321); $sorter->reorderTestsInSuite($suite, TestSuiteSorter::ORDER_RANDOMIZED, true, TestSuiteSorter::ORDER_DEFAULT); $expectedOrder = [ - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testFive', - \MultiDependencyTest::class . '::testOne', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testFour', ]; $this->assertSame($expectedOrder, $sorter->getExecutionOrder()); @@ -134,7 +138,7 @@ public function testOrderDurationWithoutCache(bool $resolveDependencies, array $ { $suite = new TestSuite; - $suite->addTestSuite(\MultiDependencyTest::class); + $suite->addTestSuite(MultiDependencyTest::class); $sorter = new TestSuiteSorter; @@ -154,21 +158,21 @@ public function orderDurationWithoutCacheProvider(): array 'dependency-ignore' => [ self::IGNORE_DEPENDENCIES, [ - \MultiDependencyTest::class . '::testOne', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testFour', - \MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testFive', ], ], 'dependency-resolve' => [ self::RESOLVE_DEPENDENCIES, [ - \MultiDependencyTest::class . '::testOne', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testFour', - \MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testFive', ], ], ]; @@ -181,12 +185,12 @@ public function testOrderDurationWithCache(bool $resolveDependencies, array $tes { $suite = new TestSuite; - $suite->addTestSuite(\MultiDependencyTest::class); + $suite->addTestSuite(MultiDependencyTest::class); $cache = new DefaultTestResultCache; foreach ($testTimes as $testName => $time) { - $cache->setTime(\MultiDependencyTest::class . '::' . $testName, $time); + $cache->setTime(MultiDependencyTest::class . '::' . $testName, $time); } $sorter = new TestSuiteSorter($cache); @@ -214,11 +218,11 @@ public function orderDurationWithCacheProvider(): array 'testFive' => 1, ], [ - \MultiDependencyTest::class . '::testOne', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testFour', - \MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testFive', ], ], 'duration-same-dependency-resolve' => [ @@ -231,11 +235,11 @@ public function orderDurationWithCacheProvider(): array 'testFive' => 1, ], [ - \MultiDependencyTest::class . '::testOne', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testFour', - \MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testFive', ], ], 'duration-different-dependency-ignore' => [ @@ -248,11 +252,11 @@ public function orderDurationWithCacheProvider(): array 'testFive' => 2, ], [ - \MultiDependencyTest::class . '::testFour', - \MultiDependencyTest::class . '::testFive', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testOne', ], ], 'duration-different-dependency-resolve' => [ @@ -265,11 +269,11 @@ public function orderDurationWithCacheProvider(): array 'testFive' => 2, ], [ - \MultiDependencyTest::class . '::testFive', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testOne', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testFour', ], ], ]; @@ -281,13 +285,13 @@ public function orderDurationWithCacheProvider(): array public function testSuiteSorterDefectsOptions(int $order, bool $resolveDependencies, array $runState, array $expected): void { $suite = new TestSuite; - $suite->addTestSuite(\MultiDependencyTest::class); + $suite->addTestSuite(MultiDependencyTest::class); $cache = new DefaultTestResultCache; foreach ($runState as $testName => $data) { - $cache->setState(\MultiDependencyTest::class . '::' . $testName, $data['state']); - $cache->setTime(\MultiDependencyTest::class . '::' . $testName, $data['time']); + $cache->setState(MultiDependencyTest::class . '::' . $testName, $data['state']); + $cache->setTime(MultiDependencyTest::class . '::' . $testName, $data['time']); } $sorter = new TestSuiteSorter($cache); @@ -302,7 +306,7 @@ public function testSuiteSorterDefectsOptions(int $order, bool $resolveDependenc * - it has five tests 'testOne' ... 'testFive' * - 'testThree' @depends on both 'testOne' and 'testTwo' * - 'testFour' @depends on 'MultiDependencyTest::testThree' to test FQN @depends - * - 'testFive' has no dependencies + * - 'testFive' has no dependencies. */ public function commonSorterOptionsProvider(): array { @@ -311,11 +315,11 @@ public function commonSorterOptionsProvider(): array TestSuiteSorter::ORDER_DEFAULT, self::IGNORE_DEPENDENCIES, [ - \MultiDependencyTest::class . '::testOne', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testFour', - \MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testFive', ], ], @@ -324,11 +328,11 @@ public function commonSorterOptionsProvider(): array TestSuiteSorter::ORDER_DEFAULT, self::RESOLVE_DEPENDENCIES, [ - \MultiDependencyTest::class . '::testOne', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testFour', - \MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testFive', ], ], @@ -337,11 +341,11 @@ public function commonSorterOptionsProvider(): array TestSuiteSorter::ORDER_REVERSED, self::IGNORE_DEPENDENCIES, [ - \MultiDependencyTest::class . '::testFive', - \MultiDependencyTest::class . '::testFour', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testOne', ], ], @@ -350,11 +354,11 @@ public function commonSorterOptionsProvider(): array TestSuiteSorter::ORDER_REVERSED, self::RESOLVE_DEPENDENCIES, [ - \MultiDependencyTest::class . '::testFive', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testOne', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testFour', ], ], ]; @@ -366,7 +370,7 @@ public function commonSorterOptionsProvider(): array * - it has five tests 'testOne' ... 'testFive' * - 'testThree' @depends on both 'testOne' and 'testTwo' * - 'testFour' @depends on 'MultiDependencyTest::testThree' to test FQN @depends - * - 'testFive' has no dependencies + * - 'testFive' has no dependencies. */ public function defectsSorterOptionsProvider(): array { @@ -383,11 +387,11 @@ public function defectsSorterOptionsProvider(): array 'testFive' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], ], [ - \MultiDependencyTest::class . '::testOne', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testFour', - \MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testFive', ], ], @@ -399,11 +403,11 @@ public function defectsSorterOptionsProvider(): array // empty result cache ], [ - \MultiDependencyTest::class . '::testOne', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testFour', - \MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testFive', ], ], @@ -419,11 +423,11 @@ public function defectsSorterOptionsProvider(): array 'testFive' => ['state' => BaseTestRunner::STATUS_SKIPPED, 'time' => 1], ], [ - \MultiDependencyTest::class . '::testFive', - \MultiDependencyTest::class . '::testOne', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testFour', ], ], @@ -439,11 +443,11 @@ public function defectsSorterOptionsProvider(): array 'testFive' => ['state' => BaseTestRunner::STATUS_SKIPPED, 'time' => 0], ], [ - \MultiDependencyTest::class . '::testFive', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testOne', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testFour', ], ], @@ -459,11 +463,11 @@ public function defectsSorterOptionsProvider(): array 'testFive' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], ], [ - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testOne', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testFour', - \MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testFive', ], ], @@ -479,11 +483,11 @@ public function defectsSorterOptionsProvider(): array 'testFive' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], ], [ - \MultiDependencyTest::class . '::testOne', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testFour', - \MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testFive', ], ], @@ -499,11 +503,11 @@ public function defectsSorterOptionsProvider(): array 'testFive' => ['state' => BaseTestRunner::STATUS_PASSED, 'time' => 1], ], [ - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testFive', - \MultiDependencyTest::class . '::testFour', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testOne', ], ], @@ -520,11 +524,11 @@ public function defectsSorterOptionsProvider(): array 'testFive' => ['state' => BaseTestRunner::STATUS_SKIPPED, 'time' => 1], ], [ - \MultiDependencyTest::class . '::testFive', - \MultiDependencyTest::class . '::testOne', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testFour', ], ], @@ -542,11 +546,11 @@ public function defectsSorterOptionsProvider(): array 'testThree' => ['state' => BaseTestRunner::STATUS_SKIPPED, 'time' => 1], ], [ - \MultiDependencyTest::class . '::testFive', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testOne', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testFour', ], ], @@ -564,11 +568,11 @@ public function defectsSorterOptionsProvider(): array 'testFive' => ['state' => BaseTestRunner::STATUS_FAILURE, 'time' => 1], ], [ - \MultiDependencyTest::class . '::testFive', - \MultiDependencyTest::class . '::testOne', - \MultiDependencyTest::class . '::testTwo', - \MultiDependencyTest::class . '::testThree', - \MultiDependencyTest::class . '::testFour', + MultiDependencyTest::class . '::testFive', + MultiDependencyTest::class . '::testOne', + MultiDependencyTest::class . '::testTwo', + MultiDependencyTest::class . '::testThree', + MultiDependencyTest::class . '::testFour', ], ], ]; @@ -580,13 +584,13 @@ public function defectsSorterOptionsProvider(): array public function testCanHandleSuiteWithEmptyTestCase(): void { $suite = new TestSuite; - $suite->addTestSuite(\EmptyTestCaseTest::class); + $suite->addTestSuite(EmptyTestCaseTest::class); $sorter = new TestSuiteSorter; $sorter->reorderTestsInSuite($suite, TestSuiteSorter::ORDER_DEFAULT, false, TestSuiteSorter::ORDER_DEFAULT); - $this->assertSame(\EmptyTestCaseTest::class, $suite->tests()[0]->getName()); + $this->assertSame(EmptyTestCaseTest::class, $suite->tests()[0]->getName()); $this->assertSame('No tests found in class "EmptyTestCaseTest".', $suite->tests()[0]->tests()[0]->getMessage()); } @@ -612,20 +616,20 @@ public function suiteSorterOptionPermutationsProvider(): array public function testOrderBySize(): void { $suite = new TestSuite; - $suite->addTestSuite(\TestWithDifferentSizes::class); + $suite->addTestSuite(TestWithDifferentSizes::class); $sorter = new TestSuiteSorter; $sorter->reorderTestsInSuite($suite, TestSuiteSorter::ORDER_SIZE, true, TestSuiteSorter::ORDER_DEFAULT); $expectedOrder = [ - \TestWithDifferentSizes::class . '::testWithSizeSmall', - \TestWithDifferentSizes::class . '::testDataProviderWithSizeSmall with data set #0', - \TestWithDifferentSizes::class . '::testDataProviderWithSizeSmall with data set #1', - \TestWithDifferentSizes::class . '::testDataProviderWithSizeMedium with data set #0', - \TestWithDifferentSizes::class . '::testDataProviderWithSizeMedium with data set #1', - \TestWithDifferentSizes::class . '::testWithSizeMedium', - \TestWithDifferentSizes::class . '::testWithSizeLarge', - \TestWithDifferentSizes::class . '::testWithSizeUnknown', + TestWithDifferentSizes::class . '::testWithSizeSmall', + TestWithDifferentSizes::class . '::testDataProviderWithSizeSmall with data set #0', + TestWithDifferentSizes::class . '::testDataProviderWithSizeSmall with data set #1', + TestWithDifferentSizes::class . '::testDataProviderWithSizeMedium with data set #0', + TestWithDifferentSizes::class . '::testDataProviderWithSizeMedium with data set #1', + TestWithDifferentSizes::class . '::testWithSizeMedium', + TestWithDifferentSizes::class . '::testWithSizeLarge', + TestWithDifferentSizes::class . '::testWithSizeUnknown', ]; $this->assertSame($expectedOrder, $sorter->getExecutionOrder()); diff --git a/tests/unit/Util/Annotation/RegistryTest.php b/tests/unit/Util/Annotation/RegistryTest.php index c71a18d8048..a43f5ad670f 100644 --- a/tests/unit/Util/Annotation/RegistryTest.php +++ b/tests/unit/Util/Annotation/RegistryTest.php @@ -9,8 +9,10 @@ */ namespace PHPUnit\Util\Annotation; +use NumericGroupAnnotationTest; use PHPUnit\Framework\TestCase; use PHPUnit\Util\Exception; +use ThisClassDoesNotExist; /** * @small @@ -25,7 +27,7 @@ public function testRegistryLookupWithExistingClassAnnotation(): void { $annotation = Registry::getInstance()->forClassName(self::class); - self::assertSame( + $this->assertSame( [ 'small' => [''], 'covers' => ['\PHPUnit\Util\Annotation\Registry'], @@ -34,7 +36,7 @@ public function testRegistryLookupWithExistingClassAnnotation(): void $annotation->symbolAnnotations() ); - self::assertSame( + $this->assertSame( $annotation, Registry::getInstance()->forClassName(self::class), 'Registry memoizes retrieved DocBlock instances' @@ -44,11 +46,11 @@ public function testRegistryLookupWithExistingClassAnnotation(): void public function testRegistryLookupWithExistingMethodAnnotation(): void { $annotation = Registry::getInstance()->forMethod( - \NumericGroupAnnotationTest::class, + NumericGroupAnnotationTest::class, 'testTicketAnnotationSupportsNumericValue' ); - self::assertSame( + $this->assertSame( [ 'testdox' => ['Empty test for @ticket numeric annotation values'], 'ticket' => ['3502'], @@ -57,10 +59,10 @@ public function testRegistryLookupWithExistingMethodAnnotation(): void $annotation->symbolAnnotations() ); - self::assertSame( + $this->assertSame( $annotation, Registry::getInstance()->forMethod( - \NumericGroupAnnotationTest::class, + NumericGroupAnnotationTest::class, 'testTicketAnnotationSupportsNumericValue' ), 'Registry memoizes retrieved DocBlock instances' @@ -73,7 +75,7 @@ public function testClassLookupForAClassThatDoesNotExistFails(): void $this->expectException(Exception::class); - $registry->forClassName(\ThisClassDoesNotExist::class); + $registry->forClassName(ThisClassDoesNotExist::class); } public function testMethodLookupForAMethodThatDoesNotExistFails(): void diff --git a/tests/unit/Util/ColorTest.php b/tests/unit/Util/ColorTest.php index e8edeb26b90..fba154dcdc3 100644 --- a/tests/unit/Util/ColorTest.php +++ b/tests/unit/Util/ColorTest.php @@ -9,6 +9,7 @@ */ namespace PHPUnit\Util; +use const DIRECTORY_SEPARATOR; use PHPUnit\Framework\TestCase; /** @@ -100,7 +101,7 @@ public function colorizeProvider(): array public function colorizePathProvider(): array { - $sep = \DIRECTORY_SEPARATOR; + $sep = DIRECTORY_SEPARATOR; $sepDim = Color::dim($sep); return [ diff --git a/tests/unit/Util/ConfigurationGeneratorTest.php b/tests/unit/Util/ConfigurationGeneratorTest.php index 81fe31715c7..2bea62a0c1b 100644 --- a/tests/unit/Util/ConfigurationGeneratorTest.php +++ b/tests/unit/Util/ConfigurationGeneratorTest.php @@ -34,7 +34,7 @@ public function testGeneratesConfigurationCorrectly(): void verbose="true"> - tests + tests diff --git a/tests/unit/Util/ConfigurationTest.php b/tests/unit/Util/ConfigurationTest.php index 7b0ba3c4b69..33bae272ee6 100644 --- a/tests/unit/Util/ConfigurationTest.php +++ b/tests/unit/Util/ConfigurationTest.php @@ -9,11 +9,25 @@ */ namespace PHPUnit\Util; +use const BAR; +use const DIRECTORY_SEPARATOR; +use const FOO; +use const PATH_SEPARATOR; +use const PHP_EOL; +use function file_put_contents; +use function getenv; +use function ini_get; +use function ini_set; +use function putenv; +use function sys_get_temp_dir; +use function uniqid; +use function unlink; use PHPUnit\Framework\Exception; use PHPUnit\Framework\TestCase; use PHPUnit\Runner\TestSuiteSorter; use PHPUnit\TextUI\ResultPrinter; use PHPUnit\Util\TestDox\CliTestDoxPrinter; +use stdClass; /** * @small @@ -102,9 +116,9 @@ public function testShouldUseDefaultValuesForInvalidIntegers(): void */ public function testShouldParseXmlConfigurationRootAttributes(string $optionName, string $optionValue, $expected): void { - $tmpFilename = \sys_get_temp_dir() . \DIRECTORY_SEPARATOR . 'phpunit.' . $optionName . \uniqid() . '.xml'; - $xml = "" . \PHP_EOL; - \file_put_contents($tmpFilename, $xml); + $tmpFilename = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'phpunit.' . $optionName . uniqid() . '.xml'; + $xml = "" . PHP_EOL; + file_put_contents($tmpFilename, $xml); $configurationInstance = Configuration::getInstance($tmpFilename); $this->assertFalse($configurationInstance->hasValidationErrors(), 'option causes validation error'); @@ -112,7 +126,7 @@ public function testShouldParseXmlConfigurationRootAttributes(string $optionName $configurationValues = $configurationInstance->getPHPUnitConfiguration(); $this->assertEquals($expected, $configurationValues[$optionName]); - @\unlink($tmpFilename); + @unlink($tmpFilename); } public function configurationRootOptionsProvider(): array @@ -143,9 +157,9 @@ public function configurationRootOptionsProvider(): array public function testShouldParseXmlConfigurationExecutionOrderCombined(): void { - $tmpFilename = \sys_get_temp_dir() . \DIRECTORY_SEPARATOR . 'phpunit.' . \uniqid() . '.xml'; - $xml = "" . \PHP_EOL; - \file_put_contents($tmpFilename, $xml); + $tmpFilename = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'phpunit.' . uniqid() . '.xml'; + $xml = "" . PHP_EOL; + file_put_contents($tmpFilename, $xml); $configurationInstance = Configuration::getInstance($tmpFilename); $this->assertFalse($configurationInstance->hasValidationErrors(), 'option causes validation error'); @@ -154,7 +168,7 @@ public function testShouldParseXmlConfigurationExecutionOrderCombined(): void $this->assertSame(TestSuiteSorter::ORDER_DEFECTS_FIRST, $configurationValues['executionOrderDefects']); $this->assertSame(true, $configurationValues['resolveDependencies']); - @\unlink($tmpFilename); + @unlink($tmpFilename); } public function testFilterConfigurationIsReadCorrectly(): void @@ -230,9 +244,9 @@ public function testTestdoxGroupConfigurationIsReadCorrectly(): void public function testListenerConfigurationIsReadCorrectly(): void { $dir = __DIR__; - $includePath = \ini_get('include_path'); + $includePath = ini_get('include_path'); - \ini_set('include_path', $dir . \PATH_SEPARATOR . $includePath); + ini_set('include_path', $dir . PATH_SEPARATOR . $includePath); $this->assertEquals( [ @@ -247,7 +261,7 @@ public function testListenerConfigurationIsReadCorrectly(): void 2 => 'April', 3 => 19.78, 4 => null, - 5 => new \stdClass, + 5 => new stdClass, 6 => TEST_FILES_PATH . 'MyTestFile.php', 7 => TEST_FILES_PATH . 'MyRelativePath', 8 => true, @@ -270,15 +284,15 @@ public function testListenerConfigurationIsReadCorrectly(): void $this->configuration->getListenerConfiguration() ); - \ini_set('include_path', $includePath); + ini_set('include_path', $includePath); } public function testExtensionConfigurationIsReadCorrectly(): void { $dir = __DIR__; - $includePath = \ini_get('include_path'); + $includePath = ini_get('include_path'); - \ini_set('include_path', $dir . \PATH_SEPARATOR . $includePath); + ini_set('include_path', $dir . PATH_SEPARATOR . $includePath); $this->assertEquals( [ @@ -293,7 +307,7 @@ public function testExtensionConfigurationIsReadCorrectly(): void 2 => 'April', 3 => 19.78, 4 => null, - 5 => new \stdClass, + 5 => new stdClass, 6 => TEST_FILES_PATH . 'MyTestFile.php', 7 => TEST_FILES_PATH . 'MyRelativePath', ], @@ -314,7 +328,7 @@ public function testExtensionConfigurationIsReadCorrectly(): void $this->configuration->getExtensionConfiguration() ); - \ini_set('include_path', $includePath); + ini_set('include_path', $includePath); } public function testLoggingConfigurationIsReadCorrectly(): void @@ -374,20 +388,20 @@ public function testPHPConfigurationIsReadCorrectly(): void */ public function testPHPConfigurationIsHandledCorrectly(): void { - $savedIniHighlightKeyword = \ini_get('highlight.keyword'); - $savedIniHighlightString = \ini_get('highlight.string'); + $savedIniHighlightKeyword = ini_get('highlight.keyword'); + $savedIniHighlightString = ini_get('highlight.string'); $this->configuration->handlePHPConfiguration(); - $path = TEST_FILES_PATH . '.' . \PATH_SEPARATOR . '/path/to/lib'; - $this->assertStringStartsWith($path, \ini_get('include_path')); - $this->assertEquals('#123456', \ini_get('highlight.keyword')); - $this->assertEquals(TEST_FILES_PATH, \ini_get('highlight.string')); - $this->assertFalse(\FOO); - $this->assertTrue(\BAR); + $path = TEST_FILES_PATH . '.' . PATH_SEPARATOR . '/path/to/lib'; + $this->assertStringStartsWith($path, ini_get('include_path')); + $this->assertEquals('#123456', ini_get('highlight.keyword')); + $this->assertEquals(TEST_FILES_PATH, ini_get('highlight.string')); + $this->assertFalse(FOO); + $this->assertTrue(BAR); $this->assertFalse($GLOBALS['foo']); $this->assertTrue((bool) $_ENV['foo']); - $this->assertEquals(1, \getenv('foo')); + $this->assertEquals(1, getenv('foo')); $this->assertEquals('bar', $_POST['foo']); $this->assertEquals('bar', $_GET['foo']); $this->assertEquals('bar', $_COOKIE['foo']); @@ -395,8 +409,8 @@ public function testPHPConfigurationIsHandledCorrectly(): void $this->assertEquals('bar', $_FILES['foo']); $this->assertEquals('bar', $_REQUEST['foo']); - \ini_set('highlight.keyword', $savedIniHighlightKeyword); - \ini_set('highlight.string', $savedIniHighlightString); + ini_set('highlight.keyword', $savedIniHighlightKeyword); + ini_set('highlight.string', $savedIniHighlightString); } /** @@ -411,7 +425,7 @@ public function testHandlePHPConfigurationDoesNotOverwriteExistingEnvArrayVariab $this->configuration->handlePHPConfiguration(); $this->assertFalse($_ENV['foo']); - $this->assertEquals('forced', \getenv('foo_force')); + $this->assertEquals('forced', getenv('foo_force')); } /** @@ -426,7 +440,7 @@ public function testHandlePHPConfigurationDoesForceOverwrittenExistingEnvArrayVa $this->configuration->handlePHPConfiguration(); $this->assertEquals('forced', $_ENV['foo_force']); - $this->assertEquals('forced', \getenv('foo_force')); + $this->assertEquals('forced', getenv('foo_force')); } /** @@ -437,18 +451,18 @@ public function testHandlePHPConfigurationDoesForceOverwrittenExistingEnvArrayVa */ public function testHandlePHPConfigurationDoesNotOverwriteVariablesFromPutEnv(): void { - $backupFoo = \getenv('foo'); + $backupFoo = getenv('foo'); - \putenv('foo=putenv'); + putenv('foo=putenv'); $this->configuration->handlePHPConfiguration(); $this->assertEquals('putenv', $_ENV['foo']); - $this->assertEquals('putenv', \getenv('foo')); + $this->assertEquals('putenv', getenv('foo')); if ($backupFoo === false) { - \putenv('foo'); // delete variable from environment + putenv('foo'); // delete variable from environment } else { - \putenv("foo={$backupFoo}"); + putenv("foo={$backupFoo}"); } } @@ -460,11 +474,11 @@ public function testHandlePHPConfigurationDoesNotOverwriteVariablesFromPutEnv(): */ public function testHandlePHPConfigurationDoesOverwriteVariablesFromPutEnvWhenForced(): void { - \putenv('foo_force=putenv'); + putenv('foo_force=putenv'); $this->configuration->handlePHPConfiguration(); $this->assertEquals('forced', $_ENV['foo_force']); - $this->assertEquals('forced', \getenv('foo_force')); + $this->assertEquals('forced', getenv('foo_force')); } /** @@ -607,9 +621,9 @@ public function test_Conflict_between_testdox_and_printerClass_is_detected(): vo /** * Asserts that the values in $actualConfiguration equal $expectedConfiguration. * - * @throws Exception * @throws \PHPUnit\Framework\ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws Exception */ protected function assertConfigurationEquals(Configuration $expectedConfiguration, Configuration $actualConfiguration): void { diff --git a/tests/unit/Util/GetoptTest.php b/tests/unit/Util/GetoptTest.php index 079571a1cdb..4a9e13e2b4b 100644 --- a/tests/unit/Util/GetoptTest.php +++ b/tests/unit/Util/GetoptTest.php @@ -9,6 +9,7 @@ */ namespace PHPUnit\Util; +use function explode; use PHPUnit\Framework\Exception; use PHPUnit\Framework\TestCase; @@ -172,7 +173,7 @@ public function testLongOptionDoesNotAllowAnArgumentException(): void public function testItHandlesLongParametesWithValues(): void { $command = 'command parameter-0 --exec parameter-1 --conf config.xml --optn parameter-2 --optn=content-of-o parameter-n'; - $args = \explode(' ', $command); + $args = explode(' ', $command); unset($args[0]); $expected = [ [ @@ -195,7 +196,7 @@ public function testItHandlesLongParametesWithValues(): void public function testItHandlesShortParametesWithValues(): void { $command = 'command parameter-0 -x parameter-1 -c config.xml -o parameter-2 -ocontent-of-o parameter-n'; - $args = \explode(' ', $command); + $args = explode(' ', $command); unset($args[0]); $expected = [ [ diff --git a/tests/unit/Util/RegularExpressionTest.php b/tests/unit/Util/RegularExpressionTest.php index 02a22081101..2b0121645c7 100644 --- a/tests/unit/Util/RegularExpressionTest.php +++ b/tests/unit/Util/RegularExpressionTest.php @@ -9,6 +9,7 @@ */ namespace PHPUnit\Util; +use Exception; use PHPUnit\Framework\TestCase; /** @@ -39,8 +40,8 @@ public function invalidRegexpProvider(): array * @testdox Valid regex $pattern on $subject returns $return * @dataProvider validRegexpProvider * - * @throws \Exception * @throws \PHPUnit\Framework\ExpectationFailedException + * @throws Exception */ public function testValidRegex($pattern, $subject, $return): void { @@ -51,8 +52,8 @@ public function testValidRegex($pattern, $subject, $return): void * @testdox Invalid regex $pattern on $subject * @dataProvider invalidRegexpProvider * - * @throws \Exception * @throws \PHPUnit\Framework\ExpectationFailedException + * @throws Exception */ public function testInvalidRegex($pattern, $subject): void { diff --git a/tests/unit/Util/TestClassTest.php b/tests/unit/Util/TestClassTest.php index 7220480888f..622d56c47b0 100644 --- a/tests/unit/Util/TestClassTest.php +++ b/tests/unit/Util/TestClassTest.php @@ -9,12 +9,27 @@ */ namespace PHPUnit\Util; +use function array_merge; +use function preg_match; +use function range; +use function realpath; +use function strpos; +use CoverageNamespacedFunctionTest; +use DuplicateKeyDataProviderTest; +use MultipleDataProviderTest; +use ParseTestMethodAnnotationsMock; use PharIo\Version\VersionConstraint; use PHPUnit\Framework\CodeCoverageException; use PHPUnit\Framework\InvalidDataProviderException; use PHPUnit\Framework\TestCase; use PHPUnit\Framework\Warning; use PHPUnit\Util\Annotation\DocBlock; +use ReflectionClass; +use ReflectionMethod; +use RequirementsClassDocBlockTest; +use RequirementsTest; +use Test3194; +use VariousIterableDataProviderTest; /** * @small @@ -30,15 +45,15 @@ final class TestClassTest extends TestCase * @testdox Test::getRequirements() for $test * @dataProvider requirementsProvider * - * @throws Warning * @throws \PHPUnit\Framework\ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws Warning */ public function testGetRequirements($test, $result): void { $this->assertEquals( $result, - Test::getRequirements(\RequirementsTest::class, $test) + Test::getRequirements(RequirementsTest::class, $test) ); } @@ -474,14 +489,14 @@ public function requirementsProvider(): array * @testdox Test::getRequirements() with constraints for $test * @dataProvider requirementsWithVersionConstraintsProvider * - * @throws Exception - * @throws Warning * @throws \PHPUnit\Framework\ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws Exception + * @throws Warning */ public function testGetRequirementsWithVersionConstraints($test, array $result): void { - $requirements = Test::getRequirements(\RequirementsTest::class, $test); + $requirements = Test::getRequirements(RequirementsTest::class, $test); foreach ($result as $type => $expected_requirement) { $this->assertArrayHasKey( @@ -616,7 +631,7 @@ public function requirementsWithVersionConstraintsProvider(): array public function testGetRequirementsWithInvalidVersionConstraintsThrowsException($test): void { $this->expectException(Warning::class); - Test::getRequirements(\RequirementsTest::class, $test); + Test::getRequirements(RequirementsTest::class, $test); } public function requirementsWithInvalidVersionConstraintsThrowsExceptionProvider(): array @@ -629,7 +644,7 @@ public function requirementsWithInvalidVersionConstraintsThrowsExceptionProvider public function testGetRequirementsMergesClassAndMethodDocBlocks(): void { - $reflector = new \ReflectionClass(\RequirementsClassDocBlockTest::class); + $reflector = new ReflectionClass(RequirementsClassDocBlockTest::class); $file = $reflector->getFileName(); $expectedAnnotations = [ @@ -658,7 +673,7 @@ public function testGetRequirementsMergesClassAndMethodDocBlocks(): void $this->assertEquals( $expectedAnnotations, - Test::getRequirements(\RequirementsClassDocBlockTest::class, 'testMethod') + Test::getRequirements(RequirementsClassDocBlockTest::class, 'testMethod') ); } @@ -666,15 +681,15 @@ public function testGetRequirementsMergesClassAndMethodDocBlocks(): void * @testdox Test::getMissingRequirements() for $test * @dataProvider missingRequirementsProvider * - * @throws Warning * @throws \PHPUnit\Framework\ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws Warning */ public function testGetMissingRequirements($test, $result): void { $this->assertEquals( $result, - Test::getMissingRequirements(\RequirementsTest::class, $test) + Test::getMissingRequirements(RequirementsTest::class, $test) ); } @@ -845,23 +860,23 @@ public function missingRequirementsProvider(): array */ public function testGetProvidedDataRegEx(): void { - $result = \preg_match(DocBlock::REGEX_DATA_PROVIDER, '@dataProvider method', $matches); + $result = preg_match(DocBlock::REGEX_DATA_PROVIDER, '@dataProvider method', $matches); $this->assertEquals(1, $result); $this->assertEquals('method', $matches[1]); - $result = \preg_match(DocBlock::REGEX_DATA_PROVIDER, '@dataProvider class::method', $matches); + $result = preg_match(DocBlock::REGEX_DATA_PROVIDER, '@dataProvider class::method', $matches); $this->assertEquals(1, $result); $this->assertEquals('class::method', $matches[1]); - $result = \preg_match(DocBlock::REGEX_DATA_PROVIDER, '@dataProvider namespace\class::method', $matches); + $result = preg_match(DocBlock::REGEX_DATA_PROVIDER, '@dataProvider namespace\class::method', $matches); $this->assertEquals(1, $result); $this->assertEquals('namespace\class::method', $matches[1]); - $result = \preg_match(DocBlock::REGEX_DATA_PROVIDER, '@dataProvider namespace\namespace\class::method', $matches); + $result = preg_match(DocBlock::REGEX_DATA_PROVIDER, '@dataProvider namespace\namespace\class::method', $matches); $this->assertEquals(1, $result); $this->assertEquals('namespace\namespace\class::method', $matches[1]); - $result = \preg_match(DocBlock::REGEX_DATA_PROVIDER, '@dataProvider メソッド', $matches); + $result = preg_match(DocBlock::REGEX_DATA_PROVIDER, '@dataProvider メソッド', $matches); $this->assertEquals(1, $result); $this->assertEquals('メソッド', $matches[1]); } @@ -871,7 +886,7 @@ public function testGetProvidedDataRegEx(): void */ public function testMultipleDataProviders(): void { - $dataSets = Test::getProvidedData(\MultipleDataProviderTest::class, 'testOne'); + $dataSets = Test::getProvidedData(MultipleDataProviderTest::class, 'testOne'); $this->assertCount(9, $dataSets); @@ -892,7 +907,7 @@ public function testMultipleDataProviders(): void public function testMultipleYieldIteratorDataProviders(): void { - $dataSets = Test::getProvidedData(\MultipleDataProviderTest::class, 'testTwo'); + $dataSets = Test::getProvidedData(MultipleDataProviderTest::class, 'testTwo'); $this->assertCount(9, $dataSets); @@ -913,7 +928,7 @@ public function testMultipleYieldIteratorDataProviders(): void public function testWithVariousIterableDataProvidersFromParent(): void { - $dataSets = Test::getProvidedData(\VariousIterableDataProviderTest::class, 'testFromParent'); + $dataSets = Test::getProvidedData(VariousIterableDataProviderTest::class, 'testFromParent'); $this->assertEquals([ ['J'], @@ -931,7 +946,7 @@ public function testWithVariousIterableDataProvidersFromParent(): void public function testWithVariousIterableDataProvidersInParent(): void { - $dataSets = Test::getProvidedData(\VariousIterableDataProviderTest::class, 'testInParent'); + $dataSets = Test::getProvidedData(VariousIterableDataProviderTest::class, 'testInParent'); $this->assertEquals([ ['J'], @@ -949,7 +964,7 @@ public function testWithVariousIterableDataProvidersInParent(): void public function testWithVariousIterableAbstractDataProviders(): void { - $dataSets = Test::getProvidedData(\VariousIterableDataProviderTest::class, 'testAbstract'); + $dataSets = Test::getProvidedData(VariousIterableDataProviderTest::class, 'testAbstract'); $this->assertEquals([ ['S'], @@ -967,7 +982,7 @@ public function testWithVariousIterableAbstractDataProviders(): void public function testWithVariousIterableStaticDataProviders(): void { - $dataSets = Test::getProvidedData(\VariousIterableDataProviderTest::class, 'testStatic'); + $dataSets = Test::getProvidedData(VariousIterableDataProviderTest::class, 'testStatic'); $this->assertEquals([ ['A'], @@ -984,7 +999,7 @@ public function testWithVariousIterableStaticDataProviders(): void public function testWithVariousIterableNonStaticDataProviders(): void { - $dataSets = Test::getProvidedData(\VariousIterableDataProviderTest::class, 'testNonStatic'); + $dataSets = Test::getProvidedData(VariousIterableDataProviderTest::class, 'testNonStatic'); $this->assertEquals([ ['S'], @@ -1004,12 +1019,12 @@ public function testWithDuplicateKeyDataProviders(): void $this->expectException(InvalidDataProviderException::class); $this->expectExceptionMessage('The key "foo" has already been defined in the data provider "dataProvider".'); - Test::getProvidedData(\DuplicateKeyDataProviderTest::class, 'test'); + Test::getProvidedData(DuplicateKeyDataProviderTest::class, 'test'); } public function testTestWithEmptyAnnotation(): void { - $result = DocBlock::ofMethod(new \ReflectionMethod( + $result = DocBlock::ofMethod(new ReflectionMethod( \VariousDocblockDefinedDataProvider::class, 'anotherAnnotation' ), VariousDocblockDefinedDataProvider::class)->getProvidedData(); @@ -1019,7 +1034,7 @@ public function testTestWithEmptyAnnotation(): void public function testTestWithSimpleCase(): void { - $result = DocBlock::ofMethod(new \ReflectionMethod( + $result = DocBlock::ofMethod(new ReflectionMethod( \VariousDocblockDefinedDataProvider::class, 'testWith1' ), VariousDocblockDefinedDataProvider::class)->getProvidedData(); @@ -1029,7 +1044,7 @@ public function testTestWithSimpleCase(): void public function testTestWithMultiLineMultiParameterCase(): void { - $result = DocBlock::ofMethod(new \ReflectionMethod( + $result = DocBlock::ofMethod(new ReflectionMethod( \VariousDocblockDefinedDataProvider::class, 'testWith1234' ), VariousDocblockDefinedDataProvider::class)->getProvidedData(); @@ -1039,7 +1054,7 @@ public function testTestWithMultiLineMultiParameterCase(): void public function testTestWithVariousTypes(): void { - $result = DocBlock::ofMethod(new \ReflectionMethod( + $result = DocBlock::ofMethod(new ReflectionMethod( \VariousDocblockDefinedDataProvider::class, 'testWithABTrueNull' ), VariousDocblockDefinedDataProvider::class)->getProvidedData(); @@ -1049,7 +1064,7 @@ public function testTestWithVariousTypes(): void public function testTestWithAnnotationAfter(): void { - $result = DocBlock::ofMethod(new \ReflectionMethod( + $result = DocBlock::ofMethod(new ReflectionMethod( \VariousDocblockDefinedDataProvider::class, 'testWith12AndAnotherAnnotation' ), VariousDocblockDefinedDataProvider::class)->getProvidedData(); @@ -1059,7 +1074,7 @@ public function testTestWithAnnotationAfter(): void public function testTestWithSimpleTextAfter(): void { - $result = DocBlock::ofMethod(new \ReflectionMethod( + $result = DocBlock::ofMethod(new ReflectionMethod( \VariousDocblockDefinedDataProvider::class, 'testWith12AndBlahBlah' ), VariousDocblockDefinedDataProvider::class)->getProvidedData(); @@ -1069,7 +1084,7 @@ public function testTestWithSimpleTextAfter(): void public function testTestWithCharacterEscape(): void { - $result = DocBlock::ofMethod(new \ReflectionMethod( + $result = DocBlock::ofMethod(new ReflectionMethod( \VariousDocblockDefinedDataProvider::class, 'testWithEscapedString' ), VariousDocblockDefinedDataProvider::class)->getProvidedData(); @@ -1079,7 +1094,7 @@ public function testTestWithCharacterEscape(): void public function testTestWithThrowsProperExceptionIfDatasetCannotBeParsed(): void { - $docBlock = DocBlock::ofMethod(new \ReflectionMethod( + $docBlock = DocBlock::ofMethod(new ReflectionMethod( \VariousDocblockDefinedDataProvider::class, 'testWithMalformedValue' ), VariousDocblockDefinedDataProvider::class); @@ -1092,7 +1107,7 @@ public function testTestWithThrowsProperExceptionIfDatasetCannotBeParsed(): void public function testTestWithThrowsProperExceptionIfMultiLineDatasetCannotBeParsed(): void { - $docBlock = DocBlock::ofMethod(new \ReflectionMethod( + $docBlock = DocBlock::ofMethod(new ReflectionMethod( \VariousDocblockDefinedDataProvider::class, 'testWithWellFormedAndMalformedValue' ), VariousDocblockDefinedDataProvider::class); @@ -1110,7 +1125,7 @@ public function testParseAnnotation(): void { $this->assertEquals( ['Foo', 'ほげ'], - Test::getDependencies(\get_class($this), 'methodForTestParseAnnotation') + Test::getDependencies(self::class, 'methodForTestParseAnnotation') ); } @@ -1128,7 +1143,7 @@ public function testParseAnnotationThatIsOnlyOneLine(): void { $this->assertEquals( ['Bar'], - Test::getDependencies(\get_class($this), 'methodForTestParseAnnotationThatIsOnlyOneLine') + Test::getDependencies(self::class, 'methodForTestParseAnnotationThatIsOnlyOneLine') ); } @@ -1141,13 +1156,13 @@ public function methodForTestParseAnnotationThatIsOnlyOneLine(): void /** * @dataProvider getLinesToBeCoveredProvider * - * @throws CodeCoverageException * @throws \PHPUnit\Framework\ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws CodeCoverageException */ public function testGetLinesToBeCovered($test, $lines): void { - if (\strpos($test, 'Namespace') === 0) { + if (strpos($test, 'Namespace') === 0) { $expected = [ TEST_FILES_PATH . 'NamespaceCoveredClass.php' => $lines, ]; @@ -1232,7 +1247,7 @@ public function testTwoCoversDefaultClassAnnotationsAreNotAllowed(): void public function testFunctionParenthesesAreAllowed(): void { $this->assertSame( - [TEST_FILES_PATH . 'CoveredFunction.php' => \range(10, 12)], + [TEST_FILES_PATH . 'CoveredFunction.php' => range(10, 12)], Test::getLinesToBeCovered( 'CoverageFunctionParenthesesTest', 'testSomething' @@ -1243,7 +1258,7 @@ public function testFunctionParenthesesAreAllowed(): void public function testFunctionParenthesesAreAllowedWithWhitespace(): void { $this->assertSame( - [TEST_FILES_PATH . 'CoveredFunction.php' => \range(10, 12)], + [TEST_FILES_PATH . 'CoveredFunction.php' => range(10, 12)], Test::getLinesToBeCovered( 'CoverageFunctionParenthesesWhitespaceTest', 'testSomething' @@ -1254,7 +1269,7 @@ public function testFunctionParenthesesAreAllowedWithWhitespace(): void public function testMethodParenthesesAreAllowed(): void { $this->assertSame( - [TEST_FILES_PATH . 'CoveredClass.php' => \range(29, 33)], + [TEST_FILES_PATH . 'CoveredClass.php' => range(29, 33)], Test::getLinesToBeCovered( 'CoverageMethodParenthesesTest', 'testSomething' @@ -1265,7 +1280,7 @@ public function testMethodParenthesesAreAllowed(): void public function testMethodParenthesesAreAllowedWithWhitespace(): void { $this->assertSame( - [TEST_FILES_PATH . 'CoveredClass.php' => \range(29, 33)], + [TEST_FILES_PATH . 'CoveredClass.php' => range(29, 33)], Test::getLinesToBeCovered( 'CoverageMethodParenthesesWhitespaceTest', 'testSomething' @@ -1277,10 +1292,10 @@ public function testNamespacedFunctionCanBeCoveredOrUsed(): void { $this->assertEquals( [ - TEST_FILES_PATH . 'NamespaceCoveredFunction.php' => \range(12, 15), + TEST_FILES_PATH . 'NamespaceCoveredFunction.php' => range(12, 15), ], Test::getLinesToBeCovered( - \CoverageNamespacedFunctionTest::class, + CoverageNamespacedFunctionTest::class, 'testFunc' ) ); @@ -1295,91 +1310,91 @@ public function getLinesToBeCoveredProvider(): array ], [ 'CoverageClassExtendedTest', - \array_merge(\range(27, 44), \range(10, 25)), + array_merge(range(27, 44), range(10, 25)), ], [ 'CoverageClassTest', - \range(27, 44), + range(27, 44), ], [ 'CoverageMethodTest', - \range(29, 33), + range(29, 33), ], [ 'CoverageMethodOneLineAnnotationTest', - \range(29, 33), + range(29, 33), ], [ 'CoverageNotPrivateTest', - \array_merge(\range(29, 33), \range(35, 39)), + array_merge(range(29, 33), range(35, 39)), ], [ 'CoverageNotProtectedTest', - \array_merge(\range(29, 33), \range(41, 43)), + array_merge(range(29, 33), range(41, 43)), ], [ 'CoverageNotPublicTest', - \array_merge(\range(35, 39), \range(41, 43)), + array_merge(range(35, 39), range(41, 43)), ], [ 'CoveragePrivateTest', - \range(41, 43), + range(41, 43), ], [ 'CoverageProtectedTest', - \range(35, 39), + range(35, 39), ], [ 'CoveragePublicTest', - \range(29, 33), + range(29, 33), ], [ 'CoverageFunctionTest', - \range(10, 12), + range(10, 12), ], [ 'NamespaceCoverageClassExtendedTest', - \array_merge(\range(29, 46), \range(12, 27)), + array_merge(range(29, 46), range(12, 27)), ], [ 'NamespaceCoverageClassTest', - \range(29, 46), + range(29, 46), ], [ 'NamespaceCoverageMethodTest', - \range(31, 35), + range(31, 35), ], [ 'NamespaceCoverageNotPrivateTest', - \array_merge(\range(31, 35), \range(37, 41)), + array_merge(range(31, 35), range(37, 41)), ], [ 'NamespaceCoverageNotProtectedTest', - \array_merge(\range(31, 35), \range(43, 45)), + array_merge(range(31, 35), range(43, 45)), ], [ 'NamespaceCoverageNotPublicTest', - \array_merge(\range(37, 41), \range(43, 45)), + array_merge(range(37, 41), range(43, 45)), ], [ 'NamespaceCoveragePrivateTest', - \range(43, 45), + range(43, 45), ], [ 'NamespaceCoverageProtectedTest', - \range(37, 41), + range(37, 41), ], [ 'NamespaceCoveragePublicTest', - \range(31, 35), + range(31, 35), ], [ 'NamespaceCoverageCoversClassTest', - \array_merge(\range(43, 45), \range(37, 41), \range(31, 35), \range(24, 26), \range(19, 22), \range(14, 17)), + array_merge(range(43, 45), range(37, 41), range(31, 35), range(24, 26), range(19, 22), range(14, 17)), ], [ 'NamespaceCoverageCoversClassPublicTest', - \range(31, 35), + range(31, 35), ], [ 'CoverageClassNothingTest', @@ -1391,7 +1406,7 @@ public function getLinesToBeCoveredProvider(): array ], [ 'CoverageCoversOverridesCoversNothingTest', - \range(29, 33), + range(29, 33), ], [ 'CoverageMethodNothingCoversMethod', @@ -1402,7 +1417,7 @@ public function getLinesToBeCoveredProvider(): array public function testParseTestMethodAnnotationsIncorporatesTraits(): void { - $result = Test::parseTestMethodAnnotations(\ParseTestMethodAnnotationsMock::class); + $result = Test::parseTestMethodAnnotations(ParseTestMethodAnnotationsMock::class); $this->assertArrayHasKey('class', $result); $this->assertArrayHasKey('method', $result); @@ -1414,10 +1429,10 @@ public function testCoversAnnotationIncludesTraitsUsedByClass(): void { $this->assertSame( [ - TEST_FILES_PATH . '3194.php' => \array_merge(\range(20, 28), \range(12, 18)), + TEST_FILES_PATH . '3194.php' => array_merge(range(20, 28), range(12, 18)), ], Test::getLinesToBeCovered( - \Test3194::class, + Test3194::class, 'testOne' ) ); @@ -1451,8 +1466,8 @@ public function canSkipCoverageProvider(): array private function getRequirementsTestClassFile(): string { if (!$this->fileRequirementsTest) { - $reflector = new \ReflectionClass(\RequirementsTest::class); - $this->fileRequirementsTest = \realpath($reflector->getFileName()); + $reflector = new ReflectionClass(RequirementsTest::class); + $this->fileRequirementsTest = realpath($reflector->getFileName()); } return $this->fileRequirementsTest; diff --git a/tests/unit/Util/TestDox/CliTestDoxPrinterColorTest.php b/tests/unit/Util/TestDox/CliTestDoxPrinterColorTest.php index 6a4581f4012..8468742cd91 100644 --- a/tests/unit/Util/TestDox/CliTestDoxPrinterColorTest.php +++ b/tests/unit/Util/TestDox/CliTestDoxPrinterColorTest.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Util\TestDox; +use const PHP_EOL; +use function implode; use PHPUnit\Framework\AssertionFailedError; use PHPUnit\Framework\TestCase; use PHPUnit\Util\Color; @@ -36,7 +38,7 @@ protected function tearDown(): void public function testColorizesDiffInFailureMessage(): void { - $raw = \implode(\PHP_EOL, ['some message', '--- Expected', '+++ Actual', '@@ @@']); + $raw = implode(PHP_EOL, ['some message', '--- Expected', '+++ Actual', '@@ @@']); $failure = new AssertionFailedError($raw); $this->printer->startTest($this); diff --git a/tests/unit/Util/XDebugFilterScriptGeneratorTest.php b/tests/unit/Util/XDebugFilterScriptGeneratorTest.php index 42b30568a47..95f58a7b70d 100644 --- a/tests/unit/Util/XDebugFilterScriptGeneratorTest.php +++ b/tests/unit/Util/XDebugFilterScriptGeneratorTest.php @@ -9,6 +9,11 @@ */ namespace PHPUnit\Util; +use const DIRECTORY_SEPARATOR; +use function addslashes; +use function basename; +use function dirname; +use function sprintf; use PHPUnit\Framework\TestCase; /** @@ -19,7 +24,7 @@ final class XDebugFilterScriptGeneratorTest extends TestCase { public function testReturnsExpectedScript(): void { - $expectedDirectory = \sprintf(\addslashes('%s' . \DIRECTORY_SEPARATOR), __DIR__); + $expectedDirectory = sprintf(addslashes('%s' . DIRECTORY_SEPARATOR), __DIR__); $expected = <<assertDirectoryNotExists($directoryPathThatDoesNotExist); $filterConfiguration = [ @@ -52,12 +57,12 @@ public function testReturnsExpectedScript(): void 'prefix' => '', ], [ - 'path' => \sprintf('%s/', __DIR__), + 'path' => sprintf('%s/', __DIR__), 'suffix' => '.php', 'prefix' => '', ], [ - 'path' => \sprintf('%s/./%s', \dirname(__DIR__), \basename(__DIR__)), + 'path' => sprintf('%s/./%s', dirname(__DIR__), basename(__DIR__)), 'suffix' => '.php', 'prefix' => '', ], diff --git a/tests/unit/Util/XmlTest.php b/tests/unit/Util/XmlTest.php index 79a5290b97c..e63752452db 100644 --- a/tests/unit/Util/XmlTest.php +++ b/tests/unit/Util/XmlTest.php @@ -9,6 +9,10 @@ */ namespace PHPUnit\Util; +use function chr; +use function ord; +use function sprintf; +use DOMDocument; use PHPUnit\Framework\Exception; use PHPUnit\Framework\TestCase; @@ -26,7 +30,7 @@ public function testPrepareString(string $char): void $escapedString = Xml::prepareString($char); $xml = "{$escapedString}"; - $dom = new \DOMDocument('1.0', 'UTF-8'); + $dom = new DOMDocument('1.0', 'UTF-8'); try { $dom->loadXML($xml); @@ -35,9 +39,9 @@ public function testPrepareString(string $char): void $this->assertNull( $e, - \sprintf( + sprintf( '\PHPUnit\Util\Xml::prepareString("\x%02x") should not crash DomDocument', - \ord($char) + ord($char) ) ); } @@ -47,7 +51,7 @@ public function charProvider(): array $data = []; for ($i = 0; $i < 256; $i++) { - $data[] = [\chr($i)]; + $data[] = [chr($i)]; } return $data; @@ -83,7 +87,7 @@ public function testLoadBoolean(): void public function testNestedXmlToVariable(): void { $xml = 'foobar'; - $dom = new \DOMDocument; + $dom = new DOMDocument; $dom->loadXML($xml); $expected = [ @@ -104,7 +108,7 @@ public function testNestedXmlToVariable(): void public function testXmlToVariableCanHandleMultipleOfTheSameArgumentType(): void { $xml = 'abc'; - $dom = new \DOMDocument; + $dom = new DOMDocument; $dom->loadXML($xml); $expected = ['a' => 'a', 'b' => 'b', 'c' => 'c']; @@ -120,7 +124,7 @@ public function testXmlToVariableCanHandleMultipleOfTheSameArgumentType(): void public function testXmlToVariableCanConstructObjectsWithConstructorArgumentsRecursively(): void { $xml = 'one0two'; - $dom = new \DOMDocument; + $dom = new DOMDocument; $dom->loadXML($xml); $actual = Xml::xmlToVariable($dom->documentElement); diff --git a/tools/composer b/tools/composer index f6df0ce3970..76d6ceb2772 100755 Binary files a/tools/composer and b/tools/composer differ diff --git a/tools/php-cs-fixer b/tools/php-cs-fixer index 859a4c38b0f..f490357f43e 100755 Binary files a/tools/php-cs-fixer and b/tools/php-cs-fixer differ diff --git a/tools/php-scoper b/tools/php-scoper index bc24de944d6..53f309491d0 100755 Binary files a/tools/php-scoper and b/tools/php-scoper differ diff --git a/tools/phpab b/tools/phpab index f8e426260ef..cbeba79f790 100755 --- a/tools/phpab +++ b/tools/phpab @@ -150,21 +150,21 @@ spl_autoload_register( ); Phar::mapPhar('phpab.phar'); -define('PHPAB_VERSION', '1.25.9'); +define('PHPAB_VERSION', '1.26.0'); $factory = new \TheSeer\Autoload\Factory(); $factory->getCLI()->run(); exit(0); __HALT_COMPILER(); ?> * -phpab.phar8vendor/theseer/directoryscanner/src/directoryscanner.php"yt^A P7vendor/theseer/directoryscanner/src/filesonlyfilter.php -yt^Af<vendor/theseer/directoryscanner/src/includeexcludefilter.php^yt^TBl1vendor/theseer/directoryscanner/src/phpfilter.php yt^FA'vendor/zetacomponents/base/src/base.phpYyt^\0vendor/zetacomponents/base/src/base_autoload.phpNyt^H¬Lvendor/zetacomponents/base/src/exceptions/double_class_repository_prefix.phpVyt^6w7vendor/zetacomponents/base/src/exceptions/exception.phpyt^ CTsAvendor/zetacomponents/base/src/exceptions/extension_not_found.php6yt^~9 <vendor/zetacomponents/base/src/exceptions/file_exception.php-yt^5vendor/zetacomponents/base/src/exceptions/file_io.phpyt^O;<vendor/zetacomponents/base/src/exceptions/file_not_found.phpJyt^,T]DX=vendor/zetacomponents/base/src/exceptions/file_permission.php yt^Dg7Ivendor/zetacomponents/base/src/exceptions/functionality_not_supported.php>yt^ V&JFvendor/zetacomponents/base/src/exceptions/init_callback_configured.phpyt^: Dvendor/zetacomponents/base/src/exceptions/invalid_callback_class.php_yt^ -Z»Bvendor/zetacomponents/base/src/exceptions/invalid_parent_class.phpEyt^@vendor/zetacomponents/base/src/exceptions/property_not_found.phpyt^"yAAvendor/zetacomponents/base/src/exceptions/property_permission.phpfyt^W>D?vendor/zetacomponents/base/src/exceptions/setting_not_found.phpTyt^H[Y;vendor/zetacomponents/base/src/exceptions/setting_value.php[yt^3vendor/zetacomponents/base/src/exceptions/value.phpyt^.Ѵ6vendor/zetacomponents/base/src/exceptions/whatever.php yt^8K0vendor/zetacomponents/base/src/ezc_bootstrap.phpyt^U–~P+vendor/zetacomponents/base/src/features.php.yt^ -''vendor/zetacomponents/base/src/file.php_Hyt^ ^'vendor/zetacomponents/base/src/init.phpVyt^ukoGvendor/zetacomponents/base/src/interfaces/configuration_initializer.phpyt^E8vendor/zetacomponents/base/src/interfaces/exportable.phpyt^B59vendor/zetacomponents/base/src/interfaces/persistable.phpyt^9J +vendor/zetacomponents/base/src/metadata.phpyt^b0vendor/zetacomponents/base/src/metadata/pear.phpyt^<3vendor/zetacomponents/base/src/metadata/tarball.phpyt^ g^*vendor/zetacomponents/base/src/options.phpyt^y*Ll)vendor/zetacomponents/base/src/struct.php?yt^t<vendor/zetacomponents/base/src/structs/file_find_context.php yt^-њ?vendor/zetacomponents/base/src/structs/repository_directory.php yt^L8'U<vendor/zetacomponents/console-tools/src/console_autoload.phpryt^i>vendor/zetacomponents/console-tools/src/dialog/menu_dialog.phpyt^1wԴBvendor/zetacomponents/console-tools/src/dialog/question_dialog.php"yt^ tQvendor/zetacomponents/console-tools/src/dialog/validators/menu_dialog_default.phpyt^+Xvendor/zetacomponents/console-tools/src/dialog/validators/question_dialog_collection.phpyt^ONUvendor/zetacomponents/console-tools/src/dialog/validators/question_dialog_mapping.phpyt^FSvendor/zetacomponents/console-tools/src/dialog/validators/question_dialog_regex.phpyt^{Rvendor/zetacomponents/console-tools/src/dialog/validators/question_dialog_type.phpCyt^(9vendor/zetacomponents/console-tools/src/dialog_viewer.php" -yt^?R28?vendor/zetacomponents/console-tools/src/exceptions/argument.phpyt^X δRvendor/zetacomponents/console-tools/src/exceptions/argument_already_registered.phpE yt^/wm'Svendor/zetacomponents/console-tools/src/exceptions/argument_mandatory_violation.phpyt^ Hvendor/zetacomponents/console-tools/src/exceptions/argument_too_many.phpyt^*Y۴Nvendor/zetacomponents/console-tools/src/exceptions/argument_type_violation.phpsyt^u[:MCvendor/zetacomponents/console-tools/src/exceptions/dialog_abort.phpyt^"@vendor/zetacomponents/console-tools/src/exceptions/exception.phpyt^P[ Jvendor/zetacomponents/console-tools/src/exceptions/invalid_option_name.phpyt^dLvendor/zetacomponents/console-tools/src/exceptions/invalid_output_target.phpyt^]vmwIvendor/zetacomponents/console-tools/src/exceptions/no_position_stored.phpyt^RGyMvendor/zetacomponents/console-tools/src/exceptions/no_valid_dialog_result.phpyt^X=vendor/zetacomponents/console-tools/src/exceptions/option.phpyt^}YPvendor/zetacomponents/console-tools/src/exceptions/option_already_registered.phpyt^-/ߴQvendor/zetacomponents/console-tools/src/exceptions/option_arguments_violation.phpyt^~xRvendor/zetacomponents/console-tools/src/exceptions/option_dependency_violation.phpyt^rQvendor/zetacomponents/console-tools/src/exceptions/option_exclusion_violation.phpyt^hVmQvendor/zetacomponents/console-tools/src/exceptions/option_mandatory_violation.phphyt^YXpAKvendor/zetacomponents/console-tools/src/exceptions/option_missing_value.phpyt^F^Fvendor/zetacomponents/console-tools/src/exceptions/option_no_alias.php yt^Hvendor/zetacomponents/console-tools/src/exceptions/option_not_exists.php$yt^6ESvendor/zetacomponents/console-tools/src/exceptions/option_string_not_wellformed.php yt^0Mvendor/zetacomponents/console-tools/src/exceptions/option_too_many_values.phpwyt^Lvendor/zetacomponents/console-tools/src/exceptions/option_type_violation.phpyt^D/1vendor/zetacomponents/console-tools/src/input.phpyt^&8:vendor/zetacomponents/console-tools/src/input/argument.phpyt^h";vendor/zetacomponents/console-tools/src/input/arguments.phpb!yt^JESJvendor/zetacomponents/console-tools/src/input/help_generators/standard.php9yt^Bj8vendor/zetacomponents/console-tools/src/input/option.phpOyt^S~Evendor/zetacomponents/console-tools/src/input/validators/standard.phpyt^ x=vendor/zetacomponents/console-tools/src/interfaces/dialog.phpT yt^*/Z;Gvendor/zetacomponents/console-tools/src/interfaces/dialog_validator.phpyt^ 5Kvendor/zetacomponents/console-tools/src/interfaces/input_help_generator.phpyt^tӁFvendor/zetacomponents/console-tools/src/interfaces/input_validator.phpyyt^eutovLvendor/zetacomponents/console-tools/src/interfaces/menu_dialog_validator.phpyt^TPvendor/zetacomponents/console-tools/src/interfaces/question_dialog_validator.phpyt^&cִ:vendor/zetacomponents/console-tools/src/options/dialog.php2 yt^3Y?vendor/zetacomponents/console-tools/src/options/menu_dialog.phpyt^1vf:vendor/zetacomponents/console-tools/src/options/output.phpyt^0ِI?vendor/zetacomponents/console-tools/src/options/progressbar.phpyt^te%Cvendor/zetacomponents/console-tools/src/options/progressmonitor.phpF yt^ Cvendor/zetacomponents/console-tools/src/options/question_dialog.phpyt^Wia=vendor/zetacomponents/console-tools/src/options/statusbar.php yt^p~[9vendor/zetacomponents/console-tools/src/options/table.phpL"yt^seK2vendor/zetacomponents/console-tools/src/output.phpMyt^W?7vendor/zetacomponents/console-tools/src/progressbar.php:yt^dm|;vendor/zetacomponents/console-tools/src/progressmonitor.phpZyt^q5vendor/zetacomponents/console-tools/src/statusbar.php yt^j rM?vendor/zetacomponents/console-tools/src/structs/option_rule.phpyt^ Avendor/zetacomponents/console-tools/src/structs/output_format.phpkyt^h+-Bvendor/zetacomponents/console-tools/src/structs/output_formats.php+yt^D1vendor/zetacomponents/console-tools/src/table.php)syt^sB16vendor/zetacomponents/console-tools/src/table/cell.phpyt^+(Կ5vendor/zetacomponents/console-tools/src/table/row.phpw/yt^ -h%ڴ8vendor/zetacomponents/console-tools/src/tools/string.phpyt^F)phpab/Application.phpJ&yt^ phpab/AutoloadRenderer.phpc#yt^ - phpab/CLI.phpQ^yt^Nphpab/Cache.php@yt^ "9phpab/CacheEntry.phpyt^д"phpab/CacheWarmingListRenderer.phpyt^sy?phpab/CachingParser.phpyt^PI!phpab/Collector.php yt^66phpab/CollectorResult.phpT yt^-phpab/ComposerIterator.php6yt^`phpab/Config.phpC3yt^ (ܴphpab/DependencySorter.phpmyt^os:phpab/Factory.php yt^8phpab/Logger.phpyt^  Ŵphpab/ParseResult.phpgyt^Wߪphpab/Parser.phpFyt^`Ӱphpab/ParserInterface.phpyt^phpab/PathComparator.phpfyt^haphpab/PharBuilder.phpgyt^= #״phpab/SourceFile.phpyt^%phpab/StaticListRenderer.phpyt^zphpab/StaticRenderer.phpyt^$Ŵ#phpab/StaticRequireListRenderer.php"yt^LXOphpab/Version.php -yt^j&Ӵ"phpab/templates/ci/default.php.tplyt^/]iphpab/templates/ci/phar.php.tplyt^~ phpab/templates/ci/php52.php.tplyt^ ^@N"phpab/templates/cs/default.php.tplyt^Bw#phpab/templates/cs/phar.php.tplyt^2q$ phpab/templates/cs/php52.php.tplyt^&N˴phpab/templates/static.php.tplyt^p휺"phpab/templates/staticphar.php.tplWyt^T.ִYsbk CL^_j?[!QI4F6ۻ{:&)nwo{{_~[<,Nޝ;ċURhLÇ??DB/zI*?3JZp'{4 4#"CɄ7 Ld.Z'La4x$E2Â' M$~ +phpab.phar8vendor/theseer/directoryscanner/src/directoryscanner.php" _A P7vendor/theseer/directoryscanner/src/filesonlyfilter.php + _Af<vendor/theseer/directoryscanner/src/includeexcludefilter.php^ _TBl1vendor/theseer/directoryscanner/src/phpfilter.php _FA'vendor/zetacomponents/base/src/base.phpY _\0vendor/zetacomponents/base/src/base_autoload.phpN _H¬Lvendor/zetacomponents/base/src/exceptions/double_class_repository_prefix.phpV _6w7vendor/zetacomponents/base/src/exceptions/exception.php _ CTsAvendor/zetacomponents/base/src/exceptions/extension_not_found.php6 _~9 <vendor/zetacomponents/base/src/exceptions/file_exception.php- _5vendor/zetacomponents/base/src/exceptions/file_io.php _O;<vendor/zetacomponents/base/src/exceptions/file_not_found.phpJ _,T]DX=vendor/zetacomponents/base/src/exceptions/file_permission.php _Dg7Ivendor/zetacomponents/base/src/exceptions/functionality_not_supported.php> _ V&JFvendor/zetacomponents/base/src/exceptions/init_callback_configured.php _: Dvendor/zetacomponents/base/src/exceptions/invalid_callback_class.php_ _ +Z»Bvendor/zetacomponents/base/src/exceptions/invalid_parent_class.phpE _@vendor/zetacomponents/base/src/exceptions/property_not_found.php _"yAAvendor/zetacomponents/base/src/exceptions/property_permission.phpf _W>D?vendor/zetacomponents/base/src/exceptions/setting_not_found.phpT _H[Y;vendor/zetacomponents/base/src/exceptions/setting_value.php[ _3vendor/zetacomponents/base/src/exceptions/value.php _.Ѵ6vendor/zetacomponents/base/src/exceptions/whatever.php  _8K0vendor/zetacomponents/base/src/ezc_bootstrap.php _U–~P+vendor/zetacomponents/base/src/features.php. _ +''vendor/zetacomponents/base/src/file.php_H _ ^'vendor/zetacomponents/base/src/init.phpV _ukoGvendor/zetacomponents/base/src/interfaces/configuration_initializer.php _E8vendor/zetacomponents/base/src/interfaces/exportable.php _B59vendor/zetacomponents/base/src/interfaces/persistable.php _9J +vendor/zetacomponents/base/src/metadata.php _b0vendor/zetacomponents/base/src/metadata/pear.php _<3vendor/zetacomponents/base/src/metadata/tarball.php _ g^*vendor/zetacomponents/base/src/options.php _y*Ll)vendor/zetacomponents/base/src/struct.php? _t<vendor/zetacomponents/base/src/structs/file_find_context.php _-њ?vendor/zetacomponents/base/src/structs/repository_directory.php _L8'U<vendor/zetacomponents/console-tools/src/console_autoload.phpr _i>vendor/zetacomponents/console-tools/src/dialog/menu_dialog.php _1wԴBvendor/zetacomponents/console-tools/src/dialog/question_dialog.php" _ tQvendor/zetacomponents/console-tools/src/dialog/validators/menu_dialog_default.php _+Xvendor/zetacomponents/console-tools/src/dialog/validators/question_dialog_collection.php _ONUvendor/zetacomponents/console-tools/src/dialog/validators/question_dialog_mapping.php _FSvendor/zetacomponents/console-tools/src/dialog/validators/question_dialog_regex.php _{Rvendor/zetacomponents/console-tools/src/dialog/validators/question_dialog_type.phpC _(9vendor/zetacomponents/console-tools/src/dialog_viewer.php" + _?R28?vendor/zetacomponents/console-tools/src/exceptions/argument.php _X δRvendor/zetacomponents/console-tools/src/exceptions/argument_already_registered.phpE _/wm'Svendor/zetacomponents/console-tools/src/exceptions/argument_mandatory_violation.php _ Hvendor/zetacomponents/console-tools/src/exceptions/argument_too_many.php _*Y۴Nvendor/zetacomponents/console-tools/src/exceptions/argument_type_violation.phps _u[:MCvendor/zetacomponents/console-tools/src/exceptions/dialog_abort.php _"@vendor/zetacomponents/console-tools/src/exceptions/exception.php _P[ Jvendor/zetacomponents/console-tools/src/exceptions/invalid_option_name.php _dLvendor/zetacomponents/console-tools/src/exceptions/invalid_output_target.php _]vmwIvendor/zetacomponents/console-tools/src/exceptions/no_position_stored.php _RGyMvendor/zetacomponents/console-tools/src/exceptions/no_valid_dialog_result.php _X=vendor/zetacomponents/console-tools/src/exceptions/option.php _}YPvendor/zetacomponents/console-tools/src/exceptions/option_already_registered.php _-/ߴQvendor/zetacomponents/console-tools/src/exceptions/option_arguments_violation.php _~xRvendor/zetacomponents/console-tools/src/exceptions/option_dependency_violation.php _rQvendor/zetacomponents/console-tools/src/exceptions/option_exclusion_violation.php _hVmQvendor/zetacomponents/console-tools/src/exceptions/option_mandatory_violation.phph _YXpAKvendor/zetacomponents/console-tools/src/exceptions/option_missing_value.php _F^Fvendor/zetacomponents/console-tools/src/exceptions/option_no_alias.php  _Hvendor/zetacomponents/console-tools/src/exceptions/option_not_exists.php$ _6ESvendor/zetacomponents/console-tools/src/exceptions/option_string_not_wellformed.php  _0Mvendor/zetacomponents/console-tools/src/exceptions/option_too_many_values.phpw _Lvendor/zetacomponents/console-tools/src/exceptions/option_type_violation.php _D/1vendor/zetacomponents/console-tools/src/input.php _&8:vendor/zetacomponents/console-tools/src/input/argument.php _h";vendor/zetacomponents/console-tools/src/input/arguments.phpb! _JESJvendor/zetacomponents/console-tools/src/input/help_generators/standard.php9 _Bj8vendor/zetacomponents/console-tools/src/input/option.phpO _S~Evendor/zetacomponents/console-tools/src/input/validators/standard.php _ x=vendor/zetacomponents/console-tools/src/interfaces/dialog.phpT _*/Z;Gvendor/zetacomponents/console-tools/src/interfaces/dialog_validator.php _ 5Kvendor/zetacomponents/console-tools/src/interfaces/input_help_generator.php _tӁFvendor/zetacomponents/console-tools/src/interfaces/input_validator.phpy _eutovLvendor/zetacomponents/console-tools/src/interfaces/menu_dialog_validator.php _TPvendor/zetacomponents/console-tools/src/interfaces/question_dialog_validator.php _&cִ:vendor/zetacomponents/console-tools/src/options/dialog.php2 _3Y?vendor/zetacomponents/console-tools/src/options/menu_dialog.php _1vf:vendor/zetacomponents/console-tools/src/options/output.php _0ِI?vendor/zetacomponents/console-tools/src/options/progressbar.php _te%Cvendor/zetacomponents/console-tools/src/options/progressmonitor.phpF _ Cvendor/zetacomponents/console-tools/src/options/question_dialog.php _Wia=vendor/zetacomponents/console-tools/src/options/statusbar.php _p~[9vendor/zetacomponents/console-tools/src/options/table.phpL" _seK2vendor/zetacomponents/console-tools/src/output.phpM _W?7vendor/zetacomponents/console-tools/src/progressbar.php: _dm|;vendor/zetacomponents/console-tools/src/progressmonitor.phpZ _q5vendor/zetacomponents/console-tools/src/statusbar.php _j rM?vendor/zetacomponents/console-tools/src/structs/option_rule.php _ Avendor/zetacomponents/console-tools/src/structs/output_format.phpk _h+-Bvendor/zetacomponents/console-tools/src/structs/output_formats.php+ _D1vendor/zetacomponents/console-tools/src/table.php)s _sB16vendor/zetacomponents/console-tools/src/table/cell.php _+(Կ5vendor/zetacomponents/console-tools/src/table/row.phpw/ _ +h%ڴ8vendor/zetacomponents/console-tools/src/tools/string.php _F)phpab/Application.phpJ& _ phpab/AutoloadRenderer.phpc# _ + phpab/CLI.php^ _ 0phpab/Cache.php@ _ "9phpab/CacheEntry.php _д"phpab/CacheWarmingListRenderer.php _sy?phpab/CachingParser.php _PI!phpab/Collector.php _66phpab/CollectorResult.phpT _-phpab/ComposerIterator.php _%?phpab/Config.phpC3 _ (ܴphpab/DependencySorter.phpm _os:phpab/Factory.php _8phpab/Logger.php _  Ŵphpab/ParseResult.phpg _Wߪphpab/Parser.phpZH _ ')phpab/ParserInterface.php _phpab/PathComparator.phpf _haphpab/PharBuilder.phpg _= #״phpab/SourceFile.php _%phpab/StaticListRenderer.php _zphpab/StaticRenderer.php _$Ŵ#phpab/StaticRequireListRenderer.php" _LXOphpab/Version.php + _j&Ӵ"phpab/templates/ci/default.php.tpl _/]iphpab/templates/ci/phar.php.tpl _~ phpab/templates/ci/php52.php.tpl _ ^@N"phpab/templates/cs/default.php.tpl _Bw#phpab/templates/cs/phar.php.tpl _2q$ phpab/templates/cs/php52.php.tpl _&N˴phpab/templates/static.php.tpl _p휺"phpab/templates/staticphar.php.tplW _T.ִYsbk CL^_j?[!QI4F6ۻ{:&)nwo{{_~[<,Nޝ;ċURhLÇ??DB/zI*?3JZp'{4 4#"CɄ7 Ld.Z'La4x$E2Â' M$~ |^8 9f0#? >!<=Wzni$z)Rēz,M喊4V& $@S\8KZ᪓ <9; ZK (~;7]U{kҊ=\Rfzghh6I 0 ]g3TvL0*#"\xPY`r۬ͨvD%8i0D!det8]]#F@%됓:CIqGepmY]iyٷz9`X4a-\Z4Rj8㫡Hn̶W&-jݕLe$!]тLd8;nWE{`kCffѬEt5ehٺC4z+ t ܒZV'3bh]ue|g|ZxGoi[uOpӮE<Z"]ijpU"bf邑=C.lۘINDf)}}-?NNHdJ  &x!%f8e+9,bA3V8)ccf k-I[+tXl .u:%EP%%f&/iO"TLfZ+ʼ Jg4FӍwi,3cs{s[}|P*^|sE_+"\ @@oiZ16G,x1jXoz0EvNFֲ8%R)3 F4,:LN1%v`6r}ueG)PzڠM18:5 S,>tj:QU0D5L5~"8j2 5fbh=D:TȳC< WJy2mbfA\JuE}PŖ-U; vUs>ё+4ȶ4)G8!=(`a|rUAj6Xx`/A: (cԆ_(3/gg>jCq]~V-WvG`Ҿيl1BݟT,;8ϒoK:rAXz%F"'ju1gMox8y 8fÅ Ωлo =|O7W案 -V59\4m~Pd ptDt 0VOYb`IR0e ~(j x3i2:%Sm N6eсx>08]nPWR!@s*:V*Z<āт )3<9%!nĵFcc28UX>#BF4fեWgqNлBpKAdx:DڽT Fz6NQJ3m-}*Mvmŀf; %"i 8Iw\mzbeg\2O mSkYiFMWhgf"&[7ukM]]4(Y3cy pgS=*u goTF#SoV>" '+Ǎ6E݊P2m|AJ@X.,k(7BC׳[ E]^F۰,,Fil)y= ^z#lv 뛮۷]š0. hqUIekӵ8mvs C0BB iiS{TKm}Z+6fNw'ek7r5(yefjQU̘:P.[UMl?nUq욧yT݋/+  3]6qZS=+ML y @# I{!Xsv;^>"5rags:&Pd4Mp:uYrx:.eaZ eՄM%[8@"'QuW:>8,s6W4ݑQju;!M;jlFԓ(pӿ i [WS]vV!g8;e'9 |4/˙хEM{΄"W96FѴLB\M^̠]vP -g]}Y\F(ݙ;7-دVYlS9 PckpX6]zKWW,y5 - ) $?p Y̓f_Re;߱L ,j-m ԣ~j]<[}3?"3eU= -Kvtpbub_OҗI͜EVa6:sf}/-r8lyksQ~_\g57'˷>~PÇK$e/bq"&UEL @"85cbûsx8yb.Ɛ 2`UgsClp1;" A+,:qiKT5ثz-WEbG .xJ ܄ߴ)FդGE< S3#;}Xw[3XdcY) +qtm" (YUڸ,PsCY!g: &F~(>V2S~ullͧ 702xL‘,--"SaU6,3PV&Qs+"6]계Q 1ے";dy!^r[GqZ`Y"LQR-tUn(76J<~n7 K Z\' ^~iegY`E+Osv/Cg˱4ýF.Fr_h=#?g̡qxCAKosrI]<ϧ{t%2Xma^[ gde1]74-_d)" T^yOf -EsXy$UsvY<@nYf5v<9┍+#-:Z"7Efk-ixe؊pKAN05X3vʫV\Y]<5q~pĕ檪1 2ٛBlR̪?lF nTgJ$R\S;9xP#H[ ҹӵZp9Em$(kb8gIu[,Z4#bK&fv晆,FR.6Ƀ@r &S+C }{ !O9TT}ϻwl:+L3ndե?r{lbNXv`onuO);q8c~[gRwS~)/[x .gB}!J5EU~(LcT2I`qVSjONՉ _Qo4n0 |p5zxgN`!T׶L,xZ,%!CIQ]ϙe3T!΍O Lled4D?F;BM4n}FL ĄGvô`'r&f`͜;@`vY2ujTOꟼpE.gB"x /$9ψW eg78~ 㓘sL%4bF8Euom- -PC`.btRVӭvIrf7PճA$+fҳ,R`dãQS*\¹y pt,7y }TJ?er,}03uW[%V,W_бy(J)nv4]Xj!\ -7Yi(C~1vrsYUm={48BFOM2يc'T牵f$cߊ8J -zx ;'\o~"6`Kj*yeG jCF:AUÇg@h(Z$Y -N;dDIB>6YQʪxw) -Aj ȹFWTO%f`"D V5ְ{'{SVEEoOI8J r~ f|DANjc4XmK~xPZ5Pu+l"+JBdޟ@JLbG6-Mj]99:T 2\sj[4$K;fqJ/BLVyVm-^T[gȷ s -T @Y>Z&e^U*eKuWP<ΨcyT&QO:_M?M-t]L2gE GTFZN#z /۵=+ -BJqlK3fڃJ_P=ͳ7//"CܽU6vIcgI+ Wa,5 -0 hW`?P~o^E+v؟)_G4zqiOa -.MlZmOY/47}_QO85D=;w I.S\2WT݉6hឥVQro]xz2SO E'9̹{eܷ\n|Pn2rլkBFWO%d\EH)&)KK2'= VXJvU-z2M3%m|QYJXLޕDߊT+Q?FǸ6bL6ʘ~W7v`>)[cXqΡv.oֹOɬN`MGCt=JN*/08]nPWR!@s*:V*Z<āт )3<9%!nĵFcc28UX>#BF4fեWgqNлBpKAdx:DڽT Fz6NQJ3m-}*Mvmŀf; %"i 8Iw\mzbeg\2O mSkYiFMWhgf"&[7ukM]]4(Y3cy pgS=*u goTF#SoV>" '+Ǎ6E݊P2m|AJ@X.,k(7BC׳[ E]^F۰,,Fil)y= ^z#lv 뛮۷]š0. hqUIekӵ8mvs C0BB iiS{TKm}Z+6fNw'ek7r5(yefjQU̘:P.[UMl?nUq욧yT݋/+  3]6qZS=+MksFdk®A^S㱛8咥(euHB#.k4/~}r8WU{Oob5k7ϗ? tuA pnsqa\Bl%8s<&U`qzrxff3?X:u9_ḻLDPGfْ ' ͖G87C<:|vNЂM&?LY W"yBECZS:Kl 8$ {v+j=Մ^47 !d}k^HJÄ-̐d8N9XFn/0h`ex:a^Y߁ɨ{<  _ⁱV 3~ F{6u1nݛvu8H uϺ9%kF03c>n;BTO>R<-6l&!t4 "vv=3:e'?aV+1lgHr p;2, z&{u6.abD`8ZAjJA)ӑqNxz}궍;IqӱQ"V h 鸋C\IwЯ>@wH׃>  ^T>ާPk:Ơ$9>' aY~4mGswlȵF1J[@yр7gdZ=aΧ.2/'KF}x>U+i]WU V6=7WZnvV^] ֓_a`ob dǜi=ݑQj!;jlFP%('Q:! A(! !/fGͻBh>vs&@hE3~șуEM{΄"W51ѴLB\M^`]vP +]}Y\F(ݘ;1-د։Yl39 PcKpX6[yK,y[o\a︅,IsNo)*؍V^6bQBe}?e.g-a>xZvNϟh} љwCijRk|1gGGGl2iݧs ȥx߷9$.ӽR 0CPr3R蚯d)" T^yOf +ikTy$UsvY<@nY榘+v"9{WFZtioZ(UFӚqg Uq + _aj4k0W#sd-we|`AvcfƔc'Ȥfbu$`VaL@ ` +AA3xVt.t+j4\r|%e ﳆYi] ?ĎP%d3P汆,FR.6Ƀ@r &S+C }; MR=!% Mi_.Amw g >_}pЅЩ\ԣ}Gp]P䃫QF#ZBv,n1:m-X-0۵Y'J %DIti+?XP87>34ϗ JhČpV㰎u? xT!0 +yh\uLN*cժsMծ>BLJzTBO8sk1OTslU-`['T0AwTRQ3c (E;K@ v]5H4I&+*VYO.Z!(Z-9h;ꉠ8¬XFPqu45ЪGuNP9NbʪTG}a[-.،{H8?XU`rMz+J ֦Ǎ.ccLbtMkFBnȝ^M%/$$XTi'XlKꊗ[Dw4P"VN#|eq,a"! L&xTA ] +ΤGTY@(Q2x1(=t/7 !AXsi`B +k_}~eLc$ξ!B7UD +GIoJ%SO݅N{s$Io + R59l&*@mKԏ+7PFʣBA r*iR#NF_&Jŝ'=T9J S{SZI<7/V6j)G,˗&T +[E +R,Ckr2 O %VBy#bAWPK5mj ®sBy*~\^9^D c-| ;i DD`hk&Z3.s/" CuSOm;~؟)_G4zqiGa +.MlZmGY/4(w'O"VpKM $UBt).TNv?pRo(7뮃wseEo)'tW}2^I\n|Pn2a׫Y)7ZJȨrR,-KdXt['PZa*<蝌YNA:r`3o&EN7< |'=˹(|q| +o>%Qn+͜uKE2_HWş2GDͦw&ko;Wl~ +zFƠًHM^w7yS[|:s" .ȥ +B Fs%j_RD?*ۄd[lŊ_vd?T]O0}ϯ"TE04mo PeŚk[}iB'$Ͻğt Ih5ew-"kPEa0Ab2a_ـIg^6:2:B9Z5jQwH$8K渒X0%39Prxҵܞ_v=45t ߹79 :o$<)%D# 4um D痿tѿ!7@>qkё=c5.G'>):!ˎ.5`>jǓ'۹$֨yPǒ,er(/-GJL=HXgٓJKΑ|u})Pcq I#^sbL'5Xn \ݢrRp{x+P{/-N АjOOj|\nöun0 y 8jM;H5RI#ABNk;X5_b%|39eqOޡ&d&{"/NJAU:Ga:>K!2,=ȇ\owl(Lv3EL@pF.|F.X-^8h <7Q#S5k=//H>] Lvo-^ei6d:#gj%7KE9JΑP4n]L&&( Jg=02isfSkN3>UQvPlPPg 53Ψ݆f^C j@FD)'mrb[4ୱI[ E@5D7ba)UH-3b]$Ɖ)4Fml %&U|"`2ƪwln}6r+,vp pa E/N}em1W1n%R!ik@tr!╓3R6$-FÄA;-Q"vԺ9nO6xߡSCU]0Dt!COϫkOv+:xZ v8حԙr݆$.+{(ͮ?k3ûǪC:}>c(0XM:u-%|쏙v"7Prh%bK,0 -QW@KUp`Xr6}W3jI94/݋;nq҇@$h!ek{E RJI,vg̗1:8(~\ DJ<׉d )B&iUp-{MAE)@Q`\J1 Jy0+-@wK v͓>n *EoH1e>|͹JB25u]fc䟟O"3nuAxz\hDC =D TgGG|Ab+ކQvqWt$ Y`izP[EU|D?&! DH}pkCn@JК~u[OҿS$H uNϠR!.]kS0=C;1(''}ԸMSzX9óD*$W8(o*^upiW7]*XݧVm\5KKY@DQk%I*pֳ&ly yI]VE'+^kfk[1+v"kusLh({/,I.mp91ÝBn[s[vqƁp#9mtBTIu*ygpRnq[|:k塐pTS|[Yh`~EϘջκXܹ8@rsɥ]]Nzk>fǬiء~m [˚%pkk:sl'!iG4`X' g,*HhhYҵM`OozJJ4]Y/n!ojoL|n:.Zfx'g|L*ǢrbtE֔Zcο^^ qd*GgU E=Rbc̴NF#,OCNhNxJ#D9Va'9E _^&t>֎vaA&E3Q?Ăy$2-\Um- 5•#xK)0cahl4\sT]Pq7T@b"=qlEũܑ|hk |FejJ*g =G謎6B=Fe#CF4/D M9P#u e*A11Hgb{XyR^!W e@ 1(/]%2+u"WCnJXXnhm~Xhj_Zmo8_Z.\ ]Ul9ֱl"ѱ6mPoDr8m$q8p8j{tyI)V1Q.9}WJЧlm4# nK?`ou&wDB}Mu(]>}"J `}<`Sf)?=nH!nHuֶa_rvЀTW7pvCxAH6vLC^Gc9Exc}Ʒ7U<( +QW@KUp`Xr6}W3jI94/6θI:vFXi]Q$H)SlYZҰ5!Z;.AoFWȷ7x@5aK̓h0? (?!>>bR=5DfNdk->x_+1ܮM pTZ Zmo8_Z.\ ]Ul9ֱl"ѱ6mPoDr8m$q8p8j{tyI)V1Q.9}WJЧlm4# nK?`ou&wDB}Mu(]>}"J `}<`Sf)?=nH!nHuֶa_rvЀTW7pvCxAH6vLC^Gc9Exc}Ʒ7U<( (-EGMB}) `1% D2~oȘenm~}=O-8M $ll]Fyn>#mDήQ#/,r14$t_-|x9<ЦNL _'::t}:,FG"RҚh3ɥf /U='uͤuk R%sհbi03S#H7UF}rYZļP'Ơ.2<z6qH7OC#9׆:>hjj\3 /p6?@d^砣R1P:8HÅ]"Y3ҭl,ojg}df2-LB,|0uҧfϦ]0X{l=2X31PՅaا,T4 Z<%H{ZdOsm:԰utS22tiD >4HC[2!!{@,c!|G&L4t`%[d҃۵ܯГ`YK,t6՚wЂ`@%hYipaG+u}S5^m4Id>m#DvVg20H opiII6 0@Sn!wXZ}si\(*s;<ՇrT;ô2e~1d0+^H:w_w!Hd'TΏf%DPRJ]UpU$PܳA;]{ c%d-[GT/!_d%)'d"G>b۫` |40=+6f8eꌺ#U#poK΀}Th\_E7 \A_^q$}`e ֮=[Kp䭄y'* UZ gEvدp@S X, +t kCK,lPE #S%i׀3¶31r2ʔ +O{k8,܃#@[!8Ipk+L۴NqaZWY¾ZybmU`*6Xo1 @@ -857,27 +869,24 @@ K $[4tmzA0ݧm{]3DOŊ$},Lhufs8 hDF"aTĸp|HiP!N-!CH0nXİ\ 8HLBڥÂP_No>$C̾O+"U) 3q|&Й:v4 K8$p_m) $.qlc kضuϟq@y6>)/ ;~iu{0Wv .z靃"9Una>9KޗY7͋לJª?Ax#f6wfU.eݻS#kdXZR[obנ]3_(ksH{~d˷@_ɥ Ǫ!lId*DI_w4c>ؠw __lzb`~z1oovvcFsv0u+{g 숅<5l{šwg?a3gQǜޜyޱ EMvŗ,,xEM醜y8O< |/p37Ɓ?p^Df) h%snjuȌg d +1xkGS8wWG2c;|,$w[-|̣ -3U}BD# -C/^P9s.y-%xloрz qh6wcz;5e9֚lww}Yd`Fв)dmL͌P .H&m8;aϣ"(F7vMy`NxYkQڦD4|1o,29J!>! ؝нg0$r_ZX 2ĘGQ5UU`!4BX /C|U+c3s(K-Y_$+AyeьݯDgt]4%}{l>8O(9טDUAaB^\mN9q Av͕W7;%*ϣGj*hyO;$%2̙k>@N=#`N)AL8ńcoW 0. ?)TPBeY/c<>Xsn~(uN r>Dd.x9 D϶0Io224QgId̐CwlJxCJi߫E -CRȨõ""^~^ݧ,Oتon.OP+/[4a}))}r)j@bm*NjЇ%n+"fs3(M.-SLq$!fxѾ1y -bȏbDǛNig{yvWE8b-jw}Vc{ -;c *&CIUqNBwA)f-6[Pv696.QW@tK -oeO;e{:Nܗ#ؽE9I$"0onH6ի<}jch8jul- MK5!Q&~د#Hy>qך5͔eBO-y@ yLy'w0֥ j. +q|--ءP_M^1;#ȗ~|^ײU{cxvsIk_2s> RamlմAZ so^H@ -ݔFQHZ|jT8"-!LrVkGEDEU@ 7UZ~fr -#$C,1fR:AƔ|*zÝ 4Er+XT^L -;_ajTy\K#kWޔ430b:1 'O`+c6x]*y͠@)ZO _-*Ϯ)QD7[m9(r[w7|6X~%0TAUb%,nhS}NLi_ƍK\EۉrcHY,>0:.9/=j%;|&xD 8l~(7vepNG6^N'dSQlg!!yUM| -,g"y); (ݍ"/X4Eш^f6\08ƩUszgZڥ֬nDW^uO|r{Ni3o[Tx}oD kQa 7~ZJIwJ g_Y2]N -x,X&!s3m'.3eCK;*x\'k<ܯiz4R9XIZ g|}ur%_*]UmU, V LB+]bՒkVInഅ}.)P֤{,)+Otg}@Ď\ %әD[ωUuӋφEBKQ)el~"xhtmsi5v-K^z٪Gۃ\M S>kU*"'?A)P=\[S~(\KV tO~ Y/?M^{ޓ1V;L&]LX!햲^6/W~_]9c/ * Vu_&u4u:AׄşWv66w$?D,XDox -U[>%}`o#(x]jQ_E2ð;}22Q rA$_FgG#,= L~QAN0{Q<= qArM6k[k!i"^dYkΌ~⑂ǖmoRtaR*<=xF&ȁ^P6}F6BGrECgmA&Ap׆fSC^[8X~DX(D􉺥JHgO/\+yUc l1.^v6' ˩C…jbl$B<®D oēvcB2Tӧ-ɶYScVGRn0+% 7!c dvh&i6P4̼Y8>Q`B-H.=l56<%Xa#U1s5 x +$;V#|H5y~i\\1 1<6$~q.Y820R w͆1a%8wW npe2ag%/`E!M(o~s6ۍBipbbR΀OV΂ =*ES?KJOXs+MNb/[F5ֶF%>>9KޗY7͋לJª?Ax#f6wfU.eݻS#kdXZR[obנ]3_(ks6{~qOR"ՎsFTJq2Zm)RCR}|$˶bX }ʻ_g/_>#/I7\FeByݟnpE$&\,5q͎IDc}-xCc:$Ζ fdS$є7g^FOV쑃/0hpel}Sf&3(k8xQl) a T +:"$P}:d`~[A!"lfز?@yEGliuH' $@#Vj>֞tRg;^;{.aElQ>^mmU"|A8:{Ͽg˔8Ԧ41M~ loшz~hpvFϽ6),圾}hݝ7o߶wN9,kZO Mgߕh{kxC86O'_'F:(@K2F1 uYv/GیEzD4I L C$ OsFࡖZ51\/ct|S +xZH*!d HB.ٱ HJ"yOʦ4Hі >\jx?;4`5x4{T͡xU]"@ ]Ѥ)k 4f20[qFo؇ĦiCR!Er({eK0Sq؄^6Dԍ5!NW40P\:)*/(G42I%h}8;L'%:Wq}E<\@j3 +f1+FtF黔 9_SVfB 98bhgugS +KK.>`cyz6aܴcRȝCD! 4S͇n1~" o+5"YNVF 0uw$L K&W5$@%琪tM.(QNoI2Up+zg`\ + }N_.:#3]Fe|5V䛰iSlηNb?=ő)@%$dIsw3aHa@"ˡe1ogIX|Z*ɰ-K*S_f-.!=;MLmRo-GYԧZ+M4DߖfpI$cGwW2q6yEvCeb,g;Wwi q[j~H'WƩ Px;he:2?BNK* .LS:7|7!᯺8=\ysг,TvVDjFrOgkϚz|E΋e^}1B SD%⢻:Vۈơl=lSRYA +U#^k]H uJ.$#fJ{1D 9oj§oExu8` 27 :MؙKomUzE+wHvd) yWNU,m]7L0hk}FohwģLȸ{*W +0*XubKPk Uco&]- #VK3elIr4ZrPV +НIZ +Wމ)CBg&'yFf X6,6E¾.v^@KE%%(MYۗUUw9$qG=C5ohz4R9XI Og7uפ \9>US՜5̫]Dr!穒kiڢt7&ZC]L@G +ՎKvOqSxrSSuFǼqAQ`B-H.=l56<%Xa#U1s5 x QL7Qe0)D36=SX4F5,+P0ܐ@4WjZF׭+qF bݖ  R(&1:iMCe{,O ''yuWAxƚ&;;"25\´K&Un\)SnhYkfp%NwyF0$V>Q= ni'wn+'6O\f^c_,3(N[ E>9fiG8E>EAއYgEQ-k;e?T"5*bw],x?Xmo_qZee\$+mim: 8٨,l1 Zo 3g̙|^۷R7]a6iӇ}8};Y"ɣrIx2.C@0LH=x3W"dEe IHK)(JHl"8JlE4K|FieN4$` 2A ͣ<!-) @@ -904,4 +913,4 @@ T Ŋ Ld*;␇K̽aru=hJeI_ :S}G'w: a@Ld4E(aiX~2)km*ݳ:-O3.OT%z؁ff :Ήx%8,+Ӻ.adv?=hMzkrmRmZ߉QaA :'t&6.򇦨Y uA -@ Es\@@BQpgCh8PSo{?벆T$OBXiYP|Q~3jfK3,n>HAԀXH) q8agĭO59H'-FGBMB \ No newline at end of file +@ Es\@@BQpgCh8PSo{?벆T$OBXiYP|Q~3jfK3,n>HAԀXH) q8n-2(wn