minor #11646 [Validator] Backported constraint validator tests from 2.5 (webmozart)

This PR was merged into the 2.3 branch.

Discussion
----------

[Validator] Backported constraint validator tests from 2.5

| Q             | A
| ------------- | ---
| Bug fix?      | no
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | -
| License       | MIT
| Doc PR        | -

This PR backports the constraint validator tests from 2.5 to 2.3 to facilitate maintenance. When we adapt a test in 2.3, we can now easily merge the change forward to 2.5.

Commits
-------

87a47ea [Validator] Backported constraint validator tests from 2.5
This commit is contained in:
Bernhard Schussek 2014-08-14 16:28:19 +02:00
commit 0ecb34f23b
51 changed files with 2137 additions and 2162 deletions

View File

@ -0,0 +1,414 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* 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 <bschussek@gmail.com>
*/
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);
}
}

View File

@ -1,437 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* 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);
}
}

View File

@ -21,11 +21,12 @@ use Symfony\Component\Form\SubmitButtonBuilder;
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 <bschussek@gmail.com>
*/
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 @@ class FormValidatorTest extends \PHPUnit_Framework_TestCase
->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->expectValidateValueAt(2, 'data', $object, $constraint1, 'group1');
$this->expectValidateValueAt(3, 'data', $object, $constraint2, 'group2');
$this->validator->initialize($context);
$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 @@ class FormValidatorTest extends \PHPUnit_Framework_TestCase
$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 @@ class FormValidatorTest extends \PHPUnit_Framework_TestCase
->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 @@ class FormValidatorTest extends \PHPUnit_Framework_TestCase
$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 @@ class FormValidatorTest extends \PHPUnit_Framework_TestCase
// 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 @@ class FormValidatorTest extends \PHPUnit_Framework_TestCase
// Launch transformer
$form->submit('foo');
$context->expects($this->never())
->method('validate');
$this->expectNoValidate();
$context->expects($this->once())
->method('addViolation')
->with(
'invalid_message_key',
array('{{ value }}' => 'foo', '{{ foo }}' => 'bar'),
'foo'
);
$context->expects($this->never())
->method('addViolationAt');
$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 @@ class FormValidatorTest extends \PHPUnit_Framework_TestCase
// Launch transformer
$form->submit('foo');
$context->expects($this->never())
->method('validate');
$this->expectNoValidate();
$context->expects($this->once())
->method('addViolation')
->with(
'invalid_message_key',
array('{{ value }}' => 'foo', '{{ foo }}' => 'bar'),
'foo'
);
$context->expects($this->never())
->method('addViolationAt');
$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 @@ class FormValidatorTest extends \PHPUnit_Framework_TestCase
->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 @@ class FormValidatorTest extends \PHPUnit_Framework_TestCase
// 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 @@ class FormValidatorTest extends \PHPUnit_Framework_TestCase
->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 @@ class FormValidatorTest extends \PHPUnit_Framework_TestCase
$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 @@ class FormValidatorTest extends \PHPUnit_Framework_TestCase
$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 @@ class FormValidatorTest extends \PHPUnit_Framework_TestCase
$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 @@ class FormValidatorTest extends \PHPUnit_Framework_TestCase
$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 @@ class FormValidatorTest extends \PHPUnit_Framework_TestCase
$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 @@ class FormValidatorTest extends \PHPUnit_Framework_TestCase
$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->expectNoValidate();
$this->validator->initialize($context);
$this->validator->validate($form, new Form());
$this->assertViolation('Extra!', array(
'{{ extra_fields }}' => 'foo'
), 'property.path', array('foo' => 'bar'));
}
/**
@ -627,26 +554,18 @@ class FormValidatorTest extends \PHPUnit_Framework_TestCase
->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 @@ class FormValidatorTest extends \PHPUnit_Framework_TestCase
$this->serverParams->expects($this->never())
->method('getNormalizedIniPostMaxSize');
$context = $this->getMockExecutionContext();
$parent = $this->getBuilder()
->setCompound(true)
->setDataMapper($this->getDataMapper())
@ -680,13 +598,11 @@ class FormValidatorTest extends \PHPUnit_Framework_TestCase
$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();
}
/**

View File

@ -0,0 +1,168 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* 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 <bschussek@gmail.com>
*/
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;
}
}

View File

@ -38,9 +38,7 @@ class AllValidator extends ConstraintValidator
$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);
}
}
}

View File

@ -70,7 +70,7 @@ class ChoiceValidator extends ConstraintValidator
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 @@ class ChoiceValidator extends ConstraintValidator
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;
}

View File

@ -43,9 +43,7 @@ class CollectionValidator extends ConstraintValidator
(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)

View File

@ -13,7 +13,6 @@ namespace Symfony\Component\Validator\Tests\Constraints;
use Symfony\Component\Intl\Util\IntlTestHelper;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\AbstractComparisonValidator;
class ComparisonTest_Class
{
@ -33,32 +32,15 @@ class ComparisonTest_Class
/**
* @author Daniel Holmes <daniel@danielholmes.org>
*/
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 @@ abstract class AbstractComparisonValidatorTestCase extends \PHPUnit_Framework_Te
*/
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 @@ abstract class AbstractComparisonValidatorTestCase extends \PHPUnit_Framework_Te
$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
));
}
/**

View File

@ -0,0 +1,194 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* 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 <bschussek@gmail.com>
*/
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();
}

View File

@ -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()
protected function createValidator()
{
$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()
{
$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 @@ class AllValidatorTest extends \PHPUnit_Framework_TestCase
{
$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 @@ class AllValidatorTest extends \PHPUnit_Framework_TestCase
$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()

View File

@ -14,38 +14,25 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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()
protected function createValidator()
{
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new BlankValidator();
$this->validator->initialize($this->context);
}
protected function tearDown()
{
$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 @@ class BlankValidatorTest extends \PHPUnit_Framework_TestCase
'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()

View File

@ -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 @@ class CallbackValidatorTest_Class
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);
}
protected function tearDown()
{
$this->context = null;
$this->validator = null;
return new CallbackValidator();
}
public function testNullIsValid()
{
$this->context->expects($this->never())
->method('addViolation');
$this->validator->validate(null, new Callback(array('foo')));
$this->assertNoViolation();
}
public function testCallbackSingleMethod()
public function testSingleMethod()
{
$object = new CallbackValidatorTest_Object();
$constraint = new Callback(array('validateOne'));
$this->context->expects($this->once())
->method('addViolation')
->with('My message', array(
'{{ value }}' => 'foobar',
));
$constraint = new Callback(array('validate'));
$this->validator->validate($object, $constraint);
$this->assertViolation('My message', array(
'{{ value }}' => 'foobar',
));
}
public function testCallbackSingleStaticMethod()
public function testSingleMethodExplicitName()
{
$object = new CallbackValidatorTest_Object();
$constraint = new Callback(array('methods' => array('validate')));
$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->assertViolation('My message', array(
'{{ value }}' => 'foobar',
));
}
public function testCallbackMultipleMethods()
public function testMultipleMethods()
{
$object = new CallbackValidatorTest_Object();
$constraint = new Callback(array('validate', 'validateStatic'));
$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->assertViolations(array(
$this->createViolation('My message', array(
'{{ value }}' => 'foobar',
)),
$this->createViolation('Static message', array(
'{{ value }}' => 'baz',
)),
));
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectCallbackArray()
public function testMultipleMethodsExplicitName()
{
$object = new CallbackValidatorTest_Object();
$constraint = new Callback(array(
'methods' => array('validate', 'validateStatic'),
));
$this->validator->validate($object, new Callback('foobar'));
$this->validator->validate($object, $constraint);
$this->assertViolations(array(
$this->createViolation('My message', array(
'{{ value }}' => 'foobar',
)),
$this->createViolation('Static message', array(
'{{ value }}' => 'baz',
)),
));
}
public function testSingleStaticMethod()
{
$object = new CallbackValidatorTest_Object();
$constraint = new Callback(array(
array(__CLASS__.'_Class', 'validateCallback')
));
$this->validator->validate($object, $constraint);
$this->assertViolation('Callback message', array(
'{{ value }}' => 'foobar',
));
}
public function testSingleStaticMethodExplicitName()
{
$object = new CallbackValidatorTest_Object();
$constraint = new Callback(array(
'methods' => array(array(__CLASS__.'_Class', 'validateCallback')),
));
$this->validator->validate($object, $constraint);
$this->assertViolation('Callback message', array(
'{{ value }}' => 'foobar',
));
}
/**
@ -151,6 +169,28 @@ class CallbackValidatorTest extends \PHPUnit_Framework_TestCase
{
$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);
}
}

View File

@ -14,38 +14,25 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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()
protected function createValidator()
{
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new CardSchemeValidator();
$this->validator->initialize($this->context);
}
protected function tearDown()
{
$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 @@ class CardSchemeValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class CardSchemeValidatorTest extends \PHPUnit_Framework_TestCase
*/
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()

View File

@ -19,33 +19,18 @@ function choice_callback()
return array('foo', 'bar');
}
class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
class ChoiceValidatorTest extends AbstractConstraintValidatorTest
{
protected $context;
protected $validator;
protected function createValidator()
{
return new ChoiceValidator();
}
public static function staticCallback()
{
return array('foo', 'bar');
}
protected function setUp()
{
$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__));
}
protected function tearDown()
{
$this->context = null;
$this->validator = null;
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
@ -61,10 +46,9 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
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 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
{
$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 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
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()
{
// search $this for "staticCallback"
$this->setObject($this);
$constraint = new Choice(array('callback' => 'staticCallback'));
$this->context->expects($this->never())
->method('addViolation');
$this->validator->validate('bar', $constraint);
$this->assertNoViolation();
}
public function testMultipleChoices()
@ -142,10 +124,9 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
'minMessage' => 'myMessage',
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ limit }}' => 2,
), null, 2);
$value = array('foo');
$this->validator->validate(array('foo'), $constraint);
$this->setValue($value);
$this->validator->validate($value, $constraint);
$this->assertViolation('myMessage', array(
'{{ limit }}' => 2,
), 'property.path', $value, 2);
}
public function testTooManyChoices()
@ -208,13 +187,15 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
'strict' => true,
));
$this->context->expects($this->never())
->method('addViolation');
$this->validator->validate(2, $constraint);
$this->assertNoViolation();
}
public function testStrictDisallowsDifferentType()
@ -252,13 +231,11 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
'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"',
));
}
}

