Skip to content

Commit

Permalink
Switch tests to the middleware logging system (#9418)
Browse files Browse the repository at this point in the history
  • Loading branch information
derrabus authored Jan 23, 2022
1 parent f7822c7 commit 328f368
Show file tree
Hide file tree
Showing 43 changed files with 412 additions and 247 deletions.
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"phpbench/phpbench": "^0.16.10 || ^1.0",
"phpstan/phpstan": "1.4.1",
"phpunit/phpunit": "^7.5 || ^8.5 || ^9.4",
"psr/log": "^1 || ^2 || ^3",
"squizlabs/php_codesniffer": "3.6.2",
"symfony/cache": "^4.4 || ^5.4 || ^6.0",
"symfony/yaml": "^3.4 || ^4.0 || ^5.0 || ^6.0",
Expand Down
33 changes: 33 additions & 0 deletions tests/Doctrine/Tests/DbalExtensions/Connection.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

namespace Doctrine\Tests\DbalExtensions;

use Doctrine\Common\EventManager;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\Connection as BaseConnection;
use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Logging\Middleware as LoggingMiddleware;

use function class_exists;

class Connection extends BaseConnection
{
/** @var QueryLog */
public $queryLog;

public function __construct(array $params, Driver $driver, ?Configuration $config = null, ?EventManager $eventManager = null)
{
$this->queryLog = new QueryLog();
if (class_exists(LoggingMiddleware::class)) {
$logging = new LoggingMiddleware(new SqlLogger($this->queryLog));
$driver = $logging->wrap($driver);
} else {
$config = $config ?? new Configuration();
$config->setSQLLogger(new LegacySqlLogger($this->queryLog));
}

parent::__construct($params, $driver, $config, $eventManager);
}
}
27 changes: 27 additions & 0 deletions tests/Doctrine/Tests/DbalExtensions/LegacySqlLogger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

declare(strict_types=1);

namespace Doctrine\Tests\DbalExtensions;

use Doctrine\DBAL\Logging\SQLLogger;

final class LegacySqlLogger implements SQLLogger
{
/** @var QueryLog */
private $queryLog;

public function __construct(QueryLog $queryLog)
{
$this->queryLog = $queryLog;
}

public function startQuery($sql, ?array $params = null, ?array $types = null): void
{
$this->queryLog->logQuery($sql, $params, $types);
}

public function stopQuery(): void
{
}
}
58 changes: 58 additions & 0 deletions tests/Doctrine/Tests/DbalExtensions/QueryLog.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

declare(strict_types=1);

namespace Doctrine\Tests\DbalExtensions;

final class QueryLog
{
/** @var bool */
public $enabled = false;

/** @var list<array{sql: string, params: array|null, types: array|null}> */
public $queries = [];

public function logQuery(string $sql, ?array $params = null, ?array $types = null): void
{
if (! $this->enabled) {
return;
}

$this->queries[] = [
'sql' => $sql,
'params' => $params,
'types' => $types,
];
}

/**
* @return $this
*/
public function reset(): self
{
$this->enabled = false;
$this->queries = [];

return $this;
}

/**
* @return $this
*/
public function enable(): self
{
$this->enabled = true;

return $this;
}

/**
* @return $this
*/
public function disable(): self
{
$this->enabled = false;

return $this;
}
}
31 changes: 31 additions & 0 deletions tests/Doctrine/Tests/DbalExtensions/SqlLogger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

namespace Doctrine\Tests\DbalExtensions;

use Psr\Log\AbstractLogger;

final class SqlLogger extends AbstractLogger
{
/** @var QueryLog */
private $queryLog;

public function __construct(QueryLog $queryLog)
{
$this->queryLog = $queryLog;
}

public function log($level, $message, array $context = []): void
{
if (! isset($context['sql'])) {
return;
}

$this->queryLog->logQuery(
$context['sql'],
$context['params'] ?? null,
$context['types'] ?? null
);
}
}
19 changes: 3 additions & 16 deletions tests/Doctrine/Tests/ORM/Functional/BasicFunctionalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

namespace Doctrine\Tests\ORM\Functional;

use Doctrine\DBAL\Logging\DebugStack;
use Doctrine\ORM\EntityNotFoundException;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\ORMInvalidArgumentException;
Expand Down Expand Up @@ -113,7 +112,6 @@ public function testOneToManyAssociationModification(): void

public function testBasicOneToOne(): void
{
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
$user = new CmsUser();
$user->name = 'Roman';
$user->username = 'romanb';
Expand Down Expand Up @@ -658,8 +656,6 @@ public function testFlushDoesNotIssueUnnecessaryUpdates(): void
$this->_em->persist($article);
$this->_em->persist($user);

//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);

$this->_em->flush();
$this->_em->clear();

Expand All @@ -669,14 +665,11 @@ public function testFlushDoesNotIssueUnnecessaryUpdates(): void
self::assertCount(1, $user2->articles);
self::assertInstanceOf(CmsAddress::class, $user2->address);

$oldLogger = $this->_em->getConnection()->getConfiguration()->getSQLLogger();
$debugStack = new DebugStack();
$this->_em->getConnection()->getConfiguration()->setSQLLogger($debugStack);

$countBeforeFlush = $this->getCurrentQueryCount();
$this->_em->flush();
self::assertCount(0, $debugStack->queries);
$countAfterFlush = $this->getCurrentQueryCount();

$this->_em->getConnection()->getConfiguration()->setSQLLogger($oldLogger);
self::assertSame($countBeforeFlush, $countAfterFlush);
}

public function testRemoveEntityByReference(): void
Expand All @@ -686,8 +679,6 @@ public function testRemoveEntityByReference(): void
$user->username = 'gblanco';
$user->status = 'developer';

//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);

$this->_em->persist($user);
$this->_em->flush();
$this->_em->clear();
Expand All @@ -698,8 +689,6 @@ public function testRemoveEntityByReference(): void
$this->_em->clear();

self::assertEquals(0, $this->_em->getConnection()->fetchOne('select count(*) from cms_users'));

//$this->_em->getConnection()->getConfiguration()->setSQLLogger(null);
}

