|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <fabien@symfony.com> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\Component\Validator\Tests\Constraints; |
| 13 | + |
| 14 | +use Symfony\Component\Validator\Constraints\Json; |
| 15 | +use Symfony\Component\Validator\Constraints\JsonValidator; |
| 16 | +use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; |
| 17 | + |
| 18 | +class JsonValidatorTest extends ConstraintValidatorTestCase |
| 19 | +{ |
| 20 | + protected function createValidator() |
| 21 | + { |
| 22 | + return new JsonValidator(); |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * @dataProvider getValidValues |
| 27 | + */ |
| 28 | + public function testJsonIsValid($value) |
| 29 | + { |
| 30 | + $this->validator->validate($value, new Json()); |
| 31 | + |
| 32 | + $this->assertNoViolation(); |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * @dataProvider getInvalidValues |
| 37 | + */ |
| 38 | + public function testInvalidValues($value) |
| 39 | + { |
| 40 | + $constraint = new Json([ |
| 41 | + 'message' => 'myMessageTest', |
| 42 | + ]); |
| 43 | + |
| 44 | + $this->validator->validate($value, $constraint); |
| 45 | + |
| 46 | + $this->buildViolation('myMessageTest') |
| 47 | + ->setParameter('{{ value }}', '"'.$value.'"') |
| 48 | + ->setCode(Json::INVALID_JSON_ERROR) |
| 49 | + ->assertRaised(); |
| 50 | + } |
| 51 | + |
| 52 | + public function getValidValues() |
| 53 | + { |
| 54 | + return [ |
| 55 | + ['{"planet":"earth", "country": "Morocco","city": "Rabat" ,"postcode" : 10160, "is_great": true, |
| 56 | + "img" : null, "area": 118.5, "foo": 15 }'], |
| 57 | + [null], |
| 58 | + [''], |
| 59 | + ['"null"'], |
| 60 | + ['null'], |
| 61 | + ['"string"'], |
| 62 | + ['1'], |
| 63 | + ['true'], |
| 64 | + [1], |
| 65 | + ]; |
| 66 | + } |
| 67 | + |
| 68 | + public function getInvalidValues() |
| 69 | + { |
| 70 | + return [ |
| 71 | + ['{"foo": 3 "bar": 4}'], |
| 72 | + ['{"foo": 3 ,"bar": 4'], |
| 73 | + ['{foo": 3, "bar": 4}'], |
| 74 | + ['foo'], |
| 75 | + ]; |
| 76 | + } |
| 77 | +} |
0 commit comments