RequiredValidatorTest.php 1.98 KB
Newer Older
Suralc committed
1 2 3 4 5
<?php
namespace yiiunit\framework\validators;


use yii\validators\RequiredValidator;
Suralc committed
6
use yiiunit\data\validators\models\FakedValidationModel;
Suralc committed
7 8 9 10 11 12 13 14
use yiiunit\TestCase;

class RequiredValidatorTest extends TestCase
{
	public function testValidateValueWithDefaults()
	{
		$val = new RequiredValidator();
		$this->assertFalse($val->validateValue(null));
Alexander Makarov committed
15
		$this->assertFalse($val->validateValue([]));
Suralc committed
16
		$this->assertTrue($val->validateValue('not empty'));
Alexander Makarov committed
17
		$this->assertTrue($val->validateValue(['with', 'elements']));
Suralc committed
18 19 20 21
	}

	public function testValidateValueWithValue()
	{
Alexander Makarov committed
22
		$val = new RequiredValidator(['requiredValue' => 55]);
Suralc committed
23 24 25 26 27 28 29 30 31 32 33 34
		$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));
	}
Suralc committed
35 36 37 38 39

	public function testValidateAttribute()
	{
		// empty req-value
		$val = new RequiredValidator();
Alexander Makarov committed
40
		$m = FakedValidationModel::createWithAttributes(['attr_val' => null]);
Suralc committed
41 42 43
		$val->validateAttribute($m, 'attr_val');
		$this->assertTrue($m->hasErrors('attr_val'));
		$this->assertTrue(stripos(current($m->getErrors('attr_val')), 'blank') !== false);
Alexander Makarov committed
44 45
		$val = new RequiredValidator(['requiredValue' => 55]);
		$m = FakedValidationModel::createWithAttributes(['attr_val' => 56]);
Suralc committed
46 47 48
		$val->validateAttribute($m, 'attr_val');
		$this->assertTrue($m->hasErrors('attr_val'));
		$this->assertTrue(stripos(current($m->getErrors('attr_val')), 'must be') !== false);
Alexander Makarov committed
49 50
		$val = new RequiredValidator(['requiredValue' => 55]);
		$m = FakedValidationModel::createWithAttributes(['attr_val' => 55]);
Suralc committed
51 52 53
		$val->validateAttribute($m, 'attr_val');
		$this->assertFalse($m->hasErrors('attr_val'));
	}
Suralc committed
54
}