From 777666fac178f023baa47ec7ca12d4d0b824b99e Mon Sep 17 00:00:00 2001 From: Yassine Guedidi Date: Thu, 17 Jul 2014 14:55:31 +0200 Subject: [PATCH 01/10] [HttpFoundation] Update QUERY_STRING when overrideGlobals --- src/Symfony/Component/HttpFoundation/Request.php | 2 ++ .../Component/HttpFoundation/Tests/RequestTest.php | 9 +++++++++ 2 files changed, 11 insertions(+) diff --git a/src/Symfony/Component/HttpFoundation/Request.php b/src/Symfony/Component/HttpFoundation/Request.php index d7053339bd..f50219deae 100644 --- a/src/Symfony/Component/HttpFoundation/Request.php +++ b/src/Symfony/Component/HttpFoundation/Request.php @@ -479,6 +479,8 @@ class Request */ public function overrideGlobals() { + $this->server->set('QUERY_STRING', static::normalizeQueryString(http_build_query($this->query->all(), null, '&'))); + $_GET = $this->query->all(); $_POST = $this->request->all(); $_SERVER = $this->server->all(); diff --git a/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php b/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php index 688f3094b9..c2719ac9ab 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php @@ -1009,6 +1009,15 @@ class RequestTest extends \PHPUnit_Framework_TestCase $this->assertArrayHasKey('HTTP_X_FORWARDED_PROTO', $_SERVER); + $request->initialize(array('foo' => 'bar', 'baz' => 'foo')); + $request->query->remove('baz'); + + $request->overrideGlobals(); + + $this->assertEquals(array('foo' => 'bar'), $_GET); + $this->assertEquals('foo=bar', $_SERVER['QUERY_STRING']); + $this->assertEquals('foo=bar', $request->server->get('QUERY_STRING')); + // restore initial $_SERVER array $_SERVER = $server; } From 273671ec59be31b08445af1e8ca7714e8e452a53 Mon Sep 17 00:00:00 2001 From: Bernhard Schussek Date: Mon, 4 Aug 2014 12:36:09 +0200 Subject: [PATCH 02/10] [Validator] Convert objects to string in comparison validators. Reapplies 6cf5e0812e6f20d60acbc0324abf96475e89b6ef --- .../Validator/ConstraintValidator.php | 39 ++++++++++++++----- .../AbstractComparisonValidator.php | 4 +- .../AbstractComparisonValidatorTestCase.php | 15 +++++++ .../Constraints/EqualToValidatorTest.php | 4 +- .../Constraints/GreaterThanValidatorTest.php | 3 ++ .../Constraints/IdenticalToValidatorTest.php | 5 ++- .../LessThanOrEqualValidatorTest.php | 3 ++ .../Constraints/LessThanValidatorTest.php | 3 ++ .../Constraints/NotEqualToValidatorTest.php | 4 +- .../NotIdenticalToValidatorTest.php | 4 +- 10 files changed, 68 insertions(+), 16 deletions(-) diff --git a/src/Symfony/Component/Validator/ConstraintValidator.php b/src/Symfony/Component/Validator/ConstraintValidator.php index ac50f7e0e2..58c0902e13 100644 --- a/src/Symfony/Component/Validator/ConstraintValidator.php +++ b/src/Symfony/Component/Validator/ConstraintValidator.php @@ -20,6 +20,21 @@ namespace Symfony\Component\Validator; */ abstract class ConstraintValidator implements ConstraintValidatorInterface { + /** + * Whether to format {@link \DateTime} objects as RFC-3339 dates + * ("Y-m-d H:i:s"). + * + * @var integer + */ + const PRETTY_DATE = 1; + + /** + * Whether to cast objects with a "__toString()" method to strings. + * + * @var integer + */ + const OBJECT_TO_STRING = 2; + /** * @var ExecutionContextInterface */ @@ -66,15 +81,15 @@ abstract class ConstraintValidator implements ConstraintValidatorInterface * won't know what an "object", "array" or "resource" is and will be * confused by the violation message. * - * @param mixed $value The value to format as string - * @param bool $prettyDateTime Whether to format {@link \DateTime} - * objects as RFC-3339 dates ("Y-m-d H:i:s") + * @param mixed $value The value to format as string + * @param integer $format A bitwise combination of the format + * constants in this class * * @return string The string representation of the passed value */ - protected function formatValue($value, $prettyDateTime = false) + protected function formatValue($value, $format = 0) { - if ($prettyDateTime && $value instanceof \DateTime) { + if (($format & self::PRETTY_DATE) && $value instanceof \DateTime) { if (class_exists('IntlDateFormatter')) { $locale = \Locale::getDefault(); $formatter = new \IntlDateFormatter($locale, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::SHORT); @@ -86,6 +101,10 @@ abstract class ConstraintValidator implements ConstraintValidatorInterface } if (is_object($value)) { + if ($format & self::OBJECT_TO_STRING && method_exists($value, '__toString')) { + return $value->__toString(); + } + return 'object'; } @@ -122,18 +141,18 @@ abstract class ConstraintValidator implements ConstraintValidatorInterface * Each of the values is converted to a string using * {@link formatValue()}. The values are then concatenated with commas. * - * @param array $values A list of values - * @param bool $prettyDateTime Whether to format {@link \DateTime} - * objects as RFC-3339 dates ("Y-m-d H:i:s") + * @param array $values A list of values + * @param integer $format A bitwise combination of the format + * constants in this class * * @return string The string representation of the value list * * @see formatValue() */ - protected function formatValues(array $values, $prettyDateTime = false) + protected function formatValues(array $values, $format = 0) { foreach ($values as $key => $value) { - $values[$key] = $this->formatValue($value, $prettyDateTime); + $values[$key] = $this->formatValue($value, $format); } return implode(', ', $values); diff --git a/src/Symfony/Component/Validator/Constraints/AbstractComparisonValidator.php b/src/Symfony/Component/Validator/Constraints/AbstractComparisonValidator.php index d2b15f2162..2e8230bb83 100644 --- a/src/Symfony/Component/Validator/Constraints/AbstractComparisonValidator.php +++ b/src/Symfony/Component/Validator/Constraints/AbstractComparisonValidator.php @@ -32,8 +32,8 @@ abstract class AbstractComparisonValidator extends ConstraintValidator if (!$this->compareValues($value, $constraint->value)) { $this->context->addViolation($constraint->message, array( - '{{ value }}' => $this->formatValue($value, true), - '{{ compared_value }}' => $this->formatValue($constraint->value, true), + '{{ value }}' => $this->formatValue($value, self::OBJECT_TO_STRING | self::PRETTY_DATE), + '{{ compared_value }}' => $this->formatValue($constraint->value, self::OBJECT_TO_STRING | self::PRETTY_DATE), '{{ compared_value_type }}' => $this->formatTypeOf($constraint->value) )); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php b/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php index 80690d29e0..a1c573baa4 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php @@ -15,6 +15,21 @@ use Symfony\Component\Intl\Util\IntlTestHelper; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraints\AbstractComparisonValidator; +class ComparisonTest_Class +{ + protected $value; + + public function __construct($value) + { + $this->value = $value; + } + + public function __toString() + { + return (string) $this->value; + } +} + /** * @author Daniel Holmes */ diff --git a/src/Symfony/Component/Validator/Tests/Constraints/EqualToValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/EqualToValidatorTest.php index 783e5508d7..997ed74023 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/EqualToValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/EqualToValidatorTest.php @@ -39,6 +39,7 @@ class EqualToValidatorTest extends AbstractComparisonValidatorTestCase array(3, '3'), array('a', 'a'), array(new \DateTime('2000-01-01'), new \DateTime('2000-01-01')), + array(new ComparisonTest_Class(5), new ComparisonTest_Class(5)), array(null, 1), ); } @@ -51,7 +52,8 @@ class EqualToValidatorTest extends AbstractComparisonValidatorTestCase return array( array(1, '1', 2, '2', 'integer'), array('22', '"22"', '333', '"333"', 'string'), - array(new \DateTime('2001-01-01'), 'Jan 1, 2001, 12:00 AM', new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', 'DateTime') + array(new \DateTime('2001-01-01'), 'Jan 1, 2001, 12:00 AM', new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', 'DateTime'), + array(new ComparisonTest_Class(4), '4', new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'), ); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorTest.php index 14a7a6d16f..64c5dbff65 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorTest.php @@ -37,6 +37,7 @@ class GreaterThanValidatorTest extends AbstractComparisonValidatorTestCase return array( array(2, 1), array(new \DateTime('2005/01/01'), new \DateTime('2001/01/01')), + array(new ComparisonTest_Class(5), new ComparisonTest_Class(4)), array('333', '22'), array(null, 1), ); @@ -52,6 +53,8 @@ class GreaterThanValidatorTest extends AbstractComparisonValidatorTestCase array(2, '2', 2, '2', 'integer'), array(new \DateTime('2000/01/01'), 'Jan 1, 2000, 12:00 AM', new \DateTime('2005/01/01'), 'Jan 1, 2005, 12:00 AM', 'DateTime'), array(new \DateTime('2000/01/01'), 'Jan 1, 2000, 12:00 AM', new \DateTime('2000/01/01'), 'Jan 1, 2000, 12:00 AM', 'DateTime'), + array(new ComparisonTest_Class(4), '4', new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'), + array(new ComparisonTest_Class(5), '5', new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'), array('22', '"22"', '333', '"333"', 'string'), array('22', '"22"', '22', '"22"', 'string') ); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/IdenticalToValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/IdenticalToValidatorTest.php index 9c08523386..dfe0f97af6 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/IdenticalToValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/IdenticalToValidatorTest.php @@ -35,11 +35,13 @@ class IdenticalToValidatorTest extends AbstractComparisonValidatorTestCase public function provideValidComparisons() { $date = new \DateTime('2000-01-01'); + $object = new ComparisonTest_Class(2); return array( array(3, 3), array('a', 'a'), array($date, $date), + array($object, $object), array(null, 1), ); } @@ -54,7 +56,8 @@ class IdenticalToValidatorTest extends AbstractComparisonValidatorTestCase array(2, '2', '2', '"2"', 'string'), array('22', '"22"', '333', '"333"', 'string'), array(new \DateTime('2001-01-01'), 'Jan 1, 2001, 12:00 AM', new \DateTime('2001-01-01'), 'Jan 1, 2001, 12:00 AM', 'DateTime'), - array(new \DateTime('2001-01-01'), 'Jan 1, 2001, 12:00 AM', new \DateTime('1999-01-01'), 'Jan 1, 1999, 12:00 AM', 'DateTime') + array(new \DateTime('2001-01-01'), 'Jan 1, 2001, 12:00 AM', new \DateTime('1999-01-01'), 'Jan 1, 1999, 12:00 AM', 'DateTime'), + array(new ComparisonTest_Class(4), '4', new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'), ); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorTest.php index fc41811a76..0f4f749b8b 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorTest.php @@ -39,6 +39,8 @@ class LessThanOrEqualValidatorTest extends AbstractComparisonValidatorTestCase array(1, 1), array(new \DateTime('2000-01-01'), new \DateTime('2000-01-01')), array(new \DateTime('2000-01-01'), new \DateTime('2020-01-01')), + array(new ComparisonTest_Class(4), new ComparisonTest_Class(5)), + array(new ComparisonTest_Class(5), new ComparisonTest_Class(5)), array('a', 'a'), array('a', 'z'), array(null, 1), @@ -53,6 +55,7 @@ class LessThanOrEqualValidatorTest extends AbstractComparisonValidatorTestCase return array( array(2, '2', 1, '1', 'integer'), array(new \DateTime('2010-01-01'), 'Jan 1, 2010, 12:00 AM', new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', 'DateTime'), + array(new ComparisonTest_Class(5), '5', new ComparisonTest_Class(4), '4', __NAMESPACE__.'\ComparisonTest_Class'), array('c', '"c"', 'b', '"b"', 'string') ); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorTest.php index 5cb5673c81..408251d214 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorTest.php @@ -37,6 +37,7 @@ class LessThanValidatorTest extends AbstractComparisonValidatorTestCase return array( array(1, 2), array(new \DateTime('2000-01-01'), new \DateTime('2010-01-01')), + array(new ComparisonTest_Class(4), new ComparisonTest_Class(5)), array('22', '333'), array(null, 1), ); @@ -52,6 +53,8 @@ class LessThanValidatorTest extends AbstractComparisonValidatorTestCase array(2, '2', 2, '2', 'integer'), array(new \DateTime('2010-01-01'), 'Jan 1, 2010, 12:00 AM', new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', 'DateTime'), array(new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', 'DateTime'), + array(new ComparisonTest_Class(5), '5', new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'), + array(new ComparisonTest_Class(6), '6', new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'), array('333', '"333"', '22', '"22"', 'string'), ); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/NotEqualToValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/NotEqualToValidatorTest.php index e0db97a0e7..d0342bfe35 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/NotEqualToValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/NotEqualToValidatorTest.php @@ -38,6 +38,7 @@ class NotEqualToValidatorTest extends AbstractComparisonValidatorTestCase array(1, 2), array('22', '333'), array(new \DateTime('2001-01-01'), new \DateTime('2000-01-01')), + array(new ComparisonTest_Class(6), new ComparisonTest_Class(5)), array(null, 1), ); } @@ -51,7 +52,8 @@ class NotEqualToValidatorTest extends AbstractComparisonValidatorTestCase array(3, '3', 3, '3', 'integer'), array('2', '"2"', 2, '2', 'integer'), array('a', '"a"', 'a', '"a"', 'string'), - array(new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', 'DateTime') + array(new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', 'DateTime'), + array(new ComparisonTest_Class(5), '5', new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'), ); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/NotIdenticalToValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/NotIdenticalToValidatorTest.php index ad2865c457..b1e31a40b7 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/NotIdenticalToValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/NotIdenticalToValidatorTest.php @@ -50,11 +50,13 @@ class NotIdenticalToValidatorTest extends AbstractComparisonValidatorTestCase public function provideInvalidComparisons() { $date = new \DateTime('2000-01-01'); + $object = new ComparisonTest_Class(2); return array( array(3, '3', 3, '3', 'integer'), array('a', '"a"', 'a', '"a"', 'string'), - array($date, 'Jan 1, 2000, 12:00 AM', $date, 'Jan 1, 2000, 12:00 AM', 'DateTime') + array($date, 'Jan 1, 2000, 12:00 AM', $date, 'Jan 1, 2000, 12:00 AM', 'DateTime'), + array($object, '2', $object, '2', __NAMESPACE__.'\ComparisonTest_Class'), ); } } From 88149209aec51c0dab633d250e70c0708213acf5 Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Thu, 7 Aug 2014 17:53:10 +0200 Subject: [PATCH 03/10] [Console] fixed style creation when providing an unknown tag option --- src/Symfony/Component/Console/Formatter/OutputFormatter.php | 6 +++++- .../Console/Tests/Formatter/OutputFormatterTest.php | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/Symfony/Component/Console/Formatter/OutputFormatter.php b/src/Symfony/Component/Console/Formatter/OutputFormatter.php index ca5f28731e..3813b542d4 100644 --- a/src/Symfony/Component/Console/Formatter/OutputFormatter.php +++ b/src/Symfony/Component/Console/Formatter/OutputFormatter.php @@ -215,7 +215,11 @@ class OutputFormatter implements OutputFormatterInterface } elseif ('bg' == $match[0]) { $style->setBackground($match[1]); } else { - $style->setOption($match[1]); + try { + $style->setOption($match[1]); + } catch (\InvalidArgumentException $e) { + return false; + } } } diff --git a/src/Symfony/Component/Console/Tests/Formatter/OutputFormatterTest.php b/src/Symfony/Component/Console/Tests/Formatter/OutputFormatterTest.php index c8f0b987af..bdaf36caef 100644 --- a/src/Symfony/Component/Console/Tests/Formatter/OutputFormatterTest.php +++ b/src/Symfony/Component/Console/Tests/Formatter/OutputFormatterTest.php @@ -151,7 +151,7 @@ class OutputFormatterTest extends \PHPUnit_Framework_TestCase { $formatter = new OutputFormatter(true); - $this->assertEquals("\033[32msome \033[0m\033[32m\033[0m\033[32m styled \033[0m\033[32m

\033[0m\033[32msingle-char tag\033[0m\033[32m

\033[0m", $formatter->format('some styled

single-char tag

')); + $this->assertEquals("\033[32msome \033[0m\033[32m\033[0m\033[32m \033[0m\033[32m\033[0m\033[32m styled \033[0m\033[32m

\033[0m\033[32msingle-char tag\033[0m\033[32m

\033[0m", $formatter->format('some styled

single-char tag

')); } public function testFormatLongString() From 24fb66ddf386f247fc47234dacb74ec0d03e35b5 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Thu, 7 Aug 2014 16:04:04 +0200 Subject: [PATCH 04/10] remove volatile tests Some tests relying on timings and external network resources were not reliable and occasionally made builds on Travis fail. --- .../Component/Finder/Tests/FinderTest.php | 21 ------------------- .../Stopwatch/Tests/StopwatchEventTest.php | 19 ----------------- .../Stopwatch/Tests/StopwatchTest.php | 13 ------------ 3 files changed, 53 deletions(-) diff --git a/src/Symfony/Component/Finder/Tests/FinderTest.php b/src/Symfony/Component/Finder/Tests/FinderTest.php index 9f9e47b646..da593a7a71 100644 --- a/src/Symfony/Component/Finder/Tests/FinderTest.php +++ b/src/Symfony/Component/Finder/Tests/FinderTest.php @@ -820,25 +820,4 @@ class FinderTest extends Iterator\RealIteratorTestCase $this->assertIterator($expected, $finder); $this->assertIteratorInForeach($expected, $finder); } - - public function testNonSeekableStream() - { - if (!in_array('ftp', stream_get_wrappers())) { - $this->markTestSkipped(sprintf('Unavailable stream "%s".', 'ftp')); - } - - try { - $i = Finder::create()->in('ftp://ftp.mozilla.org/')->depth(0)->getIterator(); - } catch (\UnexpectedValueException $e) { - $this->markTestSkipped(sprintf('Unsupported stream "%s".', 'ftp')); - } - - $contains = array( - 'ftp://ftp.mozilla.org'.DIRECTORY_SEPARATOR.'README', - 'ftp://ftp.mozilla.org'.DIRECTORY_SEPARATOR.'index.html', - 'ftp://ftp.mozilla.org'.DIRECTORY_SEPARATOR.'pub', - ); - - $this->assertIteratorInForeach($contains, $i); - } } diff --git a/src/Symfony/Component/Stopwatch/Tests/StopwatchEventTest.php b/src/Symfony/Component/Stopwatch/Tests/StopwatchEventTest.php index af63153382..825520850a 100644 --- a/src/Symfony/Component/Stopwatch/Tests/StopwatchEventTest.php +++ b/src/Symfony/Component/Stopwatch/Tests/StopwatchEventTest.php @@ -133,25 +133,6 @@ class StopwatchEventTest extends \PHPUnit_Framework_TestCase $this->assertEquals(0, $event->getStartTime(), null, self::DELTA); } - public function testEndTime() - { - $event = new StopwatchEvent(microtime(true) * 1000); - $this->assertEquals(0, $event->getEndTime()); - - $event = new StopwatchEvent(microtime(true) * 1000); - $event->start(); - $this->assertEquals(0, $event->getEndTime()); - - $event = new StopwatchEvent(microtime(true) * 1000); - $event->start(); - usleep(100000); - $event->stop(); - $event->start(); - usleep(100000); - $event->stop(); - $this->assertEquals(200, $event->getEndTime(), null, self::DELTA); - } - /** * @expectedException \InvalidArgumentException */ diff --git a/src/Symfony/Component/Stopwatch/Tests/StopwatchTest.php b/src/Symfony/Component/Stopwatch/Tests/StopwatchTest.php index a8c11424fa..6805effb48 100644 --- a/src/Symfony/Component/Stopwatch/Tests/StopwatchTest.php +++ b/src/Symfony/Component/Stopwatch/Tests/StopwatchTest.php @@ -79,19 +79,6 @@ class StopwatchTest extends \PHPUnit_Framework_TestCase $this->assertEquals(200, $event->getDuration(), null, self::DELTA); } - public function testLap() - { - $stopwatch = new Stopwatch(); - $stopwatch->start('foo', 'cat'); - usleep(100000); - $event = $stopwatch->lap('foo'); - usleep(100000); - $stopwatch->stop('foo'); - - $this->assertInstanceof('Symfony\Component\Stopwatch\StopwatchEvent', $event); - $this->assertEquals(200, $event->getDuration(), null, self::DELTA); - } - /** * @expectedException \LogicException */ From be03b7552a515a914becbdee3a94f4d8acf33330 Mon Sep 17 00:00:00 2001 From: Pablo Godel Date: Thu, 7 Aug 2014 10:14:53 -0400 Subject: [PATCH 05/10] fix typos and syntax in Profiler controller method comments --- .../WebProfilerBundle/Controller/ProfilerController.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Symfony/Bundle/WebProfilerBundle/Controller/ProfilerController.php b/src/Symfony/Bundle/WebProfilerBundle/Controller/ProfilerController.php index a106feae99..8542f2865f 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Controller/ProfilerController.php +++ b/src/Symfony/Bundle/WebProfilerBundle/Controller/ProfilerController.php @@ -310,7 +310,7 @@ class ProfilerController } /** - * Search results. + * Renders the search results. * * @param Request $request The current HTTP Request * @param string $token The token @@ -351,7 +351,7 @@ class ProfilerController } /** - * Narrow the search bar. + * Narrows the search bar. * * @param Request $request The current HTTP Request * From f1ea987f35432f2e343d7e7040ed1db7b42c3e13 Mon Sep 17 00:00:00 2001 From: Benjamin Laugueux Date: Thu, 7 Aug 2014 11:43:44 +0200 Subject: [PATCH 06/10] Allow basic auth in url. Improve regex. Add tests. --- .../Component/Validator/Constraints/UrlValidator.php | 1 + .../Validator/Tests/Constraints/UrlValidatorTest.php | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/src/Symfony/Component/Validator/Constraints/UrlValidator.php b/src/Symfony/Component/Validator/Constraints/UrlValidator.php index 748f824894..1ba47ffd1d 100644 --- a/src/Symfony/Component/Validator/Constraints/UrlValidator.php +++ b/src/Symfony/Component/Validator/Constraints/UrlValidator.php @@ -24,6 +24,7 @@ class UrlValidator extends ConstraintValidator { const PATTERN = '~^ (%s):// # protocol + (([\pL\pN-]+:)?([\pL\pN-]+)@)? # basic auth ( ([\pL\pN\pS-\.])+(\.?([\pL]|xn\-\-[\pL\pN-]+)+\.?) # a domain name | # or diff --git a/src/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.php index ac2cf9e360..4c95e5bbb0 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.php @@ -116,6 +116,8 @@ class UrlValidatorTest extends \PHPUnit_Framework_TestCase array('http://xn--espaa-rta.xn--ca-ol-fsay5a/'), array('http://xn--d1abbgf6aiiy.xn--p1ai/'), array('http://☎.com/'), + array('http://username:password@symfony.com'), + array('http://user-name@symfony.com'), ); } @@ -155,6 +157,10 @@ class UrlValidatorTest extends \PHPUnit_Framework_TestCase array('ftp://[::1]/'), array('http://[::1'), array('http://hello.☎/'), + array('http://:password@symfony.com'), + array('http://:password@@symfony.com'), + array('http://username:passwordsymfony.com'), + array('http://usern@me:password@symfony.com'), ); } From 8a2b423b53322e66c65eae81ee6e49114ab452ab Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Sun, 10 Aug 2014 14:44:20 +0200 Subject: [PATCH 07/10] [FrameworkBundle] add missing attribute to XSD The hinclude_default_template configuration option couldn't have been set in XML configurations since it wasn't defined in the XML schema definition. --- .../FrameworkBundle/Resources/config/schema/symfony-1.0.xsd | 1 + .../Tests/DependencyInjection/Fixtures/php/full.php | 1 + .../Tests/DependencyInjection/Fixtures/xml/full.xml | 2 +- .../Tests/DependencyInjection/Fixtures/yml/full.yml | 1 + .../Tests/DependencyInjection/FrameworkExtensionTest.php | 1 + 5 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd b/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd index 4b235051f8..17b817c325 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd @@ -105,6 +105,7 @@ + diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/full.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/full.php index c4eff93492..0bc94f2e73 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/full.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/full.php @@ -56,6 +56,7 @@ $container->loadFromExtension('framework', array( 'form' => array( 'resources' => array('theme1', 'theme2') ), + 'hinclude_default_template' => 'global_hinclude_template', ), 'translator' => array( 'enabled' => true, diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/full.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/full.xml index 8fd3e9b652..bfdaabc71f 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/full.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/full.xml @@ -13,7 +13,7 @@ - + loader.foo loader.bar php diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/full.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/full.yml index d013063916..0a159ddc34 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/full.yml +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/full.yml @@ -44,6 +44,7 @@ framework: base_urls: ["http://images1.example.com", "http://images2.example.com"] form: resources: [theme1, theme2] + hinclude_default_template: global_hinclude_template translator: enabled: true fallback: fr diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php index 346962e2ac..f1adb72976 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php @@ -158,6 +158,7 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertEquals(array('php', 'twig'), $container->getParameter('templating.engines'), '->registerTemplatingConfiguration() sets a templating.engines parameter'); $this->assertEquals(array('FrameworkBundle:Form', 'theme1', 'theme2'), $container->getParameter('templating.helper.form.resources'), '->registerTemplatingConfiguration() registers the theme and adds the base theme'); + $this->assertEquals('global_hinclude_template', $container->getParameter('fragment.renderer.hinclude.global_template'), '->registerTemplatingConfiguration() registers the global hinclude.js template'); } public function testTemplatingAssetsHelperScopeDependsOnPackageArgumentScopes() From b56b7409409ddc96b08b39382042bd01e1614382 Mon Sep 17 00:00:00 2001 From: Chris Sedlmayr Date: Tue, 29 Jul 2014 14:36:07 +0100 Subject: [PATCH 08/10] [HttpFoundation] MongoDbSessionHandler supports auto expiry via configurable expiry_field --- .../Storage/Handler/MongoDbSessionHandler.php | 33 +++++++-- .../Handler/MongoDbSessionHandlerTest.php | 71 ++++++++++++++++++- 2 files changed, 94 insertions(+), 10 deletions(-) diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.php b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.php index 87aa7fb4f7..b151c8e33d 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MongoDbSessionHandler.php @@ -62,9 +62,10 @@ class MongoDbSessionHandler implements \SessionHandlerInterface $this->mongo = $mongo; $this->options = array_merge(array( - 'id_field' => '_id', - 'data_field' => 'data', - 'time_field' => 'time', + 'id_field' => '_id', + 'data_field' => 'data', + 'time_field' => 'time', + 'expiry_field' => false, ), $options); } @@ -109,6 +110,9 @@ class MongoDbSessionHandler implements \SessionHandlerInterface * * See: http://docs.mongodb.org/manual/tutorial/expire-data/ */ + if (false !== $this->options['expiry_field']) { + return true; + } $time = new \MongoDate(time() - $maxlifetime); $this->getCollection()->remove(array( @@ -123,12 +127,27 @@ class MongoDbSessionHandler implements \SessionHandlerInterface */ public function write($sessionId, $data) { + $fields = array( + $this->options['data_field'] => new \MongoBinData($data, \MongoBinData::BYTE_ARRAY), + $this->options['time_field'] => new \MongoDate(), + ); + + /* Note: As discussed in the gc method of this class. You can utilise + * TTL collections in MongoDB 2.2+ + * We are setting the "expiry_field" as part of the write operation here + * You will need to create the index on your collection that expires documents + * at that time + * e.g. + * db.MySessionCollection.ensureIndex( { "expireAt": 1 }, { expireAfterSeconds: 0 } ) + */ + if (false !== $this->options['expiry_field']) { + $expiry = new \MongoDate(time() + (int) ini_get('session.gc_maxlifetime')); + $fields[$this->options['expiry_field']] = $expiry; + } + $this->getCollection()->update( array($this->options['id_field'] => $sessionId), - array('$set' => array( - $this->options['data_field'] => new \MongoBinData($data, \MongoBinData::BYTE_ARRAY), - $this->options['time_field'] => new \MongoDate(), - )), + array('$set' => $fields), array('upsert' => true, 'multiple' => false) ); diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php index 9577d52478..19170bbbf0 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php @@ -41,7 +41,7 @@ class MongoDbSessionHandlerTest extends \PHPUnit_Framework_TestCase 'data_field' => 'data', 'time_field' => 'time', 'database' => 'sf2-test', - 'collection' => 'session-test' + 'collection' => 'session-test', ); $this->storage = new MongoDbSessionHandler($this->mongo, $this->options); @@ -100,6 +100,45 @@ class MongoDbSessionHandlerTest extends \PHPUnit_Framework_TestCase $that->assertInstanceOf('MongoDate', $data[$this->options['time_field']]); } + public function testWriteWhenUsingExpiresField() + { + $this->options = array( + 'id_field' => '_id', + 'data_field' => 'data', + 'time_field' => 'time', + 'database' => 'sf2-test', + 'collection' => 'session-test', + 'expiry_field' => 'expiresAt' + ); + + $this->storage = new MongoDbSessionHandler($this->mongo, $this->options); + + $collection = $this->createMongoCollectionMock(); + + $this->mongo->expects($this->once()) + ->method('selectCollection') + ->with($this->options['database'], $this->options['collection']) + ->will($this->returnValue($collection)); + + $that = $this; + $data = array(); + + $collection->expects($this->once()) + ->method('update') + ->will($this->returnCallback(function ($criteria, $updateData, $options) use ($that, &$data) { + $that->assertEquals(array($that->options['id_field'] => 'foo'), $criteria); + $that->assertEquals(array('upsert' => true, 'multiple' => false), $options); + + $data = $updateData['$set']; + })); + + $this->assertTrue($this->storage->write('foo', 'bar')); + + $this->assertEquals('bar', $data[$this->options['data_field']]->bin); + $that->assertInstanceOf('MongoDate', $data[$this->options['time_field']]); + $that->assertInstanceOf('MongoDate', $data[$this->options['expiry_field']]); + } + public function testReplaceSessionData() { $collection = $this->createMongoCollectionMock(); @@ -154,10 +193,36 @@ class MongoDbSessionHandlerTest extends \PHPUnit_Framework_TestCase ->method('remove') ->will($this->returnCallback(function ($criteria) use ($that) { $that->assertInstanceOf('MongoDate', $criteria[$that->options['time_field']]['$lt']); - $that->assertGreaterThanOrEqual(time() - -1, $criteria[$that->options['time_field']]['$lt']->sec); + $that->assertGreaterThanOrEqual(time() - 1, $criteria[$that->options['time_field']]['$lt']->sec); })); - $this->assertTrue($this->storage->gc(-1)); + $this->assertTrue($this->storage->gc(1)); + } + + public function testGcWhenUsingExpiresField() + { + $this->options = array( + 'id_field' => '_id', + 'data_field' => 'data', + 'time_field' => 'time', + 'database' => 'sf2-test', + 'collection' => 'session-test', + 'expiry_field' => 'expiresAt' + ); + + $this->storage = new MongoDbSessionHandler($this->mongo, $this->options); + + $collection = $this->createMongoCollectionMock(); + + $this->mongo->expects($this->never()) + ->method('selectCollection'); + + $that = $this; + + $collection->expects($this->never()) + ->method('remove'); + + $this->assertTrue($this->storage->gc(1)); } private function createMongoCollectionMock() From 65220e77b431fdb7422b55e26b0d3b5dc924d659 Mon Sep 17 00:00:00 2001 From: Benjamin Laugueux Date: Mon, 11 Aug 2014 12:07:40 +0200 Subject: [PATCH 09/10] Fix toolbar vertical alignment. --- .../WebProfilerBundle/Resources/views/Profiler/toolbar.css.twig | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar.css.twig b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar.css.twig index 8e780c3155..85b30948ed 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar.css.twig +++ b/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar.css.twig @@ -22,6 +22,7 @@ -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; + vertical-align: baseline; } .sf-toolbarreset { From 87a47eadc9967ac0f6a7abcc95c2e28dbda66e9d Mon Sep 17 00:00:00 2001 From: Bernhard Schussek Date: Fri, 8 Aug 2014 10:10:43 +0200 Subject: [PATCH 10/10] [Validator] Backported constraint validator tests from 2.5 --- .../Constraints/UniqueEntityValidatorTest.php | 414 +++++++++++++++++ .../Constraints/UniqueValidatorTest.php | 437 ------------------ .../Constraints/FormValidatorTest.php | 290 +++++------- .../Constraints/UserPasswordValidatorTest.php | 168 +++++++ .../Validator/Constraints/AllValidator.php | 4 +- .../Validator/Constraints/ChoiceValidator.php | 4 +- .../Constraints/CollectionValidator.php | 4 +- .../AbstractComparisonValidatorTestCase.php | 51 +- .../AbstractConstraintValidatorTest.php | 194 ++++++++ .../Tests/Constraints/AllValidatorTest.php | 57 +-- .../Tests/Constraints/BlankValidatorTest.php | 38 +- .../Constraints/CallbackValidatorTest.php | 162 ++++--- .../Constraints/CardSchemeValidatorTest.php | 44 +- .../Tests/Constraints/ChoiceValidatorTest.php | 146 +++--- .../Tests/Constraints/CollectionTest.php | 4 +- ...llectionValidatorCustomArrayObjectTest.php | 58 +-- .../Constraints/CollectionValidatorTest.php | 219 ++++----- .../CountValidatorCountableTest.php | 17 +- .../Tests/Constraints/CountValidatorTest.php | 71 +-- .../Constraints/CountryValidatorTest.php | 45 +- .../Constraints/CurrencyValidatorTest.php | 45 +- .../Constraints/DateTimeValidatorTest.php | 47 +- .../Tests/Constraints/DateValidatorTest.php | 47 +- .../Tests/Constraints/EmailValidatorTest.php | 43 +- .../Tests/Constraints/FalseValidatorTest.php | 35 +- .../Constraints/FileValidatorPathTest.php | 10 +- .../Tests/Constraints/FileValidatorTest.php | 247 ++++++---- .../Constraints/Fixtures/test_landscape.gif | Bin 0 -> 43 bytes .../Constraints/Fixtures/test_portrait.gif | Bin 0 -> 43 bytes .../Tests/Constraints/GroupSequenceTest.php | 27 ++ .../Tests/Constraints/IbanValidatorTest.php | 34 +- .../Tests/Constraints/ImageValidatorTest.php | 125 ++--- .../Tests/Constraints/IpValidatorTest.php | 165 +++---- .../Tests/Constraints/IsbnValidatorTest.php | 91 ++-- .../Tests/Constraints/IssnValidatorTest.php | 88 ++-- .../Constraints/LanguageValidatorTest.php | 50 +- .../Tests/Constraints/LengthValidatorTest.php | 79 ++-- .../Tests/Constraints/LocaleValidatorTest.php | 44 +- .../Tests/Constraints/LuhnValidatorTest.php | 45 +- .../Constraints/NotBlankValidatorTest.php | 55 +-- .../Constraints/NotNullValidatorTest.php | 30 +- .../Tests/Constraints/NullValidatorTest.php | 33 +- .../Tests/Constraints/RangeValidatorTest.php | 112 ++--- .../Tests/Constraints/RegexValidatorTest.php | 43 +- .../Tests/Constraints/TimeValidatorTest.php | 48 +- .../Tests/Constraints/TrueValidatorTest.php | 38 +- .../Tests/Constraints/TypeValidatorTest.php | 73 ++- .../Tests/Constraints/UrlValidatorTest.php | 52 +-- .../Validator/Tests/Fixtures/Countable.php | 27 ++ .../Tests/Fixtures/CustomArrayObject.php | 70 +++ .../Fixtures/StubGlobalExecutionContext.php | 69 +++ 51 files changed, 2137 insertions(+), 2162 deletions(-) create mode 100644 src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php delete mode 100644 src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueValidatorTest.php create mode 100644 src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.php create mode 100644 src/Symfony/Component/Validator/Tests/Constraints/AbstractConstraintValidatorTest.php create mode 100644 src/Symfony/Component/Validator/Tests/Constraints/Fixtures/test_landscape.gif create mode 100644 src/Symfony/Component/Validator/Tests/Constraints/Fixtures/test_portrait.gif create mode 100644 src/Symfony/Component/Validator/Tests/Constraints/GroupSequenceTest.php create mode 100644 src/Symfony/Component/Validator/Tests/Fixtures/Countable.php create mode 100644 src/Symfony/Component/Validator/Tests/Fixtures/CustomArrayObject.php create mode 100644 src/Symfony/Component/Validator/Tests/Fixtures/StubGlobalExecutionContext.php diff --git a/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php b/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php new file mode 100644 index 0000000000..44dfc853df --- /dev/null +++ b/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueEntityValidatorTest.php @@ -0,0 +1,414 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Bridge\Doctrine\Tests\Validator\Constraints; + +use Doctrine\Common\Persistence\ManagerRegistry; +use Doctrine\Common\Persistence\ObjectManager; +use Doctrine\Common\Persistence\ObjectRepository; +use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper; +use Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity; +use Symfony\Component\Validator\Tests\Constraints\AbstractConstraintValidatorTest; +use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity; +use Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNameEntity; +use Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity; +use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; +use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator; +use Symfony\Component\Validator\Validator; +use Doctrine\ORM\Tools\SchemaTool; + +/** + * @author Bernhard Schussek + */ +class UniqueEntityValidatorTest extends AbstractConstraintValidatorTest +{ + const EM_NAME = 'foo'; + + /** + * @var ObjectManager + */ + protected $em; + + /** + * @var ManagerRegistry + */ + protected $registry; + + /** + * @var ObjectRepository + */ + protected $repository; + + protected function setUp() + { + $this->em = DoctrineTestHelper::createTestEntityManager(); + $this->registry = $this->createRegistryMock($this->em); + $this->createSchema($this->em); + + parent::setUp(); + } + + protected function createRegistryMock(ObjectManager $em = null) + { + $registry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry'); + $registry->expects($this->any()) + ->method('getManager') + ->with($this->equalTo(self::EM_NAME)) + ->will($this->returnValue($em)); + + return $registry; + } + + protected function createRepositoryMock() + { + $repository = $this->getMockBuilder('Doctrine\Common\Persistence\ObjectRepository') + ->setMethods(array('findByCustom', 'find', 'findAll', 'findOneBy', 'findBy', 'getClassName')) + ->getMock() + ; + + return $repository; + } + + protected function createEntityManagerMock($repositoryMock) + { + $em = $this->getMockBuilder('Doctrine\Common\Persistence\ObjectManager') + ->getMock() + ; + $em->expects($this->any()) + ->method('getRepository') + ->will($this->returnValue($repositoryMock)) + ; + + $classMetadata = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata'); + $classMetadata + ->expects($this->any()) + ->method('hasField') + ->will($this->returnValue(true)) + ; + $reflParser = $this->getMockBuilder('Doctrine\Common\Reflection\StaticReflectionParser') + ->disableOriginalConstructor() + ->getMock() + ; + $refl = $this->getMockBuilder('Doctrine\Common\Reflection\StaticReflectionProperty') + ->setConstructorArgs(array($reflParser, 'property-name')) + ->setMethods(array('getValue')) + ->getMock() + ; + $refl + ->expects($this->any()) + ->method('getValue') + ->will($this->returnValue(true)) + ; + $classMetadata->reflFields = array('name' => $refl); + $em->expects($this->any()) + ->method('getClassMetadata') + ->will($this->returnValue($classMetadata)) + ; + + return $em; + } + + protected function createValidator() + { + return new UniqueEntityValidator($this->registry); + } + + private function createSchema(ObjectManager $em) + { + $schemaTool = new SchemaTool($em); + $schemaTool->createSchema(array( + $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity'), + $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNameEntity'), + $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity'), + $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity'), + )); + } + + /** + * This is a functional test as there is a large integration necessary to get the validator working. + */ + public function testValidateUniqueness() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('name'), + 'em' => self::EM_NAME, + )); + + $entity1 = new SingleIntIdEntity(1, 'Foo'); + $entity2 = new SingleIntIdEntity(2, 'Foo'); + + $this->validator->validate($entity1, $constraint); + + $this->assertNoViolation(); + + $this->em->persist($entity1); + $this->em->flush(); + + $this->validator->validate($entity1, $constraint); + + $this->assertNoViolation(); + + $this->validator->validate($entity2, $constraint); + + $this->assertViolation('myMessage', array(), 'property.path.name', 'Foo'); + } + + public function testValidateCustomErrorPath() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('name'), + 'em' => self::EM_NAME, + 'errorPath' => 'bar', + )); + + $entity1 = new SingleIntIdEntity(1, 'Foo'); + $entity2 = new SingleIntIdEntity(2, 'Foo'); + + $this->em->persist($entity1); + $this->em->flush(); + + $this->validator->validate($entity2, $constraint); + + $this->assertViolation('myMessage', array(), 'property.path.bar', 'Foo'); + } + + public function testValidateUniquenessWithNull() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('name'), + 'em' => self::EM_NAME, + )); + + $entity1 = new SingleIntIdEntity(1, null); + $entity2 = new SingleIntIdEntity(2, null); + + $this->em->persist($entity1); + $this->em->persist($entity2); + $this->em->flush(); + + $this->validator->validate($entity1, $constraint); + + $this->assertNoViolation(); + } + + public function testValidateUniquenessWithIgnoreNull() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('name', 'name2'), + 'em' => self::EM_NAME, + 'ignoreNull' => false, + )); + + $entity1 = new DoubleNameEntity(1, 'Foo', null); + $entity2 = new DoubleNameEntity(2, 'Foo', null); + + $this->validator->validate($entity1, $constraint); + + $this->assertNoViolation(); + + $this->em->persist($entity1); + $this->em->flush(); + + $this->validator->validate($entity1, $constraint); + + $this->assertNoViolation(); + + $this->validator->validate($entity2, $constraint); + + $this->assertViolation('myMessage', array(), 'property.path.name', 'Foo'); + } + + public function testValidateUniquenessUsingCustomRepositoryMethod() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('name'), + 'em' => self::EM_NAME, + 'repositoryMethod' => 'findByCustom', + )); + + $repository = $this->createRepositoryMock(); + $repository->expects($this->once()) + ->method('findByCustom') + ->will($this->returnValue(array())) + ; + $this->em = $this->createEntityManagerMock($repository); + $this->registry = $this->createRegistryMock($this->em); + $this->validator = $this->createValidator(); + $this->validator->initialize($this->context); + + $entity1 = new SingleIntIdEntity(1, 'foo'); + + $this->validator->validate($entity1, $constraint); + + $this->assertNoViolation(); + } + + public function testValidateUniquenessWithUnrewoundArray() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('name'), + 'em' => self::EM_NAME, + 'repositoryMethod' => 'findByCustom', + )); + + $entity = new SingleIntIdEntity(1, 'foo'); + + $repository = $this->createRepositoryMock(); + $repository->expects($this->once()) + ->method('findByCustom') + ->will( + $this->returnCallback(function () use ($entity) { + $returnValue = array( + $entity, + ); + next($returnValue); + + return $returnValue; + }) + ) + ; + $this->em = $this->createEntityManagerMock($repository); + $this->registry = $this->createRegistryMock($this->em); + $this->validator = $this->createValidator(); + $this->validator->initialize($this->context); + + $this->validator->validate($entity, $constraint); + + $this->assertNoViolation(); + } + + /** + * @group GH-1635 + */ + public function testAssociatedEntity() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('single'), + 'em' => self::EM_NAME, + )); + + $entity1 = new SingleIntIdEntity(1, 'foo'); + $associated = new AssociationEntity(); + $associated->single = $entity1; + $associated2 = new AssociationEntity(); + $associated2->single = $entity1; + + $this->em->persist($entity1); + $this->em->persist($associated); + $this->em->flush(); + + $this->validator->validate($associated, $constraint); + + $this->assertNoViolation(); + + $this->em->persist($associated2); + $this->em->flush(); + + $this->validator->validate($associated2, $constraint); + + $this->assertViolation('myMessage', array(), 'property.path.single', 1); + } + + public function testAssociatedEntityWithNull() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('single'), + 'em' => self::EM_NAME, + 'ignoreNull' => false, + )); + + $associated = new AssociationEntity(); + $associated->single = null; + + $this->em->persist($associated); + $this->em->flush(); + + $this->validator->validate($associated, $constraint); + + $this->assertNoViolation(); + } + + /** + * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException + * @expectedExceptionMessage Associated entities are not allowed to have more than one identifier field + * @group GH-1635 + */ + public function testAssociatedCompositeEntity() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('composite'), + 'em' => self::EM_NAME, + )); + + $composite = new CompositeIntIdEntity(1, 1, "test"); + $associated = new AssociationEntity(); + $associated->composite = $composite; + + $this->em->persist($composite); + $this->em->persist($associated); + $this->em->flush(); + + $this->validator->validate($associated, $constraint); + } + + /** + * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException + * @expectedExceptionMessage Object manager "foo" does not exist. + */ + public function testDedicatedEntityManagerNullObject() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('name'), + 'em' => self::EM_NAME, + )); + + $this->em = null; + $this->registry = $this->createRegistryMock($this->em); + $this->validator = $this->createValidator(); + $this->validator->initialize($this->context); + + $entity = new SingleIntIdEntity(1, null); + + $this->validator->validate($entity, $constraint); + } + + /** + * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException + * @expectedExceptionMessage Unable to find the object manager associated with an entity of class "Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity" + */ + public function testEntityManagerNullObject() + { + $constraint = new UniqueEntity(array( + 'message' => 'myMessage', + 'fields' => array('name'), + // no "em" option set + )); + + $this->em = null; + $this->registry = $this->createRegistryMock($this->em); + $this->validator = $this->createValidator(); + $this->validator->initialize($this->context); + + $entity = new SingleIntIdEntity(1, null); + + $this->validator->validate($entity, $constraint); + } +} diff --git a/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueValidatorTest.php b/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueValidatorTest.php deleted file mode 100644 index 9980802642..0000000000 --- a/src/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueValidatorTest.php +++ /dev/null @@ -1,437 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bridge\Doctrine\Tests\Validator\Constraints; - -use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper; -use Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity; -use Symfony\Component\Validator\DefaultTranslator; -use Symfony\Component\Validator\Tests\Fixtures\FakeMetadataFactory; -use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity; -use Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNameEntity; -use Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity; -use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; -use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator; -use Symfony\Component\Validator\Mapping\ClassMetadata; -use Symfony\Component\Validator\Validator; -use Doctrine\ORM\Tools\SchemaTool; - -class UniqueValidatorTest extends \PHPUnit_Framework_TestCase -{ - protected function setUp() - { - parent::setUp(); - - if (!class_exists('Symfony\Component\Security\Core\SecurityContext')) { - $this->markTestSkipped('The "Security" component is not available'); - } - - if (!class_exists('Symfony\Component\Validator\Constraint')) { - $this->markTestSkipped('The "Validator" component is not available'); - } - } - - protected function createRegistryMock($entityManagerName, $em) - { - $registry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry'); - $registry->expects($this->any()) - ->method('getManager') - ->with($this->equalTo($entityManagerName)) - ->will($this->returnValue($em)); - - return $registry; - } - - protected function createRepositoryMock() - { - $repository = $this->getMockBuilder('Doctrine\Common\Persistence\ObjectRepository') - ->setMethods(array('findByCustom', 'find', 'findAll', 'findOneBy', 'findBy', 'getClassName')) - ->getMock() - ; - - return $repository; - } - - protected function createEntityManagerMock($repositoryMock) - { - $em = $this->getMockBuilder('Doctrine\Common\Persistence\ObjectManager') - ->getMock() - ; - $em->expects($this->any()) - ->method('getRepository') - ->will($this->returnValue($repositoryMock)) - ; - - $classMetadata = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata'); - $classMetadata - ->expects($this->any()) - ->method('hasField') - ->will($this->returnValue(true)) - ; - $reflParser = $this->getMockBuilder('Doctrine\Common\Reflection\StaticReflectionParser') - ->disableOriginalConstructor() - ->getMock() - ; - $refl = $this->getMockBuilder('Doctrine\Common\Reflection\StaticReflectionProperty') - ->setConstructorArgs(array($reflParser, 'property-name')) - ->setMethods(array('getValue')) - ->getMock() - ; - $refl - ->expects($this->any()) - ->method('getValue') - ->will($this->returnValue(true)) - ; - $classMetadata->reflFields = array('name' => $refl); - $em->expects($this->any()) - ->method('getClassMetadata') - ->will($this->returnValue($classMetadata)) - ; - - return $em; - } - - protected function createValidatorFactory($uniqueValidator) - { - $validatorFactory = $this->getMock('Symfony\Component\Validator\ConstraintValidatorFactoryInterface'); - $validatorFactory->expects($this->any()) - ->method('getInstance') - ->with($this->isInstanceOf('Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity')) - ->will($this->returnValue($uniqueValidator)); - - return $validatorFactory; - } - - public function createValidator($entityManagerName, $em, $validateClass = null, $uniqueFields = null, $errorPath = null, $repositoryMethod = 'findBy', $ignoreNull = true) - { - if (!$validateClass) { - $validateClass = 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity'; - } - if (!$uniqueFields) { - $uniqueFields = array('name'); - } - - $registry = $this->createRegistryMock($entityManagerName, $em); - - $uniqueValidator = new UniqueEntityValidator($registry); - - $metadata = new ClassMetadata($validateClass); - $constraint = new UniqueEntity(array( - 'fields' => $uniqueFields, - 'em' => $entityManagerName, - 'errorPath' => $errorPath, - 'repositoryMethod' => $repositoryMethod, - 'ignoreNull' => $ignoreNull - )); - $metadata->addConstraint($constraint); - - $metadataFactory = new FakeMetadataFactory(); - $metadataFactory->addMetadata($metadata); - $validatorFactory = $this->createValidatorFactory($uniqueValidator); - - return new Validator($metadataFactory, $validatorFactory, new DefaultTranslator()); - } - - private function createSchema($em) - { - $schemaTool = new SchemaTool($em); - $schemaTool->createSchema(array( - $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity'), - $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNameEntity'), - $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity'), - $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity'), - )); - } - - /** - * This is a functional test as there is a large integration necessary to get the validator working. - */ - public function testValidateUniqueness() - { - $entityManagerName = "foo"; - $em = DoctrineTestHelper::createTestEntityManager(); - $this->createSchema($em); - $validator = $this->createValidator($entityManagerName, $em); - - $entity1 = new SingleIntIdEntity(1, 'Foo'); - $violationsList = $validator->validate($entity1); - $this->assertEquals(0, $violationsList->count(), "No violations found on entity before it is saved to the database."); - - $em->persist($entity1); - $em->flush(); - - $violationsList = $validator->validate($entity1); - $this->assertEquals(0, $violationsList->count(), "No violations found on entity after it was saved to the database."); - - $entity2 = new SingleIntIdEntity(2, 'Foo'); - - $violationsList = $validator->validate($entity2); - $this->assertEquals(1, $violationsList->count(), "Violation found on entity with conflicting entity existing in the database."); - - $violation = $violationsList[0]; - $this->assertEquals('This value is already used.', $violation->getMessage()); - $this->assertEquals('name', $violation->getPropertyPath()); - $this->assertEquals('Foo', $violation->getInvalidValue()); - } - - public function testValidateCustomErrorPath() - { - $entityManagerName = "foo"; - $em = DoctrineTestHelper::createTestEntityManager(); - $this->createSchema($em); - $validator = $this->createValidator($entityManagerName, $em, null, null, 'bar'); - - $entity1 = new SingleIntIdEntity(1, 'Foo'); - - $em->persist($entity1); - $em->flush(); - - $entity2 = new SingleIntIdEntity(2, 'Foo'); - - $violationsList = $validator->validate($entity2); - $this->assertEquals(1, $violationsList->count(), "Violation found on entity with conflicting entity existing in the database."); - - $violation = $violationsList[0]; - $this->assertEquals('This value is already used.', $violation->getMessage()); - $this->assertEquals('bar', $violation->getPropertyPath()); - $this->assertEquals('Foo', $violation->getInvalidValue()); - } - - public function testValidateUniquenessWithNull() - { - $entityManagerName = "foo"; - $em = DoctrineTestHelper::createTestEntityManager(); - $this->createSchema($em); - $validator = $this->createValidator($entityManagerName, $em); - - $entity1 = new SingleIntIdEntity(1, null); - $entity2 = new SingleIntIdEntity(2, null); - - $em->persist($entity1); - $em->persist($entity2); - $em->flush(); - - $violationsList = $validator->validate($entity1); - $this->assertEquals(0, $violationsList->count(), "No violations found on entity having a null value."); - } - - public function testValidateUniquenessWithIgnoreNull() - { - $entityManagerName = "foo"; - $validateClass = 'Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNameEntity'; - $em = DoctrineTestHelper::createTestEntityManager(); - $this->createSchema($em); - $validator = $this->createValidator($entityManagerName, $em, $validateClass, array('name', 'name2'), 'bar', 'findby', false); - - $entity1 = new DoubleNameEntity(1, 'Foo', null); - $violationsList = $validator->validate($entity1); - $this->assertEquals(0, $violationsList->count(), "No violations found on entity before it is saved to the database."); - - $em->persist($entity1); - $em->flush(); - - $violationsList = $validator->validate($entity1); - $this->assertEquals(0, $violationsList->count(), "No violations found on entity after it was saved to the database."); - - $entity2 = new DoubleNameEntity(2, 'Foo', null); - - $violationsList = $validator->validate($entity2); - $this->assertEquals(1, $violationsList->count(), "Violation found on entity with conflicting entity existing in the database."); - - $violation = $violationsList[0]; - $this->assertEquals('This value is already used.', $violation->getMessage()); - $this->assertEquals('bar', $violation->getPropertyPath()); - $this->assertEquals('Foo', $violation->getInvalidValue()); - } - - public function testValidateUniquenessAfterConsideringMultipleQueryResults() - { - $entityManagerName = "foo"; - $em = DoctrineTestHelper::createTestEntityManager(); - $this->createSchema($em); - $validator = $this->createValidator($entityManagerName, $em); - - $entity1 = new SingleIntIdEntity(1, 'foo'); - $entity2 = new SingleIntIdEntity(2, 'foo'); - - $em->persist($entity1); - $em->persist($entity2); - $em->flush(); - - $violationsList = $validator->validate($entity1); - $this->assertEquals(1, $violationsList->count(), 'Violation found on entity with conflicting entity existing in the database.'); - - $violationsList = $validator->validate($entity2); - $this->assertEquals(1, $violationsList->count(), 'Violation found on entity with conflicting entity existing in the database.'); - } - - public function testValidateUniquenessUsingCustomRepositoryMethod() - { - $entityManagerName = 'foo'; - $repository = $this->createRepositoryMock(); - $repository->expects($this->once()) - ->method('findByCustom') - ->will($this->returnValue(array())) - ; - $em = $this->createEntityManagerMock($repository); - $validator = $this->createValidator($entityManagerName, $em, null, array(), null, 'findByCustom'); - - $entity1 = new SingleIntIdEntity(1, 'foo'); - - $violationsList = $validator->validate($entity1); - $this->assertEquals(0, $violationsList->count(), 'Violation is using custom repository method.'); - } - - public function testValidateUniquenessWithUnrewoundArray() - { - $entity = new SingleIntIdEntity(1, 'foo'); - - $entityManagerName = 'foo'; - $repository = $this->createRepositoryMock(); - $repository->expects($this->once()) - ->method('findByCustom') - ->will( - $this->returnCallback(function () use ($entity) { - $returnValue = array( - $entity, - ); - next($returnValue); - - return $returnValue; - }) - ) - ; - $em = $this->createEntityManagerMock($repository); - $validator = $this->createValidator($entityManagerName, $em, null, array(), null, 'findByCustom'); - - $violationsList = $validator->validate($entity); - $this->assertCount(0, $violationsList, 'Violation is using unrewound array as return value in the repository method.'); - } - - /** - * @group GH-1635 - */ - public function testAssociatedEntity() - { - $entityManagerName = "foo"; - $em = DoctrineTestHelper::createTestEntityManager(); - $this->createSchema($em); - $validator = $this->createValidator($entityManagerName, $em, 'Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity', array('single')); - - $entity1 = new SingleIntIdEntity(1, 'foo'); - $associated = new AssociationEntity(); - $associated->single = $entity1; - - $em->persist($entity1); - $em->persist($associated); - $em->flush(); - - $violationsList = $validator->validate($associated); - $this->assertEquals(0, $violationsList->count()); - - $associated2 = new AssociationEntity(); - $associated2->single = $entity1; - - $em->persist($associated2); - $em->flush(); - - $violationsList = $validator->validate($associated2); - $this->assertEquals(1, $violationsList->count()); - } - - public function testAssociatedEntityWithNull() - { - $entityManagerName = "foo"; - $em = DoctrineTestHelper::createTestEntityManager(); - $this->createSchema($em); - $validator = $this->createValidator($entityManagerName, $em, 'Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity', array('single'), null, 'findBy', false); - - $associated = new AssociationEntity(); - $associated->single = null; - - $em->persist($associated); - $em->flush(); - - $violationsList = $validator->validate($associated); - $this->assertEquals(0, $violationsList->count()); - } - - /** - * @group GH-1635 - */ - public function testAssociatedCompositeEntity() - { - $entityManagerName = "foo"; - $em = DoctrineTestHelper::createTestEntityManager(); - $this->createSchema($em); - $validator = $this->createValidator($entityManagerName, $em, 'Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity', array('composite')); - - $composite = new CompositeIntIdEntity(1, 1, "test"); - $associated = new AssociationEntity(); - $associated->composite = $composite; - - $em->persist($composite); - $em->persist($associated); - $em->flush(); - - $this->setExpectedException( - 'Symfony\Component\Validator\Exception\ConstraintDefinitionException', - 'Associated entities are not allowed to have more than one identifier field' - ); - $violationsList = $validator->validate($associated); - } - - public function testDedicatedEntityManagerNullObject() - { - $uniqueFields = array('name'); - $entityManagerName = 'foo'; - - $registry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry'); - - $constraint = new UniqueEntity(array( - 'fields' => $uniqueFields, - 'em' => $entityManagerName, - )); - - $uniqueValidator = new UniqueEntityValidator($registry); - - $entity = new SingleIntIdEntity(1, null); - - $this->setExpectedException( - 'Symfony\Component\Validator\Exception\ConstraintDefinitionException', - 'Object manager "foo" does not exist.' - ); - - $uniqueValidator->validate($entity, $constraint); - } - - public function testEntityManagerNullObject() - { - $uniqueFields = array('name'); - - $registry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry'); - - $constraint = new UniqueEntity(array( - 'fields' => $uniqueFields, - )); - - $uniqueValidator = new UniqueEntityValidator($registry); - - $entity = new SingleIntIdEntity(1, null); - - $this->setExpectedException( - 'Symfony\Component\Validator\Exception\ConstraintDefinitionException', - 'Unable to find the object manager associated with an entity of class "Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity"' - ); - - $uniqueValidator->validate($entity, $constraint); - } -} diff --git a/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorTest.php b/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorTest.php index dc504172a0..bfb84a15f8 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorTest.php @@ -21,11 +21,12 @@ use Symfony\Component\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 */ -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(); } /** diff --git a/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.php b/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.php new file mode 100644 index 0000000000..8b3eb53a2c --- /dev/null +++ b/src/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.php @@ -0,0 +1,168 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Security\Core\Tests\Validator\Constraints; + +use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface; +use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface; +use Symfony\Component\Security\Core\SecurityContextInterface; +use Symfony\Component\Security\Core\Validator\Constraints\UserPassword; +use Symfony\Component\Security\Core\Validator\Constraints\UserPasswordValidator; +use Symfony\Component\Validator\Tests\Constraints\AbstractConstraintValidatorTest; + +/** + * @author Bernhard Schussek + */ +class UserPasswordValidatorTest extends AbstractConstraintValidatorTest +{ + const PASSWORD = 's3Cr3t'; + + const SALT = '^S4lt$'; + + /** + * @var SecurityContextInterface + */ + protected $securityContext; + + /** + * @var PasswordEncoderInterface + */ + protected $encoder; + + /** + * @var EncoderFactoryInterface + */ + protected $encoderFactory; + + protected function createValidator() + { + return new UserPasswordValidator($this->securityContext, $this->encoderFactory); + } + + protected function setUp() + { + $user = $this->createUser(); + $this->securityContext = $this->createSecurityContext($user); + $this->encoder = $this->createPasswordEncoder(); + $this->encoderFactory = $this->createEncoderFactory($this->encoder); + + parent::setUp(); + } + + public function testPasswordIsValid() + { + $constraint = new UserPassword(array( + 'message' => 'myMessage', + )); + + $this->encoder->expects($this->once()) + ->method('isPasswordValid') + ->with(static::PASSWORD, 'secret', static::SALT) + ->will($this->returnValue(true)); + + $this->validator->validate('secret', $constraint); + + $this->assertNoViolation(); + } + + public function testPasswordIsNotValid() + { + $constraint = new UserPassword(array( + 'message' => 'myMessage', + )); + + $this->encoder->expects($this->once()) + ->method('isPasswordValid') + ->with(static::PASSWORD, 'secret', static::SALT) + ->will($this->returnValue(false)); + + $this->validator->validate('secret', $constraint); + + $this->assertViolation('myMessage'); + } + + /** + * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException + */ + public function testUserIsNotValid() + { + $user = $this->getMock('Foo\Bar\User'); + + $this->securityContext = $this->createSecurityContext($user); + $this->validator = $this->createValidator(); + $this->validator->initialize($this->context); + + $this->validator->validate('secret', new UserPassword()); + } + + protected function createUser() + { + $mock = $this->getMock('Symfony\Component\Security\Core\User\UserInterface'); + + $mock + ->expects($this->any()) + ->method('getPassword') + ->will($this->returnValue(static::PASSWORD)) + ; + + $mock + ->expects($this->any()) + ->method('getSalt') + ->will($this->returnValue(static::SALT)) + ; + + return $mock; + } + + protected function createPasswordEncoder($isPasswordValid = true) + { + return $this->getMock('Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface'); + } + + protected function createEncoderFactory($encoder = null) + { + $mock = $this->getMock('Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface'); + + $mock + ->expects($this->any()) + ->method('getEncoder') + ->will($this->returnValue($encoder)) + ; + + return $mock; + } + + protected function createSecurityContext($user = null) + { + $token = $this->createAuthenticationToken($user); + + $mock = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface'); + $mock + ->expects($this->any()) + ->method('getToken') + ->will($this->returnValue($token)) + ; + + return $mock; + } + + protected function createAuthenticationToken($user = null) + { + $mock = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'); + $mock + ->expects($this->any()) + ->method('getUser') + ->will($this->returnValue($user)) + ; + + return $mock; + } +} diff --git a/src/Symfony/Component/Validator/Constraints/AllValidator.php b/src/Symfony/Component/Validator/Constraints/AllValidator.php index 2ffb8bf16f..469d2a4214 100644 --- a/src/Symfony/Component/Validator/Constraints/AllValidator.php +++ b/src/Symfony/Component/Validator/Constraints/AllValidator.php @@ -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); } } } diff --git a/src/Symfony/Component/Validator/Constraints/ChoiceValidator.php b/src/Symfony/Component/Validator/Constraints/ChoiceValidator.php index 2e0658cfa6..79081fee49 100644 --- a/src/Symfony/Component/Validator/Constraints/ChoiceValidator.php +++ b/src/Symfony/Component/Validator/Constraints/ChoiceValidator.php @@ -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; } diff --git a/src/Symfony/Component/Validator/Constraints/CollectionValidator.php b/src/Symfony/Component/Validator/Constraints/CollectionValidator.php index a322ef49ad..33f839d3b9 100644 --- a/src/Symfony/Component/Validator/Constraints/CollectionValidator.php +++ b/src/Symfony/Component/Validator/Constraints/CollectionValidator.php @@ -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) diff --git a/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php b/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php index a1c573baa4..a56f734554 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.php @@ -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 */ -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 + )); } /** diff --git a/src/Symfony/Component/Validator/Tests/Constraints/AbstractConstraintValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/AbstractConstraintValidatorTest.php new file mode 100644 index 0000000000..bc4e1c214a --- /dev/null +++ b/src/Symfony/Component/Validator/Tests/Constraints/AbstractConstraintValidatorTest.php @@ -0,0 +1,194 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Validator\Tests\Constraints; + +use Symfony\Component\Validator\ConstraintValidatorInterface; +use Symfony\Component\Validator\ConstraintViolation; +use Symfony\Component\Validator\Context\ExecutionContext; +use Symfony\Component\Validator\Context\ExecutionContextInterface; +use Symfony\Component\Validator\Mapping\ClassMetadata; +use Symfony\Component\Validator\Mapping\PropertyMetadata; +use Symfony\Component\Validator\Tests\Fixtures\StubGlobalExecutionContext; + +/** + * @since 2.5.3 + * @author Bernhard Schussek + */ +abstract class AbstractConstraintValidatorTest extends \PHPUnit_Framework_TestCase +{ + /** + * @var ExecutionContextInterface + */ + protected $context; + + /** + * @var ConstraintValidatorInterface + */ + protected $validator; + + protected $group; + + protected $metadata; + + protected $object; + + protected $value; + + protected $root; + + protected $propertyPath; + + protected function setUp() + { + $this->group = 'MyGroup'; + $this->metadata = null; + $this->object = null; + $this->value = 'InvalidValue'; + $this->root = 'root'; + $this->propertyPath = 'property.path'; + $this->context = $this->createContext(); + $this->validator = $this->createValidator(); + $this->validator->initialize($this->context); + + \Locale::setDefault('en'); + } + + protected function createContext() + { + $translator = $this->getMock('Symfony\Component\Translation\TranslatorInterface'); + + return $this->getMockBuilder('Symfony\Component\Validator\ExecutionContext') + ->setConstructorArgs(array( + new StubGlobalExecutionContext($this->root), + $translator, + null, + $this->metadata, + $this->value, + $this->group, + $this->propertyPath + )) + ->setMethods(array('validate', 'validateValue')) + ->getMock(); + } + + protected function createViolation($message, array $parameters = array(), $propertyPath = 'property.path', $invalidValue = 'InvalidValue', $plural = null, $code = null) + { + return new ConstraintViolation( + null, + $message, + $parameters, + $this->root, + $propertyPath, + $invalidValue, + $plural, + $code + ); + } + + protected function setGroup($group) + { + $this->group = $group; + $this->context = $this->createContext(); + $this->validator->initialize($this->context); + } + + protected function setObject($object) + { + $this->object = $object; + $this->metadata = is_object($object) + ? new ClassMetadata(get_class($object)) + : null; + $this->context = $this->createContext(); + $this->validator->initialize($this->context); + } + + protected function setProperty($object, $property) + { + $this->object = $object; + $this->metadata = is_object($object) + ? new PropertyMetadata(get_class($object), $property) + : null; + $this->context = $this->createContext(); + $this->validator->initialize($this->context); + } + + protected function setValue($value) + { + $this->value = $value; + $this->context = $this->createContext(); + $this->validator->initialize($this->context); + } + + protected function setRoot($root) + { + $this->root = $root; + $this->context = $this->createContext(); + $this->validator->initialize($this->context); + } + + protected function setPropertyPath($propertyPath) + { + $this->propertyPath = $propertyPath; + $this->context = $this->createContext(); + $this->validator->initialize($this->context); + } + + protected function expectNoValidate() + { + $this->context->expects($this->never()) + ->method('validate'); + $this->context->expects($this->never()) + ->method('validateValue'); + } + + protected function expectValidateAt($i, $propertyPath, $value, $group) + { + $this->context->expects($this->at($i)) + ->method('validate') + ->with($value, $propertyPath, $group); + } + + protected function expectValidateValueAt($i, $propertyPath, $value, $constraints, $group) + { + $this->context->expects($this->at($i)) + ->method('validateValue') + ->with($value, $constraints, $propertyPath, $group); + } + + protected function assertNoViolation() + { + $this->assertCount(0, $this->context->getViolations()); + } + + protected function assertViolation($message, array $parameters = array(), $propertyPath = 'property.path', $invalidValue = 'InvalidValue', $plural = null, $code = null) + { + $violations = $this->context->getViolations(); + + $this->assertCount(1, $violations); + $this->assertEquals($this->createViolation($message, $parameters, $propertyPath, $invalidValue, $plural, $code), $violations[0]); + } + + protected function assertViolations(array $expected) + { + $violations = $this->context->getViolations(); + + $this->assertCount(count($expected), $violations); + + $i = 0; + + foreach ($expected as $violation) { + $this->assertEquals($violation, $violations[$i++]); + } + } + + abstract protected function createValidator(); +} diff --git a/src/Symfony/Component/Validator/Tests/Constraints/AllValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/AllValidatorTest.php index eaa9044e9e..d9ffd9814c 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/AllValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/AllValidatorTest.php @@ -11,40 +11,23 @@ namespace Symfony\Component\Validator\Tests\Constraints; -use Symfony\Component\Validator\ExecutionContext; -use Symfony\Component\Validator\Constraints\Range; -use Symfony\Component\Validator\Constraints\NotNull; use Symfony\Component\Validator\Constraints\All; use Symfony\Component\Validator\Constraints\AllValidator; +use Symfony\Component\Validator\Constraints\NotNull; +use Symfony\Component\Validator\Constraints\Range; -class AllValidatorTest extends \PHPUnit_Framework_TestCase +class AllValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() + 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() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/BlankValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/BlankValidatorTest.php index fe4a30b638..1d83d10b0f 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/BlankValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/BlankValidatorTest.php @@ -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() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CallbackValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CallbackValidatorTest.php index 4d248c13c8..038f1a3911 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CallbackValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CallbackValidatorTest.php @@ -11,15 +11,16 @@ namespace Symfony\Component\Validator\Tests\Constraints; -use Symfony\Component\Validator\ExecutionContext; +use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraints\Callback; use Symfony\Component\Validator\Constraints\CallbackValidator; +use Symfony\Component\Validator\ExecutionContextInterface; class CallbackValidatorTest_Class { - public static function validateStatic($object, ExecutionContext $context) + public static function validateCallback($object, ExecutionContextInterface $context) { - $context->addViolation('Static message', array('{{ value }}' => 'foobar'), 'invalidValue'); + $context->addViolation('Callback message', array('{{ value }}' => 'foobar')); return false; } @@ -27,104 +28,121 @@ 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); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CardSchemeValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CardSchemeValidatorTest.php index ee7cc7a60a..0b3b04e067 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CardSchemeValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CardSchemeValidatorTest.php @@ -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() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php index ad524b87ea..113a31e3cf 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.php @@ -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"', + )); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CollectionTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CollectionTest.php index da868d3cfd..4b485a9b10 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CollectionTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CollectionTest.php @@ -12,9 +12,9 @@ namespace Symfony\Component\Validator\Tests\Constraints; use Symfony\Component\Validator\Constraints\Collection; -use Symfony\Component\Validator\Constraints\Required; -use Symfony\Component\Validator\Constraints\Optional; use Symfony\Component\Validator\Constraints\Email; +use Symfony\Component\Validator\Constraints\Optional; +use Symfony\Component\Validator\Constraints\Required; use Symfony\Component\Validator\Constraints\Valid; /** diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorCustomArrayObjectTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorCustomArrayObjectTest.php index ebad849b8b..3d4c29681b 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorCustomArrayObjectTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorCustomArrayObjectTest.php @@ -11,63 +11,7 @@ namespace Symfony\Component\Validator\Tests\Constraints; -/** - * This class is a hand written simplified version of PHP native `ArrayObject` - * class, to show that it behaves differently than the PHP native implementation. - */ -class CustomArrayObject implements \ArrayAccess, \IteratorAggregate, \Countable, \Serializable -{ - private $array; - - public function __construct(array $array = null) - { - $this->array = $array ?: array(); - } - - public function offsetExists($offset) - { - return array_key_exists($offset, $this->array); - } - - public function offsetGet($offset) - { - return $this->array[$offset]; - } - - public function offsetSet($offset, $value) - { - if (null === $offset) { - $this->array[] = $value; - } else { - $this->array[$offset] = $value; - } - } - - public function offsetUnset($offset) - { - unset($this->array[$offset]); - } - - public function getIterator() - { - return new \ArrayIterator($this->array); - } - - public function count() - { - return count($this->array); - } - - public function serialize() - { - return serialize($this->array); - } - - public function unserialize($serialized) - { - $this->array = (array) unserialize((string) $serialized); - } -} +use Symfony\Component\Validator\Tests\Fixtures\CustomArrayObject; class CollectionValidatorCustomArrayObjectTest extends CollectionValidatorTest { diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorTest.php index e966aadae7..8c26957e6f 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorTest.php @@ -11,57 +11,44 @@ namespace Symfony\Component\Validator\Tests\Constraints; -use Symfony\Component\Validator\Constraints\Range; -use Symfony\Component\Validator\Constraints\NotNull; -use Symfony\Component\Validator\Constraints\Required; -use Symfony\Component\Validator\Constraints\Optional; use Symfony\Component\Validator\Constraints\Collection; use Symfony\Component\Validator\Constraints\CollectionValidator; +use Symfony\Component\Validator\Constraints\NotNull; +use Symfony\Component\Validator\Constraints\Optional; +use Symfony\Component\Validator\Constraints\Range; +use Symfony\Component\Validator\Constraints\Required; -abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase +abstract class CollectionValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; - - protected function setUp() + protected function createValidator() { - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new CollectionValidator(); - $this->validator->initialize($this->context); - - $this->context->expects($this->any()) - ->method('getGroup') - ->will($this->returnValue('MyGroup')); - } - - protected function tearDown() - { - $this->context = null; - $this->validator = null; + return new CollectionValidator(); } abstract protected function prepareTestData(array $contents); public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolationAt'); - $this->validator->validate(null, new Collection(array('fields' => array( 'foo' => new Range(array('min' => 4)), )))); + + $this->assertNoViolation(); } public function testFieldsAsDefaultOption() { + $constraint = new Range(array('min' => 4)); + $data = $this->prepareTestData(array('foo' => 'foobar')); - $this->context->expects($this->never()) - ->method('addViolationAt'); + $this->expectValidateValueAt(0, '[foo]', $data['foo'], array($constraint), 'MyGroup'); $this->validator->validate($data, new Collection(array( - 'foo' => new Range(array('min' => 4)), + 'foo' => $constraint, ))); + + $this->assertNoViolation(); } /** @@ -82,25 +69,23 @@ 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, ) ))); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorCountableTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorCountableTest.php index ec4d8dec71..7d46967bde 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorCountableTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorCountableTest.php @@ -11,20 +11,7 @@ namespace Symfony\Component\Validator\Tests\Constraints; -class CountValidatorCountableTest_Countable implements \Countable -{ - private $content; - - public function __construct(array $content) - { - $this->content = $content; - } - - public function count() - { - return count($this->content); - } -} +use Symfony\Component\Validator\Tests\Fixtures\Countable; /** * @author Bernhard Schussek @@ -33,6 +20,6 @@ class CountValidatorCountableTest extends CountValidatorTest { protected function createCollection(array $content) { - return new CountValidatorCountableTest_Countable($content); + return new Countable($content); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorTest.php index 9c4a38d56c..c910c1156c 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CountValidatorTest.php @@ -17,32 +17,20 @@ use Symfony\Component\Validator\Constraints\CountValidator; /** * @author Bernhard Schussek */ -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() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.php index 5fabee67fb..a080852c2a 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.php @@ -15,40 +15,32 @@ use Symfony\Component\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(); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CurrencyValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CurrencyValidatorTest.php index ea6c2eb43a..99636e6ca4 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CurrencyValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CurrencyValidatorTest.php @@ -15,40 +15,32 @@ use Symfony\Component\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() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.php index 46079a8155..5addbf34de 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.php @@ -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() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/DateValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/DateValidatorTest.php index a62426ec8a..8fdacee94d 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/DateValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/DateValidatorTest.php @@ -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() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php index 4b7a8bd6c3..e4722e159e 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.php @@ -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'), ); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/FalseValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/FalseValidatorTest.php index 22ab63a9e2..e9abbb9a38 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/FalseValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/FalseValidatorTest.php @@ -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' + )); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorPathTest.php b/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorPathTest.php index 7701d7faf4..f1f8db692a 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorPathTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorPathTest.php @@ -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"', + )); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php index 47952f061c..6c8cb8abbb 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.php @@ -11,54 +11,63 @@ namespace Symfony\Component\Validator\Tests\Constraints; +use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\Validator\Constraints\File; use Symfony\Component\Validator\Constraints\FileValidator; -use Symfony\Component\HttpFoundation\File\UploadedFile; +use Symfony\Component\Validator\Validation; -abstract class FileValidatorTest extends \PHPUnit_Framework_TestCase +abstract class FileValidatorTest extends AbstractConstraintValidatorTest { - protected $context; - protected $validator; protected $path; + protected $file; + protected function getApiVersion() + { + return Validation::API_VERSION_2_5; + } + + protected function createValidator() + { + return new FileValidator(); + } + protected function setUp() { - if (!class_exists('Symfony\Component\HttpFoundation\File\UploadedFile')) { - $this->markTestSkipped('The "HttpFoundation" component is not available'); - } + parent::setUp(); - $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false); - $this->validator = new FileValidator(); - $this->validator->initialize($this->context); $this->path = sys_get_temp_dir().DIRECTORY_SEPARATOR.'FileValidatorTest'; $this->file = fopen($this->path, 'w'); } protected function tearDown() { - fclose($this->file); + parent::tearDown(); + + if (is_resource($this->file)) { + fclose($this->file); + } + + if (file_exists($this->path)) { + unlink($this->path); + } - $this->context = null; - $this->validator = null; $this->path = null; $this->file = null; } public function testNullIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate(null, new File()); + + $this->assertNoViolation(); } public function testEmptyStringIsValid() { - $this->context->expects($this->never()) - ->method('addViolation'); - $this->validator->validate('', new File()); + + $this->assertNoViolation(); } /** @@ -71,82 +80,138 @@ 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() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/Fixtures/test_landscape.gif b/src/Symfony/Component/Validator/Tests/Constraints/Fixtures/test_landscape.gif new file mode 100644 index 0000000000000000000000000000000000000000..870123532c3b97be8e2ab75452eca7060fb474c4 GIT binary patch literal 43 qcmZ?wbhEHbWMW`sXkcLY4+e@qSs1y10y+#p0Fq%~V)Ef)um%7ZunH6a literal 0 HcmV?d00001 diff --git a/src/Symfony/Component/Validator/Tests/Constraints/Fixtures/test_portrait.gif b/src/Symfony/Component/Validator/Tests/Constraints/Fixtures/test_portrait.gif new file mode 100644 index 0000000000000000000000000000000000000000..cc480ca88ed7fa80ff8e3907ba14d692e3e9d3d4 GIT binary patch literal 43 rcmZ?wbhEHbWMp7sXkcLY4+e@qSs1w(7#VaJfB+=Jz{KRk#b6Bp7pw{t literal 0 HcmV?d00001 diff --git a/src/Symfony/Component/Validator/Tests/Constraints/GroupSequenceTest.php b/src/Symfony/Component/Validator/Tests/Constraints/GroupSequenceTest.php new file mode 100644 index 0000000000..b3e8ec2191 --- /dev/null +++ b/src/Symfony/Component/Validator/Tests/Constraints/GroupSequenceTest.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Validator\Tests\Constraints; + +use Symfony\Component\Validator\Constraints\GroupSequence; + +/** + * @author Bernhard Schussek + */ +class GroupSequenceTest extends \PHPUnit_Framework_TestCase +{ + public function testCreateDoctrineStyle() + { + $sequence = new GroupSequence(array('value' => array('Group 1', 'Group 2'))); + + $this->assertSame(array('Group 1', 'Group 2'), $sequence->groups); + } +} diff --git a/src/Symfony/Component/Validator/Tests/Constraints/IbanValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/IbanValidatorTest.php index 49b3943017..8cf7f5ae53 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/IbanValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/IbanValidatorTest.php @@ -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() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/ImageValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/ImageValidatorTest.php index 8854501624..01f1a06199 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/ImageValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/ImageValidatorTest.php @@ -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', )); diff --git a/src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php index 25cd5d44f8..bc849278de 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php @@ -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() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/IsbnValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/IsbnValidatorTest.php index 049a9ac3ee..bb49937dfd 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/IsbnValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/IsbnValidatorTest.php @@ -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.'"', + )); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/IssnValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/IssnValidatorTest.php index 3f53e738b3..b48357a880 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/IssnValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/IssnValidatorTest.php @@ -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.'"', + )); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LanguageValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LanguageValidatorTest.php index 3588887d74..98f7533cb8 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LanguageValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LanguageValidatorTest.php @@ -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(); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.php index 267f05b1b6..31039c08ae 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.php @@ -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() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php index 41feba0c71..5d40dd20bd 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.php @@ -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() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/LuhnValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/LuhnValidatorTest.php index 11c6a7cad5..9b02bf6492 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/LuhnValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/LuhnValidatorTest.php @@ -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() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/NotBlankValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/NotBlankValidatorTest.php index 7273986a87..fe28951466 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/NotBlankValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/NotBlankValidatorTest.php @@ -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', + )); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/NotNullValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/NotNullValidatorTest.php index 96f74a1ba0..8224423e9b 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/NotNullValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/NotNullValidatorTest.php @@ -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'); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/NullValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/NullValidatorTest.php index 4ca50c1087..b659bc029a 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/NullValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/NullValidatorTest.php @@ -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() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/RangeValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/RangeValidatorTest.php index f7601de797..9c043a6d56 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/RangeValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/RangeValidatorTest.php @@ -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"', + )); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/RegexValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/RegexValidatorTest.php index 25b5006c33..91f0c0532f 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/RegexValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/RegexValidatorTest.php @@ -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() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/TimeValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/TimeValidatorTest.php index cfa24b80c7..4cc5f028b4 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/TimeValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/TimeValidatorTest.php @@ -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() diff --git a/src/Symfony/Component/Validator/Tests/Constraints/TrueValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/TrueValidatorTest.php index 5a42912edf..e401b87022 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/TrueValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/TrueValidatorTest.php @@ -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', + )); } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/TypeValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/TypeValidatorTest.php index db008ce3ce..1391846387 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/TypeValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/TypeValidatorTest.php @@ -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; } } } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.php index 4c95e5bbb0..0d4e8e3394 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.php @@ -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() diff --git a/src/Symfony/Component/Validator/Tests/Fixtures/Countable.php b/src/Symfony/Component/Validator/Tests/Fixtures/Countable.php new file mode 100644 index 0000000000..282d78d45a --- /dev/null +++ b/src/Symfony/Component/Validator/Tests/Fixtures/Countable.php @@ -0,0 +1,27 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Validator\Tests\Fixtures; + +class Countable implements \Countable +{ + private $content; + + public function __construct(array $content) + { + $this->content = $content; + } + + public function count() + { + return count($this->content); + } +} diff --git a/src/Symfony/Component/Validator/Tests/Fixtures/CustomArrayObject.php b/src/Symfony/Component/Validator/Tests/Fixtures/CustomArrayObject.php new file mode 100644 index 0000000000..41eac961ac --- /dev/null +++ b/src/Symfony/Component/Validator/Tests/Fixtures/CustomArrayObject.php @@ -0,0 +1,70 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Validator\Tests\Fixtures; + +/** + * This class is a hand written simplified version of PHP native `ArrayObject` + * class, to show that it behaves differently than the PHP native implementation. + */ +class CustomArrayObject implements \ArrayAccess, \IteratorAggregate, \Countable, \Serializable +{ + private $array; + + public function __construct(array $array = null) + { + $this->array = $array ?: array(); + } + + public function offsetExists($offset) + { + return array_key_exists($offset, $this->array); + } + + public function offsetGet($offset) + { + return $this->array[$offset]; + } + + public function offsetSet($offset, $value) + { + if (null === $offset) { + $this->array[] = $value; + } else { + $this->array[$offset] = $value; + } + } + + public function offsetUnset($offset) + { + unset($this->array[$offset]); + } + + public function getIterator() + { + return new \ArrayIterator($this->array); + } + + public function count() + { + return count($this->array); + } + + public function serialize() + { + return serialize($this->array); + } + + public function unserialize($serialized) + { + $this->array = (array) unserialize((string) $serialized); + } +} diff --git a/src/Symfony/Component/Validator/Tests/Fixtures/StubGlobalExecutionContext.php b/src/Symfony/Component/Validator/Tests/Fixtures/StubGlobalExecutionContext.php new file mode 100644 index 0000000000..bfe096a86d --- /dev/null +++ b/src/Symfony/Component/Validator/Tests/Fixtures/StubGlobalExecutionContext.php @@ -0,0 +1,69 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Validator\Tests\Fixtures; + +use Symfony\Component\Validator\ConstraintViolationList; +use Symfony\Component\Validator\GlobalExecutionContextInterface; +use Symfony\Component\Validator\ValidationVisitorInterface; + +/** + * @since 2.3.19 + * @author Bernhard Schussek + */ +class StubGlobalExecutionContext implements GlobalExecutionContextInterface +{ + private $violations; + + private $root; + + private $visitor; + + function __construct($root = null, ValidationVisitorInterface $visitor = null) + { + $this->violations = new ConstraintViolationList(); + $this->root = $root; + $this->visitor = $visitor; + } + + public function getViolations() + { + return $this->violations; + } + + public function setRoot($root) + { + $this->root = $root; + } + + public function getRoot() + { + return $this->root; + } + + public function setVisitor(ValidationVisitorInterface $visitor) + { + $this->visitor = $visitor; + } + + public function getVisitor() + { + return $this->visitor; + } + + public function getValidatorFactory() + { + } + + public function getMetadataFactory() + { + } +}