From e715707128a601ec483b566de1421880476cd780 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Thu, 4 Jul 2024 00:21:15 +0200 Subject: [PATCH] AbstractMethodUnitTest: improve finding of target token These changes are similar to changes previously made in the same method in PHPCSUtils. As things were, there could be a situation where the `getTargetTokenFromFile()` method did not find the delimiter comment. In that case, the method would search for the target token starting at token 0, which would generally lead to an incorrect token being identified as the target token. This has now been fixed by verifying the outcome of the `findPrevious()` call and throwing an exception (causing the test to fail) when the delimiter comment was not found. Along the same lines, when the target token would not be found, an exception will now be thrown as well. --- tests/Core/AbstractMethodUnitTest.php | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/tests/Core/AbstractMethodUnitTest.php b/tests/Core/AbstractMethodUnitTest.php index b933be17b4..c6dec9b008 100644 --- a/tests/Core/AbstractMethodUnitTest.php +++ b/tests/Core/AbstractMethodUnitTest.php @@ -9,6 +9,7 @@ namespace PHP_CodeSniffer\Tests\Core; +use Exception; use PHP_CodeSniffer\Files\DummyFile; use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Ruleset; @@ -110,6 +111,9 @@ public function getTargetToken($commentString, $tokenType, $tokenContent=null) * @param string $tokenContent Optional. The token content for the target token. * * @return int + * + * @throws Exception When the test delimiter comment is not found. + * @throws Exception When the test target token is not found. */ public static function getTargetTokenFromFile(File $phpcsFile, $commentString, $tokenType, $tokenContent=null) { @@ -122,6 +126,12 @@ public static function getTargetTokenFromFile(File $phpcsFile, $commentString, $ $commentString ); + if ($comment === false) { + throw new Exception( + sprintf('Failed to find the test marker: %s in test case file %s', $commentString, $phpcsFile->getFilename()) + ); + } + $tokens = $phpcsFile->getTokens(); $end = ($start + 1); @@ -148,10 +158,10 @@ public static function getTargetTokenFromFile(File $phpcsFile, $commentString, $ if ($target === false) { $msg = 'Failed to find test target token for comment string: '.$commentString; if ($tokenContent !== null) { - $msg .= ' With token content: '.$tokenContent; + $msg .= ' with token content: '.$tokenContent; } - self::assertFalse(true, $msg); + throw new Exception($msg); } return $target;