public function testQueryEntityByReference(): void
Expand All @@ -721,8 +710,6 @@ public function testQueryEntityByReference(): void
});
$this->_em->clear();

//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);

$userRef = $this->_em->getReference(CmsUser::class, $user->getId());
$address2 = $this->_em->createQuery('select a from Doctrine\Tests\Models\CMS\CmsAddress a where a.user = :user')
->setParameter('user', $userRef)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ public function testOneToOneAssocToBaseTypeBidirectional(): void

public function testManyToManyToCTIHierarchy(): void
{
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
$mmrel = new CTIRelated2();
$child = new CTIChild();
$child->setData('child');
Expand Down
37 changes: 29 additions & 8 deletions tests/Doctrine/Tests/ORM/Functional/EntityRepositoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
use Doctrine\Common\Collections\Criteria;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\LockMode;
use Doctrine\DBAL\Logging\Middleware as LoggingMiddleware;
use Doctrine\DBAL\ParameterType;
use Doctrine\Deprecations\PHPUnit\VerifyDeprecations;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Exception\InvalidEntityRepository;
Expand All @@ -32,7 +34,9 @@
use Doctrine\Tests\Models\DDC753\DDC753InvalidRepository;
use Doctrine\Tests\OrmFunctionalTestCase;

use function array_pop;
use function array_fill;
use function array_values;
use function class_exists;
use function reset;

class EntityRepositoryTest extends OrmFunctionalTestCase
Expand Down Expand Up @@ -523,9 +527,9 @@ public function testIsNullCriteriaDoesNotGenerateAParameter(): void
$repos = $this->_em->getRepository(CmsUser::class);
$users = $repos->findBy(['status' => null, 'username' => 'romanb']);

$params = $this->_sqlLoggerStack->queries[$this->_sqlLoggerStack->currentQuery]['params'];
$params = $this->getLastLoggedQuery()['params'];
self::assertCount(1, $params, 'Should only execute with one parameter.');
self::assertEquals(['romanb'], $params);
self::assertEquals(['romanb'], array_values($params));
}

