Browse Source

Merge branch 'add-tests' of github.com:suralc/yii2 into suralc-add-tests

Conflicts:
	framework/yii/validators/RegularExpressionValidator.php
tags/2.0.0-alpha
Alexander Makarov 11 years ago
parent
commit
d75ad87e06
  1. 1
      framework/yii/captcha/CaptchaValidator.php
  2. 1
      framework/yii/validators/BooleanValidator.php
  3. 1
      framework/yii/validators/CompareValidator.php
  4. 3
      framework/yii/validators/EmailValidator.php
  5. 1
      framework/yii/validators/NumberValidator.php
  6. 1
      framework/yii/validators/RangeValidator.php
  7. 2
      framework/yii/validators/RegularExpressionValidator.php
  8. 1
      framework/yii/validators/RequiredValidator.php
  9. 1
      framework/yii/validators/StringValidator.php
  10. 3
      framework/yii/validators/UrlValidator.php
  11. 32
      tests/unit/data/mysql.sql
  12. 29
      tests/unit/data/postgres.sql
  13. 31
      tests/unit/data/sqlite.sql
  14. 44
      tests/unit/data/validators/TestValidator.php
  15. 66
      tests/unit/data/validators/models/FakedValidationModel.php
  16. 21
      tests/unit/data/validators/models/ValidatorTestMainModel.php
  17. 23
      tests/unit/data/validators/models/ValidatorTestRefModel.php
  18. 6
      tests/unit/framework/db/DatabaseTestCase.php
  19. 53
      tests/unit/framework/validators/BooleanValidatorTest.php
  20. 171
      tests/unit/framework/validators/CompareValidatorTest.php
  21. 64
      tests/unit/framework/validators/DateValidatorTest.php
  22. 32
      tests/unit/framework/validators/DefaultValueValidatorTest.php
  23. 30
      tests/unit/framework/validators/EmailValidatorTest.php
  24. 10
      tests/unit/framework/validators/ExistValidatorDriverTests/ExistValidatorPostgresTest.php
  25. 10
      tests/unit/framework/validators/ExistValidatorDriverTests/ExistValidatorSQliteTest.php
  26. 100
      tests/unit/framework/validators/ExistValidatorTest.php
  27. 292
      tests/unit/framework/validators/FileValidatorTest.php
  28. 46
      tests/unit/framework/validators/FilterValidatorTest.php
  29. 160
      tests/unit/framework/validators/NumberValidatorTest.php
  30. 70
      tests/unit/framework/validators/RangeValidatorTest.php
  31. 48
      tests/unit/framework/validators/RegularExpressionValidatorTest.php
  32. 54
      tests/unit/framework/validators/RequiredValidatorTest.php
  33. 116
      tests/unit/framework/validators/StringValidatorTest.php
  34. 11
      tests/unit/framework/validators/UniqueValidatorDriverTests/UniqueValidatorPostgresTest.php
  35. 11
      tests/unit/framework/validators/UniqueValidatorDriverTests/UniqueValidatorSQliteTest.php
  36. 89
      tests/unit/framework/validators/UniqueValidatorTest.php
  37. 94
      tests/unit/framework/validators/UrlValidatorTest.php
  38. 227
      tests/unit/framework/validators/ValidatorTest.php

1
framework/yii/captcha/CaptchaValidator.php

@ -101,6 +101,7 @@ class CaptchaValidator extends Validator
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @return string the client-side validation script.
* @codeCoverageIgnore
*/
public function clientValidateAttribute($object, $attribute, $view)
{

1
framework/yii/validators/BooleanValidator.php

@ -82,6 +82,7 @@ class BooleanValidator extends Validator
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @return string the client-side validation script.
* @codeCoverageIgnore
*/
public function clientValidateAttribute($object, $attribute, $view)
{

1
framework/yii/validators/CompareValidator.php

@ -182,6 +182,7 @@ class CompareValidator extends Validator
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @throws InvalidConfigException if CompareValidator::operator is invalid
* @codeCoverageIgnore
*/
public function clientValidateAttribute($object, $attribute, $view)
{

3
framework/yii/validators/EmailValidator.php

@ -64,7 +64,9 @@ class EmailValidator extends Validator
{
parent::init();
if ($this->enableIDN && !function_exists('idn_to_ascii')) {
// @codeCoverageIgnoreStart
throw new InvalidConfigException('In order to use IDN validation intl extension must be installed and enabled.');
// @codeCoverageIgnoreEnd
}
if ($this->message === null) {
$this->message = Yii::t('yii', '{attribute} is not a valid email address.');
@ -122,6 +124,7 @@ class EmailValidator extends Validator
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @return string the client-side validation script.
* @codeCoverageIgnore
*/
public function clientValidateAttribute($object, $attribute, $view)
{

1
framework/yii/validators/NumberValidator.php

@ -117,6 +117,7 @@ class NumberValidator extends Validator
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @return string the client-side validation script.
* @codeCoverageIgnore
*/
public function clientValidateAttribute($object, $attribute, $view)
{

1
framework/yii/validators/RangeValidator.php

@ -84,6 +84,7 @@ class RangeValidator extends Validator
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @return string the client-side validation script.
* @codeCoverageIgnore
*/
public function clientValidateAttribute($object, $attribute, $view)
{

2
framework/yii/validators/RegularExpressionValidator.php

@ -81,6 +81,8 @@ class RegularExpressionValidator extends Validator
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @return string the client-side validation script.
* @throws InvalidConfigException if the "pattern" is not a valid regular expression
* @codeCoverageIgnore
*/
public function clientValidateAttribute($object, $attribute, $view)
{

1
framework/yii/validators/RequiredValidator.php

@ -105,6 +105,7 @@ class RequiredValidator extends Validator
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @return string the client-side validation script.
* @codeCoverageIgnore
*/
public function clientValidateAttribute($object, $attribute, $view)
{

1
framework/yii/validators/StringValidator.php

@ -145,6 +145,7 @@ class StringValidator extends Validator
* @param \yii\base\View $view the view object that is going to be used to render views or view files
* containing a model form with this validator applied.
* @return string the client-side validation script.
* @codeCoverageIgnore
*/
public function clientValidateAttribute($object, $attribute, $view)
{

3
framework/yii/validators/UrlValidator.php

@ -54,7 +54,9 @@ class UrlValidator extends Validator
{
parent::init();
if ($this->enableIDN && !function_exists('idn_to_ascii')) {
// @codeCoverageIgnoreStart
throw new InvalidConfigException('In order to use IDN validation intl extension must be installed and enabled.');
// @codeCoverageIgnoreEnd
}
if ($this->message === null) {
$this->message = Yii::t('yii', '{attribute} is not a valid URL.');
@ -119,6 +121,7 @@ class UrlValidator extends Validator
* containing a model form with this validator applied.
* @return string the client-side validation script.
* @see \yii\Web\ActiveForm::enableClientValidation
* @codeCoverageIgnore
*/
public function clientValidateAttribute($object, $attribute, $view)
{

32
tests/unit/data/mysql.sql

@ -109,3 +109,35 @@ INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 4,
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 5, 1, 15.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 3, 1, 8.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (3, 2, 1, 40.0);
/**
* (MySQL-)Database Schema for validator tests
*/
DROP TABLE IF EXISTS tbl_validator_main CASCADE;
DROP TABLE IF EXISTS tbl_validator_ref CASCADE;
CREATE TABLE tbl_validator_main (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`field1` VARCHAR(255),
PRIMARY KEY (`id`)
) ENGINE =InnoDB DEFAULT CHARSET =utf8;
CREATE TABLE tbl_validator_ref (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`a_field` VARCHAR(255),
`ref` INT(11),
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO tbl_validator_main (id, field1) VALUES (1, 'just a string1');
INSERT INTO tbl_validator_main (id, field1) VALUES (2, 'just a string2');
INSERT INTO tbl_validator_main (id, field1) VALUES (3, 'just a string3');
INSERT INTO tbl_validator_main (id, field1) VALUES (4, 'just a string4');
INSERT INTO tbl_validator_ref (a_field, ref) VALUES ('ref_to_2', 2);
INSERT INTO tbl_validator_ref (a_field, ref) VALUES ('ref_to_2', 2);
INSERT INTO tbl_validator_ref (a_field, ref) VALUES ('ref_to_3', 3);
INSERT INTO tbl_validator_ref (a_field, ref) VALUES ('ref_to_4', 4);
INSERT INTO tbl_validator_ref (a_field, ref) VALUES ('ref_to_4', 4);
INSERT INTO tbl_validator_ref (a_field, ref) VALUES ('ref_to_5', 5);

29
tests/unit/data/postgres.sql

@ -92,3 +92,32 @@ INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 4,
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 5, 1, 15.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 3, 1, 8.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (3, 2, 1, 40.0);
/**
* (Postgres-)Database Schema for validator tests
*/
DROP TABLE IF EXISTS tbl_validator_main CASCADE;
DROP TABLE IF EXISTS tbl_validator_ref CASCADE;
CREATE TABLE tbl_validator_main (
id integer not null primary key,
field1 VARCHAR(255)
);
CREATE TABLE tbl_validator_ref (
id integer not null primary key,
a_field VARCHAR(255),
ref integer
);
INSERT INTO tbl_validator_main (id, field1) VALUES (1, 'just a string1');
INSERT INTO tbl_validator_main (id, field1) VALUES (2, 'just a string2');
INSERT INTO tbl_validator_main (id, field1) VALUES (3, 'just a string3');
INSERT INTO tbl_validator_main (id, field1) VALUES (4, 'just a string4');
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (1, 'ref_to_2', 2);
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (2, 'ref_to_2', 2);
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (3, 'ref_to_3', 3);
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (4, 'ref_to_4', 4);
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (5, 'ref_to_4', 4);
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (6, 'ref_to_5', 5);

31
tests/unit/data/sqlite.sql

@ -94,4 +94,33 @@ INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (1, 2,
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 4, 1, 10.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 5, 1, 15.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 3, 1, 8.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (3, 2, 1, 40.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (3, 2, 1, 40.0);
/**
* (SqLite-)Database Schema for validator tests
*/
DROP TABLE IF EXISTS tbl_validator_main;
DROP TABLE IF EXISTS tbl_validator_ref;
CREATE TABLE tbl_validator_main (
id INTEGER PRIMARY KEY ,
field1 VARCHAR(255)
);
CREATE TABLE tbl_validator_ref (
id INTEGER PRIMARY KEY ,
a_field VARCHAR(255),
ref INT(11)
);
INSERT INTO tbl_validator_main (id, field1) VALUES (1, 'just a string1');
INSERT INTO tbl_validator_main (id, field1) VALUES (2, 'just a string2');
INSERT INTO tbl_validator_main (id, field1) VALUES (3, 'just a string3');
INSERT INTO tbl_validator_main (id, field1) VALUES (4, 'just a string4');
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (1, 'ref_to_2', 2);
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (2, 'ref_to_2', 2);
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (3, 'ref_to_3', 3);
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (4, 'ref_to_4', 4);
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (5, 'ref_to_4', 4);
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (6, 'ref_to_5', 5);

44
tests/unit/data/validators/TestValidator.php

@ -0,0 +1,44 @@
<?php
namespace yiiunit\data\validators;
use yii\validators\Validator;
class TestValidator extends Validator
{
private $_validatedAttributes = array();
private $_setErrorOnValidateAttribute = false;
public function validateAttribute($object, $attribute)
{
$this->markAttributeValidated($attribute);
if ($this->_setErrorOnValidateAttribute == true) {
$this->addError($object, $attribute, sprintf('%s##%s', $attribute, get_class($object)));
}
}
protected function markAttributeValidated($attr, $increaseBy = 1)
{
if (!isset($this->_validatedAttributes[$attr])) {
$this->_validatedAttributes[$attr] = 1;
} else {
$this->_validatedAttributes[$attr] = $this->_validatedAttributes[$attr] + $increaseBy;
}
}
public function countAttributeValidations($attr)
{
return isset($this->_validatedAttributes[$attr]) ? $this->_validatedAttributes[$attr] : 0;
}
public function isAttributeValidated($attr)
{
return isset($this->_validatedAttributes[$attr]);
}
public function enableErrorOnValidateAttribute()
{
$this->_setErrorOnValidateAttribute = true;
}
}

66
tests/unit/data/validators/models/FakedValidationModel.php

@ -0,0 +1,66 @@
<?php
namespace yiiunit\data\validators\models;
use yii\base\Model;
/**
* @codeCoverageIgnore
*/
class FakedValidationModel extends Model
{
public $val_attr_a;
public $val_attr_b;
public $val_attr_c;
public $val_attr_d;
private $attr = array();
/**
* @param array $attributes
* @return self
*/
public static function createWithAttributes($attributes = array())
{
$m = new static();
foreach ($attributes as $attribute => $value) {
$m->$attribute = $value;
}
return $m;
}
public function rules()
{
return array(
array('val_attr_a, val_attr_b', 'required', 'on' => 'reqTest'),
array('val_attr_c', 'integer'),
);
}
public function inlineVal($attribute, $params = array())
{
return true;
}
public function __get($name)
{
if (stripos($name, 'attr') === 0) {
return isset($this->attr[$name]) ? $this->attr[$name] : null;
}
return parent::__get($name);
}
public function __set($name, $value)
{
if (stripos($name, 'attr') === 0) {
$this->attr[$name] = $value;
} else {
parent::__set($name, $value);
}
}
public function getAttributeLabel($attr)
{
return $attr;
}
}

21
tests/unit/data/validators/models/ValidatorTestMainModel.php

@ -0,0 +1,21 @@
<?php
namespace yiiunit\data\validators\models;
use yii\db\ActiveRecord;
class ValidatorTestMainModel extends ActiveRecord
{
public $testMainVal = 1;
public static function tableName()
{
return 'tbl_validator_main';
}
public function getReferences()
{
return $this->hasMany(ValidatorTestRefModel::className(), array('ref' => 'id'));
}
}

23
tests/unit/data/validators/models/ValidatorTestRefModel.php

@ -0,0 +1,23 @@
<?php
namespace yiiunit\data\validators\models;
use yii\db\ActiveRecord;
class ValidatorTestRefModel extends ActiveRecord
{
public $test_val = 2;
public $test_val_fail = 99;
public static function tableName()
{
return 'tbl_validator_ref';
}
public function getMain()
{
return $this->hasOne(ValidatorTestMainModel::className(), array('id' => 'ref'));
}
}

6
tests/unit/framework/db/DatabaseTestCase.php

@ -12,6 +12,7 @@ abstract class DatabaseTestCase extends TestCase
* @var Connection
*/
protected $db;
protected $initializeAppWithDb = false;
protected function setUp()
{
@ -21,7 +22,10 @@ abstract class DatabaseTestCase extends TestCase
$pdo_database = 'pdo_'.$this->driverName;
if (!extension_loaded('pdo') || !extension_loaded($pdo_database)) {
$this->markTestSkipped('pdo and pdo_'.$pdo_database.' extension are required.');
$this->markTestSkipped('pdo and '.$pdo_database.' extension are required.');
}
if ($this->initializeAppWithDb === true) {
\Yii::$app->setComponent('db', $this->getConnection());
}
$this->mockApplication();
}

53
tests/unit/framework/validators/BooleanValidatorTest.php

@ -0,0 +1,53 @@
<?php
namespace yiiunit\framework\validators;
use yiiunit\data\validators\models\FakedValidationModel;
use yii\validators\BooleanValidator;
use yiiunit\TestCase;
/**
* BooleanValidatorTest
*/
class BooleanValidatorTest extends TestCase
{
public function testValidateValue()
{
$val = new BooleanValidator;
$this->assertTrue($val->validateValue(true));
$this->assertTrue($val->validateValue(false));
$this->assertTrue($val->validateValue('0'));
$this->assertTrue($val->validateValue('1'));
$this->assertFalse($val->validateValue(null));
$this->assertFalse($val->validateValue(array()));
$val->strict = true;
$this->assertTrue($val->validateValue('0'));
$this->assertTrue($val->validateValue('1'));
$this->assertFalse($val->validateValue(true));
$this->assertFalse($val->validateValue(false));
$val->trueValue = true;
$val->falseValue = false;
$this->assertFalse($val->validateValue('0'));
$this->assertFalse($val->validateValue(array()));
$this->assertTrue($val->validateValue(true));
$this->assertTrue($val->validateValue(false));
}
public function testValidateAttributeAndError()
{
$obj = new FakedValidationModel;
$obj->attrA = true;
$obj->attrB = '1';
$obj->attrC = '0';
$obj->attrD = array();
$val = new BooleanValidator;
$val->validateAttribute($obj, 'attrA');
$this->assertFalse($obj->hasErrors('attrA'));
$val->validateAttribute($obj, 'attrC');
$this->assertFalse($obj->hasErrors('attrC'));
$val->strict = true;
$val->validateAttribute($obj, 'attrB');
$this->assertFalse($obj->hasErrors('attrB'));
$val->validateAttribute($obj, 'attrD');
$this->assertTrue($obj->hasErrors('attrD'));
}
}

171
tests/unit/framework/validators/CompareValidatorTest.php

@ -0,0 +1,171 @@
<?php
namespace yiiunit\framework\validators;
use yii\base\InvalidConfigException;
use yii\validators\CompareValidator;
use yiiunit\data\validators\models\FakedValidationModel;
use yiiunit\TestCase;
class CompareValidatorTest extends TestCase
{
public function testValidateValueException()
{
$this->setExpectedException('yii\base\InvalidConfigException');
$val = new CompareValidator;
$val->validateValue('val');
}
public function testValidateValue()
{
$value = 18449;
// default config
$val = new CompareValidator(array('compareValue' => $value));
$this->assertTrue($val->validateValue($value));
$this->assertTrue($val->validateValue((string)$value));
$this->assertFalse($val->validateValue($value + 1));
foreach ($this->getOperationTestData($value) as $op => $tests) {
$val = new CompareValidator(array('compareValue' => $value));
$val->operator = $op;
foreach ($tests as $test) {
$this->assertEquals($test[1], $val->validateValue($test[0]));
}
}
}
protected function getOperationTestData($value)
{
return array(
'===' => array(
array($value, true),
array((string)$value, false),
array((float)$value, false),
array($value + 1, false),
),
'!=' => array(
array($value, false),
array((string)$value, false),
array((float)$value, false),
array($value + 0.00001, true),
array(false, true),
),
'!==' => array(
array($value, false),
array((string)$value, true),
array((float)$value, true),
array(false, true),
),
'>' => array(
array($value, false),
array($value + 1, true),
array($value - 1, false),
),
'>=' => array(
array($value, true),
array($value + 1, true),
array($value - 1, false),
),
'<' => array(
array($value, false),
array($value + 1, false),
array($value - 1, true),
),
'<=' => array(
array($value, true),
array($value + 1, false),
array($value - 1, true),
),
//'non-op' => array(
// array($value, false),
// array($value + 1, false),
// array($value - 1, false),
//),
);
}
public function testValidateAttribute()
{
// invalid-array
$val = new CompareValidator;
$model = new FakedValidationModel;
$model->attr = array('test_val');
$val->validateAttribute($model, 'attr');
$this->assertTrue($model->hasErrors('attr'));
$val = new CompareValidator(array('compareValue' => 'test-string'));
$model = new FakedValidationModel;
$model->attr_test = 'test-string';
$val->validateAttribute($model, 'attr_test');
$this->assertFalse($model->hasErrors('attr_test'));
$val = new CompareValidator(array('compareAttribute' => 'attr_test_val'));
$model = new FakedValidationModel;
$model->attr_test = 'test-string';
$model->attr_test_val = 'test-string';
$val->validateAttribute($model, 'attr_test');
$this->assertFalse($model->hasErrors('attr_test'));
$this->assertFalse($model->hasErrors('attr_test_val'));
$val = new CompareValidator(array('compareAttribute' => 'attr_test_val'));
$model = new FakedValidationModel;
$model->attr_test = 'test-string';
$model->attr_test_val = 'test-string-false';
$val->validateAttribute($model, 'attr_test');
$this->assertTrue($model->hasErrors('attr_test'));
$this->assertFalse($model->hasErrors('attr_test_val'));
// assume: _repeat
$val = new CompareValidator;
$model = new FakedValidationModel;
$model->attr_test = 'test-string';
$model->attr_test_repeat = 'test-string';
$val->validateAttribute($model, 'attr_test');
$this->assertFalse($model->hasErrors('attr_test'));
$this->assertFalse($model->hasErrors('attr_test_repeat'));
$val = new CompareValidator;
$model = new FakedValidationModel;
$model->attr_test = 'test-string';
$model->attr_test_repeat = 'test-string2';
$val->validateAttribute($model, 'attr_test');
$this->assertTrue($model->hasErrors('attr_test'));
$this->assertFalse($model->hasErrors('attr_test_repeat'));
// not existing op
$val = new CompareValidator();
$val->operator = '<>';
$model = FakedValidationModel::createWithAttributes(array('attr_o' => 5, 'attr_o_repeat' => 5 ));
$val->validateAttribute($model, 'attr_o');
$this->assertTrue($model->hasErrors('attr_o'));
}
public function testValidateAttributeOperators()
{
$value = 55;
foreach ($this->getOperationTestData($value) as $operator => $tests) {
$val = new CompareValidator(array('operator' => $operator, 'compareValue' => $value));
foreach ($tests as $test) {
$model = new FakedValidationModel;
$model->attr_test = $test[0];
$val->validateAttribute($model, 'attr_test');
$this->assertEquals($test[1], !$model->hasErrors('attr_test'));
}
}
}
public function testEnsureMessageSetOnInit()
{
foreach ($this->getOperationTestData(1337) as $operator => $tests) {
$val = new CompareValidator(array('operator' => $operator));
$this->assertTrue(strlen($val->message) > 1);
}
try {
$val = new CompareValidator(array('operator' => '<>'));
} catch (InvalidConfigException $e) {
return;
}
catch (\Exception $e) {
$this->fail('InvalidConfigException expected' . get_class($e) . 'received');
return;
}
$this->fail('InvalidConfigException expected none received');
}
}

64
tests/unit/framework/validators/DateValidatorTest.php

@ -0,0 +1,64 @@
<?php
namespace yiiunit\framework\validators;
use DateTime;
use yii\validators\DateValidator;
use yiiunit\data\validators\models\FakedValidationModel;
use yiiunit\TestCase;
class DateValidatorTest extends TestCase
{
public function testEnsureMessageIsSet()
{
$val = new DateValidator;
$this->assertTrue($val->message !== null && strlen($val->message) > 1);
}
public function testValidateValue()
{
$val = new DateValidator;
$this->assertTrue($val->validateValue('2013-09-13'));
$this->assertFalse($val->validateValue('31.7.2013'));
$this->assertFalse($val->validateValue('31-7-2013'));
$this->assertFalse($val->validateValue(time()));
$val->format = 'U';
$this->assertTrue($val->validateValue(time()));
$val->format = 'd.m.Y';
$this->assertTrue($val->validateValue('31.7.2013'));
$val->format = 'Y-m-!d H:i:s';
$this->assertTrue($val->validateValue('2009-02-15 15:16:17'));
}
public function testValidateAttribute()
{
// error-array-add
$val = new DateValidator;
$model = new FakedValidationModel;
$model->attr_date = '2013-09-13';
$val->validateAttribute($model, 'attr_date');
$this->assertFalse($model->hasErrors('attr_date'));
$model = new FakedValidationModel;
$model->attr_date = '1375293913';
$val->validateAttribute($model, 'attr_date');
$this->assertTrue($model->hasErrors('attr_date'));
//// timestamp attribute
$val = new DateValidator(array('timestampAttribute' => 'attr_timestamp'));
$model = new FakedValidationModel;
$model->attr_date = '2013-09-13';
$model->attr_timestamp = true;
$val->validateAttribute($model, 'attr_date');
$this->assertFalse($model->hasErrors('attr_date'));
$this->assertFalse($model->hasErrors('attr_timestamp'));
$this->assertEquals(
DateTime::createFromFormat($val->format, '2013-09-13')->getTimestamp(),
$model->attr_timestamp
);
$val = new DateValidator();
$model = FakedValidationModel::createWithAttributes(array('attr_date' => array()));
$val->validateAttribute($model, 'attr_date');
$this->assertTrue($model->hasErrors('attr_date'));
}
}

32
tests/unit/framework/validators/DefaultValueValidatorTest.php

@ -0,0 +1,32 @@
<?php
namespace yiiunit\framework\validators;
use yii\validators\DefaultValueValidator;
use yiiunit\TestCase;
/**
* DefaultValueValidatorTest
*/
class DefaultValueValidatorTest extends TestCase
{
public function testValidateAttribute()
{
$val = new DefaultValueValidator;
$val->value = 'test_value';
$obj = new \stdclass;
$obj->attrA = 'attrA';
$obj->attrB = null;
$obj->attrC = '';
// original values to chek which attritubes where modified
$objB = clone $obj;
$val->validateAttribute($obj, 'attrB');
$this->assertEquals($val->value, $obj->attrB);
$this->assertEquals($objB->attrA, $obj->attrA);
$val->value = 'new_test_value';
$obj = clone $objB; // get clean object
$val->validateAttribute($obj, 'attrC');
$this->assertEquals('new_test_value', $obj->attrC);
$this->assertEquals($objB->attrA, $obj->attrA);
$val->validateAttribute($obj, 'attrA');
$this->assertEquals($objB->attrA, $obj->attrA);
}
}

30
tests/unit/framework/validators/EmailValidatorTest.php

@ -2,6 +2,7 @@
namespace yiiunit\framework\validators;
use yii\validators\EmailValidator;
use yiiunit\data\validators\models\FakedValidationModel;
use yiiunit\TestCase;
/**
@ -27,4 +28,33 @@ class EmailValidatorTest extends TestCase
$this->assertTrue($validator->validateValue('5011@gmail.com'));
$this->assertFalse($validator->validateValue('test@example.com'));
}
public function testValidateAttribute()
{
$val = new EmailValidator();
$model = new FakedValidationModel();
$model->attr_email = '5011@gmail.com';
$val->validateAttribute($model, 'attr_email');
$this->assertFalse($model->hasErrors('attr_email'));
}
public function testValidateValueIdn()
{
if (!function_exists('idn_to_ascii')) {
$this->markTestSkipped('Intl extension required');
return;
}
$val = new EmailValidator(array('enableIDN' => true));
$this->assertTrue($val->validateValue('5011@example.com'));
$this->assertTrue($val->validateValue('example@äüößìà.de'));
$this->assertTrue($val->validateValue('example@xn--zcack7ayc9a.de'));
}
public function testValidateValueWithName()
{
$val = new EmailValidator(array('allowName' => true));
$this->assertTrue($val->validateValue('test@example.com'));
$this->assertTrue($val->validateValue('John Smith <john.smith@example.com>'));
$this->assertFalse($val->validateValue('John Smith <example.com>'));
}
}

10
tests/unit/framework/validators/ExistValidatorDriverTests/ExistValidatorPostgresTest.php

@ -0,0 +1,10 @@
<?php
namespace yiiunit\framework\validators\ExistValidatorDriverTests;
use yiiunit\framework\validators\ExistValidatorTest;
class ExistValidatorPostgresTest extends ExistValidatorTest
{
protected $driverName = 'pgsql';
}

10
tests/unit/framework/validators/ExistValidatorDriverTests/ExistValidatorSQliteTest.php

@ -0,0 +1,10 @@
<?php
namespace yiiunit\framework\validators\ExistValidatorDriverTests;
use yiiunit\framework\validators\ExistValidatorTest;
class ExistValidatorSQliteTest extends ExistValidatorTest
{
protected $driverName = 'sqlite';
}

100
tests/unit/framework/validators/ExistValidatorTest.php

@ -0,0 +1,100 @@
<?php
namespace yiiunit\framework\validators;
use Yii;
use yii\base\Exception;
use yii\validators\ExistValidator;
use yiiunit\data\ar\ActiveRecord;
use yiiunit\data\validators\models\ValidatorTestMainModel;
use yiiunit\data\validators\models\ValidatorTestRefModel;
use yiiunit\framework\db\DatabaseTestCase;
class ExistValidatorTest extends DatabaseTestCase
{
protected $initializeAppWithDb = true;
protected $driverName = 'mysql';
public function setUp()
{
parent::setUp();
ActiveRecord::$db = Yii::$app->getComponent('db');
}
public function tearDown()
{
parent::tearDown();
}
public function testValidateValueExpectedException()
{
try {
$val = new ExistValidator();
$result = $val->validateValue('ref');
$this->fail('Exception should have been thrown at this time');
} catch (Exception $e) {
$this->assertInstanceOf('yii\base\InvalidConfigException', $e);
$this->assertEquals('The "className" property must be set.', $e->getMessage());
}
// combine to save the time creating a new db-fixture set (likely ~5 sec)
try {
$val = new ExistValidator(array('className' => ValidatorTestMainModel::className()));
$val->validateValue('ref');
$this->fail('Exception should have been thrown at this time');
} catch (Exception $e) {
$this->assertInstanceOf('yii\base\InvalidConfigException', $e);
$this->assertEquals('The "attributeName" property must be set.', $e->getMessage());
}
}
public function testValidateValue()
{
$val = new ExistValidator(array('className' => ValidatorTestRefModel::className(), 'attributeName' => 'id'));
$this->assertTrue($val->validateValue(2));
$this->assertTrue($val->validateValue(5));
$this->assertFalse($val->validateValue(99));
$this->assertFalse($val->validateValue(array('1')));
}
public function testValidateAttribute()
{
// existing value on different table
$val = new ExistValidator(array('className' => ValidatorTestMainModel::className(), 'attributeName' => 'id'));
$m = ValidatorTestRefModel::find(array('id' => 1));
$val->validateAttribute($m, 'ref');
$this->assertFalse($m->hasErrors());
// non-existing value on different table
$val = new ExistValidator(array('className' => ValidatorTestMainModel::className(), 'attributeName' => 'id'));
$m = ValidatorTestRefModel::find(array('id' => 6));
$val->validateAttribute($m, 'ref');
$this->assertTrue($m->hasErrors('ref'));
// existing value on same table
$val = new ExistValidator(array('attributeName' => 'ref'));
$m = ValidatorTestRefModel::find(array('id' => 2));
$val->validateAttribute($m, 'test_val');
$this->assertFalse($m->hasErrors());
// non-existing value on same table
$val = new ExistValidator(array('attributeName' => 'ref'));
$m = ValidatorTestRefModel::find(array('id' => 5));
$val->validateAttribute($m, 'test_val_fail');
$this->assertTrue($m->hasErrors('test_val_fail'));
// check for given value (true)
$val = new ExistValidator();
$m = ValidatorTestRefModel::find(array('id' => 3));
$val->validateAttribute($m, 'ref');
$this->assertFalse($m->hasErrors());
// check for given defaults (false)
$val = new ExistValidator();
$m = ValidatorTestRefModel::find(array('id' => 4));
$m->a_field = 'some new value';
$val->validateAttribute($m, 'a_field');
$this->assertTrue($m->hasErrors('a_field'));
// check array
$val = new ExistValidator(array('attributeName' => 'ref'));
$m = ValidatorTestRefModel::find(array('id' => 2));
$m->test_val = array(1,2,3);
$val->validateAttribute($m, 'test_val');
$this->assertTrue($m->hasErrors('test_val'));
}
}

292
tests/unit/framework/validators/FileValidatorTest.php

@ -0,0 +1,292 @@
<?php
namespace yiiunit\framework\validators;
use yii\validators\FileValidator;
use yii\web\UploadedFile;
use Yii;
use yiiunit\data\validators\models\FakedValidationModel;
use yiiunit\TestCase;
class FileValidatorTest extends TestCase
{
public function setUp()
{
$this->mockApplication();
}
public function testAssureMessagesSetOnInit()
{
$val = new FileValidator();
foreach (array('message', 'uploadRequired', 'tooMany', 'wrongType', 'tooBig', 'tooSmall') as $attr) {
$this->assertTrue(is_string($val->$attr));
}
}
public function testTypeSplitOnInit()
{
$val = new FileValidator(array('types' => 'jpeg, jpg, gif'));
$this->assertEquals(array('jpeg', 'jpg', 'gif'), $val->types);
$val = new FileValidator(array('types' => 'jpeg'));
$this->assertEquals(array('jpeg'), $val->types);
$val = new FileValidator(array('types' => ''));
$this->assertEquals(array(), $val->types);
$val = new FileValidator(array('types' => array()));
$this->assertEquals(array(), $val->types);
$val = new FileValidator();
$this->assertEquals(array(), $val->types);
$val = new FileValidator(array('types' => array('jpeg', 'exe')));
$this->assertEquals(array('jpeg', 'exe'), $val->types);
}
public function testGetSizeLimit()
{
$size = $this->sizeToBytes(ini_get('upload_max_filesize'));
$val = new FileValidator();
$this->assertEquals($size, $val->getSizeLimit());
$val->maxSize = $size + 1; // set and test if value is overridden
$this->assertEquals($size, $val->getSizeLimit());
$val->maxSize = abs($size - 1);
$this->assertEquals($size - 1, $val->getSizeLimit());
$_POST['MAX_FILE_SIZE'] = $size + 1;
$this->assertEquals($size - 1, $val->getSizeLimit());
$_POST['MAX_FILE_SIZE'] = abs($size - 2);
$this->assertSame($_POST['MAX_FILE_SIZE'], $val->getSizeLimit());
}
protected function sizeToBytes($sizeStr)
{
switch (substr($sizeStr, -1)) {
case 'M':
case 'm':
return (int)$sizeStr * 1048576;
case 'K':
case 'k':
return (int)$sizeStr * 1024;
case 'G':
case 'g':
return (int)$sizeStr * 1073741824;
default:
return (int)$sizeStr;
}
}
public function testValidateAttributeMultiple()
{
$val = new FileValidator(array('maxFiles' => 2));
$m = FakedValidationModel::createWithAttributes(array('attr_files' => 'path'));
$val->validateAttribute($m, 'attr_files');
$this->assertTrue($m->hasErrors('attr_files'));
$m = FakedValidationModel::createWithAttributes(array('attr_files' => array()));
$val->validateAttribute($m, 'attr_files');
$this->assertTrue($m->hasErrors('attr_files'));
$this->assertSame($val->uploadRequired, current($m->getErrors('attr_files')));
$m = FakedValidationModel::createWithAttributes(
array(
'attr_files' => $this->createTestFiles(
array(
array(
'name' => 'test_up_1.txt',
'size' => 1024,
),
array(
'error' => UPLOAD_ERR_NO_FILE,
),
)
)
)
);
$val->validateAttribute($m, 'attr_files');
$this->assertFalse($m->hasErrors('attr_files'));
$m = FakedValidationModel::createWithAttributes(
array('attr_files' => $this->createTestFiles(array(array(''), array(''), array(''),)))
);
$val->validateAttribute($m, 'attr_files');
$this->assertTrue($m->hasErrors());
$this->assertTrue(stripos(current($m->getErrors('attr_files')), 'you can upload at most') !== false);
}
/**
* @param array $params
* @return UploadedFile[]
*/
protected function createTestFiles($params = array())
{
$rndString = function ($len = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $len; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
};
$files = array();
foreach ($params as $param) {
if (empty($param) && count($params) != 1) {
$files[] = array('no instance of UploadedFile');
continue;
}
$name = isset($param['name']) ? $param['name'] : $rndString();
$tempName = \Yii::getAlias('@yiiunit/runtime/validators/file/tmp') . $name;
if (is_readable($tempName)) {
$size = filesize($tempName);
} else {
$size = isset($param['size']) ? $param['size'] : rand(
1,
$this->sizeToBytes(ini_get('upload_max_filesize'))
);
}
$type = isset($param['type']) ? $param['type'] : 'text/plain';
$error = isset($param['error']) ? $param['error'] : UPLOAD_ERR_OK;
if (count($params) == 1) {
$error = empty($param) ? UPLOAD_ERR_NO_FILE : $error;
return new UploadedFile($name, $tempName, $type, $size, $error);
}
$files[] = new UploadedFile($name, $tempName, $type, $size, $error);
}
return $files;
}
public function testValidateAttribute()
{
// single File
$val = new FileValidator();
$m = $this->createModelForAttributeTest();
$val->validateAttribute($m, 'attr_files');
$this->assertFalse($m->hasErrors());
$val->validateAttribute($m, 'attr_files_empty');
$this->assertTrue($m->hasErrors('attr_files_empty'));
$this->assertSame($val->uploadRequired, current($m->getErrors('attr_files_empty')));
$m = $this->createModelForAttributeTest();
// too big
$val = new FileValidator(array('maxSize' => 128));
$val->validateAttribute($m, 'attr_files');
$this->assertTrue($m->hasErrors('attr_files'));
$this->assertTrue(
stripos(
current($m->getErrors('attr_files')),
str_ireplace(array('{file}', '{limit}'), array($m->attr_files->getName(), 128), $val->tooBig)
) !== false
);
// to Small
$m = $this->createModelForAttributeTest();
$val = new FileValidator(array('minSize' => 2048));
$val->validateAttribute($m, 'attr_files');
$this->assertTrue($m->hasErrors('attr_files'));
$this->assertTrue(
stripos(
current($m->getErrors('attr_files')),
str_ireplace(array('{file}', '{limit}'), array($m->attr_files->getName(), 2048), $val->tooSmall)
) !== false
);
// UPLOAD_ERR_INI_SIZE/UPLOAD_ERR_FORM_SIZE
$m = $this->createModelForAttributeTest();
$val = new FileValidator();
$val->validateAttribute($m, 'attr_err_ini');
$this->assertTrue($m->hasErrors('attr_err_ini'));
$this->assertTrue(
stripos(
current($m->getErrors('attr_err_ini')),
str_ireplace(
array('{file}', '{limit}'),
array($m->attr_err_ini->getName(), $val->getSizeLimit()),
$val->tooBig
)
) !== false
);
// UPLOAD_ERR_PARTIAL
$m = $this->createModelForAttributeTest();
$val = new FileValidator();
$val->validateAttribute($m, 'attr_err_part');
$this->assertTrue($m->hasErrors('attr_err_part'));
$this->assertSame(Yii::t('yii', 'File upload failed.'), current($m->getErrors('attr_err_part')));
$log = Yii::$app->getLog()->toArray();
$this->assertSame(FileValidator::className() . '::validateFile', $log['messages'][0][2]);
}
public function testValidateAttributeType()
{
$val = new FileValidator(array('types' => 'jpeg, jpg'));
$m = FakedValidationModel::createWithAttributes(
array(
'attr_jpg' => $this->createTestFiles(array(array('name' => 'one.jpeg'))),
'attr_exe' => $this->createTestFiles(array(array('name' => 'bad.exe'))),
)
);
$val->validateAttribute($m, 'attr_jpg');
$this->assertFalse($m->hasErrors('attr_jpg'));
$val->validateAttribute($m, 'attr_exe');
$this->assertTrue($m->hasErrors('attr_exe'));
$this->assertTrue(stripos(current($m->getErrors('attr_exe')), 'Only files with these extensions ') !== false);
}
protected function createModelForAttributeTest()
{
return FakedValidationModel::createWithAttributes(
array(
'attr_files' => $this->createTestFiles(
array(
array('name' => 'abc.jpg', 'size' => 1024, 'type' => 'image/jpeg'),
)
),
'attr_files_empty' => $this->createTestFiles(array(array())),
'attr_err_ini' => $this->createTestFiles(array(array('error' => UPLOAD_ERR_INI_SIZE))),
'attr_err_part' => $this->createTestFiles(array(array('error' => UPLOAD_ERR_PARTIAL))),
'attr_err_tmp' => $this->createTestFiles(array(array('error' => UPLOAD_ERR_NO_TMP_DIR))),
'attr_err_write' => $this->createTestFiles(array(array('error' => UPLOAD_ERR_CANT_WRITE))),
'attr_err_ext' => $this->createTestFiles(array(array('error' => UPLOAD_ERR_EXTENSION))),
)
);
}
public function testValidateAttributeErrPartial()
{
$m = $this->createModelForAttributeTest();
$val = new FileValidator();
$val->validateAttribute($m, 'attr_err_part');
$this->assertTrue($m->hasErrors('attr_err_part'));
$this->assertSame(Yii::t('yii', 'File upload failed.'), current($m->getErrors('attr_err_part')));
$log = Yii::$app->getLog()->toArray();
$this->assertSame(FileValidator::className() . '::validateFile', $log['messages'][0][2]);
$this->assertContains('File was only', $log['messages'][0][0]);
}
public function testValidateAttributeErrCantWrite()
{
$m = $this->createModelForAttributeTest();
$val = new FileValidator();
$val->validateAttribute($m, 'attr_err_write');
$this->assertTrue($m->hasErrors('attr_err_write'));
$this->assertSame(Yii::t('yii', 'File upload failed.'), current($m->getErrors('attr_err_write')));
$log = Yii::$app->getLog()->toArray();
$this->assertSame(FileValidator::className() . '::validateFile', $log['messages'][0][2]);
$this->assertContains('Failed to write', $log['messages'][0][0]);
}
public function testValidateAttributeErrExtension()
{
$m = $this->createModelForAttributeTest();
$val = new FileValidator();
$val->validateAttribute($m, 'attr_err_ext');
$this->assertTrue($m->hasErrors('attr_err_ext'));
$this->assertSame(Yii::t('yii', 'File upload failed.'), current($m->getErrors('attr_err_ext')));
$log = Yii::$app->getLog()->toArray();
$this->assertSame(FileValidator::className() . '::validateFile', $log['messages'][0][2]);
$this->assertContains('PHP extension', $log['messages'][0][0]);
}
public function testValidateAttributeErrNoTmpDir()
{
$m = $this->createModelForAttributeTest();
$val = new FileValidator();
$val->validateAttribute($m, 'attr_err_tmp');
$this->assertTrue($m->hasErrors('attr_err_tmp'));
$this->assertSame(Yii::t('yii', 'File upload failed.'), current($m->getErrors('attr_err_tmp')));
$log = Yii::$app->getLog()->toArray();
$this->assertSame(FileValidator::className() . '::validateFile', $log['messages'][0][2]);
$this->assertContains('Missing the temporary folder', $log['messages'][0][0]);
}
}

46
tests/unit/framework/validators/FilterValidatorTest.php

@ -0,0 +1,46 @@
<?php
namespace yiiunit\framework\validators;
use yii\validators\FilterValidator;
use yiiunit\data\validators\models\FakedValidationModel;
use yiiunit\TestCase;
class FilterValidatorTest extends TestCase
{
public function testAssureExceptionOnInit()
{
$this->setExpectedException('yii\base\InvalidConfigException');
$val = new FilterValidator();
}
public function testValidateAttribute()
{
$m = FakedValidationModel::createWithAttributes(array(
'attr_one' => ' to be trimmed ',
'attr_two' => 'set this to null',
'attr_empty1' => '',
'attr_empty2' => null
));
$val = new FilterValidator(array('filter' => 'trim'));
$val->validateAttribute($m, 'attr_one');
$this->assertSame('to be trimmed', $m->attr_one);
$val->filter = function ($value) {
return null;
};
$val->validateAttribute($m, 'attr_two');
$this->assertNull($m->attr_two);
$val->filter = array($this, 'notToBeNull');
$val->validateAttribute($m, 'attr_empty1');
$this->assertSame($this->notToBeNull(''), $m->attr_empty1);
$val->skipOnEmpty = true;
$val->validateAttribute($m, 'attr_empty2');
$this->assertNotNull($m->attr_empty2);
}
public function notToBeNull($value)
{
return 'not null';
}
}

160
tests/unit/framework/validators/NumberValidatorTest.php

@ -0,0 +1,160 @@
<?php
namespace yiiunit\framework\validators;
use yii\validators\NumberValidator;
use yiiunit\data\validators\models\FakedValidationModel;
use yiiunit\TestCase;
class NumberValidatorTest extends TestCase
{
public function testEnsureMessageOnInit()
{
$val = new NumberValidator;
$this->assertTrue(is_string($val->message));
$this->assertTrue(is_null($val->max));
$val = new NumberValidator(array('min' => -1, 'max' => 20, 'integerOnly' => true));
$this->assertTrue(is_string($val->message));
$this->assertTrue(is_string($val->tooSmall));
$this->assertTrue(is_string($val->tooBig));
}
public function testValidateValueSimple()
{
$val = new NumberValidator();
$this->assertTrue($val->validateValue(20));
$this->assertTrue($val->validateValue(0));
$this->assertTrue($val->validateValue(-20));
$this->assertTrue($val->validateValue('20'));
$this->assertTrue($val->validateValue(25.45));
$this->assertFalse($val->validateValue('25,45'));
$this->assertFalse($val->validateValue('12:45'));
$val = new NumberValidator(array('integerOnly' => true));
$this->assertTrue($val->validateValue(20));
$this->assertTrue($val->validateValue(0));
$this->assertFalse($val->validateValue(25.45));
$this->assertTrue($val->validateValue('20'));
$this->assertFalse($val->validateValue('25,45'));
$this->assertTrue($val->validateValue('020'));
$this->assertTrue($val->validateValue(0x14));
$this->assertFalse($val->validateValue('0x14')); // todo check this
}
public function testValidateValueAdvanced()
{
$val = new NumberValidator();
$this->assertTrue($val->validateValue('-1.23')); // signed float
$this->assertTrue($val->validateValue('-4.423e-12')); // signed float + exponent
$this->assertTrue($val->validateValue('12E3')); // integer + exponent
$this->assertFalse($val->validateValue('e12')); // just exponent
$this->assertFalse($val->validateValue('-e3'));
$this->assertFalse($val->validateValue('-4.534-e-12')); // 'signed' exponent
$this->assertFalse($val->validateValue('12.23^4')); // expression instead of value
$val = new NumberValidator(array('integerOnly' => true));
$this->assertFalse($val->validateValue('-1.23'));
$this->assertFalse($val->validateValue('-4.423e-12'));
$this->assertFalse($val->validateValue('12E3'));
$this->assertFalse($val->validateValue('e12'));
$this->assertFalse($val->validateValue('-e3'));
$this->assertFalse($val->validateValue('-4.534-e-12'));
$this->assertFalse($val->validateValue('12.23^4'));
}
public function testValidateValueMin()
{
$val = new NumberValidator(array('min' => 1));
$this->assertTrue($val->validateValue(1));
$this->assertFalse($val->validateValue(-1));
$this->assertFalse($val->validateValue('22e-12'));
$this->assertTrue($val->validateValue(PHP_INT_MAX + 1));
$val = new NumberValidator(array('min' => 1), array('integerOnly' => true));
$this->assertTrue($val->validateValue(1));
$this->assertFalse($val->validateValue(-1));
$this->assertFalse($val->validateValue('22e-12'));
$this->assertTrue($val->validateValue(PHP_INT_MAX + 1));
}
public function testValidateValueMax()
{
$val = new NumberValidator(array('max' => 1.25));
$this->assertTrue($val->validateValue(1));
$this->assertFalse($val->validateValue(1.5));
$this->assertTrue($val->validateValue('22e-12'));
$this->assertTrue($val->validateValue('125e-2'));
$val = new NumberValidator(array('max' => 1.25, 'integerOnly' => true));
$this->assertTrue($val->validateValue(1));
$this->assertFalse($val->validateValue(1.5));
$this->assertFalse($val->validateValue('22e-12'));
$this->assertFalse($val->validateValue('125e-2'));
}
public function testValidateValueRange()
{
$val = new NumberValidator(array('min' => -10, 'max' => 20));
$this->assertTrue($val->validateValue(0));
$this->assertTrue($val->validateValue(-10));
$this->assertFalse($val->validateValue(-11));
$this->assertFalse($val->validateValue(21));
$val = new NumberValidator(array('min' => -10, 'max' => 20, 'integerOnly' => true));
$this->assertTrue($val->validateValue(0));
$this->assertFalse($val->validateValue(-11));
$this->assertFalse($val->validateValue(22));
$this->assertFalse($val->validateValue('20e-1'));
}
public function testValidateAttribute()
{
$val = new NumberValidator();
$model = new FakedValidationModel();
$model->attr_number = '5.5e1';
$val->validateAttribute($model, 'attr_number');
$this->assertFalse($model->hasErrors('attr_number'));
$model->attr_number = '43^32'; //expression
$val->validateAttribute($model, 'attr_number');
$this->assertTrue($model->hasErrors('attr_number'));
$val = new NumberValidator(array('min' => 10));
$model = new FakedValidationModel();
$model->attr_number = 10;
$val->validateAttribute($model, 'attr_number');
$this->assertFalse($model->hasErrors('attr_number'));
$model->attr_number = 5;
$val->validateAttribute($model, 'attr_number');
$this->assertTrue($model->hasErrors('attr_number'));
$val = new NumberValidator(array('max' => 10));
$model = new FakedValidationModel();
$model->attr_number = 10;
$val->validateAttribute($model, 'attr_number');
$this->assertFalse($model->hasErrors('attr_number'));
$model->attr_number = 15;
$val->validateAttribute($model, 'attr_number');
$this->assertTrue($model->hasErrors('attr_number'));
$val = new NumberValidator(array('max' => 10, 'integerOnly' => true));
$model = new FakedValidationModel();
$model->attr_number = 10;
$val->validateAttribute($model, 'attr_number');
$this->assertFalse($model->hasErrors('attr_number'));
$model->attr_number = 3.43;
$val->validateAttribute($model, 'attr_number');
$this->assertTrue($model->hasErrors('attr_number'));
$val = new NumberValidator(array('min' => 1));
$model = FakedValidationModel::createWithAttributes(array('attr_num' => array(1,2,3)));
$val->validateAttribute($model, 'attr_num');
$this->assertTrue($model->hasErrors('attr_num'));
}
public function testEnsureCustomMessageIsSetOnValidateAttribute()
{
$val = new NumberValidator(array(
'tooSmall' => '{attribute} is to small.',
'min' => 5
));
$model = new FakedValidationModel();
$model->attr_number = 0;
$val->validateAttribute($model, 'attr_number');
$this->assertTrue($model->hasErrors('attr_number'));
$this->assertEquals(1, count($model->getErrors('attr_number')));
$msgs = $model->getErrors('attr_number');
$this->assertSame('attr_number is to small.', $msgs[0]);
}
}

70
tests/unit/framework/validators/RangeValidatorTest.php

@ -0,0 +1,70 @@
<?php
namespace yiiunit\framework\validators;
use yii\validators\RangeValidator;
use yiiunit\data\validators\models\FakedValidationModel;
use yiiunit\TestCase;
class RangeValidatorTest extends TestCase
{
public function testInitException()
{
$this->setExpectedException('yii\base\InvalidConfigException', 'The "range" property must be set.');
$val = new RangeValidator(array('range' => 'not an array'));
}
public function testAssureMessageSetOnInit()
{
$val = new RangeValidator(array('range' => array()));
$this->assertTrue(is_string($val->message));
}
public function testValidateValue()
{
$val = new RangeValidator(array('range' => range(1, 10, 1)));
$this->assertTrue($val->validateValue(1));
$this->assertFalse($val->validateValue(0));
$this->assertFalse($val->validateValue(11));
$this->assertFalse($val->validateValue(5.5));
$this->assertTrue($val->validateValue(10));
$this->assertTrue($val->validateValue("10"));
$this->assertTrue($val->validateValue("5"));
}
public function testValidateValueStrict()
{
$val = new RangeValidator(array('range' => range(1, 10, 1), 'strict' => true));
$this->assertTrue($val->validateValue(1));
$this->assertTrue($val->validateValue(5));
$this->assertTrue($val->validateValue(10));
$this->assertFalse($val->validateValue("1"));
$this->assertFalse($val->validateValue("10"));
$this->assertFalse($val->validateValue("5.5"));
}
public function testValidateValueNot()
{
$val = new RangeValidator(array('range' => range(1, 10, 1), 'not' => true));
$this->assertFalse($val->validateValue(1));
$this->assertTrue($val->validateValue(0));
$this->assertTrue($val->validateValue(11));
$this->assertTrue($val->validateValue(5.5));
$this->assertFalse($val->validateValue(10));
$this->assertFalse($val->validateValue("10"));
$this->assertFalse($val->validateValue("5"));
}
public function testValidateAttribute()
{
$val = new RangeValidator(array('range' => range(1, 10, 1)));
$m = FakedValidationModel::createWithAttributes(array('attr_r1' => 5, 'attr_r2' => 999));
$val->validateAttribute($m, 'attr_r1');
$this->assertFalse($m->hasErrors());
$val->validateAttribute($m, 'attr_r2');
$this->assertTrue($m->hasErrors('attr_r2'));
$err = $m->getErrors('attr_r2');
$this->assertTrue(stripos($err[0], 'attr_r2') !== false);
}
}

48
tests/unit/framework/validators/RegularExpressionValidatorTest.php

@ -0,0 +1,48 @@
<?php
namespace yiiunit\framework\validators;
use yii\validators\RegularExpressionValidator;
use yiiunit\data\validators\models\FakedValidationModel;
use yiiunit\TestCase;
class RegularExpressionValidatorTest extends TestCase
{
public function testValidateValue()
{
$val = new RegularExpressionValidator(array('pattern' => '/^[a-zA-Z0-9](\.)?([^\/]*)$/m'));
$this->assertTrue($val->validateValue('b.4'));
$this->assertFalse($val->validateValue('b./'));
$this->assertFalse($val->validateValue(array('a', 'b')));
$val->not = true;
$this->assertFalse($val->validateValue('b.4'));
$this->assertTrue($val->validateValue('b./'));
$this->assertFalse($val->validateValue(array('a', 'b')));
}
public function testValidateAttribute()
{
$val = new RegularExpressionValidator(array('pattern' => '/^[a-zA-Z0-9](\.)?([^\/]*)$/m'));
$m = FakedValidationModel::createWithAttributes(array('attr_reg1' => 'b.4'));
$val->validateAttribute($m, 'attr_reg1');
$this->assertFalse($m->hasErrors('attr_reg1'));
$m->attr_reg1 = 'b./';
$val->validateAttribute($m, 'attr_reg1');
$this->assertTrue($m->hasErrors('attr_reg1'));
}
public function testMessageSetOnInit()
{
$val = new RegularExpressionValidator(array('pattern' => '/^[a-zA-Z0-9](\.)?([^\/]*)$/m'));
$this->assertTrue(is_string($val->message));
}
public function testInitException()
{
$this->setExpectedException('yii\base\InvalidConfigException');
$val = new RegularExpressionValidator();
$val->validateValue('abc');
}
}

54
tests/unit/framework/validators/RequiredValidatorTest.php

@ -0,0 +1,54 @@
<?php
namespace yiiunit\framework\validators;
use yii\validators\RequiredValidator;
use yiiunit\data\validators\models\FakedValidationModel;
use yiiunit\TestCase;
class RequiredValidatorTest extends TestCase
{
public function testValidateValueWithDefaults()
{
$val = new RequiredValidator();
$this->assertFalse($val->validateValue(null));
$this->assertFalse($val->validateValue(array()));
$this->assertTrue($val->validateValue('not empty'));
$this->assertTrue($val->validateValue(array('with', 'elements')));
}
public function testValidateValueWithValue()
{
$val = new RequiredValidator(array('requiredValue' => 55));
$this->assertTrue($val->validateValue(55));
$this->assertTrue($val->validateValue("55"));
$this->assertTrue($val->validateValue("0x37"));
$this->assertFalse($val->validateValue("should fail"));
$this->assertTrue($val->validateValue(true));
$val->strict = true;
$this->assertTrue($val->validateValue(55));
$this->assertFalse($val->validateValue("55"));
$this->assertFalse($val->validateValue("0x37"));
$this->assertFalse($val->validateValue("should fail"));
$this->assertFalse($val->validateValue(true));
}
public function testValidateAttribute()
{
// empty req-value
$val = new RequiredValidator();
$m = FakedValidationModel::createWithAttributes(array('attr_val' => null));
$val->validateAttribute($m, 'attr_val');
$this->assertTrue($m->hasErrors('attr_val'));
$this->assertTrue(stripos(current($m->getErrors('attr_val')), 'blank') !== false);
$val = new RequiredValidator(array('requiredValue' => 55));
$m = FakedValidationModel::createWithAttributes(array('attr_val' => 56));
$val->validateAttribute($m, 'attr_val');
$this->assertTrue($m->hasErrors('attr_val'));
$this->assertTrue(stripos(current($m->getErrors('attr_val')), 'must be') !== false);
$val = new RequiredValidator(array('requiredValue' => 55));
$m = FakedValidationModel::createWithAttributes(array('attr_val' => 55));
$val->validateAttribute($m, 'attr_val');
$this->assertFalse($m->hasErrors('attr_val'));
}
}

116
tests/unit/framework/validators/StringValidatorTest.php

@ -0,0 +1,116 @@
<?php
namespace yiiunit\framework\validators;
use yii\validators\StringValidator;
use yiiunit\data\validators\models\FakedValidationModel;
use yiiunit\TestCase;
class StringValidatorTest extends TestCase
{
public function setUp()
{
parent::setUp();
$this->mockApplication();
}
public function testValidateValue()
{
$val = new StringValidator();
$this->assertFalse($val->validateValue(array('not a string')));
$this->assertTrue($val->validateValue('Just some string'));
}
public function testValidateValueLength()
{
$val = new StringValidator(array('length' => 25));
$this->assertTrue($val->validateValue(str_repeat('x', 25)));
$this->assertTrue($val->validateValue(str_repeat('€', 25)));
$this->assertFalse($val->validateValue(str_repeat('x', 125)));
$this->assertFalse($val->validateValue(''));
$val = new StringValidator(array('length' => array(25)));
$this->assertTrue($val->validateValue(str_repeat('x', 25)));
$this->assertTrue($val->validateValue(str_repeat('x', 1250)));
$this->assertFalse($val->validateValue(str_repeat('Ä', 24)));
$this->assertFalse($val->validateValue(''));
$val = new StringValidator(array('length' => array(10, 20)));
$this->assertTrue($val->validateValue(str_repeat('x', 15)));
$this->assertTrue($val->validateValue(str_repeat('x', 10)));
$this->assertTrue($val->validateValue(str_repeat('x', 20)));
$this->assertFalse($val->validateValue(str_repeat('x', 5)));
$this->assertFalse($val->validateValue(str_repeat('x', 25)));
$this->assertFalse($val->validateValue(''));
// make sure min/max are overridden
$val = new StringValidator(array('length' => array(10, 20), 'min' => 25, 'max' => 35));
$this->assertTrue($val->validateValue(str_repeat('x', 15)));
$this->assertFalse($val->validateValue(str_repeat('x', 30)));
}
public function testValidateValueMinMax()
{
$val = new StringValidator(array('min' => 10));
$this->assertTrue($val->validateValue(str_repeat('x', 10)));
$this->assertFalse($val->validateValue('xxxx'));
$val = new StringValidator(array('max' => 10));
$this->assertTrue($val->validateValue('xxxx'));
$this->assertFalse($val->validateValue(str_repeat('y', 20)));
$val = new StringValidator(array('min' => 10, 'max' => 20));
$this->assertTrue($val->validateValue(str_repeat('y', 15)));
$this->assertFalse($val->validateValue('abc'));
$this->assertFalse($val->validateValue(str_repeat('b', 25)));
}
public function testValidateAttribute()
{
$val = new StringValidator();
$model = new FakedValidationModel();
$model->attr_string = 'a tet string';
$val->validateAttribute($model, 'attr_string');
$this->assertFalse($model->hasErrors());
$val = new StringValidator(array('length' => 20));
$model = new FakedValidationModel();
$model->attr_string = str_repeat('x', 20);
$val->validateAttribute($model, 'attr_string');
$this->assertFalse($model->hasErrors());
$model = new FakedValidationModel();
$model->attr_string = 'abc';
$val->validateAttribute($model, 'attr_string');
$this->assertTrue($model->hasErrors('attr_string'));
$val = new StringValidator(array('max' => 2));
$model = new FakedValidationModel();
$model->attr_string = 'a';
$val->validateAttribute($model, 'attr_string');
$this->assertFalse($model->hasErrors());
$model = new FakedValidationModel();
$model->attr_string = 'abc';
$val->validateAttribute($model, 'attr_string');
$this->assertTrue($model->hasErrors('attr_string'));
$val = new StringValidator(array('max' => 1));
$model = FakedValidationModel::createWithAttributes(array('attr_str' => array('abc')));
$val->validateAttribute($model, 'attr_str');
$this->assertTrue($model->hasErrors('attr_str'));
}
public function testEnsureMessagesOnInit()
{
$val = new StringValidator(array('min' => 1, 'max' => 2));
$this->assertTrue(is_string($val->message));
$this->assertTrue(is_string($val->tooLong));
$this->assertTrue(is_string($val->tooShort));
}
public function testCustomErrorMessageInValidateAttribute()
{
$val = new StringValidator(array(
'min' => 5,
'tooShort' => '{attribute} to short. Min is {min}',
));
$model = new FakedValidationModel();
$model->attr_string = 'abc';
$val->validateAttribute($model, 'attr_string');
$this->assertTrue($model->hasErrors('attr_string'));
$errorMsg = $model->getErrors('attr_string');
$this->assertEquals('attr_string to short. Min is 5', $errorMsg[0]);
}
}

11
tests/unit/framework/validators/UniqueValidatorDriverTests/UniqueValidatorPostgresTest.php

@ -0,0 +1,11 @@
<?php
namespace yiiunit\framework\validators\UniqueValidatorDriverTests;
use yiiunit\framework\validators\UniqueValidatorTest;
class UniqueValidatorPostgresTest extends UniqueValidatorTest
{
protected $driverName = 'pgsql';
}

11
tests/unit/framework/validators/UniqueValidatorDriverTests/UniqueValidatorSQliteTest.php

@ -0,0 +1,11 @@
<?php
namespace yiiunit\framework\validators\UniqueValidatorDriverTests;
use yiiunit\framework\validators\UniqueValidatorTest;
class UniqueValidatorSQliteTest extends UniqueValidatorTest
{
protected $driverName = 'sqlite';
}

89
tests/unit/framework/validators/UniqueValidatorTest.php

@ -0,0 +1,89 @@
<?php
namespace yiiunit\framework\validators;
use yii\validators\UniqueValidator;
use Yii;
use yiiunit\data\ar\ActiveRecord;
use yiiunit\data\validators\models\FakedValidationModel;
use yiiunit\data\validators\models\ValidatorTestMainModel;
use yiiunit\data\validators\models\ValidatorTestRefModel;
use yiiunit\framework\db\DatabaseTestCase;
use yiiunit\TestCase;
class UniqueValidatorTest extends DatabaseTestCase
{
protected $initializeAppWithDb = true;
protected $driverName = 'mysql';
public function setUp()
{
parent::setUp();
ActiveRecord::$db = Yii::$app->getComponent('db');
}
public function testAssureMessageSetOnInit()
{
$val = new UniqueValidator();
$this->assertTrue(is_string($val->message));
}
public function testValidateAttributeDefault()
{
$val = new UniqueValidator();
$m = ValidatorTestMainModel::find()->one();
$val->validateAttribute($m, 'id');
$this->assertFalse($m->hasErrors('id'));
$m = ValidatorTestRefModel::find(1);
$val->validateAttribute($m, 'ref');
$this->assertTrue($m->hasErrors('ref'));
// new record:
$m = new ValidatorTestRefModel();
$m->ref = 5;
$val->validateAttribute($m, 'ref');
$this->assertTrue($m->hasErrors('ref'));
$m = new ValidatorTestRefModel();
$m->id = 7;
$m->ref = 12121;
$val->validateAttribute($m, 'ref');
$this->assertFalse($m->hasErrors('ref'));
$m->save(false);
$val->validateAttribute($m, 'ref');
$this->assertFalse($m->hasErrors('ref'));
// array error
$m = FakedValidationModel::createWithAttributes(array('attr_arr' => array('a', 'b')));
$val->validateAttribute($m, 'attr_arr');
$this->assertTrue($m->hasErrors('attr_arr'));
}
public function testValidateAttributeOfNonARModel()
{
$val = new UniqueValidator(array('className' => ValidatorTestRefModel::className(), 'attributeName' => 'ref'));
$m = FakedValidationModel::createWithAttributes(array('attr_1' => 5, 'attr_2' => 1313));
$val->validateAttribute($m, 'attr_1');
$this->assertTrue($m->hasErrors('attr_1'));
$val->validateAttribute($m, 'attr_2');
$this->assertFalse($m->hasErrors('attr_2'));
}
public function testValidateNonDatabaseAttribute()
{
$val = new UniqueValidator(array('className' => ValidatorTestRefModel::className(), 'attributeName' => 'ref'));
$m = ValidatorTestMainModel::find(1);
$val->validateAttribute($m, 'testMainVal');
$this->assertFalse($m->hasErrors('testMainVal'));
$m = ValidatorTestMainModel::find(1);
$m->testMainVal = 4;
$val->validateAttribute($m, 'testMainVal');
$this->assertTrue($m->hasErrors('testMainVal'));
}
public function testValidateAttributeAttributeNotInTableException()
{
$this->setExpectedException('yii\base\InvalidConfigException');
$val = new UniqueValidator();
$m = new ValidatorTestMainModel();
$val->validateAttribute($m, 'testMainVal');
}
}

94
tests/unit/framework/validators/UrlValidatorTest.php

@ -0,0 +1,94 @@
<?php
namespace yiiunit\framework\validators;
use yiiunit\data\validators\models\FakedValidationModel;
use yii\validators\UrlValidator;
use yiiunit\TestCase;
/**
* UrlValidatorTest
*/
class UrlValidatorTest extends TestCase
{
public function testValidateValue()
{
$val = new UrlValidator;
$this->assertFalse($val->validateValue('google.de'));
$this->assertTrue($val->validateValue('http://google.de'));
$this->assertTrue($val->validateValue('https://google.de'));
$this->assertFalse($val->validateValue('htp://yiiframework.com'));
$this->assertTrue($val->validateValue('https://www.google.de/search?q=yii+framework&ie=utf-8&oe=utf-8'
.'&rls=org.mozilla:de:official&client=firefox-a&gws_rd=cr'));
$this->assertFalse($val->validateValue('ftp://ftp.ruhr-uni-bochum.de/'));
$this->assertFalse($val->validateValue('http://invalid,domain'));
$this->assertFalse($val->validateValue('http://äüö?=!"§$%&/()=}][{³²€.edu'));
}
public function testValidateValueWithDefaultScheme()
{
$val = new UrlValidator(array('defaultScheme' => 'https'));
$this->assertTrue($val->validateValue('yiiframework.com'));
$this->assertTrue($val->validateValue('http://yiiframework.com'));
}
public function testValidateValueWithoutScheme()
{
$val = new UrlValidator(array('pattern' => '/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)/i'));
$this->assertTrue($val->validateValue('yiiframework.com'));
}
public function testValidateWithCustomScheme()
{
$val = new UrlValidator(array(
'validSchemes' => array('http', 'https', 'ftp', 'ftps'),
'defaultScheme' => 'http',
));
$this->assertTrue($val->validateValue('ftp://ftp.ruhr-uni-bochum.de/'));
$this->assertTrue($val->validateValue('google.de'));
$this->assertTrue($val->validateValue('http://google.de'));
$this->assertTrue($val->validateValue('https://google.de'));
$this->assertFalse($val->validateValue('htp://yiiframework.com'));
// relative urls not supported
$this->assertFalse($val->validateValue('//yiiframework.com'));
}
public function testValidateWithIdn()
{
if(!function_exists('idn_to_ascii')) {
$this->markTestSkipped('intl package required');
return;
}
$val = new UrlValidator(array(
'enableIDN' => true,
));
$this->assertTrue($val->validateValue('http://äüößìà.de'));
// converted via http://mct.verisign-grs.com/convertServlet
$this->assertTrue($val->validateValue('http://xn--zcack7ayc9a.de'));
}
public function testValidateLength()
{
$url = 'http://' . str_pad('base', 2000, 'url') . '.de';
$val = new UrlValidator;
$this->assertFalse($val->validateValue($url));
}
public function testValidateAttributeAndError()
{
$obj = new FakedValidationModel;
$obj->attr_url = 'http://google.de';
$val = new UrlValidator;
$val->validateAttribute($obj, 'attr_url');
$this->assertFalse($obj->hasErrors('attr_url'));
$this->assertSame('http://google.de', $obj->attr_url);
$obj = new FakedValidationModel;
$val->defaultScheme = 'http';
$obj->attr_url = 'google.de';
$val->validateAttribute($obj, 'attr_url');
$this->assertFalse($obj->hasErrors('attr_url'));
$this->assertTrue(stripos($obj->attr_url, 'http') !== false);
$obj = new FakedValidationModel;
$obj->attr_url = 'gttp;/invalid string';
$val->validateAttribute($obj, 'attr_url');
$this->assertTrue($obj->hasErrors('attr_url'));
}
}

227
tests/unit/framework/validators/ValidatorTest.php

@ -0,0 +1,227 @@
<?php
namespace yiiunit\framework\validators;
use yii\validators\BooleanValidator;
use yii\validators\InlineValidator;
use yii\validators\NumberValidator;
use yiiunit\data\validators\models\FakedValidationModel;
use yiiunit\data\validators\TestValidator;
use yiiunit\TestCase;
class ValidatorTest extends TestCase
{
protected function getTestModel($additionalAttributes = array())
{
$attributes = array_merge(
array('attr_runMe1' => true, 'attr_runMe2' => true, 'attr_skip' => true),
$additionalAttributes
);
return FakedValidationModel::createWithAttributes($attributes);
}
public function testCreateValidator()
{
$model = FakedValidationModel::createWithAttributes(array('attr_test1' => 'abc', 'attr_test2' => '2013'));
/** @var $numberVal NumberValidator */
$numberVal = TestValidator::createValidator('number', $model, array('attr_test1'));
$this->assertInstanceOf(NumberValidator::className(), $numberVal);
$numberVal = TestValidator::createValidator('integer', $model, array('attr_test2'));
$this->assertInstanceOf(NumberValidator::className(), $numberVal);
$this->assertTrue($numberVal->integerOnly);
$val = TestValidator::createValidator(
'boolean',
$model,
'attr_test1, attr_test2',
array('on' => array('a', 'b'))
);
$this->assertInstanceOf(BooleanValidator::className(), $val);
$this->assertSame(array('a', 'b'), $val->on);
$this->assertSame(array('attr_test1', 'attr_test2'), $val->attributes);
$val = TestValidator::createValidator(
'boolean',
$model,
'attr_test1, attr_test2',
array('on' => 'a, b', 'except' => 'c,d,e')
);
$this->assertInstanceOf(BooleanValidator::className(), $val);
$this->assertSame(array('a', 'b'), $val->on);
$this->assertSame(array('c', 'd', 'e'), $val->except);
$val = TestValidator::createValidator('inlineVal', $model, 'val_attr_a');
$this->assertInstanceOf(InlineValidator::className(), $val);
$this->assertSame('inlineVal', $val->method);
}
public function testValidate()
{
$val = new TestValidator(array('attributes' => array('attr_runMe1', 'attr_runMe2')));
$model = $this->getTestModel();
$val->validate($model);
$this->assertTrue($val->isAttributeValidated('attr_runMe1'));
$this->assertTrue($val->isAttributeValidated('attr_runMe2'));
$this->assertFalse($val->isAttributeValidated('attr_skip'));
}
public function testValidateWithAttributeIntersect()
{
$val = new TestValidator(array('attributes' => array('attr_runMe1', 'attr_runMe2')));
$model = $this->getTestModel();
$val->validate($model, array('attr_runMe1'));
$this->assertTrue($val->isAttributeValidated('attr_runMe1'));
$this->assertFalse($val->isAttributeValidated('attr_runMe2'));
$this->assertFalse($val->isAttributeValidated('attr_skip'));
}
public function testValidateWithEmptyAttributes()
{
$val = new TestValidator();
$model = $this->getTestModel();
$val->validate($model, array('attr_runMe1'));
$this->assertFalse($val->isAttributeValidated('attr_runMe1'));
$this->assertFalse($val->isAttributeValidated('attr_runMe2'));
$this->assertFalse($val->isAttributeValidated('attr_skip'));
$val->validate($model);
$this->assertFalse($val->isAttributeValidated('attr_runMe1'));
$this->assertFalse($val->isAttributeValidated('attr_runMe2'));
$this->assertFalse($val->isAttributeValidated('attr_skip'));
}
public function testValidateWithError()
{
$val = new TestValidator(array('attributes' => array('attr_runMe1', 'attr_runMe2'), 'skipOnError' => false));
$model = $this->getTestModel();
$val->validate($model);
$this->assertTrue($val->isAttributeValidated('attr_runMe1'));
$this->assertTrue($val->isAttributeValidated('attr_runMe2'));
$this->assertFalse($val->isAttributeValidated('attr_skip'));
$this->assertEquals(1, $val->countAttributeValidations('attr_runMe2'));
$this->assertEquals(1, $val->countAttributeValidations('attr_runMe1'));
$val->validate($model, array('attr_runMe2'));
$this->assertEquals(2, $val->countAttributeValidations('attr_runMe2'));
$this->assertEquals(1, $val->countAttributeValidations('attr_runMe1'));
$this->assertEquals(0, $val->countAttributeValidations('attr_skip'));
$val = new TestValidator(array('attributes' => array('attr_runMe1', 'attr_runMe2'), 'skipOnError' => true));
$model = $this->getTestModel();
$val->enableErrorOnValidateAttribute();
$val->validate($model);
$this->assertTrue($val->isAttributeValidated('attr_runMe1'));
$this->assertTrue($val->isAttributeValidated('attr_runMe2'));
$this->assertFalse($val->isAttributeValidated('attr_skip'));
$this->assertEquals(1, $val->countAttributeValidations('attr_runMe1'));
$this->assertEquals(1, $val->countAttributeValidations('attr_runMe1'));
$this->assertEquals(0, $val->countAttributeValidations('attr_skip'));
$val->validate($model, array('attr_runMe2'));
$this->assertEquals(1, $val->countAttributeValidations('attr_runMe2'));
$this->assertEquals(1, $val->countAttributeValidations('attr_runMe1'));
$this->assertEquals(0, $val->countAttributeValidations('attr_skip'));
}
public function testValidateWithEmpty()
{
$val = new TestValidator(array(
'attributes' => array(
'attr_runMe1',
'attr_runMe2',
'attr_empty1',
'attr_empty2'
),
'skipOnEmpty' => true,
));
$model = $this->getTestModel(array('attr_empty1' => '', 'attr_emtpy2' => ' '));
$val->validate($model);
$this->assertTrue($val->isAttributeValidated('attr_runMe1'));
$this->assertTrue($val->isAttributeValidated('attr_runMe2'));
$this->assertFalse($val->isAttributeValidated('attr_empty1'));
$this->assertFalse($val->isAttributeValidated('attr_empty2'));
$model->attr_empty1 = 'not empty anymore';
$val->validate($model);
$this->assertTrue($val->isAttributeValidated('attr_empty1'));
$this->assertFalse($val->isAttributeValidated('attr_empty2'));
$val = new TestValidator(array(
'attributes' => array(
'attr_runMe1',
'attr_runMe2',
'attr_empty1',
'attr_empty2'
),
'skipOnEmpty' => false,
));
$model = $this->getTestModel(array('attr_empty1' => '', 'attr_emtpy2' => ' '));
$val->validate($model);
$this->assertTrue($val->isAttributeValidated('attr_runMe1'));
$this->assertTrue($val->isAttributeValidated('attr_runMe2'));
$this->assertTrue($val->isAttributeValidated('attr_empty1'));
$this->assertTrue($val->isAttributeValidated('attr_empty2'));
}
public function testIsEmpty()
{
$val = new TestValidator();
$this->assertTrue($val->isEmpty(null));
$this->assertTrue($val->isEmpty(array()));
$this->assertTrue($val->isEmpty(''));
$this->assertFalse($val->isEmpty(5));
$this->assertFalse($val->isEmpty(0));
$this->assertFalse($val->isEmpty(new \stdClass()));
$this->assertFalse($val->isEmpty(' '));
// trim
$this->assertTrue($val->isEmpty(' ', true));
$this->assertTrue($val->isEmpty('', true));
$this->assertTrue($val->isEmpty(" \t\n\r\0\x0B", true));
$this->assertTrue($val->isEmpty('', true));
$this->assertFalse($val->isEmpty('0', true));
$this->assertFalse($val->isEmpty(0, true));
$this->assertFalse($val->isEmpty('this ain\'t an empty value', true));
}
public function testValidateValue()
{
$this->setExpectedException(
'yii\base\NotSupportedException',
TestValidator::className() . ' does not support validateValue().'
);
$val = new TestValidator();
$val->validateValue('abc');
}
public function testClientValidateAttribute()
{
$val = new TestValidator();
$this->assertNull(
$val->clientValidateAttribute($this->getTestModel(), 'attr_runMe1', array())
); //todo pass a view instead of array
}
public function testIsActive()
{
$val = new TestValidator();
$this->assertTrue($val->isActive('scenA'));
$this->assertTrue($val->isActive('scenB'));
$val->except = array('scenB');
$this->assertTrue($val->isActive('scenA'));
$this->assertFalse($val->isActive('scenB'));
$val->on = array('scenC');
$this->assertFalse($val->isActive('scenA'));
$this->assertFalse($val->isActive('scenB'));
$this->assertTrue($val->isActive('scenC'));
}
public function testAddError()
{
$val = new TestValidator();
$m = $this->getTestModel(array('attr_msg_val' => 'abc'));
$val->addError($m, 'attr_msg_val', '{attribute}::{value}');
$errors = $m->getErrors('attr_msg_val');
$this->assertEquals('attr_msg_val::abc', $errors[0]);
$m = $this->getTestModel(array('attr_msg_val' => array('bcc')));
$val->addError($m, 'attr_msg_val', '{attribute}::{value}');
$errors = $m->getErrors('attr_msg_val');
$this->assertEquals('attr_msg_val::array()', $errors[0]);
$m = $this->getTestModel(array('attr_msg_val' => 'abc'));
$val->addError($m, 'attr_msg_val', '{attribute}::{value}::{param}', array('{param}' => 'param_value'));
$errors = $m->getErrors('attr_msg_val');
$this->assertEquals('attr_msg_val::abc::param_value', $errors[0]);
}
}
Loading…
Cancel
Save