RequiredValidatorTest.php 2.06 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
use yiiunit\TestCase;

class RequiredValidatorTest extends TestCase
{
11 12 13 14 15 16
	protected function setUp()
	{
		parent::setUp();
		$this->mockApplication();
	}

Suralc committed
17 18 19 20
	public function testValidateValueWithDefaults()
	{
		$val = new RequiredValidator();
		$this->assertFalse($val->validateValue(null));
Alexander Makarov committed
21
		$this->assertFalse($val->validateValue([]));
Suralc committed
22
		$this->assertTrue($val->validateValue('not empty'));
Alexander Makarov committed
23
		$this->assertTrue($val->validateValue(['with', 'elements']));
Suralc committed
24 25 26 27
	}

	public function testValidateValueWithValue()
	{
Alexander Makarov committed
28
		$val = new RequiredValidator(['requiredValue' => 55]);
Suralc committed
29 30 31 32 33 34 35 36 37 38 39 40
		$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
41 42 43 44 45

	public function testValidateAttribute()
	{
		// empty req-value
		$val = new RequiredValidator();
Alexander Makarov committed
46
		$m = FakedValidationModel::createWithAttributes(['attr_val' => null]);
Suralc committed
47 48 49
		$val->validateAttribute($m, 'attr_val');
		$this->assertTrue($m->hasErrors('attr_val'));
		$this->assertTrue(stripos(current($m->getErrors('attr_val')), 'blank') !== false);
Alexander Makarov committed
50 51
		$val = new RequiredValidator(['requiredValue' => 55]);
		$m = FakedValidationModel::createWithAttributes(['attr_val' => 56]);
Suralc committed
52 53 54
		$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
55 56
		$val = new RequiredValidator(['requiredValue' => 55]);
		$m = FakedValidationModel::createWithAttributes(['attr_val' => 55]);
Suralc committed
57 58 59
		$val->validateAttribute($m, 'attr_val');
		$this->assertFalse($m->hasErrors('attr_val'));
	}
Suralc committed
60
}