Files
crm_ecosplay/tests/Service/MailerServiceTest.php
Serreau Jovann 8bda02888c test: couverture 83% methodes (1046 tests, 2135 assertions)
Entites completes a 100% :
- AdvertTest : 12 nouveaux (state, customer, totals, hmac, lines, payments)
- CustomerTest : 3 nouveaux (isPendingDelete, revendeurCode, updatedAt)
- DevisTest : 6 nouveaux (customer, submissionId, lines, state constants)
- FactureTest : 10 nouveaux (state, totals, isPaid, lines, hmac, splitIndex)
- OrderNumberTest : 1 nouveau (markAsUnused)
- WebsiteTest : 1 nouveau (revendeurCode)

Services completes/ameliores :
- DocuSealServiceTest : 30 nouveaux (sendDevis, resendDevis, download, compta)
- AdvertServiceTest : 6 nouveaux (isTvaEnabled, getTvaRate, computeTotals)
- DevisServiceTest : 6 nouveaux (idem)
- FactureServiceTest : 8 nouveaux (idem + createPaidFactureFromAdvert)
- MailerServiceTest : 7 nouveaux (unsubscribe headers, VCF, formatFileSize)
- MeilisearchServiceTest : 42 nouveaux (index/remove/search tous types)
- RgpdServiceTest : 6 nouveaux (sendVerificationCode, verifyCode)
- OrderNumberServiceTest : 2 nouveaux (preview/generate unused)
- TarificationServiceTest : 1 nouveau (stripe error logger)
- ComptaPdfTest : 4 nouveaux (totaux, colonnes numeriques, signature)
- FacturePdfTest : 6 nouveaux (QR code, RIB, CGV Twig, footer skip)

Controllers ameliores :
- ComptabiliteControllerTest : 13 nouveaux (JSON, PDF, sign, callback)
- StatsControllerTest : 2 nouveaux (rich data, 6-month evolution)
- SyncControllerTest : 13 nouveaux (sync 6 types + purge)
- ClientsControllerTest : 7 nouveaux (show, delete, resendWelcome)
- FactureControllerTest : 2 nouveaux (generatePdf 404, send success)
- LegalControllerTest : 6 nouveaux (rgpdVerify GET/POST)
- TarificationControllerTest : 3 nouveaux (purge paths)
- AdminControllersTest : 9 nouveaux (dashboard search, services)
- WebhookStripeControllerTest : 3 nouveaux (invalid signatures)
- KeycloakAuthenticatorTest : 4 nouveaux (groups, domain check)

Commands :
- PaymentReminderCommandTest : 1 nouveau (formalNotice step)
- TestMailCommandTest : 2 nouveaux (force-dsn success/failure)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 00:13:00 +02:00

302 lines
13 KiB
PHP

