I'm writing integration/database tests for a Zend Framework 3 application by using
- zendframework/zend-test
3.1.0
, - phpunit/phpunit
6.2.2
, and - phpunit/dbunit
3.0.0
My tests are failing due to the
Connect Error: SQLSTATE[HY000] [1040] Too many connections
I set some breakpoints and took a look into the database:
SHOW STATUS WHERE `variable_name` = 'Threads_connected';
And I've actually seen over 100
opened connections.
I've reduced them by disconnecting in the tearDown()
:
protected function tearDown()
{
parent::tearDown();
if ($this->dbAdapter && $this->dbAdapter instanceof Adapter) {
$this->dbAdapter->getDriver()->getConnection()->disconnect();
}
}
But I still have over 80
opened connections.
How to decrease the number of the database connections in tests to a possible minimum?
more info
(1) I have a lot of tests, where I dispatch
a URI. Every such request causes at least one database request, that cause a new database connection. These connections seem not to be closed. This might cause the most connections. (But I haven't yet found a way to make the application close the connections after the request is processed.)
(2) One of the issues might be my testing against the database:
protected function retrieveActualData($table, $idColumn, $idValue)
{
$sql = new Sql($this->dbAdapter);
$select = $sql->select($table);
$select->where([$table . '.' . $idColumn . ' = ?' => $idValue]);
$statement = $sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
$data = $result->current();
return $data;
}
But the call of the $this->dbAdapter->getDriver()->getConnection()->disconnect()
before the return
gave nothing.
Example of usage in a test method:
public function testInputDataActionSaving()
{
// The getFormParams(...) returns an array with the needed input.
$formParams = $this->getFormParams(self::FORM_CREATE_CLUSTER);
$createWhateverUrl = '/whatever/create';
$this->dispatch($createWhateverUrl, Request::METHOD_POST, $formParams);
$this->assertEquals(
$formParams['whatever']['some_param'],
$this->retrieveActualData('whatever', 'id', 2)['some_param']
);
}
(3) Another issue might be in the PHPUnit (or my configuration of it?). (Striken out, because "PHPUnit does not do anything related to database connections.", see this comment.) Anyway, even if it's not a PHPUnit issue, the fact is, that after the line
$testSuite = $configuration->getTestSuiteConfiguration($this->arguments['testsuite'] ?? null);
in the PHPUnit\TextUI\Command
I get 31
new connections.