PHPStan PHPUnit extensions and rules

Overview

PHPStan PHPUnit extensions and rules

Build Latest Stable Version License

This extension provides following features:

  • createMock(), getMockForAbstractClass() and getMockFromWsdl() methods return an intersection type (see the detailed explanation of intersection types) of the mock object and the mocked class so that both methods from the mock object (like expects) and from the mocked class are available on the object.
  • getMock() called on MockBuilder is also supported.
  • Interprets Foo|PHPUnit_Framework_MockObject_MockObject in phpDoc so that it results in an intersection type instead of a union type.
  • Defines early terminating method calls for the PHPUnit\Framework\TestCase class to prevent undefined variable errors.
  • Specifies types of expressions passed to various assert methods like assertInstanceOf, assertTrue, assertInternalType etc.
  • Combined with PHPStan's level 4, it points out always-true and always-false asserts like assertTrue(true) etc.

It also contains this strict framework-specific rules (can be enabled separately):

  • Check that you are not using assertSame() with true as expected value. assertTrue() should be used instead.
  • Check that you are not using assertSame() with false as expected value. assertFalse() should be used instead.
  • Check that you are not using assertSame() with null as expected value. assertNull() should be used instead.
  • Check that you are not using assertSame() with count($variable) as second parameter. assertCount($variable) should be used instead.

How to document mock objects in phpDocs?

If you need to configure the mock even after you assign it to a property or return it from a method, you should add PHPUnit_Framework_MockObject_MockObject to the phpDoc:

/**
 * @return Foo&PHPUnit_Framework_MockObject_MockObject
 */
private function createFooMock()
{
	return $this->createMock(Foo::class);
}

public function testSomething()
{
	$fooMock = $this->createFooMock();
	$fooMock->method('doFoo')->will($this->returnValue('test'));
	$fooMock->doFoo();
}

Please note that the correct syntax for intersection types is Foo&PHPUnit_Framework_MockObject_MockObject. Foo|PHPUnit_Framework_MockObject_MockObject is also supported, but only for ecosystem and legacy reasons.

If the mock is fully configured and only the methods of the mocked class are supposed to be called on the value, it's fine to typehint only the mocked class:

/** @var Foo */
private $foo;

protected function setUp()
{
	$fooMock = $this->createMock(Foo::class);
	$fooMock->method('doFoo')->will($this->returnValue('test'));
	$this->foo = $fooMock;
}

public function testSomething()
{
	$this->foo->doFoo();
	// $this->foo->method() and expects() can no longer be called
}

Installation

To use this extension, require it in Composer:

composer require --dev phpstan/phpstan-phpunit

If you also install phpstan/extension-installer then you're all set!

Manual installation

If you don't want to use phpstan/extension-installer, include extension.neon in your project's PHPStan config:

includes:
    - vendor/phpstan/phpstan-phpunit/extension.neon

To perform framework-specific checks, include also this file:

    - vendor/phpstan/phpstan-phpunit/rules.neon
