Files
myep-team/tests/Logging/InjectUserProcessorTest.php
T

84 lines
2.6 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Tests\Logging;
use App\Logging\InjectUserProcessor;
use Monolog\Level;
use Monolog\LogRecord;
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\User\InMemoryUser;
/**
* The processor runs on every channel, so it sees whatever user the firewall of the request
* authenticated - including the in-memory user the stateless "api" firewall resolves its shared
* key to, which has no getId() and no getEmail(). That cost a stored submission a 500 once.
*
* Every case here passes a web SAPI: with "cli" the processor returns the system record before
* reaching any of this, which is exactly why no functional test caught the bug.
*/
class InjectUserProcessorTest extends TestCase
{
public function testAnApiFirewallUserIsLoggedByItsIdentifier(): void
{
$record = $this->process(new InMemoryUser('api', null, ['ROLE_API']));
$this->assertSame(
['id' => null, 'username' => 'api', 'roles' => ['ROLE_API']],
$record->extra['user']
);
}
public function testAnAnonymousRequestIsLoggedAsSystem(): void
{
$record = $this->process(null);
$this->assertSame('system', $record->extra['user']['username']);
}
public function testTheConsoleIsLoggedAsSystemEvenWithAUser(): void
{
$record = $this->process(new InMemoryUser('api', null, ['ROLE_API']), sapi: 'cli');
$this->assertSame('system', $record->extra['user']['username']);
}
public function testAnAlreadyResolvedUserIsLeftAlone(): void
{
$security = $this->createMock(Security::class);
$security->expects($this->never())->method('getUser');
$processor = new InjectUserProcessor($security, 'fpm-fcgi');
$record = $processor(self::record(['user' => ['username' => 'kept']]));
$this->assertSame(['username' => 'kept'], $record->extra['user']);
}
private function process(?InMemoryUser $user, string $sapi = 'fpm-fcgi'): LogRecord
{
$security = $this->createMock(Security::class);
$security->method('getUser')->willReturn($user);
$processor = new InjectUserProcessor($security, $sapi);
return $processor(self::record());
}
/**
* @param array<string, mixed> $extra
*/
private static function record(array $extra = []): LogRecord
{
return new LogRecord(
new \DateTimeImmutable(),
'api',
Level::Info,
'Application form submission received',
[],
$extra
);
}
}