phpstan-phpunit icon indicating copy to clipboard operation
phpstan-phpunit copied to clipboard

Support assertNotEmpty/assertEmpty

Open ntzm opened this issue 6 years ago • 5 comments

Passing a value to assertNotEmpty/assertEmpty doesn't tell phpstan that the value isn't/is empty

ntzm avatar Dec 19 '19 14:12 ntzm

Can you be more specific with a code sample?

ondrejmirtes avatar Dec 19 '19 14:12 ondrejmirtes

Here's an example test:

public function testFoo() : void {
	$file = file( 'file.txt' );

	self::assertNotEmpty( $file );
	self::assertCount( 10, $file );
}

The assertCount() line gets flagged as an error by PHPStan because assertNotEmpty() does not narrow the type of $file from array|false to array.

Error:

[phpstan] Parameter #2 $haystack of static method PHPUnit\Framework\Assert::assertCount() expects Countable|iterable, array<int, string>|false given.

johnbillion avatar May 12 '21 20:05 johnbillion

self::assertIsArray( $file ); does correctly narrow the type.

johnbillion avatar May 12 '21 20:05 johnbillion

I just stumbled across this issue myself.

I have code that looks like this:

$value = someFunctionThatReturnsStringOrNull();
self::assertNotEmpty($value);
someFunctionThatAcceptsStrings($value);

PHPStan complains that $value might be null. However, this case should haven been caught by the assertNotEmpty() call. If I replace assertNotEmpty() with assertNotNull(), the error is gone.

derrabus avatar Jun 04 '21 14:06 derrabus

Note that assertCount(1, $file) does not narrow the type either.

greg0ire avatar Oct 18 '21 18:10 greg0ire

Is this fixed with https://github.com/phpstan/phpstan-phpunit/commit/f5b7eb65d93d38673d4c9d8b0b20b6c601697778 ?

canvural avatar Oct 24 '22 11:10 canvural

Yes, should be, although I've written that mainly to fix wrong @psalm-assert empty annotation in PHPUnit, which would get much more annoying with PHPStan 1.9.0 soon to be released :)

ondrejmirtes avatar Oct 24 '22 11:10 ondrejmirtes

Yes, should be, although I've written that mainly to fix wrong @psalm-assert empty annotation in PHPStan, which would get much more annoying with PHPStan 1.9.0 soon to be released :)

Yeah I also experienced that while testing 1.9.x I was gonna mention it but you were faster here.

canvural avatar Oct 24 '22 11:10 canvural

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

github-actions[bot] avatar Nov 25 '22 00:11 github-actions[bot]