Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Codeception didn't clean DB when inserting data through Yii2 models #4617

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
amkoro opened this issue Nov 10, 2017 · 6 comments
Closed

Codeception didn't clean DB when inserting data through Yii2 models #4617

amkoro opened this issue Nov 10, 2017 · 6 comments

Comments

@amkoro
Copy link

amkoro commented Nov 10, 2017

What are you trying to achieve?

I have a regular Yii2 models News and NewsImage. I have the only fixtures for news. Trying to write a test which will add new news item, get auto-generated id and insert new news_image item with such id.

What do you get instead?

Test executes successfully - no issues there. Table news stays empty, but table news_item have my test data (one row). It was not removed as I expected. You can see I have cleanup and transaction config options enabled, plus codeception output shows that "transaction cancelled".

Provide console output if related. Use -vvv mode for more details.

- NewsTest: News
  [yii\db\Connection::open] 'Opening DB connection: mysql:host=127.0.0.1;dbname=testdb'
  [Database] Transaction started
✔ NewsTest: News (0.09s)
  [Database] Transaction cancelled; all changes reverted.
<?php
namespace common\tests\unit\models;

use Codeception\Test\Unit;
use common\models\News;
use common\models\NewsImage;
use common\fixtures\News as NewsFixture;

class NewsTest extends Unit
{
    /**
     * @var \common\tests\UnitTester
     */
    protected $tester;

    public function _before()
    {
        $this->tester->haveFixtures([
            'news' => [
                'class' => NewsFixture::className(),
                'dataFile' => codecept_data_dir().'news.php'
            ]
        ]);
    }

    public function testNews()
    {
        $newsModel = new News();
        $newsModel->title = 'test title';
        $newsModel->description = 'description test';
        $this->assertTrue($newsModel->save());
        $newsId = $newsModel->id;

        $newsImageModel = new NewsImage();
        $newsImageModel->news_id = $newsId;
        $newsImageModel->uname = 'testuid';
        $this->assertTrue($newsImageModel->save());
    }
}

Details

  • Codeception version: 2.3.x-dev
  • PHP Version: 7.1.11
  • Operating System: Ubuntu 16.04
  • Installation type: Composer
  • List of installed packages (composer show)
codeception/mockery-module               0.2.3              Mockery Module for Codeception
codeception/phpbuiltinserver             v1.3.0             PhpBuiltinServer extension for Codeception
codeception/specify                      0.4.6              BDD code blocks for PHPUnit and Codeception
codeception/verify                       0.4.0              BDD assertion library for PHPUnit
phpunit/php-code-coverage                5.2.3              Library that provides collection, processing, and rendering functionality for PHP code coverage information.
phpunit/php-file-iterator                1.4.2              FilterIterator implementation that filters files based on a list of suffixes.
phpunit/php-text-template                1.2.1              Simple template engine.
phpunit/php-timer                        1.0.9              Utility class for timing
phpunit/php-token-stream                 2.0.1              Wrapper around PHP's tokenizer extension.
phpunit/phpunit                          6.4.4              The PHP Unit Testing framework.
phpunit/phpunit-mock-objects             4.0.4              Mock Object library for PHPUnit
yiisoft/yii2                             2.0.13             Yii PHP Framework Version 2
yiisoft/yii2-bootstrap                   2.0.7              The Twitter Bootstrap extension for the Yii framework
yiisoft/yii2-composer                    2.0.5              The composer plugin for Yii extension installer
yiisoft/yii2-debug                       2.0.12             The debugger extension for the Yii framework
yiisoft/yii2-faker                       2.0.3              Fixture generator. The Faker integration for the Yii framework.
yiisoft/yii2-gii                         2.0.5              The Gii extension for the Yii framework
yiisoft/yii2-queue                       dev-master 1ab8c05 Yii2 Queue Extension which supported DB, Redis, RabbitMQ, Beanstalk and Gearman
yiisoft/yii2-swiftmailer                 2.1.0              The SwiftMailer integration for the Yii framework
  • Suite configuration:
namespace: common\tests
actor: Tester
paths:
    tests: tests
    log: tests/_output
    data: tests/_data
    helpers: tests/_support
settings:
    bootstrap: _bootstrap.php
    colors: true
    memory_limit: 1024M
extensions:
    enabled:
        - Codeception\Extension\PhpBuiltinServer
    config:
        Codeception\Extension\PhpBuiltinServer:
            hostname: 127.0.0.1
            port: 8000
            autostart: true
            documentRoot: 'common/tests/_data'
modules:
    enabled:
        - Asserts
        - Yii2
    config:
        Yii2:
            configFile: 'config/test-local.php'
            part: [fixtures, orm]
            cleanup: true
            transaction: true
@Naktibalda
Copy link
Member

Do you use transactions in your models?
Mysql doesn't support nested transactions.

@amkoro
Copy link
Author

amkoro commented Nov 10, 2017

@Naktibalda no, I have a regular Yii2 model:

<?php
namespace common\models;

use yii\db\ActiveRecord;

/**
 * This is the model class for table "news_image".
 *
 * @property integer $id
 * @property string $news_id
 * @property string $uname
 */
class NewsImage extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'news_image';
    }

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

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'news_id' => 'News ID',
            'uname' => 'Uname',
        ];
    }
}

the same for "news"

@samdark samdark added the Yii label Nov 10, 2017
@amkoro
Copy link
Author

amkoro commented Nov 10, 2017

additional info:

  1. the issue appears only if I use fixtures
  2. it doesn't matter how you insert the second part of data: through model or through Yii::$app->db->createCommand()

@amkoro
Copy link
Author

amkoro commented Nov 13, 2017

Any idea how to fix the issue?

@bscheshirwork
Copy link
Contributor

bscheshirwork commented Nov 15, 2017

@amkoro this behavior has been changed

    public function _before()
    {
        $this->tester->haveFixtures([
            'news' => [
                'class' => NewsFixture::className(),
                'dataFile' => codecept_data_dir().'news.php'
            ]
        ]);
    }

use _fixtures instead of haveFixtures in before
(Example for Cest)

    public function _fixtures()
    {
        return [
            'news' => [
                'class' => NewsFixture::className(),
                'dataFile' => codecept_data_dir().'news.php'
            ]
        ];
    }

_fixtures run before beginTransaction:

foreach ($this->modules as $module) {
$module->_before($event->getTest());
}

// load fixtures before db transaction
if ($test instanceof \Codeception\Test\Cest) {
$this->loadFixtures($test->getTestClass());
} else {
$this->loadFixtures($test);
}
if ($this->config['transaction']
&& $this->app->has('db')
&& $this->app->db instanceof \yii\db\Connection
) {
$this->transaction = $this->app->db->beginTransaction();
$this->debugSection('Database', 'Transaction started');
}

_before run after beginTransaction

$this->executeBeforeMethods($this->testMethod, $I);

@SamMousa
Copy link
Collaborator

The Yii2 module has almost been completely rewritten with respect to database cleanup / transactions. I think this can be closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants