From 398d858384803e4ad00a3084bd406bafbfe58a61 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 20:56:38 +0000 Subject: [PATCH] Run PHPStan on the tests directory and fix reported issues Add `tests` to the PHPStan paths (level 9 unchanged) and scan the wp-cli-tests TestCase so PHPStan knows the base class and its polyfills. Fix the 169 errors this reports in the test code: - add `void` return types to test methods and helpers - document parameters, properties and data provider return types with precise array types and shapes - reference `cli\table\Ascii` / `cli\table\Tabular` with their declared lowercase namespace - assert that fopen()/file_get_contents() succeeded before use - use assertCount() instead of assertSame() on count() - pass values that match the documented types (strings instead of ints in table rows, a valid int type for an invalid alignment, `false` instead of `null` to reset Colors) - test null cell values through the renderer and the Table constructor, which both accept mixed values, instead of through addRow() - avoid PHPStan remembering Colors::colorize() results across Colors::disable() by asserting on local variables - only restore mb_detect_order() with a non-empty list Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UWTd5n3ZupvgHr4fEBJCGp --- phpstan.neon.dist | 2 + tests/Test_Arguments.php | 81 +++++++++++--------- tests/Test_Cli.php | 68 +++++++++-------- tests/Test_Colors.php | 10 ++- tests/Test_Shell.php | 2 +- tests/Test_Table.php | 150 ++++++++++++++++++++----------------- tests/Test_Table_Ascii.php | 51 +++++++------ tests/bootstrap.php | 6 +- 8 files changed, 203 insertions(+), 167 deletions(-) diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 4611d49f..7e769d2a 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -2,8 +2,10 @@ parameters: level: 9 paths: - lib + - tests scanDirectories: - vendor/wp-cli/wp-cli/php scanFiles: - vendor/php-stubs/wordpress-stubs/wordpress-stubs.php + - vendor/wp-cli/wp-cli-tests/tests/includes/TestCase.php treatPhpDocTypesAsCertain: false diff --git a/tests/Test_Arguments.php b/tests/Test_Arguments.php index 33ff7281..ee97ef95 100644 --- a/tests/Test_Arguments.php +++ b/tests/Test_Arguments.php @@ -13,26 +13,26 @@ class Test_Arguments extends TestCase { /** * Array of expected settings - * @var array + * @var array */ - protected $settings = null; + protected $settings = array(); /** * Array of flags - * @var array + * @var array> */ - protected $flags = null; + protected $flags = array(); /** * Array of expected options - * @var array + * @var array> */ - protected $options = null; + protected $options = array(); /** * Clear the $_SERVER['argv'] array */ - public static function clearArgv() + public static function clearArgv(): void { $_SERVER['argv'] = array(); $_SERVER['argc'] = 0; @@ -41,25 +41,27 @@ public static function clearArgv() /** * Add one or more element(s) at the end of the $_SERVER['argv'] array * - * @param array $args: value(s) to add to the argv array + * @param string|array $args value(s) to add to the argv array */ - public static function pushToArgv($args) + public static function pushToArgv($args): void { if (is_string($args)) { $args = explode(' ', $args); } + $argv = is_array($_SERVER['argv']) ? $_SERVER['argv'] : array(); foreach ($args as $arg) { - array_push($_SERVER['argv'], $arg); + $argv[] = $arg; } - $_SERVER['argc'] += count($args); + $_SERVER['argv'] = $argv; + $_SERVER['argc'] = count($argv); } /** * Set up valid flags and options */ - public function set_up() + public function set_up(): void { self::clearArgv(); self::pushToArgv('my_script.php'); @@ -103,11 +105,11 @@ static function ( $errno, $errstr ) { /** * Tear down fixtures */ - public function tear_down() + public function tear_down(): void { - $this->flags = null; - $this->options = null; - $this->settings = null; + $this->flags = array(); + $this->options = array(); + $this->settings = array(); self::clearArgv(); restore_error_handler(); } @@ -115,7 +117,7 @@ public function tear_down() /** * Test adding a flag, getting a flag and getting all flags */ - public function testAddFlags() + public function testAddFlags(): void { $args = new cli\Arguments($this->settings); @@ -138,7 +140,7 @@ public function testAddFlags() /** * Test adding a option, getting a option and getting all options */ - public function testAddOptions() + public function testAddOptions(): void { $args = new cli\Arguments($this->settings); @@ -157,7 +159,7 @@ public function testAddOptions() /** * Data provider with valid args and options * - * @return array set of args and expected parsed values + * @return array, array}> set of args and expected parsed values */ public static function settingsWithValidOptions() { @@ -180,7 +182,7 @@ public static function settingsWithValidOptions() /** * Data provider with missing options * - * @return array set of args and expected parsed values + * @return array, array}> set of args and expected parsed values */ public static function settingsWithMissingOptions() { @@ -199,7 +201,7 @@ public static function settingsWithMissingOptions() /** * Data provider with missing options. The default value should be populated * - * @return array set of args and expected parsed values + * @return array, array}> set of args and expected parsed values */ public static function settingsWithMissingOptionsWithDefault() { @@ -215,6 +217,11 @@ public static function settingsWithMissingOptionsWithDefault() ); } + /** + * Data provider with no options. The default values should be populated + * + * @return array, array}> set of args and expected parsed values + */ public static function settingsWithNoOptionsWithDefault() { return array( @@ -228,10 +235,10 @@ public static function settingsWithNoOptionsWithDefault() /** * Generic private testParse method. * - * @param array $args arguments as they appear in the cli - * @param array $expectedValues expected values after parsing + * @param array $cliParams arguments as they appear in the cli + * @param array $expectedValues expected values after parsing */ - private function _testParse($cliParams, $expectedValues) + private function _testParse($cliParams, $expectedValues): void { self::pushToArgv($cliParams); @@ -250,24 +257,24 @@ private function _testParse($cliParams, $expectedValues) } /** - * @param array $args arguments as they appear in the cli - * @param array $expectedValues expected values after parsing + * @param array $cliParams arguments as they appear in the cli + * @param array $expectedValues expected values after parsing * * @dataProvider settingsWithValidOptions */ #[DataProvider( 'settingsWithValidOptions' )] // phpcs:ignore PHPCompatibility.Attributes.NewAttributes.PHPUnitAttributeFound - public function testParseWithValidOptions($cliParams, $expectedValues) + public function testParseWithValidOptions($cliParams, $expectedValues): void { $this->_testParse($cliParams, $expectedValues); } /** - * @param array $args arguments as they appear in the cli - * @param array $expectedValues expected values after parsing + * @param array $cliParams arguments as they appear in the cli + * @param array $expectedValues expected values after parsing * @dataProvider settingsWithMissingOptions */ #[DataProvider( 'settingsWithMissingOptions' )] // phpcs:ignore PHPCompatibility.Attributes.NewAttributes.PHPUnitAttributeFound - public function testParseWithMissingOptions($cliParams, $expectedValues) + public function testParseWithMissingOptions($cliParams, $expectedValues): void { $this->expectException(\Exception::class); $this->expectExceptionMessage('no value given for --option1'); @@ -275,27 +282,27 @@ public function testParseWithMissingOptions($cliParams, $expectedValues) } /** - * @param array $args arguments as they appear in the cli - * @param array $expectedValues expected values after parsing + * @param array $cliParams arguments as they appear in the cli + * @param array $expectedValues expected values after parsing * @dataProvider settingsWithMissingOptionsWithDefault */ #[DataProvider( 'settingsWithMissingOptionsWithDefault' )] // phpcs:ignore PHPCompatibility.Attributes.NewAttributes.PHPUnitAttributeFound - public function testParseWithMissingOptionsWithDefault($cliParams, $expectedValues) + public function testParseWithMissingOptionsWithDefault($cliParams, $expectedValues): void { $this->_testParse($cliParams, $expectedValues); } /** - * @param array $args arguments as they appear in the cli - * @param array $expectedValues expected values after parsing + * @param array $cliParams arguments as they appear in the cli + * @param array $expectedValues expected values after parsing * @dataProvider settingsWithNoOptionsWithDefault */ #[DataProvider( 'settingsWithNoOptionsWithDefault' )] // phpcs:ignore PHPCompatibility.Attributes.NewAttributes.PHPUnitAttributeFound - public function testParseWithNoOptionsWithDefault($cliParams, $expectedValues) { + public function testParseWithNoOptionsWithDefault($cliParams, $expectedValues): void { $this->_testParse($cliParams, $expectedValues); } - public function testHelpScreenRender() { + public function testHelpScreenRender(): void { $args = new \cli\Arguments( $this->settings ); $help = $args->getHelpScreen(); diff --git a/tests/Test_Cli.php b/tests/Test_Cli.php index bd4476d8..d92aa8b2 100644 --- a/tests/Test_Cli.php +++ b/tests/Test_Cli.php @@ -5,25 +5,25 @@ class Test_Cli extends TestCase { - function set_up() { - // Reset enable state - \cli\Colors::enable( null ); + function set_up(): void { + // Reset enable state (anything other than `true` resets it to auto-detection). + \cli\Colors::enable( false ); // Empty the cache \cli\Colors::clearStringCache(); } - function test_string_length() { + function test_string_length(): void { $this->assertEquals( \cli\Colors::length( 'x' ), 1 ); $this->assertEquals( \cli\Colors::length( '日' ), 1 ); } - function test_string_width() { + function test_string_width(): void { $this->assertEquals( \cli\Colors::width( 'x' ), 1 ); $this->assertEquals( \cli\Colors::width( '日' ), 2 ); // Double-width char. } - function test_encoded_string_length() { + function test_encoded_string_length(): void { $this->assertEquals( \cli\Colors::length( 'hello' ), 5 ); $this->assertEquals( \cli\Colors::length( 'óra' ), 3 ); @@ -31,7 +31,7 @@ function test_encoded_string_length() { } - function test_encoded_string_width() { + function test_encoded_string_width(): void { $this->assertEquals( \cli\Colors::width( 'hello' ), 5 ); $this->assertEquals( \cli\Colors::width( 'óra' ), 3 ); @@ -39,7 +39,7 @@ function test_encoded_string_width() { } - function test_encoded_string_pad() { + function test_encoded_string_pad(): void { $this->assertEquals( 6, strlen( \cli\Colors::pad( 'hello', 6 ) ) ); $this->assertEquals( 7, strlen( \cli\Colors::pad( 'óra', 6 ) ) ); // special characters take one byte @@ -56,7 +56,7 @@ function test_encoded_string_pad() { $this->assertSame( 3, strpos( \cli\Colors::pad( 'hello', 10, false, false, STR_PAD_BOTH ), 'e' ) ); } - function test_colorized_string_pad() { + function test_colorized_string_pad(): void { // Colors enabled. Colors::enable( true ); @@ -84,7 +84,7 @@ function test_colorized_string_pad() { $this->assertSame( 32, strlen( Colors::pad( $ora, 20, true /*pre_colorized*/ ) ) ); } - function test_encoded_substr() { + function test_encoded_substr(): void { $this->assertEquals( \cli\safe_substr( \cli\Colors::pad( 'hello', 6), 0, 2 ), 'he' ); $this->assertEquals( \cli\safe_substr( \cli\Colors::pad( 'óra', 6), 0, 2 ), 'ór' ); @@ -102,7 +102,7 @@ function test_encoded_substr() { $this->assertSame( '語 ', \cli\safe_substr( Colors::pad( '日本語', 8 ), -3, 3 ) ); } - function test_various_substr() { + function test_various_substr(): void { // Save. $test_safe_substr = getenv( 'PHP_CLI_TOOLS_TEST_SAFE_SUBSTR' ); if ( function_exists( 'mb_detect_order' ) ) { @@ -218,12 +218,12 @@ function test_various_substr() { // Restore. putenv( false == $test_safe_substr ? 'PHP_CLI_TOOLS_TEST_SAFE_SUBSTR' : "PHP_CLI_TOOLS_TEST_SAFE_SUBSTR=$test_safe_substr" ); - if ( function_exists( 'mb_detect_order' ) ) { + if ( function_exists( 'mb_detect_order' ) && array() !== $mb_detect_order ) { mb_detect_order( $mb_detect_order ); } } - function test_is_width_encoded_substr() { + function test_is_width_encoded_substr(): void { $this->assertSame( 'he', \cli\safe_substr( Colors::pad( 'hello', 6 ), 0, 2, true /*is_width*/ ) ); $this->assertSame( 'ór', \cli\safe_substr( Colors::pad( 'óra', 6 ), 0, 2, true /*is_width*/ ) ); @@ -271,12 +271,12 @@ function test_is_width_encoded_substr() { $this->assertSame( '本語9', \cli\safe_substr( '1日4本語90', -4, 5, true /*is_width*/ ) ); } - function test_colorized_string_length() { + function test_colorized_string_length(): void { $this->assertEquals( \cli\Colors::length( \cli\Colors::colorize( '%Gx%n', true ) ), 1 ); $this->assertEquals( \cli\Colors::length( \cli\Colors::colorize( '%G日%n', true ) ), 1 ); } - function test_colorized_string_width() { + function test_colorized_string_width(): void { // Colors enabled. Colors::enable( true ); @@ -304,20 +304,20 @@ function test_colorized_string_width() { $this->assertSame( 2, Colors::width( $dw, true /*pre_colorized*/ ) ); } - function test_colorize_string_is_colored() { + function test_colorize_string_is_colored(): void { $original = '%Gx'; $colorized = "\033[32;1mx"; $this->assertEquals( \cli\Colors::colorize( $original, true ), $colorized ); } - function test_colorize_when_colorize_is_forced() { + function test_colorize_when_colorize_is_forced(): void { $original = '%gx%n'; $this->assertEquals( \cli\Colors::colorize( $original, false ), 'x' ); } - function test_binary_string_is_converted_back_to_original_string() { + function test_binary_string_is_converted_back_to_original_string(): void { $string = 'x'; $string_with_color = '%b' . $string; $colorized_string = "\033[34m$string"; @@ -329,7 +329,7 @@ function test_binary_string_is_converted_back_to_original_string() { $this->assertEquals( \cli\Colors::decolorize( $colorized_string ), $string ); } - function test_string_cache() { + function test_string_cache(): void { $string = 'x'; $string_with_color = '%k' . $string; $colorized_string = "\033[30m$string"; @@ -353,7 +353,7 @@ function test_string_cache() { $this->assertEquals( $test_cache, $real_cache[ md5( $string_with_color ) ] ); } - function test_string_cache_colorize() { + function test_string_cache_colorize(): void { $string = 'x'; $string_with_color = '%k' . $string; $colorized_string = "\033[30m$string"; @@ -362,16 +362,20 @@ function test_string_cache_colorize() { Colors::enable( true ); // Ensure colorization works - $this->assertSame( $colorized_string, Colors::colorize( $string_with_color ) ); - $this->assertSame( $colorized_string, Colors::colorize( $string_with_color ) ); + $colorized = Colors::colorize( $string_with_color ); + $this->assertSame( $colorized_string, $colorized ); + $cached = Colors::colorize( $string_with_color ); + $this->assertSame( $colorized_string, $cached ); // Colors disabled. Colors::disable( true ); $this->assertFalse( Colors::shouldColorize() ); // Ensure it doesn't come from the cache. - $this->assertSame( $string, Colors::colorize( $string_with_color ) ); - $this->assertSame( $string, Colors::colorize( $string_with_color ) ); + $decolorized = Colors::colorize( $string_with_color ); + $this->assertSame( $string, $decolorized ); + $cached = Colors::colorize( $string_with_color ); + $this->assertSame( $string, $cached ); // Check that escaped % isn't stripped on putting into cache. $string = 'x%%n'; @@ -380,7 +384,7 @@ function test_string_cache_colorize() { $this->assertSame( 'x%n', Colors::colorize( $string_with_color ) ); } - function test_decolorize() { + function test_decolorize(): void { // Colors enabled. Colors::enable( true ); @@ -405,7 +409,7 @@ function test_decolorize() { $this->assertSame( $both_string, Colors::decolorize( $both_string, 3 /*noop*/ ) ); } - function test_strwidth() { + function test_strwidth(): void { // Save. $test_strwidth = getenv( 'PHP_CLI_TOOLS_TEST_STRWIDTH' ); if ( function_exists( 'mb_detect_order' ) ) { @@ -483,7 +487,7 @@ function test_strwidth() { $this->assertSame( 15, mb_strwidth( $str, 'SJIS' ) ); putenv( 'PHP_CLI_TOOLS_TEST_STRWIDTH=8' ); // Test safe_strlen(). - if ( function_exists( 'mb_strlen' ) && function_exists( 'mb_detect_order' ) ) { + if ( function_exists( 'mb_strlen' ) ) { $this->assertSame( 8, \cli\strwidth( $str ) ); // mb_strlen() - doesn't allow for double-width. $this->assertSame( 8, mb_strlen( $str, 'SJIS' ) ); } else { @@ -494,12 +498,12 @@ function test_strwidth() { // Restore. putenv( false == $test_strwidth ? 'PHP_CLI_TOOLS_TEST_STRWIDTH' : "PHP_CLI_TOOLS_TEST_STRWIDTH=$test_strwidth" ); - if ( function_exists( 'mb_detect_order' ) ) { + if ( function_exists( 'mb_detect_order' ) && array() !== $mb_detect_order ) { mb_detect_order( $mb_detect_order ); } } - function test_safe_strlen() { + function test_safe_strlen(): void { // Save. $test_safe_strlen = getenv( 'PHP_CLI_TOOLS_TEST_SAFE_STRLEN' ); if ( function_exists( 'mb_detect_order' ) ) { @@ -549,12 +553,12 @@ function test_safe_strlen() { // Restore. putenv( false == $test_safe_strlen ? 'PHP_CLI_TOOLS_TEST_SAFE_STRLEN' : "PHP_CLI_TOOLS_TEST_SAFE_STRLEN=$test_safe_strlen" ); - if ( function_exists( 'mb_detect_order' ) ) { + if ( function_exists( 'mb_detect_order' ) && array() !== $mb_detect_order ) { mb_detect_order( $mb_detect_order ); } } - function test_render_with_color_tokens_and_sprintf_args_colors_disabled() { + function test_render_with_color_tokens_and_sprintf_args_colors_disabled(): void { Colors::disable( true ); // Color tokens in format string must not cause "sprintf(): Too few arguments". @@ -562,7 +566,7 @@ function test_render_with_color_tokens_and_sprintf_args_colors_disabled() { $this->assertSame( '[2024-01-01 12:00:00] Starting!', $result ); } - function test_render_with_color_tokens_and_sprintf_args_colors_enabled() { + function test_render_with_color_tokens_and_sprintf_args_colors_enabled(): void { Colors::enable( true ); $result = \cli\render( '[%C%k%s%N] Starting!', '2024-01-01 12:00:00' ); diff --git a/tests/Test_Colors.php b/tests/Test_Colors.php index b7d28ff9..a7a122d8 100644 --- a/tests/Test_Colors.php +++ b/tests/Test_Colors.php @@ -7,10 +7,13 @@ class Test_Colors extends TestCase { /** - * @dataProvider dataColors + * @dataProvider dataColors + * + * @param string $str Color token, e.g. `%k`. + * @param array $color Color definition for the token. */ #[DataProvider( 'dataColors' )] // phpcs:ignore PHPCompatibility.Attributes.NewAttributes.PHPUnitAttributeFound - public function testColors( $str, $color ) { + public function testColors( $str, $color ): void { // Colors enabled. Colors::enable( true ); @@ -23,6 +26,9 @@ public function testColors( $str, $color ) { } } + /** + * @return array}> + */ public static function dataColors() { $ret = array(); foreach ( Colors::getColors() as $str => $color ) { diff --git a/tests/Test_Shell.php b/tests/Test_Shell.php index f7930279..299ee4d5 100644 --- a/tests/Test_Shell.php +++ b/tests/Test_Shell.php @@ -11,7 +11,7 @@ class Test_Shell extends TestCase { /** * Test getting TERM columns. */ - function testColumns() { + function testColumns(): void { // Save. $env_term = getenv( 'TERM' ); $env_columns = getenv( 'COLUMNS' ); diff --git a/tests/Test_Table.php b/tests/Test_Table.php index 5b6db372..c73647f2 100644 --- a/tests/Test_Table.php +++ b/tests/Test_Table.php @@ -2,7 +2,7 @@ use cli\Colors; use cli\Table; -use cli\Table\Ascii; +use cli\table\Ascii; use cli\Shell; use WP_CLI\Tests\TestCase; @@ -11,12 +11,12 @@ */ class Test_Table extends TestCase { - public function test_column_value_too_long_ascii() { + public function test_column_value_too_long_ascii(): void { $constraint_width = 80; $table = new cli\Table; - $renderer = new cli\Table\Ascii; + $renderer = new cli\table\Ascii; $renderer->setConstraintWidth( $constraint_width ); $table->setRenderer( $renderer ); $table->setHeaders( array( 'Field', 'Value' ) ); @@ -40,7 +40,7 @@ public function test_column_value_too_long_ascii() { $constraint_width = 81; - $renderer = new cli\Table\Ascii; + $renderer = new cli\table\Ascii; $renderer->setConstraintWidth( $constraint_width ); $table->setRenderer( $renderer ); @@ -50,9 +50,9 @@ public function test_column_value_too_long_ascii() { } } - public function test_display_lines_keep_row_order_with_many_rows() { + public function test_display_lines_keep_row_order_with_many_rows(): void { $table = new cli\Table(); - $renderer = new cli\Table\Ascii(); + $renderer = new cli\table\Ascii(); $renderer->setConstraintWidth( 80 ); $table->setRenderer( $renderer ); $table->setHeaders( array( 'ID', 'Value' ) ); @@ -76,12 +76,12 @@ public function test_display_lines_keep_row_order_with_many_rows() { $this->assertSame( $out[0], $out[ count( $out ) - 1 ] ); } - public function test_column_value_too_long_with_multibytes() { + public function test_column_value_too_long_with_multibytes(): void { $constraint_width = 80; $table = new cli\Table; - $renderer = new cli\Table\Ascii; + $renderer = new cli\table\Ascii; $renderer->setConstraintWidth( $constraint_width ); $table->setRenderer( $renderer ); $table->setHeaders( array( 'Field', 'Value' ) ); @@ -95,7 +95,7 @@ public function test_column_value_too_long_with_multibytes() { $constraint_width = 81; - $renderer = new cli\Table\Ascii; + $renderer = new cli\table\Ascii; $renderer->setConstraintWidth( $constraint_width ); $table->setRenderer( $renderer ); @@ -105,10 +105,10 @@ public function test_column_value_too_long_with_multibytes() { } } - public function test_column_odd_single_width_with_double_width() { + public function test_column_odd_single_width_with_double_width(): void { $dummy = new cli\Table; - $renderer = new cli\Table\Ascii; + $renderer = new cli\table\Ascii; $strip_borders = function ( $a ) { return array_map( function ( $v ) { @@ -122,7 +122,7 @@ public function test_column_odd_single_width_with_double_width() { $out = $renderer->row( array( '1あいうえおか2きくカけこ' ) ); $result = $strip_borders( explode( "\n", $out ) ); - $this->assertSame( 3, count( $result ) ); + $this->assertCount( 3, $result ); $this->assertSame( '1あいうえ ', $result[0] ); // 1 single-width, 4 double-width, space = 10. $this->assertSame( 'おか2きくカ', $result[1] ); // 2 double-width, 1 single-width, 2 double-width, 1 half-width = 10. $this->assertSame( 'けこ ', $result[2] ); // 2 double-width, 8 spaces = 10. @@ -134,7 +134,7 @@ public function test_column_odd_single_width_with_double_width() { $out = $renderer->row( array( '1あいうえおか2きくカけこ' ) ); $result = $strip_borders( explode( "\n", $out ) ); - $this->assertSame( 13, count( $result ) ); + $this->assertCount( 13, $result ); // Uneven rows. $this->assertSame( '1', $result[0] ); $this->assertSame( 'あ', $result[1] ); @@ -146,20 +146,20 @@ public function test_column_odd_single_width_with_double_width() { $out = $renderer->row( array( '1あいうえおか2きくカけこ' ) ); $result = $strip_borders( explode( "\n", $out ) ); - $this->assertSame( 1, count( $result ) ); + $this->assertCount( 1, $result ); } - public function test_column_fullwidth_and_combining() { + public function test_column_fullwidth_and_combining(): void { $constraint_width = 80; $table = new cli\Table; - $renderer = new cli\Table\Ascii; + $renderer = new cli\table\Ascii; $renderer->setConstraintWidth( $constraint_width ); $table->setRenderer( $renderer ); $table->setHeaders( array( 'Field', 'Value' ) ); - $table->addRow( array( 'ID', 2151 ) ); - $table->addRow( array( 'post_author', 1 ) ); + $table->addRow( array( 'ID', '2151' ) ); + $table->addRow( array( 'post_author', '1' ) ); $table->addRow( array( 'post_title', 'only-english-lorem-ipsum-dolor-sit-amet-consectetur-adipisicing-elit-sed-do-eiusmod-tempor-incididunt-ut-labore' ) ); $table->addRow( array( 'post_content', //'ให้รู้จัก ให้หาหนทางใหม่' . @@ -183,7 +183,7 @@ public function test_column_fullwidth_and_combining() { $constraint_width = 81; - $renderer = new cli\Table\Ascii; + $renderer = new cli\table\Ascii; $renderer->setConstraintWidth( $constraint_width ); $table->setRenderer( $renderer ); @@ -194,7 +194,7 @@ public function test_column_fullwidth_and_combining() { $constraint_width = 200; - $renderer = new cli\Table\Ascii; + $renderer = new cli\table\Ascii; $renderer->setConstraintWidth( $constraint_width ); $table->setRenderer( $renderer ); @@ -204,7 +204,7 @@ public function test_column_fullwidth_and_combining() { } } - public function test_ascii_pre_colorized_widths() { + public function test_ascii_pre_colorized_widths(): void { Colors::enable( true ); @@ -232,7 +232,7 @@ public function test_ascii_pre_colorized_widths() { $out = $table->getDisplayLines(); // "+ 4" accommodates 3 borders and header. - $this->assertSame( 4 + 4, count( $out ) ); + $this->assertCount( 4 + 4, $out ); // Borders & header. $this->assertSame( 42, strlen( $out[0] ) ); @@ -257,7 +257,7 @@ public function test_ascii_pre_colorized_widths() { $out = $table->getDisplayLines(); // "+ 4" accommodates 3 borders and header. - $this->assertSame( 4 + 4, count( $out ) ); + $this->assertCount( 4 + 4, $out ); // Borders & header. $this->assertSame( 56, strlen( $out[0] ) ); @@ -272,9 +272,9 @@ public function test_ascii_pre_colorized_widths() { $this->assertSame( 56, strlen( $out[6] ) ); } - public function test_preserve_trailing_tabs() { + public function test_preserve_trailing_tabs(): void { $table = new cli\Table(); - $renderer = new cli\Table\Tabular(); + $renderer = new cli\table\Tabular(); $table->setRenderer( $renderer ); $table->setHeaders( array( 'Field', 'Type', 'Null', 'Key', 'Default', 'Extra' ) ); @@ -294,18 +294,23 @@ public function test_preserve_trailing_tabs() { $this->assertSame( $expected, $out, 'Trailing tabs should be preserved in table output.' ); } - public function test_null_values_are_handled() { - $table = new cli\Table(); - $renderer = new cli\Table\Tabular(); - $table->setRenderer( $renderer ); - - $table->setHeaders( array( 'Field', 'Type', 'Null', 'Key', 'Default', 'Extra' ) ); + public function test_null_values_are_handled(): void { + $headers = array( 'Field', 'Type', 'Null', 'Key', 'Default', 'Extra' ); + $rows = array( + // Row with a null value in the middle + array( 'id', 'int', 'NO', 'PRI', null, 'auto_increment' ), + // Row with a null value at the end + array( 'name', 'varchar(255)', 'YES', '', 'NULL', null ), + ); - // Add row with a null value in the middle - $table->addRow( array( 'id', 'int', 'NO', 'PRI', null, 'auto_increment' ) ); + // The renderer itself must cope with null values. + $renderer = new cli\table\Tabular(); + $this->assertSame( "id\tint\tNO\tPRI\t\tauto_increment", $renderer->row( $rows[0] ) ); + $this->assertSame( "name\tvarchar(255)\tYES\t\tNULL\t", $renderer->row( $rows[1] ) ); - // Add row with a null value at the end - $table->addRow( array( 'name', 'varchar(255)', 'YES', '', 'NULL', null ) ); + // And so must a table built from rows containing null values. + $table = new cli\Table( $headers, $rows ); + $table->setRenderer( $renderer ); $out = $table->getDisplayLines(); @@ -317,9 +322,9 @@ public function test_null_values_are_handled() { $this->assertSame( $expected, $out, 'Null values should be safely converted to empty strings in table output.' ); } - public function test_default_alignment() { + public function test_default_alignment(): void { $table = new cli\Table(); - $table->setRenderer( new cli\Table\Ascii() ); + $table->setRenderer( new cli\table\Ascii() ); $table->setHeaders( array( 'Header1', 'Header2' ) ); $table->addRow( array( 'Row1Col1', 'Row1Col2' ) ); @@ -330,9 +335,9 @@ public function test_default_alignment() { $this->assertStringContainsString( '| Row1Col1 | Row1Col2 |', $out[3] ); } - public function test_right_alignment() { + public function test_right_alignment(): void { $table = new cli\Table(); - $table->setRenderer( new cli\Table\Ascii() ); + $table->setRenderer( new cli\table\Ascii() ); $table->setHeaders( array( 'Name', 'Size' ) ); $table->setAlignments( array( 'Name' => \cli\table\Column::ALIGN_RIGHT, 'Size' => \cli\table\Column::ALIGN_RIGHT ) ); $table->addRow( array( 'file.txt', '1024 B' ) ); @@ -345,9 +350,9 @@ public function test_right_alignment() { $this->assertStringContainsString( '| file.txt | 1024 B |', $out[3] ); } - public function test_center_alignment() { + public function test_center_alignment(): void { $table = new cli\Table(); - $table->setRenderer( new cli\Table\Ascii() ); + $table->setRenderer( new cli\table\Ascii() ); $table->setHeaders( array( 'A', 'B' ) ); $table->setAlignments( array( 'A' => \cli\table\Column::ALIGN_CENTER, 'B' => \cli\table\Column::ALIGN_CENTER ) ); $table->addRow( array( 'test', 'data' ) ); @@ -360,9 +365,9 @@ public function test_center_alignment() { $this->assertStringContainsString( '| test | data |', $out[3] ); } - public function test_mixed_alignments() { + public function test_mixed_alignments(): void { $table = new cli\Table(); - $table->setRenderer( new cli\Table\Ascii() ); + $table->setRenderer( new cli\table\Ascii() ); $table->setHeaders( array( 'Name', 'Count', 'Status' ) ); $table->setAlignments( array( 'Name' => \cli\table\Column::ALIGN_LEFT, @@ -379,24 +384,24 @@ public function test_mixed_alignments() { $this->assertStringContainsString( '| Item | 42 | OK |', $out[3] ); } - public function test_invalid_alignment_value() { + public function test_invalid_alignment_value(): void { $this->expectException( \InvalidArgumentException::class ); $table = new cli\Table(); $table->setHeaders( array( 'Header1' ) ); - $table->setAlignments( array( 'Header1' => 'invalid-alignment' ) ); + $table->setAlignments( array( 'Header1' => 99 ) ); } - public function test_invalid_alignment_column() { + public function test_invalid_alignment_column(): void { $this->expectException( \InvalidArgumentException::class ); $table = new cli\Table(); $table->setHeaders( array( 'Header1' ) ); $table->setAlignments( array( 'NonExistent' => \cli\table\Column::ALIGN_LEFT ) ); } - public function test_alignment_before_headers() { + public function test_alignment_before_headers(): void { // Test that alignments can be set before headers without throwing an error $table = new cli\Table(); - $table->setRenderer( new cli\Table\Ascii() ); + $table->setRenderer( new cli\table\Ascii() ); $table->setAlignments( array( 'Name' => \cli\table\Column::ALIGN_RIGHT ) ); $table->setHeaders( array( 'Name' ) ); $table->addRow( array( 'LongName' ) ); @@ -408,7 +413,7 @@ public function test_alignment_before_headers() { $this->assertStringContainsString( '| LongName |', $out[3] ); } - public function test_resetRows() { + public function test_resetRows(): void { $table = new cli\Table(); $table->setHeaders( array( 'Name', 'Age' ) ); $table->addRow( array( 'Alice', '30' ) ); @@ -425,14 +430,14 @@ public function test_resetRows() { $this->assertGreaterThan( 0, count( $out ) ); } - public function test_shortcut_constructor_tabular() { + public function test_shortcut_constructor_tabular(): void { $headers = array( array( 'Name' => 'Alice', 'Age' => '30' ), array( 'Name' => 'Bob', 'Age' => '25' ), ); $table = new cli\Table( $headers ); - $table->setRenderer( new cli\Table\Tabular() ); + $table->setRenderer( new cli\table\Tabular() ); $out = $table->getDisplayLines(); @@ -445,7 +450,7 @@ public function test_shortcut_constructor_tabular() { $this->assertSame( $expected, $out ); } - public function test_shortcut_constructor_normalization() { + public function test_shortcut_constructor_normalization(): void { $headers = array( array( 'Name' => 'Alice', 'Age' => '30' ), array( 'Age' => '25', 'Name' => 'Bob' ), // Different order @@ -453,7 +458,7 @@ public function test_shortcut_constructor_normalization() { ); $table = new cli\Table( $headers ); - $table->setRenderer( new cli\Table\Tabular() ); + $table->setRenderer( new cli\table\Tabular() ); $out = $table->getDisplayLines(); @@ -467,15 +472,16 @@ public function test_shortcut_constructor_normalization() { $this->assertSame( $expected, $out ); } - public function test_displayRow_ascii() { + public function test_displayRow_ascii(): void { $mockFile = tempnam( sys_get_temp_dir(), 'temp' ); $resource = fopen( $mockFile, 'wb' ); + $this->assertNotFalse( $resource ); try { \cli\Streams::setStream( 'out', $resource ); $table = new cli\Table(); - $renderer = new cli\Table\Ascii(); + $renderer = new cli\table\Ascii(); $table->setRenderer( $renderer ); $table->setHeaders( array( 'Name', 'Age' ) ); @@ -483,6 +489,7 @@ public function test_displayRow_ascii() { $table->displayRow( array( 'Alice', '30' ) ); $output = file_get_contents( $mockFile ); + $this->assertIsString( $output ); // Should contain the row data $this->assertStringContainsString( 'Alice', $output ); @@ -498,15 +505,16 @@ public function test_displayRow_ascii() { } } - public function test_displayRow_tabular() { + public function test_displayRow_tabular(): void { $mockFile = tempnam( sys_get_temp_dir(), 'temp' ); $resource = fopen( $mockFile, 'wb' ); + $this->assertNotFalse( $resource ); try { \cli\Streams::setStream( 'out', $resource ); $table = new cli\Table(); - $renderer = new cli\Table\Tabular(); + $renderer = new cli\table\Tabular(); $table->setRenderer( $renderer ); $table->setHeaders( array( 'Name', 'Age' ) ); @@ -514,6 +522,7 @@ public function test_displayRow_tabular() { $table->displayRow( array( 'Alice', '30' ) ); $output = file_get_contents( $mockFile ); + $this->assertIsString( $output ); // Should contain the row data with tabs $this->assertStringContainsString( 'Alice', $output ); @@ -525,9 +534,9 @@ public function test_displayRow_tabular() { } } - public function test_renderers_declare_whether_they_need_widths() { - $this->assertTrue( ( new cli\Table\Ascii() )->needsWidths() ); - $this->assertFalse( ( new cli\Table\Tabular() )->needsWidths() ); + public function test_renderers_declare_whether_they_need_widths(): void { + $this->assertTrue( ( new cli\table\Ascii() )->needsWidths() ); + $this->assertFalse( ( new cli\table\Tabular() )->needsWidths() ); } /** @@ -535,16 +544,18 @@ public function test_renderers_declare_whether_they_need_widths() { */ public static function data_renderers() { return [ - 'ascii' => [ new cli\Table\Ascii() ], - 'tabular' => [ new cli\Table\Tabular() ], + 'ascii' => [ new cli\table\Ascii() ], + 'tabular' => [ new cli\table\Tabular() ], ]; } /** * @dataProvider data_renderers + * + * @param \cli\table\Renderer $renderer Renderer to use for the table. */ #[\PHPUnit\Framework\Attributes\DataProvider( 'data_renderers' )] // phpcs:ignore PHPCompatibility.Attributes.NewAttributes.PHPUnitAttributeFound - public function test_display_lines_from_rows_match_display_lines( $renderer ) { + public function test_display_lines_from_rows_match_display_lines( $renderer ): void { $rows = [ [ 'first', "multi\nline" ], [ 'second', '' ], @@ -582,9 +593,9 @@ public function test_display_lines_from_rows_match_display_lines( $renderer ) { } } - public function test_display_lines_from_rows_are_yielded_as_rows_are_read_with_tabular_renderer() { + public function test_display_lines_from_rows_are_yielded_as_rows_are_read_with_tabular_renderer(): void { $table = new cli\Table(); - $table->setRenderer( new cli\Table\Tabular() ); + $table->setRenderer( new cli\table\Tabular() ); $table->setHeaders( [ 'Name' ] ); $log = []; @@ -602,9 +613,9 @@ public function test_display_lines_from_rows_are_yielded_as_rows_are_read_with_t $this->assertSame( [ 'line Name', 'read a', 'line a', 'read b', 'line b' ], $log ); } - public function test_display_lines_from_rows_are_aligned_with_ascii_renderer() { + public function test_display_lines_from_rows_are_aligned_with_ascii_renderer(): void { $table = new cli\Table(); - $table->setRenderer( new cli\Table\Ascii() ); + $table->setRenderer( new cli\table\Ascii() ); $table->setHeaders( [ 'Name' ] ); $lines = iterator_to_array( $table->getDisplayLinesFromRows( new ArrayIterator( [ [ 'a' ], [ 'longer' ] ] ) ), false ); @@ -613,15 +624,16 @@ public function test_display_lines_from_rows_are_aligned_with_ascii_renderer() { $this->assertSame( '| a |', $lines[3] ); } - public function test_display_rows_writes_the_display_lines() { + public function test_display_rows_writes_the_display_lines(): void { $mock_file = tempnam( sys_get_temp_dir(), 'temp' ); $resource = fopen( $mock_file, 'wb' ); + $this->assertNotFalse( $resource ); try { \cli\Streams::setStream( 'out', $resource ); $table = new cli\Table(); - $table->setRenderer( new cli\Table\Tabular() ); + $table->setRenderer( new cli\table\Tabular() ); $table->setHeaders( [ 'Name', 'Age' ] ); $table->displayRows( new ArrayIterator( [ [ 'Alice', '30' ], [ 'Bob', '25' ] ] ) ); diff --git a/tests/Test_Table_Ascii.php b/tests/Test_Table_Ascii.php index 39cc99fd..6fa6e48b 100644 --- a/tests/Test_Table_Ascii.php +++ b/tests/Test_Table_Ascii.php @@ -28,6 +28,7 @@ class Test_Table_Ascii extends TestCase { public function set_up() { $this->_mockFile = tempnam(sys_get_temp_dir(), 'temp'); $resource = fopen($this->_mockFile, 'wb'); + $this->assertNotFalse($resource); Streams::setStream('out', $resource); $this->_instance = new Table(); @@ -46,7 +47,7 @@ public function tear_down() { /** * Draw simple One column table */ - public function testDrawOneColumnTable() { + public function testDrawOneColumnTable(): void { $headers = array('Test Header'); $rows = array( array('x'), @@ -74,7 +75,7 @@ public function testDrawOneColumnTable() { * where `x` character has green color. * At the same time it checks that `green` defined in `cli\Colors` really looks as `green`. */ - public function testDrawOneColumnColoredTable() { + public function testDrawOneColumnColoredTable(): void { Colors::enable( true ); $headers = array('Test Header'); $rows = array( @@ -96,7 +97,7 @@ public function testDrawOneColumnColoredTable() { /** * Check it works with colors disabled. */ - public function testDrawOneColumnColorDisabledTable() { + public function testDrawOneColumnColorDisabledTable(): void { Colors::disable( true ); $this->assertFalse( Colors::shouldColorize() ); $headers = array('Test Header'); @@ -117,7 +118,7 @@ public function testDrawOneColumnColorDisabledTable() { /** * Test that colorized text wraps correctly while maintaining color codes. */ - public function testWrappedColorizedText() { + public function testWrappedColorizedText(): void { Colors::enable( true ); $headers = array('Column 1', 'Column 2'); $green_code = "\x1b\x5b\x33\x32\x3b\x31\x6d"; // Green + bright @@ -156,7 +157,7 @@ public function testWrappedColorizedText() { /** * Test word-wrapping mode keeps words together. */ - public function testWordWrappingMode() { + public function testWordWrappingMode(): void { $headers = array('name', 'status'); $rows = array( array('all-in-one-wp-migration-multisite-extension', 'inactive'), @@ -187,7 +188,7 @@ public function testWordWrappingMode() { /** * Test truncate mode with ellipsis. */ - public function testTruncateMode() { + public function testTruncateMode(): void { $headers = array('name', 'status'); $rows = array( array('all-in-one-wp-migration-multisite-extension', 'inactive'), @@ -218,7 +219,7 @@ public function testTruncateMode() { /** * Test that wrapping mode setter validates input. */ - public function testWrappingModeValidation() { + public function testWrappingModeValidation(): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage("Invalid wrapping mode 'invalid'"); @@ -229,11 +230,11 @@ public function testWrappingModeValidation() { /** * Checks that spacing and borders are handled correctly in table */ - public function testSpacingInTable() { + public function testSpacingInTable(): void { $headers = array('A', ' ', 'C', ''); $rows = array( array(' ', 'B1', '', 'D1'), - array('A2', '', ' C2', null), + array('A2', '', ' C2', ''), ); $output = <<<'OUT' +-------+------+-----+----+ @@ -250,7 +251,7 @@ public function testSpacingInTable() { /** * Test correct table indentation and border positions for multibyte strings */ - public function testTableWithMultibyteStrings() { + public function testTableWithMultibyteStrings(): void { $headers = array('German', 'French', 'Russian', 'Chinese'); $rows = array( array('Schätzen', 'Apprécier', 'Оценить', '欣賞'), @@ -269,7 +270,7 @@ public function testTableWithMultibyteStrings() { /** * Test that % gets escaped correctly. */ - public function testTableWithPercentCharacters() { + public function testTableWithPercentCharacters(): void { $headers = array( 'Heading', 'Heading2', 'Heading3' ); $rows = array( array( '% at start', 'at end %', 'in % middle' ) @@ -288,16 +289,16 @@ public function testTableWithPercentCharacters() { /** * Test that a % is appropriately padded in the table */ - public function testTablePaddingWithPercentCharacters() { + public function testTablePaddingWithPercentCharacters(): void { $headers = array( 'ID', 'post_title', 'post_name' ); $rows = array( array( - 3, + '3', '10%', '' ), array( - 1, + '1', 'Hello world!', 'hello-world' ), @@ -318,11 +319,12 @@ public function testTablePaddingWithPercentCharacters() { * Draw wide multiplication Table. * Example with many columns, many rows */ - public function testDrawMultiplicationTable() { + public function testDrawMultiplicationTable(): void { $maxFactor = 16; - $headers = array_merge(array('x'), range(1, $maxFactor)); - for ($i = 1, $rows = array(); $i <= $maxFactor; ++$i) { - $rows[] = array_merge(array($i), range($i, $i * $maxFactor, $i)); + $headers = array_map('strval', array_merge(array('x'), range(1, $maxFactor))); + $rows = array(); + for ($i = 1; $i <= $maxFactor; ++$i) { + $rows[] = array_map('strval', array_merge(array($i), range($i, $i * $maxFactor, $i))); } $output = <<<'OUT' @@ -354,7 +356,7 @@ public function testDrawMultiplicationTable() { /** * Draw a table with headers but no data */ - public function testDrawWithHeadersNoData() { + public function testDrawWithHeadersNoData(): void { $headers = array('header 1', 'header 2'); $rows = array(); $output = <<<'OUT' @@ -370,10 +372,10 @@ public function testDrawWithHeadersNoData() { * Verifies that Input and Output equals, * Sugar method for fast access from tests * - * @param array $input First element is header array, second element is rows array - * @param mixed $output Expected output + * @param array{array, array>} $input First element is header array, second element is rows array + * @param string $output Expected output */ - private function assertInOutEquals(array $input, $output) { + private function assertInOutEquals(array $input, $output): void { $this->_instance->setHeaders($input[0]); $this->_instance->setRows($input[1]); $this->_instance->display(); @@ -383,10 +385,11 @@ private function assertInOutEquals(array $input, $output) { /** * Checks that contents of input string and temporary file match * - * @param mixed $expected Expected output + * @param string $expected Expected output */ - private function assertOutFileEqualsWith($expected) { + private function assertOutFileEqualsWith($expected): void { $actual = file_get_contents($this->_mockFile); + $this->assertIsString($actual); $actual = str_replace("\r\n", "\n", $actual); $expected = str_replace("\r\n", "\n", $expected); $this->assertEquals($expected, $actual); diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 17708596..20e5b33b 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -1,7 +1,9 @@