diff --git a/src/Symfony/Component/PasswordHasher/Tests/Command/UserPasswordHashCommandTest.php b/src/Symfony/Component/PasswordHasher/Tests/Command/UserPasswordHashCommandTest.php index 253403d218205..819a92899962b 100644 --- a/src/Symfony/Component/PasswordHasher/Tests/Command/UserPasswordHashCommandTest.php +++ b/src/Symfony/Component/PasswordHasher/Tests/Command/UserPasswordHashCommandTest.php @@ -277,10 +277,11 @@ public function testNonInteractiveEncodePasswordUsesFirstUserClass() public function testThrowsExceptionOnNoConfiguredHashers() { + $tester = new CommandTester(new UserPasswordHashCommand($this->getMockBuilder(PasswordHasherFactoryInterface::class)->getMock(), [])); + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('There are no configured password hashers for the "security" extension.'); - $tester = new CommandTester(new UserPasswordHashCommand($this->getMockBuilder(PasswordHasherFactoryInterface::class)->getMock(), [])); $tester->execute([ 'password' => 'password', ], ['interactive' => false]); diff --git a/src/Symfony/Component/PasswordHasher/Tests/Hasher/MessageDigestPasswordHasherTest.php b/src/Symfony/Component/PasswordHasher/Tests/Hasher/MessageDigestPasswordHasherTest.php index 6abcb797b9c27..2e7a192bf8ad2 100644 --- a/src/Symfony/Component/PasswordHasher/Tests/Hasher/MessageDigestPasswordHasherTest.php +++ b/src/Symfony/Component/PasswordHasher/Tests/Hasher/MessageDigestPasswordHasherTest.php @@ -38,16 +38,19 @@ public function testHash() public function testHashAlgorithmDoesNotExist() { - $this->expectException(\LogicException::class); $hasher = new MessageDigestPasswordHasher('foobar'); + + $this->expectException(\LogicException::class); + $hasher->hash('password', ''); } public function testHashLength() { - $this->expectException(InvalidPasswordException::class); $hasher = new MessageDigestPasswordHasher(); + $this->expectException(InvalidPasswordException::class); + $hasher->hash(str_repeat('a', 5000), 'salt'); } diff --git a/src/Symfony/Component/PasswordHasher/Tests/Hasher/PasswordHasherFactoryTest.php b/src/Symfony/Component/PasswordHasher/Tests/Hasher/PasswordHasherFactoryTest.php index be60a3e163c8b..e2c2b8305fc22 100644 --- a/src/Symfony/Component/PasswordHasher/Tests/Hasher/PasswordHasherFactoryTest.php +++ b/src/Symfony/Component/PasswordHasher/Tests/Hasher/PasswordHasherFactoryTest.php @@ -130,7 +130,6 @@ public function testGetNullNamedHasherForHasherAware() public function testGetInvalidNamedHasherForHasherAware() { - $this->expectException(\RuntimeException::class); $factory = new PasswordHasherFactory([ HasherAwareUser::class => new MessageDigestPasswordHasher('sha1'), 'hasher_name' => new MessageDigestPasswordHasher('sha256'), @@ -138,6 +137,9 @@ public function testGetInvalidNamedHasherForHasherAware() $user = new HasherAwareUser(); $user->hasherName = 'invalid_hasher_name'; + + $this->expectException(\RuntimeException::class); + $factory->getPasswordHasher($user); } diff --git a/src/Symfony/Component/PasswordHasher/Tests/Hasher/Pbkdf2PasswordHasherTest.php b/src/Symfony/Component/PasswordHasher/Tests/Hasher/Pbkdf2PasswordHasherTest.php index 05785b2141c46..76279b3589eef 100644 --- a/src/Symfony/Component/PasswordHasher/Tests/Hasher/Pbkdf2PasswordHasherTest.php +++ b/src/Symfony/Component/PasswordHasher/Tests/Hasher/Pbkdf2PasswordHasherTest.php @@ -38,16 +38,19 @@ public function testHash() public function testHashAlgorithmDoesNotExist() { - $this->expectException(\LogicException::class); $hasher = new Pbkdf2PasswordHasher('foobar'); + + $this->expectException(\LogicException::class); + $hasher->hash('password', ''); } public function testHashLength() { - $this->expectException(InvalidPasswordException::class); $hasher = new Pbkdf2PasswordHasher('foobar'); + $this->expectException(InvalidPasswordException::class); + $hasher->hash(str_repeat('a', 5000), 'salt'); } diff --git a/src/Symfony/Component/PasswordHasher/Tests/Hasher/SodiumPasswordHasherTest.php b/src/Symfony/Component/PasswordHasher/Tests/Hasher/SodiumPasswordHasherTest.php index 3dc97c768f6f1..302b479be0c75 100644 --- a/src/Symfony/Component/PasswordHasher/Tests/Hasher/SodiumPasswordHasherTest.php +++ b/src/Symfony/Component/PasswordHasher/Tests/Hasher/SodiumPasswordHasherTest.php @@ -52,8 +52,8 @@ public function testNonArgonValidation() public function testHashLength() { $this->expectException(InvalidPasswordException::class); - $hasher = new SodiumPasswordHasher(); - $hasher->hash(str_repeat('a', 4097)); + + (new SodiumPasswordHasher())->hash(str_repeat('a', 4097)); } public function testCheckPasswordLength() diff --git a/src/Symfony/Component/Process/Tests/ProcessTest.php b/src/Symfony/Component/Process/Tests/ProcessTest.php index dfb4fd2936959..63ad90d95356a 100644 --- a/src/Symfony/Component/Process/Tests/ProcessTest.php +++ b/src/Symfony/Component/Process/Tests/ProcessTest.php @@ -328,11 +328,13 @@ public function testSetInputWhileRunningThrowsAnException() /** * @dataProvider provideInvalidInputValues */ - public function testInvalidInput($value) + public function testInvalidInput(array|object $value) { + $process = $this->getProcess('foo'); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('"Symfony\Component\Process\Process::setInput" only accepts strings, Traversable objects or stream resources.'); - $process = $this->getProcess('foo'); + $process->setInput($value); } @@ -347,7 +349,7 @@ public static function provideInvalidInputValues() /** * @dataProvider provideInputValues */ - public function testValidInput($expected, $value) + public function testValidInput(?string $expected, null|float|string $value) { $process = $this->getProcess('foo'); $process->setInput($value); @@ -593,8 +595,10 @@ public function testSuccessfulMustRunHasCorrectExitCode() public function testMustRunThrowsException() { - $this->expectException(ProcessFailedException::class); $process = $this->getProcess('exit 1'); + + $this->expectException(ProcessFailedException::class); + $process->mustRun(); } @@ -972,9 +976,11 @@ public function testExitCodeIsAvailableAfterSignal() public function testSignalProcessNotRunning() { + $process = $this->getProcess('foo'); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Cannot send signal on a non running process.'); - $process = $this->getProcess('foo'); + $process->signal(1); // SIGHUP } @@ -1062,20 +1068,24 @@ public function testDisableOutputDisablesTheOutput() public function testDisableOutputWhileRunningThrowsException() { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Disabling output while the process is running is not possible.'); $p = $this->getProcessForCode('sleep(39);'); $p->start(); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Disabling output while the process is running is not possible.'); + $p->disableOutput(); } public function testEnableOutputWhileRunningThrowsException() { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Enabling output while the process is running is not possible.'); $p = $this->getProcessForCode('sleep(40);'); $p->disableOutput(); $p->start(); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Enabling output while the process is running is not possible.'); + $p->enableOutput(); } @@ -1091,19 +1101,23 @@ public function testEnableOrDisableOutputAfterRunDoesNotThrowException() public function testDisableOutputWhileIdleTimeoutIsSet() { - $this->expectException(LogicException::class); - $this->expectExceptionMessage('Output cannot be disabled while an idle timeout is set.'); $process = $this->getProcess('foo'); $process->setIdleTimeout(1); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Output cannot be disabled while an idle timeout is set.'); + $process->disableOutput(); } public function testSetIdleTimeoutWhileOutputIsDisabled() { - $this->expectException(LogicException::class); - $this->expectExceptionMessage('timeout cannot be set while the output is disabled.'); $process = $this->getProcess('foo'); $process->disableOutput(); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('timeout cannot be set while the output is disabled.'); + $process->setIdleTimeout(1); } @@ -1119,11 +1133,13 @@ public function testSetNullIdleTimeoutWhileOutputIsDisabled() */ public function testGetOutputWhileDisabled($fetchMethod) { - $this->expectException(LogicException::class); - $this->expectExceptionMessage('Output has been disabled.'); $p = $this->getProcessForCode('sleep(41);'); $p->disableOutput(); $p->start(); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Output has been disabled.'); + $p->{$fetchMethod}(); } @@ -1523,17 +1539,21 @@ public function testPreparedCommandWithQuoteInIt() public function testPreparedCommandWithMissingValue() { + $p = Process::fromShellCommandline('echo "${:abc}"'); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Command line is missing a value for parameter "abc": echo "${:abc}"'); - $p = Process::fromShellCommandline('echo "${:abc}"'); + $p->run(null, ['bcd' => 'BCD']); } public function testPreparedCommandWithNoValues() { + $p = Process::fromShellCommandline('echo "${:abc}"'); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Command line is missing a value for parameter "abc": echo "${:abc}"'); - $p = Process::fromShellCommandline('echo "${:abc}"'); + $p->run(null, []); } diff --git a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorArrayAccessTestCase.php b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorArrayAccessTestCase.php index 90d931873e667..9cc79f2c68184 100644 --- a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorArrayAccessTestCase.php +++ b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorArrayAccessTestCase.php @@ -53,13 +53,14 @@ public function testGetValue($collection, $path, $value) public function testGetValueFailsIfNoSuchIndex() { - $this->expectException(NoSuchIndexException::class); $this->propertyAccessor = PropertyAccess::createPropertyAccessorBuilder() ->enableExceptionOnInvalidIndex() ->getPropertyAccessor(); $object = static::getContainer(['firstName' => 'Bernhard']); + $this->expectException(NoSuchIndexException::class); + $this->propertyAccessor->getValue($object, '[lastName]'); } diff --git a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorCollectionTestCase.php b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorCollectionTestCase.php index 742889ade2e01..f97260363c012 100644 --- a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorCollectionTestCase.php +++ b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorCollectionTestCase.php @@ -156,8 +156,6 @@ public function testSetValueCallsAdderAndRemoverForNestedCollections() public function testSetValueFailsIfNoAdderNorRemoverFound() { - $this->expectException(NoSuchPropertyException::class); - $this->expectExceptionMessageMatches('/Could not determine access type for property "axes" in class "Mock_PropertyAccessorCollectionTestCase_CarNoAdderAndRemover_[^"]*"./'); $car = $this->createMock(__CLASS__.'_CarNoAdderAndRemover'); $axesBefore = $this->getContainer([1 => 'second', 3 => 'fourth']); $axesAfter = $this->getContainer([0 => 'first', 1 => 'second', 2 => 'third']); @@ -166,6 +164,9 @@ public function testSetValueFailsIfNoAdderNorRemoverFound() ->method('getAxes') ->willReturn($axesBefore); + $this->expectException(NoSuchPropertyException::class); + $this->expectExceptionMessageMatches('/Could not determine access type for property "axes" in class "Mock_PropertyAccessorCollectionTestCase_CarNoAdderAndRemover_[^"]*"./'); + $this->propertyAccessor->setValue($car, 'axes', $axesAfter); } @@ -195,9 +196,10 @@ public function testIsWritableReturnsFalseIfNoAdderNorRemoverExists() public function testSetValueFailsIfAdderAndRemoverExistButValueIsNotTraversable() { + $car = new PropertyAccessorCollectionTestCase_Car(); + $this->expectException(NoSuchPropertyException::class); $this->expectExceptionMessageMatches('/The property "axes" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\PropertyAccessorCollectionTestCase_Car" can be defined with the methods "addAxis\(\)", "removeAxis\(\)" but the new value must be an array or an instance of \\\Traversable\./'); - $car = new PropertyAccessorCollectionTestCase_Car(); $this->propertyAccessor->setValue($car, 'axes', 'Not an array or Traversable'); } diff --git a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php index 7b4dfba0759f5..73c55be83133f 100644 --- a/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php +++ b/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php @@ -83,7 +83,7 @@ public static function getPathsWithMissingIndex() /** * @dataProvider getValidReadPropertyPaths */ - public function testGetValue($objectOrArray, $path, $value) + public function testGetValue(array|object $objectOrArray, string $path, ?string $value) { $this->assertSame($value, $this->propertyAccessor->getValue($objectOrArray, $path)); } @@ -91,7 +91,7 @@ public function testGetValue($objectOrArray, $path, $value) /** * @dataProvider getPathsWithMissingProperty */ - public function testGetValueThrowsExceptionIfPropertyNotFound($objectOrArray, $path) + public function testGetValueThrowsExceptionIfPropertyNotFound(array|object $objectOrArray, string $path) { $this->expectException(NoSuchPropertyException::class); $this->propertyAccessor->getValue($objectOrArray, $path); @@ -100,7 +100,7 @@ public function testGetValueThrowsExceptionIfPropertyNotFound($objectOrArray, $p /** * @dataProvider getPathsWithMissingProperty */ - public function testGetValueReturnsNullIfPropertyNotFoundAndExceptionIsDisabled($objectOrArray, $path) + public function testGetValueReturnsNullIfPropertyNotFoundAndExceptionIsDisabled(array|object $objectOrArray, string $path) { $this->propertyAccessor = new PropertyAccessor(PropertyAccessor::MAGIC_GET | PropertyAccessor::MAGIC_SET, PropertyAccessor::DO_NOT_THROW); @@ -110,7 +110,7 @@ public function testGetValueReturnsNullIfPropertyNotFoundAndExceptionIsDisabled( /** * @dataProvider getPathsWithMissingIndex */ - public function testGetValueThrowsNoExceptionIfIndexNotFound($objectOrArray, $path) + public function testGetValueThrowsNoExceptionIfIndexNotFound(array|object $objectOrArray, string $path) { $this->assertNull($this->propertyAccessor->getValue($objectOrArray, $path)); } @@ -118,10 +118,12 @@ public function testGetValueThrowsNoExceptionIfIndexNotFound($objectOrArray, $pa /** * @dataProvider getPathsWithMissingIndex */ - public function testGetValueThrowsExceptionIfIndexNotFoundAndIndexExceptionsEnabled($objectOrArray, $path) + public function testGetValueThrowsExceptionIfIndexNotFoundAndIndexExceptionsEnabled(array|object $objectOrArray, string $path) { - $this->expectException(NoSuchIndexException::class); $this->propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS, PropertyAccessor::THROW_ON_INVALID_INDEX | PropertyAccessor::THROW_ON_INVALID_PROPERTY_PATH); + + $this->expectException(NoSuchIndexException::class); + $this->propertyAccessor->getValue($objectOrArray, $path); } @@ -143,9 +145,6 @@ public function testGetValueThrowsExceptionIfUninitializedPropertyWithGetter() public function testGetValueThrowsExceptionIfUninitializedPropertyWithGetterOfAnonymousClass() { - $this->expectException(UninitializedPropertyException::class); - $this->expectExceptionMessage('The method "class@anonymous::getUninitialized()" returned "null", but expected type "array". Did you forget to initialize a property or to make the return type nullable using "?array"?'); - $object = new class() { private $uninitialized; @@ -155,14 +154,14 @@ public function getUninitialized(): array } }; + $this->expectException(UninitializedPropertyException::class); + $this->expectExceptionMessage('The method "class@anonymous::getUninitialized()" returned "null", but expected type "array". Did you forget to initialize a property or to make the return type nullable using "?array"?'); + $this->propertyAccessor->getValue($object, 'uninitialized'); } public function testGetValueThrowsExceptionIfUninitializedNotNullablePropertyWithGetterOfAnonymousClass() { - $this->expectException(UninitializedPropertyException::class); - $this->expectExceptionMessage('The property "class@anonymous::$uninitialized" is not readable because it is typed "string". You should initialize it or declare a default value instead.'); - $object = new class() { private string $uninitialized; @@ -172,18 +171,21 @@ public function getUninitialized(): string } }; + $this->expectException(UninitializedPropertyException::class); + $this->expectExceptionMessage('The property "class@anonymous::$uninitialized" is not readable because it is typed "string". You should initialize it or declare a default value instead.'); + $this->propertyAccessor->getValue($object, 'uninitialized'); } public function testGetValueThrowsExceptionIfUninitializedPropertyOfAnonymousClass() { - $this->expectException(UninitializedPropertyException::class); - $this->expectExceptionMessage('The property "class@anonymous::$uninitialized" is not readable because it is typed "string". You should initialize it or declare a default value instead.'); - $object = new class() { public string $uninitialized; }; + $this->expectException(UninitializedPropertyException::class); + $this->expectExceptionMessage('The property "class@anonymous::$uninitialized" is not readable because it is typed "string". You should initialize it or declare a default value instead.'); + $this->propertyAccessor->getValue($object, 'uninitialized'); } @@ -205,9 +207,6 @@ public function testGetValueThrowsExceptionIfUninitializedNotNullablePropertyWit public function testGetValueThrowsExceptionIfUninitializedPropertyWithGetterOfAnonymousStdClass() { - $this->expectException(UninitializedPropertyException::class); - $this->expectExceptionMessage('The method "stdClass@anonymous::getUninitialized()" returned "null", but expected type "array". Did you forget to initialize a property or to make the return type nullable using "?array"?'); - $object = new class() extends \stdClass { private $uninitialized; @@ -217,16 +216,19 @@ public function getUninitialized(): array } }; + $this->expectException(UninitializedPropertyException::class); + $this->expectExceptionMessage('The method "stdClass@anonymous::getUninitialized()" returned "null", but expected type "array". Did you forget to initialize a property or to make the return type nullable using "?array"?'); + $this->propertyAccessor->getValue($object, 'uninitialized'); } public function testGetValueThrowsExceptionIfUninitializedPropertyWithGetterOfAnonymousChildClass() { + $object = new class() extends UninitializedPrivateProperty {}; + $this->expectException(UninitializedPropertyException::class); $this->expectExceptionMessage('The method "Symfony\Component\PropertyAccess\Tests\Fixtures\UninitializedPrivateProperty@anonymous::getUninitialized()" returned "null", but expected type "array". Did you forget to initialize a property or to make the return type nullable using "?array"?'); - $object = new class() extends \Symfony\Component\PropertyAccess\Tests\Fixtures\UninitializedPrivateProperty {}; - $this->propertyAccessor->getValue($object, 'uninitialized'); } @@ -312,7 +314,7 @@ public function testGetValueReadsMagicCallThatReturnsConstant() /** * @dataProvider getValidWritePropertyPaths */ - public function testSetValue($objectOrArray, $path) + public function testSetValue(array|object $objectOrArray, string $path) { $this->propertyAccessor->setValue($objectOrArray, $path, 'Updated'); @@ -322,7 +324,7 @@ public function testSetValue($objectOrArray, $path) /** * @dataProvider getPathsWithMissingProperty */ - public function testSetValueThrowsExceptionIfPropertyNotFound($objectOrArray, $path) + public function testSetValueThrowsExceptionIfPropertyNotFound(array|object $objectOrArray, string $path) { $this->expectException(NoSuchPropertyException::class); $this->propertyAccessor->setValue($objectOrArray, $path, 'Updated'); @@ -331,7 +333,7 @@ public function testSetValueThrowsExceptionIfPropertyNotFound($objectOrArray, $p /** * @dataProvider getPathsWithMissingIndex */ - public function testSetValueThrowsNoExceptionIfIndexNotFound($objectOrArray, $path) + public function testSetValueThrowsNoExceptionIfIndexNotFound(array|object $objectOrArray, string $path) { $this->propertyAccessor->setValue($objectOrArray, $path, 'Updated'); @@ -341,7 +343,7 @@ public function testSetValueThrowsNoExceptionIfIndexNotFound($objectOrArray, $pa /** * @dataProvider getPathsWithMissingIndex */ - public function testSetValueThrowsNoExceptionIfIndexNotFoundAndIndexExceptionsEnabled($objectOrArray, $path) + public function testSetValueThrowsNoExceptionIfIndexNotFoundAndIndexExceptionsEnabled(array|object $objectOrArray, string $path) { $this->propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS, PropertyAccessor::THROW_ON_INVALID_INDEX | PropertyAccessor::THROW_ON_INVALID_PROPERTY_PATH); $this->propertyAccessor->setValue($objectOrArray, $path, 'Updated'); @@ -351,9 +353,10 @@ public function testSetValueThrowsNoExceptionIfIndexNotFoundAndIndexExceptionsEn public function testSetValueThrowsExceptionIfNotArrayAccess() { - $this->expectException(NoSuchIndexException::class); $object = new \stdClass(); + $this->expectException(NoSuchIndexException::class); + $this->propertyAccessor->setValue($object, '[index]', 'Updated'); } @@ -368,27 +371,30 @@ public function testSetValueUpdatesMagicSet() public function testSetValueIgnoresMagicSet() { - $this->expectException(NoSuchPropertyException::class); $propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS); $author = new TestClassMagicGet('Bernhard'); + $this->expectException(NoSuchPropertyException::class); + $propertyAccessor->setValue($author, 'magicProperty', 'Updated'); } public function testSetValueThrowsExceptionIfThereAreMissingParameters() { - $this->expectException(NoSuchPropertyException::class); $object = new TestClass('Bernhard'); + $this->expectException(NoSuchPropertyException::class); + $this->propertyAccessor->setValue($object, 'publicAccessorWithMoreRequiredParameters', 'Updated'); } public function testSetValueDoesNotUpdateMagicCallByDefault() { - $this->expectException(NoSuchPropertyException::class); $author = new TestClassMagicCall('Bernhard'); + $this->expectException(NoSuchPropertyException::class); + $this->propertyAccessor->setValue($author, 'magicCallProperty', 'Updated'); } @@ -412,7 +418,7 @@ public function testGetValueWhenArrayValueIsNull() /** * @dataProvider getValidReadPropertyPaths */ - public function testIsReadable($objectOrArray, $path) + public function testIsReadable(array|object $objectOrArray, string $path) { $this->assertTrue($this->propertyAccessor->isReadable($objectOrArray, $path)); } @@ -420,7 +426,7 @@ public function testIsReadable($objectOrArray, $path) /** * @dataProvider getPathsWithMissingProperty */ - public function testIsReadableReturnsFalseIfPropertyNotFound($objectOrArray, $path) + public function testIsReadableReturnsFalseIfPropertyNotFound(array|object $objectOrArray, string $path) { $this->assertFalse($this->propertyAccessor->isReadable($objectOrArray, $path)); } @@ -428,7 +434,7 @@ public function testIsReadableReturnsFalseIfPropertyNotFound($objectOrArray, $pa /** * @dataProvider getPathsWithMissingIndex */ - public function testIsReadableReturnsTrueIfIndexNotFound($objectOrArray, $path) + public function testIsReadableReturnsTrueIfIndexNotFound(array|object $objectOrArray, string $path) { // Non-existing indices can be read. In this case, null is returned $this->assertTrue($this->propertyAccessor->isReadable($objectOrArray, $path)); @@ -437,7 +443,7 @@ public function testIsReadableReturnsTrueIfIndexNotFound($objectOrArray, $path) /** * @dataProvider getPathsWithMissingIndex */ - public function testIsReadableReturnsFalseIfIndexNotFoundAndIndexExceptionsEnabled($objectOrArray, $path) + public function testIsReadableReturnsFalseIfIndexNotFoundAndIndexExceptionsEnabled(array|object $objectOrArray, string $path) { $this->propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS, PropertyAccessor::THROW_ON_INVALID_INDEX | PropertyAccessor::THROW_ON_INVALID_PROPERTY_PATH); @@ -465,7 +471,7 @@ public function testIsReadableRecognizesMagicCallIfEnabled() /** * @dataProvider getValidWritePropertyPaths */ - public function testIsWritable($objectOrArray, $path) + public function testIsWritable(array|object $objectOrArray, string $path) { $this->assertTrue($this->propertyAccessor->isWritable($objectOrArray, $path)); } @@ -473,7 +479,7 @@ public function testIsWritable($objectOrArray, $path) /** * @dataProvider getPathsWithMissingProperty */ - public function testIsWritableReturnsFalseIfPropertyNotFound($objectOrArray, $path) + public function testIsWritableReturnsFalseIfPropertyNotFound(array|object $objectOrArray, string $path) { $this->assertFalse($this->propertyAccessor->isWritable($objectOrArray, $path)); } @@ -481,7 +487,7 @@ public function testIsWritableReturnsFalseIfPropertyNotFound($objectOrArray, $pa /** * @dataProvider getPathsWithMissingIndex */ - public function testIsWritableReturnsTrueIfIndexNotFound($objectOrArray, $path) + public function testIsWritableReturnsTrueIfIndexNotFound(array|object $objectOrArray, string $path) { // Non-existing indices can be written. Arrays are created on-demand. $this->assertTrue($this->propertyAccessor->isWritable($objectOrArray, $path)); @@ -490,7 +496,7 @@ public function testIsWritableReturnsTrueIfIndexNotFound($objectOrArray, $path) /** * @dataProvider getPathsWithMissingIndex */ - public function testIsWritableReturnsTrueIfIndexNotFoundAndIndexExceptionsEnabled($objectOrArray, $path) + public function testIsWritableReturnsTrueIfIndexNotFoundAndIndexExceptionsEnabled(array|object $objectOrArray, string $path) { $this->propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS, PropertyAccessor::THROW_ON_INVALID_INDEX | PropertyAccessor::THROW_ON_INVALID_PROPERTY_PATH); @@ -588,7 +594,7 @@ public static function getNullSafeIndexPaths(): iterable /** * @dataProvider getNullSafeIndexPaths */ - public function testNullSafeIndexWithThrowOnInvalidIndex($objectOrArray, $path, $value) + public function testNullSafeIndexWithThrowOnInvalidIndex(array|object $objectOrArray, string $path, ?string $value) { $this->propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS, PropertyAccessor::THROW_ON_INVALID_INDEX | PropertyAccessor::THROW_ON_INVALID_PROPERTY_PATH); @@ -652,18 +658,20 @@ public function testIsWritableForReferenceChainIssue($object, $path, $value) public function testThrowTypeError() { + $object = new TypeHinted(); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Expected argument of type "DateTimeImmutable", "string" given at property path "date"'); - $object = new TypeHinted(); $this->propertyAccessor->setValue($object, 'date', 'This is a string, \DateTimeImmutable expected.'); } public function testThrowTypeErrorWithNullArgument() { + $object = new TypeHinted(); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Expected argument of type "DateTimeImmutable", "null" given'); - $object = new TypeHinted(); $this->propertyAccessor->setValue($object, 'date', null); } @@ -713,9 +721,10 @@ public function testAttributeWithSpecialChars() public function testThrowTypeErrorWithInterface() { + $object = new TypeHinted(); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Expected argument of type "Countable", "string" given'); - $object = new TypeHinted(); $this->propertyAccessor->setValue($object, 'countable', 'This is a string, \Countable expected.'); } @@ -733,9 +742,10 @@ public function testAnonymousClassRead() public function testAnonymousClassReadThrowExceptionOnInvalidPropertyPath() { - $this->expectException(NoSuchPropertyException::class); $obj = $this->generateAnonymousClass('bar'); + $this->expectException(NoSuchPropertyException::class); + $this->propertyAccessor->getValue($obj, 'invalid_property'); } @@ -784,25 +794,28 @@ public function setFoo($foo) public function testThrowTypeErrorInsideSetterCall() { - $this->expectException(\TypeError::class); $object = new TestClassTypeErrorInsideCall(); + $this->expectException(\TypeError::class); + $this->propertyAccessor->setValue($object, 'property', 'foo'); } public function testDoNotDiscardReturnTypeError() { - $this->expectException(\TypeError::class); $object = new ReturnTyped(); + $this->expectException(\TypeError::class); + $this->propertyAccessor->setValue($object, 'foos', [new \DateTimeImmutable()]); } public function testDoNotDiscardReturnTypeErrorWhenWriterMethodIsMisconfigured() { - $this->expectException(\TypeError::class); $object = new ReturnTyped(); + $this->expectException(\TypeError::class); + $this->propertyAccessor->setValue($object, 'name', 'foo'); } @@ -850,41 +863,51 @@ public function testAdderAndRemoverArePreferredOverSetterForSameSingularAndPlura public function testAdderWithoutRemover() { + $object = new TestAdderRemoverInvalidMethods(); + $this->expectException(NoSuchPropertyException::class); $this->expectExceptionMessageMatches('/.*The add method "addFoo" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestAdderRemoverInvalidMethods" was found, but the corresponding remove method "removeFoo" was not found\./'); - $object = new TestAdderRemoverInvalidMethods(); + $this->propertyAccessor->setValue($object, 'foos', [1, 2]); } public function testRemoverWithoutAdder() { + $object = new TestAdderRemoverInvalidMethods(); + $this->expectException(NoSuchPropertyException::class); $this->expectExceptionMessageMatches('/.*The remove method "removeBar" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestAdderRemoverInvalidMethods" was found, but the corresponding add method "addBar" was not found\./'); - $object = new TestAdderRemoverInvalidMethods(); + $this->propertyAccessor->setValue($object, 'bars', [1, 2]); } public function testAdderAndRemoveNeedsTheExactParametersDefined() { + $object = new TestAdderRemoverInvalidArgumentLength(); + $this->expectException(NoSuchPropertyException::class); $this->expectExceptionMessageMatches('/.*The method "addFoo" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestAdderRemoverInvalidArgumentLength" requires 0 arguments, but should accept only 1\./'); - $object = new TestAdderRemoverInvalidArgumentLength(); + $this->propertyAccessor->setValue($object, 'foo', [1, 2]); } public function testSetterNeedsTheExactParametersDefined() { + $object = new TestAdderRemoverInvalidArgumentLength(); + $this->expectException(NoSuchPropertyException::class); $this->expectExceptionMessageMatches('/.*The method "setBar" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestAdderRemoverInvalidArgumentLength" requires 2 arguments, but should accept only 1\./'); - $object = new TestAdderRemoverInvalidArgumentLength(); + $this->propertyAccessor->setValue($object, 'bar', [1, 2]); } public function testSetterNeedsPublicAccess() { + $object = new TestClassSetValue(0); + $this->expectException(NoSuchPropertyException::class); $this->expectExceptionMessageMatches('/.*The method "setFoo" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestClassSetValue" was found but does not have public access./'); - $object = new TestClassSetValue(0); + $this->propertyAccessor->setValue($object, 'foo', 1); } diff --git a/src/Symfony/Component/PropertyAccess/Tests/PropertyPathBuilderTest.php b/src/Symfony/Component/PropertyAccess/Tests/PropertyPathBuilderTest.php index 948ca066cb8fb..fe21325b3d1af 100644 --- a/src/Symfony/Component/PropertyAccess/Tests/PropertyPathBuilderTest.php +++ b/src/Symfony/Component/PropertyAccess/Tests/PropertyPathBuilderTest.php @@ -185,7 +185,7 @@ public function testReplaceNegative() /** * @dataProvider provideInvalidOffsets */ - public function testReplaceDoesNotAllowInvalidOffsets($offset) + public function testReplaceDoesNotAllowInvalidOffsets(int $offset) { $this->expectException(\OutOfBoundsException::class); $this->builder->replace($offset, 1, new PropertyPath('new1[new2].new3')); diff --git a/src/Symfony/Component/PropertyAccess/Tests/PropertyPathTest.php b/src/Symfony/Component/PropertyAccess/Tests/PropertyPathTest.php index 40a9346088fda..9257229c3aebf 100644 --- a/src/Symfony/Component/PropertyAccess/Tests/PropertyPathTest.php +++ b/src/Symfony/Component/PropertyAccess/Tests/PropertyPathTest.php @@ -52,7 +52,7 @@ public static function providePathsContainingUnexpectedCharacters() /** * @dataProvider providePathsContainingUnexpectedCharacters */ - public function testUnexpectedCharacters($path) + public function testUnexpectedCharacters(string $path) { $this->expectException(InvalidPropertyPathException::class); new PropertyPath($path); @@ -137,17 +137,19 @@ public function testGetElement() public function testGetElementDoesNotAcceptInvalidIndices() { - $this->expectException(\OutOfBoundsException::class); $propertyPath = new PropertyPath('grandpa.parent[child]'); + $this->expectException(\OutOfBoundsException::class); + $propertyPath->getElement(3); } public function testGetElementDoesNotAcceptNegativeIndices() { - $this->expectException(\OutOfBoundsException::class); $propertyPath = new PropertyPath('grandpa.parent[child]'); + $this->expectException(\OutOfBoundsException::class); + $propertyPath->getElement(-1); } @@ -161,17 +163,19 @@ public function testIsProperty() public function testIsPropertyDoesNotAcceptInvalidIndices() { - $this->expectException(\OutOfBoundsException::class); $propertyPath = new PropertyPath('grandpa.parent[child]'); + $this->expectException(\OutOfBoundsException::class); + $propertyPath->isProperty(3); } public function testIsPropertyDoesNotAcceptNegativeIndices() { - $this->expectException(\OutOfBoundsException::class); $propertyPath = new PropertyPath('grandpa.parent[child]'); + $this->expectException(\OutOfBoundsException::class); + $propertyPath->isProperty(-1); } @@ -185,17 +189,19 @@ public function testIsIndex() public function testIsIndexDoesNotAcceptInvalidIndices() { - $this->expectException(\OutOfBoundsException::class); $propertyPath = new PropertyPath('grandpa.parent[child]'); + $this->expectException(\OutOfBoundsException::class); + $propertyPath->isIndex(3); } public function testIsIndexDoesNotAcceptNegativeIndices() { - $this->expectException(\OutOfBoundsException::class); $propertyPath = new PropertyPath('grandpa.parent[child]'); + $this->expectException(\OutOfBoundsException::class); + $propertyPath->isIndex(-1); } } diff --git a/src/Symfony/Component/RateLimiter/Tests/Policy/TokenBucketLimiterTest.php b/src/Symfony/Component/RateLimiter/Tests/Policy/TokenBucketLimiterTest.php index 2a79293a0ece9..6662cba70f3dd 100644 --- a/src/Symfony/Component/RateLimiter/Tests/Policy/TokenBucketLimiterTest.php +++ b/src/Symfony/Component/RateLimiter/Tests/Policy/TokenBucketLimiterTest.php @@ -49,23 +49,25 @@ public function testReserve() public function testReserveMoreTokensThanBucketSize() { + $limiter = $this->createLimiter(); + $this->expectException(\LogicException::class); $this->expectExceptionMessage('Cannot reserve more tokens (15) than the burst size of the rate limiter (10).'); - $limiter = $this->createLimiter(); $limiter->reserve(15); } public function testReserveMaxWaitingTime() { - $this->expectException(MaxWaitDurationExceededException::class); - $limiter = $this->createLimiter(10, Rate::perMinute()); // enough free tokens $this->assertEquals(0, $limiter->reserve(10, 300)->getWaitDuration()); // waiting time within set maximum $this->assertEquals(300, $limiter->reserve(5, 300)->getWaitDuration()); + + $this->expectException(MaxWaitDurationExceededException::class); + // waiting time exceeded maximum time (as 5 tokens are already reserved) $limiter->reserve(5, 300); } diff --git a/src/Symfony/Component/RateLimiter/Tests/RateLimiterFactoryTest.php b/src/Symfony/Component/RateLimiter/Tests/RateLimiterFactoryTest.php index 5ac5963a2a1cb..c60ff6f0c53fd 100644 --- a/src/Symfony/Component/RateLimiter/Tests/RateLimiterFactoryTest.php +++ b/src/Symfony/Component/RateLimiter/Tests/RateLimiterFactoryTest.php @@ -66,8 +66,8 @@ public static function validConfigProvider() public function testInvalidConfig(string $exceptionClass, array $config) { $this->expectException($exceptionClass); + $factory = new RateLimiterFactory($config, new InMemoryStorage()); - $factory->create('key'); } public static function invalidConfigProvider() diff --git a/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php b/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php index 2c599730f0b09..4db2f9596764b 100644 --- a/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php +++ b/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php @@ -86,8 +86,10 @@ public function testRelativeUrlWithNullParameter() public function testRelativeUrlWithNullParameterButNotOptional() { - $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/testing/{foo}/bar', ['foo' => null])); + + $this->expectException(InvalidParameterException::class); + // This must raise an exception because the default requirement for "foo" is "[^/]+" which is not met with these params. // Generating path "/testing//bar" would be wrong as matching this route would fail. $this->getGenerator($routes)->generate('test', [], UrlGeneratorInterface::ABSOLUTE_PATH); @@ -294,18 +296,17 @@ public function testDumpWithLocalizedRoutesPreserveTheGoodLocaleInTheUrl() public function testGenerateWithoutRoutes() { - $this->expectException(RouteNotFoundException::class); $routes = $this->getRoutes('foo', new Route('/testing/{foo}')); + + $this->expectException(RouteNotFoundException::class); + $this->getGenerator($routes)->generate('test', [], UrlGeneratorInterface::ABSOLUTE_URL); } public function testGenerateWithInvalidLocale() { - $this->expectException(RouteNotFoundException::class); $routes = new RouteCollection(); - $route = new Route(''); - $name = 'test'; foreach (['hr' => '/foo', 'en' => '/bar'] as $locale => $path) { @@ -318,28 +319,37 @@ public function testGenerateWithInvalidLocale() } $generator = $this->getGenerator($routes, [], null, 'fr'); + + $this->expectException(RouteNotFoundException::class); + $generator->generate($name); } public function testGenerateForRouteWithoutMandatoryParameter() { + $routes = $this->getRoutes('test', new Route('/testing/{foo}')); + $this->expectException(MissingMandatoryParametersException::class); $this->expectExceptionMessage('Some mandatory parameters are missing ("foo") to generate a URL for route "test".'); - $routes = $this->getRoutes('test', new Route('/testing/{foo}')); + $this->getGenerator($routes)->generate('test', [], UrlGeneratorInterface::ABSOLUTE_URL); } public function testGenerateForRouteWithInvalidOptionalParameter() { - $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/testing/{foo}', ['foo' => '1'], ['foo' => 'd+'])); + + $this->expectException(InvalidParameterException::class); + $this->getGenerator($routes)->generate('test', ['foo' => 'bar'], UrlGeneratorInterface::ABSOLUTE_URL); } public function testGenerateForRouteWithInvalidParameter() { - $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/testing/{foo}', [], ['foo' => '1|2'])); + + $this->expectException(InvalidParameterException::class); + $this->getGenerator($routes)->generate('test', ['foo' => '0'], UrlGeneratorInterface::ABSOLUTE_URL); } @@ -372,22 +382,28 @@ public function testGenerateForRouteWithInvalidParameterButDisabledRequirementsC public function testGenerateForRouteWithInvalidMandatoryParameter() { - $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/testing/{foo}', [], ['foo' => 'd+'])); + + $this->expectException(InvalidParameterException::class); + $this->getGenerator($routes)->generate('test', ['foo' => 'bar'], UrlGeneratorInterface::ABSOLUTE_URL); } public function testGenerateForRouteWithInvalidUtf8Parameter() { - $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/testing/{foo}', [], ['foo' => '\pL+'], ['utf8' => true])); + + $this->expectException(InvalidParameterException::class); + $this->getGenerator($routes)->generate('test', ['foo' => 'abc123'], UrlGeneratorInterface::ABSOLUTE_URL); } public function testRequiredParamAndEmptyPassed() { - $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/{slug}', [], ['slug' => '.+'])); + + $this->expectException(InvalidParameterException::class); + $this->getGenerator($routes)->generate('test', ['slug' => '']); } @@ -561,25 +577,30 @@ public function testImportantVariable() public function testImportantVariableWithNoDefault() { - $this->expectException(MissingMandatoryParametersException::class); - $this->expectExceptionMessage('Some mandatory parameters are missing ("_format") to generate a URL for route "test".'); $routes = $this->getRoutes('test', new Route('/{page}.{!_format}')); $generator = $this->getGenerator($routes); + $this->expectException(MissingMandatoryParametersException::class); + $this->expectExceptionMessage('Some mandatory parameters are missing ("_format") to generate a URL for route "test".'); + $generator->generate('test', ['page' => 'index']); } public function testDefaultRequirementOfVariableDisallowsSlash() { - $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/{page}.{_format}')); + + $this->expectException(InvalidParameterException::class); + $this->getGenerator($routes)->generate('test', ['page' => 'index', '_format' => 'sl/ash']); } public function testDefaultRequirementOfVariableDisallowsNextSeparator() { - $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/{page}.{_format}')); + + $this->expectException(InvalidParameterException::class); + $this->getGenerator($routes)->generate('test', ['page' => 'do.t', '_format' => 'html']); } @@ -606,22 +627,28 @@ public function testWithHostSameAsContextAndAbsolute() public function testUrlWithInvalidParameterInHost() { - $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/', [], ['foo' => 'bar'], [], '{foo}.example.com')); + + $this->expectException(InvalidParameterException::class); + $this->getGenerator($routes)->generate('test', ['foo' => 'baz'], UrlGeneratorInterface::ABSOLUTE_PATH); } public function testUrlWithInvalidParameterInHostWhenParamHasADefaultValue() { - $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/', ['foo' => 'bar'], ['foo' => 'bar'], [], '{foo}.example.com')); + + $this->expectException(InvalidParameterException::class); + $this->getGenerator($routes)->generate('test', ['foo' => 'baz'], UrlGeneratorInterface::ABSOLUTE_PATH); } public function testUrlWithInvalidParameterEqualsDefaultValueInHost() { - $this->expectException(InvalidParameterException::class); $routes = $this->getRoutes('test', new Route('/', ['foo' => 'baz'], ['foo' => 'bar'], [], '{foo}.example.com')); + + $this->expectException(InvalidParameterException::class); + $this->getGenerator($routes)->generate('test', ['foo' => 'baz'], UrlGeneratorInterface::ABSOLUTE_PATH); } @@ -771,11 +798,11 @@ public function testAliases() public function testAliasWhichTargetRouteDoesntExist() { - $this->expectException(RouteNotFoundException::class); - $routes = new RouteCollection(); $routes->addAlias('d', 'non-existent'); + $this->expectException(RouteNotFoundException::class); + $this->getGenerator($routes)->generate('d'); } @@ -827,39 +854,39 @@ public function testTargettingADeprecatedAliasShouldTriggerDeprecation() public function testCircularReferenceShouldThrowAnException() { - $this->expectException(RouteCircularReferenceException::class); - $this->expectExceptionMessage('Circular reference detected for route "b", path: "b -> a -> b".'); - $routes = new RouteCollection(); $routes->addAlias('a', 'b'); $routes->addAlias('b', 'a'); + $this->expectException(RouteCircularReferenceException::class); + $this->expectExceptionMessage('Circular reference detected for route "b", path: "b -> a -> b".'); + $this->getGenerator($routes)->generate('b'); } public function testDeepCircularReferenceShouldThrowAnException() { - $this->expectException(RouteCircularReferenceException::class); - $this->expectExceptionMessage('Circular reference detected for route "b", path: "b -> c -> b".'); - $routes = new RouteCollection(); $routes->addAlias('a', 'b'); $routes->addAlias('b', 'c'); $routes->addAlias('c', 'b'); + $this->expectException(RouteCircularReferenceException::class); + $this->expectExceptionMessage('Circular reference detected for route "b", path: "b -> c -> b".'); + $this->getGenerator($routes)->generate('b'); } public function testIndirectCircularReferenceShouldThrowAnException() { - $this->expectException(RouteCircularReferenceException::class); - $this->expectExceptionMessage('Circular reference detected for route "a", path: "a -> b -> c -> a".'); - $routes = new RouteCollection(); $routes->addAlias('a', 'b'); $routes->addAlias('b', 'c'); $routes->addAlias('c', 'a'); + $this->expectException(RouteCircularReferenceException::class); + $this->expectExceptionMessage('Circular reference detected for route "a", path: "a -> b -> c -> a".'); + $this->getGenerator($routes)->generate('a'); } diff --git a/src/Symfony/Component/Routing/Tests/Loader/ObjectLoaderTest.php b/src/Symfony/Component/Routing/Tests/Loader/ObjectLoaderTest.php index 54717b6116ae8..c5aeff9f7f658 100644 --- a/src/Symfony/Component/Routing/Tests/Loader/ObjectLoaderTest.php +++ b/src/Symfony/Component/Routing/Tests/Loader/ObjectLoaderTest.php @@ -45,8 +45,10 @@ public function testLoadCallsServiceAndReturnsCollection() */ public function testExceptionWithoutSyntax(string $resourceString) { - $this->expectException(\InvalidArgumentException::class); $loader = new TestObjectLoader(); + + $this->expectException(\InvalidArgumentException::class); + $loader->load($resourceString); } @@ -64,23 +66,26 @@ public static function getBadResourceStrings() public function testExceptionOnNoObjectReturned() { - $this->expectException(\TypeError::class); $loader = new TestObjectLoader(); $loader->loaderMap = ['my_service' => 'NOT_AN_OBJECT']; + + $this->expectException(\TypeError::class); + $loader->load('my_service::method'); } public function testExceptionOnBadMethod() { - $this->expectException(\BadMethodCallException::class); $loader = new TestObjectLoader(); $loader->loaderMap = ['my_service' => new \stdClass()]; + + $this->expectException(\BadMethodCallException::class); + $loader->load('my_service::method'); } public function testExceptionOnMethodNotReturningCollection() { - $this->expectException(\LogicException::class); $service = $this->getMockBuilder(\stdClass::class) ->addMethods(['loadRoutes']) ->getMock(); @@ -90,6 +95,9 @@ public function testExceptionOnMethodNotReturningCollection() $loader = new TestObjectLoader(); $loader->loaderMap = ['my_service' => $service]; + + $this->expectException(\LogicException::class); + $loader->load('my_service::loadRoutes'); } } @@ -105,7 +113,7 @@ public function supports(mixed $resource, string $type = null): bool protected function getObject(string $id): object { - return $this->loaderMap[$id] ?? null; + return $this->loaderMap[$id]; } } diff --git a/src/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.php b/src/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.php index 9e42db7a7e6fe..5291535fd1f72 100644 --- a/src/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.php +++ b/src/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.php @@ -219,18 +219,22 @@ public function testLocalizedImportsOfNotLocalizedRoutes() */ public function testLoadThrowsExceptionWithInvalidFile($filePath) { - $this->expectException(\InvalidArgumentException::class); $loader = new XmlFileLoader(new FileLocator([__DIR__.'/../Fixtures'])); + + $this->expectException(\InvalidArgumentException::class); + $loader->load($filePath); } /** * @dataProvider getPathsToInvalidFiles */ - public function testLoadThrowsExceptionWithInvalidFileEvenWithoutSchemaValidation($filePath) + public function testLoadThrowsExceptionWithInvalidFileEvenWithoutSchemaValidation(string $filePath) { - $this->expectException(\InvalidArgumentException::class); $loader = new CustomXmlFileLoader(new FileLocator([__DIR__.'/../Fixtures'])); + + $this->expectException(\InvalidArgumentException::class); + $loader->load($filePath); } @@ -250,9 +254,11 @@ public static function getPathsToInvalidFiles() public function testDocTypeIsNotAllowed() { + $loader = new XmlFileLoader(new FileLocator([__DIR__.'/../Fixtures'])); + $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('Document types are not allowed.'); - $loader = new XmlFileLoader(new FileLocator([__DIR__.'/../Fixtures'])); + $loader->load('withdoctype.xml'); } @@ -458,16 +464,18 @@ public function testLoadRouteWithControllerSetInDefaults() public function testOverrideControllerInDefaults() { + $loader = new XmlFileLoader(new FileLocator([__DIR__.'/../Fixtures/controller'])); + $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessageMatches('/The routing file "[^"]*" must not specify both the "controller" attribute and the defaults key "_controller" for "app_blog"/'); - $loader = new XmlFileLoader(new FileLocator([__DIR__.'/../Fixtures/controller'])); + $loader->load('override_defaults.xml'); } /** * @dataProvider provideFilesImportingRoutesWithControllers */ - public function testImportRouteWithController($file) + public function testImportRouteWithController(string $file) { $loader = new XmlFileLoader(new FileLocator([__DIR__.'/../Fixtures/controller'])); $routeCollection = $loader->load($file); @@ -490,9 +498,11 @@ public static function provideFilesImportingRoutesWithControllers() public function testImportWithOverriddenController() { + $loader = new XmlFileLoader(new FileLocator([__DIR__.'/../Fixtures/controller'])); + $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessageMatches('/The routing file "[^"]*" must not specify both the "controller" attribute and the defaults key "_controller" for the "import" tag/'); - $loader = new XmlFileLoader(new FileLocator([__DIR__.'/../Fixtures/controller'])); + $loader->load('import_override_defaults.xml'); } diff --git a/src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php b/src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php index c925affcf1c7c..5e19254d8737a 100644 --- a/src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php +++ b/src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php @@ -49,10 +49,12 @@ public function testLoadDoesNothingIfEmpty() /** * @dataProvider getPathsToInvalidFiles */ - public function testLoadThrowsExceptionWithInvalidFile($filePath) + public function testLoadThrowsExceptionWithInvalidFile(string $filePath) { - $this->expectException(\InvalidArgumentException::class); $loader = new YamlFileLoader(new FileLocator([__DIR__.'/../Fixtures'])); + + $this->expectException(\InvalidArgumentException::class); + $loader->load($filePath); } @@ -151,9 +153,11 @@ public function testLoadRouteWithControllerSetInDefaults() public function testOverrideControllerInDefaults() { + $loader = new YamlFileLoader(new FileLocator([__DIR__.'/../Fixtures/controller'])); + $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessageMatches('/The routing file "[^"]*" must not specify both the "controller" key and the defaults key "_controller" for "app_blog"/'); - $loader = new YamlFileLoader(new FileLocator([__DIR__.'/../Fixtures/controller'])); + $loader->load('override_defaults.yml'); } @@ -183,9 +187,11 @@ public static function provideFilesImportingRoutesWithControllers() public function testImportWithOverriddenController() { + $loader = new YamlFileLoader(new FileLocator([__DIR__.'/../Fixtures/controller'])); + $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessageMatches('/The routing file "[^"]*" must not specify both the "controller" key and the defaults key "_controller" for "_static"/'); - $loader = new YamlFileLoader(new FileLocator([__DIR__.'/../Fixtures/controller'])); + $loader->load('import_override_defaults.yml'); } @@ -396,10 +402,11 @@ public function testImportRouteWithNoTrailingSlash() public function testRequirementsWithoutPlaceholderName() { + $loader = new YamlFileLoader(new FileLocator([__DIR__.'/../Fixtures'])); + $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('A placeholder name must be a string (0 given). Did you forget to specify the placeholder key for the requirement "\\d+" of route "foo"'); - $loader = new YamlFileLoader(new FileLocator([__DIR__.'/../Fixtures'])); $loader->load('requirements_without_placeholder_name.yml'); } diff --git a/src/Symfony/Component/Routing/Tests/Matcher/Dumper/CompiledUrlMatcherDumperTest.php b/src/Symfony/Component/Routing/Tests/Matcher/Dumper/CompiledUrlMatcherDumperTest.php index 232314b5ab734..d61d736ad0ebb 100644 --- a/src/Symfony/Component/Routing/Tests/Matcher/Dumper/CompiledUrlMatcherDumperTest.php +++ b/src/Symfony/Component/Routing/Tests/Matcher/Dumper/CompiledUrlMatcherDumperTest.php @@ -493,11 +493,13 @@ private function generateDumpedMatcher(RouteCollection $collection) public function testGenerateDumperMatcherWithObject() { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('Symfony\Component\Routing\Route cannot contain objects'); $routeCollection = new RouteCollection(); $routeCollection->add('_', new Route('/', [new \stdClass()])); $dumper = new CompiledUrlMatcherDumper($routeCollection); + + $this->expectExceptionMessage('Symfony\Component\Routing\Route cannot contain objects'); + $this->expectException(\InvalidArgumentException::class); + $dumper->dump(); } } diff --git a/src/Symfony/Component/Routing/Tests/Matcher/RedirectableUrlMatcherTest.php b/src/Symfony/Component/Routing/Tests/Matcher/RedirectableUrlMatcherTest.php index 1f3774b5b4e69..dc8126a43cb42 100644 --- a/src/Symfony/Component/Routing/Tests/Matcher/RedirectableUrlMatcherTest.php +++ b/src/Symfony/Component/Routing/Tests/Matcher/RedirectableUrlMatcherTest.php @@ -41,13 +41,15 @@ public function testExtraTrailingSlash() public function testRedirectWhenNoSlashForNonSafeMethod() { - $this->expectException(ResourceNotFoundException::class); $coll = new RouteCollection(); $coll->add('foo', new Route('/foo/')); $context = new RequestContext(); $context->setMethod('POST'); $matcher = $this->getUrlMatcher($coll, $context); + + $this->expectException(ResourceNotFoundException::class); + $matcher->match('/foo'); } diff --git a/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php b/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php index 41126642e4767..34966dfe82fb0 100644 --- a/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php +++ b/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php @@ -199,21 +199,25 @@ public function testMatchImportantVariable() public function testShortPathDoesNotMatchImportantVariable() { - $this->expectException(ResourceNotFoundException::class); - $collection = new RouteCollection(); $collection->add('index', new Route('/index.{!_format}', ['_format' => 'xml'])); - $this->getUrlMatcher($collection)->match('/index'); + $matcher = $this->getUrlMatcher($collection); + + $this->expectException(ResourceNotFoundException::class); + + $matcher->match('/index'); } public function testTrailingEncodedNewlineIsNotOverlooked() { - $this->expectException(ResourceNotFoundException::class); $collection = new RouteCollection(); $collection->add('foo', new Route('/foo')); $matcher = $this->getUrlMatcher($collection); + + $this->expectException(ResourceNotFoundException::class); + $matcher->match('/foo%0a'); } @@ -358,31 +362,35 @@ public function testDefaultRequirementOfVariable() public function testDefaultRequirementOfVariableDisallowsSlash() { - $this->expectException(ResourceNotFoundException::class); $coll = new RouteCollection(); $coll->add('test', new Route('/{page}.{_format}')); $matcher = $this->getUrlMatcher($coll); + $this->expectException(ResourceNotFoundException::class); + $matcher->match('/index.sl/ash'); } public function testDefaultRequirementOfVariableDisallowsNextSeparator() { - $this->expectException(ResourceNotFoundException::class); $coll = new RouteCollection(); $coll->add('test', new Route('/{page}.{_format}', [], ['_format' => 'html|xml'])); $matcher = $this->getUrlMatcher($coll); + $this->expectException(ResourceNotFoundException::class); + $matcher->match('/do.t.html'); } public function testMissingTrailingSlash() { - $this->expectException(ResourceNotFoundException::class); $coll = new RouteCollection(); $coll->add('foo', new Route('/foo/')); $matcher = $this->getUrlMatcher($coll); + + $this->expectException(ResourceNotFoundException::class); + $matcher->match('/foo'); } @@ -452,12 +460,14 @@ public function testSamePathWithDifferentScheme() public function testCondition() { - $this->expectException(ResourceNotFoundException::class); $coll = new RouteCollection(); $route = new Route('/foo'); $route->setCondition('context.getMethod() == "POST"'); $coll->add('foo', $route); $matcher = $this->getUrlMatcher($coll); + + $this->expectException(ResourceNotFoundException::class); + $matcher->match('/foo'); } @@ -690,21 +700,25 @@ public function testMixOfStaticAndVariableVariationInTrailingSlashWithMethods() public function testWithOutHostHostDoesNotMatch() { - $this->expectException(ResourceNotFoundException::class); $coll = new RouteCollection(); $coll->add('foo', new Route('/foo/{foo}', [], [], [], '{locale}.example.com')); $matcher = $this->getUrlMatcher($coll, new RequestContext('', 'GET', 'example.com')); + + $this->expectException(ResourceNotFoundException::class); + $matcher->match('/foo/bar'); } public function testPathIsCaseSensitive() { - $this->expectException(ResourceNotFoundException::class); $coll = new RouteCollection(); $coll->add('foo', new Route('/locale', [], ['locale' => 'EN|FR|DE'])); $matcher = $this->getUrlMatcher($coll); + + $this->expectException(ResourceNotFoundException::class); + $matcher->match('/en'); } @@ -719,10 +733,12 @@ public function testHostIsCaseInsensitive() public function testNoConfiguration() { - $this->expectException(NoConfigurationException::class); $coll = new RouteCollection(); $matcher = $this->getUrlMatcher($coll); + + $this->expectException(NoConfigurationException::class); + $matcher->match('/'); } @@ -752,12 +768,14 @@ public function testNestedCollections() public function testSchemeAndMethodMismatch() { - $this->expectException(ResourceNotFoundException::class); - $this->expectExceptionMessage('No routes found for "/".'); $coll = new RouteCollection(); $coll->add('foo', new Route('/', [], [], [], null, ['https'], ['POST'])); $matcher = $this->getUrlMatcher($coll); + + $this->expectException(ResourceNotFoundException::class); + $this->expectExceptionMessage('No routes found for "/".'); + $matcher->match('/'); } diff --git a/src/Symfony/Component/Routing/Tests/RouteCompilerTest.php b/src/Symfony/Component/Routing/Tests/RouteCompilerTest.php index 63186881afb33..b53c37f67c408 100644 --- a/src/Symfony/Component/Routing/Tests/RouteCompilerTest.php +++ b/src/Symfony/Component/Routing/Tests/RouteCompilerTest.php @@ -252,32 +252,35 @@ public function testRouteWithSameVariableTwice() public function testRouteCharsetMismatch() { - $this->expectException(\LogicException::class); $route = new Route("/\xE9/{bar}", [], ['bar' => '.'], ['utf8' => true]); + $this->expectException(\LogicException::class); + $route->compile(); } public function testRequirementCharsetMismatch() { - $this->expectException(\LogicException::class); $route = new Route('/foo/{bar}', [], ['bar' => "\xE9"], ['utf8' => true]); + $this->expectException(\LogicException::class); + $route->compile(); } public function testRouteWithFragmentAsPathParameter() { - $this->expectException(\InvalidArgumentException::class); $route = new Route('/{_fragment}'); + $this->expectException(\InvalidArgumentException::class); + $route->compile(); } /** * @dataProvider getVariableNamesStartingWithADigit */ - public function testRouteWithVariableNameStartingWithADigit($name) + public function testRouteWithVariableNameStartingWithADigit(string $name) { $this->expectException(\DomainException::class); $route = new Route('/{'.$name.'}'); @@ -296,7 +299,7 @@ public static function getVariableNamesStartingWithADigit() /** * @dataProvider provideCompileWithHostData */ - public function testCompileWithHost($name, $arguments, $prefix, $regex, $variables, $pathVariables, $tokens, $hostRegex, $hostVariables, $hostTokens) + public function testCompileWithHost(string $name, array $arguments, string $prefix, string $regex, array $variables, array $pathVariables, array $tokens, string $hostRegex, array $hostVariables, array $hostTokens) { $r = new \ReflectionClass(Route::class); $route = $r->newInstanceArgs($arguments); @@ -366,15 +369,17 @@ public static function provideCompileWithHostData() public function testRouteWithTooLongVariableName() { - $this->expectException(\DomainException::class); $route = new Route(sprintf('/{%s}', str_repeat('a', RouteCompiler::VARIABLE_MAXIMUM_LENGTH + 1))); + + $this->expectException(\DomainException::class); + $route->compile(); } /** * @dataProvider provideRemoveCapturingGroup */ - public function testRemoveCapturingGroup($regex, $requirement) + public function testRemoveCapturingGroup(string $regex, string $requirement) { $route = new Route('/{foo}', [], ['foo' => $requirement]); diff --git a/src/Symfony/Component/Routing/Tests/RouteTest.php b/src/Symfony/Component/Routing/Tests/RouteTest.php index b68ddd0e7b245..176c6f05ee021 100644 --- a/src/Symfony/Component/Routing/Tests/RouteTest.php +++ b/src/Symfony/Component/Routing/Tests/RouteTest.php @@ -146,8 +146,10 @@ public function testRequirementAlternativeStartAndEndRegexSyntax() */ public function testSetInvalidRequirement($req) { - $this->expectException(\InvalidArgumentException::class); $route = new Route('/{foo}'); + + $this->expectException(\InvalidArgumentException::class); + $route->setRequirement('foo', $req); } diff --git a/src/Symfony/Component/Routing/Tests/RouterTest.php b/src/Symfony/Component/Routing/Tests/RouterTest.php index b8766831bd580..fa8c66f2fad83 100644 --- a/src/Symfony/Component/Routing/Tests/RouterTest.php +++ b/src/Symfony/Component/Routing/Tests/RouterTest.php @@ -89,7 +89,7 @@ public function testGetOptionWithUnsupportedOption() { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('The Router does not support the "option_foo" option'); - $this->router->getOption('option_foo', true); + $this->router->getOption('option_foo'); } public function testThatRouteCollectionIsLoaded() diff --git a/src/Symfony/Component/Security/Core/Tests/Authentication/RememberMe/InMemoryTokenProviderTest.php b/src/Symfony/Component/Security/Core/Tests/Authentication/RememberMe/InMemoryTokenProviderTest.php index 45fd046a9ac73..6fc2ab1555a1b 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authentication/RememberMe/InMemoryTokenProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authentication/RememberMe/InMemoryTokenProviderTest.php @@ -31,8 +31,7 @@ public function testCreateNewToken() public function testLoadTokenBySeriesThrowsNotFoundException() { $this->expectException(TokenNotFoundException::class); - $provider = new InMemoryTokenProvider(); - $provider->loadTokenBySeries('foo'); + (new InMemoryTokenProvider())->loadTokenBySeries('foo'); } public function testUpdateToken() @@ -50,12 +49,14 @@ public function testUpdateToken() public function testDeleteToken() { - $this->expectException(TokenNotFoundException::class); $provider = new InMemoryTokenProvider(); $token = new PersistentToken('foo', 'foo', 'foo', 'foo', new \DateTimeImmutable()); $provider->createNewToken($token); $provider->deleteTokenBySeries('foo'); + + $this->expectException(TokenNotFoundException::class); + $provider->loadTokenBySeries('foo'); } } diff --git a/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/VoterTest.php b/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/VoterTest.php index 80c3f4a00b6a2..5636340e6aea2 100644 --- a/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/VoterTest.php +++ b/src/Symfony/Component/Security/Core/Tests/Authorization/Voter/VoterTest.php @@ -67,8 +67,7 @@ public function testVoteWithTypeError() { $this->expectException(\TypeError::class); $this->expectExceptionMessage('Should error'); - $voter = new TypeErrorVoterTest_Voter(); - $voter->vote($this->token, new \stdClass(), ['EDIT']); + (new TypeErrorVoterTest_Voter())->vote($this->token, new \stdClass(), ['EDIT']); } } diff --git a/src/Symfony/Component/Security/Core/Tests/User/ChainUserProviderTest.php b/src/Symfony/Component/Security/Core/Tests/User/ChainUserProviderTest.php index 09227752bb0ee..901115615a3df 100644 --- a/src/Symfony/Component/Security/Core/Tests/User/ChainUserProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/User/ChainUserProviderTest.php @@ -47,7 +47,6 @@ public function testLoadUserByIdentifier() public function testLoadUserByIdentifierThrowsUserNotFoundException() { - $this->expectException(UserNotFoundException::class); $provider1 = $this->createMock(InMemoryUserProvider::class); $provider1 ->expects($this->once()) @@ -65,6 +64,9 @@ public function testLoadUserByIdentifierThrowsUserNotFoundException() ; $provider = new ChainUserProvider([$provider1, $provider2]); + + $this->expectException(UserNotFoundException::class); + $provider->loadUserByIdentifier('foo'); } @@ -141,7 +143,6 @@ public function testRefreshUserAgain() public function testRefreshUserThrowsUnsupportedUserException() { - $this->expectException(UnsupportedUserException::class); $provider1 = $this->createMock(InMemoryUserProvider::class); $provider1 ->expects($this->once()) @@ -169,6 +170,9 @@ public function testRefreshUserThrowsUnsupportedUserException() ; $provider = new ChainUserProvider([$provider1, $provider2]); + + $this->expectException(UnsupportedUserException::class); + $provider->refreshUser($this->createMock(UserInterface::class)); } diff --git a/src/Symfony/Component/Security/Core/Tests/User/InMemoryUserCheckerTest.php b/src/Symfony/Component/Security/Core/Tests/User/InMemoryUserCheckerTest.php index 8b01e5f02e880..25107723e4fc7 100644 --- a/src/Symfony/Component/Security/Core/Tests/User/InMemoryUserCheckerTest.php +++ b/src/Symfony/Component/Security/Core/Tests/User/InMemoryUserCheckerTest.php @@ -35,7 +35,6 @@ public function testCheckPostAuthPass() public function testCheckPreAuthDisabled() { $this->expectException(DisabledException::class); - $checker = new InMemoryUserChecker(); - $checker->checkPreAuth(new InMemoryUser('John', 'password', [], false)); + (new InMemoryUserChecker())->checkPreAuth(new InMemoryUser('John', 'password', [], false)); } } diff --git a/src/Symfony/Component/Security/Core/Tests/User/InMemoryUserProviderTest.php b/src/Symfony/Component/Security/Core/Tests/User/InMemoryUserProviderTest.php index 1a843e4e71c55..98afb3b4f2230 100644 --- a/src/Symfony/Component/Security/Core/Tests/User/InMemoryUserProviderTest.php +++ b/src/Symfony/Component/Security/Core/Tests/User/InMemoryUserProviderTest.php @@ -62,16 +62,17 @@ public function testCreateUser() public function testCreateUserAlreadyExist() { - $this->expectException(\LogicException::class); $provider = new InMemoryUserProvider(); $provider->createUser(new InMemoryUser('fabien', 'foo')); + + $this->expectException(\LogicException::class); + $provider->createUser(new InMemoryUser('fabien', 'foo')); } public function testLoadUserByIdentifierDoesNotExist() { $this->expectException(UserNotFoundException::class); - $provider = new InMemoryUserProvider(); - $provider->loadUserByIdentifier('fabien'); + (new InMemoryUserProvider())->loadUserByIdentifier('fabien'); } } diff --git a/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTestCase.php b/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTestCase.php index ccf556a01e240..c78f6b5f3d02a 100644 --- a/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTestCase.php +++ b/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTestCase.php @@ -113,13 +113,14 @@ public static function emptyPasswordData() public function testUserIsNotValid() { - $this->expectException(ConstraintDefinitionException::class); $user = new \stdClass(); $this->tokenStorage = $this->createTokenStorage($user); $this->validator = $this->createValidator(); $this->validator->initialize($this->context); + $this->expectException(ConstraintDefinitionException::class); + $this->validator->validate('secret', new UserPassword()); } diff --git a/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/SessionTokenStorageTest.php b/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/SessionTokenStorageTest.php index 64e618031f7de..593d1a781f81d 100644 --- a/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/SessionTokenStorageTest.php +++ b/src/Symfony/Component/Security/Csrf/Tests/TokenStorage/SessionTokenStorageTest.php @@ -94,8 +94,10 @@ public function testGetNonExistingTokenFromClosedSession() public function testGetNonExistingTokenFromActiveSession() { - $this->expectException(TokenNotFoundException::class); $this->session->start(); + + $this->expectException(TokenNotFoundException::class); + $this->storage->getToken('token_id'); } diff --git a/src/Symfony/Component/Security/Http/Tests/AccessToken/Oidc/OidcTokenHandlerTest.php b/src/Symfony/Component/Security/Http/Tests/AccessToken/Oidc/OidcTokenHandlerTest.php index ccf11e49862b6..ae3ca5308b06a 100644 --- a/src/Symfony/Component/Security/Http/Tests/AccessToken/Oidc/OidcTokenHandlerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/AccessToken/Oidc/OidcTokenHandlerTest.php @@ -80,12 +80,12 @@ public static function getClaims(): iterable */ public function testThrowsAnErrorIfTokenIsInvalid(string $token) { - $this->expectException(BadCredentialsException::class); - $this->expectExceptionMessage('Invalid credentials.'); - $loggerMock = $this->createMock(LoggerInterface::class); $loggerMock->expects($this->once())->method('error'); + $this->expectException(BadCredentialsException::class); + $this->expectExceptionMessage('Invalid credentials.'); + (new OidcTokenHandler( new ES256(), $this->getJWK(), @@ -128,9 +128,6 @@ public static function getInvalidTokens(): iterable public function testThrowsAnErrorIfUserPropertyIsMissing() { - $this->expectException(BadCredentialsException::class); - $this->expectExceptionMessage('Invalid credentials.'); - $loggerMock = $this->createMock(LoggerInterface::class); $loggerMock->expects($this->once())->method('error'); @@ -145,6 +142,9 @@ public function testThrowsAnErrorIfUserPropertyIsMissing() ]; $token = $this->buildJWS(json_encode($claims)); + $this->expectException(BadCredentialsException::class); + $this->expectExceptionMessage('Invalid credentials.'); + (new OidcTokenHandler( new ES256(), self::getJWK(), diff --git a/src/Symfony/Component/Security/Http/Tests/AccessToken/Oidc/OidcUserInfoTokenHandlerTest.php b/src/Symfony/Component/Security/Http/Tests/AccessToken/Oidc/OidcUserInfoTokenHandlerTest.php index 2c8d9ae803f9d..40eb5ce81d616 100644 --- a/src/Symfony/Component/Security/Http/Tests/AccessToken/Oidc/OidcUserInfoTokenHandlerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/AccessToken/Oidc/OidcUserInfoTokenHandlerTest.php @@ -63,15 +63,10 @@ public static function getClaims(): iterable public function testThrowsAnExceptionIfUserPropertyIsMissing() { - $this->expectException(BadCredentialsException::class); - $this->expectExceptionMessage('Invalid credentials.'); - - $response = ['foo' => 'bar']; - $responseMock = $this->createMock(ResponseInterface::class); $responseMock->expects($this->once()) ->method('toArray') - ->willReturn($response); + ->willReturn(['foo' => 'bar']); $clientMock = $this->createMock(HttpClientInterface::class); $clientMock->expects($this->once()) @@ -83,6 +78,10 @@ public function testThrowsAnExceptionIfUserPropertyIsMissing() ->method('error'); $handler = new OidcUserInfoTokenHandler($clientMock, $loggerMock); + + $this->expectException(BadCredentialsException::class); + $this->expectExceptionMessage('Invalid credentials.'); + $handler->getUserBadgeFrom('a-secret-token'); } } diff --git a/src/Symfony/Component/Security/Http/Tests/Authenticator/AccessToken/ChainedAccessTokenExtractorsTest.php b/src/Symfony/Component/Security/Http/Tests/Authenticator/AccessToken/ChainedAccessTokenExtractorsTest.php index 1507e425726a6..f7ef04c6e701b 100644 --- a/src/Symfony/Component/Security/Http/Tests/Authenticator/AccessToken/ChainedAccessTokenExtractorsTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Authenticator/AccessToken/ChainedAccessTokenExtractorsTest.php @@ -67,13 +67,13 @@ public function testAuthenticate() /** * @dataProvider provideInvalidAuthenticateData */ - public function testAuthenticateInvalid($request, $errorMessage, $exceptionType = BadRequestHttpException::class) + public function testAuthenticateInvalid(Request $request, string $errorMessage, string $exceptionType) { + $this->setUpAuthenticator(); + $this->expectException($exceptionType); $this->expectExceptionMessage($errorMessage); - $this->setUpAuthenticator(); - $this->authenticator->authenticate($request); } diff --git a/src/Symfony/Component/Security/Http/Tests/Authenticator/AccessToken/FormEncodedBodyAccessTokenAuthenticatorTest.php b/src/Symfony/Component/Security/Http/Tests/Authenticator/AccessToken/FormEncodedBodyAccessTokenAuthenticatorTest.php index 3299f01729104..11443a1c92992 100644 --- a/src/Symfony/Component/Security/Http/Tests/Authenticator/AccessToken/FormEncodedBodyAccessTokenAuthenticatorTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Authenticator/AccessToken/FormEncodedBodyAccessTokenAuthenticatorTest.php @@ -82,13 +82,13 @@ public function testAuthenticateWithCustomParameter() /** * @dataProvider provideInvalidAuthenticateData */ - public function testAuthenticateInvalid($request, $errorMessage, $exceptionType = BadRequestHttpException::class) + public function testAuthenticateInvalid(Request $request, string $errorMessage, string $exceptionType) { + $this->setUpAuthenticator(); + $this->expectException($exceptionType); $this->expectExceptionMessage($errorMessage); - $this->setUpAuthenticator(); - $this->authenticator->authenticate($request); } diff --git a/src/Symfony/Component/Security/Http/Tests/Authenticator/AccessToken/HeaderAccessTokenAuthenticatorTest.php b/src/Symfony/Component/Security/Http/Tests/Authenticator/AccessToken/HeaderAccessTokenAuthenticatorTest.php index de85e66fdf372..23910af80e3d9 100644 --- a/src/Symfony/Component/Security/Http/Tests/Authenticator/AccessToken/HeaderAccessTokenAuthenticatorTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Authenticator/AccessToken/HeaderAccessTokenAuthenticatorTest.php @@ -110,13 +110,13 @@ public function testAuthenticateWithCustomTokenType() /** * @dataProvider provideInvalidAuthenticateData */ - public function testAuthenticateInvalid($request, $errorMessage, $exceptionType = BadRequestHttpException::class) + public function testAuthenticateInvalid(Request $request, string $errorMessage, string $exceptionType) { + $this->setUpAuthenticator(); + $this->expectException($exceptionType); $this->expectExceptionMessage($errorMessage); - $this->setUpAuthenticator(); - $this->authenticator->authenticate($request); } diff --git a/src/Symfony/Component/Security/Http/Tests/Authenticator/AccessToken/QueryAccessTokenAuthenticatorTest.php b/src/Symfony/Component/Security/Http/Tests/Authenticator/AccessToken/QueryAccessTokenAuthenticatorTest.php index 428b1fd08ea2b..00fa650841e2d 100644 --- a/src/Symfony/Component/Security/Http/Tests/Authenticator/AccessToken/QueryAccessTokenAuthenticatorTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Authenticator/AccessToken/QueryAccessTokenAuthenticatorTest.php @@ -78,13 +78,13 @@ public function testAuthenticateWithCustomParameter() /** * @dataProvider provideInvalidAuthenticateData */ - public function testAuthenticateInvalid($request, $errorMessage, $exceptionType = BadRequestHttpException::class) + public function testAuthenticateInvalid(Request $request, string $errorMessage, string $exceptionType) { + $this->setUpAuthenticator(); + $this->expectException($exceptionType); $this->expectExceptionMessage($errorMessage); - $this->setUpAuthenticator(); - $this->authenticator->authenticate($request); } diff --git a/src/Symfony/Component/Security/Http/Tests/Authenticator/AccessTokenAuthenticatorTest.php b/src/Symfony/Component/Security/Http/Tests/Authenticator/AccessTokenAuthenticatorTest.php index 4f010000429dd..3279b8520d4d2 100644 --- a/src/Symfony/Component/Security/Http/Tests/Authenticator/AccessTokenAuthenticatorTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Authenticator/AccessTokenAuthenticatorTest.php @@ -37,9 +37,6 @@ protected function setUp(): void public function testAuthenticateWithoutAccessToken() { - $this->expectException(BadCredentialsException::class); - $this->expectExceptionMessage('Invalid credentials.'); - $request = Request::create('/test'); $this->accessTokenExtractor @@ -53,6 +50,9 @@ public function testAuthenticateWithoutAccessToken() $this->accessTokenExtractor, ); + $this->expectException(BadCredentialsException::class); + $this->expectExceptionMessage('Invalid credentials.'); + $authenticator->authenticate($request); } diff --git a/src/Symfony/Component/Security/Http/Tests/Authenticator/FormLoginAuthenticatorTest.php b/src/Symfony/Component/Security/Http/Tests/Authenticator/FormLoginAuthenticatorTest.php index b0b44d94ea73b..af5c4fad267be 100644 --- a/src/Symfony/Component/Security/Http/Tests/Authenticator/FormLoginAuthenticatorTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Authenticator/FormLoginAuthenticatorTest.php @@ -72,13 +72,14 @@ public static function provideUsernamesForLength() */ public function testHandleNonStringUsernameWithArray($postOnly) { - $this->expectException(BadRequestHttpException::class); - $this->expectExceptionMessage('The key "_username" must be a string, "array" given.'); - $request = Request::create('/login_check', 'POST', ['_username' => []]); $request->setSession($this->createSession()); $this->setUpAuthenticator(['post_only' => $postOnly]); + + $this->expectException(BadRequestHttpException::class); + $this->expectExceptionMessage('The key "_username" must be a string, "array" given.'); + $this->authenticator->authenticate($request); } @@ -87,13 +88,14 @@ public function testHandleNonStringUsernameWithArray($postOnly) */ public function testHandleNonStringUsernameWithInt($postOnly) { - $this->expectException(BadRequestHttpException::class); - $this->expectExceptionMessage('The key "_username" must be a string, "integer" given.'); - $request = Request::create('/login_check', 'POST', ['_username' => 42]); $request->setSession($this->createSession()); $this->setUpAuthenticator(['post_only' => $postOnly]); + + $this->expectException(BadRequestHttpException::class); + $this->expectExceptionMessage('The key "_username" must be a string, "integer" given.'); + $this->authenticator->authenticate($request); } @@ -102,13 +104,14 @@ public function testHandleNonStringUsernameWithInt($postOnly) */ public function testHandleNonStringUsernameWithObject($postOnly) { - $this->expectException(BadRequestHttpException::class); - $this->expectExceptionMessage('The key "_username" must be a string, "object" given.'); - $request = Request::create('/login_check', 'POST', ['_username' => new \stdClass()]); $request->setSession($this->createSession()); $this->setUpAuthenticator(['post_only' => $postOnly]); + + $this->expectException(BadRequestHttpException::class); + $this->expectExceptionMessage('The key "_username" must be a string, "object" given.'); + $this->authenticator->authenticate($request); } @@ -132,13 +135,14 @@ public function testHandleNonStringUsernameWithToString($postOnly) */ public function testHandleNonStringPasswordWithArray(bool $postOnly) { - $this->expectException(BadRequestHttpException::class); - $this->expectExceptionMessage('The key "_password" must be a string, "array" given.'); - $request = Request::create('/login_check', 'POST', ['_username' => 'foo', '_password' => []]); $request->setSession($this->createSession()); $this->setUpAuthenticator(['post_only' => $postOnly]); + + $this->expectException(BadRequestHttpException::class); + $this->expectExceptionMessage('The key "_password" must be a string, "array" given.'); + $this->authenticator->authenticate($request); } diff --git a/src/Symfony/Component/Security/Http/Tests/Authenticator/JsonLoginAuthenticatorTest.php b/src/Symfony/Component/Security/Http/Tests/Authenticator/JsonLoginAuthenticatorTest.php index 21b2203c830e9..2bac2e0a789fd 100644 --- a/src/Symfony/Component/Security/Http/Tests/Authenticator/JsonLoginAuthenticatorTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Authenticator/JsonLoginAuthenticatorTest.php @@ -93,13 +93,13 @@ public function testAuthenticateWithCustomPath() /** * @dataProvider provideInvalidAuthenticateData */ - public function testAuthenticateInvalid($request, $errorMessage, $exceptionType = BadRequestHttpException::class) + public function testAuthenticateInvalid(Request $request, string $errorMessage, string $exceptionType = BadRequestHttpException::class) { + $this->setUpAuthenticator(); + $this->expectException($exceptionType); $this->expectExceptionMessage($errorMessage); - $this->setUpAuthenticator(); - $this->authenticator->authenticate($request); } diff --git a/src/Symfony/Component/Security/Http/Tests/Authenticator/LoginLinkAuthenticatorTest.php b/src/Symfony/Component/Security/Http/Tests/Authenticator/LoginLinkAuthenticatorTest.php index 5d8088f4fb208..08af3a378894b 100644 --- a/src/Symfony/Component/Security/Http/Tests/Authenticator/LoginLinkAuthenticatorTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Authenticator/LoginLinkAuthenticatorTest.php @@ -79,7 +79,6 @@ public function testSuccessfulAuthenticate() public function testUnsuccessfulAuthenticate() { - $this->expectException(InvalidLoginLinkAuthenticationException::class); $this->setUpAuthenticator(); $request = Request::create('/login/link/check?stuff=1&user=weaverryan'); @@ -89,13 +88,15 @@ public function testUnsuccessfulAuthenticate() ->willThrowException(new ExpiredLoginLinkException()); $passport = $this->authenticator->authenticate($request); + + $this->expectException(InvalidLoginLinkAuthenticationException::class); + // trigger the user loader to try to load the user $passport->getBadge(UserBadge::class)->getUser(); } public function testMissingUser() { - $this->expectException(InvalidLoginLinkAuthenticationException::class); $this->setUpAuthenticator(); $request = Request::create('/login/link/check?stuff=1'); @@ -103,6 +104,8 @@ public function testMissingUser() $this->loginLinkHandler->expects($this->never()) ->method('consumeLoginLink'); + $this->expectException(InvalidLoginLinkAuthenticationException::class); + $this->authenticator->authenticate($request); } diff --git a/src/Symfony/Component/Security/Http/Tests/Authenticator/RememberMeAuthenticatorTest.php b/src/Symfony/Component/Security/Http/Tests/Authenticator/RememberMeAuthenticatorTest.php index 52bb1a61d9ca1..2c8e70585072d 100644 --- a/src/Symfony/Component/Security/Http/Tests/Authenticator/RememberMeAuthenticatorTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Authenticator/RememberMeAuthenticatorTest.php @@ -86,17 +86,19 @@ public function testAuthenticateWithoutToken() public function testAuthenticateWithoutOldToken() { + $request = Request::create('/', 'GET', [], ['_remember_me_cookie' => base64_encode('foo:bar')]); + $this->expectException(AuthenticationException::class); - $request = Request::create('/', 'GET', [], ['_remember_me_cookie' => base64_encode('foo:bar')]); $this->authenticator->authenticate($request); } public function testAuthenticateWithTokenWithoutDelimiter() { + $request = Request::create('/', 'GET', [], ['_remember_me_cookie' => 'invalid']); + $this->expectException(AuthenticationException::class); - $request = Request::create('/', 'GET', [], ['_remember_me_cookie' => 'invalid']); $this->authenticator->authenticate($request); } } diff --git a/src/Symfony/Component/Security/Http/Tests/EventListener/CheckCredentialsListenerTest.php b/src/Symfony/Component/Security/Http/Tests/EventListener/CheckCredentialsListenerTest.php index 85a9b8b78e465..1ade1bf0a7c57 100644 --- a/src/Symfony/Component/Security/Http/Tests/EventListener/CheckCredentialsListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/EventListener/CheckCredentialsListenerTest.php @@ -43,7 +43,7 @@ protected function setUp(): void /** * @dataProvider providePasswords */ - public function testPasswordAuthenticated($password, $passwordValid, $result) + public function testPasswordAuthenticated(string $password, bool $passwordValid, bool $result) { $hasher = $this->createMock(PasswordHasherInterface::class); $hasher->expects($this->any())->method('verify')->with('password-hash', $password)->willReturn($passwordValid); @@ -71,19 +71,22 @@ public static function providePasswords() public function testEmptyPassword() { + $this->hasherFactory + ->expects($this->never()) + ->method('getPasswordHasher'); + + $event = $this->createEvent(new Passport(new UserBadge('wouter', fn () => $this->user), new PasswordCredentials(''))); + $this->expectException(BadCredentialsException::class); $this->expectExceptionMessage('The presented password cannot be empty.'); - $this->hasherFactory->expects($this->never())->method('getPasswordHasher'); - - $event = $this->createEvent(new Passport(new UserBadge('wouter', fn () => $this->user), new PasswordCredentials(''))); $this->listener->checkPassport($event); } /** * @dataProvider provideCustomAuthenticatedResults */ - public function testCustomAuthenticated($result) + public function testCustomAuthenticated(bool $result) { $this->hasherFactory->expects($this->never())->method('getPasswordHasher'); diff --git a/src/Symfony/Component/Security/Http/Tests/EventListener/CsrfProtectionListenerTest.php b/src/Symfony/Component/Security/Http/Tests/EventListener/CsrfProtectionListenerTest.php index 7942616b2a396..b591c5ef3c0b5 100644 --- a/src/Symfony/Component/Security/Http/Tests/EventListener/CsrfProtectionListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/EventListener/CsrfProtectionListenerTest.php @@ -58,15 +58,16 @@ public function testValidCsrfToken() public function testInvalidCsrfToken() { - $this->expectException(InvalidCsrfTokenException::class); - $this->expectExceptionMessage('Invalid CSRF token.'); - $this->csrfTokenManager->expects($this->any()) ->method('isTokenValid') ->with(new CsrfToken('authenticator_token_id', 'abc123')) ->willReturn(false); $event = $this->createEvent($this->createPassport(new CsrfTokenBadge('authenticator_token_id', 'abc123'))); + + $this->expectException(InvalidCsrfTokenException::class); + $this->expectExceptionMessage('Invalid CSRF token.'); + $this->listener->checkPassport($event); } diff --git a/src/Symfony/Component/Security/Http/Tests/EventListener/IsGrantedAttributeListenerTest.php b/src/Symfony/Component/Security/Http/Tests/EventListener/IsGrantedAttributeListenerTest.php index 3f5f2ff7a01c7..2d03b7ac357ea 100644 --- a/src/Symfony/Component/Security/Http/Tests/EventListener/IsGrantedAttributeListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/EventListener/IsGrantedAttributeListenerTest.php @@ -191,8 +191,6 @@ public function testIsGrantedArrayWithNullValueSubjectFromArguments() public function testExceptionWhenMissingSubjectAttribute() { - $this->expectException(\RuntimeException::class); - $authChecker = $this->createMock(AuthorizationCheckerInterface::class); $event = new ControllerArgumentsEvent( @@ -204,6 +202,9 @@ public function testExceptionWhenMissingSubjectAttribute() ); $listener = new IsGrantedAttributeListener($authChecker); + + $this->expectException(\RuntimeException::class); + $listener->onKernelControllerArguments($event); } @@ -261,9 +262,6 @@ public static function getAccessDeniedMessageTests() public function testNotFoundHttpException() { - $this->expectException(HttpException::class); - $this->expectExceptionMessage('Not found'); - $authChecker = $this->createMock(AuthorizationCheckerInterface::class); $authChecker->expects($this->any()) ->method('isGranted') @@ -278,6 +276,10 @@ public function testNotFoundHttpException() ); $listener = new IsGrantedAttributeListener($authChecker); + + $this->expectException(HttpException::class); + $this->expectExceptionMessage('Not found'); + $listener->onKernelControllerArguments($event); } @@ -387,10 +389,6 @@ public function testIsGrantedWithRequestAsSubject() public function testHttpExceptionWithExceptionCode() { - $this->expectException(HttpException::class); - $this->expectExceptionMessage('Exception Code'); - $this->expectExceptionCode(10010); - $authChecker = $this->createMock(AuthorizationCheckerInterface::class); $authChecker->expects($this->any()) ->method('isGranted') @@ -405,15 +403,16 @@ public function testHttpExceptionWithExceptionCode() ); $listener = new IsGrantedAttributeListener($authChecker); + + $this->expectException(HttpException::class); + $this->expectExceptionMessage('Exception Code'); + $this->expectExceptionCode(10010); + $listener->onKernelControllerArguments($event); } public function testAccessDeniedExceptionWithExceptionCode() { - $this->expectException(AccessDeniedException::class); - $this->expectExceptionMessage('Exception Code'); - $this->expectExceptionCode(10010); - $authChecker = $this->createMock(AuthorizationCheckerInterface::class); $authChecker->expects($this->any()) ->method('isGranted') @@ -428,6 +427,11 @@ public function testAccessDeniedExceptionWithExceptionCode() ); $listener = new IsGrantedAttributeListener($authChecker); + + $this->expectException(AccessDeniedException::class); + $this->expectExceptionMessage('Exception Code'); + $this->expectExceptionCode(10010); + $listener->onKernelControllerArguments($event); } } diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/AccessListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/AccessListenerTest.php index 181454e43ec33..e9bc31587ffba 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/AccessListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/AccessListenerTest.php @@ -32,7 +32,6 @@ class AccessListenerTest extends TestCase { public function testHandleWhenTheAccessDecisionManagerDecidesToRefuseAccess() { - $this->expectException(AccessDeniedException::class); $request = new Request(); $accessMap = $this->createMock(AccessMapInterface::class); @@ -70,6 +69,8 @@ public function getCredentials(): mixed $accessMap ); + $this->expectException(AccessDeniedException::class); + $listener(new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MAIN_REQUEST)); } @@ -131,7 +132,6 @@ public function testHandleWhenAccessMapReturnsEmptyAttributes() public function testHandleWhenTheSecurityTokenStorageHasNoToken() { - $this->expectException(AccessDeniedException::class); $tokenStorage = new TokenStorage(); $request = new Request(); @@ -155,6 +155,8 @@ public function testHandleWhenTheSecurityTokenStorageHasNoToken() false ); + $this->expectException(AccessDeniedException::class); + $listener(new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MAIN_REQUEST)); } diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/LogoutListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/LogoutListenerTest.php index 06139bcca1aff..c7cdc7abd216a 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/LogoutListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/LogoutListenerTest.php @@ -122,8 +122,6 @@ public function testHandleMatchedPathWithoutCsrfValidation() public function testNoResponseSet() { - $this->expectException(\RuntimeException::class); - [$listener, , $httpUtils, $options] = $this->getListener(); $request = new Request(); @@ -133,6 +131,8 @@ public function testNoResponseSet() ->with($request, $options['logout_path']) ->willReturn(true); + $this->expectException(\RuntimeException::class); + $listener(new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MAIN_REQUEST)); } @@ -141,7 +141,6 @@ public function testNoResponseSet() */ public function testCsrfValidationFails($invalidToken) { - $this->expectException(LogoutException::class); $tokenManager = $this->getTokenManager(); [$listener, , $httpUtils, $options] = $this->getListener(null, $tokenManager); @@ -160,6 +159,8 @@ public function testCsrfValidationFails($invalidToken) ->method('isTokenValid') ->willReturn(false); + $this->expectException(LogoutException::class); + $listener(new RequestEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MAIN_REQUEST)); } diff --git a/src/Symfony/Component/Security/Http/Tests/Firewall/SwitchUserListenerTest.php b/src/Symfony/Component/Security/Http/Tests/Firewall/SwitchUserListenerTest.php index 916e54d669376..46da56485d529 100644 --- a/src/Symfony/Component/Security/Http/Tests/Firewall/SwitchUserListenerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Firewall/SwitchUserListenerTest.php @@ -68,22 +68,26 @@ public function testEventIsIgnoredIfUsernameIsNotPassedWithTheRequest() public function testExitUserThrowsAuthenticationExceptionIfNoCurrentToken() { - $this->expectException(AuthenticationCredentialsNotFoundException::class); $this->tokenStorage->setToken(null); $this->request->query->set('_switch_user', '_exit'); $listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager); + + $this->expectException(AuthenticationCredentialsNotFoundException::class); + $listener($this->event); } public function testExitUserThrowsAuthenticationExceptionIfOriginalTokenCannotBeFound() { - $this->expectException(AuthenticationCredentialsNotFoundException::class); $token = new UsernamePasswordToken(new InMemoryUser('username', '', ['ROLE_FOO']), 'key', ['ROLE_FOO']); $this->tokenStorage->setToken($token); $this->request->query->set('_switch_user', SwitchUserListener::EXIT_VALUE); $listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager); + + $this->expectException(AuthenticationCredentialsNotFoundException::class); + $listener($this->event); } @@ -134,7 +138,6 @@ public function testExitUserDispatchesEventWithRefreshedUser() public function testSwitchUserIsDisallowed() { - $this->expectException(AccessDeniedException::class); $token = new UsernamePasswordToken(new InMemoryUser('username', '', ['ROLE_FOO']), 'key', ['ROLE_FOO']); $user = new InMemoryUser('username', 'password', []); @@ -146,12 +149,14 @@ public function testSwitchUserIsDisallowed() ->willReturn(false); $listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager); + + $this->expectException(AccessDeniedException::class); + $listener($this->event); } public function testSwitchUserTurnsAuthenticationExceptionTo403() { - $this->expectException(AccessDeniedException::class); $token = new UsernamePasswordToken(new InMemoryUser('username', '', ['ROLE_ALLOWED_TO_SWITCH']), 'key', ['ROLE_ALLOWED_TO_SWITCH']); $this->tokenStorage->setToken($token); @@ -161,6 +166,9 @@ public function testSwitchUserTurnsAuthenticationExceptionTo403() ->method('decide'); $listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager); + + $this->expectException(AccessDeniedException::class); + $listener($this->event); } @@ -303,10 +311,12 @@ public function testSwitchUserWithReplacedToken() public function testSwitchUserThrowsAuthenticationExceptionIfNoCurrentToken() { - $this->expectException(AuthenticationCredentialsNotFoundException::class); $this->tokenStorage->setToken(null); $this->request->query->set('_switch_user', 'username'); $listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager); + + $this->expectException(AuthenticationCredentialsNotFoundException::class); + $listener($this->event); } diff --git a/src/Symfony/Component/Security/Http/Tests/HttpUtilsTest.php b/src/Symfony/Component/Security/Http/Tests/HttpUtilsTest.php index e165a4df52c4d..ccb538f953df9 100644 --- a/src/Symfony/Component/Security/Http/Tests/HttpUtilsTest.php +++ b/src/Symfony/Component/Security/Http/Tests/HttpUtilsTest.php @@ -306,7 +306,6 @@ public function testCheckRequestPathWithUrlMatcherAndResourceFoundByRequest() public function testCheckRequestPathWithUrlMatcherLoadingException() { - $this->expectException(\RuntimeException::class); $urlMatcher = $this->createMock(UrlMatcherInterface::class); $urlMatcher ->expects($this->any()) @@ -315,6 +314,9 @@ public function testCheckRequestPathWithUrlMatcherLoadingException() ; $utils = new HttpUtils(null, $urlMatcher); + + $this->expectException(\RuntimeException::class); + $utils->checkRequestPath($this->getRequest(), 'foobar'); } @@ -369,8 +371,7 @@ public function testUrlGeneratorIsRequiredToGenerateUrl() { $this->expectException(\LogicException::class); $this->expectExceptionMessage('You must provide a UrlGeneratorInterface instance to be able to use routes.'); - $utils = new HttpUtils(); - $utils->generateUri(new Request(), 'route_name'); + (new HttpUtils())->generateUri(new Request(), 'route_name'); } private function getUrlGenerator($generatedUrl = '/foo/bar') diff --git a/src/Symfony/Component/Security/Http/Tests/Logout/LogoutUrlGeneratorTest.php b/src/Symfony/Component/Security/Http/Tests/Logout/LogoutUrlGeneratorTest.php index c0e5dcbe38521..7073f35496006 100644 --- a/src/Symfony/Component/Security/Http/Tests/Logout/LogoutUrlGeneratorTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Logout/LogoutUrlGeneratorTest.php @@ -46,9 +46,10 @@ public function testGetLogoutPath() public function testGetLogoutPathWithoutLogoutListenerRegisteredForKeyThrowsException() { + $this->generator->registerListener('secured_area', '/logout', null, null, null); + $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('No LogoutListener found for firewall key "unregistered_key".'); - $this->generator->registerListener('secured_area', '/logout', null, null, null); $this->generator->getLogoutPath('unregistered_key'); } @@ -88,20 +89,22 @@ public function testGuessFromTokenWithoutFirewallNameFallbacksToCurrentFirewall( public function testUnableToGuessWithoutCurrentFirewallThrowsException() { + $this->generator->registerListener('secured_area', '/logout', null, null); + $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('This request is not behind a firewall, pass the firewall name manually to generate a logout URL.'); - $this->generator->registerListener('secured_area', '/logout', null, null); $this->generator->getLogoutPath(); } public function testUnableToGuessWithCurrentFirewallThrowsException() { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('Unable to find logout in the current firewall, pass the firewall name manually to generate a logout URL.'); $this->generator->registerListener('secured_area', '/logout', null, null); $this->generator->setCurrentFirewall('admin'); + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Unable to find logout in the current firewall, pass the firewall name manually to generate a logout URL.'); + $this->generator->getLogoutPath(); } } diff --git a/src/Symfony/Component/Security/Http/Tests/RememberMe/PersistentRememberMeHandlerTest.php b/src/Symfony/Component/Security/Http/Tests/RememberMe/PersistentRememberMeHandlerTest.php index 39c7a9f3ed7b8..80753fcebb0c2 100644 --- a/src/Symfony/Component/Security/Http/Tests/RememberMe/PersistentRememberMeHandlerTest.php +++ b/src/Symfony/Component/Security/Http/Tests/RememberMe/PersistentRememberMeHandlerTest.php @@ -129,8 +129,6 @@ public function testConsumeRememberMeCookieValidByValidatorWithoutUpdate() public function testConsumeRememberMeCookieInvalidToken() { - $this->expectException(CookieTheftException::class); - $this->tokenProvider->expects($this->any()) ->method('loadTokenBySeries') ->with('series1') @@ -138,14 +136,13 @@ public function testConsumeRememberMeCookieInvalidToken() $this->tokenProvider->expects($this->never())->method('updateToken')->with('series1'); + $this->expectException(CookieTheftException::class); + $this->handler->consumeRememberMeCookie(new RememberMeDetails(InMemoryUser::class, 'wouter', 360, 'series1:tokenvalue')); } public function testConsumeRememberMeCookieExpired() { - $this->expectException(AuthenticationException::class); - $this->expectExceptionMessage('The cookie has expired.'); - $this->tokenProvider->expects($this->any()) ->method('loadTokenBySeries') ->with('series1') @@ -153,6 +150,9 @@ public function testConsumeRememberMeCookieExpired() $this->tokenProvider->expects($this->never())->method('updateToken')->with('series1'); + $this->expectException(AuthenticationException::class); + $this->expectExceptionMessage('The cookie has expired.'); + $this->handler->consumeRememberMeCookie(new RememberMeDetails(InMemoryUser::class, 'wouter', 360, 'series1:tokenvalue')); } diff --git a/src/Symfony/Component/Security/Http/Tests/Session/SessionAuthenticationStrategyTest.php b/src/Symfony/Component/Security/Http/Tests/Session/SessionAuthenticationStrategyTest.php index b52b2f5a522c8..158baf68a330a 100644 --- a/src/Symfony/Component/Security/Http/Tests/Session/SessionAuthenticationStrategyTest.php +++ b/src/Symfony/Component/Security/Http/Tests/Session/SessionAuthenticationStrategyTest.php @@ -31,12 +31,14 @@ public function testSessionIsNotChanged() public function testUnsupportedStrategy() { - $this->expectException(\RuntimeException::class); - $this->expectExceptionMessage('Invalid session authentication strategy "foo"'); $request = $this->getRequest(); $request->expects($this->never())->method('getSession'); $strategy = new SessionAuthenticationStrategy('foo'); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Invalid session authentication strategy "foo"'); + $strategy->onAuthentication($request, $this->createMock(TokenInterface::class)); } diff --git a/src/Symfony/Component/Serializer/Tests/Annotation/SerializedNameTest.php b/src/Symfony/Component/Serializer/Tests/Annotation/SerializedNameTest.php index c2b5e5f2ab6b3..3a829aecf4f84 100644 --- a/src/Symfony/Component/Serializer/Tests/Annotation/SerializedNameTest.php +++ b/src/Symfony/Component/Serializer/Tests/Annotation/SerializedNameTest.php @@ -30,7 +30,7 @@ public function testNotAStringSerializedNameParameter() public function testSerializedNameParameters() { - $maxDepth = new SerializedName('foo'); - $this->assertEquals('foo', $maxDepth->getSerializedName()); + $foo = new SerializedName('foo'); + $this->assertEquals('foo', $foo->getSerializedName()); } } diff --git a/src/Symfony/Component/Serializer/Tests/DependencyInjection/SerializerPassTest.php b/src/Symfony/Component/Serializer/Tests/DependencyInjection/SerializerPassTest.php index eb77263f49fc9..037eafdb66665 100644 --- a/src/Symfony/Component/Serializer/Tests/DependencyInjection/SerializerPassTest.php +++ b/src/Symfony/Component/Serializer/Tests/DependencyInjection/SerializerPassTest.php @@ -28,20 +28,20 @@ class SerializerPassTest extends TestCase { public function testThrowExceptionWhenNoNormalizers() { - $this->expectException(\RuntimeException::class); - $this->expectExceptionMessage('You must tag at least one service as "serializer.normalizer" to use the "serializer" service'); $container = new ContainerBuilder(); $container->setParameter('kernel.debug', false); $container->register('serializer'); $serializerPass = new SerializerPass(); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('You must tag at least one service as "serializer.normalizer" to use the "serializer" service'); + $serializerPass->process($container); } public function testThrowExceptionWhenNoEncoders() { - $this->expectException(\RuntimeException::class); - $this->expectExceptionMessage('You must tag at least one service as "serializer.encoder" to use the "serializer" service'); $container = new ContainerBuilder(); $container->setParameter('kernel.debug', false); $container->register('serializer') @@ -50,6 +50,10 @@ public function testThrowExceptionWhenNoEncoders() $container->register('normalizer')->addTag('serializer.normalizer'); $serializerPass = new SerializerPass(); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('You must tag at least one service as "serializer.encoder" to use the "serializer" service'); + $serializerPass->process($container); } diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/JsonDecodeTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/JsonDecodeTest.php index 66cd10114cc90..f336bcd42f8a9 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/JsonDecodeTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/JsonDecodeTest.php @@ -47,11 +47,9 @@ public static function decodeProvider() $stdClass = new \stdClass(); $stdClass->foo = 'bar'; - $assoc = ['foo' => 'bar']; - return [ ['{"foo": "bar"}', $stdClass, []], - ['{"foo": "bar"}', $assoc, ['json_decode_associative' => true]], + ['{"foo": "bar"}', ['foo' => 'bar'], ['json_decode_associative' => true]], ]; } diff --git a/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncoderTest.php b/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncoderTest.php index 1b47684ae1c8d..a34e82c6b09a5 100644 --- a/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncoderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Encoder/JsonEncoderTest.php @@ -84,12 +84,13 @@ public function testWithDefaultContext() public function testEncodeNotUtf8WithoutPartialOnError() { - $this->expectException(UnexpectedValueException::class); $arr = [ 'utf8' => 'Hello World!', 'notUtf8' => "\xb0\xd0\xb5\xd0", ]; + $this->expectException(UnexpectedValueException::class); + $this->encoder->encode($arr, 'json'); } diff --git a/src/Symfony/Component/Serializer/Tests/Mapping/Factory/CacheMetadataFactoryTest.php b/src/Symfony/Component/Serializer/Tests/Mapping/Factory/CacheMetadataFactoryTest.php index 9525ca6059fb3..6db0b95ae2403 100644 --- a/src/Symfony/Component/Serializer/Tests/Mapping/Factory/CacheMetadataFactoryTest.php +++ b/src/Symfony/Component/Serializer/Tests/Mapping/Factory/CacheMetadataFactoryTest.php @@ -58,10 +58,11 @@ public function testHasMetadataFor() public function testInvalidClassThrowsException() { - $this->expectException(InvalidArgumentException::class); $decorated = $this->createMock(ClassMetadataFactoryInterface::class); $factory = new CacheClassMetadataFactory($decorated, new ArrayAdapter()); + $this->expectException(InvalidArgumentException::class); + $factory->getMetadataFor('Not\Exist'); } diff --git a/src/Symfony/Component/Serializer/Tests/Mapping/Factory/CompiledClassMetadataFactoryTest.php b/src/Symfony/Component/Serializer/Tests/Mapping/Factory/CompiledClassMetadataFactoryTest.php index 683f445dfe2b0..ff54fb96b7af1 100644 --- a/src/Symfony/Component/Serializer/Tests/Mapping/Factory/CompiledClassMetadataFactoryTest.php +++ b/src/Symfony/Component/Serializer/Tests/Mapping/Factory/CompiledClassMetadataFactoryTest.php @@ -34,19 +34,21 @@ public function testItImplementsClassMetadataFactoryInterface() public function testItThrowAnExceptionWhenCacheFileIsNotFound() { + $classMetadataFactory = $this->createMock(ClassMetadataFactoryInterface::class); + $this->expectException(\RuntimeException::class); $this->expectExceptionMessageMatches('#File ".*/Fixtures/not-found-serializer.class.metadata.php" could not be found.#'); - $classMetadataFactory = $this->createMock(ClassMetadataFactoryInterface::class); new CompiledClassMetadataFactory(__DIR__.'/../../Fixtures/not-found-serializer.class.metadata.php', $classMetadataFactory); } public function testItThrowAnExceptionWhenMetadataIsNotOfTypeArray() { + $classMetadataFactory = $this->createMock(ClassMetadataFactoryInterface::class); + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Compiled metadata must be of the type array, object given.'); - $classMetadataFactory = $this->createMock(ClassMetadataFactoryInterface::class); new CompiledClassMetadataFactory(__DIR__.'/../../Fixtures/object-metadata.php', $classMetadataFactory); } diff --git a/src/Symfony/Component/Serializer/Tests/Mapping/Loader/YamlFileLoaderTest.php b/src/Symfony/Component/Serializer/Tests/Mapping/Loader/YamlFileLoaderTest.php index ea81a9d8ad7cd..48e95aecd9245 100644 --- a/src/Symfony/Component/Serializer/Tests/Mapping/Loader/YamlFileLoaderTest.php +++ b/src/Symfony/Component/Serializer/Tests/Mapping/Loader/YamlFileLoaderTest.php @@ -65,8 +65,10 @@ public function testLoadClassMetadataReturnsFalseWhenEmpty() public function testLoadClassMetadataReturnsThrowsInvalidMapping() { - $this->expectException(MappingException::class); $loader = new YamlFileLoader(__DIR__.'/../../Fixtures/invalid-mapping.yml'); + + $this->expectException(MappingException::class); + $loader->loadClassMetadata($this->metadata); } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php index 0b91fc0dbc288..ca3c7579be301 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php @@ -82,10 +82,12 @@ public function testInstantiateObjectDenormalizer() public function testDenormalizeWithExtraAttribute() { - $this->expectException(ExtraAttributesException::class); - $this->expectExceptionMessage('Extra attributes are not allowed ("fooFoo" is unknown).'); $factory = new ClassMetadataFactory(new AttributeLoader()); $normalizer = new AbstractObjectNormalizerDummy($factory); + + $this->expectException(ExtraAttributesException::class); + $this->expectExceptionMessage('Extra attributes are not allowed ("fooFoo" is unknown).'); + $normalizer->denormalize( ['fooFoo' => 'foo'], Dummy::class, @@ -96,10 +98,12 @@ public function testDenormalizeWithExtraAttribute() public function testDenormalizeWithExtraAttributes() { - $this->expectException(ExtraAttributesException::class); - $this->expectExceptionMessage('Extra attributes are not allowed ("fooFoo", "fooBar" are unknown).'); $factory = new ClassMetadataFactory(new AttributeLoader()); $normalizer = new AbstractObjectNormalizerDummy($factory); + + $this->expectException(ExtraAttributesException::class); + $this->expectExceptionMessage('Extra attributes are not allowed ("fooFoo", "fooBar" are unknown).'); + $normalizer->denormalize( ['fooFoo' => 'foo', 'fooBar' => 'bar'], Dummy::class, @@ -110,9 +114,11 @@ public function testDenormalizeWithExtraAttributes() public function testDenormalizeWithExtraAttributesAndNoGroupsWithMetadataFactory() { + $normalizer = new AbstractObjectNormalizerWithMetadata(); + $this->expectException(ExtraAttributesException::class); $this->expectExceptionMessage('Extra attributes are not allowed ("fooFoo", "fooBar" are unknown).'); - $normalizer = new AbstractObjectNormalizerWithMetadata(); + $normalizer->denormalize( ['fooFoo' => 'foo', 'fooBar' => 'bar', 'bar' => 'bar'], Dummy::class, @@ -134,9 +140,11 @@ public function testDenormalizePlainObject() public function testDenormalizeWithDuplicateNestedAttributes() { + $normalizer = new AbstractObjectNormalizerWithMetadata(); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Duplicate serialized path: "one,two,three" used for properties "foo" and "bar".'); - $normalizer = new AbstractObjectNormalizerWithMetadata(); + $normalizer->denormalize([], DuplicateValueNestedDummy::class, 'any'); } @@ -204,8 +212,6 @@ public function testDenormalizeWithNestedAttributes() public function testDenormalizeWithNestedAttributesDuplicateKeys() { - $this->expectException(LogicException::class); - $this->expectExceptionMessage('Duplicate values for key "quux" found. One value is set via the SerializedPath attribute: "one->four", the other one is set via the SerializedName attribute: "notquux".'); $normalizer = new AbstractObjectNormalizerWithMetadata(); $data = [ 'one' => [ @@ -213,6 +219,10 @@ public function testDenormalizeWithNestedAttributesDuplicateKeys() ], 'quux' => 'notquux', ]; + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Duplicate values for key "quux" found. One value is set via the SerializedPath attribute: "one->four", the other one is set via the SerializedName attribute: "notquux".'); + $normalizer->denormalize($data, DuplicateKeyNestedDummy::class, 'any'); } @@ -265,25 +275,29 @@ public function testDenormalizeWithNestedAttributesInConstructorAndDiscriminator public function testNormalizeWithNestedAttributesMixingArrayTypes() { - $this->expectException(LogicException::class); - $this->expectExceptionMessage('The element you are trying to set is already populated: "[one][two]"'); $foobar = new AlreadyPopulatedNestedDummy(); $foobar->foo = 'foo'; $foobar->bar = 'bar'; $classMetadataFactory = new ClassMetadataFactory(new AttributeLoader()); $normalizer = new ObjectNormalizer($classMetadataFactory, new MetadataAwareNameConverter($classMetadataFactory)); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('The element you are trying to set is already populated: "[one][two]"'); + $normalizer->normalize($foobar, 'any'); } public function testNormalizeWithNestedAttributesElementAlreadySet() { - $this->expectException(LogicException::class); - $this->expectExceptionMessage('The element you are trying to set is already populated: "[one][two][three]"'); $foobar = new DuplicateValueNestedDummy(); $foobar->foo = 'foo'; $foobar->bar = 'bar'; $classMetadataFactory = new ClassMetadataFactory(new AttributeLoader()); $normalizer = new ObjectNormalizer($classMetadataFactory, new MetadataAwareNameConverter($classMetadataFactory)); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('The element you are trying to set is already populated: "[one][two][three]"'); + $normalizer->normalize($foobar, 'any'); } @@ -691,9 +705,10 @@ private function getDenormalizerForObjectWithBasicProperties() */ public function testExtraAttributesException() { + $normalizer = new ObjectNormalizer(); + $this->expectException(LogicException::class); $this->expectExceptionMessage('A class metadata factory must be provided in the constructor when setting "allow_extra_attributes" to false.'); - $normalizer = new ObjectNormalizer(); $normalizer->denormalize([], \stdClass::class, 'xml', [ 'allow_extra_attributes' => false, diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/DataUriNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/DataUriNormalizerTest.php index 92e173fe096ad..7e9af436038fe 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/DataUriNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/DataUriNormalizerTest.php @@ -121,7 +121,7 @@ public function testGiveNotAccessToLocalFiles() /** * @dataProvider invalidUriProvider */ - public function testInvalidData($uri) + public function testInvalidData(?string $uri) { $this->expectException(UnexpectedValueException::class); $this->normalizer->denormalize($uri, 'SplFileObject'); @@ -148,7 +148,7 @@ public static function invalidUriProvider() /** * @dataProvider validUriProvider */ - public function testValidData($uri) + public function testValidData(string $uri) { $this->assertInstanceOf(\SplFileObject::class, $this->normalizer->denormalize($uri, 'SplFileObject')); } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php index 1d471981e4f0e..eb2b6530678c2 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php @@ -374,8 +374,6 @@ protected function getDenormalizerForIgnoredAttributes(): GetSetMethodNormalizer public function testUnableToNormalizeObjectAttribute() { - $this->expectException(LogicException::class); - $this->expectExceptionMessage('Cannot normalize attribute "object" because the injected serializer is not a normalizer'); $serializer = $this->createMock(SerializerInterface::class); $this->normalizer->setSerializer($serializer); @@ -383,6 +381,9 @@ public function testUnableToNormalizeObjectAttribute() $object = new \stdClass(); $obj->setObject($object); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Cannot normalize attribute "object" because the injected serializer is not a normalizer'); + $this->normalizer->normalize($obj, 'any'); } @@ -391,14 +392,12 @@ public function testSiblingReference() $serializer = new Serializer([$this->normalizer]); $this->normalizer->setSerializer($serializer); - $siblingHolder = new SiblingHolder(); - $expected = [ 'sibling0' => ['coopTilleuls' => 'Les-Tilleuls.coop'], 'sibling1' => ['coopTilleuls' => 'Les-Tilleuls.coop'], 'sibling2' => ['coopTilleuls' => 'Les-Tilleuls.coop'], ]; - $this->assertEquals($expected, $this->normalizer->normalize($siblingHolder)); + $this->assertEquals($expected, $this->normalizer->normalize(new SiblingHolder())); } public function testDenormalizeNonExistingAttribute() diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php index 54a977f55ec3b..f8f8546d7cb39 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php @@ -68,9 +68,10 @@ public function testNormalize() public function testCircularNormalize() { - $this->expectException(CircularReferenceException::class); $this->createNormalizer([JsonSerializableNormalizer::CIRCULAR_REFERENCE_LIMIT => 1]); + $this->expectException(CircularReferenceException::class); + $this->serializer ->expects($this->once()) ->method('normalize') diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php index f9f2e8ad040d6..05b1891f50119 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php @@ -307,8 +307,6 @@ public function testConstructorWithUnconstructableNullableObjectTypeHintDenormal public function testConstructorWithUnknownObjectTypeHintDenormalize() { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('Could not determine the class of the parameter "unknown".'); $data = [ 'id' => 10, 'unknown' => [ @@ -321,6 +319,9 @@ public function testConstructorWithUnknownObjectTypeHintDenormalize() $serializer = new Serializer([$normalizer]); $normalizer->setSerializer($serializer); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Could not determine the class of the parameter "unknown".'); + $normalizer->denormalize($data, DummyWithConstructorInexistingObject::class); } @@ -623,8 +624,6 @@ protected function getDenormalizerForTypeEnforcement(): ObjectNormalizer public function testUnableToNormalizeObjectAttribute() { - $this->expectException(LogicException::class); - $this->expectExceptionMessage('Cannot normalize attribute "object" because the injected serializer is not a normalizer'); $serializer = $this->createMock(SerializerInterface::class); $this->normalizer->setSerializer($serializer); @@ -632,6 +631,9 @@ public function testUnableToNormalizeObjectAttribute() $object = new \stdClass(); $obj->setObject($object); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Cannot normalize attribute "object" because the injected serializer is not a normalizer'); + $this->normalizer->normalize($obj, 'any'); } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/PropertyNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/PropertyNormalizerTest.php index 631111d2a2b6c..585c2068ec682 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/PropertyNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/PropertyNormalizerTest.php @@ -400,8 +400,6 @@ public function testDenormalizeShouldIgnoreStaticProperty() public function testUnableToNormalizeObjectAttribute() { - $this->expectException(LogicException::class); - $this->expectExceptionMessage('Cannot normalize attribute "bar" because the injected serializer is not a normalizer'); $serializer = $this->createMock(SerializerInterface::class); $this->normalizer->setSerializer($serializer); @@ -409,6 +407,9 @@ public function testUnableToNormalizeObjectAttribute() $object = new \stdClass(); $obj->setBar($object); + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Cannot normalize attribute "bar" because the injected serializer is not a normalizer'); + $this->normalizer->normalize($obj, 'any'); } diff --git a/src/Symfony/Component/Serializer/Tests/SerializerTest.php b/src/Symfony/Component/Serializer/Tests/SerializerTest.php index 6248531076558..45d467064e306 100644 --- a/src/Symfony/Component/Serializer/Tests/SerializerTest.php +++ b/src/Symfony/Component/Serializer/Tests/SerializerTest.php @@ -97,8 +97,10 @@ public function testItThrowsExceptionOnInvalidEncoder() public function testNormalizeNoMatch() { - $this->expectException(UnexpectedValueException::class); $serializer = new Serializer([$this->createMock(NormalizerInterface::class)]); + + $this->expectException(UnexpectedValueException::class); + $serializer->normalize(new \stdClass(), 'xml'); } @@ -118,15 +120,19 @@ public function testNormalizeGivesPriorityToInterfaceOverTraversable() public function testNormalizeOnDenormalizer() { - $this->expectException(UnexpectedValueException::class); $serializer = new Serializer([new TestDenormalizer()], []); + + $this->expectException(UnexpectedValueException::class); + $this->assertTrue($serializer->normalize(new \stdClass(), 'json')); } public function testDenormalizeNoMatch() { - $this->expectException(UnexpectedValueException::class); $serializer = new Serializer([$this->createMock(NormalizerInterface::class)]); + + $this->expectException(UnexpectedValueException::class); + $serializer->denormalize('foo', 'stdClass'); } @@ -140,9 +146,11 @@ public function testDenormalizeOnObjectThatOnlySupportsDenormalization() public function testDenormalizeOnNormalizer() { - $this->expectException(UnexpectedValueException::class); $serializer = new Serializer([new TestNormalizer()], []); $data = ['title' => 'foo', 'numbers' => [5, 3]]; + + $this->expectException(UnexpectedValueException::class); + $this->assertTrue($serializer->denormalize(json_encode($data), 'stdClass', 'json')); } @@ -237,17 +245,21 @@ public function testSerializeEmpty() public function testSerializeNoEncoder() { - $this->expectException(UnexpectedValueException::class); $serializer = new Serializer([], []); $data = ['title' => 'foo', 'numbers' => [5, 3]]; + + $this->expectException(UnexpectedValueException::class); + $serializer->serialize($data, 'json'); } public function testSerializeNoNormalizer() { - $this->expectException(LogicException::class); $serializer = new Serializer([], ['json' => new JsonEncoder()]); $data = ['title' => 'foo', 'numbers' => [5, 3]]; + + $this->expectException(LogicException::class); + $serializer->serialize(Model::fromArray($data), 'json'); } @@ -271,25 +283,31 @@ public function testDeserializeUseCache() public function testDeserializeNoNormalizer() { - $this->expectException(LogicException::class); $serializer = new Serializer([], ['json' => new JsonEncoder()]); $data = ['title' => 'foo', 'numbers' => [5, 3]]; + + $this->expectException(LogicException::class); + $serializer->deserialize(json_encode($data), Model::class, 'json'); } public function testDeserializeWrongNormalizer() { - $this->expectException(UnexpectedValueException::class); $serializer = new Serializer([new CustomNormalizer()], ['json' => new JsonEncoder()]); $data = ['title' => 'foo', 'numbers' => [5, 3]]; + + $this->expectException(UnexpectedValueException::class); + $serializer->deserialize(json_encode($data), Model::class, 'json'); } public function testDeserializeNoEncoder() { - $this->expectException(UnexpectedValueException::class); $serializer = new Serializer([], []); $data = ['title' => 'foo', 'numbers' => [5, 3]]; + + $this->expectException(UnexpectedValueException::class); + $serializer->deserialize(json_encode($data), Model::class, 'json'); } @@ -689,29 +707,37 @@ public function testDeserializeScalar() public function testDeserializeLegacyScalarType() { - $this->expectException(LogicException::class); $serializer = new Serializer([], ['json' => new JsonEncoder()]); + + $this->expectException(LogicException::class); + $serializer->deserialize('42', 'integer', 'json'); } public function testDeserializeScalarTypeToCustomType() { - $this->expectException(LogicException::class); $serializer = new Serializer([], ['json' => new JsonEncoder()]); + + $this->expectException(LogicException::class); + $serializer->deserialize('"something"', Foo::class, 'json'); } public function testDeserializeNonscalarTypeToScalar() { - $this->expectException(NotNormalizableValueException::class); $serializer = new Serializer([], ['json' => new JsonEncoder()]); + + $this->expectException(NotNormalizableValueException::class); + $serializer->deserialize('{"foo":true}', 'string', 'json'); } public function testDeserializeInconsistentScalarType() { - $this->expectException(NotNormalizableValueException::class); $serializer = new Serializer([], ['json' => new JsonEncoder()]); + + $this->expectException(NotNormalizableValueException::class); + $serializer->deserialize('"42"', 'int', 'json'); } @@ -727,8 +753,10 @@ public function testDeserializeScalarArray() public function testDeserializeInconsistentScalarArray() { - $this->expectException(NotNormalizableValueException::class); $serializer = new Serializer([new ArrayDenormalizer()], ['json' => new JsonEncoder()]); + + $this->expectException(NotNormalizableValueException::class); + $serializer->deserialize('["42"]', 'int[]', 'json'); } diff --git a/src/Symfony/Component/Stopwatch/Tests/StopwatchEventTest.php b/src/Symfony/Component/Stopwatch/Tests/StopwatchEventTest.php index 82b3c832a77d0..fcc2436054716 100644 --- a/src/Symfony/Component/Stopwatch/Tests/StopwatchEventTest.php +++ b/src/Symfony/Component/Stopwatch/Tests/StopwatchEventTest.php @@ -122,8 +122,10 @@ public function testDurationWithMultipleStarts() public function testStopWithoutStart() { - $this->expectException(\LogicException::class); $event = new StopwatchEvent(microtime(true) * 1000); + + $this->expectException(\LogicException::class); + $event->stop(); } diff --git a/src/Symfony/Component/Stopwatch/Tests/StopwatchTest.php b/src/Symfony/Component/Stopwatch/Tests/StopwatchTest.php index 6be89b80efa41..68585d2f8e3c6 100644 --- a/src/Symfony/Component/Stopwatch/Tests/StopwatchTest.php +++ b/src/Symfony/Component/Stopwatch/Tests/StopwatchTest.php @@ -88,15 +88,15 @@ public function testStop() public function testUnknownEvent() { $this->expectException(\LogicException::class); - $stopwatch = new Stopwatch(); - $stopwatch->getEvent('foo'); + + (new Stopwatch())->getEvent('foo'); } public function testStopWithoutStart() { $this->expectException(\LogicException::class); - $stopwatch = new Stopwatch(); - $stopwatch->stop('foo'); + + (new Stopwatch())->stop('foo'); } public function testMorePrecision() @@ -159,8 +159,8 @@ public function testReopenASection() public function testReopenANewSectionShouldThrowAnException() { $this->expectException(\LogicException::class); - $stopwatch = new Stopwatch(); - $stopwatch->openSection('section'); + + (new Stopwatch())->openSection('section'); } public function testReset() diff --git a/src/Symfony/Component/Translation/Bridge/Phrase/Tests/PhraseProviderFactoryTest.php b/src/Symfony/Component/Translation/Bridge/Phrase/Tests/PhraseProviderFactoryTest.php index 5eac650385b5f..6521656af7d6e 100644 --- a/src/Symfony/Component/Translation/Bridge/Phrase/Tests/PhraseProviderFactoryTest.php +++ b/src/Symfony/Component/Translation/Bridge/Phrase/Tests/PhraseProviderFactoryTest.php @@ -62,13 +62,13 @@ public function testCreate(string $expected, string $dsn) */ public function testUnsupportedSchemeException(string $dsn, string $message) { + $factory = $this->createFactory(); + $dsn = new Dsn($dsn); + $this->expectException(UnsupportedSchemeException::class); $this->expectExceptionMessage($message); - $dsn = new Dsn($dsn); - - $this->createFactory() - ->create($dsn); + $factory->create($dsn); } /** @@ -76,24 +76,24 @@ public function testUnsupportedSchemeException(string $dsn, string $message) */ public function testIncompleteDsnException(string $dsn, string $message) { + $factory = $this->createFactory(); + $dsn = new Dsn($dsn); + $this->expectException(IncompleteDsnException::class); $this->expectExceptionMessage($message); - $dsn = new Dsn($dsn); - - $this->createFactory() - ->create($dsn); + $factory->create($dsn); } public function testRequiredUserAgentOption() { + $factory = $this->createFactory(); + $dsn = new Dsn('phrase://PROJECT_ID:API_TOKEN@default'); + $this->expectException(MissingRequiredOptionException::class); $this->expectExceptionMessage('The option "userAgent" is required but missing.'); - $dsn = new Dsn('phrase://PROJECT_ID:API_TOKEN@default'); - - $this->createFactory() - ->create($dsn); + $factory->create($dsn); } public function testHttpClientConfig() diff --git a/src/Symfony/Component/Translation/Bridge/Phrase/Tests/PhraseProviderTest.php b/src/Symfony/Component/Translation/Bridge/Phrase/Tests/PhraseProviderTest.php index 089480b1c3d44..fd1c220935b7f 100644 --- a/src/Symfony/Component/Translation/Bridge/Phrase/Tests/PhraseProviderTest.php +++ b/src/Symfony/Component/Translation/Bridge/Phrase/Tests/PhraseProviderTest.php @@ -379,10 +379,6 @@ public function cacheKeyProvider(): \Generator */ public function testReadProviderExceptions(int $statusCode, string $expectedExceptionMessage, string $expectedLoggerMessage) { - $this->expectException(ProviderExceptionInterface::class); - $this->expectExceptionCode(0); - $this->expectExceptionMessage($expectedExceptionMessage); - $this->getLogger() ->expects(self::once()) ->method('error') @@ -407,6 +403,10 @@ public function testReadProviderExceptions(int $statusCode, string $expectedExce ], ]), endpoint: 'api.phrase.com/api/v2'); + $this->expectException(ProviderExceptionInterface::class); + $this->expectExceptionCode(0); + $this->expectExceptionMessage($expectedExceptionMessage); + $provider->read(['messages'], ['en_GB']); } @@ -415,10 +415,6 @@ public function testReadProviderExceptions(int $statusCode, string $expectedExce */ public function testInitLocalesExceptions(int $statusCode, string $expectedExceptionMessage, string $expectedLoggerMessage) { - $this->expectException(ProviderExceptionInterface::class); - $this->expectExceptionCode(0); - $this->expectExceptionMessage($expectedExceptionMessage); - $this->getLogger() ->expects(self::once()) ->method('error') @@ -442,6 +438,10 @@ public function testInitLocalesExceptions(int $statusCode, string $expectedExcep ], ]), endpoint: 'api.phrase.com/api/v2'); + $this->expectException(ProviderExceptionInterface::class); + $this->expectExceptionCode(0); + $this->expectExceptionMessage($expectedExceptionMessage); + $provider->read(['messages'], ['en_GB']); } @@ -539,10 +539,6 @@ public function testCreateUnknownLocale() */ public function testCreateLocaleExceptions(int $statusCode, string $expectedExceptionMessage, string $expectedLoggerMessage) { - $this->expectException(ProviderExceptionInterface::class); - $this->expectExceptionCode(0); - $this->expectExceptionMessage($expectedExceptionMessage); - $this->getLogger() ->expects(self::once()) ->method('error') @@ -567,6 +563,10 @@ public function testCreateLocaleExceptions(int $statusCode, string $expectedExce ], ]), endpoint: 'api.phrase.com/api/v2'); + $this->expectException(ProviderExceptionInterface::class); + $this->expectExceptionCode(0); + $this->expectExceptionMessage($expectedExceptionMessage); + $provider->read(['messages'], ['nl_NL']); } @@ -627,10 +627,6 @@ public function testDelete() */ public function testDeleteProviderExceptions(int $statusCode, string $expectedExceptionMessage, string $expectedLoggerMessage) { - $this->expectException(ProviderExceptionInterface::class); - $this->expectExceptionCode(0); - $this->expectExceptionMessage($expectedExceptionMessage); - $this->getLogger() ->expects(self::once()) ->method('error') @@ -661,6 +657,10 @@ public function testDeleteProviderExceptions(int $statusCode, string $expectedEx ], ])); + $this->expectException(ProviderExceptionInterface::class); + $this->expectExceptionCode(0); + $this->expectExceptionMessage($expectedExceptionMessage); + $provider->delete($bag); } @@ -745,10 +745,6 @@ public function testWrite(string $locale, string $localeId, string $domain, stri */ public function testWriteProviderExceptions(int $statusCode, string $expectedExceptionMessage, string $expectedLoggerMessage) { - $this->expectException(ProviderExceptionInterface::class); - $this->expectExceptionCode(0); - $this->expectExceptionMessage($expectedExceptionMessage); - $this->getLogger() ->expects(self::once()) ->method('error') @@ -784,6 +780,10 @@ public function testWriteProviderExceptions(int $statusCode, string $expectedExc ], ])); + $this->expectException(ProviderExceptionInterface::class); + $this->expectExceptionCode(0); + $this->expectExceptionMessage($expectedExceptionMessage); + $provider->write($bag); } diff --git a/src/Symfony/Component/Translation/Tests/Command/XliffLintCommandTest.php b/src/Symfony/Component/Translation/Tests/Command/XliffLintCommandTest.php index ee8e52e06dea0..454783494b574 100644 --- a/src/Symfony/Component/Translation/Tests/Command/XliffLintCommandTest.php +++ b/src/Symfony/Component/Translation/Tests/Command/XliffLintCommandTest.php @@ -120,11 +120,12 @@ public function testLintSucceedsWhenLocaleInFileAndInTargetLanguageNameUsesDashe public function testLintFileNotReadable() { - $this->expectException(\RuntimeException::class); $tester = $this->createCommandTester(); $filename = $this->createFile(); unlink($filename); + $this->expectException(\RuntimeException::class); + $tester->execute(['filename' => $filename], ['decorated' => false]); } diff --git a/src/Symfony/Component/Translation/Tests/DependencyInjection/TranslationExtractorPassTest.php b/src/Symfony/Component/Translation/Tests/DependencyInjection/TranslationExtractorPassTest.php index bcb2ccd454023..574c7338793ed 100644 --- a/src/Symfony/Component/Translation/Tests/DependencyInjection/TranslationExtractorPassTest.php +++ b/src/Symfony/Component/Translation/Tests/DependencyInjection/TranslationExtractorPassTest.php @@ -49,14 +49,16 @@ public function testProcessNoDefinitionFound() public function testProcessMissingAlias() { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('The alias for the tag "translation.extractor" of service "foo.id" must be set.'); $container = new ContainerBuilder(); $container->register('translation.extractor'); $container->register('foo.id') ->addTag('translation.extractor', []); $translationDumperPass = new TranslationExtractorPass(); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('The alias for the tag "translation.extractor" of service "foo.id" must be set.'); + $translationDumperPass->process($container); } } diff --git a/src/Symfony/Component/Translation/Tests/Formatter/IntlFormatterTest.php b/src/Symfony/Component/Translation/Tests/Formatter/IntlFormatterTest.php index 4bf8ed43e8389..9e2d22752bfd5 100644 --- a/src/Symfony/Component/Translation/Tests/Formatter/IntlFormatterTest.php +++ b/src/Symfony/Component/Translation/Tests/Formatter/IntlFormatterTest.php @@ -90,12 +90,22 @@ public static function provideDataForFormat() ]; } - public function testPercentsAndBracketsAreTrimmed() + /** + * @dataProvider percentAndBracketsAreTrimmedProvider + */ + public function testPercentsAndBracketsAreTrimmed(string $expected, string $message, array $paramters) { $formatter = new IntlFormatter(); $this->assertInstanceof(IntlFormatterInterface::class, $formatter); - $this->assertSame('Hello Fab', $formatter->formatIntl('Hello {name}', 'en', ['name' => 'Fab'])); - $this->assertSame('Hello Fab', $formatter->formatIntl('Hello {name}', 'en', ['%name%' => 'Fab'])); - $this->assertSame('Hello Fab', $formatter->formatIntl('Hello {name}', 'en', ['{{ name }}' => 'Fab'])); + $this->assertSame($expected, $formatter->formatIntl($message, 'en', $paramters)); + } + + public static function percentAndBracketsAreTrimmedProvider(): array + { + return [ + ['Hello Fab', 'Hello {name}', ['name' => 'Fab']], + ['Hello Fab', 'Hello {name}', ['%name%' => 'Fab']], + ['Hello Fab', 'Hello {name}', ['{{ name }}' => 'Fab']], + ]; } } diff --git a/src/Symfony/Component/Translation/Tests/Loader/CsvFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/CsvFileLoaderTest.php index 332d5a4d9330a..e43675ee9b773 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/CsvFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/CsvFileLoaderTest.php @@ -44,16 +44,14 @@ public function testLoadDoesNothingIfEmpty() public function testLoadNonExistingResource() { $this->expectException(NotFoundResourceException::class); - $loader = new CsvFileLoader(); - $resource = __DIR__.'/../Fixtures/not-exists.csv'; - $loader->load($resource, 'en', 'domain1'); + + (new CsvFileLoader())->load(__DIR__.'/../Fixtures/not-exists.csv', 'en', 'domain1'); } public function testLoadNonLocalResource() { $this->expectException(InvalidResourceException::class); - $loader = new CsvFileLoader(); - $resource = 'http://example.com/resources.csv'; - $loader->load($resource, 'en', 'domain1'); + + (new CsvFileLoader())->load('http://example.com/resources.csv', 'en', 'domain1'); } } diff --git a/src/Symfony/Component/Translation/Tests/Loader/IcuDatFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/IcuDatFileLoaderTest.php index fca84fa5bf8a5..15fe11bc16985 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/IcuDatFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/IcuDatFileLoaderTest.php @@ -24,8 +24,8 @@ class IcuDatFileLoaderTest extends LocalizedTestCase public function testLoadInvalidResource() { $this->expectException(InvalidResourceException::class); - $loader = new IcuDatFileLoader(); - $loader->load(__DIR__.'/../Fixtures/resourcebundle/corrupted/resources', 'es', 'domain2'); + + (new IcuDatFileLoader())->load(__DIR__.'/../Fixtures/resourcebundle/corrupted/resources', 'es', 'domain2'); } public function testDatEnglishLoad() @@ -56,7 +56,7 @@ public function testDatFrenchLoad() public function testLoadNonExistingResource() { $this->expectException(NotFoundResourceException::class); - $loader = new IcuDatFileLoader(); - $loader->load(__DIR__.'/../Fixtures/non-existing.txt', 'en', 'domain1'); + + (new IcuDatFileLoader())->load(__DIR__.'/../Fixtures/non-existing.txt', 'en', 'domain1'); } } diff --git a/src/Symfony/Component/Translation/Tests/Loader/IcuResFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/IcuResFileLoaderTest.php index 7bce83211ea1a..066c072ddc1c8 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/IcuResFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/IcuResFileLoaderTest.php @@ -36,14 +36,14 @@ public function testLoad() public function testLoadNonExistingResource() { $this->expectException(NotFoundResourceException::class); - $loader = new IcuResFileLoader(); - $loader->load(__DIR__.'/../Fixtures/non-existing.txt', 'en', 'domain1'); + + (new IcuResFileLoader())->load(__DIR__.'/../Fixtures/non-existing.txt', 'en', 'domain1'); } public function testLoadInvalidResource() { $this->expectException(InvalidResourceException::class); - $loader = new IcuResFileLoader(); - $loader->load(__DIR__.'/../Fixtures/resourcebundle/corrupted', 'en', 'domain1'); + + (new IcuResFileLoader())->load(__DIR__.'/../Fixtures/resourcebundle/corrupted', 'en', 'domain1'); } } diff --git a/src/Symfony/Component/Translation/Tests/Loader/IniFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/IniFileLoaderTest.php index cfac4903a7207..8617664991551 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/IniFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/IniFileLoaderTest.php @@ -43,8 +43,7 @@ public function testLoadDoesNothingIfEmpty() public function testLoadNonExistingResource() { $this->expectException(NotFoundResourceException::class); - $loader = new IniFileLoader(); - $resource = __DIR__.'/../Fixtures/non-existing.ini'; - $loader->load($resource, 'en', 'domain1'); + + (new IniFileLoader())->load(__DIR__.'/../Fixtures/non-existing.ini', 'en', 'domain1'); } } diff --git a/src/Symfony/Component/Translation/Tests/Loader/JsonFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/JsonFileLoaderTest.php index 54f08a741a75d..5160cfb74e8a1 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/JsonFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/JsonFileLoaderTest.php @@ -44,17 +44,15 @@ public function testLoadDoesNothingIfEmpty() public function testLoadNonExistingResource() { $this->expectException(NotFoundResourceException::class); - $loader = new JsonFileLoader(); - $resource = __DIR__.'/../Fixtures/non-existing.json'; - $loader->load($resource, 'en', 'domain1'); + + (new JsonFileLoader())->load(__DIR__.'/../Fixtures/non-existing.json', 'en', 'domain1'); } public function testParseException() { $this->expectException(InvalidResourceException::class); $this->expectExceptionMessage('Error parsing JSON: Syntax error, malformed JSON'); - $loader = new JsonFileLoader(); - $resource = __DIR__.'/../Fixtures/malformed.json'; - $loader->load($resource, 'en', 'domain1'); + + (new JsonFileLoader())->load(__DIR__.'/../Fixtures/malformed.json', 'en', 'domain1'); } } diff --git a/src/Symfony/Component/Translation/Tests/Loader/MoFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/MoFileLoaderTest.php index 562ea0e478d38..3c494a06dee9b 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/MoFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/MoFileLoaderTest.php @@ -47,17 +47,15 @@ public function testLoadPlurals() public function testLoadNonExistingResource() { $this->expectException(NotFoundResourceException::class); - $loader = new MoFileLoader(); - $resource = __DIR__.'/../Fixtures/non-existing.mo'; - $loader->load($resource, 'en', 'domain1'); + + (new MoFileLoader())->load(__DIR__.'/../Fixtures/non-existing.mo', 'en', 'domain1'); } public function testLoadInvalidResource() { $this->expectException(InvalidResourceException::class); - $loader = new MoFileLoader(); - $resource = __DIR__.'/../Fixtures/empty.mo'; - $loader->load($resource, 'en', 'domain1'); + + (new MoFileLoader())->load(__DIR__.'/../Fixtures/empty.mo', 'en', 'domain1'); } public function testLoadEmptyTranslation() diff --git a/src/Symfony/Component/Translation/Tests/Loader/PhpFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/PhpFileLoaderTest.php index e5ae2e89fa068..ce76c15f5a899 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/PhpFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/PhpFileLoaderTest.php @@ -33,16 +33,14 @@ public function testLoad() public function testLoadNonExistingResource() { $this->expectException(NotFoundResourceException::class); - $loader = new PhpFileLoader(); - $resource = __DIR__.'/../Fixtures/non-existing.php'; - $loader->load($resource, 'en', 'domain1'); + + (new PhpFileLoader())->load(__DIR__.'/../Fixtures/non-existing.php', 'en', 'domain1'); } public function testLoadThrowsAnExceptionIfFileNotLocal() { $this->expectException(InvalidResourceException::class); - $loader = new PhpFileLoader(); - $resource = 'http://example.com/resources.php'; - $loader->load($resource, 'en', 'domain1'); + + (new PhpFileLoader())->load('http://example.com/resources.php', 'en', 'domain1'); } } diff --git a/src/Symfony/Component/Translation/Tests/Loader/PoFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/PoFileLoaderTest.php index 4822de76cb0a8..3e963f68285cb 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/PoFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/PoFileLoaderTest.php @@ -57,9 +57,8 @@ public function testLoadDoesNothingIfEmpty() public function testLoadNonExistingResource() { $this->expectException(NotFoundResourceException::class); - $loader = new PoFileLoader(); - $resource = __DIR__.'/../Fixtures/non-existing.po'; - $loader->load($resource, 'en', 'domain1'); + + (new PoFileLoader())->load(__DIR__.'/../Fixtures/non-existing.po', 'en', 'domain1'); } public function testLoadEmptyTranslation() diff --git a/src/Symfony/Component/Translation/Tests/Loader/QtFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/QtFileLoaderTest.php index 908dca31e8f77..72aa4bfaa9c27 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/QtFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/QtFileLoaderTest.php @@ -37,35 +37,31 @@ public function testLoad() public function testLoadNonExistingResource() { $this->expectException(NotFoundResourceException::class); - $loader = new QtFileLoader(); - $resource = __DIR__.'/../Fixtures/non-existing.ts'; - $loader->load($resource, 'en', 'domain1'); + + (new QtFileLoader())->load(__DIR__.'/../Fixtures/non-existing.ts', 'en', 'domain1'); } public function testLoadNonLocalResource() { $this->expectException(InvalidResourceException::class); - $loader = new QtFileLoader(); - $resource = 'http://domain1.com/resources.ts'; - $loader->load($resource, 'en', 'domain1'); + + (new QtFileLoader())->load('http://domain1.com/resources.ts', 'en', 'domain1'); } public function testLoadInvalidResource() { $this->expectException(InvalidResourceException::class); - $loader = new QtFileLoader(); - $resource = __DIR__.'/../Fixtures/invalid-xml-resources.xlf'; - $loader->load($resource, 'en', 'domain1'); + + (new QtFileLoader())->load(__DIR__.'/../Fixtures/invalid-xml-resources.xlf', 'en', 'domain1'); } public function testLoadEmptyResource() { - $loader = new QtFileLoader(); $resource = __DIR__.'/../Fixtures/empty.xlf'; $this->expectException(InvalidResourceException::class); $this->expectExceptionMessage(sprintf('Unable to load "%s".', $resource)); - $loader->load($resource, 'en', 'domain1'); + (new QtFileLoader())->load($resource, 'en', 'domain1'); } } diff --git a/src/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.php index b64b6f9511519..35442e59675d0 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.php @@ -143,50 +143,47 @@ public function testTargetAttributesAreStoredCorrectly() public function testLoadInvalidResource() { $this->expectException(InvalidResourceException::class); - $loader = new XliffFileLoader(); - $loader->load(__DIR__.'/../Fixtures/resources.php', 'en', 'domain1'); + + (new XliffFileLoader())->load(__DIR__.'/../Fixtures/resources.php', 'en', 'domain1'); } public function testLoadResourceDoesNotValidate() { $this->expectException(InvalidResourceException::class); - $loader = new XliffFileLoader(); - $loader->load(__DIR__.'/../Fixtures/non-valid.xlf', 'en', 'domain1'); + + (new XliffFileLoader())->load(__DIR__.'/../Fixtures/non-valid.xlf', 'en', 'domain1'); } public function testLoadNonExistingResource() { $this->expectException(NotFoundResourceException::class); - $loader = new XliffFileLoader(); - $resource = __DIR__.'/../Fixtures/non-existing.xlf'; - $loader->load($resource, 'en', 'domain1'); + + (new XliffFileLoader())->load(__DIR__.'/../Fixtures/non-existing.xlf', 'en', 'domain1'); } public function testLoadThrowsAnExceptionIfFileNotLocal() { $this->expectException(InvalidResourceException::class); - $loader = new XliffFileLoader(); - $resource = 'http://example.com/resources.xlf'; - $loader->load($resource, 'en', 'domain1'); + + (new XliffFileLoader())->load('http://example.com/resources.xlf', 'en', 'domain1'); } public function testDocTypeIsNotAllowed() { $this->expectException(InvalidResourceException::class); $this->expectExceptionMessage('Document types are not allowed.'); - $loader = new XliffFileLoader(); - $loader->load(__DIR__.'/../Fixtures/withdoctype.xlf', 'en', 'domain1'); + + (new XliffFileLoader())->load(__DIR__.'/../Fixtures/withdoctype.xlf', 'en', 'domain1'); } public function testParseEmptyFile() { - $loader = new XliffFileLoader(); $resource = __DIR__.'/../Fixtures/empty.xlf'; $this->expectException(InvalidResourceException::class); $this->expectExceptionMessage(sprintf('Unable to load "%s":', $resource)); - $loader->load($resource, 'en', 'domain1'); + (new XliffFileLoader())->load($resource, 'en', 'domain1'); } public function testLoadNotes() diff --git a/src/Symfony/Component/Translation/Tests/Loader/YamlFileLoaderTest.php b/src/Symfony/Component/Translation/Tests/Loader/YamlFileLoaderTest.php index 647cd3acc2c85..f5d67998e04e6 100644 --- a/src/Symfony/Component/Translation/Tests/Loader/YamlFileLoaderTest.php +++ b/src/Symfony/Component/Translation/Tests/Loader/YamlFileLoaderTest.php @@ -52,25 +52,31 @@ public function testLoadDoesNothingIfEmpty() public function testLoadNonExistingResource() { - $this->expectException(NotFoundResourceException::class); $loader = new YamlFileLoader(); $resource = __DIR__.'/../Fixtures/non-existing.yml'; + + $this->expectException(NotFoundResourceException::class); + $loader->load($resource, 'en', 'domain1'); } public function testLoadThrowsAnExceptionIfFileNotLocal() { - $this->expectException(InvalidResourceException::class); $loader = new YamlFileLoader(); $resource = 'http://example.com/resources.yml'; + + $this->expectException(InvalidResourceException::class); + $loader->load($resource, 'en', 'domain1'); } public function testLoadThrowsAnExceptionIfNotAnArray() { - $this->expectException(InvalidResourceException::class); $loader = new YamlFileLoader(); $resource = __DIR__.'/../Fixtures/non-valid.yml'; + + $this->expectException(InvalidResourceException::class); + $loader->load($resource, 'en', 'domain1'); } } diff --git a/src/Symfony/Component/Translation/Tests/MessageCatalogueTest.php b/src/Symfony/Component/Translation/Tests/MessageCatalogueTest.php index fb118e93afbb8..439e2ba045b22 100644 --- a/src/Symfony/Component/Translation/Tests/MessageCatalogueTest.php +++ b/src/Symfony/Component/Translation/Tests/MessageCatalogueTest.php @@ -191,30 +191,36 @@ public function testAddFallbackCatalogue() public function testAddFallbackCatalogueWithParentCircularReference() { - $this->expectException(LogicException::class); $main = new MessageCatalogue('en_US'); $fallback = new MessageCatalogue('fr_FR'); $fallback->addFallbackCatalogue($main); + + $this->expectException(LogicException::class); + $main->addFallbackCatalogue($fallback); } public function testAddFallbackCatalogueWithFallbackCircularReference() { - $this->expectException(LogicException::class); $fr = new MessageCatalogue('fr'); $en = new MessageCatalogue('en'); $es = new MessageCatalogue('es'); $fr->addFallbackCatalogue($en); $es->addFallbackCatalogue($en); + + $this->expectException(LogicException::class); + $en->addFallbackCatalogue($fr); } public function testAddCatalogueWhenLocaleIsNotTheSameAsTheCurrentOne() { - $this->expectException(LogicException::class); $catalogue = new MessageCatalogue('en'); + + $this->expectException(LogicException::class); + $catalogue->addCatalogue(new MessageCatalogue('fr', [])); } diff --git a/src/Symfony/Component/Translation/Tests/TranslatorTest.php b/src/Symfony/Component/Translation/Tests/TranslatorTest.php index 9ba54f6bf6763..ca7cb0d01e595 100644 --- a/src/Symfony/Component/Translation/Tests/TranslatorTest.php +++ b/src/Symfony/Component/Translation/Tests/TranslatorTest.php @@ -69,17 +69,19 @@ public function testSetGetLocale() /** * @dataProvider getInvalidLocalesTests */ - public function testSetInvalidLocale($locale) + public function testSetInvalidLocale(string $locale) { - $this->expectException(InvalidArgumentException::class); $translator = new Translator('fr'); + + $this->expectException(InvalidArgumentException::class); + $translator->setLocale($locale); } /** * @dataProvider getValidLocalesTests */ - public function testSetValidLocale($locale) + public function testSetValidLocale(string $locale) { $translator = new Translator($locale); $translator->setLocale($locale); @@ -186,15 +188,17 @@ public function testTransWithFallbackLocale() */ public function testAddResourceInvalidLocales($locale) { - $this->expectException(InvalidArgumentException::class); $translator = new Translator('fr'); + + $this->expectException(InvalidArgumentException::class); + $translator->addResource('array', ['foo' => 'foofoo'], $locale); } /** * @dataProvider getValidLocalesTests */ - public function testAddResourceValidLocales($locale) + public function testAddResourceValidLocales(string $locale) { $translator = new Translator('fr'); $translator->addResource('array', ['foo' => 'foofoo'], $locale); @@ -219,15 +223,16 @@ public function testAddResourceAfterTrans() /** * @dataProvider getTransFileTests */ - public function testTransWithoutFallbackLocaleFile($format, $loader) + public function testTransWithoutFallbackLocaleFile(string $format, string $loader) { - $this->expectException(NotFoundResourceException::class); $loaderClass = 'Symfony\\Component\\Translation\\Loader\\'.$loader; $translator = new Translator('en'); $translator->addLoader($format, new $loaderClass()); $translator->addResource($format, __DIR__.'/Fixtures/non-existing', 'en'); $translator->addResource($format, __DIR__.'/Fixtures/resources.'.$format, 'en'); + $this->expectException(NotFoundResourceException::class); + // force catalogue loading $translator->trans('foo'); } @@ -235,7 +240,7 @@ public function testTransWithoutFallbackLocaleFile($format, $loader) /** * @dataProvider getTransFileTests */ - public function testTransWithFallbackLocaleFile($format, $loader) + public function testTransWithFallbackLocaleFile(string $format, string $loader) { $loaderClass = 'Symfony\\Component\\Translation\\Loader\\'.$loader; $translator = new Translator('en_GB'); @@ -343,10 +348,11 @@ public function testTransNonExistentWithFallback() public function testWhenAResourceHasNoRegisteredLoader() { - $this->expectException(RuntimeException::class); $translator = new Translator('en'); $translator->addResource('array', ['foo' => 'foofoo'], 'en'); + $this->expectException(RuntimeException::class); + $translator->trans('foo'); } @@ -409,18 +415,19 @@ public function testTransICU(...$args) */ public function testTransInvalidLocale($locale) { - $this->expectException(InvalidArgumentException::class); $translator = new Translator('en'); $translator->addLoader('array', new ArrayLoader()); $translator->addResource('array', ['foo' => 'foofoo'], 'en'); + $this->expectException(InvalidArgumentException::class); + $translator->trans('foo', [], '', $locale); } /** * @dataProvider getValidLocalesTests */ - public function testTransValidLocale($locale) + public function testTransValidLocale(string $locale) { $translator = new Translator($locale); $translator->addLoader('array', new ArrayLoader()); @@ -433,7 +440,7 @@ public function testTransValidLocale($locale) /** * @dataProvider getFlattenedTransTests */ - public function testFlattenedTrans($expected, $messages, $id) + public function testFlattenedTrans(string $expected, $messages, $id) { $translator = new Translator('en'); $translator->addLoader('array', new ArrayLoader()); @@ -470,7 +477,7 @@ public static function getTransFileTests() ]; } - public static function getTransTests(): iterable + public static function getTransTests(): array { $param = new TranslatableMessage('Symfony is %what%!', ['%what%' => 'awesome'], ''); @@ -587,11 +594,12 @@ public function testIntlDomainOverlapseWithIntlResourceBefore() public function testMissingLoaderForResourceError() { + $translator = new Translator('en'); + $translator->addResource('twig', 'messages.en.twig', 'en'); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('No loader is registered for the "twig" format when loading the "messages.en.twig" resource.'); - $translator = new Translator('en'); - $translator->addResource('twig', 'messages.en.twig', 'en'); $translator->getCatalogue('en'); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php b/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php index 521d5abd8e3f9..0b3a3897dbebb 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php @@ -231,11 +231,9 @@ public static function throwsOnInvalidStringDatesProvider(): array 'value' => 'foo', ]); - $constraintClass = $constraint::class; - return [ - [$constraint, sprintf('The compared value "foo" could not be converted to a "DateTimeImmutable" instance in the "%s" constraint.', $constraintClass), new \DateTimeImmutable()], - [$constraint, sprintf('The compared value "foo" could not be converted to a "DateTime" instance in the "%s" constraint.', $constraintClass), new \DateTime()], + [$constraint, sprintf('The compared value "foo" could not be converted to a "DateTimeImmutable" instance in the "%s" constraint.', $constraint::class), new \DateTimeImmutable()], + [$constraint, sprintf('The compared value "foo" could not be converted to a "DateTime" instance in the "%s" constraint.', $constraint::class), new \DateTime()], ]; } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CssColorValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CssColorValidatorTest.php index 5c7904a8001af..081d41a57c705 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CssColorValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CssColorValidatorTest.php @@ -369,7 +369,12 @@ public function testInvalidRGBA($cssColor) public static function getInvalidRGBA(): array { - return [['rgba(999,999,999,999)'], ['rgba(-99,-99,-99,-99)'], ['rgba(a,b,c,d)'], ['rgba(99 99, 9 99, 99 9, . 9)']]; + return [ + ['rgba(999,999,999,999)'], + ['rgba(-99,-99,-99,-99)'], + ['rgba(a,b,c,d)'], + ['rgba(99 99, 9 99, 99 9, . 9)'], + ]; } /** @@ -415,7 +420,13 @@ public function testInvalidHSLA($cssColor) public function getInvalidHSLA(): array { - return [['hsla(1000, 1000%, 20000%, 999)'], ['hsla(-100, -10%, -2%, 999)'], ['hsla(a, b, c, d)'], ['hsla(a, b%, c%, d)'], ['hsla( 9 99% , 99 9% , 9 %']]; + return [ + ['hsla(1000, 1000%, 20000%, 999)'], + ['hsla(-100, -10%, -2%, 999)'], + ['hsla(a, b, c, d)'], + ['hsla(a, b%, c%, d)'], + ['hsla( 9 99% , 99 9% , 9 %'], + ]; } /** diff --git a/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php index d894236e104af..ab424a82d25d6 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php @@ -245,11 +245,12 @@ public function testModeHtml5AllowNoTld() public function testUnknownModesOnValidateTriggerException() { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('The "Symfony\Component\Validator\Constraints\Email::$mode" parameter value is not valid.'); $constraint = new Email(); $constraint->mode = 'Unknown Mode'; + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The "Symfony\Component\Validator\Constraints\Email::$mode" parameter value is not valid.'); + $this->validator->validate('example@example..com', $constraint); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/FileTest.php b/src/Symfony/Component/Validator/Tests/Constraints/FileTest.php index b05a3ec86aafa..e8c27b4b1f290 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/FileTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/FileTest.php @@ -57,8 +57,10 @@ public function testMaxSizeCanBeSetAfterInitialization($maxSize, $bytes, $binary */ public function testInvalidValueForMaxSizeThrowsExceptionAfterInitialization($maxSize) { - $this->expectException(ConstraintDefinitionException::class); $file = new File(['maxSize' => 1000]); + + $this->expectException(ConstraintDefinitionException::class); + $file->maxSize = $maxSize; } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTestCase.php b/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTestCase.php index 960a8f3b6e2f3..b5d05801e53fe 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTestCase.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTestCase.php @@ -519,10 +519,11 @@ public static function uploadedFileErrorProvider() public function testNegativeMaxSize() { + $file = new File(); + $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('"-1" is not a valid maximum size.'); - $file = new File(); $file->maxSize = -1; } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanOrEqualValidatorWithPositiveOrZeroConstraintTest.php b/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanOrEqualValidatorWithPositiveOrZeroConstraintTest.php index 34e546029c731..11b092c6df484 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanOrEqualValidatorWithPositiveOrZeroConstraintTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanOrEqualValidatorWithPositiveOrZeroConstraintTest.php @@ -69,15 +69,11 @@ public function testThrowsConstraintExceptionIfValue() */ public function testThrowsConstraintExceptionIfNoValueOrPropertyPath($options) { - $this->expectException(ConstraintDefinitionException::class); - $this->expectExceptionMessage('requires either the "value" or "propertyPath" option to be set.'); - $this->markTestSkipped('Value option always set for PositiveOrZero constraint'); + $this->markTestSkipped('Value option always set for PositiveOrZero constraint'); } public function testThrowsConstraintExceptionIfBothValueAndPropertyPath() { - $this->expectException(ConstraintDefinitionException::class); - $this->expectExceptionMessage('requires only one of the "value" or "propertyPath" options to be set, not both.'); $this->markTestSkipped('Value option is set for PositiveOrZero constraint automatically'); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorWithPositiveConstraintTest.php b/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorWithPositiveConstraintTest.php index 5ce59d129cf80..18a503bf237d5 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorWithPositiveConstraintTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorWithPositiveConstraintTest.php @@ -67,15 +67,11 @@ public function testThrowsConstraintExceptionIfValue() */ public function testThrowsConstraintExceptionIfNoValueOrPropertyPath($options) { - $this->expectException(ConstraintDefinitionException::class); - $this->expectExceptionMessage('requires either the "value" or "propertyPath" option to be set.'); $this->markTestSkipped('Value option always set for Positive constraint.'); } public function testThrowsConstraintExceptionIfBothValueAndPropertyPath() { - $this->expectException(ConstraintDefinitionException::class); - $this->expectExceptionMessage('requires only one of the "value" or "propertyPath" options to be set, not both.'); $this->markTestSkipped('Value option is set for Positive constraint automatically'); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.php index 000b9d900c690..0afc9e6e15d64 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.php @@ -116,7 +116,7 @@ public static function getThreeCharactersWithWhitespaces() /** * @dataProvider getFiveOrMoreCharacters */ - public function testValidValuesMin($value) + public function testValidValuesMin(int|string $value) { $constraint = new Length(['min' => 5]); $this->validator->validate($value, $constraint); @@ -127,7 +127,7 @@ public function testValidValuesMin($value) /** * @dataProvider getThreeOrLessCharacters */ - public function testValidValuesMax($value) + public function testValidValuesMax(int|string $value) { $constraint = new Length(['max' => 3]); $this->validator->validate($value, $constraint); @@ -138,7 +138,7 @@ public function testValidValuesMax($value) /** * @dataProvider getFourCharacters */ - public function testValidValuesExact($value) + public function testValidValuesExact(int|string $value) { $constraint = new Length(4); $this->validator->validate($value, $constraint); @@ -184,7 +184,7 @@ public function testValidBytesValues() /** * @dataProvider getThreeOrLessCharacters */ - public function testInvalidValuesMin($value, $valueLength) + public function testInvalidValuesMin(int|string $value, int $valueLength) { $constraint = new Length([ 'min' => 4, @@ -206,7 +206,7 @@ public function testInvalidValuesMin($value, $valueLength) /** * @dataProvider getThreeOrLessCharacters */ - public function testInvalidValuesMinNamed($value, $valueLength) + public function testInvalidValuesMinNamed(int|string $value, int $valueLength) { $constraint = new Length(min: 4, minMessage: 'myMessage'); @@ -225,7 +225,7 @@ public function testInvalidValuesMinNamed($value, $valueLength) /** * @dataProvider getFiveOrMoreCharacters */ - public function testInvalidValuesMax($value, $valueLength) + public function testInvalidValuesMax(int|string $value, int $valueLength) { $constraint = new Length([ 'max' => 4, @@ -247,7 +247,7 @@ public function testInvalidValuesMax($value, $valueLength) /** * @dataProvider getFiveOrMoreCharacters */ - public function testInvalidValuesMaxNamed($value, $valueLength) + public function testInvalidValuesMaxNamed(int|string $value, int $valueLength) { $constraint = new Length(max: 4, maxMessage: 'myMessage'); @@ -266,7 +266,7 @@ public function testInvalidValuesMaxNamed($value, $valueLength) /** * @dataProvider getThreeOrLessCharacters */ - public function testInvalidValuesExactLessThanFour($value, $valueLength) + public function testInvalidValuesExactLessThanFour(int|string $value, int $valueLength) { $constraint = new Length([ 'min' => 4, @@ -289,7 +289,7 @@ public function testInvalidValuesExactLessThanFour($value, $valueLength) /** * @dataProvider getThreeOrLessCharacters */ - public function testInvalidValuesExactLessThanFourNamed($value, $valueLength) + public function testInvalidValuesExactLessThanFourNamed(int|string $value, int $valueLength) { $constraint = new Length(exactly: 4, exactMessage: 'myMessage'); @@ -308,7 +308,7 @@ public function testInvalidValuesExactLessThanFourNamed($value, $valueLength) /** * @dataProvider getFiveOrMoreCharacters */ - public function testInvalidValuesExactMoreThanFour($value, $valueLength) + public function testInvalidValuesExactMoreThanFour(int|string $value, int $valueLength) { $constraint = new Length([ 'min' => 4, diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorWithNegativeOrZeroConstraintTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorWithNegativeOrZeroConstraintTest.php index f75364e1dc359..946bf93c7826b 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorWithNegativeOrZeroConstraintTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorWithNegativeOrZeroConstraintTest.php @@ -67,15 +67,11 @@ public function testThrowsConstraintExceptionIfValue() */ public function testThrowsConstraintExceptionIfNoValueOrPropertyPath($options) { - $this->expectException(ConstraintDefinitionException::class); - $this->expectExceptionMessage('requires either the "value" or "propertyPath" option to be set.'); $this->markTestSkipped('Value option always set for NegativeOrZero constraint'); } public function testThrowsConstraintExceptionIfBothValueAndPropertyPath() { - $this->expectException(ConstraintDefinitionException::class); - $this->expectExceptionMessage('requires only one of the "value" or "propertyPath" options to be set, not both.'); $this->markTestSkipped('Value option is set for NegativeOrZero constraint automatically'); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorWithNegativeConstraintTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorWithNegativeConstraintTest.php index 569e662b2be9b..35fac73ecab34 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorWithNegativeConstraintTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorWithNegativeConstraintTest.php @@ -67,15 +67,11 @@ public function testThrowsConstraintExceptionIfValue() */ public function testThrowsConstraintExceptionIfNoValueOrPropertyPath($options) { - $this->expectException(ConstraintDefinitionException::class); - $this->expectExceptionMessage('requires either the "value" or "propertyPath" option to be set.'); $this->markTestSkipped('Value option always set for Negative constraint'); } public function testThrowsConstraintExceptionIfBothValueAndPropertyPath() { - $this->expectException(ConstraintDefinitionException::class); - $this->expectExceptionMessage('requires only one of the "value" or "propertyPath" options to be set, not both.'); $this->markTestSkipped('Value option is set for Negative constraint automatically'); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php index 4eec91c63d683..1626eecef48ff 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php @@ -151,7 +151,7 @@ public function testInvalidLocaleWithoutCanonicalizationNamed() ->assertRaised(); } - public static function getUncanonicalizedLocales(): iterable + public static function getUncanonicalizedLocales(): array { return [ ['en-US'], diff --git a/src/Symfony/Component/Validator/Tests/Constraints/UuidValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/UuidValidatorTest.php index 7c2e587cf6b89..b5084b6d7f05f 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/UuidValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/UuidValidatorTest.php @@ -44,9 +44,10 @@ public function testEmptyStringIsValid() public function testExpectsUuidConstraintCompatibleType() { - $this->expectException(UnexpectedTypeException::class); $constraint = $this->getMockForAbstractClass(Constraint::class); + $this->expectException(UnexpectedTypeException::class); + $this->validator->validate('216fff40-98d9-11e3-a5e2-0800200c9a66', $constraint); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/WhenTest.php b/src/Symfony/Component/Validator/Tests/Constraints/WhenTest.php index 12d2bd146dda1..7cfe13f2f2e78 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/WhenTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/WhenTest.php @@ -36,9 +36,7 @@ public function testNonConstraintsAreRejected() { $this->expectException(ConstraintDefinitionException::class); $this->expectExceptionMessage('The value "foo" is not an instance of Constraint in constraint "Symfony\Component\Validator\Constraints\When"'); - new When('true', [ - 'foo', - ]); + new When('true', ['foo']); } public function testAttributes() diff --git a/src/Symfony/Component/Validator/Tests/ContainerConstraintValidatorFactoryTest.php b/src/Symfony/Component/Validator/Tests/ContainerConstraintValidatorFactoryTest.php index 63b7f6f96ae01..980a70e40a66c 100644 --- a/src/Symfony/Component/Validator/Tests/ContainerConstraintValidatorFactoryTest.php +++ b/src/Symfony/Component/Validator/Tests/ContainerConstraintValidatorFactoryTest.php @@ -49,7 +49,6 @@ public function testGetInstanceReturnsService() public function testGetInstanceInvalidValidatorClass() { - $this->expectException(ValidatorException::class); $constraint = $this->createMock(Constraint::class); $constraint ->expects($this->once()) @@ -57,6 +56,9 @@ public function testGetInstanceInvalidValidatorClass() ->willReturn('Fully\\Qualified\\ConstraintValidator\\Class\\Name'); $factory = new ContainerConstraintValidatorFactory(new Container()); + + $this->expectException(ValidatorException::class); + $factory->getInstance($constraint); } } diff --git a/src/Symfony/Component/Validator/Tests/DependencyInjection/AddConstraintValidatorsPassTest.php b/src/Symfony/Component/Validator/Tests/DependencyInjection/AddConstraintValidatorsPassTest.php index 052c88f85319b..1b85c7e2a37ff 100644 --- a/src/Symfony/Component/Validator/Tests/DependencyInjection/AddConstraintValidatorsPassTest.php +++ b/src/Symfony/Component/Validator/Tests/DependencyInjection/AddConstraintValidatorsPassTest.php @@ -47,8 +47,6 @@ public function testThatConstraintValidatorServicesAreProcessed() public function testAbstractConstraintValidator() { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('The service "my_abstract_constraint_validator" tagged "validator.constraint_validator" must not be abstract.'); $container = new ContainerBuilder(); $container->register('validator.validator_factory') ->addArgument([]); @@ -58,6 +56,10 @@ public function testAbstractConstraintValidator() ->addTag('validator.constraint_validator'); $addConstraintValidatorsPass = new AddConstraintValidatorsPass(); + + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The service "my_abstract_constraint_validator" tagged "validator.constraint_validator" must not be abstract.'); + $addConstraintValidatorsPass->process($container); } diff --git a/src/Symfony/Component/Validator/Tests/Mapping/ClassMetadataTest.php b/src/Symfony/Component/Validator/Tests/Mapping/ClassMetadataTest.php index 815f4a1f56680..d38ecf8605d1f 100644 --- a/src/Symfony/Component/Validator/Tests/Mapping/ClassMetadataTest.php +++ b/src/Symfony/Component/Validator/Tests/Mapping/ClassMetadataTest.php @@ -279,17 +279,21 @@ public function testGroupSequencesFailIfContainingDefault() public function testGroupSequenceFailsIfGroupSequenceProviderIsSet() { - $this->expectException(GroupDefinitionException::class); $metadata = new ClassMetadata(self::PROVIDERCLASS); $metadata->setGroupSequenceProvider(true); + + $this->expectException(GroupDefinitionException::class); + $metadata->setGroupSequence(['GroupSequenceProviderEntity', 'Foo']); } public function testGroupSequenceProviderFailsIfGroupSequenceIsSet() { - $this->expectException(GroupDefinitionException::class); $metadata = new ClassMetadata(self::PROVIDERCLASS); $metadata->setGroupSequence(['GroupSequenceProviderEntity', 'Foo']); + + $this->expectException(GroupDefinitionException::class); + $metadata->setGroupSequenceProvider(true); } diff --git a/src/Symfony/Component/Validator/Tests/Mapping/Factory/BlackHoleMetadataFactoryTest.php b/src/Symfony/Component/Validator/Tests/Mapping/Factory/BlackHoleMetadataFactoryTest.php index 549bc518b41b5..1fff113011620 100644 --- a/src/Symfony/Component/Validator/Tests/Mapping/Factory/BlackHoleMetadataFactoryTest.php +++ b/src/Symfony/Component/Validator/Tests/Mapping/Factory/BlackHoleMetadataFactoryTest.php @@ -20,14 +20,11 @@ class BlackHoleMetadataFactoryTest extends TestCase public function testGetMetadataForThrowsALogicException() { $this->expectException(LogicException::class); - $metadataFactory = new BlackHoleMetadataFactory(); - $metadataFactory->getMetadataFor('foo'); + (new BlackHoleMetadataFactory())->getMetadataFor('foo'); } public function testHasMetadataForReturnsFalse() { - $metadataFactory = new BlackHoleMetadataFactory(); - - $this->assertFalse($metadataFactory->hasMetadataFor('foo')); + $this->assertFalse((new BlackHoleMetadataFactory())->hasMetadataFor('foo')); } } diff --git a/src/Symfony/Component/Validator/Tests/Mapping/Factory/LazyLoadingMetadataFactoryTest.php b/src/Symfony/Component/Validator/Tests/Mapping/Factory/LazyLoadingMetadataFactoryTest.php index 3d10506aea337..d2250114ffbff 100644 --- a/src/Symfony/Component/Validator/Tests/Mapping/Factory/LazyLoadingMetadataFactoryTest.php +++ b/src/Symfony/Component/Validator/Tests/Mapping/Factory/LazyLoadingMetadataFactoryTest.php @@ -109,14 +109,17 @@ public function testCachedMetadata() public function testNonClassNameStringValues() { - $this->expectException(NoSuchMetadataException::class); $testedValue = 'error@example.com'; $loader = $this->createMock(LoaderInterface::class); $cache = $this->createMock(CacheItemPoolInterface::class); - $factory = new LazyLoadingMetadataFactory($loader, $cache); $cache ->expects($this->never()) ->method('getItem'); + + $factory = new LazyLoadingMetadataFactory($loader, $cache); + + $this->expectException(NoSuchMetadataException::class); + $factory->getMetadataFor($testedValue); } diff --git a/src/Symfony/Component/Validator/Tests/Mapping/Loader/YamlFileLoaderTest.php b/src/Symfony/Component/Validator/Tests/Mapping/Loader/YamlFileLoaderTest.php index a5c983939bcb2..60493787e1ba5 100644 --- a/src/Symfony/Component/Validator/Tests/Mapping/Loader/YamlFileLoaderTest.php +++ b/src/Symfony/Component/Validator/Tests/Mapping/Loader/YamlFileLoaderTest.php @@ -48,10 +48,11 @@ public function testLoadClassMetadataReturnsFalseIfEmpty() */ public function testInvalidYamlFiles($path) { - $this->expectException(\InvalidArgumentException::class); $loader = new YamlFileLoader(__DIR__.'/'.$path); $metadata = new ClassMetadata(Entity::class); + $this->expectException(\InvalidArgumentException::class); + $loader->loadClassMetadata($metadata); } diff --git a/src/Symfony/Component/Validator/Tests/Validator/RecursiveValidatorTest.php b/src/Symfony/Component/Validator/Tests/Validator/RecursiveValidatorTest.php index cffbaa5fbeca5..ee183a1bfdf15 100644 --- a/src/Symfony/Component/Validator/Tests/Validator/RecursiveValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Validator/RecursiveValidatorTest.php @@ -531,12 +531,13 @@ public function testsIgnoreNullReference() public function testFailOnScalarReferences() { - $this->expectException(NoSuchMetadataException::class); $entity = new Entity(); $entity->reference = 'string'; $this->metadata->addPropertyConstraint('reference', new Valid()); + $this->expectException(NoSuchMetadataException::class); + $this->validate($entity); } @@ -786,7 +787,6 @@ public function testDisableTraversableTraversal() public function testMetadataMustExistIfTraversalIsDisabled() { - $this->expectException(NoSuchMetadataException::class); $entity = new Entity(); $entity->reference = new \ArrayIterator(); @@ -794,6 +794,8 @@ public function testMetadataMustExistIfTraversalIsDisabled() 'traverse' => false, ])); + $this->expectException(NoSuchMetadataException::class); + $this->validate($entity); } @@ -1670,12 +1672,11 @@ public function testTraversalDisabledOnClass() public function testExpectTraversableIfTraversalEnabledOnClass() { - $this->expectException(ConstraintDefinitionException::class); - $entity = new Entity(); - $this->metadata->addConstraint(new Traverse(true)); - $this->validator->validate($entity); + $this->expectException(ConstraintDefinitionException::class); + + $this->validator->validate(new Entity()); } public function testReferenceTraversalDisabledOnClass() diff --git a/src/Symfony/Component/Webhook/Tests/Client/RequestParserTest.php b/src/Symfony/Component/Webhook/Tests/Client/RequestParserTest.php index 18dbe5c1ff616..53171866d6e47 100644 --- a/src/Symfony/Component/Webhook/Tests/Client/RequestParserTest.php +++ b/src/Symfony/Component/Webhook/Tests/Client/RequestParserTest.php @@ -21,9 +21,6 @@ class RequestParserTest extends TestCase public function testParseDoesNotMatch() { $this->expectException(RejectWebhookException::class); - - $request = new Request(); - $parser = new RequestParser(); - $parser->parse($request, '$ecret'); + (new RequestParser())->parse(new Request(), '$ecret'); } } diff --git a/src/Symfony/Component/Workflow/Tests/DefinitionTest.php b/src/Symfony/Component/Workflow/Tests/DefinitionTest.php index 9e9c7832f4a1e..3dc40dd5634de 100644 --- a/src/Symfony/Component/Workflow/Tests/DefinitionTest.php +++ b/src/Symfony/Component/Workflow/Tests/DefinitionTest.php @@ -64,18 +64,20 @@ public function testAddTransition() public function testAddTransitionAndFromPlaceIsNotDefined() { + $places = range('a', 'b'); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Place "c" referenced in transition "name" does not exist.'); - $places = range('a', 'b'); new Definition($places, [new Transition('name', 'c', $places[1])]); } public function testAddTransitionAndToPlaceIsNotDefined() { + $places = range('a', 'b'); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Place "c" referenced in transition "name" does not exist.'); - $places = range('a', 'b'); new Definition($places, [new Transition('name', $places[0], 'c')]); } diff --git a/src/Symfony/Component/Workflow/Tests/RegistryTest.php b/src/Symfony/Component/Workflow/Tests/RegistryTest.php index f9a8fe0200318..d3282a8bce060 100644 --- a/src/Symfony/Component/Workflow/Tests/RegistryTest.php +++ b/src/Symfony/Component/Workflow/Tests/RegistryTest.php @@ -63,18 +63,14 @@ public function testGetWithMultipleMatch() { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Too many workflows (workflow2, workflow3) match this subject (Symfony\Component\Workflow\Tests\Subject2); set a different name on each and use the second (name) argument of this method.'); - $w1 = $this->registry->get(new Subject2()); - $this->assertInstanceOf(Workflow::class, $w1); - $this->assertSame('workflow1', $w1->getName()); + $this->registry->get(new Subject2()); } public function testGetWithNoMatch() { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Unable to find a workflow for class "stdClass".'); - $w1 = $this->registry->get(new \stdClass()); - $this->assertInstanceOf(Workflow::class, $w1); - $this->assertSame('workflow1', $w1->getName()); + $this->registry->get(new \stdClass()); } public function testAllWithOneMatchWithSuccess() diff --git a/src/Symfony/Component/Workflow/Tests/Validator/WorkflowValidatorTest.php b/src/Symfony/Component/Workflow/Tests/Validator/WorkflowValidatorTest.php index 036ece77f442d..34eeda6f82721 100644 --- a/src/Symfony/Component/Workflow/Tests/Validator/WorkflowValidatorTest.php +++ b/src/Symfony/Component/Workflow/Tests/Validator/WorkflowValidatorTest.php @@ -24,8 +24,6 @@ class WorkflowValidatorTest extends TestCase public function testWorkflowWithInvalidNames() { - $this->expectException(InvalidDefinitionException::class); - $this->expectExceptionMessage('All transitions for a place must have an unique name. Multiple transitions named "t1" where found for place "a" in workflow "foo".'); $places = range('a', 'c'); $transitions = []; @@ -35,6 +33,9 @@ public function testWorkflowWithInvalidNames() $definition = new Definition($places, $transitions); + $this->expectException(InvalidDefinitionException::class); + $this->expectExceptionMessage('All transitions for a place must have an unique name. Multiple transitions named "t1" where found for place "a" in workflow "foo".'); + (new WorkflowValidator())->validate($definition, 'foo'); } diff --git a/src/Symfony/Component/Yaml/Tests/Command/LintCommandTest.php b/src/Symfony/Component/Yaml/Tests/Command/LintCommandTest.php index 5208f123da871..a501f48d09e37 100644 --- a/src/Symfony/Component/Yaml/Tests/Command/LintCommandTest.php +++ b/src/Symfony/Component/Yaml/Tests/Command/LintCommandTest.php @@ -143,11 +143,12 @@ public function testLintWithExclude() public function testLintFileNotReadable() { - $this->expectException(\RuntimeException::class); $tester = $this->createCommandTester(); $filename = $this->createFile(''); unlink($filename); + $this->expectException(\RuntimeException::class); + $tester->execute(['filename' => $filename], ['decorated' => false]); } diff --git a/src/Symfony/Component/Yaml/Tests/InlineTest.php b/src/Symfony/Component/Yaml/Tests/InlineTest.php index 62fbb6af41b34..36b93e967da48 100644 --- a/src/Symfony/Component/Yaml/Tests/InlineTest.php +++ b/src/Symfony/Component/Yaml/Tests/InlineTest.php @@ -827,20 +827,20 @@ public function testTheEmptyStringIsAValidMappingKey() /** * @dataProvider getNotPhpCompatibleMappingKeyData */ - public function testImplicitStringCastingOfMappingKeysThrows($yaml, $expected) + public function testImplicitStringCastingOfMappingKeysThrowsException(string $yaml) { $this->expectException(ParseException::class); $this->expectExceptionMessage('Implicit casting of incompatible mapping keys to strings is not supported. Quote your evaluable mapping keys instead'); - $this->assertSame($expected, Inline::parse($yaml)); + Inline::parse($yaml); } public static function getNotPhpCompatibleMappingKeyData() { return [ - 'boolean-true' => ['{true: "foo"}', ['true' => 'foo']], - 'boolean-false' => ['{false: "foo"}', ['false' => 'foo']], - 'null' => ['{null: "foo"}', ['null' => 'foo']], - 'float' => ['{0.25: "foo"}', ['0.25' => 'foo']], + 'boolean-true' => ['{true: "foo"}'], + 'boolean-false' => ['{false: "foo"}'], + 'null' => ['{null: "foo"}'], + 'float' => ['{0.25: "foo"}'], ]; } diff --git a/src/Symfony/Component/Yaml/Tests/ParserTest.php b/src/Symfony/Component/Yaml/Tests/ParserTest.php index c34af87388b7f..9abdf5b02533d 100644 --- a/src/Symfony/Component/Yaml/Tests/ParserTest.php +++ b/src/Symfony/Component/Yaml/Tests/ParserTest.php @@ -650,25 +650,27 @@ public static function getObjectForMapTests() public function testObjectsSupportDisabledWithExceptions() { - $this->expectException(ParseException::class); $yaml = <<<'EOF' foo: !php/object:O:30:"Symfony\Tests\Component\Yaml\B":1:{s:1:"b";s:3:"foo";} bar: 1 EOF; + $this->expectException(ParseException::class); + $this->parser->parse($yaml, Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE); } public function testMappingKeyInMultiLineStringThrowsException() { - $this->expectException(ParseException::class); - $this->expectExceptionMessage('Mapping values are not allowed in multi-line blocks at line 2 (near "dbal:wrong").'); - $yaml = <<<'EOF' data: dbal:wrong default_connection: monolith EOF; + + $this->expectException(ParseException::class); + $this->expectExceptionMessage('Mapping values are not allowed in multi-line blocks at line 2 (near "dbal:wrong").'); + $this->parser->parse($yaml); } @@ -707,7 +709,6 @@ public function testNonUtf8Exception() public function testUnindentedCollectionException() { - $this->expectException(ParseException::class); $yaml = <<<'EOF' collection: @@ -717,12 +718,13 @@ public function testUnindentedCollectionException() EOF; + $this->expectException(ParseException::class); + $this->parser->parse($yaml); } public function testShortcutKeyUnindentedCollectionException() { - $this->expectException(ParseException::class); $yaml = <<<'EOF' collection: @@ -731,6 +733,8 @@ public function testShortcutKeyUnindentedCollectionException() EOF; + $this->expectException(ParseException::class); + $this->parser->parse($yaml); } @@ -929,8 +933,6 @@ public function testScalarInSequence() */ public function testMappingDuplicateKeyBlock() { - $this->expectException(ParseException::class); - $this->expectExceptionMessage('Duplicate key "child" detected'); $input = <<<'EOD' parent: child: first @@ -939,28 +941,24 @@ public function testMappingDuplicateKeyBlock() child: duplicate child: duplicate EOD; - $expected = [ - 'parent' => [ - 'child' => 'first', - ], - ]; - $this->assertSame($expected, Yaml::parse($input)); + + $this->expectException(ParseException::class); + $this->expectExceptionMessage('Duplicate key "child" detected'); + + Yaml::parse($input); } public function testMappingDuplicateKeyFlow() { - $this->expectException(ParseException::class); - $this->expectExceptionMessage('Duplicate key "child" detected'); $input = <<<'EOD' parent: { child: first, child: duplicate } parent: { child: duplicate, child: duplicate } EOD; - $expected = [ - 'parent' => [ - 'child' => 'first', - ], - ]; - $this->assertSame($expected, Yaml::parse($input)); + + $this->expectException(ParseException::class); + $this->expectExceptionMessage('Duplicate key "child" detected'); + + Yaml::parse($input); } /** @@ -1202,26 +1200,28 @@ public function testYamlDirective() public function testFloatKeys() { - $this->expectException(ParseException::class); - $this->expectExceptionMessage('Numeric keys are not supported. Quote your evaluable mapping keys instead'); $yaml = <<<'EOF' foo: 1.2: "bar" 1.3: "baz" EOF; + $this->expectException(ParseException::class); + $this->expectExceptionMessage('Numeric keys are not supported. Quote your evaluable mapping keys instead'); + $this->parser->parse($yaml); } public function testBooleanKeys() { - $this->expectException(ParseException::class); - $this->expectExceptionMessage('Non-string keys are not supported. Quote your evaluable mapping keys instead'); $yaml = <<<'EOF' true: foo false: bar EOF; + $this->expectException(ParseException::class); + $this->expectExceptionMessage('Non-string keys are not supported. Quote your evaluable mapping keys instead'); + $this->parser->parse($yaml); } @@ -1252,12 +1252,13 @@ public function testExplicitStringCasting() public function testColonInMappingValueException() { - $this->expectException(ParseException::class); - $this->expectExceptionMessage('A colon cannot be used in an unquoted mapping value'); $yaml = <<<'EOF' foo: bar: baz EOF; + $this->expectException(ParseException::class); + $this->expectExceptionMessage('A colon cannot be used in an unquoted mapping value'); + $this->parser->parse($yaml); } @@ -2347,21 +2348,20 @@ public function testExceptionWhenUsingUnsupportedBuiltInTags() public function testComplexMappingThrowsParseException() { - $this->expectException(ParseException::class); - $this->expectExceptionMessage('Complex mappings are not supported at line 1 (near "? "1"").'); $yaml = <<expectException(ParseException::class); + $this->expectExceptionMessage('Complex mappings are not supported at line 1 (near "? "1"").'); + $this->parser->parse($yaml); } public function testComplexMappingNestedInMappingThrowsParseException() { - $this->expectException(ParseException::class); - $this->expectExceptionMessage('Complex mappings are not supported at line 2 (near "? "1"").'); $yaml = <<expectException(ParseException::class); + $this->expectExceptionMessage('Complex mappings are not supported at line 2 (near "? "1"").'); + $this->parser->parse($yaml); } public function testComplexMappingNestedInSequenceThrowsParseException() { - $this->expectException(ParseException::class); - $this->expectExceptionMessage('Complex mappings are not supported at line 1 (near "- ? "1"").'); $yaml = <<expectException(ParseException::class); + $this->expectExceptionMessage('Complex mappings are not supported at line 1 (near "- ? "1"").'); + $this->parser->parse($yaml); } public function testParsingIniThrowsException() { - $this->expectException(ParseException::class); - $this->expectExceptionMessage('Unable to parse at line 2 (near " foo = bar").'); $ini = <<expectException(ParseException::class); + $this->expectExceptionMessage('Unable to parse at line 2 (near " foo = bar").'); + $this->parser->parse($ini); } @@ -2440,8 +2445,6 @@ public function testCanParseVeryLongValue() public function testParserCleansUpReferencesBetweenRuns() { - $this->expectException(ParseException::class); - $this->expectExceptionMessage('Reference "foo" does not exist at line 2'); $yaml = <<expectException(ParseException::class); + $this->expectExceptionMessage('Reference "foo" does not exist at line 2'); + $this->parser->parse($yaml); } @@ -2574,8 +2581,6 @@ public function testParsingNonExistentFilesThrowsException() public function testParsingNotReadableFilesThrowsException() { - $this->expectException(ParseException::class); - $this->expectExceptionMessageMatches('#^File ".+/Fixtures/not_readable.yml" cannot be read\.$#'); if ('\\' === \DIRECTORY_SEPARATOR) { $this->markTestSkipped('chmod is not supported on Windows'); } @@ -2587,6 +2592,9 @@ public function testParsingNotReadableFilesThrowsException() $file = __DIR__.'/Fixtures/not_readable.yml'; chmod($file, 0200); + $this->expectException(ParseException::class); + $this->expectExceptionMessageMatches('#^File ".+/Fixtures/not_readable.yml" cannot be read\.$#'); + $this->parser->parseFile($file); } @@ -2648,11 +2656,13 @@ public function testParseReferencesOnMergeKeysWithMappingsParsedAsObjects() public function testEvalRefException() { - $this->expectException(ParseException::class); - $this->expectExceptionMessage('Reference "foo" does not exist'); $yaml = <<expectException(ParseException::class); + $this->expectExceptionMessage('Reference "foo" does not exist'); + $this->parser->parse($yaml); } diff --git a/src/Symfony/Contracts/Service/Test/ServiceLocatorTestCase.php b/src/Symfony/Contracts/Service/Test/ServiceLocatorTestCase.php index 583f72a78ee22..65a3fe3379e93 100644 --- a/src/Symfony/Contracts/Service/Test/ServiceLocatorTestCase.php +++ b/src/Symfony/Contracts/Service/Test/ServiceLocatorTestCase.php @@ -12,7 +12,9 @@ namespace Symfony\Contracts\Service\Test; use PHPUnit\Framework\TestCase; +use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; +use Psr\Container\NotFoundExceptionInterface; use Symfony\Contracts\Service\ServiceLocatorTrait; abstract class ServiceLocatorTestCase extends TestCase @@ -66,27 +68,29 @@ public function testGetDoesNotMemoize() public function testThrowsOnUndefinedInternalService() { - if (!$this->getExpectedException()) { - $this->expectException(\Psr\Container\NotFoundExceptionInterface::class); - $this->expectExceptionMessage('The service "foo" has a dependency on a non-existent service "bar". This locator only knows about the "foo" service.'); - } $locator = $this->getServiceLocator([ 'foo' => function () use (&$locator) { return $locator->get('bar'); }, ]); + if (!$this->getExpectedException()) { + $this->expectException(NotFoundExceptionInterface::class); + $this->expectExceptionMessage('The service "foo" has a dependency on a non-existent service "bar". This locator only knows about the "foo" service.'); + } + $locator->get('foo'); } public function testThrowsOnCircularReference() { - $this->expectException(\Psr\Container\ContainerExceptionInterface::class); - $this->expectExceptionMessage('Circular reference detected for service "bar", path: "bar -> baz -> bar".'); $locator = $this->getServiceLocator([ 'foo' => function () use (&$locator) { return $locator->get('bar'); }, 'bar' => function () use (&$locator) { return $locator->get('baz'); }, 'baz' => function () use (&$locator) { return $locator->get('bar'); }, ]); + $this->expectException(ContainerExceptionInterface::class); + $this->expectExceptionMessage('Circular reference detected for service "bar", path: "bar -> baz -> bar".'); + $locator->get('foo'); } } diff --git a/src/Symfony/Contracts/Translation/Test/TranslatorTest.php b/src/Symfony/Contracts/Translation/Test/TranslatorTest.php index 18e669077713a..756228af548a3 100644 --- a/src/Symfony/Contracts/Translation/Test/TranslatorTest.php +++ b/src/Symfony/Contracts/Translation/Test/TranslatorTest.php @@ -183,9 +183,10 @@ public function testReturnMessageIfExactlyOneStandardRuleIsGiven() */ public function testThrowExceptionIfMatchingMessageCannotBeFound($id, $number) { - $this->expectException(\InvalidArgumentException::class); $translator = $this->getTranslator(); + $this->expectException(\InvalidArgumentException::class); + $translator->trans($id, ['%count%' => $number]); }