TimestampBehaviorTest.php 2.16 KB
Newer Older
1 2
<?php

3 4 5
namespace yiiunit\framework\behaviors;

use Yii;
6 7 8
use yiiunit\TestCase;
use yii\db\Connection;
use yii\db\ActiveRecord;
9
use yii\behaviors\TimestampBehavior;
10 11

/**
12
 * Unit test for [[\yii\behaviors\TimestampBehavior]].
Qiang Xue committed
13
 * @see TimestampBehavior
14 15
 *
 * @group behaviors
16
 */
17
class TimestampBehaviorTest extends TestCase
18 19 20 21 22 23 24 25 26 27 28 29 30
{
	/**
	 * @var Connection test db connection
	 */
	protected $dbConnection;

	public static function setUpBeforeClass()
	{
		if (!extension_loaded('pdo') || !extension_loaded('pdo_sqlite')) {
			static::markTestSkipped('PDO and SQLite extensions are required.');
		}
	}

Alexander Makarov committed
31 32
	public function setUp()
	{
Alexander Makarov committed
33 34 35 36 37 38 39 40 41 42
		$this->mockApplication([
			'components' => [
				'db' => [
					'class' => '\yii\db\Connection',
					'dsn' => 'sqlite::memory:',
				]
			]
		]);

		$columns = [
43
			'id' => 'pk',
Alexander Kochetov committed
44 45
			'created_at' => 'integer',
			'updated_at' => 'integer',
Alexander Makarov committed
46
		];
47
		Yii::$app->getDb()->createCommand()->createTable('test_auto_timestamp', $columns)->execute();
48 49 50 51 52 53 54 55 56 57 58 59 60 61
	}

	public function tearDown()
	{
		Yii::$app->getDb()->close();
		parent::tearDown();
	}

	// Tests :

	public function testNewRecord()
	{
		$currentTime = time();

62
		$model = new ActiveRecordTimestamp();
63 64
		$model->save(false);

Alexander Kochetov committed
65 66
		$this->assertTrue($model->created_at >= $currentTime);
		$this->assertTrue($model->updated_at >= $currentTime);
67 68 69 70 71 72 73 74 75
	}

	/**
	 * @depends testNewRecord
	 */
	public function testUpdateRecord()
	{
		$currentTime = time();

76
		$model = new ActiveRecordTimestamp();
77 78 79 80
		$model->save(false);

		$enforcedTime = $currentTime - 100;

Alexander Kochetov committed
81 82
		$model->created_at = $enforcedTime;
		$model->updated_at = $enforcedTime;
83 84
		$model->save(false);

Alexander Kochetov committed
85 86
		$this->assertEquals($enforcedTime, $model->created_at, 'Create time has been set on update!');
		$this->assertTrue($model->updated_at >= $currentTime, 'Update time has NOT been set on update!');
87
	}
88 89 90
}

/**
Qiang Xue committed
91
 * Test Active Record class with [[TimestampBehavior]] behavior attached.
92 93
 *
 * @property integer $id
Alexander Kochetov committed
94 95
 * @property integer $created_at
 * @property integer $updated_at
96
 */
97
class ActiveRecordTimestamp extends ActiveRecord
98 99 100
{
	public function behaviors()
	{
Alexander Makarov committed
101
		return [
102
			TimestampBehavior::className(),
Alexander Makarov committed
103
		];
104 105 106 107 108 109
	}

	public static function tableName()
	{
		return 'test_auto_timestamp';
	}
Alexander Makarov committed
110
}