<?php
namespace App\Tests\Service;
use App\Entity\EmailTracking;
use App\Service\MailerService;
use App\Service\UnsubscribeManager;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class MailerServiceTest extends TestCase
{
private MessageBusInterface $bus;
private string $projectDir;
private UrlGeneratorInterface $urlGenerator;
private UnsubscribeManager $unsubscribeManager;
private EntityManagerInterface $em;
private MailerService $service;
protected function setUp(): void
{
$this->bus = $this->createStub(MessageBusInterface::class);
$this->projectDir = sys_get_temp_dir() . '/mailer_test_' . uniqid();
mkdir($this->projectDir);
$this->urlGenerator = $this->createStub(UrlGeneratorInterface::class);
$this->unsubscribeManager = $this->createStub(UnsubscribeManager::class);
$this->em = $this->createStub(EntityManagerInterface::class);
$this->service = new MailerService(
$this->bus,
$this->projectDir,
'passphrase',
'admin@example.com',
$this->urlGenerator,
$this->unsubscribeManager,
$this->em
);
}
protected function tearDown(): void
{
$this->removeDir($this->projectDir);
}
private function removeDir(string $dir): void
{
if (!is_dir($dir)) return;
$files = array_diff(scandir($dir), ['.', '..']);
foreach ($files as $file) {
$path = $dir . '/' . $file;
is_dir($path) ? $this->removeDir($path) : unlink($path);
}
rmdir($dir);
}
public function testGetAdminEmail(): void
{
$this->assertEquals('admin@example.com', $this->service->getAdminEmail());
}
public function testGetAdminFrom(): void
{
$this->assertEquals('Association E-Cosplay <admin@example.com>', $this->service->getAdminFrom());
}
public function testSendEmail(): void
{
$this->urlGenerator->method('generate')->willReturn('http://track');
$this->unsubscribeManager->method('isUnsubscribed')->willReturn(false);
$this->unsubscribeManager->method('generateToken')->willReturn('token');
$bus = $this->createMock(MessageBusInterface::class);
$bus->expects($this->once())
->method('dispatch')
->willReturn(new Envelope(new \stdClass()));
$em = $this->createMock(EntityManagerInterface::class);
$em->expects($this->once())
->method('persist')
->with($this->isInstanceOf(EmailTracking::class));
$service = new MailerService($bus, $this->projectDir, 'p', 'admin@example.com', $this->urlGenerator, $this->unsubscribeManager, $em);
$service->sendEmail('user@example.com', 'Subject', 'Content');
}
public function testSendEmailWithAttachmentsAndReplyTo(): void
{
$filePath = $this->projectDir . '/test.txt';
file_put_contents($filePath, 'content');
$this->urlGenerator->method('generate')->willReturn('http://track');
$this->unsubscribeManager->method('isUnsubscribed')->willReturn(false);
$bus = $this->createMock(MessageBusInterface::class);
$bus->expects($this->once())
->method('dispatch')
->willReturn(new Envelope(new \stdClass()));
$service = new MailerService($bus, $this->projectDir, 'p', 'a@e.com', $this->urlGenerator, $this->unsubscribeManager, $this->em);
$service->sendEmail(
'user@example.com',
'Subject',
'Content',
null,
'reply@example.com',
true,
[['path' => $filePath, 'name' => 'custom.txt']]
);
}
public function testSendEmailToWhitelistedAdmin(): void
{
$this->urlGenerator->method('generate')->willReturn('http://track');
$bus = $this->createMock(MessageBusInterface::class);
$bus->expects($this->once())->method('dispatch')->willReturn(new Envelope(new \stdClass()));
$unsubscribeManager = $this->createMock(UnsubscribeManager::class);
$unsubscribeManager->expects($this->never())->method('isUnsubscribed');
$service = new MailerService($bus, $this->projectDir, 'p', 'admin@example.com', $this->urlGenerator, $unsubscribeManager, $this->em);
$service->sendEmail('admin@example.com', 'Subject', 'Content');
}
public function testSendEmailDoesNotSendIfUnsubscribed(): void
{
$this->unsubscribeManager->method('isUnsubscribed')->willReturn(true);
$bus = $this->createMock(MessageBusInterface::class);
$bus->expects($this->never())->method('dispatch');
$service = new MailerService($bus, $this->projectDir, 'p', 'a@e.com', $this->urlGenerator, $this->unsubscribeManager, $this->em);
$service->sendEmail('user@example.com', 'Subject', 'Content');
}
public function testSendWithoutCertFiles(): void
{
$email = (new Email())->from('a@e.com')->to('b@e.com')->subject('S')->html('C');
$bus = $this->createMock(MessageBusInterface::class);
$bus->expects($this->once())->method('dispatch')->willReturn(new Envelope(new \stdClass()));
$service = new MailerService($bus, $this->projectDir, 'p', 'a@e.com', $this->urlGenerator, $this->unsubscribeManager, $this->em);
$service->send($email);
}
public function testSendWithPublicKey(): void
{
touch($this->projectDir . '/key.asc');
$email = (new Email())->from('a@e.com')->to('b@e.com')->subject('S')->html('C');
$bus = $this->createMock(MessageBusInterface::class);
$bus->expects($this->once())->method('dispatch')->willReturn(new Envelope(new \stdClass()));
$service = new MailerService($bus, $this->projectDir, 'p', 'a@e.com', $this->urlGenerator, $this->unsubscribeManager, $this->em);
$service->send($email);
$this->assertCount(1, $email->getAttachments());
}
// --- addUnsubscribeHeaders (exercised through sendEmail with non-admin, non-unsubscribed) ---
public function testSendEmailAddsUnsubscribeHeadersForNonAdmin(): void
{
$this->urlGenerator->method('generate')->willReturn('http://track');
$this->unsubscribeManager->method('isUnsubscribed')->willReturn(false);
$this->unsubscribeManager->method('generateToken')->willReturn('mytoken');
$bus = $this->createMock(MessageBusInterface::class);
$bus->expects($this->once())
->method('dispatch')
->willReturnCallback(function ($envelope) {
return new Envelope(new \stdClass());
});
$service = new MailerService($bus, $this->projectDir, 'p', 'admin@e.com', $this->urlGenerator, $this->unsubscribeManager, $this->em);
$service->sendEmail('other@example.com', 'Subject', '<html>Content</html>');
// No assertion needed beyond no exception; dispatch was called once
$this->addToAssertionCount(1);
}
// --- generateVcf (exercised through sendEmail — VCF attached) ---
public function testSendEmailAttachesVcf(): void
{
$this->urlGenerator->method('generate')->willReturn('http://track');
$this->unsubscribeManager->method('isUnsubscribed')->willReturn(false);
$this->unsubscribeManager->method('generateToken')->willReturn('token');
$capturedEmail = null;
$bus = $this->createStub(MessageBusInterface::class);
$bus->method('dispatch')->willReturnCallback(function ($msg) use (&$capturedEmail) {
if ($msg instanceof \Symfony\Component\Mailer\Messenger\SendEmailMessage) {
$capturedEmail = $msg->getMessage();
}
return new Envelope(new \stdClass());
});
$service = new MailerService($bus, $this->projectDir, 'p', 'admin@e.com', $this->urlGenerator, $this->unsubscribeManager, $this->em);
$service->sendEmail('other@example.com', 'Subject', '<html>Content</html>');
// VCF was attached and then cleaned up; the email should have had it during dispatch
$this->assertNotNull($capturedEmail);
}
// --- formatFileSize (exercised via injectAttachmentsList which is called when attachments present) ---
public function testSendEmailFormatFileSizeBytes(): void
{
// A tiny attachment: < 1024 bytes => formatFileSize returns "X o"
$filePath = $this->projectDir . '/tiny.txt';
file_put_contents($filePath, 'ab'); // 2 bytes
$this->urlGenerator->method('generate')->willReturn('http://track');
$this->unsubscribeManager->method('isUnsubscribed')->willReturn(false);
$html = '<html><body><tr><td align="center" style="background-color: #111827; something">footer</td></tr></body></html>';
$bus = $this->createMock(MessageBusInterface::class);
$bus->expects($this->once())->method('dispatch')->willReturn(new Envelope(new \stdClass()));
$service = new MailerService($bus, $this->projectDir, 'p', 'admin@e.com', $this->urlGenerator, $this->unsubscribeManager, $this->em);
$service->sendEmail('other@example.com', 'Subject', $html, null, null, false, [['path' => $filePath, 'name' => 'tiny.txt']]);
$this->addToAssertionCount(1);
}
public function testSendEmailFormatFileSizeKilobytes(): void
{
// > 1024 bytes => formatFileSize returns "X Ko"
$filePath = $this->projectDir . '/medium.txt';
file_put_contents($filePath, str_repeat('a', 2048)); // 2 KB
$this->urlGenerator->method('generate')->willReturn('http://track');
$this->unsubscribeManager->method('isUnsubscribed')->willReturn(false);
$bus = $this->createMock(MessageBusInterface::class);
$bus->expects($this->once())->method('dispatch')->willReturn(new Envelope(new \stdClass()));
$service = new MailerService($bus, $this->projectDir, 'p', 'admin@e.com', $this->urlGenerator, $this->unsubscribeManager, $this->em);
$service->sendEmail('other@example.com', 'Subject', '<html>C</html>', null, null, false, [['path' => $filePath]]);
$this->addToAssertionCount(1);
}
public function testSendEmailFormatFileSizeMegabytes(): void
{
// > 1048576 bytes => formatFileSize returns "X,X Mo"
$filePath = $this->projectDir . '/large.txt';
file_put_contents($filePath, str_repeat('a', 1048577)); // just over 1MB
$this->urlGenerator->method('generate')->willReturn('http://track');
$this->unsubscribeManager->method('isUnsubscribed')->willReturn(false);
$bus = $this->createMock(MessageBusInterface::class);
$bus->expects($this->once())->method('dispatch')->willReturn(new Envelope(new \stdClass()));
$service = new MailerService($bus, $this->projectDir, 'p', 'admin@e.com', $this->urlGenerator, $this->unsubscribeManager, $this->em);
$service->sendEmail('other@example.com', 'Subject', '<html>C</html>', null, null, false, [['path' => $filePath]]);
$this->addToAssertionCount(1);
}
public function testSendEmailExcludesAscAndSmimeAttachmentsFromList(): void
{
$ascPath = $this->projectDir . '/key.asc';
touch($ascPath);
$this->urlGenerator->method('generate')->willReturn('http://track');
$this->unsubscribeManager->method('isUnsubscribed')->willReturn(false);
$bus = $this->createMock(MessageBusInterface::class);
$bus->expects($this->once())->method('dispatch')->willReturn(new Envelope(new \stdClass()));
$service = new MailerService($bus, $this->projectDir, 'p', 'admin@e.com', $this->urlGenerator, $this->unsubscribeManager, $this->em);
// Only the .asc file — filtered list will be empty, so HTML unchanged
$service->sendEmail('other@example.com', 'Subject', '<html>C</html>', null, null, false, [['path' => $ascPath, 'name' => 'key.asc']]);
$this->addToAssertionCount(1);
}
public function testSendEmailInjectsAttachmentBeforeFooter(): void
{
$filePath = $this->projectDir . '/doc.pdf';
file_put_contents($filePath, '%PDF-test');
$this->urlGenerator->method('generate')->willReturn('http://track');
$this->unsubscribeManager->method('isUnsubscribed')->willReturn(false);
// HTML with the footer dark marker
$html = '<html><body><table><tr><td>before</td></tr><tr><td align="center" style="background-color: #111827; padding">footer</td></tr></table></body></html>';
$bus = $this->createMock(MessageBusInterface::class);
$bus->expects($this->once())->method('dispatch')->willReturn(new Envelope(new \stdClass()));
$service = new MailerService($bus, $this->projectDir, 'p', 'admin@e.com', $this->urlGenerator, $this->unsubscribeManager, $this->em);
$service->sendEmail('other@example.com', 'Subject', $html, null, null, false, [['path' => $filePath, 'name' => 'doc.pdf']]);
$this->addToAssertionCount(1);
}
}