Skip to content

Commit a0eb4e1

Browse files
authored
Merge pull request #1450 from derrabus/improvement/test-logger-impl
2 parents e6f64e3 + 2cd05b3 commit a0eb4e1

10 files changed

+45
-71
lines changed

composer.json

+1
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
"doctrine/orm": "^2.13 || ^3",
4141
"doctrine/persistence": "^2 || ^3",
4242
"doctrine/sql-formatter": "^1.0",
43+
"fig/log-test": "^1",
4344
"phpstan/phpstan": "^1.10",
4445
"phpstan/phpstan-deprecation-rules": "^1.1",
4546
"phpstan/phpstan-phpunit": "^1.3",

phpcs.xml.dist

+1-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
</rule>
3939

4040
<rule ref="Squiz.Strings.DoubleQuoteUsage.ContainsVar">
41-
<exclude-pattern>tests/TestLogger.php</exclude-pattern>
41+
<exclude-pattern>tests/LogUtil.php</exclude-pattern>
4242
<exclude-pattern>src/Tools/Console/ConsoleLogger.php</exclude-pattern>
4343
</rule>
4444

tests/AbstractMigrationTest.php

+4-1
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,12 @@
1212
use Doctrine\Migrations\Query\Query;
1313
use Doctrine\Migrations\Tests\Stub\AbstractMigrationStub;
1414
use Doctrine\Migrations\Tests\Stub\AbstractMigrationWithoutDownStub;
15+
use Psr\Log\Test\TestLogger;
1516

1617
class AbstractMigrationTest extends MigrationTestCase
1718
{
19+
use LogUtil;
20+
1821
private AbstractMigrationStub $migration;
1922

2023
private TestLogger $logger;
@@ -73,7 +76,7 @@ public function testWarnIfAddDefaultMessage(): void
7376
public function testWarnIfDontOutputMessageIfFalse(): void
7477
{
7578
$this->migration->warnIf(false, 'trallala');
76-
self::assertSame('', $this->getLogOutput($this->logger));
79+
self::assertSame([], $this->logger->records);
7780
}
7881

7982
public function testWriteInvokesOutputWriter(): void

tests/TestLogger.php tests/LogUtil.php

+16-18
Original file line numberDiff line numberDiff line change
@@ -4,51 +4,49 @@
44

55
namespace Doctrine\Migrations\Tests;
66

7-
use DateTime;
87
use DateTimeInterface;
9-
use Psr\Log\AbstractLogger;
8+
use Psr\Log\Test\TestLogger;
109
use Stringable;
1110

11+
use function array_map;
1212
use function gettype;
13+
use function implode;
1314
use function is_object;
1415
use function is_scalar;
1516
use function str_contains;
1617
use function strtr;
1718

18-
class TestLogger extends AbstractLogger
19+
trait LogUtil
1920
{
20-
/** @var string[] */
21-
public array $logs = [];
21+
private function getLogOutput(TestLogger $logger): string
22+
{
23+
return implode("\n", $this->getInterpolatedLogRecords($logger));
24+
}
2225

23-
/**
24-
* {@inheritDoc}
25-
*
26-
* @param string|Stringable $message
27-
* @param mixed[] $context
28-
*/
29-
public function log($level, $message, array $context = []): void
26+
/** @return list<string> */
27+
private function getInterpolatedLogRecords(TestLogger $logger): array
3028
{
31-
$this->logs[] = $this->interpolate($message, $context);
29+
return array_map($this->interpolate(...), $logger->records);
3230
}
3331

3432
/**
3533
* Interpolates context values into the message placeholders.
3634
*
37-
* @param mixed[] $context
35+
* @param array{level: mixed, message: string|Stringable, context: mixed[]} $record
3836
*/
39-
private function interpolate(string|Stringable $message, array $context): string
37+
private function interpolate(array $record): string
4038
{
41-
$message = (string) $message;
39+
$message = (string) $record['message'];
4240
if (! str_contains($message, '{')) {
4341
return $message;
4442
}
4543

4644
$replacements = [];
47-
foreach ($context as $key => $val) {
45+
foreach ($record['context'] as $key => $val) {
4846
if ($val === null || is_scalar($val) || $val instanceof Stringable) {
4947
$replacements["{{$key}}"] = $val;
5048
} elseif ($val instanceof DateTimeInterface) {
51-
$replacements["{{$key}}"] = $val->format(DateTime::RFC3339);
49+
$replacements["{{$key}}"] = $val->format(DateTimeInterface::RFC3339);
5250
} elseif (is_object($val)) {
5351
$replacements["{{$key}}"] = '[object ' . $val::class . ']';
5452
} else {

tests/Metadata/Storage/DebugLogger.php

-24
This file was deleted.

tests/Metadata/Storage/TableMetadataStorageTest.php

+7-7
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
use Doctrine\Migrations\Version\ExecutionResult;
2727
use Doctrine\Migrations\Version\Version;
2828
use PHPUnit\Framework\TestCase;
29+
use Psr\Log\Test\TestLogger;
2930

3031
use function sprintf;
3132

@@ -42,7 +43,7 @@ class TableMetadataStorageTest extends TestCase
4243
/** @var AbstractSchemaManager<AbstractPlatform> */
4344
private AbstractSchemaManager $schemaManager;
4445

45-
private DebugLogger $debugLogger;
46+
private TestLogger $testLogger;
4647

4748
private function getSqliteConnection(Configuration|null $configuration = null): Connection
4849
{
@@ -54,8 +55,8 @@ private function getSqliteConnection(Configuration|null $configuration = null):
5455
public function setUp(): void
5556
{
5657
$this->connectionConfig = new Configuration();
57-
$this->debugLogger = new DebugLogger();
58-
$this->connectionConfig->setMiddlewares([new Middleware($this->debugLogger)]);
58+
$this->testLogger = new TestLogger();
59+
$this->connectionConfig->setMiddlewares([new Middleware($this->testLogger)]);
5960
$this->connection = $this->getSqliteConnection($this->connectionConfig);
6061
$this->schemaManager = $this->connection->createSchemaManager();
6162

@@ -67,13 +68,12 @@ public function testSchemaIntrospectionExecutedOnlyOnce(): void
6768
{
6869
$this->storage->ensureInitialized();
6970

70-
$oldQueryCount = $this->debugLogger->count;
71+
$this->testLogger->reset();
7172
$this->storage->ensureInitialized();
72-
self::assertSame(0, $this->debugLogger->count - $oldQueryCount);
73+
self::assertCount(0, $this->testLogger->records);
7374

74-
$oldQueryCount = $this->debugLogger->count;
7575
$this->storage->getExecutedMigrations();
76-
self::assertSame(1, $this->debugLogger->count - $oldQueryCount);
76+
self::assertCount(1, $this->testLogger->records);
7777
}
7878

7979
public function testDifferentTableNotUpdatedOnRead(): void

tests/MigrationTestCase.php

-7
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,6 @@
88
use Doctrine\DBAL\DriverManager;
99
use PHPUnit\Framework\TestCase;
1010

11-
use function implode;
12-
1311
abstract class MigrationTestCase extends TestCase
1412
{
1513
public function getSqliteConnection(): Connection
@@ -18,9 +16,4 @@ public function getSqliteConnection(): Connection
1816

1917
return DriverManager::getConnection($params);
2018
}
21-
22-
public function getLogOutput(TestLogger $logger): string
23-
{
24-
return implode("\n", $logger->logs);
25-
}
2619
}

tests/MigratorTest.php

+3-2
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
use Doctrine\Migrations\Version\Direction;
2424
use Doctrine\Migrations\Version\Version;
2525
use PHPUnit\Framework\MockObject\MockObject;
26+
use Psr\Log\Test\TestLogger;
2627
use Symfony\Component\Console\Output\StreamOutput;
2728
use Symfony\Component\Stopwatch\Stopwatch;
2829
use Throwable;
@@ -79,8 +80,8 @@ public function testEmptyPlanShowsMessage(): void
7980
$planList = new MigrationPlanList([], Direction::UP);
8081
$migrator->migrate($planList, $this->migratorConfiguration);
8182

82-
self::assertCount(1, $this->logger->logs, 'should output the no migrations message');
83-
self::assertStringContainsString('No migrations', $this->logger->logs[0]);
83+
self::assertCount(1, $this->logger->records, 'should output the no migrations message');
84+
self::assertStringContainsString('No migrations', $this->logger->records[0]['message']);
8485
}
8586

8687
protected function createTestMigrator(): DbalMigrator

tests/Tools/Console/Command/MigrationVersionTest.php

+3-4
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,12 @@
1313
use Doctrine\Migrations\MigrationsRepository;
1414
use Doctrine\Migrations\Tests\Helper;
1515
use Doctrine\Migrations\Tests\MigrationTestCase;
16-
use Doctrine\Migrations\Tests\TestLogger;
1716
use Doctrine\Migrations\Tools\Console\Command\VersionCommand;
1817
use Doctrine\Migrations\Version\Direction;
1918
use Doctrine\Migrations\Version\ExecutionResult;
2019
use Doctrine\Migrations\Version\Version;
2120
use InvalidArgumentException;
21+
use Psr\Log\NullLogger;
2222
use Symfony\Component\Console\Helper\HelperSet;
2323
use Symfony\Component\Console\Helper\QuestionHelper;
2424
use Symfony\Component\Console\Tester\CommandTester;
@@ -40,13 +40,12 @@ protected function setUp(): void
4040
$configuration = new Configuration();
4141
$configuration->addMigrationsDirectory('DoctrineMigrations', sys_get_temp_dir());
4242

43-
$conn = $this->getSqliteConnection();
44-
$logger = new TestLogger();
43+
$conn = $this->getSqliteConnection();
4544

4645
$dependencyFactory = DependencyFactory::fromConnection(
4746
new ExistingConfiguration($configuration),
4847
new ExistingConnection($conn),
49-
$logger,
48+
new NullLogger(),
5049
);
5150

5251
$this->migrationRepository = $dependencyFactory->getMigrationRepository();

tests/Version/ExecutorTest.php

+10-7
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
use Doctrine\Migrations\ParameterFormatter;
1515
use Doctrine\Migrations\Provider\SchemaDiffProvider;
1616
use Doctrine\Migrations\Query\Query;
17-
use Doctrine\Migrations\Tests\TestLogger;
17+
use Doctrine\Migrations\Tests\LogUtil;
1818
use Doctrine\Migrations\Tests\Version\Fixture\EmptyTestMigration;
1919
use Doctrine\Migrations\Tests\Version\Fixture\VersionExecutorTestMigration;
2020
use Doctrine\Migrations\Version\DbalExecutor;
@@ -25,13 +25,16 @@
2525
use Exception;
2626
use PHPUnit\Framework\MockObject\MockObject;
2727
use PHPUnit\Framework\TestCase;
28+
use Psr\Log\Test\TestLogger;
2829
use Symfony\Component\Stopwatch\Stopwatch;
2930
use Symfony\Component\Stopwatch\StopwatchEvent;
3031
use Symfony\Component\Stopwatch\StopwatchPeriod;
3132
use Throwable;
3233

3334
class ExecutorTest extends TestCase
3435
{
36+
use LogUtil;
37+
3538
/** @var Connection&MockObject */
3639
private Connection $connection;
3740

@@ -90,7 +93,7 @@ public function testExecuteWithNoQueries(): void
9093
'++ migrating xx',
9194
'Migration xx was executed but did not result in any SQL statements.',
9295
'Migration xx migrated (took 100ms, used 100 memory)',
93-
], $this->logger->logs);
96+
], $this->getInterpolatedLogRecords($this->logger));
9497
}
9598

9699
public function testExecuteUp(): void
@@ -137,7 +140,7 @@ public function testExecuteUp(): void
137140
3 => 'SELECT 2 ',
138141
4 => 'Query took 100ms',
139142
5 => 'Migration test migrated (took 100ms, used 100 memory)',
140-
], $this->logger->logs);
143+
], $this->getInterpolatedLogRecords($this->logger));
141144
}
142145

