RequiredValidatorTest.php 2 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
	public function testValidateValueWithDefaults()
	{
		$val = new RequiredValidator();
Qiang Xue committed
20 21 22 23
		$this->assertFalse($val->validate(null));
		$this->assertFalse($val->validate([]));
		$this->assertTrue($val->validate('not empty'));
		$this->assertTrue($val->validate(['with', 'elements']));
Suralc committed
24 25 26 27
	}

	public function testValidateValueWithValue()
	{
Alexander Makarov committed
28
		$val = new RequiredValidator(['requiredValue' => 55]);
Qiang Xue committed
29 30 31 32 33
		$this->assertTrue($val->validate(55));
		$this->assertTrue($val->validate("55"));
		$this->assertTrue($val->validate("0x37"));
		$this->assertFalse($val->validate("should fail"));
		$this->assertTrue($val->validate(true));
Suralc committed
34
		$val->strict = true;
Qiang Xue committed
35 36 37 38 39
		$this->assertTrue($val->validate(55));
		$this->assertFalse($val->validate("55"));
		$this->assertFalse($val->validate("0x37"));
		$this->assertFalse($val->validate("should fail"));
		$this->assertFalse($val->validate(true));
Suralc committed
40
	}
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'));
	}
Qiang Xue committed
60
}