Comments
  • Regression with assertEmpty extension

    Regression with assertEmpty extension

    Somehow passing array<'0.6.0'|'1.0.0'|'1.0.x-dev'|'1.1.x-dev'|'9999999-dev'|'dev-feature-b'|'dev-feature/a-1.0-B'|'dev-master', true> into self::assertEmpty() is not allowed

    183    Call to method PHPUnit\Framework\Assert::assertEmpty() with
             array<'0.6.0'|'1.0.0'|'1.0.x-dev'|'1.1.x-dev'|'9999999-dev'|'dev-feature-b'|'dev-feature/a-1.0-B'|'dev-master', true> and
             literal-string&non-falsy-string will always evaluate to false.
    

    It's not a non-empty-array, so I don't see why it isn't allowed.

    The code looks something like this, but obviously there is no error there as I cannot use the phpunit code

    https://phpstan.org/r/7c7be20e-ed51-4311-a0e0-74c061f99561

    opened by Seldaek 12
  • False positive in PHPStan 1.4.8 with `assertNotSame` with instances of the same class

    False positive in PHPStan 1.4.8 with `assertNotSame` with instances of the same class

    Using phpstan/phpstan-phpunit 1.0.0 and phpstan/phpstan 1.4.8, the following code creates a false positive:

    namespace OliverKlee\Oelib\Tests\Unit\Templating;
    
    use Nimut\TestingFramework\TestCase\UnitTestCase;
    use OliverKlee\Oelib\Templating\Template;
    use OliverKlee\Oelib\Templating\TemplateRegistry;
    
    class TemplateRegistryTest extends UnitTestCase
    {
        /**
         * @test
         */
        public function getForExistingTemplateFileNameCalledTwoTimesReturnsNewInstance(): void
        {
            self::assertNotSame(
                TemplateRegistry::get('EXT:oelib/Tests/Functional/Fixtures/Template.html'),
                TemplateRegistry::get('EXT:oelib/Tests/Functional/Fixtures/Template.html')
            );
        }
    }
    

    This is the error (with different line numbers):

     ------ --------------------------------------------------------------------------------------------------------------------------------------------------------- 
      Line   Tests/Unit/Templating/TemplateRegistryTest.php                                                                                                           
     ------ --------------------------------------------------------------------------------------------------------------------------------------------------------- 
      69     Call to static method PHPUnit\Framework\Assert::assertNotSame() with OliverKlee\Oelib\Templating\Template and OliverKlee\Oelib\Templating\Template will  
             always evaluate to false.                                                                                                                                
      91     Call to static method PHPUnit\Framework\Assert::assertNotSame() with OliverKlee\Oelib\Templating\Template and OliverKlee\Oelib\Templating\Template will  
             always evaluate to false.                                                                                                                                
     ------ --------------------------------------------------------------------------------------------------------------------------------------------------------- 
    

    This problem is new with PHPStan 1.4.8 (as it did no occur with PHPStan 1.4.7).

    You can find the complete build with the problem at https://github.com/oliverklee/ext-oelib/pull/904.

    (I was not able to use the PHPStan playground for this as I currently do not know of any way of including PHPUnit in it: https://phpstan.org/r/c7fa7bda-1024-45c3-957d-7b91de41b844)

    opened by oliverklee 12
  • Don't work Foo&PHPUnit_Framework_MockObject_MockObject

    Don't work Foo&PHPUnit_Framework_MockObject_MockObject

    Don't work comments Foo&PHPUnit_Framework_MockObject_MockObject and Foo&MockObject

    /**
    * @return Foo&MockObject
    */
    private function createSomeMock()
    {
        $mock = $this
            ->getMockBuilder(Foo::class)
            ->setMethodsExcept(['foo', 'bar'])
            ->setConstructorArgs([])
            ->getMock();
    
        return $mock;
    }
    

    phpstan error: PHPDoc tag @return contains unresolvable type.

    phpstan version: 0.12.37 phpstan-phpunit version: 0.12.16

    opened by marksartdev 12
  • cannot recognise trait methods

    cannot recognise trait methods

    I'm testing my codebase miklcct/thin_php_app and in two of the test files phpstan throws an error:

     ------ ------------------------------------------------------------------------------------ 
      Line   test/View/StreamToStringTest.php                                                    
     ------ ------------------------------------------------------------------------------------ 
      16     Call to an undefined method PHPUnit\Framework\MockObject\MockObject::__toString().  
     ------ ------------------------------------------------------------------------------------ 
    
     ------ -------------------------------------------------------------------------------- 
      Line   test/View/StringToStreamTest.php                                                
     ------ -------------------------------------------------------------------------------- 
      16     Call to an undefined method PHPUnit\Framework\MockObject\MockObject::render().  
     ------ -------------------------------------------------------------------------------- 
    

    The mock objects are created by $iut = $this->getMockForTrait(StreamToString::class); and $iut = $this->getMockForTrait(StringToStream::class);, and the traits have the mentioned methods defined. PhpStorm type hints work on these 2 files.

    opened by miklcct 11
  • Filter scope when using PHPUnit's assertions

    Filter scope when using PHPUnit's assertions

    I'm not sure if this is the correct repo to open this issue, but it seems to be the best place...

    What I'd like to implement (with some help, sure) is the ability to do the same thing done when assert() is called but when using PHPUnit's assertions:

    https://github.com/phpstan/phpstan/blob/a50b95cb29fe720a3f8b35297fe3b559d6616d5a/src/Analyser/NodeScopeResolver.php#L197-L204

    Some context:

    We create contexts for Behat using PHPUnit's assertions and sometimes we have this kind of code:

    public function thenSomethingMustHaveHappened(): void
    {
        $something = $this->lovelyService->doSomething(); // which has `?Something` as return type hint
    
        Assert::assertNotNull($something);
        Assert::assertSame('Something', $something->getSomething());    
    }
    

    Then PHPstan complains:

    ------ -------------------------------------------------------------------------------------------------- 
      Line   SomethingContext.php                                                                     
     ------ -------------------------------------------------------------------------------------------------- 
      XX     Calling method getSomething() on possibly null value of type Something|null.  
     ------ -------------------------------------------------------------------------------------------------- 
    

    However if assert($something !== null) is used, things just work...

    Of course we could simply use assert() everywhere but we rather use a more friendly tool. So this leads us to two questions:

    1. is this interesting for phpstan?
    2. how can we implement this?
    opened by lcobucci 11
  • False positive when using assertNull and assertSame on same method

    False positive when using assertNull and assertSame on same method

    Summary of a problem or a feature request

    When asserting a method result to be null, then changing the internal state of the object, and then asserting the method result to be the same as some object, PHPStan currently fails thinking it will still be null, letting assertSame() always fail.

    Code snippet that reproduces the problem

    <?php
    
    declare(strict_types=1);
    
    class Foo {
        /**
         * @var Bar|null
         */
        protected $bar;
    
        /**
         * @return Bar|null
         */
        public function getBar(): ?Bar
        {
            return $this->bar;
        }
    
        /**
         * @param Bar|null $bar
         */
        public function setBar(?Bar $bar): void
        {
            $this->bar = $bar;
        }
    }
    
    class Bar
    {
    }
    
    class FooTest extends TestCase
    {
        public function testBar(): void
        {
            $foo = new Foo();
            $bar = new Bar();
    
            $this->assertNull($foo->getBar());
            $foo->setBar($bar);
            $this->assertSame($bar, $foo->getBar()); // <-- This line triggers the error
        }
    }
    

    Used configuration

    parameters:
      level: max
    
    includes:
      - vendor/phpstan/phpstan-phpunit/extension.neon
      - vendor/phpstan/phpstan-phpunit/rules.neon
    
    • phpstan/phpstan @ 0.10.2
    • phpstan/phpstan-phpunit @ 0.10

    Actual output

     ------ --------------------------------------------------------------------------------------------------------------------------------------- 
      Line   FooTest.php                                                                                                                            
     ------ --------------------------------------------------------------------------------------------------------------------------------------- 
      18     Call to method PHPUnit\Framework\Assert::assertSame() with FactorioItemBrowser\ExportData\Bar and null will always evaluate to false.  
     ------ --------------------------------------------------------------------------------------------------------------------------------------- 
                                                                                                                           
     [ERROR] Found 1 error      
    

    Expected output

     [OK] No errors   
    

    PHPUnit test does run successfully, and so should PHPStan, as all asserts are valid.

    opened by BluePsyduck 10
  • Analysis of `assertSame` cannot infer type if expected value is constant from symfony `Response` object

    Analysis of `assertSame` cannot infer type if expected value is constant from symfony `Response` object

    Since the phpstan update to 1.7.0, assertSame throws an error when used with symfonysResponse::HTTP_*constants. As the error only appears forassertSamecalls and not others e.g.assertEquals` I think the error may lay in this extension instead of in phpstan itself.

    Error message

    Parameter #1 $expected of method PHPUnit\Framework\Assert::assertSame() contains unresolvable type.
    

    How to reproduce

    use PHPUnit\Framework\TestCase;
    use Symfony\Component\HttpFoundation\Response;
    
    class Test extends TestCase
    {
        public function testThrowsAnError(): void
        {
             $this->assertSame(Response::HTTP_OK, 200);   
        }
    
        public function testThrowsNoError(): void
        {
             $this->assertEquals(Response::HTTP_OK, 200);   
             $this->assertSame(\PDO::PARAM_BOOL, 5);   
        }
    }
    

    Environment

    PHP: 8.1.5 phpstan: 1.7.0 phpstan-phpunit: 1.1.1 phpunit: 9.5.20

    Other extensions: phpstan-symfony: 1.1.8 phpstan-doctrine: 1.3.5

    opened by keulinho 9
  • Conflict with Phpstorm resolution.

    Conflict with Phpstorm resolution.

    I'm using

    "phpstan/phpstan": "0.12.*",
    "phpstan/phpstan-phpunit": "0.12.*",
    "phpunit/phpunit": "8.2.5",
    

    I have warning from Phpstorm 'void' method 'getMockBuilder' result used with the following code :

    $pdfGenerator = $this->getMockBuilder(PdfGenerator::class)->getMock();
    

    When I Cmd + Click, I see Phpstorm are locating the getMockBuilder in phpstan/phpstan-phpunit/stubs (instead of inside Phpunit package, maybe he take the first one in lexical order) with the following annotation:

    	/**
    	 * @template T
    	 * @phpstan-param class-string<T> $originalClassName
    	 * @phpstan-return MockObject&T
    	 */
    	public function createConfiguredMock($originalClassName) {}
    

    And theses annotations are not understood by Phpstorm.

    Changing to

    	/**
    	 * @template T
    	 * @phpstan-param class-string<T> $originalClassName
    	 * @phpstan-return MockObject&T
             * @return MockBuilder
    	 */
    	public function createConfiguredMock($originalClassName) {}
    

    Fix the issue.

    By the way, in Phpunit code, the annotations are

    /**
         * Returns a builder object to create mock objects using a fluent interface.
         *
         * @param string|string[] $className
         *
         * @psalm-template RealInstanceType of object
         * @psalm-param class-string<RealInstanceType>|string[] $className
         * @psalm-return MockBuilder<RealInstanceType>
         */
        public function getMockBuilder($className): MockBuilder
        {
            $this->recordDoubledType($className);
    
            return new MockBuilder($this, $className);
        }
    

    So the returnType/paramsType are added both with the psalm syntax and the regular syntax.

    Shouldn't the regular syntax be used too in the stubs provided by phpstan ?

    opened by VincentLanglet 9
  • assertSame() specifies a value

    assertSame() specifies a value

    I just tried dev-master version of PHPStan with dev-master (actually ^0.10) of phpstan-phpunit and I stumbled across this issue: assertSame somehow fixes the value to the first occurrence.

    Although the test pass, an error is reported for the second assert:

    Call to static method PHPUnit\Framework\Assert::assertSame() with int(200) and int(100) will always evaluate to false.
    
    <?php declare(strict_types = 1);
    
    namespace App;
    
    class FooTest extends \PHPUnit\Framework\TestCase
    {
    
    	public function testAssertSameBehaviour(): void
    	{
    		$foo = new Foo();
    		$foo->setValue(100);
    
    		self::assertSame(100, $foo->getValue());
    
    		$foo->setValue(200);
    		self::assertSame(200, $foo->getValue());
    	}
    
    }
    
    
    class Foo {
    
    	/** @var int */
    	private $value;
    
    	public function getValue(): int
    	{
    		return $this->value;
    	}
    
    	public function setValue(int $value): void
    	{
    		$this->value = $value;
    	}
    
    }
    
    opened by mhujer 9
  • if I assert using assertInstanceOf it must not report an error afterwards

    if I assert using assertInstanceOf it must not report an error afterwards

    Hello

    Inside a unit test I had a code like this

            $collector = $client->getProfile()->getCollector('request');
    

    because $client->getProfile() can return false|Profile phpstan was reporting the following issue:

     20     Cannot call method getCollector() on                                                                
             false|Symfony\Component\HttpKernel\Profiler\Profile.
     ------ ---------------------------------------------------------------------------------------------------- 
    

    I changed my code to something like this:

            $profiler = $client->getProfile();
            $this->assertInstanceOf(Profile::class, $profiler);
    
            $collector = $profiler->getCollector('request');
    

    And the error was still reported. So finally I had to add this /** @var Profile $profiler */ inline docblock in order for the error not to be reported and trick PHPstan.

    I believe that since you do an assertInstanceOf there is no need to display an error and having to trick PHPstan by adding inline docblock. Is this possible to be fixed?

    opened by gmponos 8
  • Require phpunit on dev deps

    Require phpunit on dev deps

    PHPUnit should not be a mandatory requirement.

    Some users would like to use PHPUnit phar global installation and don't want to have to get the whole dependencies of PHPUnit and itself on the project vendor dir.

    What is the goal of this requirement? I don't see any direct class usage so far.

    UPDATE: BTW, it also mandatory to require also phpstan from plugins? What is the usage if we use the docker image or the shim repository?

    Regards

    opened by soullivaneuh 8
  • PhpStan does not consider usage of Phpunit Assert::assertNotEmpty and Assert::assertContainsOnlyInstancesOf when returning an Array

    PhpStan does not consider usage of Phpunit Assert::assertNotEmpty and Assert::assertContainsOnlyInstancesOf when returning an Array

    Hello,

    I am building a test returning an array of entities to be used in some others tests marked with @depends. Despite I check that my returned array is not empty an contains only instances of a specific class, phpstan keeps alerting that my returned value does not match. Here is my code:

         /**
         * @return Post[]
         *
         * @throws \Exception
         */
        public function testFindForHomePageReturnsCollectionOfPosts(): array
        {
            $testSubject = self::getContainer()->get(PostRepository::class);
            if (!$testSubject instanceof PostRepository) {
                throw new ServiceNotFoundException(PostRepository::class);
            }
    
            $result = $testSubject->findForHomePage()->toArray();
            self::assertNotEmpty($result);
            self::assertContainsOnlyInstancesOf(Post::class, $result);
    
            return $result;
        }
    

    And the alert thrown by phpstan (line 34 is the return $result statement): image

    Context:

    Symfony 6.2 KernelTestCase phpunit/phpunit 9.5.25 symfony/phpunit-bridge 6.2.0

    PhpStan 1.9.3 extensions:

    • phpstan-phpunit 1.3.2
    • phpstan-doctrine 1.3.18
    • phpstan-symfony 1.2.15
    • phpstan/phpstan-webmozart-assert 1.2.1

    Thanks a lot for your help :)

    opened by Lreus 0
  • Update build-cs (major)

    Update build-cs (major)

    Mend Renovate

    This PR contains the following updates:

    | Package | Type | Update | Change | |---|---|---|---| | dealerdirect/phpcodesniffer-composer-installer (source) | require-dev | major | ^0.7.0 -> ^1.0.0 | | slevomat/coding-standard | require-dev | major | ^7.0 -> ^8.0 |


    Release Notes

    Dealerdirect/phpcodesniffer-composer-installer

    v1.0.0

    Compare Source

    What's Changed

    New Contributors

    Full Changelog: https://github.com/PHPCSStandards/composer-installer/compare/v0.7.2...v1.0.0

    slevomat/coding-standard

    v8.8.0

    Compare Source

    🔧 Improvements

    • Support for unsealed array shapes
    • Allow for the 1.0.0 version of the Composer PHPCS plugin (thanks to @​jrfnl)

    🐛 Fixes

    • SlevomatCodingStandard.Classes.RequireAbstractOrFinal: Fixed false positive for readonly classes
    • Fix typo in exception message (thanks to @​jslmorrison)

    v8.7.1

    Compare Source

    🐛 Fixes

    • SlevomatCodingStandard.TypeHints.ParameterTypeHintSpacing: Fixed false positive when parameter has attribute but no type hint

    v8.7.0

    Compare Source

    🔧 Improvements

    • Support for phpstan/phpdoc-parser 1.15
    • Support for phpstan/phpdoc-parser 1.14
    • SlevomatCodingStandard.Attributes.AttributesOrder: New option orderAlphabetically
    • SlevomatCodingStandard.Attributes.AttributesOrder: Attributes could be ordered by mask (thanks to @​alexndlm)

    🐛 Fixes

    • SlevomatCodingStandard.Attributes.AttributeAndTargetSpacing: Fixed fixer

    v8.6.4

    Compare Source

    🔧 Improvements

    • Improved annotations parsing
    • SlevomatCodingStandard.Classes.ClassConstantVisibility: Added support for traits with constants
    • SlevomatCodingStandard.Classes.ConstantSpacing: Added support for traits with constants

    🐛 Fixes

    • SlevomatCodingStandard.Attributes.DisallowAttributesJoining: Fix for attribute with trailing comma (thanks to @​javer)

    v8.6.3

    Compare Source

    🐛 Fixes

    • Slevomat.Namespaces.ReferenceUsedNamesOnly: Fixed fixer when there's conflict with Slevomat.Namespaces.UnusedUses
    • SlevomatCodingStandard.Namespaces.FullyQualifiedClassNameInAnnotation: Fixed false positives for int<0, max> and int<min, 100>
    • SlevomatCodingStandard.Attributes.AttributeAndTargetSpacing: Fixed false positive for comment after attribute

    v8.6.2

    Compare Source

    🐛 Fixes

    • SlevomatCodingStandard.Namespaces.FullyQualifiedClassNameInAnnotation: Fixed false positive with self::CONSTANT

    v8.6.1

    Compare Source

    🔧 Improvements

    • Support of phpstan/phpdoc-parser 1.12.0

    🐛 Fixes

    • SlevomatCodingStandard.Namespaces.FullyQualifiedClassNameInAnnotation: Fixed false positives for global constants
    • SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration: Fixed false positives for constants

    v8.6.0

    Compare Source

    🆕 New sniffs

    • Added SlevomatCodingStandard.Attributes.AttributesOrder
    • Added SlevomatCodingStandard.Attributes.AttributeAndTargetSpacing
    • Added SlevomatCodingStandard.Attributes.DisallowMultipleAttributesPerLine
    • Added SlevomatCodingStandard.Attributes.DisallowAttributesJoining (thanks to @​michnovka)
    • Added SlevomatCodingStandard.Attributes.RequireAttributeAfterDocComment

    🔧 Improvements

    • Support of phpstan/phpdoc-parser 1.11.0
    • Support for @phpstan-self-out/@phpstan-this-out
    • Support for @param-out annotation`
    • Support for @template with default value
    • Add dev Composer keyword (thanks to @​GaryJones)

    🐛 Fixes

    • Improved detection of references in double quotes strings

    v8.5.2

    Compare Source

    🐛 Fixes

    • SlevomatCodingStandard.TypeHints.PropertyTypeHint: Fixed false positives when enableUnionTypeHint is disabled and enableIntersectionTypeHint is enabled
    • SlevomatCodingStandard.TypeHints.ParameterTypeHint: Fixed false positives when enableUnionTypeHint is disabled and enableIntersectionTypeHint is enabled
    • SlevomatCodingStandard.TypeHints.ReturnTypeHint: Fixed false positives when enableUnionTypeHint is disabled and enableIntersectionTypeHint is enabled

    v8.5.1

    Compare Source

    🐛 Fixes

    • SlevomatCodingStandard.PHP.RequireExplicitAssertion: Fixed broken fixer when enableAdvancedStringTypes is enabled

    v8.5.0

    Compare Source

    🔧 Improvements

    • PHP 8.2: Support for standalone null, true and false type hints
    • SlevomatCodingStandard.PHP.RequireExplicitAssertion: Improved support for native simple types
    • SlevomatCodingStandard.PHP.RequireExplicitAssertion: New option enableIntegerRanges
    • SlevomatCodingStandard.PHP.RequireExplicitAssertion: New option enableAdvancedStringTypes
    • Support of phpstan/phpdoc-parser 1.8.0

    🐛 Fixes

    • SlevomatCodingStandard.Classes.PropertyDeclaration: Fixed false positive
    • SlevomatCodingStandard.PHP.RequireExplicitAssertion: Fixed false positive
    • SlevomatCodingStandard.ControlStructures.DisallowYodaComparison/RequireYodaComparison: Fixed support for condition in arrow function
    • SlevomatCodingStandard.Classes.DisallowMultiPropertyDefinition: Fixed false positives for old array definition style
    • SlevomatCodingStandard.Variables.UselessVariable: Fixed false positives

    v8.4.0

    Compare Source

    🔧 Improvements

    • Support of phpstan/phpdoc-parser 1.7.0

    🐛 Fixes

    • Fixed detection of some PHP 8.1 types
    • SlevomatCodingStandard.PHP.RequireNowdoc: Accepts escaped sequences (thanks to @​dg)
    • SlevomatCodingStandard.Functions.RequireSingleLineCall: Skip calls with multi-line double-quoted string (thanks to @​schlndh)
    • SlevomatCodingStandard.PHP.UselessParentheses: Fixed false positive with xor
    • SlevomatCodingStandard.Operators.RequireCombinedAssignmentOperator: Try to ignore string offsets

    v8.3.0

    Compare Source

    🆕 New sniffs

    • Added SlevomatCodingStandard.Complexity.Cognitive (thanks to @​bkdotcom)
    • Added SlevomatCodingStandard.Files.FileLength (thanks to @​bkdotcom)
    • Added SlevomatCodingStandard.Classes.ClassLength (thanks to @​bkdotcom)

    🐛 Fixes

    • SlevomatCodingStandard.PHP.RequireExplicitAssertion: Do not throw away static type (thanks to @​simPod)

    v8.2.0

    Compare Source

    🆕 New sniffs

    • Added SlevomatCodingStandard.Classes.BackedEnumTypeSpacing

    🔧 Improvements

    • SlevomatCodingStandard.TypeHints.ParameterTypeHint: MissingTraversableTypeHintSpecification is not reported when promoted property has @var annotation

    v8.1.0

    Compare Source

    🔧 Improvements

    • SlevomatCodingStandard.Classes.PropertyDeclaration: New option checkPromoted to enable check of promoted properties
    • SlevomatCodingStandard.Classes.PropertyDeclaration: New option enableMultipleSpacesBetweenModifiersCheck to enable check of spaces between property modifiers
    • SlevomatCodingStandard.Classes.PropertyDeclaration: Improved error messages
    • SlevomatCodingStandard.Classes.ForbiddenPublicProperty: New option checkPromoted to enable check of promoted properties

    🐛 Fixes

    • SlevomatCodingStandard.TypeHints.PropertyTypeHint: Fix inconsistent enableIntersectionTypeHint (thanks to @​schlndh)

    v8.0.1

    Compare Source

    🐛 Fixes

    • Group use statements are ignored - we don't support them
    • SlevomatCodingStandard.PHP.UselessParentheses: Fixed false positive
    • SlevomatCodingStandard.TypeHints.ParameterTypeHint: Fixed internal error (thanks to @​schlndh)

    v8.0.0

    Compare Source

    🔧 Improvements

    • Support for intersection types
    • Support for readonly properties
    • Support for enums
    • Support for never type hint
    • Support for more unofficial type hints
    • SlevomatCodingStandard.Classes.PropertyDeclaration: Checks also order of modifiers
    • SlevomatCodingStandard.Classes.ClassStructure: Support for enum cases and readonly properties

    🐛 Fixes

    • SlevomatCodingStandard.Classes.PropertyDeclaration: Fixed missing support for only static property
    • SlevomatCodingStandard.TypeHints.PropertyTypeHint: Fixed missing support for only static property
    • SlevomatCodingStandard.Commenting.EmptyComment: Fixed internal error
    • SlevomatCodingStandard.Classes.ForbiddenPublicProperty: Fixed internal error
    • SlevomatCodingStandard.Namespaces.FullyQualifiedClassNameInAnnotation: Fixed false positives for @psalm-import-type in @psalm-var
    • SlevomatCodingStandard.PHP.RequireExplicitAssertion: Ignore unsupported unofficial type hints

    ⚠️BC breaks

    • SlevomatCodingStandard.TypeHints.PropertyTypeHintSpacing renamed to SlevomatCodingStandard.Classes.PropertyDeclaration
    • SlevomatCodingStandard.Classes.ClassStructure: Removed option enableFinalMethods
    • Removed error SlevomatCodingStandard.Namespaces.UnusedUses.MismatchingCaseSensitivity

    Configuration

    📅 Schedule: Branch creation - "before 3am on Monday" (UTC), Automerge - At any time (no schedule defined).

    🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    👻 Immortal: This PR will be recreated if closed unmerged. Get config help if that's undesired.


    • [ ] If you want to rebase/retry this PR, check this box

    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 1
  • Inconsistent behavior with `class_string` of mocks for intersection types

    Inconsistent behavior with `class_string` of mocks for intersection types

    I have not been able to create a working example for this on the PHPStan playground as this bug involves PHPUnit and the phpstan-phpunit package.

    We have a class with a generator function that looks like this:

        /**
         * Creates an instance of a class taking into account the class-extensions
         * API of TYPO3. USE THIS method instead of the PHP "new" keyword.
         * Eg. "$obj = new myclass;" should be "$obj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance("myclass")" instead!
         *
         * You can also pass arguments for a constructor:
         * \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\myClass::class, $arg1, $arg2, ..., $argN)
         *
         * @template T of object
         * @param class-string<T> $className name of the class to instantiate, must not be empty and not start with a backslash
         * @param array<int, mixed> $constructorArguments Arguments for the constructor
         * @return T the created instance
         */
        public static function makeInstance($className, ...$constructorArguments)
        {…}
    

    One of the tests for this method looks like this:

        /**
         * @test
         */
        public function makeInstanceReturnsClassInstance(): void
        {
            $className = get_class($this->getMockBuilder('foo')->getMock());
            self::assertInstanceOf($className, GeneralUtility::makeInstance($className));
        }
    

    PHPStan (or phpstan-phpunit) now seems to mix up two different representations of a class string for a intersection types (which both look plausible to me, but they're not the same to PHPStan):

      3123   Parameter #1 $className of static method TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance() expects                                                       
             class-string<foo&PHPUnit\Framework\MockObject\MockObject>,
             class-string<foo>&class-string<PHPUnit\Framework\MockObject\MockObject> given.   
    
    opened by oliverklee 1
  • Wrong types for `assertIsNotNumeric`

    Wrong types for `assertIsNotNumeric`

    The following TestCase will cause PHPStan to report a false positive.

    <?php declare(strict_types=1);
    
    use PHPUnit\Framework\TestCase;
    
    /**
     * @phpstan-return non-empty-string
     */
    function someFunction(): string {
    	return '10';
    }
    
    final class MyTest extends TestCase {
    	public function testGeneration(): void {
    		self::assertIsNotNumeric(
    			someFunction(),
    			'This expectation message is misinterpreted as the "actual" param.'
    		);
    	}
    }
    

    The false positive:

    Call to static method PHPUnit\Framework\Assert::assertIsNotNumeric() with non-empty-string and 'This expectation…' will always evaluate to true.

    opened by ZebulanStanphill 4
  • Dependency Dashboard

    Dependency Dashboard

    This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

    Awaiting Schedule

    These updates are awaiting their schedule. Click on a checkbox to get an update now.

    • [ ] Update dependency consistence-community/coding-standard to v3.11.2

    Open

    These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

    Detected dependencies

    composer
    build-cs/composer.json
    • consistence-community/coding-standard ^3.10
    • dealerdirect/phpcodesniffer-composer-installer ^0.7.0
    • slevomat/coding-standard ^7.0
    composer.json
    • php ^7.2 || ^8.0
    • phpstan/phpstan ^1.9.3
    • nikic/php-parser ^4.13.0
    • php-parallel-lint/php-parallel-lint ^1.2
    • phpstan/phpstan-strict-rules ^1.0
    • phpunit/phpunit ^9.5
    github-actions
    .github/workflows/build.yml
    • actions/checkout v3
    • shivammathur/setup-php v2
    • actions/checkout v3
    • shivammathur/setup-php v2
    • actions/checkout v3
    • shivammathur/setup-php v2
    • actions/checkout v3
    • shivammathur/setup-php v2
    .github/workflows/create-tag.yml
    • actions/checkout v3
    • WyriHaximus/github-action-get-previous-tag v1
    • WyriHaximus/github-action-next-semvers v1
    • rickstaa/action-create-tag v1
    • rickstaa/action-create-tag v1
    .github/workflows/lock-closed-issues.yml
    • dessant/lock-threads v4
    .github/workflows/release-toot.yml
    • cbrgm/mastodon-github-action v1
    .github/workflows/release-tweet.yml
    • Eomm/why-don-t-you-tweet v1
    .github/workflows/release.yml
    • actions/checkout v3
    • metcalfc/changelog-generator v4.0.1
    • actions/create-release v1

    • [ ] Check this box to trigger a request for Renovate to run again on this repository
    opened by renovate[bot] 0
Releases(1.3.3)
Owner
PHPStan
PHP Static Analysis Tool - discover bugs in your code without running it!
PHPStan
Qase-phpunit - Qase TMS PHPUnit reporter.

Qase TMS PHPUnit reporter Publish results simple and easy. How to integrate composer require qase/phpunit-reporter Example of usage The PHPUnit report

Qase TMS 6 Nov 24, 2022
Mockery - Designed as a drop in alternative to PHPUnit's phpunit-mock-objects library

Mockery Mockery is a simple yet flexible PHP mock object framework for use in unit testing with PHPUnit, PHPSpec or any other testing framework. Its c

Mockery 10.3k Jan 1, 2023
Rector upgrades rules for PHPUnit

Rector Rules for PHPUnit See available PHPUnit rules Install composer require rector/rector-phpunit Use Sets To add a set to your config, use Rector\P

RectorPHP 34 Dec 27, 2022
The most powerful and flexible mocking framework for PHPUnit / Codeception.

AspectMock AspectMock is not an ordinary PHP mocking framework. With the power of Aspect Oriented programming and the awesome Go-AOP library, AspectMo

Codeception Testing Framework 777 Dec 12, 2022
PHP libraries that makes Selenium WebDriver + PHPUnit functional testing easy and robust

Steward: easy and robust testing with Selenium WebDriver + PHPUnit Steward is a set of libraries made to simplify writing and running robust functiona

LMC s.r.o. 219 Dec 17, 2022
Additional PHPUnit assertions and helper functions

Jasny PHPUnit extension Additional functionality for PHPUnit. Callback mock - assert that callback is called with correct arguments. Safe mocks - disa

Arnold Daniels 2 Jul 24, 2022
:computer: Parallel testing for PHPUnit

ParaTest The objective of ParaTest is to support parallel testing in PHPUnit. Provided you have well-written PHPUnit tests, you can drop paratest in y

null 2k Dec 31, 2022
vfsStream is a stream wrapper for a virtual file system that may be helpful in unit tests to mock the real file system. It can be used with any unit test framework, like PHPUnit or SimpleTest.

vfsStream vfsStream is a stream wrapper for a virtual file system that may be helpful in unit tests to mock the real file system. It can be used with

null 1.4k Dec 23, 2022
Add mocking capabilities to Pest or PHPUnit

This repository contains the Pest Plugin Mock. The Mocking API can be used in regular PHPUnit projects. For that, you just have to run the following c

PEST 16 Dec 3, 2022
A sample RESTful API in Laravel with PHPunit test.

Laravel PHP Framework URL | URI | Action |

Fasil 9 Jul 11, 2020
PHPUnit Application Architecture Test

PHPUnit Application Architecture Test Idea: write architecture tests as well as feature and unit tests Installation Install via composer composer requ

null 19 Dec 11, 2022
PHPUnit to Pest Converter

PestConverter PestConverter is a PHP library for converting PHPUnit tests to Pest tests. Before use Before using this converter, make sure your files

null 10 Nov 21, 2022
Allows the running of PHPUnit within ExpressionEngine

EE Unit Tests EE Unit Tests is an Add-on for ExpressionEngine that allows developers to execute unit tests from the Command Line. EE Unit Tests uses P

Eric Lamb 6 Jan 14, 2022
PHPUnit extension for database interaction testing.

This extension is no longer maintained DbUnit PHPUnit extension for database interaction testing. Installation Composer If you use Composer to manage

Sebastian Bergmann 224 Aug 20, 2022
Mock implementation of the Translation package, for testing with PHPUnit

PoP Translation - Mock Mock implementation of the Translation package, for testing with PHPUnit Install Via Composer composer require getpop/translati

PoP 1 Jan 13, 2022
Magento PHPUnit Integration

Magento PHPUnit Integration Magento is a quite complex platform without built in unit test suite, so the code is not oriented on running tests over it

EcomDev B.V. 303 Dec 18, 2022
The objective of ParaTest is to support parallel testing in PHPUnit

The objective of ParaTest is to support parallel testing in PHPUnit. Provided you have well-written PHPUnit tests, you can drop paratest in your project and start using it with no additional bootstrap or configurations!

null 2k Dec 31, 2022
Report high memory usage PHPUnit tests: Managed by opg-org-infra & Terraform

phpunit-memory-usage Report high memory usage PHPUnit tests: Managed by opg-org-infra & Terraform Configuration Add into the phpunit.xml extensions se

Ministry of Justice 2 Aug 4, 2022