Skip to content

Commit

Permalink
AbstractMethodUnitTest: improve finding of target token
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
jrfnl committed Jul 4, 2024
1 parent e245088 commit e715707
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions tests/Core/AbstractMethodUnitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)
{
Expand All @@ -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);

Expand All @@ -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;
Expand Down

0 comments on commit e715707

Please sign in to comment.