DateValidatorTest.php 2.11 KB
Newer Older
Suralc committed
1 2 3 4 5 6
<?php

namespace yiiunit\framework\validators;

use DateTime;
use yii\validators\DateValidator;
7
use yiiunit\data\validators\models\FakedValidationModel;
Suralc committed
8 9 10 11 12
use yiiunit\TestCase;


class DateValidatorTest extends TestCase
{
13 14 15 16 17 18
	protected function setUp()
	{
		parent::setUp();
		$this->mockApplication();
	}

Suralc committed
19 20 21 22 23 24 25 26 27
	public function testEnsureMessageIsSet()
	{
		$val = new DateValidator;
		$this->assertTrue($val->message !== null && strlen($val->message) > 1);
	}

	public function testValidateValue()
	{
		$val = new DateValidator;
Qiang Xue committed
28 29 30 31 32
		$this->assertFalse($val->validate('3232-32-32'));
		$this->assertTrue($val->validate('2013-09-13'));
		$this->assertFalse($val->validate('31.7.2013'));
		$this->assertFalse($val->validate('31-7-2013'));
		$this->assertFalse($val->validate(time()));
Suralc committed
33
		$val->format = 'U';
Qiang Xue committed
34
		$this->assertTrue($val->validate(time()));
Suralc committed
35
		$val->format = 'd.m.Y';
Qiang Xue committed
36
		$this->assertTrue($val->validate('31.7.2013'));
Suralc committed
37
		$val->format = 'Y-m-!d H:i:s';
Qiang Xue committed
38
		$this->assertTrue($val->validate('2009-02-15 15:16:17'));
Suralc committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
	}

	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
Alexander Makarov committed
54
		$val = new DateValidator(['timestampAttribute' => 'attr_timestamp']);
Suralc committed
55 56 57 58 59 60 61 62 63 64
		$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
		);
65
		$val = new DateValidator();
Alexander Makarov committed
66
		$model = FakedValidationModel::createWithAttributes(['attr_date' => []]);
67 68
		$val->validateAttribute($model, 'attr_date');
		$this->assertTrue($model->hasErrors('attr_date'));
Suralc committed
69 70

	}
Qiang Xue committed
71
}