public function testIsNullCriteria(): void
Expand Down Expand Up @@ -718,11 +722,28 @@ public function testInvalidOrientation(): void
public function testFindByAssociationArray(): void
{
$repo = $this->_em->getRepository(CmsAddress::class);
$data = $repo->findBy(['user' => [1, 2, 3]]);

$query = array_pop($this->_sqlLoggerStack->queries);
self::assertEquals([1, 2, 3], $query['params'][0]);
self::assertEquals(Connection::PARAM_INT_ARRAY, $query['types'][0]);
$repo->findBy(['user' => [1, 2, 3]]);

if (! class_exists(LoggingMiddleware::class)) {
// DBAL 2 logs queries before resolving parameter positions
self::assertSame(
[
'sql' => 'SELECT t0.id AS id_1, t0.country AS country_2, t0.zip AS zip_3, t0.city AS city_4, t0.user_id AS user_id_5 FROM cms_addresses t0 WHERE t0.user_id IN (?)',
'params' => [[1, 2, 3]],
'types' => [Connection::PARAM_INT_ARRAY],
],
$this->getLastLoggedQuery()
);
} else {
self::assertSame(
[
'sql' => 'SELECT t0.id AS id_1, t0.country AS country_2, t0.zip AS zip_3, t0.city AS city_4, t0.user_id AS user_id_5 FROM cms_addresses t0 WHERE t0.user_id IN (?, ?, ?)',
'params' => [1 => 1, 2 => 2, 3 => 3],
'types' => array_fill(1, 3, ParameterType::INTEGER),
],
$this->getLastLoggedQuery()
);
}
}

/**
Expand Down
1 change: 0 additions & 1 deletion tests/Doctrine/Tests/ORM/Functional/FlushEventTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ protected function setUp(): void

public function testPersistNewEntitiesOnPreFlush(): void
{
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
$this->_em->getEventManager()->addEventListener(Events::onFlush, new OnFlushListener());

$user = new CmsUser();
Expand Down
2 changes: 0 additions & 2 deletions tests/Doctrine/Tests/ORM/Functional/LifecycleCallbackTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,6 @@ public function testPostLoadTriggeredOnRefresh(): void
*/
public function testCascadedEntitiesCallsPrePersist(): void
{
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);

$e1 = new LifecycleCallbackTestEntity();
$e2 = new LifecycleCallbackTestEntity();

Expand Down
23 changes: 12 additions & 11 deletions tests/Doctrine/Tests/ORM/Functional/Locking/LockTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@
use Exception;
use InvalidArgumentException;

use function array_pop;

/**
* @group locking
*/
Expand Down Expand Up @@ -175,13 +173,15 @@ public function testLockPessimisticWrite(): void
$this->_em->commit();
} catch (Exception $e) {
$this->_em->rollback();
}

throw $e;
$lastLoggedQuery = $this->getLastLoggedQuery()['sql'];
// DBAL 2 logs a commit as last query.
if ($lastLoggedQuery === '"COMMIT"') {
$lastLoggedQuery = $this->getLastLoggedQuery(1)['sql'];
}

$query = array_pop($this->_sqlLoggerStack->queries);
$query = array_pop($this->_sqlLoggerStack->queries);
self::assertStringContainsString($writeLockSql, $query['sql']);
self::assertStringContainsString($writeLockSql, $lastLoggedQuery);
}

/**
Expand Down Expand Up @@ -209,14 +209,15 @@ public function testLockPessimisticRead(): void
$this->_em->commit();
} catch (Exception $e) {
$this->_em->rollback();

throw $e;
}

array_pop($this->_sqlLoggerStack->queries);
$query = array_pop($this->_sqlLoggerStack->queries);
$lastLoggedQuery = $this->getLastLoggedQuery()['sql'];
// DBAL 2 logs a commit as last query.
if ($lastLoggedQuery === '"COMMIT"') {
$lastLoggedQuery = $this->getLastLoggedQuery(1)['sql'];
}

self::assertStringContainsString($readLockSql, $query['sql']);
self::assertStringContainsString($readLockSql, $lastLoggedQuery);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,15 +79,13 @@ public function testRemovesAManyToManyAssociation(): void

public function testEagerLoadFromInverseSideAndLazyLoadFromOwningSide(): void
{
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
$this->createLoadingFixture();
$categories = $this->findCategories();
$this->assertLazyLoadFromOwningSide($categories);
}

public function testEagerLoadFromOwningSideAndLazyLoadFromInverseSide(): void
{
//$this->_em->getConnection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger);
$this->createLoadingFixture();
$products = $this->findProducts();
$this->assertLazyLoadFromInverseSide($products);
Expand Down
Loading

0 comments on commit 328f368

Please sign in to comment.