View File

@ -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;
/**

View File

@ -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
{

View File

@ -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 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
$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 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
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 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
$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 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
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 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
'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,
)
)));

View File

@ -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 <bschussek@gmail.com>
@ -33,6 +20,6 @@ class CountValidatorCountableTest extends CountValidatorTest
{
protected function createCollection(array $content)
{
return new CountValidatorCountableTest_Countable($content);
return new Countable($content);
}
}

View File

@ -17,32 +17,20 @@ use Symfony\Component\Validator\Constraints\CountValidator;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
abstract class CountValidatorTest extends \PHPUnit_Framework_TestCase
abstract class CountValidatorTest 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 CountValidator();
$this->validator->initialize($this->context);
}
protected function tearDown()
{
$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 @@ abstract class CountValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ abstract class CountValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ abstract class CountValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ abstract class CountValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ abstract class CountValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ abstract class CountValidatorTest extends \PHPUnit_Framework_TestCase
'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()

View File

@ -15,40 +15,32 @@ use Symfony\Component\Intl\Util\IntlTestHelper;
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 @@ class CountryValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class CountryValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class CountryValidatorTest extends \PHPUnit_Framework_TestCase
\Locale::setDefault('en_GB');
$existingCountry = 'GB';
$this->context->expects($this->never())
->method('addViolation');
$this->validator->validate($existingCountry, new Country());
$this->assertNoViolation();
}
}

View File

@ -15,40 +15,32 @@ use Symfony\Component\Intl\Util\IntlTestHelper;
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 @@ class CurrencyValidatorTest extends \PHPUnit_Framework_TestCase
*/
public function testValidCurrencies($currency)
{
$this->context->expects($this->never())
->method('addViolation');
$this->validator->validate($currency, new Currency());
$this->assertNoViolation();
}
/**
@ -76,10 +67,10 @@ class CurrencyValidatorTest extends \PHPUnit_Framework_TestCase
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 @@ class CurrencyValidatorTest extends \PHPUnit_Framework_TestCase
'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()

View File

@ -14,46 +14,32 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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()
protected function createValidator()
{
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new DateTimeValidator();
$this->validator->initialize($this->context);
}
protected function tearDown()
{
$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 @@ class DateTimeValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class DateTimeValidatorTest extends \PHPUnit_Framework_TestCase
'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()

View File

@ -14,46 +14,32 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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()
protected function createValidator()
{
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new DateValidator();
$this->validator->initialize($this->context);
}
protected function tearDown()
{
$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 @@ class DateValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class DateValidatorTest extends \PHPUnit_Framework_TestCase
'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()

View File

@ -14,38 +14,25 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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()
protected function createValidator()
{
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new EmailValidator();
$this->validator->initialize($this->context);
}
protected function tearDown()
{
$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 @@ class EmailValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class EmailValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class EmailValidatorTest extends \PHPUnit_Framework_TestCase
array('example'),
array('example@'),
array('example@localhost'),
array('example@example.com@example.com'),
);
}
}

View File

@ -14,38 +14,25 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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()
protected function createValidator()
{
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new FalseValidator();
$this->validator->initialize($this->context);
}
protected function tearDown()
{
$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 @@ class FalseValidatorTest extends \PHPUnit_Framework_TestCase
'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'
));
}
}

View File

@ -26,12 +26,10 @@ class FileValidatorPathTest extends FileValidatorTest
'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"',
));
}
}

View File

@ -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 @@ abstract class FileValidatorTest extends \PHPUnit_Framework_TestCase
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));
// 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'),
);
}
/**
* @dataProvider provideMaxSizeExceededTests
*/
public function testMaxSizeExceeded($bytesWritten, $limit, $sizeAsString, $limitAsString, $suffix)
{
fseek($this->file, $bytesWritten-1, SEEK_SET);
fwrite($this->file, '0');
fclose($this->file);
$constraint = new File(array(
'maxSize' => 10,
'maxSize' => $limit,
'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);
$this->assertViolation('myMessage', array(
'{{ limit }}' => $limitAsString,
'{{ size }}' => $sizeAsString,
'{{ suffix }}' => $suffix,
'{{ file }}' => '"'.$this->path.'"',
));
}
public function testTooLargeKiloBytes()
public function provideMaxSizeNotExceededTests()
{
fwrite($this->file, str_repeat('0', 1400));
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'),
);
}
/**
* @dataProvider provideMaxSizeNotExceededTests
*/
public function testMaxSizeNotExceeded($bytesWritten, $limit)
{
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);
}
public function testTooLargeMegaBytes()
{
fwrite($this->file, str_repeat('0', 1400000));
$constraint = new File(array(
'maxSize' => '1M',
'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 @@ abstract class FileValidatorTest extends \PHPUnit_Framework_TestCase
->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 @@ abstract class FileValidatorTest extends \PHPUnit_Framework_TestCase
->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 @@ abstract class FileValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ abstract class FileValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ abstract class FileValidatorTest extends \PHPUnit_Framework_TestCase
'maxSize' => $maxSize
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', $params);
$this->validator->validate($file, $constraint);
$this->assertViolation('myMessage', $params);
}
public function uploadedFileErrorProvider()

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 B

View File

@ -0,0 +1,27 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* 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 <bschussek@gmail.com>
*/
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);
}
}

View File

@ -13,31 +13,27 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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 @@ class IbanValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class IbanValidatorTest extends \PHPUnit_Framework_TestCase
'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()

View File

@ -13,59 +13,54 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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 @@ class ImageValidatorTest extends \PHPUnit_Framework_TestCase
));
$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 @@ class ImageValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class ImageValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class ImageValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class ImageValidatorTest extends \PHPUnit_Framework_TestCase
*/
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',
));

View File

@ -13,39 +13,27 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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()
protected function createValidator()
{
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new IpValidator();
$this->validator->initialize($this->context);
}
protected function tearDown()
{
$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 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
*/
public function testInvalidValidatorVersion()
{
$ip = new Ip(array(
new Ip(array(
'version' => 666,
));
}
@ -71,12 +59,11 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
'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()

View File

@ -13,20 +13,16 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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 @@ class IsbnValidatorTest extends \PHPUnit_Framework_TestCase
array('0321812700'),
array('0-45122-5244'),
array('0-4712-92311'),
array('0-9752298-0-X')
);
}
@ -58,6 +55,7 @@ class IsbnValidatorTest extends \PHPUnit_Framework_TestCase
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 @@ class IsbnValidatorTest extends \PHPUnit_Framework_TestCase
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 @@ class IsbnValidatorTest extends \PHPUnit_Framework_TestCase
public function testExpectsStringCompatibleType()
{
$constraint = new Isbn(true);
$this->validator->validate(new \stdClass(), $constraint);
}
@ -153,12 +150,13 @@ class IsbnValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class IsbnValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class IsbnValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class IsbnValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class IsbnValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class IsbnValidatorTest extends \PHPUnit_Framework_TestCase
*/
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.'"',
));
}
}

View File

@ -13,20 +13,16 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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 @@ class IssnValidatorTest extends \PHPUnit_Framework_TestCase
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 @@ class IssnValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class IssnValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class IssnValidatorTest extends \PHPUnit_Framework_TestCase
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 @@ class IssnValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class IssnValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class IssnValidatorTest extends \PHPUnit_Framework_TestCase
*/
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.'"',
));
}
}

View File

@ -14,41 +14,34 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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 createValidator()
{
return new LanguageValidator();
}
protected function setUp()
{
IntlTestHelper::requireIntl($this);
IntlTestHelper::requireFullIntl($this);
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new LanguageValidator();
$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 Language());
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->context->expects($this->never())
->method('addViolation');
$this->validator->validate('', new Language());
$this->assertNoViolation();
}
/**
@ -64,10 +57,9 @@ class LanguageValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class LanguageValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class LanguageValidatorTest extends \PHPUnit_Framework_TestCase
{
\Locale::setDefault('fr_FR');
$existingLanguage = 'en';
$this->context->expects($this->never())
->method('addViolation');
$this->validator->validate($existingLanguage, new Language(array(
'message' => 'aMessage'
)));
$this->assertNoViolation();
}
}

View File

@ -13,39 +13,27 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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 @@ class LengthValidatorTest extends \PHPUnit_Framework_TestCase
$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 @@ class LengthValidatorTest extends \PHPUnit_Framework_TestCase
$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 @@ class LengthValidatorTest extends \PHPUnit_Framework_TestCase
$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 @@ class LengthValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class LengthValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class LengthValidatorTest extends \PHPUnit_Framework_TestCase
'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()

View File

@ -14,41 +14,34 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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 @@ class LocaleValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class LocaleValidatorTest extends \PHPUnit_Framework_TestCase
'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()

View File

@ -13,39 +13,27 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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()
protected function createValidator()
{
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new LuhnValidator();
$this->validator->initialize($this->context);
}
protected function tearDown()
{
$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 @@ class LuhnValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class LuhnValidatorTest extends \PHPUnit_Framework_TestCase
*/
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()

View File

@ -13,23 +13,13 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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 @@ class NotBlankValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class NotBlankValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class NotBlankValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class NotBlankValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class NotBlankValidatorTest extends \PHPUnit_Framework_TestCase
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage');
$this->validator->validate(array(), $constraint);
$this->assertViolation('myMessage', array(
'{{ value }}' => 'array',
));
}
}

View File

@ -13,23 +13,13 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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()
protected function createValidator()
{
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new NotNullValidator();
$this->validator->initialize($this->context);
}
protected function tearDown()
{
$this->context = null;
$this->validator = null;
return new NotNullValidator();
}
/**
@ -37,10 +27,9 @@ class NotNullValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class NotNullValidatorTest extends \PHPUnit_Framework_TestCase
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
));
$this->validator->validate(null, $constraint);
$this->assertViolation('myMessage');
}
}

View File

@ -13,31 +13,20 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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 @@ class NullValidatorTest extends \PHPUnit_Framework_TestCase
'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()

View File

@ -13,25 +13,20 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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 @@ class RangeValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class RangeValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class RangeValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class RangeValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class RangeValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class RangeValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class RangeValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class RangeValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class RangeValidatorTest extends \PHPUnit_Framework_TestCase
'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"',
));
}
}

View File

@ -13,39 +13,27 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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()
protected function createValidator()
{
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new RegexValidator();
$this->validator->initialize($this->context);
}
protected function tearDown()
{
$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 @@ class RegexValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class RegexValidatorTest extends \PHPUnit_Framework_TestCase
'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()

View File

@ -13,47 +13,34 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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()
protected function createValidator()
{
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new TimeValidator();
$this->validator->initialize($this->context);
}
protected function tearDown()
{
$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 @@ class TimeValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class TimeValidatorTest extends \PHPUnit_Framework_TestCase
'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()

View File

@ -13,39 +13,27 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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()
protected function createValidator()
{
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new TrueValidator();
$this->validator->initialize($this->context);
}
protected function tearDown()
{
$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 @@ class TrueValidatorTest extends \PHPUnit_Framework_TestCase
'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',
));
}
}

View File

@ -13,49 +13,48 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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()
protected function createValidator()
{
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new TypeValidator();
$this->validator->initialize($this->context);
}
protected function tearDown()
{
$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('', new Type(array('type' => 'string')));
$this->validator->validate('', $constraint);
$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 @@ class TypeValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class TypeValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class TypeValidatorTest extends \PHPUnit_Framework_TestCase
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;
}
}
}

View File

@ -13,39 +13,27 @@ namespace Symfony\Component\Validator\Tests\Constraints;
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()
protected function createValidator()
{
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new UrlValidator();
$this->validator->initialize($this->context);
}
protected function tearDown()
{
$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 @@ class UrlValidatorTest extends \PHPUnit_Framework_TestCase
*/
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 @@ class UrlValidatorTest extends \PHPUnit_Framework_TestCase
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 @@ class UrlValidatorTest extends \PHPUnit_Framework_TestCase
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 @@ class UrlValidatorTest extends \PHPUnit_Framework_TestCase
'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 @@ class UrlValidatorTest extends \PHPUnit_Framework_TestCase
*/
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()

View File

@ -0,0 +1,27 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* 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);
}
}

View File

@ -0,0 +1,70 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* 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);
}
}

View File

@ -0,0 +1,69 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* 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 <bschussek@gmail.com>
*/
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()
{
}
}