From fa5f40929fa4fb0411aaa9d7a5183ea800efedd3 Mon Sep 17 00:00:00 2001 From: Sebastian Bergmann Date: Sun, 3 Jan 2021 08:32:22 +0100 Subject: [PATCH 1/2] Sync PHP-CS-Fixer configuration --- .php_cs.dist | 84 +++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 77 insertions(+), 7 deletions(-) diff --git a/.php_cs.dist b/.php_cs.dist index 1c89105aaf5..1c10a3a1640 100644 --- a/.php_cs.dist +++ b/.php_cs.dist @@ -11,13 +11,17 @@ EOF; $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) @@ -25,7 +29,9 @@ return PhpCsFixer\Config::create() ->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', @@ -61,31 +67,48 @@ return PhpCsFixer\Config::create() 'braces' => true, 'cast_spaces' => true, 'class_attributes_separation' => ['elements' => ['const', 'method', 'property']], + '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, @@ -96,16 +119,19 @@ return PhpCsFixer\Config::create() '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, @@ -119,7 +145,6 @@ return PhpCsFixer\Config::create() '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, @@ -132,19 +157,26 @@ return PhpCsFixer\Config::create() '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', @@ -169,28 +201,54 @@ return PhpCsFixer\Config::create() '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, @@ -204,11 +262,23 @@ return PhpCsFixer\Config::create() '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, 'trim_array_spaces' => true, From 8839d8da3684a215de5a4e956299589b9159b224 Mon Sep 17 00:00:00 2001 From: Sebastian Bergmann Date: Sun, 3 Jan 2021 08:32:27 +0100 Subject: [PATCH 2/2] Fix CS/WS issues --- src/Exception.php | 4 +- src/Framework/Assert.php | 491 ++++++------ src/Framework/Assert/Functions.php | 704 +++++++++--------- src/Framework/Constraint/ArrayHasKey.php | 8 +- src/Framework/Constraint/ArraySubset.php | 26 +- src/Framework/Constraint/Attribute.php | 6 +- src/Framework/Constraint/Callback.php | 4 +- .../Constraint/ClassHasAttribute.php | 19 +- .../Constraint/ClassHasStaticAttribute.php | 9 +- src/Framework/Constraint/Composite.php | 7 +- src/Framework/Constraint/Constraint.php | 15 +- src/Framework/Constraint/Count.php | 19 +- src/Framework/Constraint/DirectoryExists.php | 9 +- src/Framework/Constraint/Exception.php | 12 +- src/Framework/Constraint/ExceptionCode.php | 9 +- src/Framework/Constraint/ExceptionMessage.php | 14 +- .../ExceptionMessageRegularExpression.php | 8 +- src/Framework/Constraint/FileExists.php | 9 +- src/Framework/Constraint/IsAnything.php | 2 +- src/Framework/Constraint/IsEmpty.php | 17 +- src/Framework/Constraint/IsEqual.php | 18 +- src/Framework/Constraint/IsFinite.php | 4 +- src/Framework/Constraint/IsIdentical.php | 41 +- src/Framework/Constraint/IsInfinite.php | 4 +- src/Framework/Constraint/IsInstanceOf.php | 14 +- src/Framework/Constraint/IsJson.php | 16 +- src/Framework/Constraint/IsNan.php | 4 +- src/Framework/Constraint/IsReadable.php | 9 +- src/Framework/Constraint/IsType.php | 47 +- src/Framework/Constraint/IsWritable.php | 9 +- src/Framework/Constraint/JsonMatches.php | 12 +- .../JsonMatchesErrorMessageProvider.php | 22 +- src/Framework/Constraint/LogicalAnd.php | 10 +- src/Framework/Constraint/LogicalNot.php | 26 +- src/Framework/Constraint/LogicalOr.php | 10 +- src/Framework/Constraint/LogicalXor.php | 10 +- .../Constraint/RegularExpression.php | 7 +- src/Framework/Constraint/StringContains.php | 13 +- src/Framework/Constraint/StringEndsWith.php | 5 +- .../StringMatchesFormatDescription.php | 25 +- src/Framework/Constraint/StringStartsWith.php | 6 +- .../Constraint/TraversableContains.php | 15 +- .../Constraint/TraversableContainsEqual.php | 12 +- .../TraversableContainsIdentical.php | 12 +- .../Constraint/TraversableContainsOnly.php | 4 +- src/Framework/DataProviderTestSuite.php | 8 +- src/Framework/Exception/Exception.php | 12 +- .../Exception/ExpectationFailedException.php | 3 +- .../Exception/InvalidArgumentException.php | 11 +- src/Framework/ExceptionWrapper.php | 11 +- src/Framework/MockObject/Api/Method.php | 6 +- .../MockObject/Builder/InvocationMocker.php | 29 +- .../MockObject/Builder/InvocationStubber.php | 3 +- .../MockObject/Exception/Exception.php | 4 +- src/Framework/MockObject/Generator.php | 301 ++++---- src/Framework/MockObject/Invocation.php | 33 +- .../MockObject/InvocationHandler.php | 9 +- src/Framework/MockObject/Matcher.php | 32 +- .../MockObject/MethodNameConstraint.php | 9 +- src/Framework/MockObject/MockBuilder.php | 29 +- src/Framework/MockObject/MockClass.php | 7 +- src/Framework/MockObject/MockMethod.php | 55 +- src/Framework/MockObject/MockMethodSet.php | 10 +- src/Framework/MockObject/MockTrait.php | 4 +- .../MockObject/Rule/ConsecutiveParameters.php | 24 +- .../MockObject/Rule/InvocationOrder.php | 5 +- .../MockObject/Rule/InvokedAtIndex.php | 3 +- .../MockObject/Rule/InvokedCount.php | 5 +- src/Framework/MockObject/Rule/MethodName.php | 3 +- src/Framework/MockObject/Rule/Parameters.php | 20 +- .../MockObject/Stub/ConsecutiveCalls.php | 6 +- src/Framework/MockObject/Stub/Exception.php | 8 +- .../MockObject/Stub/ReturnArgument.php | 3 +- .../MockObject/Stub/ReturnCallback.php | 15 +- .../MockObject/Stub/ReturnReference.php | 3 +- src/Framework/MockObject/Stub/ReturnStub.php | 3 +- .../MockObject/Stub/ReturnValueMap.php | 9 +- src/Framework/TestBuilder.php | 33 +- src/Framework/TestCase.php | 310 ++++---- src/Framework/TestFailure.php | 11 +- src/Framework/TestListener.php | 10 +- .../TestListenerDefaultImplementation.php | 10 +- src/Framework/TestResult.php | 84 ++- src/Framework/TestSuite.php | 130 ++-- src/Framework/TestSuiteIterator.php | 10 +- src/Runner/BaseTestRunner.php | 10 +- src/Runner/DefaultTestResultCache.php | 60 +- src/Runner/Exception.php | 4 +- .../Filter/ExcludeGroupFilterIterator.php | 4 +- src/Runner/Filter/Factory.php | 6 +- src/Runner/Filter/GroupFilterIterator.php | 12 +- .../Filter/IncludeGroupFilterIterator.php | 4 +- src/Runner/Filter/NameFilterIterator.php | 30 +- src/Runner/Hook/TestListenerAdapter.php | 9 +- src/Runner/PhptTestCase.php | 160 ++-- src/Runner/ResultCacheExtension.php | 19 +- src/Runner/StandardTestSuiteLoader.php | 59 +- src/Runner/TestSuiteSorter.php | 64 +- src/Runner/Version.php | 15 +- src/TextUI/Command.php | 200 ++--- src/TextUI/Exception.php | 4 +- src/TextUI/Help.php | 47 +- src/TextUI/ResultPrinter.php | 80 +- src/TextUI/TestRunner.php | 121 +-- src/Util/Annotation/DocBlock.php | 188 +++-- src/Util/Annotation/Registry.php | 14 +- src/Util/Blacklist.php | 24 +- src/Util/Color.php | 40 +- src/Util/Configuration.php | 140 ++-- src/Util/ConfigurationGenerator.php | 4 +- src/Util/ErrorHandler.php | 38 +- src/Util/Exception.php | 4 +- src/Util/FileLoader.php | 23 +- src/Util/Filesystem.php | 13 +- src/Util/Filter.php | 24 +- src/Util/Getopt.php | 78 +- src/Util/GlobalState.php | 61 +- src/Util/InvalidDataSetException.php | 4 +- src/Util/Json.php | 30 +- src/Util/Log/JUnit.php | 58 +- src/Util/Log/TeamCity.php | 66 +- src/Util/PHP/AbstractPhpProcess.php | 70 +- src/Util/PHP/DefaultPhpProcess.php | 71 +- src/Util/PHP/WindowsPhpProcess.php | 6 +- src/Util/Printer.php | 57 +- src/Util/RegularExpression.php | 4 +- src/Util/Test.php | 218 +++--- src/Util/TestDox/CliTestDoxPrinter.php | 81 +- src/Util/TestDox/HtmlResultPrinter.php | 6 +- src/Util/TestDox/NamePrettifier.php | 117 +-- src/Util/TestDox/ResultPrinter.php | 17 +- src/Util/TestDox/TestDoxPrinter.php | 39 +- src/Util/TestDox/XmlResultPrinter.php | 30 +- src/Util/TextTestListRenderer.php | 19 +- src/Util/Type.php | 4 +- src/Util/VersionComparisonOperator.php | 7 +- src/Util/XdebugFilterScriptGenerator.php | 22 +- src/Util/Xml.php | 81 +- src/Util/XmlTestListRenderer.php | 19 +- .../DataProviderIssue2922/FirstTest.php | 3 +- tests/_files/ExceptionNamespaceTest.php | 4 +- tests/_files/ExceptionTest.php | 6 +- tests/basic/unit/SetUpBeforeClassTest.php | 9 +- tests/basic/unit/SetUpTest.php | 7 +- tests/basic/unit/StatusTest.php | 8 +- tests/basic/unit/TearDownAfterClassTest.php | 5 +- tests/end-to-end/_files/Extension.php | 29 +- tests/end-to-end/loggers/_files/HookTest.php | 3 +- .../loggers/_files/raw_output_StatusTest.txt | 6 +- .../regression/GitHub/2137/Issue2137Test.php | 4 +- .../regression/GitHub/2158/Issue2158Test.php | 4 +- .../GitHub/2725/BeforeAfterClassPidTest.php | 9 +- .../regression/GitHub/3093/Issue3093Test.php | 4 +- .../regression/GitHub/3739/Issue3739Test.php | 5 +- tests/unit/Framework/Assert/FunctionsTest.php | 16 +- tests/unit/Framework/AssertTest.php | 447 +++++------ .../Framework/Constraint/ArraySubsetTest.php | 22 +- .../Framework/Constraint/CallbackTest.php | 6 +- .../Constraint/ClassHasAttributeTest.php | 10 +- .../ClassHasStaticAttributeTest.php | 10 +- .../Constraint/ConstraintTestCase.php | 16 +- tests/unit/Framework/Constraint/CountTest.php | 42 +- .../Constraint/ExceptionCodeTest.php | 3 +- .../Constraint/ExceptionMessageRegExpTest.php | 16 +- .../Constraint/ExceptionMessageTest.php | 17 +- .../unit/Framework/Constraint/IsEmptyTest.php | 8 +- .../unit/Framework/Constraint/IsEqualTest.php | 43 +- .../Framework/Constraint/IsIdenticalTest.php | 9 +- .../Framework/Constraint/IsInstanceOfTest.php | 14 +- .../unit/Framework/Constraint/IsTypeTest.php | 23 +- .../JsonMatchesErrorMessageProviderTest.php | 20 +- .../Framework/Constraint/JsonMatchesTest.php | 24 +- .../Framework/Constraint/LogicalAndTest.php | 54 +- .../Framework/Constraint/LogicalOrTest.php | 53 +- .../Framework/Constraint/LogicalXorTest.php | 6 +- .../Constraint/ObjectHasAttributeTest.php | 10 +- .../Framework/Constraint/SameSizeTest.php | 14 +- .../StringMatchesFormatDescriptionTest.php | 11 +- .../Constraint/TraversableContainsTest.php | 16 +- tests/unit/Framework/ConstraintTest.php | 73 +- tests/unit/Framework/ExceptionWrapperTest.php | 16 +- .../unit/Framework/IncompleteTestCaseTest.php | 8 +- .../Framework/MockObject/GeneratorTest.php | 4 +- .../MockObject/InvocationHandlerTest.php | 8 +- .../unit/Framework/MockObject/MatcherTest.php | 14 +- .../Framework/MockObject/MockClassTest.php | 6 +- .../Framework/MockObject/MockMethodTest.php | 6 +- .../Framework/MockObject/MockObjectTest.php | 12 +- .../Framework/MockObject/MockTraitTest.php | 6 +- tests/unit/Framework/SkippedTestCaseTest.php | 8 +- tests/unit/Framework/TestBuilderTest.php | 29 +- tests/unit/Framework/TestCaseTest.php | 313 ++++---- tests/unit/Framework/TestFailureTest.php | 3 +- tests/unit/Framework/TestImplementorTest.php | 8 +- tests/unit/Framework/TestListenerTest.php | 9 +- .../unit/Framework/TestSuiteIteratorTest.php | 10 +- tests/unit/Framework/TestSuiteTest.php | 82 +- .../Runner/Filter/NameFilterIteratorTest.php | 3 +- tests/unit/Runner/PhptTestCaseTest.php | 54 +- .../unit/Runner/ResultCacheExtensionTest.php | 38 +- tests/unit/Runner/TestSuiteSorterTest.php | 288 +++---- tests/unit/Util/Annotation/RegistryTest.php | 16 +- tests/unit/Util/ColorTest.php | 3 +- tests/unit/Util/ConfigurationTest.php | 88 ++- tests/unit/Util/GetoptTest.php | 5 +- tests/unit/Util/RegularExpressionTest.php | 5 +- tests/unit/Util/TestClassTest.php | 156 ++-- .../TestDox/CliTestDoxPrinterColorTest.php | 4 +- .../Util/XDebugFilterScriptGeneratorTest.php | 13 +- tests/unit/Util/XmlTest.php | 18 +- 210 files changed, 4629 insertions(+), 3306 deletions(-) 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 fbc3eb7a93f..de9fa0fd7b6 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,9 +1911,9 @@ 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 @@ -1894,7 +1921,7 @@ public static function assertAttributeNotSame($expected, string $actualAttribute */ 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,8 +2011,8 @@ 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 @@ -2006,9 +2033,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 +2054,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 +2071,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 +2088,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 +2105,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 +2122,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 +2139,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 +2156,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 +2173,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 +2190,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 +2207,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 +2224,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,8 +2241,8 @@ 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 @@ -2236,8 +2263,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 +2280,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 +2297,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 +2314,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 +2331,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 +2348,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 +2365,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 +2382,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 +2399,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 +2416,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 +2433,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 +2452,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 +2473,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 +2484,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 +2505,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 +2533,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 +2559,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 +2570,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 +2587,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 +2597,7 @@ public static function assertStringMatchesFormatFile(string $formatFile, string static::assertThat( $string, new StringMatchesFormatDescription( - \file_get_contents($formatFile) + file_get_contents($formatFile) ), $message ); @@ -2579,8 +2606,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 +2617,7 @@ public static function assertStringNotMatchesFormatFile(string $formatFile, stri $string, new LogicalNot( new StringMatchesFormatDescription( - \file_get_contents($formatFile) + file_get_contents($formatFile) ) ), $message @@ -2600,8 +2627,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 +2641,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 +2656,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 +2667,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 +2678,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 +2689,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 +2702,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 +2713,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 +2730,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 +2745,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 +2762,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 +2779,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 +2797,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 +2815,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 +2830,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 +2849,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 +2861,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 +2883,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 +2904,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 +2917,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 +2928,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 +2945,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 +2965,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 +2982,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 +3005,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 +3032,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 +3061,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 +3071,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 +3086,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); @@ -3328,8 +3355,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 +3369,7 @@ public static function readAttribute($classOrObject, string $attributeName) ); } - if (\is_object($classOrObject)) { + if (is_object($classOrObject)) { return static::getObjectAttribute( $classOrObject, $attributeName @@ -3368,7 +3395,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 +3404,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 +3418,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 +3426,7 @@ public static function getStaticAttribute(string $className, string $attributeNa } throw new Exception( - \sprintf( + sprintf( 'Attribute "%s" not found in class.', $attributeName ) @@ -3421,7 +3448,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 +3471,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 +3506,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 +3534,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 +3549,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 +3557,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 +3570,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); diff --git a/src/Framework/Assert/Functions.php b/src/Framework/Assert/Functions.php index 6f07773aefd..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,13 +1536,13 @@ 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 @@ -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..97ec763dfdf 100644 --- a/src/Framework/Constraint/Callback.php +++ b/src/Framework/Constraint/Callback.php @@ -9,6 +9,8 @@ */ namespace PHPUnit\Framework\Constraint; +use function call_user_func; + /** * Constraint that evaluates against a specified closure. */ @@ -40,6 +42,6 @@ public function toString(): string */ protected function matches($other): bool { - return \call_user_func($this->callback, $other); + return call_user_func($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 0822863a403..e37b4a17fd0 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/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/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 6786b69b780..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,38 +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) { - $parameterStart = \strpos($args[$i], '$'); + foreach (range(0, count($args) - 1) as $i) { + $parameterStart = strpos($args[$i], '$'); if (!$parameterStart) { continue; } - $args[$i] = \substr($args[$i], $parameterStart); + $args[$i] = substr($args[$i], $parameterStart); } $methodTemplate->setVar( [ 'method_name' => $name, - 'arguments' => \implode(', ', $args), + 'arguments' => implode(', ', $args), ] ); @@ -436,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( @@ -463,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(), @@ -493,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(), @@ -523,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(), @@ -546,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(), @@ -580,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(), @@ -606,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(), @@ -652,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 ) @@ -668,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(), @@ -680,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 ) @@ -692,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(), @@ -720,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; } @@ -740,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(), @@ -753,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'] ) @@ -761,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(), @@ -785,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(), @@ -812,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) ); } @@ -826,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(), @@ -859,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(), @@ -902,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( @@ -943,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 = ''; @@ -965,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 [ @@ -982,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'])) { @@ -1001,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'] . '\\' : '', @@ -1013,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())); } @@ -1023,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]; @@ -1037,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 27faa8028e3..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; } @@ -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 getMethodParametersForDeclaration(\ReflectionMethod $method): string + private static function getMethodParametersForDeclaration(ReflectionMethod $method): string { $parameters = []; @@ -268,7 +281,7 @@ private static function getMethodParametersForDeclaration(\ReflectionMethod $met if ($parameter->hasType()) { $type = $parameter->getType(); - if ($type instanceof \ReflectionNamedType) { + if ($type instanceof ReflectionNamedType) { $typeName = $type->getName(); } } @@ -276,7 +289,7 @@ private static function getMethodParametersForDeclaration(\ReflectionMethod $met if ($parameter->isVariadic()) { $name = '...' . $name; } elseif ($parameter->isDefaultValueAvailable()) { - $default = ' = ' . \var_export($parameter->getDefaultValue(), true); + $default = ' = ' . var_export($parameter->getDefaultValue(), true); } elseif ($parameter->isOptional()) { $default = ' = null'; } @@ -300,15 +313,15 @@ private static function getMethodParametersForDeclaration(\ReflectionMethod $met $parameters[] = $nullable . $typeDeclaration . $reference . $name . $default; } - return \implode(', ', $parameters); + return implode(', ', $parameters); } /** * Returns the parameters of a function or method. * - * @throws \ReflectionException + * @throws ReflectionException */ - private static function getMethodParametersForCall(\ReflectionMethod $method): string + private static function getMethodParametersForCall(ReflectionMethod $method): string { $parameters = []; @@ -333,10 +346,10 @@ private static function getMethodParametersForCall(\ReflectionMethod $method): s } } - return \implode(', ', $parameters); + return implode(', ', $parameters); } - private static function deriveReturnType(\ReflectionMethod $method): Type + private static function deriveReturnType(ReflectionMethod $method): Type { $returnType = $method->getReturnType(); @@ -355,7 +368,7 @@ 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/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 442a55628e7..988431763f0 100644 --- a/src/Framework/TestCase.php +++ b/src/Framework/TestCase.php @@ -9,6 +9,58 @@ */ namespace PHPUnit\Framework; +use const LC_ALL; +use const LC_COLLATE; +use const LC_CTYPE; +use const LC_MESSAGES; +use const LC_MONETARY; +use const LC_NUMERIC; +use const LC_TIME; +use const PATHINFO_FILENAME; +use const PHP_EOL; +use const PHP_URL_PATH; +use function array_filter; +use function array_flip; +use function array_keys; +use function array_merge; +use function array_unique; +use function array_values; +use function assert; +use function basename; +use function call_user_func; +use function chdir; +use function class_exists; +use function clearstatcache; +use function count; +use function defined; +use function explode; +use function get_class; +use function get_include_path; +use function getcwd; +use function implode; +use function in_array; +use function ini_set; +use function is_array; +use function is_int; +use function is_object; +use function is_string; +use function libxml_clear_errors; +use function method_exists; +use function ob_end_clean; +use function ob_get_contents; +use function ob_get_level; +use function ob_start; +use function parse_url; +use function pathinfo; +use function preg_replace; +use function serialize; +use function setlocale; +use function sprintf; +use function strlen; +use function strpos; +use function substr; +use function trim; +use function var_export; use DeepCopy\DeepCopy; use PHPUnit\Framework\Constraint\Exception as ExceptionConstraint; use PHPUnit\Framework\Constraint\ExceptionCode; @@ -46,6 +98,8 @@ use Prophecy\Prophecy\MethodProphecy; use Prophecy\Prophecy\ObjectProphecy; use Prophecy\Prophet; +use ReflectionClass; +use ReflectionException; use SebastianBergmann\Comparator\Comparator; use SebastianBergmann\Comparator\Factory as ComparatorFactory; use SebastianBergmann\Diff\Differ; @@ -54,10 +108,12 @@ use SebastianBergmann\GlobalState\Restorer; use SebastianBergmann\GlobalState\Snapshot; use SebastianBergmann\ObjectEnumerator\Enumerator; +use Text_Template; +use Throwable; abstract class TestCase extends Assert implements SelfDescribing, Test { - private const LOCALE_CATEGORIES = [\LC_ALL, \LC_COLLATE, \LC_CTYPE, \LC_MONETARY, \LC_NUMERIC, \LC_TIME]; + private const LOCALE_CATEGORIES = [LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_TIME]; /** * @var ?bool @@ -375,7 +431,7 @@ 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 +494,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 +505,7 @@ public function toString(): string } // @codeCoverageIgnoreEnd - $buffer = \sprintf( + $buffer = sprintf( '%s::%s', $class->name, $this->getName(false) @@ -523,7 +579,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 +675,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 +704,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 +716,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 +734,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 +750,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 +768,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 +835,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 +867,7 @@ public function setUseErrorHandler(bool $useErrorHandler): void */ public function doubledTypes(): array { - return \array_unique($this->doubledTypes); + return array_unique($this->doubledTypes); } /** @@ -919,7 +975,7 @@ public function getActualOutput(): string return $this->output; } - return (string) \ob_get_contents(); + return (string) ob_get_contents(); } /** @@ -951,7 +1007,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 +1053,7 @@ public function setRegisterMockObjectsFromTestArgumentsRecursively(bool $flag): } /** - * @throws \Throwable + * @throws Throwable * * @internal This method is not covered by the backward compatibility promise for PHPUnit */ @@ -1007,8 +1063,8 @@ public function runBare(): void $this->snapshotGlobalState(); $this->startOutputBuffering(); - \clearstatcache(); - $currentWorkingDirectory = \getcwd(); + clearstatcache(); + $currentWorkingDirectory = getcwd(); $hookMethods = TestUtil::getHookMethods(static::class); @@ -1038,9 +1094,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 +1117,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 +1140,7 @@ public function runBare(): void } } } - } catch (\Throwable $_e) { + } catch (Throwable $_e) { $e = $e ?? $_e; } @@ -1099,17 +1155,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 +1175,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 +1221,7 @@ public function getDependencies(): array */ public function hasDependencies(): bool { - return \count($this->dependencies) > 0; + return count($this->dependencies) > 0; } /** @@ -1335,7 +1391,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 +1412,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)); + $buffer .= sprintf(' (%s)', $exporter->shortenedRecursiveExport($this->data)); } } @@ -1393,27 +1449,27 @@ 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; } @@ -1472,7 +1528,7 @@ protected function runTest() $this->numAssertions++; throw new AssertionFailedError( - \sprintf( + sprintf( 'Failed asserting that exception with message "%s" is thrown', $this->expectedExceptionMessage ) @@ -1481,7 +1537,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 +1546,7 @@ protected function runTest() $this->numAssertions++; throw new AssertionFailedError( - \sprintf( + sprintf( 'Failed asserting that exception with code "%s" is thrown', $this->expectedExceptionCode ) @@ -1509,13 +1565,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 +1588,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 +1642,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 +1686,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 +1704,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 +1767,7 @@ protected function getMockClass($originalClassName, $methods = [], array $argume $cloneArguments ); - return \get_class($mock); + return get_class($mock); } /** @@ -1769,11 +1825,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 +1923,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 +1961,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; } @@ -1944,13 +2000,13 @@ 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; } @@ -1960,12 +2016,12 @@ private function checkRequirements(): void ); if (!empty($missingRequirements)) { - $this->markTestSkipped(\implode(\PHP_EOL, $missingRequirements)); + $this->markTestSkipped(implode(PHP_EOL, $missingRequirements)); } } /** - * @throws \Throwable + * @throws Throwable */ private function verifyMockObjects(): void { @@ -1986,9 +2042,9 @@ 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()); } } } @@ -2000,17 +2056,17 @@ private function handleDependencies(): bool { if (!empty($this->dependencies) && !$this->inIsolation) { $passed = $this->result->passed(); - $passedKeys = \array_keys($passed); + $passedKeys = array_keys($passed); foreach ($passedKeys as $key => $value) { - $pos = \strpos($value, ' with data set'); + $pos = strpos($value, ' with data set'); if ($pos !== false) { - $passedKeys[$key] = \substr($value, 0, $pos); + $passedKeys[$key] = substr($value, 0, $pos); } } - $passedKeys = \array_flip(\array_unique($passedKeys)); + $passedKeys = array_flip(array_unique($passedKeys)); foreach ($this->dependencies as $dependency) { $deepClone = false; @@ -2022,23 +2078,23 @@ 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) { + if (strpos($dependency, '::') === false) { $dependency = static::class . '::' . $dependency; } @@ -2095,7 +2151,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 ); @@ -2112,7 +2168,7 @@ private function markSkippedForMissingDependency(string $dependency): void $this->result->addError( $this, new SkippedTestError( - \sprintf( + sprintf( 'This test depends on "%s" to pass.', $dependency ) @@ -2132,7 +2188,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 ) @@ -2157,10 +2213,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(); } /** @@ -2168,9 +2224,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( @@ -2178,16 +2234,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 @@ -2201,8 +2257,8 @@ private function snapshotGlobalState(): void } /** - * @throws RiskyTestError * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws RiskyTestError */ private function restoreGlobalState(): void { @@ -2246,7 +2302,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'); @@ -2281,8 +2337,8 @@ private function createGlobalStateSnapshot(bool $backupGlobals): Snapshot } /** - * @throws RiskyTestError * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws RiskyTestError */ private function compareGlobalStateSnapshots(Snapshot $before, Snapshot $after): void { @@ -2353,11 +2409,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); } /** @@ -2381,7 +2437,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( @@ -2416,7 +2472,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 = []; @@ -2425,7 +2481,7 @@ private function cleanupIniSettings(): void private function cleanupLocaleSettings(): void { foreach ($this->locale as $category => $locale) { - \setlocale($category, $locale); + setlocale($category, $locale); } $this->locale = []; @@ -2434,7 +2490,7 @@ private function cleanupLocaleSettings(): void /** * @throws Exception */ - private function checkExceptionExpectations(\Throwable $throwable): bool + private function checkExceptionExpectations(Throwable $throwable): bool { $result = false; @@ -2446,11 +2502,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(), @@ -2480,13 +2536,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; } } @@ -2495,15 +2551,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; } @@ -2517,7 +2573,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 c4d28145cd8..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,7 +772,7 @@ 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; 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/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..906a28f6d5a 100644 --- a/src/Runner/DefaultTestResultCache.php +++ b/src/Runner/DefaultTestResultCache.php @@ -9,13 +9,29 @@ */ namespace PHPUnit\Runner; +use const DIRECTORY_SEPARATOR; +use function assert; +use function defined; +use function dirname; +use function file_get_contents; +use function file_put_contents; +use function in_array; +use function is_dir; +use function is_file; +use function is_float; +use function is_int; +use function is_string; +use function serialize; +use function sprintf; +use function unserialize; use PHPUnit\Util\ErrorHandler; use PHPUnit\Util\Filesystem; +use Serializable; /** * @internal This class is not covered by the backward compatibility promise for PHPUnit */ -final class DefaultTestResultCache implements \Serializable, TestResultCache +final class DefaultTestResultCache implements Serializable, TestResultCache { /** * @var string @@ -23,7 +39,7 @@ final class DefaultTestResultCache implements \Serializable, TestResultCache public const DEFAULT_RESULT_CACHE_FILENAME = '.phpunit.result.cache'; /** - * Provide extra protection against incomplete or corrupt caches + * Provide extra protection against incomplete or corrupt caches. * * @var int[] */ @@ -37,14 +53,14 @@ final class DefaultTestResultCache implements \Serializable, TestResultCache ]; /** - * Path and filename for result cache file + * Path and filename for result cache file. * * @var string */ private $cacheFilename; /** - * The list of defective tests + * The list of defective tests. * * * // Mark a test skipped @@ -56,7 +72,7 @@ final class DefaultTestResultCache implements \Serializable, TestResultCache private $defects = []; /** - * The list of execution duration of suites and tests (in seconds) + * The list of execution duration of suites and tests (in seconds). * * * // Record running time for test @@ -69,9 +85,9 @@ final class DefaultTestResultCache implements \Serializable, TestResultCache public function __construct(?string $filepath = null) { - if ($filepath !== null && \is_dir($filepath)) { + if ($filepath !== null && is_dir($filepath)) { // cache path provided, use default cache filename in that location - $filepath .= \DIRECTORY_SEPARATOR . self::DEFAULT_RESULT_CACHE_FILENAME; + $filepath .= DIRECTORY_SEPARATOR . self::DEFAULT_RESULT_CACHE_FILENAME; } $this->cacheFilename = $filepath ?? $_ENV['PHPUNIT_RESULT_CACHE'] ?? self::DEFAULT_RESULT_CACHE_FILENAME; @@ -90,22 +106,22 @@ public function persist(): void */ public function saveToFile(): void { - if (\defined('PHPUNIT_TESTSUITE_RESULTCACHE')) { + if (defined('PHPUNIT_TESTSUITE_RESULTCACHE')) { return; } - if (!Filesystem::createDirectory(\dirname($this->cacheFilename))) { + if (!Filesystem::createDirectory(dirname($this->cacheFilename))) { throw new Exception( - \sprintf( + sprintf( 'Cannot create directory "%s" for result cache file', $this->cacheFilename ) ); } - \file_put_contents( + file_put_contents( $this->cacheFilename, - \serialize($this) + serialize($this) ); } @@ -135,11 +151,11 @@ public function load(): void { $this->clear(); - if (!\is_file($this->cacheFilename)) { + if (!is_file($this->cacheFilename)) { return; } - $cacheData = @\file_get_contents($this->cacheFilename); + $cacheData = @file_get_contents($this->cacheFilename); // @codeCoverageIgnoreStart if ($cacheData === false) { @@ -149,7 +165,7 @@ public function load(): void $cache = ErrorHandler::invokeIgnoringWarnings( static function () use ($cacheData) { - return @\unserialize($cacheData, ['allowed_classes' => [self::class]]); + return @unserialize($cacheData, ['allowed_classes' => [self::class]]); } ); @@ -182,7 +198,7 @@ public function clear(): void public function serialize(): string { - return \serialize([ + return serialize([ 'defects' => $this->defects, 'times' => $this->times, ]); @@ -193,22 +209,22 @@ public function serialize(): string */ public function unserialize($serialized): void { - $data = \unserialize($serialized); + $data = unserialize($serialized); if (isset($data['times'])) { foreach ($data['times'] as $testName => $testTime) { - \assert(\is_string($testName)); - \assert(\is_float($testTime)); + assert(is_string($testName)); + assert(is_float($testTime)); $this->times[$testName] = $testTime; } } if (isset($data['defects'])) { foreach ($data['defects'] as $testName => $testResult) { - \assert(\is_string($testName)); - \assert(\is_int($testResult)); + assert(is_string($testName)); + assert(is_int($testResult)); - if (\in_array($testResult, self::ALLOWED_CACHE_TEST_STATUSES, true)) { + if (in_array($testResult, self::ALLOWED_CACHE_TEST_STATUSES, true)) { $this->defects[$testName] = $testResult; } } 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 ad1d0ebc436..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,9 +120,9 @@ private function setFilter(string $filter): void // Escape delimiters in regular expression. Do NOT use preg_quote, // to keep magic characters. - $filter = \sprintf( + $filter = sprintf( '/%s/i', - \str_replace( + str_replace( '/', '\\/', $filter 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 958f70b3c82..e29b3dba30a 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; @@ -51,9 +85,9 @@ final class PhptTestCase implements SelfDescribing, Test */ public function __construct(string $filename, AbstractPhpProcess $phpUtil = null) { - if (!\is_file($filename)) { + if (!is_file($filename)) { throw new Exception( - \sprintf( + sprintf( 'File "%s" does not exist.', $filename ) @@ -75,13 +109,13 @@ 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 +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'])) { @@ -169,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, @@ -239,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])) { @@ -272,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]; @@ -284,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 { @@ -296,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) { @@ -328,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), @@ -389,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; @@ -408,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']); } @@ -440,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 @@ -457,7 +491,7 @@ private function parseExternal(array &$sections): void ); } - $sections[$section] = \file_get_contents($testDirectory . $externalFilename); + $sections[$section] = file_get_contents($testDirectory . $externalFilename); } } } @@ -474,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) { @@ -502,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 @@ -517,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', @@ -536,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') && !defined('PHPUNIT_TESTSUITE')) { + $composerAutoload = var_export(PHPUNIT_COMPOSER_INSTALL, true); } $phar = '\'\''; - if (\defined('__PHPUNIT_PHAR__')) { - $phar = \var_export(__PHPUNIT_PHAR__, true); + if (defined('__PHPUNIT_PHAR__')) { + $phar = var_export(__PHPUNIT_PHAR__, true); } $globals = ''; if (!empty($GLOBALS['__PHPUNIT_BOOTSTRAP'])) { - $globals = '$GLOBALS[\'__PHPUNIT_BOOTSTRAP\'] = ' . \var_export( + $globals = '$GLOBALS[\'__PHPUNIT_BOOTSTRAP\'] = ' . var_export( $GLOBALS['__PHPUNIT_BOOTSTRAP'], true ) . ";\n"; @@ -565,7 +599,7 @@ private function renderForCoverage(string &$job): void ] ); - \file_put_contents($files['job'], $job); + file_put_contents($files['job'], $job); $job = $template->render(); } @@ -574,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 = []; @@ -587,7 +621,7 @@ private function cleanupForCoverage(): array } foreach ($files as $file) { - @\unlink($file); + @unlink($file); } return $coverage; @@ -598,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; } @@ -618,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'; @@ -630,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; @@ -653,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]; } @@ -662,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, ]]; } @@ -688,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, ], ]; @@ -705,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, ]]; } @@ -719,14 +753,14 @@ 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, ]]; } @@ -756,7 +790,7 @@ private function settings(bool $collectCoverage): array 'report_zend_debug=0', ]; - if (\extension_loaded('pcov')) { + if (extension_loaded('pcov')) { if ($collectCoverage) { $settings[] = 'pcov.enabled=1'; } else { @@ -764,8 +798,8 @@ private function settings(bool $collectCoverage): array } } - if (\extension_loaded('xdebug')) { - if (\version_compare(\phpversion('xdebug'), '3', '>=')) { + if (extension_loaded('xdebug')) { + if (version_compare(phpversion('xdebug'), '3', '>=')) { if ($collectCoverage) { $settings[] = 'xdebug.mode=coverage'; } else { 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 cff48c22658..3c71f1d4d7e 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.13', \dirname(__DIR__, 2)))->getVersion(); + self::$version = (new VersionId('8.5.13', 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 308ecee0fbc..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; @@ -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 aa42cdb04af..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 && \PHP_MAJOR_VERSION < 8 && !$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,7 +526,7 @@ public function doRun(Test $suite, array $arguments = [], array $warnings = [], } if ($codeCoverageReports > 0) { - if (\PHP_MAJOR_VERSION >= 8) { + if (PHP_MAJOR_VERSION >= 8) { $this->writeMessage('Error', 'This version of PHPUnit does not support code coverage on PHP 8'); $codeCoverageReports = 0; @@ -576,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); } @@ -605,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'); } } @@ -682,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() ) @@ -803,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); } @@ -815,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) { @@ -1036,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'] ) @@ -1054,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(), @@ -1067,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( @@ -1082,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'] ) @@ -1102,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(), @@ -1115,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( @@ -1240,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; @@ -1276,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'] ); } @@ -1305,7 +1328,7 @@ private function writeMessage(string $type, string $message): void } $this->write( - \sprintf( + sprintf( "%-15s%s\n", $type . ':', $message @@ -1337,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 ) @@ -1349,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()) ) @@ -1359,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 85838e52fc3..151c503fbb9 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,29 +408,29 @@ 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); } } @@ -414,7 +450,7 @@ public function handlePHPConfiguration(): void break; default: - $target = &$GLOBALS['_' . \strtoupper($array)]; + $target = &$GLOBALS['_' . strtoupper($array)]; break; } @@ -428,11 +464,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 +829,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 +938,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->schemaValidateSource(\file_get_contents($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 +1012,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 +1042,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 +1076,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 +1087,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 +1101,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 +1114,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 +1126,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 +1165,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 +1179,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..fcf9891bd1e 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 */ @@ -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..56c11a78b7b 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', @@ -126,7 +142,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 +150,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 +158,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 +171,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 +189,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 +200,7 @@ public function startTestSuite(TestSuite $suite): void $this->printEvent( 'testCount', - ['count' => \count($suite)] + ['count' => count($suite)] ); } @@ -196,13 +212,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 +241,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 +262,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 +306,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 +323,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 +337,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 +346,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 +359,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 +372,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 +389,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/WindowsPhpProcess.php b/src/Util/PHP/WindowsPhpProcess.php index bd19df2b8b0..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,7 @@ final class WindowsPhpProcess extends DefaultPhpProcess { public function getCommand(array $settings, string $file = null): string { - if (\PHP_MAJOR_VERSION < 8) { + if (PHP_MAJOR_VERSION < 8) { return '"' . parent::getCommand($settings, $file) . '"'; } @@ -32,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/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/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/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/loggers/_files/HookTest.php b/tests/end-to-end/loggers/_files/HookTest.php index 63280452072..caca5bcca22 100644 --- a/tests/end-to-end/loggers/_files/HookTest.php +++ b/tests/end-to-end/loggers/_files/HookTest.php @@ -9,6 +9,7 @@ */ namespace PHPUnit\Test; +use Exception; use PHPUnit\Framework\RiskyTestError; use PHPUnit\Framework\TestCase; use PHPUnit\Framework\Warning; @@ -27,7 +28,7 @@ public function testFailure(): void public function testError(): void { - throw new \Exception('message'); + throw new Exception('message'); } public function testIncomplete(): void diff --git a/tests/end-to-end/loggers/_files/raw_output_StatusTest.txt b/tests/end-to-end/loggers/_files/raw_output_StatusTest.txt index 2bd24959398..48cf232a560 100644 --- a/tests/end-to-end/loggers/_files/raw_output_StatusTest.txt +++ b/tests/end-to-end/loggers/_files/raw_output_StatusTest.txt @@ -8,7 +8,7 @@ Configuration: %stests%ebasic%econfiguration.basic.xml ┐ ├ Exception: forcing an Exception in setUpBeforeClass() │ - ╵ %stests%ebasic%eunit%eSetUpBeforeClassTest.php:31 + ╵ %stests%ebasic%eunit%eSetUpBeforeClassTest.php:32 ┴ ↩ Two  %f ms @@ -21,14 +21,14 @@ Configuration: %stests%ebasic%econfiguration.basic.xml ┐ ├ RuntimeException: throw exception in setUp │ - ╵ %stests%ebasic%eunit%eSetUpTest.php:29 + ╵ %stests%ebasic%eunit%eSetUpTest.php:30 ┴ ✘ Two with set up exception  %f ms ┐ ├ RuntimeException: throw exception in setUp │ - ╵ %stests%ebasic%eunit%eSetUpTest.php:29 + ╵ %stests%ebasic%eunit%eSetUpTest.php:30 ┴ Test result status with and without message diff --git a/tests/end-to-end/regression/GitHub/2137/Issue2137Test.php b/tests/end-to-end/regression/GitHub/2137/Issue2137Test.php index 236caac9f5e..35803de65d6 100644 --- a/tests/end-to-end/regression/GitHub/2137/Issue2137Test.php +++ b/tests/end-to-end/regression/GitHub/2137/Issue2137Test.php @@ -12,9 +12,9 @@ class Issue2137Test extends PHPUnit\Framework\TestCase /** * @dataProvider provideBrandService * - * @throws Exception * @throws \PHPUnit\Framework\ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws Exception */ public function testBrandService($provided, $expected): void { @@ -32,9 +32,9 @@ public function provideBrandService() /** * @dataProvider provideBrandService * - * @throws Exception * @throws \PHPUnit\Framework\ExpectationFailedException * @throws \SebastianBergmann\RecursionContext\InvalidArgumentException + * @throws Exception */ public function testSomethingElseInvalid($provided, $expected): void { diff --git a/tests/end-to-end/regression/GitHub/2158/Issue2158Test.php b/tests/end-to-end/regression/GitHub/2158/Issue2158Test.php index df636ee0d0a..aa547cc8505 100644 --- a/tests/end-to-end/regression/GitHub/2158/Issue2158Test.php +++ b/tests/end-to-end/regression/GitHub/2158/Issue2158Test.php @@ -12,7 +12,7 @@ class Issue2158Test extends TestCase { /** - * Set constant in main process + * Set constant in main process. */ public function testSomething(): void { @@ -22,7 +22,7 @@ public function testSomething(): void /** * Constant defined previously in main process constant should be available and - * no errors should be yielded by reload of included files + * no errors should be yielded by reload of included files. * * @runInSeparateProcess */ diff --git a/tests/end-to-end/regression/GitHub/2725/BeforeAfterClassPidTest.php b/tests/end-to-end/regression/GitHub/2725/BeforeAfterClassPidTest.php index 476461ba2e3..06faf4a204b 100644 --- a/tests/end-to-end/regression/GitHub/2725/BeforeAfterClassPidTest.php +++ b/tests/end-to-end/regression/GitHub/2725/BeforeAfterClassPidTest.php @@ -9,6 +9,7 @@ */ namespace Issue2725; +use function getmypid; use PHPUnit\Framework\TestCase; /** @@ -23,7 +24,7 @@ class BeforeAfterClassPidTest extends TestCase */ public static function showPidBefore(): void { - $GLOBALS[static::PID_VARIABLE] = \getmypid(); + $GLOBALS[static::PID_VARIABLE] = getmypid(); } /** @@ -31,7 +32,7 @@ public static function showPidBefore(): void */ public static function showPidAfter(): void { - if ($GLOBALS[static::PID_VARIABLE] - \getmypid() !== 0) { + if ($GLOBALS[static::PID_VARIABLE] - getmypid() !== 0) { print "\n@afterClass output - PID difference should be zero!"; } @@ -40,11 +41,11 @@ public static function showPidAfter(): void public function testMethod1WithItsBeforeAndAfter(): void { - $this->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/3093/Issue3093Test.php b/tests/end-to-end/regression/GitHub/3093/Issue3093Test.php index ea850df38f6..a9f84b8f2bf 100644 --- a/tests/end-to-end/regression/GitHub/3093/Issue3093Test.php +++ b/tests/end-to-end/regression/GitHub/3093/Issue3093Test.php @@ -16,7 +16,7 @@ public function someDataProvider(): array public function testFirstWithoutDependencies(): void { - self::assertTrue(true); + $this->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/3739/Issue3739Test.php b/tests/end-to-end/regression/GitHub/3739/Issue3739Test.php index 5390b5889cc..13b68f0f068 100644 --- a/tests/end-to-end/regression/GitHub/3739/Issue3739Test.php +++ b/tests/end-to-end/regression/GitHub/3739/Issue3739Test.php @@ -9,18 +9,19 @@ */ namespace Issue3739; +use function unlink; use PHPUnit\Framework\TestCase; class Issue3739 { public function unlinkFileThatDoesNotExistWithErrorSuppression(): bool { - return @\unlink(__DIR__ . '/DOES_NOT_EXIST'); + return @unlink(__DIR__ . '/DOES_NOT_EXIST'); } public function unlinkFileThatDoesNotExistWithoutErrorSuppression(): bool { - return \unlink(__DIR__ . '/DOES_NOT_EXIST'); + return unlink(__DIR__ . '/DOES_NOT_EXIST'); } } 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 0f5fb3b5fb3..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 6dd19319fb9..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 @@ -131,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()); } @@ -145,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); @@ -157,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' @@ -180,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/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..2518c57f584 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; } )); @@ -1029,7 +1029,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/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/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/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..129fba172ff 100644 --- a/tests/unit/Util/TestClassTest.php +++ b/tests/unit/Util/TestClassTest.php @@ -9,12 +9,28 @@ */ namespace PHPUnit\Util; +use function array_merge; +use function get_class; +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 +46,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 +490,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 +632,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 +645,7 @@ public function requirementsWithInvalidVersionConstraintsThrowsExceptionProvider public function testGetRequirementsMergesClassAndMethodDocBlocks(): void { - $reflector = new \ReflectionClass(\RequirementsClassDocBlockTest::class); + $reflector = new ReflectionClass(RequirementsClassDocBlockTest::class); $file = $reflector->getFileName(); $expectedAnnotations = [ @@ -658,7 +674,7 @@ public function testGetRequirementsMergesClassAndMethodDocBlocks(): void $this->assertEquals( $expectedAnnotations, - Test::getRequirements(\RequirementsClassDocBlockTest::class, 'testMethod') + Test::getRequirements(RequirementsClassDocBlockTest::class, 'testMethod') ); } @@ -666,15 +682,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 +861,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 +887,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 +908,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 +929,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 +947,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 +965,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 +983,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 +1000,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 +1020,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 +1035,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 +1045,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 +1055,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 +1065,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 +1075,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 +1085,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 +1095,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 +1108,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 +1126,7 @@ public function testParseAnnotation(): void { $this->assertEquals( ['Foo', 'ほげ'], - Test::getDependencies(\get_class($this), 'methodForTestParseAnnotation') + Test::getDependencies(get_class($this), 'methodForTestParseAnnotation') ); } @@ -1128,7 +1144,7 @@ public function testParseAnnotationThatIsOnlyOneLine(): void { $this->assertEquals( ['Bar'], - Test::getDependencies(\get_class($this), 'methodForTestParseAnnotationThatIsOnlyOneLine') + Test::getDependencies(get_class($this), 'methodForTestParseAnnotationThatIsOnlyOneLine') ); } @@ -1141,13 +1157,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 +1248,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 +1259,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 +1270,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 +1281,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 +1293,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 +1311,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 +1407,7 @@ public function getLinesToBeCoveredProvider(): array ], [ 'CoverageCoversOverridesCoversNothingTest', - \range(29, 33), + range(29, 33), ], [ 'CoverageMethodNothingCoversMethod', @@ -1402,7 +1418,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 +1430,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 +1467,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);