FitTech
@FitTech

Почему не удаляются данные фикстуры из базы?

Здравствуйте! Разбираюсь с тестированием(Yii2 basic), пока что unit тесты. Подключил фикстуру для класса User, пользователи во время работы теста в базу(тестовую) добавляются, но после выполнения они от туда не удаляются. Подскажите, пожалуйста, почему?

В папке config есть файл test_db.php, настроил тестовую базу.
Установил codeception. Появилась папка tests. В unit.suite.yml добавил fixtures.

В наличии:
Модель User
<?php

namespace app\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "user".
 *
 * @property int $id
 * @property string $username
 * @property int $created_at
 *
 * @property Bill[] $bills
 * @property Transaction[] $transactions
 * @property Transaction[] $transactions0
 */
class User extends \yii\db\ActiveRecord implements IdentityInterface
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username'], 'required'],
            [['created_at'], 'integer'],
            [['username'], 'string', 'max' => 255],
            [['username'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'created_at' => 'Created At',
        ];
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'updatedAtAttribute' => false
            ],
        ];
    }

    public function afterSave($insert, $changedAttributes){
        parent::afterSave($insert, $changedAttributes);
        // Add bill for new user;
        Bill::create($this->id);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getBill()
    {
        return $this->hasOne(Bill::className(), ['user_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRecipient()
    {
        return $this->hasMany(Transaction::className(), ['recipient_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getSender()
    {
        return $this->hasMany(Transaction::className(), ['sender_id' => 'id']);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        // TODO: Implement findIdentityByAccessToken() method.
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        // TODO: Implement findIdentityByAccessToken() method.
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        // TODO: Implement validateAuthKey() method.
    }

    /**
     * @param int|string $id
     * @return null|IdentityInterface|static
     */
    public static function findIdentity($id)
    {
        return self::findOne($id);
    }

    public function getId()
    {
        return $this->id;
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return $user = User::findOne(['username' => $username]);
    }
}


Тестирую класс Site, SiteTest.php

<?php

namespace tests;

use app\models\form\LoginForm;
use app\tests\fixtures\UserFixture;

class SiteTest extends \Codeception\Test\Unit
{
    /**
     * @var \UnitTester
     */
    protected $tester;

    public function _fixtures()
    {
        return ['users' => UserFixture::className()];
    }

    public function testLogin()
    {
        $user = $this->tester->grabFixture('users', 'user1');

        $login = new LoginForm();
        $login->username = $user->username;
    }
}


Фикстура User

<?php

namespace app\tests\fixtures;

use yii\test\ActiveFixture;

class UserFixture extends ActiveFixture
{
    public $modelClass = 'app\models\User';
}


Файл для фикстуры user.php:

<?php

    return [
        'user1' => [
            'id' => 1,
            'username' => 'test1',
            'created_at' => 1542814772
        ],
        'user2' => [
            'id' => 2,
            'username' => 'test2',
            'created_at' => 1542814773
        ],
        'user3' => [
            'id' => 3,
            'username' => 'test3',
            'created_at' => 1542814774
        ]
    ];


Запускаю ./vendor/bin/codecept run unit SiteTest, первый раз отрабатывает и добавляет пользователей в тестовую базу, после окончания теста данные остаются в базе, а не удаляются. Следующий запуск теста данные не добавляет если они есть в базе.
  • Вопрос задан
  • 134 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы