Search code examples
yii2codeceptionfixtures

Codeception: testing app based on Yii2 with fixtures causes "too many connections" error


Following example shows how I load and unload fixture in any methods which need it:

class ServiceTest extends \Codeception\Test\Unit
{

    protected $tester;

    protected function loadFixture()
    {
        $this->tester->haveFixtures(['user' => ['class' => UserFixture::class]]);
    }

    protected function unLoadFixture()
    {
        $this->tester->grabFixture('user')->db->close();
    }

    public function testSuccessSignin()
    {
        $this->loadFixture();
        $form   = new SigninForm([
            'email'    => 'brady.renner@rutherford.com',
            'password' => '123456',
        ]);
        $result = Service::signin($form, new \yii\web\User([
            'identityClass' => Identity::class,
        ]));
        $this->assertTrue($result);
        $this->unLoadFixture();
    }
}

But seems db->close() not works properly and SHOW PROCESSLIST shows many connections in "Sleep" status when I run a test looking like above. Same happens when I load fixture by _before() or fixture() method (these methods are the unnecessary cause, not all methods need the fixture).


Solution

  • You need to pass the attribute persistent connection true for your database connection, see the issue here non GITHUB

    'db' => array(
          'class' => 'yii\db\Connection',
          'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_test',
          'username' => 'root',
          'password' => '',
          'tablePrefix' => '',
          'charset' => 'utf8',
          'attributes'=>[
               PDO::ATTR_PERSISTENT => true
          ]
     ),
    

    EDIT

    Apart from the above given solution if it does not work for you, you can try @Mik suggestion in comments, setting cleanup:false under yii2 module settings in the codeception Suit configurations see here