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

use yii\validators\RequiredValidator;
Suralc committed
5
use yiiunit\data\validators\models\FakedValidationModel;
Suralc committed
6 7
use yiiunit\TestCase;

8 9 10
/**
 * @group validators
 */
Suralc committed
11 12
class RequiredValidatorTest extends TestCase
{
13 14 15 16 17
    protected function setUp()
    {
        parent::setUp();
        $this->mockApplication();
    }
18

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

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

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
    public function testValidateAttribute()
    {
        // empty req-value
        $val = new RequiredValidator();
        $m = FakedValidationModel::createWithAttributes(['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(['requiredValue' => 55]);
        $m = FakedValidationModel::createWithAttributes(['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(['requiredValue' => 55]);
        $m = FakedValidationModel::createWithAttributes(['attr_val' => 55]);
        $val->validateAttribute($m, 'attr_val');
        $this->assertFalse($m->hasErrors('attr_val'));
    }
Qiang Xue committed
62
}