Commit d75ad87e by Alexander Makarov

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

Conflicts: framework/yii/validators/RegularExpressionValidator.php
parents 8e4067ec 06682d0b
...@@ -101,6 +101,7 @@ class CaptchaValidator extends Validator ...@@ -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 * @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. * containing a model form with this validator applied.
* @return string the client-side validation script. * @return string the client-side validation script.
* @codeCoverageIgnore
*/ */
public function clientValidateAttribute($object, $attribute, $view) public function clientValidateAttribute($object, $attribute, $view)
{ {
......
...@@ -82,6 +82,7 @@ class BooleanValidator extends Validator ...@@ -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 * @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. * containing a model form with this validator applied.
* @return string the client-side validation script. * @return string the client-side validation script.
* @codeCoverageIgnore
*/ */
public function clientValidateAttribute($object, $attribute, $view) public function clientValidateAttribute($object, $attribute, $view)
{ {
......
...@@ -182,6 +182,7 @@ class CompareValidator extends Validator ...@@ -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 * @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. * containing a model form with this validator applied.
* @throws InvalidConfigException if CompareValidator::operator is invalid * @throws InvalidConfigException if CompareValidator::operator is invalid
* @codeCoverageIgnore
*/ */
public function clientValidateAttribute($object, $attribute, $view) public function clientValidateAttribute($object, $attribute, $view)
{ {
......
...@@ -64,7 +64,9 @@ class EmailValidator extends Validator ...@@ -64,7 +64,9 @@ class EmailValidator extends Validator
{ {
parent::init(); parent::init();
if ($this->enableIDN && !function_exists('idn_to_ascii')) { 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.'); throw new InvalidConfigException('In order to use IDN validation intl extension must be installed and enabled.');
// @codeCoverageIgnoreEnd
} }
if ($this->message === null) { if ($this->message === null) {
$this->message = Yii::t('yii', '{attribute} is not a valid email address.'); $this->message = Yii::t('yii', '{attribute} is not a valid email address.');
...@@ -122,6 +124,7 @@ class EmailValidator extends Validator ...@@ -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 * @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. * containing a model form with this validator applied.
* @return string the client-side validation script. * @return string the client-side validation script.
* @codeCoverageIgnore
*/ */
public function clientValidateAttribute($object, $attribute, $view) public function clientValidateAttribute($object, $attribute, $view)
{ {
......
...@@ -117,6 +117,7 @@ class NumberValidator extends Validator ...@@ -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 * @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. * containing a model form with this validator applied.
* @return string the client-side validation script. * @return string the client-side validation script.
* @codeCoverageIgnore
*/ */
public function clientValidateAttribute($object, $attribute, $view) public function clientValidateAttribute($object, $attribute, $view)
{ {
......
...@@ -84,6 +84,7 @@ class RangeValidator extends Validator ...@@ -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 * @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. * containing a model form with this validator applied.
* @return string the client-side validation script. * @return string the client-side validation script.
* @codeCoverageIgnore
*/ */
public function clientValidateAttribute($object, $attribute, $view) public function clientValidateAttribute($object, $attribute, $view)
{ {
......
...@@ -81,6 +81,8 @@ class RegularExpressionValidator extends Validator ...@@ -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 * @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. * containing a model form with this validator applied.
* @return string the client-side validation script. * @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) public function clientValidateAttribute($object, $attribute, $view)
{ {
......
...@@ -105,6 +105,7 @@ class RequiredValidator extends Validator ...@@ -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 * @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. * containing a model form with this validator applied.
* @return string the client-side validation script. * @return string the client-side validation script.
* @codeCoverageIgnore
*/ */
public function clientValidateAttribute($object, $attribute, $view) public function clientValidateAttribute($object, $attribute, $view)
{ {
......
...@@ -145,6 +145,7 @@ class StringValidator extends Validator ...@@ -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 * @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. * containing a model form with this validator applied.
* @return string the client-side validation script. * @return string the client-side validation script.
* @codeCoverageIgnore
*/ */
public function clientValidateAttribute($object, $attribute, $view) public function clientValidateAttribute($object, $attribute, $view)
{ {
......
...@@ -54,7 +54,9 @@ class UrlValidator extends Validator ...@@ -54,7 +54,9 @@ class UrlValidator extends Validator
{ {
parent::init(); parent::init();
if ($this->enableIDN && !function_exists('idn_to_ascii')) { 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.'); throw new InvalidConfigException('In order to use IDN validation intl extension must be installed and enabled.');
// @codeCoverageIgnoreEnd
} }
if ($this->message === null) { if ($this->message === null) {
$this->message = Yii::t('yii', '{attribute} is not a valid URL.'); $this->message = Yii::t('yii', '{attribute} is not a valid URL.');
...@@ -119,6 +121,7 @@ class UrlValidator extends Validator ...@@ -119,6 +121,7 @@ class UrlValidator extends Validator
* containing a model form with this validator applied. * containing a model form with this validator applied.
* @return string the client-side validation script. * @return string the client-side validation script.
* @see \yii\Web\ActiveForm::enableClientValidation * @see \yii\Web\ActiveForm::enableClientValidation
* @codeCoverageIgnore
*/ */
public function clientValidateAttribute($object, $attribute, $view) public function clientValidateAttribute($object, $attribute, $view)
{ {
......
...@@ -109,3 +109,35 @@ INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 4, ...@@ -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, 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 (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);
/**
* (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);
...@@ -92,3 +92,32 @@ INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 4, ...@@ -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, 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 (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);
/**
* (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);
\ No newline at end of file
...@@ -95,3 +95,32 @@ INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 4, ...@@ -95,3 +95,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, 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 (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);
<?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;
}
}
\ No newline at end of file
<?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;
}
}
\ No newline at end of file
<?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'));
}
}
\ No newline at end of file
<?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'));
}
}
\ No newline at end of file
...@@ -12,6 +12,7 @@ abstract class DatabaseTestCase extends TestCase ...@@ -12,6 +12,7 @@ abstract class DatabaseTestCase extends TestCase
* @var Connection * @var Connection
*/ */
protected $db; protected $db;
protected $initializeAppWithDb = false;
protected function setUp() protected function setUp()
{ {
...@@ -21,7 +22,10 @@ abstract class DatabaseTestCase extends TestCase ...@@ -21,7 +22,10 @@ abstract class DatabaseTestCase extends TestCase
$pdo_database = 'pdo_'.$this->driverName; $pdo_database = 'pdo_'.$this->driverName;
if (!extension_loaded('pdo') || !extension_loaded($pdo_database)) { 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(); $this->mockApplication();
} }
......
<?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'));
}
}
<?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');
}
}
\ No newline at end of file
<?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'));
}
}
\ No newline at end of file
<?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);
}
}
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
namespace yiiunit\framework\validators; namespace yiiunit\framework\validators;
use yii\validators\EmailValidator; use yii\validators\EmailValidator;
use yiiunit\data\validators\models\FakedValidationModel;
use yiiunit\TestCase; use yiiunit\TestCase;
/** /**
...@@ -27,4 +28,33 @@ class EmailValidatorTest extends TestCase ...@@ -27,4 +28,33 @@ class EmailValidatorTest extends TestCase
$this->assertTrue($validator->validateValue('5011@gmail.com')); $this->assertTrue($validator->validateValue('5011@gmail.com'));
$this->assertFalse($validator->validateValue('test@example.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>'));
}
} }
<?php
namespace yiiunit\framework\validators\ExistValidatorDriverTests;
use yiiunit\framework\validators\ExistValidatorTest;
class ExistValidatorPostgresTest extends ExistValidatorTest
{
protected $driverName = 'pgsql';
}
\ No newline at end of file
<?php
namespace yiiunit\framework\validators\ExistValidatorDriverTests;
use yiiunit\framework\validators\ExistValidatorTest;
class ExistValidatorSQliteTest extends ExistValidatorTest
{
protected $driverName = 'sqlite';
}
\ No newline at end of file
<?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'));
}
}
\ No newline at end of file
<?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';
}
}
\ No newline at end of file
<?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]);
}
}
\ No newline at end of file
<?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);
}
}
\ No newline at end of file
<?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');
}
}
\ No newline at end of file
<?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'));
}
}
\ No newline at end of file
<?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]);
}
}
\ No newline at end of file
<?php
namespace yiiunit\framework\validators\UniqueValidatorDriverTests;
use yiiunit\framework\validators\UniqueValidatorTest;
class UniqueValidatorPostgresTest extends UniqueValidatorTest
{
protected $driverName = 'pgsql';
}
\ No newline at end of file
<?php
namespace yiiunit\framework\validators\UniqueValidatorDriverTests;
use yiiunit\framework\validators\UniqueValidatorTest;
class UniqueValidatorSQliteTest extends UniqueValidatorTest
{
protected $driverName = 'sqlite';
}
\ No newline at end of file
<?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');
}
}
\ No newline at end of file
<?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'));
}
}
<?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]);
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment