From 87a47eadc9967ac0f6a7abcc95c2e28dbda66e9d Mon Sep 17 00:00:00 2001 From: Bernhard Schussek Date: Fri, 8 Aug 2014 10:10:43 +0200 Subject: [PATCH] [Validator] Backported constraint validator tests from 2.5 --- .../Constraints/UniqueEntityValidatorTest.php | 414 +++++++++++++++++ .../Constraints/UniqueValidatorTest.php | 437 ------------------ .../Constraints/FormValidatorTest.php | 294 +++++------- .../Constraints/UserPasswordValidatorTest.php | 168 +++++++ .../Validator/Constraints/AllValidator.php | 4 +- .../Validator/Constraints/ChoiceValidator.php | 4 +- .../Constraints/CollectionValidator.php | 4 +- .../AbstractComparisonValidatorTestCase.php | 51 +- .../AbstractConstraintValidatorTest.php | 194 ++++++++ .../Tests/Constraints/AllValidatorTest.php | 57 +-- .../Tests/Constraints/BlankValidatorTest.php | 38 +- .../Constraints/CallbackValidatorTest.php | 156 ++++--- .../Constraints/CardSchemeValidatorTest.php | 44 +- .../Tests/Constraints/ChoiceValidatorTest.php | 146 +++--- .../Tests/Constraints/CollectionTest.php | 4 +- ...llectionValidatorCustomArrayObjectTest.php | 58 +-- .../Constraints/CollectionValidatorTest.php | 219 ++++----- .../CountValidatorCountableTest.php | 17 +- .../Tests/Constraints/CountValidatorTest.php | 71 +-- .../Constraints/CountryValidatorTest.php | 45 +- .../Constraints/CurrencyValidatorTest.php | 45 +- .../Constraints/DateTimeValidatorTest.php | 47 +- .../Tests/Constraints/DateValidatorTest.php | 47 +- .../Tests/Constraints/EmailValidatorTest.php | 43 +- .../Tests/Constraints/FalseValidatorTest.php | 35 +- .../Constraints/FileValidatorPathTest.php | 10 +- .../Tests/Constraints/FileValidatorTest.php | 243 ++++++---- .../Constraints/Fixtures/test_landscape.gif | Bin 0 -> 43 bytes .../Constraints/Fixtures/test_portrait.gif | Bin 0 -> 43 bytes .../Tests/Constraints/GroupSequenceTest.php | 27 ++ .../Tests/Constraints/IbanValidatorTest.php | 34 +- .../Tests/Constraints/ImageValidatorTest.php | 125 ++--- .../Tests/Constraints/IpValidatorTest.php | 165 +++---- .../Tests/Constraints/IsbnValidatorTest.php | 91 ++-- .../Tests/Constraints/IssnValidatorTest.php | 88 ++-- .../Constraints/LanguageValidatorTest.php | 50 +- .../Tests/Constraints/LengthValidatorTest.php | 79 ++-- .../Tests/Constraints/LocaleValidatorTest.php | 44 +- .../Tests/Constraints/LuhnValidatorTest.php | 45 +- .../Constraints/NotBlankValidatorTest.php | 55 +-- .../Constraints/NotNullValidatorTest.php | 30 +- .../Tests/Constraints/NullValidatorTest.php | 33 +- .../Tests/Constraints/RangeValidatorTest.php | 112 ++--- .../Tests/Constraints/RegexValidatorTest.php | 43 +- .../Tests/Constraints/TimeValidatorTest.php | 48 +- .../Tests/Constraints/TrueValidatorTest.php | 38 +- .../Tests/Constraints/TypeValidatorTest.php | 73 ++- .../Tests/Constraints/UrlValidatorTest.php | 52 +-- .../Validator/Tests/Fixtures/Countable.php | 27 ++ .../Tests/Fixtures/CustomArrayObject.php | 70 +++ .../Fixtures/StubGlobalExecutionContext.php | 69 +++ 51 files changed, 2134 insertions(+), 2159 deletions(-) create mode 100644 src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php delete mode 100644 src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueValidatorTest.php create mode 100644 src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.php create mode 100644 src/Symfony/Component/Validator/Tests/Constraints/AbstractConstraintValidatorTest.php create mode 100644 src/Symfony/Component/Validator/Tests/Constraints/Fixtures/test_landscape.gif create mode 100644 src/Symfony/Component/Validator/Tests/Constraints/Fixtures/test_portrait.gif create mode 100644 src/Symfony/Component/Validator/Tests/Constraints/GroupSequenceTest.php create mode 100644 src/Symfony/Component/Validator/Tests/Fixtures/Countable.php create mode 100644 src/Symfony/Component/Validator/Tests/Fixtures/CustomArrayObject.php create mode 100644 src/Symfony/Component/Validator/Tests/Fixtures/StubGlobalExecutionContext.php diff --git a/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php b/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php new file mode 100644 index 000000000000..44dfc853dfe5 --- /dev/null +++ b/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php @@ -0,0 +1,414 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Bridge\Doctrine\Tests\Validator\Constraints; + +use Doctrine\Common\Persistence\ManagerRegistry; +use Doctrine\Common\Persistence\ObjectManager; +use Doctrine\Common\Persistence\ObjectRepository; +use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper; +use Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity; +use Symfony\Component\Validator\Tests\Constraints\AbstractConstraintValidatorTest; +use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity; +use Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNameEntity; +use Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity; +use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; +use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator; +use Symfony\Component\Validator\Validator; +use Doctrine\ORM\Tools\SchemaTool; + +/** + * @author Bernhard Schussek + */ +class UniqueEntityValidatorTest extends AbstractConstraintValidatorTest +{ + const EM_NAME = 'foo'; + + /** + * @var ObjectManager + */ + protected $em; + + /** + * @var ManagerRegistry + */ + protected $registry; + + /** + * @var ObjectRepository + */ + protected $repository; + + protected function setUp() + { + $this->em = DoctrineTestHelper::createTestEntityManager(); + $this->registry = $this->createRegistryMock($this->em); + $this->createSchema($this->em); + + parent::setUp(); + } + + protected function createRegistryMock(ObjectManager $em = null) + { + $registry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry'); + $registry->expects($this->any()) + ->method('getManager') + ->with($this->equalTo(self::EM_NAME)) + ->will($this->returnValue($em)); + + return $registry; + } + + protected function createRepositoryMock() + { + $repository = $this->getMockBuilder('Doctrine\Common\Persistence\ObjectRepository') + ->setMethods(array('findByCustom', 'find', 'findAll', 'findOneBy', 'findBy', 'getClassName')) + ->getMock() + ; + + return $repository; + } + + protected function createEntityManagerMock($repositoryMock) + { + $em = $this->getMockBuilder('Doctrine\Common\Persistence\ObjectManager') + ->getMock() + ; + $em->expects($this->any()) + ->method('getRepository') + ->will($this->returnValue($repositoryMock)) + ; + + $classMetadata = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata'); + $classMetadata + ->expects($this->any()) + ->method('hasField') + ->will($this->returnValue(true)) + ; + $reflParser = $this->getMockBuilder('Doctrine\Common\Reflection\StaticReflectionParser') + ->disableOriginalConstructor() + ->getMock() + ; + $refl = $this->getMockBuilder('Doctrine\Common\Reflection\StaticReflectionProperty') + ->setConstructorArgs(array($reflParser, 'property-name')) + ->setMethods(array('getValue')) + ->getMock() + ; + $refl + ->expects($this->any()) + ->method('getValue') + ->will($this->returnValue(true)) + ; + $classMetadata->reflFields = array('name' => $refl); + $em->expects($this->any()) + ->method('getClassMetadata') + ->will($this->returnValue($classMetadata)) + ; + + return $em; + } + + protected function createValidator() + { + return new UniqueEntityValidator($this->registry); + } + + private function createSchema(ObjectManager $em) + { + $schemaTool = new SchemaTool($em); + $schemaTool->createSchema(array( + $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity'), + $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNameEntity'), + $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity'), + $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity'), + )); + } + + /** + * This is a functional test as there is a large integration necessary to get the validator working. + */ + public function testValidateUniqueness() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('name'), + 'em' => self::EM_NAME, + )); + + $entity1 = new SingleIntIdEntity(1, 'Foo'); + $entity2 = new SingleIntIdEntity(2, 'Foo'); + + $this->validator->validate($entity1, $constraint); + + $this->assertNoViolation(); + + $this->em->persist($entity1); + $this->em->flush(); + + $this->validator->validate($entity1, $constraint); + + $this->assertNoViolation(); + + $this->validator->validate($entity2, $constraint); + + $this->assertViolation('myMessage', array(), 'property.path.name', 'Foo'); + } + + public function testValidateCustomErrorPath() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('name'), + 'em' => self::EM_NAME, + 'errorPath' => 'bar', + )); + + $entity1 = new SingleIntIdEntity(1, 'Foo'); + $entity2 = new SingleIntIdEntity(2, 'Foo'); + + $this->em->persist($entity1); + $this->em->flush(); + + $this->validator->validate($entity2, $constraint); + + $this->assertViolation('myMessage', array(), 'property.path.bar', 'Foo'); + } + + public function testValidateUniquenessWithNull() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('name'), + 'em' => self::EM_NAME, + )); + + $entity1 = new SingleIntIdEntity(1, null); + $entity2 = new SingleIntIdEntity(2, null); + + $this->em->persist($entity1); + $this->em->persist($entity2); + $this->em->flush(); + + $this->validator->validate($entity1, $constraint); + + $this->assertNoViolation(); + } + + public function testValidateUniquenessWithIgnoreNull() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('name', 'name2'), + 'em' => self::EM_NAME, + 'ignoreNull' => false, + )); + + $entity1 = new DoubleNameEntity(1, 'Foo', null); + $entity2 = new DoubleNameEntity(2, 'Foo', null); + + $this->validator->validate($entity1, $constraint); + + $this->assertNoViolation(); + + $this->em->persist($entity1); + $this->em->flush(); + + $this->validator->validate($entity1, $constraint); + + $this->assertNoViolation(); + + $this->validator->validate($entity2, $constraint); + + $this->assertViolation('myMessage', array(), 'property.path.name', 'Foo'); + } + + public function testValidateUniquenessUsingCustomRepositoryMethod() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('name'), + 'em' => self::EM_NAME, + 'repositoryMethod' => 'findByCustom', + )); + + $repository = $this->createRepositoryMock(); + $repository->expects($this->once()) + ->method('findByCustom') + ->will($this->returnValue(array())) + ; + $this->em = $this->createEntityManagerMock($repository); + $this->registry = $this->createRegistryMock($this->em); + $this->validator = $this->createValidator(); + $this->validator->initialize($this->context); + + $entity1 = new SingleIntIdEntity(1, 'foo'); + + $this->validator->validate($entity1, $constraint); + + $this->assertNoViolation(); + } + + public function testValidateUniquenessWithUnrewoundArray() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('name'), + 'em' => self::EM_NAME, + 'repositoryMethod' => 'findByCustom', + )); + + $entity = new SingleIntIdEntity(1, 'foo'); + + $repository = $this->createRepositoryMock(); + $repository->expects($this->once()) + ->method('findByCustom') + ->will( + $this->returnCallback(function () use ($entity) { + $returnValue = array( + $entity, + ); + next($returnValue); + + return $returnValue; + }) + ) + ; + $this->em = $this->createEntityManagerMock($repository); + $this->registry = $this->createRegistryMock($this->em); + $this->validator = $this->createValidator(); + $this->validator->initialize($this->context); + + $this->validator->validate($entity, $constraint); + + $this->assertNoViolation(); + } + + /** + * @group GH-1635 + */ + public function testAssociatedEntity() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('single'), + 'em' => self::EM_NAME, + )); + + $entity1 = new SingleIntIdEntity(1, 'foo'); + $associated = new AssociationEntity(); + $associated->single = $entity1; + $associated2 = new AssociationEntity(); + $associated2->single = $entity1; + + $this->em->persist($entity1); + $this->em->persist($associated); + $this->em->flush(); + + $this->validator->validate($associated, $constraint); + + $this->assertNoViolation(); + + $this->em->persist($associated2); + $this->em->flush(); + + $this->validator->validate($associated2, $constraint); + + $this->assertViolation('myMessage', array(), 'property.path.single', 1); + } + + public function testAssociatedEntityWithNull() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('single'), + 'em' => self::EM_NAME, + 'ignoreNull' => false, + )); + + $associated = new AssociationEntity(); + $associated->single = null; + + $this->em->persist($associated); + $this->em->flush(); + + $this->validator->validate($associated, $constraint); + + $this->assertNoViolation(); + } + + /** + * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException + * @expectedExceptionMessage Associated entities are not allowed to have more than one identifier field + * @group GH-1635 + */ + public function testAssociatedCompositeEntity() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('composite'), + 'em' => self::EM_NAME, + )); + + $composite = new CompositeIntIdEntity(1, 1, "test"); + $associated = new AssociationEntity(); + $associated->composite = $composite; + + $this->em->persist($composite); + $this->em->persist($associated); + $this->em->flush(); + + $this->validator->validate($associated, $constraint); + } + + /** + * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException + * @expectedExceptionMessage Object manager "foo" does not exist. + */ + public function testDedicatedEntityManagerNullObject() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('name'), + 'em' => self::EM_NAME, + )); + + $this->em = null; + $this->registry = $this->createRegistryMock($this->em); + $this->validator = $this->createValidator(); + $this->validator->initialize($this->context); + + $entity = new SingleIntIdEntity(1, null); + + $this->validator->validate($entity, $constraint); + } + + /** + * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException + * @expectedExceptionMessage Unable to find the object manager associated with an entity of class "Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity" + */ + public function testEntityManagerNullObject() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('name'), + // no "em" option set + )); + + $this->em = null; + $this->registry = $this->createRegistryMock($this->em); + $this->validator = $this->createValidator(); + $this->validator->initialize($this->context); + + $entity = new SingleIntIdEntity(1, null); + + $this->validator->validate($entity, $constraint); + } +} diff --git a/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueValidatorTest.php b/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueValidatorTest.php deleted file mode 100644 index 998080264200..000000000000 --- a/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueValidatorTest.php +++ /dev/null @@ -1,437 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bridge\Doctrine\Tests\Validator\Constraints; - -use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper; -use Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity; -use Symfony\Component\Validator\DefaultTranslator; -use Symfony\Component\Validator\Tests\Fixtures\FakeMetadataFactory; -use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity; -use Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNameEntity; -use Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity; -use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; -use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator; -use Symfony\Component\Validator\Mapping\ClassMetadata; -use Symfony\Component\Validator\Validator; -use Doctrine\ORM\Tools\SchemaTool; - -class UniqueValidatorTest extends \PHPUnit_Framework_TestCase -{ - protected function setUp() - { - parent::setUp(); - - if (!class_exists('Symfony\Component\Security\Core\SecurityContext')) { - $this->markTestSkipped('The "Security" component is not available'); - } - - if (!class_exists('Symfony\Component\Validator\Constraint')) { - $this->markTestSkipped('The "Validator" component is not available'); - } - } - - protected function createRegistryMock($entityManagerName, $em) - { - $registry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry'); - $registry->expects($this->any()) - ->method('getManager') - ->with($this->equalTo($entityManagerName)) - ->will($this->returnValue($em)); - - return $registry; - } - - protected function createRepositoryMock() - { - $repository = $this->getMockBuilder('Doctrine\Common\Persistence\ObjectRepository') - ->setMethods(array('findByCustom', 'find', 'findAll', 'findOneBy', 'findBy', 'getClassName')) - ->getMock() - ; - - return $repository; - } - - protected function createEntityManagerMock($repositoryMock) - { - $em = $this->getMockBuilder('Doctrine\Common\Persistence\ObjectManager') - ->getMock() - ; - $em->expects($this->any()) - ->method('getRepository') - ->will($this->returnValue($repositoryMock)) - ; - - $classMetadata = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata'); - $classMetadata - ->expects($this->any()) - ->method('hasField') - ->will($this->returnValue(true)) - ; - $reflParser = $this->getMockBuilder('Doctrine\Common\Reflection\StaticReflectionParser') - ->disableOriginalConstructor() - ->getMock() - ; - $refl = $this->getMockBuilder('Doctrine\Common\Reflection\StaticReflectionProperty') - ->setConstructorArgs(array($reflParser, 'property-name')) - ->setMethods(array('getValue')) - ->getMock() - ; - $refl - ->expects($this->any()) - ->method('getValue') - ->will($this->returnValue(true)) - ; - $classMetadata->reflFields = array('name' => $refl); - $em->expects($this->any()) - ->method('getClassMetadata') - ->will($this->returnValue($classMetadata)) - ; - - return $em; - } - - protected function createValidatorFactory($uniqueValidator) - { - $validatorFactory = $this->getMock('Symfony\Component\Validator\ConstraintValidatorFactoryInterface'); - $validatorFactory->expects($this->any()) - ->method('getInstance') - ->with($this->isInstanceOf('Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity')) - ->will($this->returnValue($uniqueValidator)); - - return $validatorFactory; - } - - public function createValidator($entityManagerName, $em, $validateClass = null, $uniqueFields = null, $errorPath = null, $repositoryMethod = 'findBy', $ignoreNull = true) - { - if (!$validateClass) { - $validateClass = 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity'; - } - if (!$uniqueFields) { - $uniqueFields = array('name'); - } - - $registry = $this->createRegistryMock($entityManagerName, $em); - - $uniqueValidator = new UniqueEntityValidator($registry); - - $metadata = new ClassMetadata($validateClass); - $constraint = new UniqueEntity(array( - 'fields' => $uniqueFields, - 'em' => $entityManagerName, - 'errorPath' => $errorPath, - 'repositoryMethod' => $repositoryMethod, - 'ignoreNull' => $ignoreNull - )); - $metadata->addConstraint($constraint); - - $metadataFactory = new FakeMetadataFactory(); - $metadataFactory->addMetadata($metadata); - $validatorFactory = $this->createValidatorFactory($uniqueValidator); - - return new Validator($metadataFactory, $validatorFactory, new DefaultTranslator()); - } - - private function createSchema($em) - { - $schemaTool = new SchemaTool($em); - $schemaTool->createSchema(array( - $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity'), - $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNameEntity'), - $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity'), - $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity'), - )); - } - - /** - * This is a functional test as there is a large integration necessary to get the validator working. - */ - public function testValidateUniqueness() - { - $entityManagerName = "foo"; - $em = DoctrineTestHelper::createTestEntityManager(); - $this->createSchema($em); - $validator = $this->createValidator($entityManagerName, $em); - - $entity1 = new SingleIntIdEntity(1, 'Foo'); - $violationsList = $validator->validate($entity1); - $this->assertEquals(0, $violationsList->count(), "No violations found on entity before it is saved to the database."); - - $em->persist($entity1); - $em->flush(); - - $violationsList = $validator->validate($entity1); - $this->assertEquals(0, $violationsList->count(), "No violations found on entity after it was saved to the database."); - - $entity2 = new SingleIntIdEntity(2, 'Foo'); - - $violationsList = $validator->validate($entity2); - $this->assertEquals(1, $violationsList->count(), "Violation found on entity with conflicting entity existing in the database."); - - $violation = $violationsList[0]; - $this->assertEquals('This value is already used.', $violation->getMessage()); - $this->assertEquals('name', $violation->getPropertyPath()); - $this->assertEquals('Foo', $violation->getInvalidValue()); - } - - public function testValidateCustomErrorPath() - { - $entityManagerName = "foo"; - $em = DoctrineTestHelper::createTestEntityManager(); - $this->createSchema($em); - $validator = $this->createValidator($entityManagerName, $em, null, null, 'bar'); - - $entity1 = new SingleIntIdEntity(1, 'Foo'); - - $em->persist($entity1); - $em->flush(); - - $entity2 = new SingleIntIdEntity(2, 'Foo'); - - $violationsList = $validator->validate($entity2); - $this->assertEquals(1, $violationsList->count(), "Violation found on entity with conflicting entity existing in the database."); - - $violation = $violationsList[0]; - $this->assertEquals('This value is already used.', $violation->getMessage()); - $this->assertEquals('bar', $violation->getPropertyPath()); - $this->assertEquals('Foo', $violation->getInvalidValue()); - } - - public function testValidateUniquenessWithNull() - { - $entityManagerName = "foo"; - $em = DoctrineTestHelper::createTestEntityManager(); - $this->createSchema($em); - $validator = $this->createValidator($entityManagerName, $em); - - $entity1 = new SingleIntIdEntity(1, null); - $entity2 = new SingleIntIdEntity(2, null); - - $em->persist($entity1); - $em->persist($entity2); - $em->flush(); - - $violationsList = $validator->validate($entity1); - $this->assertEquals(0, $violationsList->count(), "No violations found on entity having a null value."); - } - - public function testValidateUniquenessWithIgnoreNull() - { - $entityManagerName = "foo"; - $validateClass = 'Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNameEntity'; - $em = DoctrineTestHelper::createTestEntityManager(); - $this->createSchema($em); - $validator = $this->createValidator($entityManagerName, $em, $validateClass, array('name', 'name2'), 'bar', 'findby', false); - - $entity1 = new DoubleNameEntity(1, 'Foo', null); - $violationsList = $validator->validate($entity1); - $this->assertEquals(0, $violationsList->count(), "No violations found on entity before it is saved to the database."); - - $em->persist($entity1); - $em->flush(); - - $violationsList = $validator->validate($entity1); - $this->assertEquals(0, $violationsList->count(), "No violations found on entity after it was saved to the database."); - - $entity2 = new DoubleNameEntity(2, 'Foo', null); - - $violationsList = $validator->validate($entity2); - $this->assertEquals(1, $violationsList->count(), "Violation found on entity with conflicting entity existing in the database."); - - $violation = $violationsList[0]; - $this->assertEquals('This value is already used.', $violation->getMessage()); - $this->assertEquals('bar', $violation->getPropertyPath()); - $this->assertEquals('Foo', $violation->getInvalidValue()); - } - - public function testValidateUniquenessAfterConsideringMultipleQueryResults() - { - $entityManagerName = "foo"; - $em = DoctrineTestHelper::createTestEntityManager(); - $this->createSchema($em); - $validator = $this->createValidator($entityManagerName, $em); - - $entity1 = new SingleIntIdEntity(1, 'foo'); - $entity2 = new SingleIntIdEntity(2, 'foo'); - - $em->persist($entity1); - $em->persist($entity2); - $em->flush(); - - $violationsList = $validator->validate($entity1); - $this->assertEquals(1, $violationsList->count(), 'Violation found on entity with conflicting entity existing in the database.'); - - $violationsList = $validator->validate($entity2); - $this->assertEquals(1, $violationsList->count(), 'Violation found on entity with conflicting entity existing in the database.'); - } - - public function testValidateUniquenessUsingCustomRepositoryMethod() - { - $entityManagerName = 'foo'; - $repository = $this->createRepositoryMock(); - $repository->expects($this->once()) - ->method('findByCustom') - ->will($this->returnValue(array())) - ; - $em = $this->createEntityManagerMock($repository); - $validator = $this->createValidator($entityManagerName, $em, null, array(), null, 'findByCustom'); - - $entity1 = new SingleIntIdEntity(1, 'foo'); - - $violationsList = $validator->validate($entity1); - $this->assertEquals(0, $violationsList->count(), 'Violation is using custom repository method.'); - } - - public function testValidateUniquenessWithUnrewoundArray() - { - $entity = new SingleIntIdEntity(1, 'foo'); - - $entityManagerName = 'foo'; - $repository = $this->createRepositoryMock(); - $repository->expects($this->once()) - ->method('findByCustom') - ->will( - $this->returnCallback(function () use ($entity) { - $returnValue = array( - $entity, - ); - next($returnValue); - - return $returnValue; - }) - ) - ; - $em = $this->createEntityManagerMock($repository); - $validator = $this->createValidator($entityManagerName, $em, null, array(), null, 'findByCustom'); - - $violationsList = $validator->validate($entity); - $this->assertCount(0, $violationsList, 'Violation is using unrewound array as return value in the repository method.'); - } - - /** - * @group GH-1635 - */ - public function testAssociatedEntity() - { - $entityManagerName = "foo"; - $em = DoctrineTestHelper::createTestEntityManager(); - $this->createSchema($em); - $validator = $this->createValidator($entityManagerName, $em, 'Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity', array('single')); - - $entity1 = new SingleIntIdEntity(1, 'foo'); - $associated = new AssociationEntity(); - $associated->single = $entity1; - - $em->persist($entity1); - $em->persist($associated); - $em->flush(); - - $violationsList = $validator->validate($associated); - $this->assertEquals(0, $violationsList->count()); - - $associated2 = new AssociationEntity(); - $associated2->single = $entity1; - - $em->persist($associated2); - $em->flush(); - - $violationsList = $validator->validate($associated2); - $this->assertEquals(1, $violationsList->count()); - } - - public function testAssociatedEntityWithNull() - { - $entityManagerName = "foo"; - $em = DoctrineTestHelper::createTestEntityManager(); - $this->createSchema($em); - $validator = $this->createValidator($entityManagerName, $em, 'Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity', array('single'), null, 'findBy', false); - - $associated = new AssociationEntity(); - $associated->single = null; - - $em->persist($associated); - $em->flush(); - - $violationsList = $validator->validate($associated); - $this->assertEquals(0, $violationsList->count()); - } - - /** - * @group GH-1635 - */ - public function testAssociatedCompositeEntity() - { - $entityManagerName = "foo"; - $em = DoctrineTestHelper::createTestEntityManager(); - $this->createSchema($em); - $validator = $this->createValidator($entityManagerName, $em, 'Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity', array('composite')); - - $composite = new CompositeIntIdEntity(1, 1, "test"); - $associated = new AssociationEntity(); - $associated->composite = $composite; - - $em->persist($composite); - $em->persist($associated); - $em->flush(); - - $this->setExpectedException( - 'Symfony\Component\Validator\Exception\ConstraintDefinitionException', - 'Associated entities are not allowed to have more than one identifier field' - ); - $violationsList = $validator->validate($associated); - } - - public function testDedicatedEntityManagerNullObject() - { - $uniqueFields = array('name'); - $entityManagerName = 'foo'; - - $registry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry'); - - $constraint = new UniqueEntity(array( - 'fields' => $uniqueFields, - 'em' => $entityManagerName, - )); - - $uniqueValidator = new UniqueEntityValidator($registry); - - $entity = new SingleIntIdEntity(1, null); - - $this->setExpectedException( - 'Symfony\Component\Validator\Exception\ConstraintDefinitionException', - 'Object manager "foo" does not exist.' - ); - - $uniqueValidator->validate($entity, $constraint); - } - - public function testEntityManagerNullObject() - { - $uniqueFields = array('name'); - - $registry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry'); - - $constraint = new UniqueEntity(array( - 'fields' => $uniqueFields, - )); - - $uniqueValidator = new UniqueEntityValidator($registry); - - $entity = new SingleIntIdEntity(1, null); - - $this->setExpectedException( - 'Symfony\Component\Validator\Exception\ConstraintDefinitionException', - 'Unable to find the object manager associated with an entity of class "Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity"' - ); - - $uniqueValidator->validate($entity, $constraint); - } -} diff --git a/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorTest.php b/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorTest.php index dc504172a0a6..bfb84a15f84b 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorTest.php @@ -21,11 +21,12 @@ use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraints\NotNull; use Symfony\Component\Validator\Constraints\NotBlank; +use Symfony\Component\Validator\Tests\Constraints\AbstractConstraintValidatorTest; /** * @author Bernhard Schussek */ -class FormValidatorTest extends \PHPUnit_Framework_TestCase +class FormValidatorTest extends AbstractConstraintValidatorTest { /** * @var \PHPUnit_Framework_MockObject_MockObject @@ -40,51 +41,43 @@ class FormValidatorTest extends \PHPUnit_Framework_TestCase /** * @var \PHPUnit_Framework_MockObject_MockObject */ - private $serverParams; - - /** - * @var FormValidator - */ - private $validator; + protected $serverParams; protected function setUp() { - if (!class_exists('Symfony\Component\EventDispatcher\Event')) { - $this->markTestSkipped('The "EventDispatcher" component is not available'); - } - $this->dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface'); $this->factory = $this->getMock('Symfony\Component\Form\FormFactoryInterface'); $this->serverParams = $this->getMock( 'Symfony\Component\Form\Extension\Validator\Util\ServerParams', array('getNormalizedIniPostMaxSize', 'getContentLength') ); - $this->validator = new FormValidator($this->serverParams); + + parent::setUp(); + } + + protected function createValidator() + { + return new FormValidator($this->serverParams); } public function testValidate() { - $context = $this->getMockExecutionContext(); $object = $this->getMock('\stdClass'); $options = array('validation_groups' => array('group1', 'group2')); $form = $this->getBuilder('name', '\stdClass', $options) ->setData($object) ->getForm(); - $context->expects($this->at(0)) - ->method('validate') - ->with($object, 'data', 'group1', true); - $context->expects($this->at(1)) - ->method('validate') - ->with($object, 'data', 'group2', true); + $this->expectValidateAt(0, 'data', $object, 'group1'); + $this->expectValidateAt(1, 'data', $object, 'group2'); - $this->validator->initialize($context); $this->validator->validate($form, new Form()); + + $this->assertNoViolation(); } public function testValidateConstraints() { - $context = $this->getMockExecutionContext(); $object = $this->getMock('\stdClass'); $constraint1 = new NotNull(array('groups' => array('group1', 'group2'))); $constraint2 = new NotBlank(array('groups' => 'group2')); @@ -98,28 +91,20 @@ public function testValidateConstraints() ->getForm(); // First default constraints - $context->expects($this->at(0)) - ->method('validate') - ->with($object, 'data', 'group1', true); - $context->expects($this->at(1)) - ->method('validate') - ->with($object, 'data', 'group2', true); + $this->expectValidateAt(0, 'data', $object, 'group1'); + $this->expectValidateAt(1, 'data', $object, 'group2'); // Then custom constraints - $context->expects($this->at(2)) - ->method('validateValue') - ->with($object, $constraint1, 'data', 'group1'); - $context->expects($this->at(3)) - ->method('validateValue') - ->with($object, $constraint2, 'data', 'group2'); - - $this->validator->initialize($context); + $this->expectValidateValueAt(2, 'data', $object, $constraint1, 'group1'); + $this->expectValidateValueAt(3, 'data', $object, $constraint2, 'group2'); + $this->validator->validate($form, new Form()); + + $this->assertNoViolation(); } public function testDontValidateIfParentWithoutCascadeValidation() { - $context = $this->getMockExecutionContext(); $object = $this->getMock('\stdClass'); $parent = $this->getBuilder('parent', null, array('cascade_validation' => false)) @@ -132,16 +117,15 @@ public function testDontValidateIfParentWithoutCascadeValidation() $form->setData($object); - $context->expects($this->never()) - ->method('validate'); + $this->expectNoValidate(); - $this->validator->initialize($context); $this->validator->validate($form, new Form()); + + $this->assertNoViolation(); } public function testValidateConstraintsEvenIfNoCascadeValidation() { - $context = $this->getMockExecutionContext(); $object = $this->getMock('\stdClass'); $constraint1 = new NotNull(array('groups' => array('group1', 'group2'))); $constraint2 = new NotBlank(array('groups' => 'group2')); @@ -159,20 +143,16 @@ public function testValidateConstraintsEvenIfNoCascadeValidation() ->getForm(); $parent->add($form); - $context->expects($this->at(0)) - ->method('validateValue') - ->with($object, $constraint1, 'data', 'group1'); - $context->expects($this->at(1)) - ->method('validateValue') - ->with($object, $constraint2, 'data', 'group2'); + $this->expectValidateValueAt(0, 'data', $object, $constraint1, 'group1'); + $this->expectValidateValueAt(1, 'data', $object, $constraint2, 'group2'); - $this->validator->initialize($context); $this->validator->validate($form, new Form()); + + $this->assertNoViolation(); } public function testDontValidateIfNoValidationGroups() { - $context = $this->getMockExecutionContext(); $object = $this->getMock('\stdClass'); $form = $this->getBuilder('name', '\stdClass', array( @@ -183,16 +163,15 @@ public function testDontValidateIfNoValidationGroups() $form->setData($object); - $context->expects($this->never()) - ->method('validate'); + $this->expectNoValidate(); - $this->validator->initialize($context); $this->validator->validate($form, new Form()); + + $this->assertNoViolation(); } public function testDontValidateConstraintsIfNoValidationGroups() { - $context = $this->getMockExecutionContext(); $object = $this->getMock('\stdClass'); $constraint1 = $this->getMock('Symfony\Component\Validator\Constraint'); $constraint2 = $this->getMock('Symfony\Component\Validator\Constraint'); @@ -208,16 +187,15 @@ public function testDontValidateConstraintsIfNoValidationGroups() // Launch transformer $form->submit(array()); - $context->expects($this->never()) - ->method('validate'); + $this->expectNoValidate(); - $this->validator->initialize($context); $this->validator->validate($form, new Form()); + + $this->assertNoViolation(); } public function testDontValidateIfNotSynchronized() { - $context = $this->getMockExecutionContext(); $object = $this->getMock('\stdClass'); $form = $this->getBuilder('name', '\stdClass', array( @@ -237,26 +215,18 @@ function () { throw new TransformationFailedException(); } // Launch transformer $form->submit('foo'); - $context->expects($this->never()) - ->method('validate'); - - $context->expects($this->once()) - ->method('addViolation') - ->with( - 'invalid_message_key', - array('{{ value }}' => 'foo', '{{ foo }}' => 'bar'), - 'foo' - ); - $context->expects($this->never()) - ->method('addViolationAt'); + $this->expectNoValidate(); - $this->validator->initialize($context); $this->validator->validate($form, new Form()); + + $this->assertViolation('invalid_message_key', array( + '{{ value }}' => 'foo', + '{{ foo }}' => 'bar' + ), 'property.path', 'foo', null, Form::ERR_INVALID); } public function testAddInvalidErrorEvenIfNoValidationGroups() { - $context = $this->getMockExecutionContext(); $object = $this->getMock('\stdClass'); $form = $this->getBuilder('name', '\stdClass', array( @@ -277,31 +247,24 @@ function () { throw new TransformationFailedException(); } // Launch transformer $form->submit('foo'); - $context->expects($this->never()) - ->method('validate'); - - $context->expects($this->once()) - ->method('addViolation') - ->with( - 'invalid_message_key', - array('{{ value }}' => 'foo', '{{ foo }}' => 'bar'), - 'foo' - ); - $context->expects($this->never()) - ->method('addViolationAt'); + $this->expectNoValidate(); - $this->validator->initialize($context); $this->validator->validate($form, new Form()); + + $this->assertViolation('invalid_message_key', array( + '{{ value }}' => 'foo', + '{{ foo }}' => 'bar' + ), 'property.path', 'foo', null, Form::ERR_INVALID); } public function testDontValidateConstraintsIfNotSynchronized() { - $context = $this->getMockExecutionContext(); $object = $this->getMock('\stdClass'); $constraint1 = $this->getMock('Symfony\Component\Validator\Constraint'); $constraint2 = $this->getMock('Symfony\Component\Validator\Constraint'); $options = array( + 'invalid_message' => 'invalid_message_key', 'validation_groups' => array('group1', 'group2'), 'constraints' => array($constraint1, $constraint2), ); @@ -314,19 +277,20 @@ function () { throw new TransformationFailedException(); } ->getForm(); // Launch transformer - $form->submit(array()); + $form->submit('foo'); - $context->expects($this->never()) - ->method('validate'); + $this->expectNoValidate(); - $this->validator->initialize($context); $this->validator->validate($form, new Form()); + + $this->assertViolation('invalid_message_key', array( + '{{ value }}' => 'foo', + ), 'property.path','foo', null, Form::ERR_INVALID); } // https://github.com/symfony/symfony/issues/4359 public function testDontMarkInvalidIfAnyChildIsNotSynchronized() { - $context = $this->getMockExecutionContext(); $object = $this->getMock('\stdClass'); $failingTransformer = new CallbackTransformer( @@ -348,55 +312,46 @@ function () { throw new TransformationFailedException(); } // Launch transformer $form->submit(array('child' => 'foo')); - $context->expects($this->never()) - ->method('addViolation'); - $context->expects($this->never()) - ->method('addViolationAt'); + $this->expectNoValidate(); - $this->validator->initialize($context); $this->validator->validate($form, new Form()); + + $this->assertNoViolation(); } public function testHandleCallbackValidationGroups() { - $context = $this->getMockExecutionContext(); $object = $this->getMock('\stdClass'); $options = array('validation_groups' => array($this, 'getValidationGroups')); $form = $this->getBuilder('name', '\stdClass', $options) ->setData($object) ->getForm(); - $context->expects($this->at(0)) - ->method('validate') - ->with($object, 'data', 'group1', true); - $context->expects($this->at(1)) - ->method('validate') - ->with($object, 'data', 'group2', true); + $this->expectValidateAt(0, 'data', $object, 'group1'); + $this->expectValidateAt(1, 'data', $object, 'group2'); - $this->validator->initialize($context); $this->validator->validate($form, new Form()); + + $this->assertNoViolation(); } public function testDontExecuteFunctionNames() { - $context = $this->getMockExecutionContext(); $object = $this->getMock('\stdClass'); $options = array('validation_groups' => 'header'); $form = $this->getBuilder('name', '\stdClass', $options) ->setData($object) ->getForm(); - $context->expects($this->once()) - ->method('validate') - ->with($object, 'data', 'header', true); + $this->expectValidateAt(0, 'data', $object, 'header'); - $this->validator->initialize($context); $this->validator->validate($form, new Form()); + + $this->assertNoViolation(); } public function testHandleClosureValidationGroups() { - $context = $this->getMockExecutionContext(); $object = $this->getMock('\stdClass'); $options = array('validation_groups' => function (FormInterface $form) { return array('group1', 'group2'); @@ -405,20 +360,16 @@ public function testHandleClosureValidationGroups() ->setData($object) ->getForm(); - $context->expects($this->at(0)) - ->method('validate') - ->with($object, 'data', 'group1', true); - $context->expects($this->at(1)) - ->method('validate') - ->with($object, 'data', 'group2', true); + $this->expectValidateAt(0, 'data', $object, 'group1'); + $this->expectValidateAt(1, 'data', $object, 'group2'); - $this->validator->initialize($context); $this->validator->validate($form, new Form()); + + $this->assertNoViolation(); } public function testUseValidationGroupOfClickedButton() { - $context = $this->getMockExecutionContext(); $object = $this->getMock('\stdClass'); $parent = $this->getBuilder('parent', null, array('cascade_validation' => true)) @@ -436,17 +387,15 @@ public function testUseValidationGroupOfClickedButton() $parent->submit(array('name' => $object, 'submit' => '')); - $context->expects($this->once()) - ->method('validate') - ->with($object, 'data', 'button_group', true); + $this->expectValidateAt(0, 'data', $object, 'button_group'); - $this->validator->initialize($context); $this->validator->validate($form, new Form()); + + $this->assertNoViolation(); } public function testDontUseValidationGroupOfUnclickedButton() { - $context = $this->getMockExecutionContext(); $object = $this->getMock('\stdClass'); $parent = $this->getBuilder('parent', null, array('cascade_validation' => true)) @@ -464,17 +413,15 @@ public function testDontUseValidationGroupOfUnclickedButton() $form->setData($object); - $context->expects($this->once()) - ->method('validate') - ->with($object, 'data', 'form_group', true); + $this->expectValidateAt(0, 'data', $object, 'form_group'); - $this->validator->initialize($context); $this->validator->validate($form, new Form()); + + $this->assertNoViolation(); } public function testUseInheritedValidationGroup() { - $context = $this->getMockExecutionContext(); $object = $this->getMock('\stdClass'); $parentOptions = array( @@ -490,17 +437,15 @@ public function testUseInheritedValidationGroup() $form->setData($object); - $context->expects($this->once()) - ->method('validate') - ->with($object, 'data', 'group', true); + $this->expectValidateAt(0, 'data', $object, 'group'); - $this->validator->initialize($context); $this->validator->validate($form, new Form()); + + $this->assertNoViolation(); } public function testUseInheritedCallbackValidationGroup() { - $context = $this->getMockExecutionContext(); $object = $this->getMock('\stdClass'); $parentOptions = array( @@ -516,20 +461,16 @@ public function testUseInheritedCallbackValidationGroup() $form->setData($object); - $context->expects($this->at(0)) - ->method('validate') - ->with($object, 'data', 'group1', true); - $context->expects($this->at(1)) - ->method('validate') - ->with($object, 'data', 'group2', true); + $this->expectValidateAt(0, 'data', $object, 'group1'); + $this->expectValidateAt(1, 'data', $object, 'group2'); - $this->validator->initialize($context); $this->validator->validate($form, new Form()); + + $this->assertNoViolation(); } public function testUseInheritedClosureValidationGroup() { - $context = $this->getMockExecutionContext(); $object = $this->getMock('\stdClass'); $parentOptions = array( @@ -547,52 +488,43 @@ public function testUseInheritedClosureValidationGroup() $form->setData($object); - $context->expects($this->at(0)) - ->method('validate') - ->with($object, 'data', 'group1', true); - $context->expects($this->at(1)) - ->method('validate') - ->with($object, 'data', 'group2', true); + $this->expectValidateAt(0, 'data', $object, 'group1'); + $this->expectValidateAt(1, 'data', $object, 'group2'); - $this->validator->initialize($context); $this->validator->validate($form, new Form()); + + $this->assertNoViolation(); } public function testAppendPropertyPath() { - $context = $this->getMockExecutionContext(); $object = $this->getMock('\stdClass'); $form = $this->getBuilder('name', '\stdClass') ->setData($object) ->getForm(); - $context->expects($this->once()) - ->method('validate') - ->with($object, 'data', 'Default', true); + $this->expectValidateAt(0, 'data', $object, 'Default'); - $this->validator->initialize($context); $this->validator->validate($form, new Form()); + + $this->assertNoViolation(); } public function testDontWalkScalars() { - $context = $this->getMockExecutionContext(); - $form = $this->getBuilder() ->setData('scalar') ->getForm(); - $context->expects($this->never()) - ->method('validate'); + $this->expectNoValidate(); - $this->validator->initialize($context); $this->validator->validate($form, new Form()); + + $this->assertNoViolation(); } public function testViolationIfExtraData() { - $context = $this->getMockExecutionContext(); - $form = $this->getBuilder('parent', null, array('extra_fields_message' => 'Extra!')) ->setCompound(true) ->setDataMapper($this->getDataMapper()) @@ -601,18 +533,13 @@ public function testViolationIfExtraData() $form->submit(array('foo' => 'bar')); - $context->expects($this->once()) - ->method('addViolation') - ->with( - 'Extra!', - array('{{ extra_fields }}' => 'foo'), - array('foo' => 'bar') - ); - $context->expects($this->never()) - ->method('addViolationAt'); - - $this->validator->initialize($context); + $this->expectNoValidate(); + $this->validator->validate($form, new Form()); + + $this->assertViolation('Extra!', array( + '{{ extra_fields }}' => 'foo' + ), 'property.path', array('foo' => 'bar')); } /** @@ -627,26 +554,18 @@ public function testPostMaxSizeViolation($contentLength, $iniMax, $nbViolation, ->method('getNormalizedIniPostMaxSize') ->will($this->returnValue($iniMax)); - $context = $this->getMockExecutionContext(); $options = array('post_max_size_message' => 'Max {{ max }}!'); $form = $this->getBuilder('name', null, $options)->getForm(); + $this->validator->validate($form, new Form()); + + $violations = array(); + for ($i = 0; $i < $nbViolation; ++$i) { - if (0 === $i && count($params) > 0) { - $context->expects($this->at($i)) - ->method('addViolation') - ->with($options['post_max_size_message'], $params); - } else { - $context->expects($this->at($i)) - ->method('addViolation'); - } + $violations[] = $this->createViolation($options['post_max_size_message'], $params, 'property.path', $contentLength); } - $context->expects($this->never()) - ->method('addViolationAt'); - - $this->validator->initialize($context); - $this->validator->validate($form, new Form()); + $this->assertViolations($violations); } public function getPostMaxSizeFixtures() @@ -672,7 +591,6 @@ public function testNoViolationIfNotRoot() $this->serverParams->expects($this->never()) ->method('getNormalizedIniPostMaxSize'); - $context = $this->getMockExecutionContext(); $parent = $this->getBuilder() ->setCompound(true) ->setDataMapper($this->getDataMapper()) @@ -680,13 +598,11 @@ public function testNoViolationIfNotRoot() $form = $this->getForm(); $parent->add($form); - $context->expects($this->never()) - ->method('addViolation'); - $context->expects($this->never()) - ->method('addViolationAt'); + $this->expectNoValidate(); - $this->validator->initialize($context); $this->validator->validate($form, new Form()); + + $this->assertNoViolation(); } /** diff --git a/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.php b/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.php new file mode 100644 index 000000000000..8b3eb53a2c15 --- /dev/null +++ b/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.php @@ -0,0 +1,168 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Security\Core\Tests\Validator\Constraints; + +use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface; +use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface; +use Symfony\Component\Security\Core\SecurityContextInterface; +use Symfony\Component\Security\Core\Validator\Constraints\UserPassword; +use Symfony\Component\Security\Core\Validator\Constraints\UserPasswordValidator; +use Symfony\Component\Validator\Tests\Constraints\AbstractConstraintValidatorTest; + +/** + * @author Bernhard Schussek + */ +class UserPasswordValidatorTest extends AbstractConstraintValidatorTest +{ + const PASSWORD = 's3Cr3t'; + + const SALT = '^S4lt$'; + + /** + * @var SecurityContextInterface + */ + protected $securityContext; + + /** + * @var PasswordEncoderInterface + */ + protected $encoder; + + /** + * @var EncoderFactoryInterface + */ + protected $encoderFactory; + + protected function createValidator() + { + return new UserPasswordValidator($this->securityContext, $this->encoderFactory); + } + + protected function setUp() + { + $user = $this->createUser(); + $this->securityContext = $this->createSecurityContext($user); + $this->encoder = $this->createPasswordEncoder(); + $this->encoderFactory = $this->createEncoderFactory($this->encoder); + + parent::setUp(); + } + + public function testPasswordIsValid() + { + $constraint = new UserPassword(array( + 'message' => 'myMessage', + )); + + $this->encoder->expects($this->once()) + ->method('isPasswordValid') + ->with(static::PASSWORD, 'secret', static::SALT) + ->will($this->returnValue(true)); + + $this->validator->validate('secret', $constraint); + + $this->assertNoViolation(); + } + + public function testPasswordIsNotValid() + { + $constraint = new UserPassword(array( + 'message' => 'myMessage', + )); + + $this->encoder->expects($this->once()) + ->method('isPasswordValid') + ->with(static::PASSWORD, 'secret', static::SALT) + ->will($this->returnValue(false)); + + $this->validator->validate('secret', $constraint); + + $this->assertViolation('myMessage'); + } + + /** + * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException + */ + public function testUserIsNotValid() + { + $user = $this->getMock('Foo\Bar\User'); + + $this->securityContext = $this->createSecurityContext($user); + $this->validator = $this->createValidator(); + $this->validator->initialize($this->context); + + $this->validator->validate('secret', new UserPassword()); + } + + protected function createUser() + { + $mock = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); + + $mock + ->expects($this->any()) + ->method('getPassword') + ->will($this->returnValue(static::PASSWORD)) + ; + + $mock + ->expects($this->any()) + ->method('getSalt') + ->will($this->returnValue(static::SALT)) + ; + + return $mock; + } + + protected function createPasswordEncoder($isPasswordValid = true) + { + return $this->getMock('Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface'); + } + + protected function createEncoderFactory($encoder = null) + { + $mock = $this->getMock('Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface'); + + $mock + ->expects($this->any()) + ->method('getEncoder') + ->will($this->returnValue($encoder)) + ; + + return $mock; + } + + protected function createSecurityContext($user = null) + { + $token = $this->createAuthenticationToken($user); + + $mock = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface'); + $mock + ->expects($this->any()) + ->method('getToken') + ->will($this->returnValue($token)) + ; + + return $mock; + } + + protected function createAuthenticationToken($user = null) + { + $mock = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'); + $mock + ->expects($this->any()) + ->method('getUser') + ->will($this->returnValue($user)) + ; + + return $mock; + } +} diff --git a/src/Symfony/Component/Validator/Constraints/AllValidator.php b/src/Symfony/Component/Validator/Constraints/AllValidator.php index 2ffb8bf16fb9..469d2a42148a 100644 --- a/src/Symfony/Component/Validator/Constraints/AllValidator.php +++ b/src/Symfony/Component/Validator/Constraints/AllValidator.php @@ -38,9 +38,7 @@ public function validate($value, Constraint $constraint) $group = $this->context->getGroup(); foreach ($value as $key => $element) { - foreach ($constraint->constraints as $constr) { - $this->context->validateValue($element, $constr, '['.$key.']', $group); - } + $this->context->validateValue($element, $constraint->constraints, '['.$key.']', $group); } } } diff --git a/src/Symfony/Component/Validator/Constraints/ChoiceValidator.php b/src/Symfony/Component/Validator/Constraints/ChoiceValidator.php index 2e0658cfa6da..79081fee49ce 100644 --- a/src/Symfony/Component/Validator/Constraints/ChoiceValidator.php +++ b/src/Symfony/Component/Validator/Constraints/ChoiceValidator.php @@ -70,7 +70,7 @@ public function validate($value, Constraint $constraint) if ($constraint->min !== null && $count < $constraint->min) { $this->context->addViolation($constraint->minMessage, array( '{{ limit }}' => $constraint->min - ), null, (int) $constraint->min); + ), $value, (int) $constraint->min); return; } @@ -78,7 +78,7 @@ public function validate($value, Constraint $constraint) if ($constraint->max !== null && $count > $constraint->max) { $this->context->addViolation($constraint->maxMessage, array( '{{ limit }}' => $constraint->max - ), null, (int) $constraint->max); + ), $value, (int) $constraint->max); return; } diff --git a/src/Symfony/Component/Validator/Constraints/CollectionValidator.php b/src/Symfony/Component/Validator/Constraints/CollectionValidator.php index a322ef49adc4..33f839d3b949 100644 --- a/src/Symfony/Component/Validator/Constraints/CollectionValidator.php +++ b/src/Symfony/Component/Validator/Constraints/CollectionValidator.php @@ -43,9 +43,7 @@ public function validate($value, Constraint $constraint) (is_array($value) && array_key_exists($field, $value)) || ($value instanceof \ArrayAccess && $value->offsetExists($field)) ) { - foreach ($fieldConstraint->constraints as $constr) { - $this->context->validateValue($value[$field], $constr, '['.$field.']', $group); - } + $this->context->validateValue($value[$field], $fieldConstraint->constraints, '['.$field.']', $group); } elseif (!$fieldConstraint instanceof Optional && !$constraint->allowMissingFields) { $this->context->addViolationAt('['.$field.']', $constraint->missingFieldsMessage, array( '{{ field }}' => $this->formatValue($field) diff --git a/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php b/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php index a1c573baa4e1..a56f734554fd 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php @@ -13,7 +13,6 @@ use Symfony\Component\Intl\Util\IntlTestHelper; use Symfony\Component\Validator\Constraint; -use Symfony\Component\Validator\Constraints\AbstractComparisonValidator; class ComparisonTest_Class { @@ -33,32 +32,15 @@ public function __toString() /** * @author Daniel Holmes */ -abstract class AbstractComparisonValidatorTestCase extends \PHPUnit_Framework_TestCase +abstract class AbstractComparisonValidatorTestCase extends AbstractConstraintValidatorTest { - private $validator; - private $context; - - protected function setUp() - { - $this->validator = $this->createValidator(); - $this->context = $this->getMockBuilder('Symfony\Component\Validator\ExecutionContext') - ->disableOriginalConstructor() - ->getMock(); - $this->validator->initialize($this->context); - - \Locale::setDefault('en'); - } - /** - * @return AbstractComparisonValidator + * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException */ - abstract protected function createValidator(); - public function testThrowsConstraintExceptionIfNoValueOrProperty() { - $this->setExpectedException('Symfony\Component\Validator\Exception\ConstraintDefinitionException'); - $comparison = $this->createConstraint(array()); + $this->validator->validate('some value', $comparison); } @@ -69,16 +51,11 @@ public function testThrowsConstraintExceptionIfNoValueOrProperty() */ public function testValidComparisonToValue($dirtyValue, $comparisonValue) { - $this->context->expects($this->never()) - ->method('addViolation'); - $constraint = $this->createConstraint(array('value' => $comparisonValue)); - $this->context->expects($this->any()) - ->method('getPropertyPath') - ->will($this->returnValue('property1')); - $this->validator->validate($dirtyValue, $constraint); + + $this->assertNoViolation(); } /** @@ -105,19 +82,13 @@ public function testInvalidComparisonToValue($dirtyValue, $dirtyValueAsString, $ $constraint = $this->createConstraint(array('value' => $comparedValue)); $constraint->message = 'Constraint Message'; - $this->context->expects($this->any()) - ->method('getPropertyPath') - ->will($this->returnValue('property1')); - - $this->context->expects($this->once()) - ->method('addViolation') - ->with('Constraint Message', array( - '{{ value }}' => $dirtyValueAsString, - '{{ compared_value }}' => $comparedValueString, - '{{ compared_value_type }}' => $comparedValueType - )); - $this->validator->validate($dirtyValue, $constraint); + + $this->assertViolation('Constraint Message', array( + '{{ value }}' => $dirtyValueAsString, + '{{ compared_value }}' => $comparedValueString, + '{{ compared_value_type }}' => $comparedValueType + )); } /** diff --git a/src/Symfony/Component/Validator/Tests/Constraints/AbstractConstraintValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/AbstractConstraintValidatorTest.php new file mode 100644 index 000000000000..bc4e1c214a02 --- /dev/null +++ b/src/Symfony/Component/Validator/Tests/Constraints/AbstractConstraintValidatorTest.php @@ -0,0 +1,194 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Validator\Tests\Constraints; + +use Symfony\Component\Validator\ConstraintValidatorInterface; +use Symfony\Component\Validator\ConstraintViolation; +use Symfony\Component\Validator\Context\ExecutionContext; +use Symfony\Component\Validator\Context\ExecutionContextInterface; +use Symfony\Component\Validator\Mapping\ClassMetadata; +use Symfony\Component\Validator\Mapping\PropertyMetadata; +use Symfony\Component\Validator\Tests\Fixtures\StubGlobalExecutionContext; + +/** + * @since 2.5.3 + * @author Bernhard Schussek + */ +abstract class AbstractConstraintValidatorTest extends \PHPUnit_Framework_TestCase +{ + /** + * @var ExecutionContextInterface + */ + protected $context; + + /** + * @var ConstraintValidatorInterface + */ + protected $validator; + + protected $group; + + protected $metadata; + + protected $object; + + protected $value; + + protected $root; + + protected $propertyPath; + + protected function setUp() + { + $this->group = 'MyGroup'; + $this->metadata = null; + $this->object = null; + $this->value = 'InvalidValue'; + $this->root = 'root'; + $this->propertyPath = 'property.path'; + $this->context = $this->createContext(); + $this->validator = $this->createValidator(); + $this->validator->initialize($this->context); + + \Locale::setDefault('en'); + } + + protected function createContext() + { + $translator = $this->getMock('Symfony\Component\Translation\TranslatorInterface'); + + return $this->getMockBuilder('Symfony\Component\Validator\ExecutionContext') + ->setConstructorArgs(array( + new StubGlobalExecutionContext($this->root), + $translator, + null, + $this->metadata, + $this->value, + $this->group, + $this->propertyPath + )) + ->setMethods(array('validate', 'validateValue')) + ->getMock(); + } + + protected function createViolation($message, array $parameters = array(), $propertyPath = 'property.path', $invalidValue = 'InvalidValue', $plural = null, $code = null) + { + return new ConstraintViolation( + null, + $message, + $parameters, + $this->root, + $propertyPath, + $invalidValue, + $plural, + $code + ); + } + + protected function setGroup($group) + { + $this->group = $group; + $this->context = $this->createContext(); + $this->validator->initialize($this->context); + } + + protected function setObject($object) + { + $this->object = $object; + $this->metadata = is_object($object) + ? new ClassMetadata(get_class($object)) + : null; + $this->context = $this->createContext(); + $this->validator->initialize($this->context); + } + + protected function setProperty($object, $property) + { + $this->object = $object; + $this->metadata = is_object($object) + ? new PropertyMetadata(get_class($object), $property) + : null; + $this->context = $this->createContext(); + $this->validator->initialize($this->context); + } + + protected function setValue($value) + { + $this->value = $value; + $this->context = $this->createContext(); + $this->validator->initialize($this->context); + } + + protected function setRoot($root) + { + $this->root = $root; + $this->context = $this->createContext(); + $this->validator->initialize($this->context); + } + + protected function setPropertyPath($propertyPath) + { + $this->propertyPath = $propertyPath; + $this->context = $this->createContext(); + $this->validator->initialize($this->context); + } + + protected function expectNoValidate() + { + $this->context->expects($this->never()) + ->method('validate'); + $this->context->expects($this->never()) + ->method('validateValue'); + } + + protected function expectValidateAt($i, $propertyPath, $value, $group) + { + $this->context->expects($this->at($i)) + ->method('validate') + ->with($value, $propertyPath, $group); + } + + protected function expectValidateValueAt($i, $propertyPath, $value, $constraints, $group) + { + $this->context->expects($this->at($i)) + ->method('validateValue') + ->with($value, $constraints, $propertyPath, $group); + } + + protected function assertNoViolation() + { + $this->assertCount(0, $this->context->getViolations()); + } + + protected function assertViolation($message, array $parameters = array(), $propertyPath = 'property.path', $invalidValue = 'InvalidValue', $plural = null, $code = null) + { + $violations = $this->context->getViolations(); + + $this->assertCount(1, $violations); + $this->assertEquals($this->createViolation($message, $parameters, $propertyPath, $invalidValue, $plural, $code), $violations[0]); + } + + protected function assertViolations(array $expected) + { + $violations = $this->context->getViolations(); + + $this->assertCount(count($expected), $violations); + + $i = 0; + + foreach ($expected as $violation) { + $this->assertEquals($violation, $violations[$i++]); + } + } + + abstract protected function createValidator(); +} diff --git a/src/Symfony/Component/Validator/Tests/Constraints/AllValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/AllValidatorTest.php index eaa9044e9ef5..d9ffd9814c2b 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/AllValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/AllValidatorTest.php @@ -11,40 +11,23 @@ namespace Symfony\Component\Validator\Tests\Constraints; -use Symfony\Component\Validator\ExecutionContext; -use Symfony\Component\Validator\Constraints\Range; -use Symfony\Component\Validator\Constraints\NotNull; use Symfony\Component\Validator\Constraints\All; use Symfony\Component\Validator\Constraints\AllValidator; +use Symfony\Component\Validator\Constraints\NotNull; +use Symfony\Component\Validator\Constraints\Range; -class AllValidatorTest extends \PHPUnit_Framework_TestCase +class AllValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() - { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new AllValidator(); - $this->validator->initialize($this->context); - - $this->context->expects($this->any()) - ->method('getGroup') - ->will($this->returnValue('MyGroup')); - } - - protected function tearDown() + protected function createValidator() { - $this->validator = null; - $this->context = null; + return new AllValidator(); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new All(new Range(array('min' => 4)))); + + $this->assertNoViolation(); } /** @@ -62,18 +45,15 @@ public function testWalkSingleConstraint($array) { $constraint = new Range(array('min' => 4)); - $i = 1; + $i = 0; foreach ($array as $key => $value) { - $this->context->expects($this->at($i++)) - ->method('validateValue') - ->with($value, $constraint, '['.$key.']', 'MyGroup'); + $this->expectValidateValueAt($i++, '['.$key.']', $value, array($constraint), 'MyGroup'); } - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate($array, new All($constraint)); + + $this->assertNoViolation(); } /** @@ -85,21 +65,16 @@ public function testWalkMultipleConstraints($array) $constraint2 = new NotNull(); $constraints = array($constraint1, $constraint2); - $i = 1; + + $i = 0; foreach ($array as $key => $value) { - $this->context->expects($this->at($i++)) - ->method('validateValue') - ->with($value, $constraint1, '['.$key.']', 'MyGroup'); - $this->context->expects($this->at($i++)) - ->method('validateValue') - ->with($value, $constraint2, '['.$key.']', 'MyGroup'); + $this->expectValidateValueAt($i++, '['.$key.']', $value, array($constraint1, $constraint2), 'MyGroup'); } - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate($array, new All($constraints)); + + $this->assertNoViolation(); } public function getValidArguments() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/BlankValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/BlankValidatorTest.php index fe4a30b6389a..1d83d10b0f2a 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/BlankValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/BlankValidatorTest.php @@ -14,38 +14,25 @@ use Symfony\Component\Validator\Constraints\Blank; use Symfony\Component\Validator\Constraints\BlankValidator; -class BlankValidatorTest extends \PHPUnit_Framework_TestCase +class BlankValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() - { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new BlankValidator(); - $this->validator->initialize($this->context); - } - - protected function tearDown() + protected function createValidator() { - $this->context = null; - $this->validator = null; + return new BlankValidator(); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new Blank()); + + $this->assertNoViolation(); } public function testBlankIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('', new Blank()); + + $this->assertNoViolation(); } /** @@ -57,13 +44,12 @@ public function testInvalidValues($value, $valueAsString) 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => $valueAsString, - )); - $this->validator->validate($value, $constraint); + + $this->assertViolation( + 'myMessage', + array('{{ value }}' => $valueAsString) + ); } public function getInvalidValues() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CallbackValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CallbackValidatorTest.php index 4d248c13c840..038f1a39111b 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CallbackValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CallbackValidatorTest.php @@ -11,15 +11,16 @@ namespace Symfony\Component\Validator\Tests\Constraints; -use Symfony\Component\Validator\ExecutionContext; +use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraints\Callback; use Symfony\Component\Validator\Constraints\CallbackValidator; +use Symfony\Component\Validator\ExecutionContextInterface; class CallbackValidatorTest_Class { - public static function validateStatic($object, ExecutionContext $context) + public static function validateCallback($object, ExecutionContextInterface $context) { - $context->addViolation('Static message', array('{{ value }}' => 'foobar'), 'invalidValue'); + $context->addViolation('Callback message', array('{{ value }}' => 'foobar')); return false; } @@ -27,104 +28,121 @@ public static function validateStatic($object, ExecutionContext $context) class CallbackValidatorTest_Object { - public function validateOne(ExecutionContext $context) + public function validate(ExecutionContextInterface $context) { - $context->addViolation('My message', array('{{ value }}' => 'foobar'), 'invalidValue'); + $context->addViolation('My message', array('{{ value }}' => 'foobar')); return false; } - public function validateTwo(ExecutionContext $context) + public static function validateStatic(ExecutionContextInterface $context) { - $context->addViolation('Other message', array('{{ value }}' => 'baz'), 'otherInvalidValue'); + $context->addViolation('Static message', array('{{ value }}' => 'baz')); return false; } } -class CallbackValidatorTest extends \PHPUnit_Framework_TestCase +class CallbackValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() + protected function createValidator() { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new CallbackValidator(); - $this->validator->initialize($this->context); + return new CallbackValidator(); } - protected function tearDown() + public function testNullIsValid() { - $this->context = null; - $this->validator = null; + $this->validator->validate(null, new Callback(array('foo'))); + + $this->assertNoViolation(); } - public function testNullIsValid() + public function testSingleMethod() { - $this->context->expects($this->never()) - ->method('addViolation'); + $object = new CallbackValidatorTest_Object(); + $constraint = new Callback(array('validate')); - $this->validator->validate(null, new Callback(array('foo'))); + $this->validator->validate($object, $constraint); + + $this->assertViolation('My message', array( + '{{ value }}' => 'foobar', + )); } - public function testCallbackSingleMethod() + public function testSingleMethodExplicitName() { $object = new CallbackValidatorTest_Object(); - $constraint = new Callback(array('validateOne')); + $constraint = new Callback(array('methods' => array('validate'))); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('My message', array( - '{{ value }}' => 'foobar', - )); + $this->validator->validate($object, $constraint); + + $this->assertViolation('My message', array( + '{{ value }}' => 'foobar', + )); + } + + public function testMultipleMethods() + { + $object = new CallbackValidatorTest_Object(); + $constraint = new Callback(array('validate', 'validateStatic')); $this->validator->validate($object, $constraint); + + $this->assertViolations(array( + $this->createViolation('My message', array( + '{{ value }}' => 'foobar', + )), + $this->createViolation('Static message', array( + '{{ value }}' => 'baz', + )), + )); } - public function testCallbackSingleStaticMethod() + public function testMultipleMethodsExplicitName() { $object = new CallbackValidatorTest_Object(); + $constraint = new Callback(array( + 'methods' => array('validate', 'validateStatic'), + )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('Static message', array( - '{{ value }}' => 'foobar', - )); + $this->validator->validate($object, $constraint); - $this->validator->validate($object, new Callback(array( - array(__CLASS__.'_Class', 'validateStatic') - ))); + $this->assertViolations(array( + $this->createViolation('My message', array( + '{{ value }}' => 'foobar', + )), + $this->createViolation('Static message', array( + '{{ value }}' => 'baz', + )), + )); } - public function testCallbackMultipleMethods() + public function testSingleStaticMethod() { $object = new CallbackValidatorTest_Object(); + $constraint = new Callback(array( + array(__CLASS__.'_Class', 'validateCallback') + )); - $this->context->expects($this->at(0)) - ->method('addViolation') - ->with('My message', array( - '{{ value }}' => 'foobar', - )); - $this->context->expects($this->at(1)) - ->method('addViolation') - ->with('Other message', array( - '{{ value }}' => 'baz', - )); + $this->validator->validate($object, $constraint); - $this->validator->validate($object, new Callback(array( - 'validateOne', 'validateTwo' - ))); + $this->assertViolation('Callback message', array( + '{{ value }}' => 'foobar', + )); } - /** - * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException - */ - public function testExpectCallbackArray() + public function testSingleStaticMethodExplicitName() { $object = new CallbackValidatorTest_Object(); + $constraint = new Callback(array( + 'methods' => array(array(__CLASS__.'_Class', 'validateCallback')), + )); - $this->validator->validate($object, new Callback('foobar')); + $this->validator->validate($object, $constraint); + + $this->assertViolation('Callback message', array( + '{{ value }}' => 'foobar', + )); } /** @@ -151,6 +169,28 @@ public function testConstraintGetTargets() { $constraint = new Callback(array('foo')); - $this->assertEquals('class', $constraint->getTargets()); + $this->assertEquals(Constraint::CLASS_CONSTRAINT, $constraint->getTargets()); + } + + /** + * @expectedException \Symfony\Component\Validator\Exception\MissingOptionsException + */ + public function testNoConstructorArguments() + { + new Callback(); + } + + public function testAnnotationInvocationSingleValued() + { + $constraint = new Callback(array('value' => 'validateStatic')); + + $this->assertEquals(new Callback('validateStatic'), $constraint); + } + + public function testAnnotationInvocationMultiValued() + { + $constraint = new Callback(array('value' => array(__CLASS__.'_Class', 'validateCallback'))); + + $this->assertEquals(new Callback(array(__CLASS__.'_Class', 'validateCallback')), $constraint); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CardSchemeValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CardSchemeValidatorTest.php index ee7cc7a60a38..0b3b04e067cd 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CardSchemeValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CardSchemeValidatorTest.php @@ -14,38 +14,25 @@ use Symfony\Component\Validator\Constraints\CardScheme; use Symfony\Component\Validator\Constraints\CardSchemeValidator; -class CardSchemeValidatorTest extends \PHPUnit_Framework_TestCase +class CardSchemeValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() - { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new CardSchemeValidator(); - $this->validator->initialize($this->context); - } - - protected function tearDown() + protected function createValidator() { - $this->context = null; - $this->validator = null; + return new CardSchemeValidator(); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new CardScheme(array('schemes' => array()))); + + $this->assertNoViolation(); } public function testEmptyStringIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('', new CardScheme(array('schemes' => array()))); + + $this->assertNoViolation(); } /** @@ -53,10 +40,9 @@ public function testEmptyStringIsValid() */ public function testValidNumbers($scheme, $number) { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate($number, new CardScheme(array('schemes' => $scheme))); + + $this->assertNoViolation(); } /** @@ -64,10 +50,16 @@ public function testValidNumbers($scheme, $number) */ public function testInvalidNumbers($scheme, $number) { - $this->context->expects($this->once()) - ->method('addViolation'); + $constraint = new CardScheme(array( + 'schemes' => $scheme, + 'message' => 'myMessage', + )); - $this->validator->validate($number, new CardScheme(array('schemes' => $scheme))); + $this->validator->validate($number, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => is_string($number) ? '"'.$number.'"' : $number, + )); } public function getValidNumbers() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php index ad524b87ea2b..113a31e3cfc0 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php @@ -19,31 +19,16 @@ function choice_callback() return array('foo', 'bar'); } -class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase +class ChoiceValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - public static function staticCallback() - { - return array('foo', 'bar'); - } - - protected function setUp() + protected function createValidator() { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new ChoiceValidator(); - $this->validator->initialize($this->context); - - $this->context->expects($this->any()) - ->method('getClassName') - ->will($this->returnValue(__CLASS__)); + return new ChoiceValidator(); } - protected function tearDown() + public static function staticCallback() { - $this->context = null; - $this->validator = null; + return array('foo', 'bar'); } /** @@ -61,10 +46,9 @@ public function testExpectArrayIfMultipleIsTrue() public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new Choice(array('choices' => array('foo', 'bar')))); + + $this->assertNoViolation(); } /** @@ -87,20 +71,18 @@ public function testValidChoiceArray() { $constraint = new Choice(array('choices' => array('foo', 'bar'))); - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('bar', $constraint); + + $this->assertNoViolation(); } public function testValidChoiceCallbackFunction() { $constraint = new Choice(array('callback' => __NAMESPACE__.'\choice_callback')); - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('bar', $constraint); + + $this->assertNoViolation(); } public function testValidChoiceCallbackClosure() @@ -109,30 +91,30 @@ public function testValidChoiceCallbackClosure() return array('foo', 'bar'); })); - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('bar', $constraint); + + $this->assertNoViolation(); } public function testValidChoiceCallbackStaticMethod() { $constraint = new Choice(array('callback' => array(__CLASS__, 'staticCallback'))); - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('bar', $constraint); + + $this->assertNoViolation(); } public function testValidChoiceCallbackContextMethod() { - $constraint = new Choice(array('callback' => 'staticCallback')); + // search $this for "staticCallback" + $this->setObject($this); - $this->context->expects($this->never()) - ->method('addViolation'); + $constraint = new Choice(array('callback' => 'staticCallback')); $this->validator->validate('bar', $constraint); + + $this->assertNoViolation(); } public function testMultipleChoices() @@ -142,10 +124,9 @@ public function testMultipleChoices() 'multiple' => true, )); - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(array('baz', 'bar'), $constraint); + + $this->assertNoViolation(); } public function testInvalidChoice() @@ -155,13 +136,11 @@ public function testInvalidChoice() 'message' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"baz"', - ), null, null); - $this->validator->validate('baz', $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"baz"', + )); } public function testInvalidChoiceMultiple() @@ -172,13 +151,11 @@ public function testInvalidChoiceMultiple() 'multiple' => true, )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"baz"', - )); - $this->validator->validate(array('foo', 'baz'), $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"baz"', + )); } public function testTooFewChoices() @@ -190,13 +167,15 @@ public function testTooFewChoices() 'minMessage' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ limit }}' => 2, - ), null, 2); + $value = array('foo'); + + $this->setValue($value); + + $this->validator->validate($value, $constraint); - $this->validator->validate(array('foo'), $constraint); + $this->assertViolation('myMessage', array( + '{{ limit }}' => 2, + ), 'property.path', $value, 2); } public function testTooManyChoices() @@ -208,13 +187,15 @@ public function testTooManyChoices() 'maxMessage' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ limit }}' => 2, - ), null, 2); + $value = array('foo', 'bar', 'moo'); - $this->validator->validate(array('foo', 'bar', 'moo'), $constraint); + $this->setValue($value); + + $this->validator->validate($value, $constraint); + + $this->assertViolation('myMessage', array( + '{{ limit }}' => 2, + ), 'property.path', $value, 2); } public function testNonStrict() @@ -224,11 +205,10 @@ public function testNonStrict() 'strict' => false, )); - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('2', $constraint); $this->validator->validate(2, $constraint); + + $this->assertNoViolation(); } public function testStrictAllowsExactValue() @@ -238,10 +218,9 @@ public function testStrictAllowsExactValue() 'strict' => true, )); - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(2, $constraint); + + $this->assertNoViolation(); } public function testStrictDisallowsDifferentType() @@ -252,13 +231,11 @@ public function testStrictDisallowsDifferentType() 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"2"', - )); - $this->validator->validate('2', $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"2"', + )); } public function testNonStrictWithMultipleChoices() @@ -269,10 +246,9 @@ public function testNonStrictWithMultipleChoices() 'strict' => false )); - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(array('2', 3), $constraint); + + $this->assertNoViolation(); } public function testStrictWithMultipleChoices() @@ -284,12 +260,10 @@ public function testStrictWithMultipleChoices() 'multipleMessage' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"3"', - )); - $this->validator->validate(array(2, '3'), $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"3"', + )); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CollectionTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CollectionTest.php index da868d3cfdd1..4b485a9b108b 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CollectionTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CollectionTest.php @@ -12,9 +12,9 @@ namespace Symfony\Component\Validator\Tests\Constraints; use Symfony\Component\Validator\Constraints\Collection; -use Symfony\Component\Validator\Constraints\Required; -use Symfony\Component\Validator\Constraints\Optional; use Symfony\Component\Validator\Constraints\Email; +use Symfony\Component\Validator\Constraints\Optional; +use Symfony\Component\Validator\Constraints\Required; use Symfony\Component\Validator\Constraints\Valid; /** diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorCustomArrayObjectTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorCustomArrayObjectTest.php index ebad849b8b3c..3d4c29681bf4 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorCustomArrayObjectTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorCustomArrayObjectTest.php @@ -11,63 +11,7 @@ namespace Symfony\Component\Validator\Tests\Constraints; -/** - * This class is a hand written simplified version of PHP native `ArrayObject` - * class, to show that it behaves differently than the PHP native implementation. - */ -class CustomArrayObject implements \ArrayAccess, \IteratorAggregate, \Countable, \Serializable -{ - private $array; - - public function __construct(array $array = null) - { - $this->array = $array ?: array(); - } - - public function offsetExists($offset) - { - return array_key_exists($offset, $this->array); - } - - public function offsetGet($offset) - { - return $this->array[$offset]; - } - - public function offsetSet($offset, $value) - { - if (null === $offset) { - $this->array[] = $value; - } else { - $this->array[$offset] = $value; - } - } - - public function offsetUnset($offset) - { - unset($this->array[$offset]); - } - - public function getIterator() - { - return new \ArrayIterator($this->array); - } - - public function count() - { - return count($this->array); - } - - public function serialize() - { - return serialize($this->array); - } - - public function unserialize($serialized) - { - $this->array = (array) unserialize((string) $serialized); - } -} +use Symfony\Component\Validator\Tests\Fixtures\CustomArrayObject; class CollectionValidatorCustomArrayObjectTest extends CollectionValidatorTest { diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorTest.php index e966aadae787..8c26957e6f41 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorTest.php @@ -11,57 +11,44 @@ namespace Symfony\Component\Validator\Tests\Constraints; -use Symfony\Component\Validator\Constraints\Range; -use Symfony\Component\Validator\Constraints\NotNull; -use Symfony\Component\Validator\Constraints\Required; -use Symfony\Component\Validator\Constraints\Optional; use Symfony\Component\Validator\Constraints\Collection; use Symfony\Component\Validator\Constraints\CollectionValidator; +use Symfony\Component\Validator\Constraints\NotNull; +use Symfony\Component\Validator\Constraints\Optional; +use Symfony\Component\Validator\Constraints\Range; +use Symfony\Component\Validator\Constraints\Required; -abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase +abstract class CollectionValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() + protected function createValidator() { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new CollectionValidator(); - $this->validator->initialize($this->context); - - $this->context->expects($this->any()) - ->method('getGroup') - ->will($this->returnValue('MyGroup')); - } - - protected function tearDown() - { - $this->context = null; - $this->validator = null; + return new CollectionValidator(); } abstract protected function prepareTestData(array $contents); public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolationAt'); - $this->validator->validate(null, new Collection(array('fields' => array( 'foo' => new Range(array('min' => 4)), )))); + + $this->assertNoViolation(); } public function testFieldsAsDefaultOption() { + $constraint = new Range(array('min' => 4)); + $data = $this->prepareTestData(array('foo' => 'foobar')); - $this->context->expects($this->never()) - ->method('addViolationAt'); + $this->expectValidateValueAt(0, '[foo]', $data['foo'], array($constraint), 'MyGroup'); $this->validator->validate($data, new Collection(array( - 'foo' => new Range(array('min' => 4)), + 'foo' => $constraint, ))); + + $this->assertNoViolation(); } /** @@ -82,25 +69,23 @@ public function testWalkSingleConstraint() 'foo' => 3, 'bar' => 5, ); - $i = 1; + + $i = 0; foreach ($array as $key => $value) { - $this->context->expects($this->at($i++)) - ->method('validateValue') - ->with($value, $constraint, '['.$key.']', 'MyGroup'); + $this->expectValidateValueAt($i++, '['.$key.']', $value, array($constraint), 'MyGroup'); } $data = $this->prepareTestData($array); - $this->context->expects($this->never()) - ->method('addViolationAt'); - $this->validator->validate($data, new Collection(array( 'fields' => array( 'foo' => $constraint, 'bar' => $constraint, ), ))); + + $this->assertNoViolation(); } public function testWalkMultipleConstraints() @@ -114,48 +99,46 @@ public function testWalkMultipleConstraints() 'foo' => 3, 'bar' => 5, ); - $i = 1; + + $i = 0; foreach ($array as $key => $value) { - foreach ($constraints as $constraint) { - $this->context->expects($this->at($i++)) - ->method('validateValue') - ->with($value, $constraint, '['.$key.']', 'MyGroup'); - } + $this->expectValidateValueAt($i++, '['.$key.']', $value, $constraints, 'MyGroup'); } $data = $this->prepareTestData($array); - $this->context->expects($this->never()) - ->method('addViolationAt'); - $this->validator->validate($data, new Collection(array( 'fields' => array( 'foo' => $constraints, 'bar' => $constraints, ) ))); + + $this->assertNoViolation(); } public function testExtraFieldsDisallowed() { + $constraint = new Range(array('min' => 4)); + $data = $this->prepareTestData(array( 'foo' => 5, 'baz' => 6, )); - $this->context->expects($this->once()) - ->method('addViolationAt') - ->with('[baz]', 'myMessage', array( - '{{ field }}' => '"baz"' - )); + $this->expectValidateValueAt(0, '[foo]', $data['foo'], array($constraint), 'MyGroup'); $this->validator->validate($data, new Collection(array( 'fields' => array( - 'foo' => new Range(array('min' => 4)), + 'foo' => $constraint, ), 'extraFieldsMessage' => 'myMessage', ))); + + $this->assertViolation('myMessage', array( + '{{ field }}' => '"baz"' + ), 'property.path[baz]', 6); } // bug fix @@ -165,16 +148,17 @@ public function testNullNotConsideredExtraField() 'foo' => null, )); - $constraint = new Collection(array( + $constraint = new Range(array('min' => 4)); + + $this->expectValidateValueAt(0, '[foo]', $data['foo'], array($constraint), 'MyGroup'); + + $this->validator->validate($data, new Collection(array( 'fields' => array( - 'foo' => new Range(array('min' => 4)), + 'foo' => $constraint, ), - )); - - $this->context->expects($this->never()) - ->method('addViolationAt'); + ))); - $this->validator->validate($data, $constraint); + $this->assertNoViolation(); } public function testExtraFieldsAllowed() @@ -184,54 +168,52 @@ public function testExtraFieldsAllowed() 'bar' => 6, )); - $constraint = new Collection(array( + $constraint = new Range(array('min' => 4)); + + $this->expectValidateValueAt(0, '[foo]', $data['foo'], array($constraint), 'MyGroup'); + + $this->validator->validate($data, new Collection(array( 'fields' => array( - 'foo' => new Range(array('min' => 4)), + 'foo' => $constraint, ), 'allowExtraFields' => true, - )); - - $this->context->expects($this->never()) - ->method('addViolationAt'); + ))); - $this->validator->validate($data, $constraint); + $this->assertNoViolation(); } public function testMissingFieldsDisallowed() { $data = $this->prepareTestData(array()); - $constraint = new Collection(array( + $constraint = new Range(array('min' => 4)); + + $this->validator->validate($data, new Collection(array( 'fields' => array( - 'foo' => new Range(array('min' => 4)), + 'foo' => $constraint, ), 'missingFieldsMessage' => 'myMessage', - )); - - $this->context->expects($this->once()) - ->method('addViolationAt') - ->with('[foo]', 'myMessage', array( - '{{ field }}' => '"foo"', - )); + ))); - $this->validator->validate($data, $constraint); + $this->assertViolation('myMessage', array( + '{{ field }}' => '"foo"' + ), 'property.path[foo]', null); } public function testMissingFieldsAllowed() { $data = $this->prepareTestData(array()); - $constraint = new Collection(array( + $constraint = new Range(array('min' => 4)); + + $this->validator->validate($data, new Collection(array( 'fields' => array( - 'foo' => new Range(array('min' => 4)), + 'foo' => $constraint, ), 'allowMissingFields' => true, - )); - - $this->context->expects($this->never()) - ->method('addViolationAt'); + ))); - $this->validator->validate($data, $constraint); + $this->assertNoViolation(); } public function testOptionalFieldPresent() @@ -240,24 +222,22 @@ public function testOptionalFieldPresent() 'foo' => null, )); - $this->context->expects($this->never()) - ->method('addViolationAt'); - $this->validator->validate($data, new Collection(array( 'foo' => new Optional(), ))); + + $this->assertNoViolation(); } public function testOptionalFieldNotPresent() { $data = $this->prepareTestData(array()); - $this->context->expects($this->never()) - ->method('addViolationAt'); - $this->validator->validate($data, new Collection(array( 'foo' => new Optional(), ))); + + $this->assertNoViolation(); } public function testOptionalFieldSingleConstraint() @@ -268,18 +248,15 @@ public function testOptionalFieldSingleConstraint() $constraint = new Range(array('min' => 4)); - $this->context->expects($this->once()) - ->method('validateValue') - ->with($array['foo'], $constraint, '[foo]', 'MyGroup'); - - $this->context->expects($this->never()) - ->method('addViolationAt'); + $this->expectValidateValueAt(0, '[foo]', $array['foo'], array($constraint), 'MyGroup'); $data = $this->prepareTestData($array); $this->validator->validate($data, new Collection(array( 'foo' => new Optional($constraint), ))); + + $this->assertNoViolation(); } public function testOptionalFieldMultipleConstraints() @@ -292,22 +269,16 @@ public function testOptionalFieldMultipleConstraints() new NotNull(), new Range(array('min' => 4)), ); - $i = 1; - - foreach ($constraints as $constraint) { - $this->context->expects($this->at($i++)) - ->method('validateValue') - ->with($array['foo'], $constraint, '[foo]', 'MyGroup'); - } - $this->context->expects($this->never()) - ->method('addViolationAt'); + $this->expectValidateValueAt(0, '[foo]', $array['foo'], $constraints, 'MyGroup'); $data = $this->prepareTestData($array); $this->validator->validate($data, new Collection(array( 'foo' => new Optional($constraints), ))); + + $this->assertNoViolation(); } public function testRequiredFieldPresent() @@ -316,30 +287,27 @@ public function testRequiredFieldPresent() 'foo' => null, )); - $this->context->expects($this->never()) - ->method('addViolationAt'); - $this->validator->validate($data, new Collection(array( 'foo' => new Required(), ))); + + $this->assertNoViolation(); } public function testRequiredFieldNotPresent() { $data = $this->prepareTestData(array()); - $this->context->expects($this->once()) - ->method('addViolationAt') - ->with('[foo]', 'myMessage', array( - '{{ field }}' => '"foo"', - )); - $this->validator->validate($data, new Collection(array( 'fields' => array( 'foo' => new Required(), ), 'missingFieldsMessage' => 'myMessage', ))); + + $this->assertViolation('myMessage', array( + '{{ field }}' => '"foo"' + ), 'property.path[foo]', null); } public function testRequiredFieldSingleConstraint() @@ -350,18 +318,15 @@ public function testRequiredFieldSingleConstraint() $constraint = new Range(array('min' => 4)); - $this->context->expects($this->once()) - ->method('validateValue') - ->with($array['foo'], $constraint, '[foo]', 'MyGroup'); - - $this->context->expects($this->never()) - ->method('addViolationAt'); + $this->expectValidateValueAt(0, '[foo]', $array['foo'], array($constraint), 'MyGroup'); $data = $this->prepareTestData($array); $this->validator->validate($data, new Collection(array( 'foo' => new Required($constraint), ))); + + $this->assertNoViolation(); } public function testRequiredFieldMultipleConstraints() @@ -374,22 +339,16 @@ public function testRequiredFieldMultipleConstraints() new NotNull(), new Range(array('min' => 4)), ); - $i = 1; - - foreach ($constraints as $constraint) { - $this->context->expects($this->at($i++)) - ->method('validateValue') - ->with($array['foo'], $constraint, '[foo]', 'MyGroup'); - } - $this->context->expects($this->never()) - ->method('addViolationAt'); + $this->expectValidateValueAt(0, '[foo]', $array['foo'], $constraints, 'MyGroup'); $data = $this->prepareTestData($array); - $this->validator->validate($array, new Collection(array( + $this->validator->validate($data, new Collection(array( 'foo' => new Required($constraints), ))); + + $this->assertNoViolation(); } public function testObjectShouldBeLeftUnchanged() @@ -398,9 +357,13 @@ public function testObjectShouldBeLeftUnchanged() 'foo' => 3 )); + $constraint = new Range(array('min' => 2)); + + $this->expectValidateValueAt(0, '[foo]', $value['foo'], array($constraint), 'MyGroup'); + $this->validator->validate($value, new Collection(array( 'fields' => array( - 'foo' => new Range(array('min' => 2)), + 'foo' => $constraint, ) ))); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorCountableTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorCountableTest.php index ec4d8dec7112..7d46967bde48 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorCountableTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorCountableTest.php @@ -11,20 +11,7 @@ namespace Symfony\Component\Validator\Tests\Constraints; -class CountValidatorCountableTest_Countable implements \Countable -{ - private $content; - - public function __construct(array $content) - { - $this->content = $content; - } - - public function count() - { - return count($this->content); - } -} +use Symfony\Component\Validator\Tests\Fixtures\Countable; /** * @author Bernhard Schussek @@ -33,6 +20,6 @@ class CountValidatorCountableTest extends CountValidatorTest { protected function createCollection(array $content) { - return new CountValidatorCountableTest_Countable($content); + return new Countable($content); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorTest.php index 9c4a38d56c7e..c910c1156ccc 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorTest.php @@ -17,32 +17,20 @@ /** * @author Bernhard Schussek */ -abstract class CountValidatorTest extends \PHPUnit_Framework_TestCase +abstract class CountValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() - { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new CountValidator(); - $this->validator->initialize($this->context); - } - - protected function tearDown() + protected function createValidator() { - $this->context = null; - $this->validator = null; + return new CountValidator(); } abstract protected function createCollection(array $content); public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new Count(6)); + + $this->assertNoViolation(); } /** @@ -93,11 +81,10 @@ public function getFiveOrMoreElements() */ public function testValidValuesMax($value) { - $this->context->expects($this->never()) - ->method('addViolation'); - $constraint = new Count(array('max' => 3)); $this->validator->validate($value, $constraint); + + $this->assertNoViolation(); } /** @@ -105,11 +92,10 @@ public function testValidValuesMax($value) */ public function testValidValuesMin($value) { - $this->context->expects($this->never()) - ->method('addViolation'); - $constraint = new Count(array('min' => 5)); $this->validator->validate($value, $constraint); + + $this->assertNoViolation(); } /** @@ -117,11 +103,10 @@ public function testValidValuesMin($value) */ public function testValidValuesExact($value) { - $this->context->expects($this->never()) - ->method('addViolation'); - $constraint = new Count(4); $this->validator->validate($value, $constraint); + + $this->assertNoViolation(); } /** @@ -134,14 +119,12 @@ public function testInvalidValuesMax($value) 'maxMessage' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', $this->identicalTo(array( - '{{ count }}' => count($value), - '{{ limit }}' => 4, - )), $value, 4); - $this->validator->validate($value, $constraint); + + $this->assertViolation('myMessage', array( + '{{ count }}' => count($value), + '{{ limit }}' => 4, + ), 'property.path', $value, 4); } /** @@ -154,14 +137,12 @@ public function testInvalidValuesMin($value) 'minMessage' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', $this->identicalTo(array( - '{{ count }}' => count($value), - '{{ limit }}' => 4, - )), $value, 4); - $this->validator->validate($value, $constraint); + + $this->assertViolation('myMessage', array( + '{{ count }}' => count($value), + '{{ limit }}' => 4, + ), 'property.path', $value, 4); } /** @@ -175,14 +156,12 @@ public function testInvalidValuesExact($value) 'exactMessage' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', $this->identicalTo(array( + $this->validator->validate($value, $constraint); + + $this->assertViolation('myMessage', array( '{{ count }}' => count($value), '{{ limit }}' => 4, - )), $value, 4); - - $this->validator->validate($value, $constraint); + ), 'property.path', $value, 4); } public function testDefaultOption() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.php index 5fabee67fb39..a080852c2acd 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.php @@ -15,40 +15,32 @@ use Symfony\Component\Validator\Constraints\Country; use Symfony\Component\Validator\Constraints\CountryValidator; -class CountryValidatorTest extends \PHPUnit_Framework_TestCase +class CountryValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - protected function setUp() { - IntlTestHelper::requireIntl($this); + IntlTestHelper::requireFullIntl($this); - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new CountryValidator(); - $this->validator->initialize($this->context); + parent::setUp(); } - protected function tearDown() + protected function createValidator() { - $this->context = null; - $this->validator = null; + return new CountryValidator(); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new Country()); + + $this->assertNoViolation(); } public function testEmptyStringIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('', new Country()); + + $this->assertNoViolation(); } /** @@ -64,10 +56,9 @@ public function testExpectsStringCompatibleType() */ public function testValidCountries($country) { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate($country, new Country()); + + $this->assertNoViolation(); } public function getValidCountries() @@ -88,13 +79,11 @@ public function testInvalidCountries($country) 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => $country, - )); - $this->validator->validate($country, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => $country, + )); } public function getInvalidCountries() @@ -113,9 +102,9 @@ public function testValidateUsingCountrySpecificLocale() \Locale::setDefault('en_GB'); $existingCountry = 'GB'; - $this->context->expects($this->never()) - ->method('addViolation'); $this->validator->validate($existingCountry, new Country()); + + $this->assertNoViolation(); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CurrencyValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CurrencyValidatorTest.php index ea6c2eb43ac0..99636e6ca4f0 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CurrencyValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CurrencyValidatorTest.php @@ -15,40 +15,32 @@ use Symfony\Component\Validator\Constraints\Currency; use Symfony\Component\Validator\Constraints\CurrencyValidator; -class CurrencyValidatorTest extends \PHPUnit_Framework_TestCase +class CurrencyValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - protected function setUp() { - IntlTestHelper::requireIntl($this); + IntlTestHelper::requireFullIntl($this); - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new CurrencyValidator(); - $this->validator->initialize($this->context); + parent::setUp(); } - protected function tearDown() + protected function createValidator() { - $this->context = null; - $this->validator = null; + return new CurrencyValidator(); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new Currency()); + + $this->assertNoViolation(); } public function testEmptyStringIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('', new Currency()); + + $this->assertNoViolation(); } /** @@ -64,10 +56,9 @@ public function testExpectsStringCompatibleType() */ public function testValidCurrencies($currency) { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate($currency, new Currency()); + + $this->assertNoViolation(); } /** @@ -76,10 +67,10 @@ public function testValidCurrencies($currency) public function testValidCurrenciesWithCountrySpecificLocale($currency) { \Locale::setDefault('en_GB'); - $this->context->expects($this->never()) - ->method('addViolation'); $this->validator->validate($currency, new Currency()); + + $this->assertNoViolation(); } public function getValidCurrencies() @@ -102,13 +93,11 @@ public function testInvalidCurrencies($currency) 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => $currency, - )); - $this->validator->validate($currency, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => $currency, + )); } public function getInvalidCurrencies() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.php index 46079a815502..5addbf34de87 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.php @@ -14,46 +14,32 @@ use Symfony\Component\Validator\Constraints\DateTime; use Symfony\Component\Validator\Constraints\DateTimeValidator; -class DateTimeValidatorTest extends \PHPUnit_Framework_TestCase +class DateTimeValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() - { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new DateTimeValidator(); - $this->validator->initialize($this->context); - } - - protected function tearDown() + protected function createValidator() { - $this->context = null; - $this->validator = null; + return new DateTimeValidator(); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new DateTime()); + + $this->assertNoViolation(); } public function testEmptyStringIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('', new DateTime()); + + $this->assertNoViolation(); } public function testDateTimeClassIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(new \DateTime(), new DateTime()); + + $this->assertNoViolation(); } /** @@ -69,10 +55,9 @@ public function testExpectsStringCompatibleType() */ public function testValidDateTimes($dateTime) { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate($dateTime, new DateTime()); + + $this->assertNoViolation(); } public function getValidDateTimes() @@ -93,13 +78,11 @@ public function testInvalidDateTimes($dateTime) 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"'.$dateTime.'"', - )); - $this->validator->validate($dateTime, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$dateTime.'"', + )); } public function getInvalidDateTimes() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/DateValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/DateValidatorTest.php index a62426ec8a58..8fdacee94d49 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/DateValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/DateValidatorTest.php @@ -14,46 +14,32 @@ use Symfony\Component\Validator\Constraints\Date; use Symfony\Component\Validator\Constraints\DateValidator; -class DateValidatorTest extends \PHPUnit_Framework_TestCase +class DateValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() - { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new DateValidator(); - $this->validator->initialize($this->context); - } - - protected function tearDown() + protected function createValidator() { - $this->context = null; - $this->validator = null; + return new DateValidator(); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new Date()); + + $this->assertNoViolation(); } public function testEmptyStringIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('', new Date()); + + $this->assertNoViolation(); } public function testDateTimeClassIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(new \DateTime(), new Date()); + + $this->assertNoViolation(); } /** @@ -69,10 +55,9 @@ public function testExpectsStringCompatibleType() */ public function testValidDates($date) { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate($date, new Date()); + + $this->assertNoViolation(); } public function getValidDates() @@ -93,13 +78,11 @@ public function testInvalidDates($date) 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"'.$date.'"', - )); - $this->validator->validate($date, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$date.'"', + )); } public function getInvalidDates() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php index 4b7a8bd6c39b..e4722e159e5b 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php @@ -14,38 +14,25 @@ use Symfony\Component\Validator\Constraints\Email; use Symfony\Component\Validator\Constraints\EmailValidator; -class EmailValidatorTest extends \PHPUnit_Framework_TestCase +class EmailValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() - { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new EmailValidator(); - $this->validator->initialize($this->context); - } - - protected function tearDown() + protected function createValidator() { - $this->context = null; - $this->validator = null; + return new EmailValidator(false); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new Email()); + + $this->assertNoViolation(); } public function testEmptyStringIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('', new Email()); + + $this->assertNoViolation(); } /** @@ -61,10 +48,9 @@ public function testExpectsStringCompatibleType() */ public function testValidEmails($email) { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate($email, new Email()); + + $this->assertNoViolation(); } public function getValidEmails() @@ -85,13 +71,11 @@ public function testInvalidEmails($email) 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"'.$email.'"', - )); - $this->validator->validate($email, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$email.'"', + )); } public function getInvalidEmails() @@ -100,7 +84,6 @@ public function getInvalidEmails() array('example'), array('example@'), array('example@localhost'), - array('example@example.com@example.com'), ); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/FalseValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/FalseValidatorTest.php index 22ab63a9e2de..e9abbb9a386c 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/FalseValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/FalseValidatorTest.php @@ -14,38 +14,25 @@ use Symfony\Component\Validator\Constraints\False; use Symfony\Component\Validator\Constraints\FalseValidator; -class FalseValidatorTest extends \PHPUnit_Framework_TestCase +class FalseValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() - { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new FalseValidator(); - $this->validator->initialize($this->context); - } - - protected function tearDown() + protected function createValidator() { - $this->context = null; - $this->validator = null; + return new FalseValidator(); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new False()); + + $this->assertNoViolation(); } public function testFalseIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(false, new False()); + + $this->assertNoViolation(); } public function testTrueIsInvalid() @@ -54,10 +41,10 @@ public function testTrueIsInvalid() 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array('{{ value }}' => 'true')); - $this->validator->validate(true, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => 'true' + )); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorPathTest.php b/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorPathTest.php index 7701d7faf42e..f1f8db692a60 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorPathTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorPathTest.php @@ -26,12 +26,10 @@ public function testFileNotFound() 'notFoundMessage' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ file }}' => '"foobar"', - )); - $this->validator->validate('foobar', $constraint); + + $this->assertViolation('myMessage', array( + '{{ file }}' => '"foobar"', + )); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php index 47952f061cab..6c8cb8abbb26 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php @@ -11,54 +11,63 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\Validator\Constraints\File; use Symfony\Component\Validator\Constraints\FileValidator; -use Symfony\Component\HttpFoundation\File\UploadedFile; +use Symfony\Component\Validator\Validation; -abstract class FileValidatorTest extends \PHPUnit_Framework_TestCase +abstract class FileValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; protected $path; + protected $file; + protected function getApiVersion() + { + return Validation::API_VERSION_2_5; + } + + protected function createValidator() + { + return new FileValidator(); + } + protected function setUp() { - if (!class_exists('Symfony\Component\HttpFoundation\File\UploadedFile')) { - $this->markTestSkipped('The "HttpFoundation" component is not available'); - } + parent::setUp(); - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new FileValidator(); - $this->validator->initialize($this->context); $this->path = sys_get_temp_dir().DIRECTORY_SEPARATOR.'FileValidatorTest'; $this->file = fopen($this->path, 'w'); } protected function tearDown() { - fclose($this->file); + parent::tearDown(); + + if (is_resource($this->file)) { + fclose($this->file); + } + + if (file_exists($this->path)) { + unlink($this->path); + } - $this->context = null; - $this->validator = null; $this->path = null; $this->file = null; } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new File()); + + $this->assertNoViolation(); } public function testEmptyStringIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('', new File()); + + $this->assertNoViolation(); } /** @@ -71,82 +80,138 @@ public function testExpectsStringCompatibleTypeOrFile() public function testValidFile() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate($this->path, new File()); + + $this->assertNoViolation(); } public function testValidUploadedfile() { - $this->context->expects($this->never()) - ->method('addViolation'); - $file = new UploadedFile($this->path, 'originalName', null, null, null, true); $this->validator->validate($file, new File()); + + $this->assertNoViolation(); } - public function testTooLargeBytes() + public function provideMaxSizeExceededTests() { - fwrite($this->file, str_repeat('0', 11)); - - $constraint = new File(array( - 'maxSize' => 10, - 'maxSizeMessage' => 'myMessage', - )); - - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ limit }}' => '10', - '{{ size }}' => '11', - '{{ suffix }}' => 'bytes', - '{{ file }}' => '"'.$this->path.'"', - )); - - $this->validator->validate($this->getFile($this->path), $constraint); + // We have various interesting limit - size combinations to test. + // Assume a limit of 1000 bytes (1 kB). Then the following table + // lists the violation messages for different file sizes: + + // -----------+-------------------------------------------------------- + // Size | Violation Message + // -----------+-------------------------------------------------------- + // 1000 bytes | No violation + // 1001 bytes | "Size of 1001 bytes exceeded limit of 1000 bytes" + // 1004 bytes | "Size of 1004 bytes exceeded limit of 1000 bytes" + // | NOT: "Size of 1 kB exceeded limit of 1 kB" + // 1005 bytes | "Size of 1.01 kB exceeded limit of 1 kB" + // -----------+-------------------------------------------------------- + + // As you see, we have two interesting borders: + + // 1000/1001 - The border as of which a violation occurs + // 1004/1005 - The border as of which the message can be rounded to kB + + // Analogous for kB/MB. + + // Prior to Symfony 2.5, violation messages are always displayed in the + // same unit used to specify the limit. + + // As of Symfony 2.5, the above logic is implemented. + return array( + // limit in bytes + array(1001, 1000, '1001', '1000', 'bytes'), + array(1004, 1000, '1004', '1000', 'bytes'), + array(1005, 1000, '1005', '1000', 'bytes'), + + array(1000001, 1000000, '1000001', '1000000', 'bytes'), + array(1004999, 1000000, '1004999', '1000000', 'bytes'), + array(1005000, 1000000, '1005000', '1000000', 'bytes'), + + // limit in kB + //array(1001, '1k') OK in 2.4, not in 2.5 + //array(1004, '1k') OK in 2.4, not in 2.5 + array(1005, '1k', '1.01', '1', 'kB'), + + //array(1000001, '1000k') OK in 2.4, not in 2.5 + array(1004999, '1000k', '1005', '1000', 'kB'), + array(1005000, '1000k', '1005', '1000', 'kB'), + + // limit in MB + //array(1000001, '1M') OK in 2.4, not in 2.5 + //array(1004999, '1M') OK in 2.4, not in 2.5 + array(1005000, '1M', '1.01', '1', 'MB'), + ); } - public function testTooLargeKiloBytes() + /** + * @dataProvider provideMaxSizeExceededTests + */ + public function testMaxSizeExceeded($bytesWritten, $limit, $sizeAsString, $limitAsString, $suffix) { - fwrite($this->file, str_repeat('0', 1400)); + fseek($this->file, $bytesWritten-1, SEEK_SET); + fwrite($this->file, '0'); + fclose($this->file); $constraint = new File(array( - 'maxSize' => '1k', + 'maxSize' => $limit, 'maxSizeMessage' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ limit }}' => '1', - '{{ size }}' => '1.4', - '{{ suffix }}' => 'kB', - '{{ file }}' => '"'.$this->path.'"', - )); - $this->validator->validate($this->getFile($this->path), $constraint); + + $this->assertViolation('myMessage', array( + '{{ limit }}' => $limitAsString, + '{{ size }}' => $sizeAsString, + '{{ suffix }}' => $suffix, + '{{ file }}' => '"'.$this->path.'"', + )); + } + + public function provideMaxSizeNotExceededTests() + { + return array( + // limit in bytes + array(1000, 1000), + array(1000000, 1000000), + + // limit in kB + array(1000, '1k'), + array(1000000, '1000k'), + + // as of Symfony 2.5, the following are not accepted anymore + array(1001, '1k'), + array(1004, '1k'), + array(1000001, '1000k'), + + // limit in MB + array(1000000, '1M'), + + // as of Symfony 2.5, the following are not accepted anymore + array(1000001, '1M'), + array(1004999, '1M'), + ); } - public function testTooLargeMegaBytes() + /** + * @dataProvider provideMaxSizeNotExceededTests + */ + public function testMaxSizeNotExceeded($bytesWritten, $limit) { - fwrite($this->file, str_repeat('0', 1400000)); + fseek($this->file, $bytesWritten-1, SEEK_SET); + fwrite($this->file, '0'); + fclose($this->file); $constraint = new File(array( - 'maxSize' => '1M', + 'maxSize' => $limit, 'maxSizeMessage' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ limit }}' => '1', - '{{ size }}' => '1.4', - '{{ suffix }}' => 'MB', - '{{ file }}' => '"'.$this->path.'"', - )); - $this->validator->validate($this->getFile($this->path), $constraint); + + $this->assertNoViolation(); } /** @@ -179,14 +244,13 @@ public function testValidMimeType() ->will($this->returnValue('image/jpg')) ; - $this->context->expects($this->never()) - ->method('addViolation'); - $constraint = new File(array( 'mimeTypes' => array('image/png', 'image/jpg'), )); $this->validator->validate($file, $constraint); + + $this->assertNoViolation(); } public function testValidWildcardMimeType() @@ -207,14 +271,13 @@ public function testValidWildcardMimeType() ->will($this->returnValue('image/jpg')) ; - $this->context->expects($this->never()) - ->method('addViolation'); - $constraint = new File(array( 'mimeTypes' => array('image/*'), )); $this->validator->validate($file, $constraint); + + $this->assertNoViolation(); } public function testInvalidMimeType() @@ -240,15 +303,13 @@ public function testInvalidMimeType() 'mimeTypesMessage' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ type }}' => '"application/pdf"', - '{{ types }}' => '"image/png", "image/jpg"', - '{{ file }}' => '"'.$this->path.'"', - )); - $this->validator->validate($file, $constraint); + + $this->assertViolation('myMessage', array( + '{{ type }}' => '"application/pdf"', + '{{ types }}' => '"image/png", "image/jpg"', + '{{ file }}' => '"'.$this->path.'"', + )); } public function testInvalidWildcardMimeType() @@ -274,15 +335,13 @@ public function testInvalidWildcardMimeType() 'mimeTypesMessage' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ type }}' => '"application/pdf"', - '{{ types }}' => '"image/*", "image/jpg"', - '{{ file }}' => '"'.$this->path.'"', - )); - $this->validator->validate($file, $constraint); + + $this->assertViolation('myMessage', array( + '{{ type }}' => '"application/pdf"', + '{{ types }}' => '"image/*", "image/jpg"', + '{{ file }}' => '"'.$this->path.'"', + )); } /** @@ -297,12 +356,10 @@ public function testUploadedFileError($error, $message, array $params = array(), 'maxSize' => $maxSize )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', $params); - $this->validator->validate($file, $constraint); + $this->assertViolation('myMessage', $params); + } public function uploadedFileErrorProvider() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/Fixtures/test_landscape.gif b/src/Symfony/Component/Validator/Tests/Constraints/Fixtures/test_landscape.gif new file mode 100644 index 0000000000000000000000000000000000000000..870123532c3b97be8e2ab75452eca7060fb474c4 GIT binary patch literal 43 qcmZ?wbhEHbWMW`sXkcLY4+e@qSs1y10y+#p0Fq%~V)Ef)um%7ZunH6a literal 0 HcmV?d00001 diff --git a/src/Symfony/Component/Validator/Tests/Constraints/Fixtures/test_portrait.gif b/src/Symfony/Component/Validator/Tests/Constraints/Fixtures/test_portrait.gif new file mode 100644 index 0000000000000000000000000000000000000000..cc480ca88ed7fa80ff8e3907ba14d692e3e9d3d4 GIT binary patch literal 43 rcmZ?wbhEHbWMp7sXkcLY4+e@qSs1w(7#VaJfB+=Jz{KRk#b6Bp7pw{t literal 0 HcmV?d00001 diff --git a/src/Symfony/Component/Validator/Tests/Constraints/GroupSequenceTest.php b/src/Symfony/Component/Validator/Tests/Constraints/GroupSequenceTest.php new file mode 100644 index 000000000000..b3e8ec219169 --- /dev/null +++ b/src/Symfony/Component/Validator/Tests/Constraints/GroupSequenceTest.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Validator\Tests\Constraints; + +use Symfony\Component\Validator\Constraints\GroupSequence; + +/** + * @author Bernhard Schussek + */ +class GroupSequenceTest extends \PHPUnit_Framework_TestCase +{ + public function testCreateDoctrineStyle() + { + $sequence = new GroupSequence(array('value' => array('Group 1', 'Group 2'))); + + $this->assertSame(array('Group 1', 'Group 2'), $sequence->groups); + } +} diff --git a/src/Symfony/Component/Validator/Tests/Constraints/IbanValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/IbanValidatorTest.php index 49b39430178d..8cf7f5ae53c5 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/IbanValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/IbanValidatorTest.php @@ -13,31 +13,27 @@ use Symfony\Component\Validator\Constraints\Iban; use Symfony\Component\Validator\Constraints\IbanValidator; +use Symfony\Component\Validator\Validation; -class IbanValidatorTest extends \PHPUnit_Framework_TestCase +class IbanValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() + protected function createValidator() { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new IbanValidator(); - $this->validator->initialize($this->context); + return new IbanValidator(); } public function testNullIsValid() { - $this->context->expects($this->never())->method('addViolation'); - $this->validator->validate(null, new Iban()); + + $this->assertNoViolation(); } public function testEmptyStringIsValid() { - $this->context->expects($this->never())->method('addViolation'); - $this->validator->validate('', new Iban()); + + $this->assertNoViolation(); } /** @@ -45,9 +41,9 @@ public function testEmptyStringIsValid() */ public function testValidIbans($iban) { - $this->context->expects($this->never())->method('addViolation'); - $this->validator->validate($iban, new Iban()); + + $this->assertNoViolation(); } public function getValidIbans() @@ -161,13 +157,11 @@ public function testInvalidIbans($iban) 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"'.$iban.'"', - )); - $this->validator->validate($iban, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$iban.'"', + )); } public function getInvalidIbans() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/ImageValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/ImageValidatorTest.php index 88545016243d..01f1a06199c4 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/ImageValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/ImageValidatorTest.php @@ -13,59 +13,54 @@ use Symfony\Component\Validator\Constraints\Image; use Symfony\Component\Validator\Constraints\ImageValidator; +use Symfony\Component\Validator\Validation; -class ImageValidatorTest extends \PHPUnit_Framework_TestCase +class ImageValidatorTest extends AbstractConstraintValidatorTest { protected $context; protected $validator; protected $path; protected $image; + protected $imageLandscape; + protected $imagePortrait; + + protected function createValidator() + { + return new ImageValidator(); + } protected function setUp() { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new ImageValidator(); - $this->validator->initialize($this->context); + parent::setUp(); + $this->image = __DIR__.'/Fixtures/test.gif'; + $this->imageLandscape = __DIR__.'/Fixtures/test_landscape.gif'; + $this->imagePortrait = __DIR__.'/Fixtures/test_portrait.gif'; } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new Image()); + + $this->assertNoViolation(); } public function testEmptyStringIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('', new Image()); + + $this->assertNoViolation(); } public function testValidImage() { - if (!class_exists('Symfony\Component\HttpFoundation\File\File')) { - $this->markTestSkipped('The "HttpFoundation" component is not available'); - } - - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate($this->image, new Image()); + + $this->assertNoViolation(); } public function testValidSize() { - if (!class_exists('Symfony\Component\HttpFoundation\File\File')) { - $this->markTestSkipped('The "HttpFoundation" component is not available'); - } - - $this->context->expects($this->never()) - ->method('addViolation'); - $constraint = new Image(array( 'minWidth' => 1, 'maxWidth' => 2, @@ -74,90 +69,68 @@ public function testValidSize() )); $this->validator->validate($this->image, $constraint); + + $this->assertNoViolation(); } public function testWidthTooSmall() { - if (!class_exists('Symfony\Component\HttpFoundation\File\File')) { - $this->markTestSkipped('The "HttpFoundation" component is not available'); - } - $constraint = new Image(array( 'minWidth' => 3, 'minWidthMessage' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ width }}' => '2', - '{{ min_width }}' => '3', - )); - $this->validator->validate($this->image, $constraint); + + $this->assertViolation('myMessage', array( + '{{ width }}' => '2', + '{{ min_width }}' => '3', + )); } public function testWidthTooBig() { - if (!class_exists('Symfony\Component\HttpFoundation\File\File')) { - $this->markTestSkipped('The "HttpFoundation" component is not available'); - } - $constraint = new Image(array( 'maxWidth' => 1, 'maxWidthMessage' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ width }}' => '2', - '{{ max_width }}' => '1', - )); - $this->validator->validate($this->image, $constraint); + + $this->assertViolation('myMessage', array( + '{{ width }}' => '2', + '{{ max_width }}' => '1', + )); } public function testHeightTooSmall() { - if (!class_exists('Symfony\Component\HttpFoundation\File\File')) { - $this->markTestSkipped('The "HttpFoundation" component is not available'); - } - $constraint = new Image(array( 'minHeight' => 3, 'minHeightMessage' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ height }}' => '2', - '{{ min_height }}' => '3', - )); - $this->validator->validate($this->image, $constraint); + + $this->assertViolation('myMessage', array( + '{{ height }}' => '2', + '{{ min_height }}' => '3', + )); } public function testHeightTooBig() { - if (!class_exists('Symfony\Component\HttpFoundation\File\File')) { - $this->markTestSkipped('The "HttpFoundation" component is not available'); - } - $constraint = new Image(array( 'maxHeight' => 1, 'maxHeightMessage' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ height }}' => '2', - '{{ max_height }}' => '1', - )); - $this->validator->validate($this->image, $constraint); + + $this->assertViolation('myMessage', array( + '{{ height }}' => '2', + '{{ max_height }}' => '1', + )); } /** @@ -165,10 +138,6 @@ public function testHeightTooBig() */ public function testInvalidMinWidth() { - if (!class_exists('Symfony\Component\HttpFoundation\File\File')) { - $this->markTestSkipped('The "HttpFoundation" component is not available'); - } - $constraint = new Image(array( 'minWidth' => '1abc', )); @@ -181,10 +150,6 @@ public function testInvalidMinWidth() */ public function testInvalidMaxWidth() { - if (!class_exists('Symfony\Component\HttpFoundation\File\File')) { - $this->markTestSkipped('The "HttpFoundation" component is not available'); - } - $constraint = new Image(array( 'maxWidth' => '1abc', )); @@ -197,10 +162,6 @@ public function testInvalidMaxWidth() */ public function testInvalidMinHeight() { - if (!class_exists('Symfony\Component\HttpFoundation\File\File')) { - $this->markTestSkipped('The "HttpFoundation" component is not available'); - } - $constraint = new Image(array( 'minHeight' => '1abc', )); @@ -213,10 +174,6 @@ public function testInvalidMinHeight() */ public function testInvalidMaxHeight() { - if (!class_exists('Symfony\Component\HttpFoundation\File\File')) { - $this->markTestSkipped('The "HttpFoundation" component is not available'); - } - $constraint = new Image(array( 'maxHeight' => '1abc', )); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php index 25cd5d44f840..bc849278de59 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php @@ -13,39 +13,27 @@ use Symfony\Component\Validator\Constraints\Ip; use Symfony\Component\Validator\Constraints\IpValidator; +use Symfony\Component\Validator\Validation; -class IpValidatorTest extends \PHPUnit_Framework_TestCase +class IpValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() - { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new IpValidator(); - $this->validator->initialize($this->context); - } - - protected function tearDown() + protected function createValidator() { - $this->context = null; - $this->validator = null; + return new IpValidator(); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new Ip()); + + $this->assertNoViolation(); } public function testEmptyStringIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('', new Ip()); + + $this->assertNoViolation(); } /** @@ -61,7 +49,7 @@ public function testExpectsStringCompatibleType() */ public function testInvalidValidatorVersion() { - $ip = new Ip(array( + new Ip(array( 'version' => 666, )); } @@ -71,12 +59,11 @@ public function testInvalidValidatorVersion() */ public function testValidIpsV4($ip) { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate($ip, new Ip(array( 'version' => Ip::V4, ))); + + $this->assertNoViolation(); } public function getValidIpsV4() @@ -98,12 +85,11 @@ public function getValidIpsV4() */ public function testValidIpsV6($ip) { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate($ip, new Ip(array( 'version' => Ip::V6, ))); + + $this->assertNoViolation(); } public function getValidIpsV6() @@ -136,12 +122,11 @@ public function getValidIpsV6() */ public function testValidIpsAll($ip) { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate($ip, new Ip(array( 'version' => Ip::ALL, ))); + + $this->assertNoViolation(); } public function getValidIpsAll() @@ -159,13 +144,11 @@ public function testInvalidIpsV4($ip) 'message' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"'.$ip.'"', - )); - $this->validator->validate($ip, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$ip.'"', + )); } public function getInvalidIpsV4() @@ -193,13 +176,11 @@ public function testInvalidPrivateIpsV4($ip) 'message' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"'.$ip.'"', - )); - $this->validator->validate($ip, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$ip.'"', + )); } public function getInvalidPrivateIpsV4() @@ -221,13 +202,11 @@ public function testInvalidReservedIpsV4($ip) 'message' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"'.$ip.'"', - )); - $this->validator->validate($ip, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$ip.'"', + )); } public function getInvalidReservedIpsV4() @@ -249,13 +228,11 @@ public function testInvalidPublicIpsV4($ip) 'message' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"'.$ip.'"', - )); - $this->validator->validate($ip, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$ip.'"', + )); } public function getInvalidPublicIpsV4() @@ -273,13 +250,11 @@ public function testInvalidIpsV6($ip) 'message' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"'.$ip.'"', - )); - $this->validator->validate($ip, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$ip.'"', + )); } public function getInvalidIpsV6() @@ -311,13 +286,11 @@ public function testInvalidPrivateIpsV6($ip) 'message' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"'.$ip.'"', - )); - $this->validator->validate($ip, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$ip.'"', + )); } public function getInvalidPrivateIpsV6() @@ -339,13 +312,11 @@ public function testInvalidReservedIpsV6($ip) 'message' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"'.$ip.'"', - )); - $this->validator->validate($ip, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$ip.'"', + )); } public function getInvalidReservedIpsV6() @@ -366,13 +337,11 @@ public function testInvalidPublicIpsV6($ip) 'message' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"'.$ip.'"', - )); - $this->validator->validate($ip, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$ip.'"', + )); } public function getInvalidPublicIpsV6() @@ -390,13 +359,11 @@ public function testInvalidIpsAll($ip) 'message' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"'.$ip.'"', - )); - $this->validator->validate($ip, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$ip.'"', + )); } public function getInvalidIpsAll() @@ -414,13 +381,11 @@ public function testInvalidPrivateIpsAll($ip) 'message' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"'.$ip.'"', - )); - $this->validator->validate($ip, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$ip.'"', + )); } public function getInvalidPrivateIpsAll() @@ -438,13 +403,11 @@ public function testInvalidReservedIpsAll($ip) 'message' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"'.$ip.'"', - )); - $this->validator->validate($ip, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$ip.'"', + )); } public function getInvalidReservedIpsAll() @@ -462,13 +425,11 @@ public function testInvalidPublicIpsAll($ip) 'message' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"'.$ip.'"', - )); - $this->validator->validate($ip, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$ip.'"', + )); } public function getInvalidPublicIpsAll() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/IsbnValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/IsbnValidatorTest.php index 049a9ac3eebc..bb49937dfdbf 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/IsbnValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/IsbnValidatorTest.php @@ -13,20 +13,16 @@ use Symfony\Component\Validator\Constraints\Isbn; use Symfony\Component\Validator\Constraints\IsbnValidator; +use Symfony\Component\Validator\Validation; /** * @see https://en.wikipedia.org/wiki/Isbn */ -class IsbnValidatorTest extends \PHPUnit_Framework_TestCase +class IsbnValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - public function setUp() + protected function createValidator() { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new IsbnValidator(); - $this->validator->initialize($this->context); + return new IsbnValidator(); } public function getValidIsbn10() @@ -44,6 +40,7 @@ public function getValidIsbn10() array('0321812700'), array('0-45122-5244'), array('0-4712-92311'), + array('0-9752298-0-X') ); } @@ -58,6 +55,7 @@ public function getInvalidIsbn10() array('0-4X19-92611'), array('0_45122_5244'), array('2870#971#648'), + //array('0-9752298-0-x'), array('1A34567890'), // chr(1) evaluates to 0 // 2070546810 is valid @@ -122,21 +120,19 @@ public function getInvalidIsbn() public function testNullIsValid() { $constraint = new Isbn(true); - $this->context - ->expects($this->never()) - ->method('addViolation'); $this->validator->validate(null, $constraint); + + $this->assertNoViolation(); } public function testEmptyStringIsValid() { $constraint = new Isbn(true); - $this->context - ->expects($this->never()) - ->method('addViolation'); $this->validator->validate('', $constraint); + + $this->assertNoViolation(); } /** @@ -145,6 +141,7 @@ public function testEmptyStringIsValid() public function testExpectsStringCompatibleType() { $constraint = new Isbn(true); + $this->validator->validate(new \stdClass(), $constraint); } @@ -153,12 +150,13 @@ public function testExpectsStringCompatibleType() */ public function testValidIsbn10($isbn) { - $constraint = new Isbn(array('isbn10' => true)); - $this->context - ->expects($this->never()) - ->method('addViolation'); + $constraint = new Isbn(array( + 'isbn10' => true, + )); $this->validator->validate($isbn, $constraint); + + $this->assertNoViolation(); } /** @@ -166,13 +164,16 @@ public function testValidIsbn10($isbn) */ public function testInvalidIsbn10($isbn) { - $constraint = new Isbn(array('isbn10' => true)); - $this->context - ->expects($this->once()) - ->method('addViolation') - ->with($constraint->isbn10Message); + $constraint = new Isbn(array( + 'isbn10' => true, + 'isbn10Message' => 'myMessage', + )); $this->validator->validate($isbn, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$isbn.'"', + )); } /** @@ -180,12 +181,11 @@ public function testInvalidIsbn10($isbn) */ public function testValidIsbn13($isbn) { - $constraint = new Isbn(array('isbn13' => true)); - $this->context - ->expects($this->never()) - ->method('addViolation'); + $constraint = new Isbn(array('isbn13' => true,)); $this->validator->validate($isbn, $constraint); + + $this->assertNoViolation(); } /** @@ -193,13 +193,16 @@ public function testValidIsbn13($isbn) */ public function testInvalidIsbn13($isbn) { - $constraint = new Isbn(array('isbn13' => true)); - $this->context - ->expects($this->once()) - ->method('addViolation') - ->with($constraint->isbn13Message); + $constraint = new Isbn(array( + 'isbn13' => true, + 'isbn13Message' => 'myMessage', + )); $this->validator->validate($isbn, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$isbn.'"', + )); } /** @@ -207,12 +210,14 @@ public function testInvalidIsbn13($isbn) */ public function testValidIsbn($isbn) { - $constraint = new Isbn(array('isbn10' => true, 'isbn13' => true)); - $this->context - ->expects($this->never()) - ->method('addViolation'); + $constraint = new Isbn(array( + 'isbn10' => true, + 'isbn13' => true, + )); $this->validator->validate($isbn, $constraint); + + $this->assertNoViolation(); } /** @@ -220,12 +225,16 @@ public function testValidIsbn($isbn) */ public function testInvalidIsbn($isbn) { - $constraint = new Isbn(array('isbn10' => true, 'isbn13' => true)); - $this->context - ->expects($this->once()) - ->method('addViolation') - ->with($constraint->bothIsbnMessage); + $constraint = new Isbn(array( + 'isbn10' => true, + 'isbn13' => true, + 'bothIsbnMessage' => 'myMessage', + )); $this->validator->validate($isbn, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$isbn.'"', + )); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/IssnValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/IssnValidatorTest.php index 3f53e738b3bf..b48357a880cd 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/IssnValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/IssnValidatorTest.php @@ -13,20 +13,16 @@ use Symfony\Component\Validator\Constraints\Issn; use Symfony\Component\Validator\Constraints\IssnValidator; +use Symfony\Component\Validator\Validation; /** * @see https://en.wikipedia.org/wiki/Issn */ -class IssnValidatorTest extends \PHPUnit_Framework_TestCase +class IssnValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - public function setUp() + protected function createValidator() { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new IssnValidator(); - $this->validator->initialize($this->context); + return new IssnValidator(); } public function getValidLowerCasedIssn() @@ -110,21 +106,19 @@ public function getInvalidIssn() public function testNullIsValid() { $constraint = new Issn(); - $this->context - ->expects($this->never()) - ->method('addViolation'); $this->validator->validate(null, $constraint); + + $this->assertNoViolation(); } public function testEmptyStringIsValid() { $constraint = new Issn(); - $this->context - ->expects($this->never()) - ->method('addViolation'); $this->validator->validate('', $constraint); + + $this->assertNoViolation(); } /** @@ -141,13 +135,16 @@ public function testExpectsStringCompatibleType() */ public function testCaseSensitiveIssns($issn) { - $constraint = new Issn(array('caseSensitive' => true)); - $this->context - ->expects($this->once()) - ->method('addViolation') - ->with($constraint->message); + $constraint = new Issn(array( + 'caseSensitive' => true, + 'message' => 'myMessage', + )); $this->validator->validate($issn, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$issn.'"', + )); } /** @@ -155,13 +152,16 @@ public function testCaseSensitiveIssns($issn) */ public function testRequireHyphenIssns($issn) { - $constraint = new Issn(array('requireHyphen' => true)); - $this->context - ->expects($this->once()) - ->method('addViolation') - ->with($constraint->message); + $constraint = new Issn(array( + 'requireHyphen' => true, + 'message' => 'myMessage', + )); $this->validator->validate($issn, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$issn.'"', + )); } /** @@ -170,11 +170,10 @@ public function testRequireHyphenIssns($issn) public function testValidIssn($issn) { $constraint = new Issn(); - $this->context - ->expects($this->never()) - ->method('addViolation'); $this->validator->validate($issn, $constraint); + + $this->assertNoViolation(); } /** @@ -182,13 +181,15 @@ public function testValidIssn($issn) */ public function testInvalidFormatIssn($issn) { - $constraint = new Issn(); - $this->context - ->expects($this->once()) - ->method('addViolation') - ->with($constraint->message); + $constraint = new Issn(array( + 'message' => 'myMessage', + )); $this->validator->validate($issn, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$issn.'"', + )); } /** @@ -196,13 +197,15 @@ public function testInvalidFormatIssn($issn) */ public function testInvalidValueIssn($issn) { - $constraint = new Issn(); - $this->context - ->expects($this->once()) - ->method('addViolation') - ->with($constraint->message); + $constraint = new Issn(array( + 'message' => 'myMessage', + )); $this->validator->validate($issn, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$issn.'"', + )); } /** @@ -210,11 +213,14 @@ public function testInvalidValueIssn($issn) */ public function testInvalidIssn($issn) { - $constraint = new Issn(); - $this->context - ->expects($this->once()) - ->method('addViolation'); + $constraint = new Issn(array( + 'message' => 'myMessage', + )); $this->validator->validate($issn, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$issn.'"', + )); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LanguageValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LanguageValidatorTest.php index 3588887d7499..98f7533cb8a5 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LanguageValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LanguageValidatorTest.php @@ -14,41 +14,34 @@ use Symfony\Component\Intl\Util\IntlTestHelper; use Symfony\Component\Validator\Constraints\Language; use Symfony\Component\Validator\Constraints\LanguageValidator; +use Symfony\Component\Validator\Validation; -class LanguageValidatorTest extends \PHPUnit_Framework_TestCase +class LanguageValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() + protected function createValidator() { - IntlTestHelper::requireIntl($this); - - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new LanguageValidator(); - $this->validator->initialize($this->context); + return new LanguageValidator(); } - protected function tearDown() + protected function setUp() { - $this->context = null; - $this->validator = null; + IntlTestHelper::requireFullIntl($this); + + parent::setUp(); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new Language()); + + $this->assertNoViolation(); } public function testEmptyStringIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('', new Language()); + + $this->assertNoViolation(); } /** @@ -64,10 +57,9 @@ public function testExpectsStringCompatibleType() */ public function testValidLanguages($language) { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate($language, new Language()); + + $this->assertNoViolation(); } public function getValidLanguages() @@ -88,13 +80,11 @@ public function testInvalidLanguages($language) 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => $language, - )); - $this->validator->validate($language, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => $language, + )); } public function getInvalidLanguages() @@ -109,11 +99,11 @@ public function testValidateUsingCountrySpecificLocale() { \Locale::setDefault('fr_FR'); $existingLanguage = 'en'; - $this->context->expects($this->never()) - ->method('addViolation'); $this->validator->validate($existingLanguage, new Language(array( 'message' => 'aMessage' ))); + + $this->assertNoViolation(); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.php index 267f05b1b605..31039c08ae04 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.php @@ -13,39 +13,27 @@ use Symfony\Component\Validator\Constraints\Length; use Symfony\Component\Validator\Constraints\LengthValidator; +use Symfony\Component\Validator\Validation; -class LengthValidatorTest extends \PHPUnit_Framework_TestCase +class LengthValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() + protected function createValidator() { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new LengthValidator(); - $this->validator->initialize($this->context); - } - - protected function tearDown() - { - $this->context = null; - $this->validator = null; + return new LengthValidator(); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new Length(6)); + + $this->assertNoViolation(); } public function testEmptyStringIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('', new Length(6)); + + $this->assertNoViolation(); } /** @@ -111,11 +99,10 @@ public function testValidValuesMin($value, $mbOnly = false) $this->markTestSkipped('mb_strlen does not exist'); } - $this->context->expects($this->never()) - ->method('addViolation'); - $constraint = new Length(array('min' => 5)); $this->validator->validate($value, $constraint); + + $this->assertNoViolation(); } /** @@ -127,11 +114,10 @@ public function testValidValuesMax($value, $mbOnly = false) $this->markTestSkipped('mb_strlen does not exist'); } - $this->context->expects($this->never()) - ->method('addViolation'); - $constraint = new Length(array('max' => 3)); $this->validator->validate($value, $constraint); + + $this->assertNoViolation(); } /** @@ -143,11 +129,10 @@ public function testValidValuesExact($value, $mbOnly = false) $this->markTestSkipped('mb_strlen does not exist'); } - $this->context->expects($this->never()) - ->method('addViolation'); - $constraint = new Length(4); $this->validator->validate($value, $constraint); + + $this->assertNoViolation(); } /** @@ -164,14 +149,12 @@ public function testInvalidValuesMin($value, $mbOnly = false) 'minMessage' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', $this->identicalTo(array( - '{{ value }}' => '"'.$value.'"', - '{{ limit }}' => 4, - )), $this->identicalTo($value), 4); - $this->validator->validate($value, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$value.'"', + '{{ limit }}' => 4, + ), 'property.path', $value, 4); } /** @@ -188,14 +171,12 @@ public function testInvalidValuesMax($value, $mbOnly = false) 'maxMessage' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', $this->identicalTo(array( - '{{ value }}' => '"'.$value.'"', - '{{ limit }}' => 4, - )), $this->identicalTo($value), 4); - $this->validator->validate($value, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$value.'"', + '{{ limit }}' => 4, + ), 'property.path', $value, 4); } /** @@ -213,14 +194,12 @@ public function testInvalidValuesExact($value, $mbOnly = false) 'exactMessage' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', $this->identicalTo(array( - '{{ value }}' => '"'.$value.'"', - '{{ limit }}' => 4, - )), $this->identicalTo($value), 4); - $this->validator->validate($value, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$value.'"', + '{{ limit }}' => 4, + ), 'property.path', $value, 4); } public function testConstraintGetDefaultOption() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php index 41feba0c7123..5d40dd20bd3a 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php @@ -14,41 +14,34 @@ use Symfony\Component\Intl\Util\IntlTestHelper; use Symfony\Component\Validator\Constraints\Locale; use Symfony\Component\Validator\Constraints\LocaleValidator; +use Symfony\Component\Validator\Validation; -class LocaleValidatorTest extends \PHPUnit_Framework_TestCase +class LocaleValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; + protected function createValidator() + { + return new LocaleValidator(); + } protected function setUp() { IntlTestHelper::requireIntl($this); - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new LocaleValidator(); - $this->validator->initialize($this->context); - } - - protected function tearDown() - { - $this->context = null; - $this->validator = null; + parent::setUp(); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new Locale()); + + $this->assertNoViolation(); } public function testEmptyStringIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('', new Locale()); + + $this->assertNoViolation(); } /** @@ -64,10 +57,9 @@ public function testExpectsStringCompatibleType() */ public function testValidLocales($locale) { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate($locale, new Locale()); + + $this->assertNoViolation(); } public function getValidLocales() @@ -90,13 +82,11 @@ public function testInvalidLocales($locale) 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => $locale, - )); - $this->validator->validate($locale, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => $locale, + )); } public function getInvalidLocales() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LuhnValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LuhnValidatorTest.php index 11c6a7cad529..9b02bf649223 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LuhnValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LuhnValidatorTest.php @@ -13,39 +13,27 @@ use Symfony\Component\Validator\Constraints\Luhn; use Symfony\Component\Validator\Constraints\LuhnValidator; +use Symfony\Component\Validator\Validation; -class LuhnValidatorTest extends \PHPUnit_Framework_TestCase +class LuhnValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() - { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new LuhnValidator(); - $this->validator->initialize($this->context); - } - - protected function tearDown() + protected function createValidator() { - $this->context = null; - $this->validator = null; + return new LuhnValidator(); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new Luhn()); + + $this->assertNoViolation(); } public function testEmptyStringIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('', new Luhn()); + + $this->assertNoViolation(); } /** @@ -53,10 +41,9 @@ public function testEmptyStringIsValid() */ public function testValidNumbers($number) { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate($number, new Luhn()); + + $this->assertNoViolation(); } public function getValidNumbers() @@ -88,13 +75,15 @@ public function getValidNumbers() */ public function testInvalidNumbers($number) { - $constraint = new Luhn(); - - $this->context->expects($this->once()) - ->method('addViolation') - ->with($constraint->message); + $constraint = new Luhn(array( + 'message' => 'myMessage', + )); $this->validator->validate($number, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$number.'"', + )); } public function getInvalidNumbers() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/NotBlankValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/NotBlankValidatorTest.php index 7273986a8750..fe289514665c 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/NotBlankValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/NotBlankValidatorTest.php @@ -13,23 +13,13 @@ use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Constraints\NotBlankValidator; +use Symfony\Component\Validator\Validation; -class NotBlankValidatorTest extends \PHPUnit_Framework_TestCase +class NotBlankValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() + protected function createValidator() { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new NotBlankValidator(); - $this->validator->initialize($this->context); - } - - protected function tearDown() - { - $this->context = null; - $this->validator = null; + return new NotBlankValidator(); } /** @@ -37,10 +27,9 @@ protected function tearDown() */ public function testValidValues($value) { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate($value, new NotBlank()); + + $this->assertNoViolation(); } public function getValidValues() @@ -60,11 +49,11 @@ public function testNullIsInvalid() 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage'); - $this->validator->validate(null, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => 'null', + )); } public function testBlankIsInvalid() @@ -73,11 +62,11 @@ public function testBlankIsInvalid() 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage'); - $this->validator->validate('', $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '""', + )); } public function testFalseIsInvalid() @@ -86,11 +75,11 @@ public function testFalseIsInvalid() 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage'); - $this->validator->validate(false, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => 'false', + )); } public function testEmptyArrayIsInvalid() @@ -99,10 +88,10 @@ public function testEmptyArrayIsInvalid() 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage'); - $this->validator->validate(array(), $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => 'array', + )); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/NotNullValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/NotNullValidatorTest.php index 96f74a1ba02a..8224423e9bf0 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/NotNullValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/NotNullValidatorTest.php @@ -13,23 +13,13 @@ use Symfony\Component\Validator\Constraints\NotNull; use Symfony\Component\Validator\Constraints\NotNullValidator; +use Symfony\Component\Validator\Validation; -class NotNullValidatorTest extends \PHPUnit_Framework_TestCase +class NotNullValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() - { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new NotNullValidator(); - $this->validator->initialize($this->context); - } - - protected function tearDown() + protected function createValidator() { - $this->context = null; - $this->validator = null; + return new NotNullValidator(); } /** @@ -37,10 +27,9 @@ protected function tearDown() */ public function testValidValues($value) { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate($value, new NotNull()); + + $this->assertNoViolation(); } public function getValidValues() @@ -59,11 +48,8 @@ public function testNullIsInvalid() 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - )); - $this->validator->validate(null, $constraint); + + $this->assertViolation('myMessage'); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/NullValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/NullValidatorTest.php index 4ca50c1087d5..b659bc029a46 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/NullValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/NullValidatorTest.php @@ -13,31 +13,20 @@ use Symfony\Component\Validator\Constraints\Null; use Symfony\Component\Validator\Constraints\NullValidator; +use Symfony\Component\Validator\Validation; -class NullValidatorTest extends \PHPUnit_Framework_TestCase +class NullValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() + protected function createValidator() { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new NullValidator(); - $this->validator->initialize($this->context); - } - - protected function tearDown() - { - $this->context = null; - $this->validator = null; + return new NullValidator(); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new Null()); + + $this->assertNoViolation(); } /** @@ -49,13 +38,11 @@ public function testInvalidValues($value, $valueAsString) 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => $valueAsString, - )); - $this->validator->validate($value, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => $valueAsString, + )); } public function getInvalidValues() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/RangeValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/RangeValidatorTest.php index f7601de797ba..9c043a6d5609 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/RangeValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/RangeValidatorTest.php @@ -13,25 +13,20 @@ use Symfony\Component\Validator\Constraints\Range; use Symfony\Component\Validator\Constraints\RangeValidator; +use Symfony\Component\Validator\Validation; -class RangeValidatorTest extends \PHPUnit_Framework_TestCase +class RangeValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() + protected function createValidator() { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new RangeValidator(); - $this->validator->initialize($this->context); + return new RangeValidator(); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new Range(array('min' => 10, 'max' => 20))); + + $this->assertNoViolation(); } public function getTenToTwenty() @@ -73,11 +68,10 @@ public function getMoreThanTwenty() */ public function testValidValuesMin($value) { - $this->context->expects($this->never()) - ->method('addViolation'); - $constraint = new Range(array('min' => 10)); $this->validator->validate($value, $constraint); + + $this->assertNoViolation(); } /** @@ -85,11 +79,10 @@ public function testValidValuesMin($value) */ public function testValidValuesMax($value) { - $this->context->expects($this->never()) - ->method('addViolation'); - $constraint = new Range(array('max' => 20)); $this->validator->validate($value, $constraint); + + $this->assertNoViolation(); } /** @@ -97,11 +90,10 @@ public function testValidValuesMax($value) */ public function testValidValuesMinMax($value) { - $this->context->expects($this->never()) - ->method('addViolation'); - $constraint = new Range(array('min' => 10, 'max' => 20)); $this->validator->validate($value, $constraint); + + $this->assertNoViolation(); } /** @@ -114,14 +106,12 @@ public function testInvalidValuesMin($value) 'minMessage' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', $this->identicalTo(array( - '{{ value }}' => $value, - '{{ limit }}' => 10, - ))); - $this->validator->validate($value, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => $value, + '{{ limit }}' => 10, + )); } /** @@ -134,14 +124,12 @@ public function testInvalidValuesMax($value) 'maxMessage' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', $this->identicalTo(array( - '{{ value }}' => $value, - '{{ limit }}' => 20, - ))); - $this->validator->validate($value, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => $value, + '{{ limit }}' => 20, + )); } /** @@ -156,14 +144,12 @@ public function testInvalidValuesCombinedMax($value) 'maxMessage' => 'myMaxMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMaxMessage', $this->identicalTo(array( - '{{ value }}' => $value, - '{{ limit }}' => 20, - ))); - $this->validator->validate($value, $constraint); + + $this->assertViolation('myMaxMessage', array( + '{{ value }}' => $value, + '{{ limit }}' => 20, + )); } /** @@ -178,14 +164,12 @@ public function testInvalidValuesCombinedMin($value) 'maxMessage' => 'myMaxMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMinMessage', $this->identicalTo(array( + $this->validator->validate($value, $constraint); + + $this->assertViolation('myMinMessage', array( '{{ value }}' => $value, '{{ limit }}' => 10, - ))); - - $this->validator->validate($value, $constraint); + )); } public function getInvalidValues() @@ -207,14 +191,12 @@ public function testMinMessageIsSet() 'minMessage' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => 9, - '{{ limit }}' => 10, - )); - $this->validator->validate(9, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => 9, + '{{ limit }}' => 10, + )); } public function testMaxMessageIsSet() @@ -225,28 +207,24 @@ public function testMaxMessageIsSet() 'maxMessage' => 'myMessage', )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => 21, - '{{ limit }}' => 20, - )); - $this->validator->validate(21, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => 21, + '{{ limit }}' => 20, + )); } public function testNonNumeric() { - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"abcd"', - )); - $this->validator->validate('abcd', new Range(array( 'min' => 10, 'max' => 20, 'invalidMessage' => 'myMessage', ))); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"abcd"', + )); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/RegexValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/RegexValidatorTest.php index 25b5006c33e2..91f0c0532fce 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/RegexValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/RegexValidatorTest.php @@ -13,39 +13,27 @@ use Symfony\Component\Validator\Constraints\Regex; use Symfony\Component\Validator\Constraints\RegexValidator; +use Symfony\Component\Validator\Validation; -class RegexValidatorTest extends \PHPUnit_Framework_TestCase +class RegexValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() - { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new RegexValidator(); - $this->validator->initialize($this->context); - } - - protected function tearDown() + protected function createValidator() { - $this->context = null; - $this->validator = null; + return new RegexValidator(); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new Regex(array('pattern' => '/^[0-9]+$/'))); + + $this->assertNoViolation(); } public function testEmptyStringIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('', new Regex(array('pattern' => '/^[0-9]+$/'))); + + $this->assertNoViolation(); } /** @@ -61,11 +49,10 @@ public function testExpectsStringCompatibleType() */ public function testValidValues($value) { - $this->context->expects($this->never()) - ->method('addViolation'); - $constraint = new Regex(array('pattern' => '/^[0-9]+$/')); $this->validator->validate($value, $constraint); + + $this->assertNoViolation(); } public function getValidValues() @@ -88,13 +75,11 @@ public function testInvalidValues($value) 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"'.$value.'"', - )); - $this->validator->validate($value, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$value.'"', + )); } public function getInvalidValues() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/TimeValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/TimeValidatorTest.php index cfa24b80c746..4cc5f028b43b 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/TimeValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/TimeValidatorTest.php @@ -13,47 +13,34 @@ use Symfony\Component\Validator\Constraints\Time; use Symfony\Component\Validator\Constraints\TimeValidator; +use Symfony\Component\Validator\Validation; -class TimeValidatorTest extends \PHPUnit_Framework_TestCase +class TimeValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() - { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new TimeValidator(); - $this->validator->initialize($this->context); - } - - protected function tearDown() + protected function createValidator() { - $this->context = null; - $this->validator = null; + return new TimeValidator(); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new Time()); + + $this->assertNoViolation(); } public function testEmptyStringIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('', new Time()); + + $this->assertNoViolation(); } public function testDateTimeClassIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(new \DateTime(), new Time()); + + $this->assertNoViolation(); } /** @@ -69,10 +56,9 @@ public function testExpectsStringCompatibleType() */ public function testValidTimes($time) { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate($time, new Time()); + + $this->assertNoViolation(); } public function getValidTimes() @@ -93,13 +79,11 @@ public function testInvalidTimes($time) 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"'.$time.'"', - )); - $this->validator->validate($time, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$time.'"', + )); } public function getInvalidTimes() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/TrueValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/TrueValidatorTest.php index 5a42912edfd9..e401b8702214 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/TrueValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/TrueValidatorTest.php @@ -13,39 +13,27 @@ use Symfony\Component\Validator\Constraints\True; use Symfony\Component\Validator\Constraints\TrueValidator; +use Symfony\Component\Validator\Validation; -class TrueValidatorTest extends \PHPUnit_Framework_TestCase +class TrueValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() - { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new TrueValidator(); - $this->validator->initialize($this->context); - } - - protected function tearDown() + protected function createValidator() { - $this->context = null; - $this->validator = null; + return new TrueValidator(); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new True()); + + $this->assertNoViolation(); } public function testTrueIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(true, new True()); + + $this->assertNoViolation(); } public function testFalseIsInvalid() @@ -54,12 +42,10 @@ public function testFalseIsInvalid() 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => 'false', - )); - $this->validator->validate(false, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => 'false', + )); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/TypeValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/TypeValidatorTest.php index db008ce3cef9..139184638737 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/TypeValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/TypeValidatorTest.php @@ -13,49 +13,48 @@ use Symfony\Component\Validator\Constraints\Type; use Symfony\Component\Validator\Constraints\TypeValidator; +use Symfony\Component\Validator\Validation; -class TypeValidatorTest extends \PHPUnit_Framework_TestCase +class TypeValidatorTest extends AbstractConstraintValidatorTest { protected static $file; - protected $context; - protected $validator; - - protected function setUp() - { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new TypeValidator(); - $this->validator->initialize($this->context); - } - - protected function tearDown() + protected function createValidator() { - $this->context = null; - $this->validator = null; + return new TypeValidator(); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); + $constraint = new Type(array('type' => 'integer')); - $this->validator->validate(null, new Type(array('type' => 'integer'))); + $this->validator->validate(null, $constraint); + + $this->assertNoViolation(); } public function testEmptyIsValidIfString() { - $this->context->expects($this->never()) - ->method('addViolation'); + $constraint = new Type(array('type' => 'string')); + + $this->validator->validate('', $constraint); - $this->validator->validate('', new Type(array('type' => 'string'))); + $this->assertNoViolation(); } public function testEmptyIsInvalidIfNoString() { - $this->context->expects($this->once()) - ->method('addViolation'); + $constraint = new Type(array( + 'type' => 'integer', + 'message' => 'myMessage', + )); - $this->validator->validate('', new Type(array('type' => 'integer'))); + $this->validator->validate('', $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '""', + '{{ type }}' => 'integer', + )); } /** @@ -63,12 +62,11 @@ public function testEmptyIsInvalidIfNoString() */ public function testValidValues($value, $type) { - $this->context->expects($this->never()) - ->method('addViolation'); - $constraint = new Type(array('type' => $type)); $this->validator->validate($value, $constraint); + + $this->assertNoViolation(); } public function getValidValues() @@ -118,14 +116,12 @@ public function testInvalidValues($value, $type, $valueAsString) 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => $valueAsString, - '{{ type }}' => $type, - )); - $this->validator->validate($value, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => $valueAsString, + '{{ type }}' => $type, + )); } public function getInvalidValues() @@ -167,17 +163,18 @@ public function getInvalidValues() protected function createFile() { - if (!self::$file) { - self::$file = fopen(__FILE__, 'r'); + if (!static::$file) { + static::$file = fopen(__FILE__, 'r'); } - return self::$file; + return static::$file; } public static function tearDownAfterClass() { - if (self::$file) { - fclose(self::$file); + if (static::$file) { + fclose(static::$file); + static::$file = null; } } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.php index 4c95e5bbb0a4..0d4e8e3394e3 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.php @@ -13,39 +13,27 @@ use Symfony\Component\Validator\Constraints\Url; use Symfony\Component\Validator\Constraints\UrlValidator; +use Symfony\Component\Validator\Validation; -class UrlValidatorTest extends \PHPUnit_Framework_TestCase +class UrlValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() - { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new UrlValidator(); - $this->validator->initialize($this->context); - } - - protected function tearDown() + protected function createValidator() { - $this->context = null; - $this->validator = null; + return new UrlValidator(); } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new Url()); + + $this->assertNoViolation(); } public function testEmptyStringIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('', new Url()); + + $this->assertNoViolation(); } /** @@ -61,10 +49,9 @@ public function testExpectsStringCompatibleType() */ public function testValidUrls($url) { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate($url, new Url()); + + $this->assertNoViolation(); } public function getValidUrls() @@ -72,7 +59,7 @@ public function getValidUrls() return array( array('http://a.pl'), array('http://www.google.com'), - array('http://www.google.com.'), + //array('http://www.google.com.') OK as of 2.5 array('http://www.google.museum'), array('https://google.com/'), array('https://google.com:80/'), @@ -86,7 +73,7 @@ public function getValidUrls() array('http://symfony.com/#?'), array('http://www.symfony.com/doc/current/book/validation.html#supported-constraints'), array('http://very.long.domain.name.com/'), - array('http://localhost/'), + //array('http://localhost/') OK as of 2.5 array('http://127.0.0.1/'), array('http://127.0.0.1:80/'), array('http://[::1]/'), @@ -130,13 +117,11 @@ public function testInvalidUrls($url) 'message' => 'myMessage' )); - $this->context->expects($this->once()) - ->method('addViolation') - ->with('myMessage', array( - '{{ value }}' => '"'.$url.'"', - )); - $this->validator->validate($url, $constraint); + + $this->assertViolation('myMessage', array( + '{{ value }}' => '"'.$url.'"', + )); } public function getInvalidUrls() @@ -169,14 +154,13 @@ public function getInvalidUrls() */ public function testCustomProtocolIsValid($url) { - $this->context->expects($this->never()) - ->method('addViolation'); - $constraint = new Url(array( 'protocols' => array('ftp', 'file', 'git') )); $this->validator->validate($url, $constraint); + + $this->assertNoViolation(); } public function getValidCustomUrls() diff --git a/src/Symfony/Component/Validator/Tests/Fixtures/Countable.php b/src/Symfony/Component/Validator/Tests/Fixtures/Countable.php new file mode 100644 index 000000000000..282d78d45a67 --- /dev/null +++ b/src/Symfony/Component/Validator/Tests/Fixtures/Countable.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Validator\Tests\Fixtures; + +class Countable implements \Countable +{ + private $content; + + public function __construct(array $content) + { + $this->content = $content; + } + + public function count() + { + return count($this->content); + } +} diff --git a/src/Symfony/Component/Validator/Tests/Fixtures/CustomArrayObject.php b/src/Symfony/Component/Validator/Tests/Fixtures/CustomArrayObject.php new file mode 100644 index 000000000000..41eac961acf9 --- /dev/null +++ b/src/Symfony/Component/Validator/Tests/Fixtures/CustomArrayObject.php @@ -0,0 +1,70 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Validator\Tests\Fixtures; + +/** + * This class is a hand written simplified version of PHP native `ArrayObject` + * class, to show that it behaves differently than the PHP native implementation. + */ +class CustomArrayObject implements \ArrayAccess, \IteratorAggregate, \Countable, \Serializable +{ + private $array; + + public function __construct(array $array = null) + { + $this->array = $array ?: array(); + } + + public function offsetExists($offset) + { + return array_key_exists($offset, $this->array); + } + + public function offsetGet($offset) + { + return $this->array[$offset]; + } + + public function offsetSet($offset, $value) + { + if (null === $offset) { + $this->array[] = $value; + } else { + $this->array[$offset] = $value; + } + } + + public function offsetUnset($offset) + { + unset($this->array[$offset]); + } + + public function getIterator() + { + return new \ArrayIterator($this->array); + } + + public function count() + { + return count($this->array); + } + + public function serialize() + { + return serialize($this->array); + } + + public function unserialize($serialized) + { + $this->array = (array) unserialize((string) $serialized); + } +} diff --git a/src/Symfony/Component/Validator/Tests/Fixtures/StubGlobalExecutionContext.php b/src/Symfony/Component/Validator/Tests/Fixtures/StubGlobalExecutionContext.php new file mode 100644 index 000000000000..bfe096a86dad --- /dev/null +++ b/src/Symfony/Component/Validator/Tests/Fixtures/StubGlobalExecutionContext.php @@ -0,0 +1,69 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Validator\Tests\Fixtures; + +use Symfony\Component\Validator\ConstraintViolationList; +use Symfony\Component\Validator\GlobalExecutionContextInterface; +use Symfony\Component\Validator\ValidationVisitorInterface; + +/** + * @since 2.3.19 + * @author Bernhard Schussek + */ +class StubGlobalExecutionContext implements GlobalExecutionContextInterface +{ + private $violations; + + private $root; + + private $visitor; + + function __construct($root = null, ValidationVisitorInterface $visitor = null) + { + $this->violations = new ConstraintViolationList(); + $this->root = $root; + $this->visitor = $visitor; + } + + public function getViolations() + { + return $this->violations; + } + + public function setRoot($root) + { + $this->root = $root; + } + + public function getRoot() + { + return $this->root; + } + + public function setVisitor(ValidationVisitorInterface $visitor) + { + $this->visitor = $visitor; + } + + public function getVisitor() + { + return $this->visitor; + } + + public function getValidatorFactory() + { + } + + public function getMetadataFactory() + { + } +}