AutoTimestampTest.php 2.37 KB
Newer Older
1 2
<?php

3 4 5
namespace yiiunit\framework\behaviors;

use Yii;
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
use yiiunit\TestCase;
use yii\db\Connection;
use yii\db\ActiveRecord;
use yii\behaviors\AutoTimestamp;

/**
 * Unit test for [[\yii\behaviors\AutoTimestamp]].
 * @see AutoTimestamp
 */
class AutoTimestampTest extends TestCase
{
	/**
	 * @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
29 30
	public function setUp()
	{
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
		$this->mockApplication(
			array(
				'components' => array(
					'db' => array(
						'class' => '\yii\db\Connection',
						'dsn' => 'sqlite::memory:',
					)
				)
			)
		);

		$columns = array(
			'id' => 'pk',
			'create_time' => 'integer',
			'update_time' => 'integer',
		);
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 ActiveRecordAutoTimestamp();
63 64 65 66 67 68 69 70 71 72 73 74 75
		$model->save(false);

		$this->assertTrue($model->create_time >= $currentTime);
		$this->assertTrue($model->update_time >= $currentTime);
	}

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

76
		$model = new ActiveRecordAutoTimestamp();
77 78 79 80 81 82 83 84 85 86 87
		$model->save(false);

		$enforcedTime = $currentTime - 100;

		$model->create_time = $enforcedTime;
		$model->update_time = $enforcedTime;
		$model->save(false);

		$this->assertEquals($enforcedTime, $model->create_time, 'Create time has been set on update!');
		$this->assertTrue($model->update_time >= $currentTime, 'Update time has NOT been set on update!');
	}
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
}

/**
 * Test Active Record class with [[AutoTimestamp]] behavior attached.
 *
 * @property integer $id
 * @property integer $create_time
 * @property integer $update_time
 */
class ActiveRecordAutoTimestamp extends ActiveRecord
{
	public function behaviors()
	{
		return array(
			'timestamp' => array(
				'class' => AutoTimestamp::className(),
				'attributes' => array(
					static::EVENT_BEFORE_INSERT => array('create_time', 'update_time'),
					static::EVENT_BEFORE_UPDATE => 'update_time',
				),
			),
		);
	}

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