143146
/** @test */
@@ -151,7 +154,7 @@ public function executeUpShouldAppendDescriptionWhenItIsNotEmpty(): void
151154

152155
$this->versionExecutor->execute($plan, $migratorConfiguration);
153156

154-
self::assertSame('++ migrating test (testing)', $this->logger->logs[0]);
157+
self::assertSame('++ migrating test (testing)', $this->getInterpolatedLogRecords($this->logger)[0]);
155158
}
156159

157160
public function testExecuteDown(): void
@@ -198,7 +201,7 @@ public function testExecuteDown(): void
198201
3 => 'SELECT 4 ',
199202
4 => 'Query took 100ms',
200203
5 => 'Migration test reverted (took 100ms, used 100 memory)',
201-
], $this->logger->logs);
204+
], $this->getInterpolatedLogRecords($this->logger));
202205
}
203206

204207
public function testExecuteDryRun(): void
@@ -261,7 +264,7 @@ public function testExecuteDryRun(): void
261264
'SELECT 1 ',
262265
'SELECT 2 ',
263266
'Migration test migrated (took 100ms, used 100 memory)',
264-
], $this->logger->logs);
267+
], $this->getInterpolatedLogRecords($this->logger));
265268
}
266269

267270
/** @test */
@@ -498,7 +501,7 @@ public function executeDownShouldAppendDescriptionWhenItIsNotEmpty(): void
498501
$migratorConfiguration,
499502
);
500503

501-
self::assertSame('++ reverting test', $this->logger->logs[0]);
504+
self::assertSame('++ reverting test', $this->getInterpolatedLogRecords($this->logger)[0]);
502505
}
503506

504507
protected function setUp(): void

0 commit comments

Comments
 (0)