From 0e965d96ff42447ebd4c1858c777df7bcd933fdd Mon Sep 17 00:00:00 2001 From: jrfnl Date: Sat, 14 Sep 2024 23:31:50 +0200 Subject: [PATCH] WP_UnitTestCase_Base: introduce a new assertion and a new helper method Introduces `WP_UnitTestCase_Base::assertSamePathIgnoringDirectorySeparators()` and an associated helper method `WP_UnitTestCase_Base::normalizeDirectorySeparatorsInPath()` to allow for comparing two file path strings independently of OS-specific differences. The normalization is done in a separate method to also allow this method to be used for path normalization within test methods themselves, like for normalizing a group of paths in an array. The pretty specific method name for the helper (`normalizeDirectorySeparatorsInPath()`) is an attempt to prevent naming conflicts with methods which may exist in plugin test suites build on top of the WP Core test suite. --- tests/phpunit/includes/abstract-testcase.php | 34 ++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/tests/phpunit/includes/abstract-testcase.php b/tests/phpunit/includes/abstract-testcase.php index f2978644faf2a..224929eb377a8 100644 --- a/tests/phpunit/includes/abstract-testcase.php +++ b/tests/phpunit/includes/abstract-testcase.php @@ -1070,6 +1070,40 @@ public function assertNonEmptyMultidimensionalArray( $actual, $message = '' ) { } } + /** + * Assert that two text strings representing file paths are the same, while ignoring + * OS-specific differences in the directory separators. + * + * This allows for tests to be compatible for running on both *nix based as well as Windows OS. + * + * @since 6.7.0 + * + * @param string $path_a File or directory path. + * @param string $path_b File or directory path. + */ + public function assertSamePathIgnoringDirectorySeparators( $path_a, $path_b ) { + $path_a = $this->normalizeDirectorySeparatorsInPath( $path_a ); + $path_b = $this->normalizeDirectorySeparatorsInPath( $path_b ); + + $this->assertSame( $path_a, $path_b ); + } + + /** + * Normalize directory separators in a file path to be a forward slash. + * + * @since 6.7.0 + * + * @param string $path File or directory path. + * @return string The normalized file or directory path. + */ + public function normalizeDirectorySeparatorsInPath( $path ) { + if ( ! is_string( $path ) || PHP_OS_FAMILY !== 'Windows' ) { + return $path; + } + + return strtr( $path, '\\', '/' ); + } + /** * Checks each of the WP_Query is_* functions/properties against expected boolean value. *