Files
e-ticket/tests/Service/MailerServiceTest.php

190 lines
7.8 KiB
PHP
Raw Normal View History

<?php
namespace App\Tests\Service;
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\Routing\Generator\UrlGeneratorInterface;
class MailerServiceTest extends TestCase
{
private MessageBusInterface $bus;
private UnsubscribeManager $unsubscribeManager;
private EntityManagerInterface $em;
private UrlGeneratorInterface $urlGenerator;
private string $projectDir;
protected function setUp(): void
{
$this->bus = $this->createMock(MessageBusInterface::class);
$this->unsubscribeManager = $this->createMock(UnsubscribeManager::class);
$this->em = $this->createMock(EntityManagerInterface::class);
$this->urlGenerator = $this->createMock(UrlGeneratorInterface::class);
$this->projectDir = sys_get_temp_dir().'/mailer_test_'.uniqid();
mkdir($this->projectDir.'/public', 0o777, true);
mkdir($this->projectDir.'/config/cert', 0o777, true);
}
protected function tearDown(): void
{
@unlink($this->projectDir.'/public/key.asc');
@unlink($this->projectDir.'/config/cert/certificate.pem');
@unlink($this->projectDir.'/config/cert/private-key.pem');
@rmdir($this->projectDir.'/config/cert');
@rmdir($this->projectDir.'/config');
@rmdir($this->projectDir.'/public');
@rmdir($this->projectDir);
}
private function createService(): MailerService
{
return new MailerService(
$this->bus,
$this->projectDir,
'passphrase',
Complete TASK_CHECKUP: security, UX, tests, coverage, accessibility, config externalization Billetterie: - Partial refund support (STATUS_PARTIALLY_REFUNDED, refundedAmount field, migration) - Race condition fix: PESSIMISTIC_WRITE lock on stock decrement in transaction - Idempotency key on PaymentIntent::create, reuse existing PI if stripeSessionId set - Disable checkout when event ended (server 400 + template hide) - Webhook deduplication via cache (24h TTL on stripe event.id) - Email validation (filter_var) in OrderController guest flow - JSON cart validation (structure check before processing) - Invitation expiration after 7 days (isExpired method + landing page message) - Stripe Checkout fallback when JS fails to load (noscript + redirect) Config externalization: - Move Stripe fees (STRIPE_FEE_RATE, STRIPE_FEE_FIXED) and admin email (ADMIN_EMAIL) to .env/services.yaml - Replace all hardcoded contact@e-cosplay.fr across 13 files - MailerService: getAdminEmail()/getAdminFrom(), default $from=null resolves to admin UX & Accessibility: - ARIA tabs: role=tablist/tab/tabpanel, aria-selected, keyboard nav (arrows, Home, End) - aria-label on cart +/- buttons and editor toolbar buttons - tabindex=0 on editor toolbar buttons for keyboard access - data-confirm handler in app.js (was only in admin.js) - Cart error feedback on checkout failure - Billet designer save feedback (loading/success/error states) - Stock polling every 30s with rupture/low stock badges - Back to event link on payment page Security: - HTML sanitizer: BLOCKED_TAGS list (script, style, iframe, svg, etc.) - content fully removed - Stripe polling timeout (15s max) with fallback redirect - Rate limiting on public order access (20/5min) - .catch() on all fetch() calls (sortable, billet-designer) Tests (92% PHP, 100% JS lines): - PCOV added to dev Dockerfile - Test DB setup: .env.test with DATABASE_URL, Redis auth, Meilisearch key - Rate limiter disabled in test env - Makefile: test_db_setup, test_db_reset, run_test_php, run_test_coverage_php/js - New tests: InvitationFlowTest (21), AuditServiceTest (4), ExportServiceTest (9), InvoiceServiceTest (4) - New tests: SuspendedUserSubscriberTest, RateLimiterSubscriberTest, MeilisearchServiceTest - New tests: Stripe webhook payment_failed (6) + charge.refunded (6) - New tests: BilletBuyer refund, User suspended, OrganizerInvitation expiration - JS tests: stock polling (6), data-confirm (2), copy-url restore (1), editor ARIA (2), XSS (9), tabs keyboard (9) - ESLint + PHP CS Fixer: 0 errors - SonarQube exclusions aligned with vitest coverage config Infra: - Meilisearch consistency command (app:meilisearch:check-consistency --fix) + cron daily 3am - MeilisearchService: getAllDocumentIds(), listIndexes() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 11:14:06 +01:00
'contact@test.com',
$this->urlGenerator,
$this->unsubscribeManager,
$this->em,
);
}
public function testGetAdminEmail(): void
{
$service = $this->createService();
self::assertSame('contact@test.com', $service->getAdminEmail());
}
public function testGetAdminFrom(): void
{
$service = $this->createService();
self::assertSame('E-Ticket <contact@test.com>', $service->getAdminFrom());
}
public function testSendEmailSkipsUnsubscribedRecipient(): void
{
$this->unsubscribeManager->method('isUnsubscribed')->willReturn(true);
$this->bus->expects(self::never())->method('dispatch');
$this->createService()->sendEmail('user@example.com', 'Subject', '<p>Body</p>');
}
public function testSendEmailDoesNotSkipWhitelistedAddress(): void
{
$this->unsubscribeManager->method('isUnsubscribed')->willReturn(true);
$this->urlGenerator->method('generate')->willReturn('https://example.com/track/abc');
$this->em->expects(self::once())->method('persist');
$this->em->expects(self::once())->method('flush');
$this->bus->expects(self::once())->method('dispatch')->willReturn(new Envelope(new \stdClass()));
Complete TASK_CHECKUP: security, UX, tests, coverage, accessibility, config externalization Billetterie: - Partial refund support (STATUS_PARTIALLY_REFUNDED, refundedAmount field, migration) - Race condition fix: PESSIMISTIC_WRITE lock on stock decrement in transaction - Idempotency key on PaymentIntent::create, reuse existing PI if stripeSessionId set - Disable checkout when event ended (server 400 + template hide) - Webhook deduplication via cache (24h TTL on stripe event.id) - Email validation (filter_var) in OrderController guest flow - JSON cart validation (structure check before processing) - Invitation expiration after 7 days (isExpired method + landing page message) - Stripe Checkout fallback when JS fails to load (noscript + redirect) Config externalization: - Move Stripe fees (STRIPE_FEE_RATE, STRIPE_FEE_FIXED) and admin email (ADMIN_EMAIL) to .env/services.yaml - Replace all hardcoded contact@e-cosplay.fr across 13 files - MailerService: getAdminEmail()/getAdminFrom(), default $from=null resolves to admin UX & Accessibility: - ARIA tabs: role=tablist/tab/tabpanel, aria-selected, keyboard nav (arrows, Home, End) - aria-label on cart +/- buttons and editor toolbar buttons - tabindex=0 on editor toolbar buttons for keyboard access - data-confirm handler in app.js (was only in admin.js) - Cart error feedback on checkout failure - Billet designer save feedback (loading/success/error states) - Stock polling every 30s with rupture/low stock badges - Back to event link on payment page Security: - HTML sanitizer: BLOCKED_TAGS list (script, style, iframe, svg, etc.) - content fully removed - Stripe polling timeout (15s max) with fallback redirect - Rate limiting on public order access (20/5min) - .catch() on all fetch() calls (sortable, billet-designer) Tests (92% PHP, 100% JS lines): - PCOV added to dev Dockerfile - Test DB setup: .env.test with DATABASE_URL, Redis auth, Meilisearch key - Rate limiter disabled in test env - Makefile: test_db_setup, test_db_reset, run_test_php, run_test_coverage_php/js - New tests: InvitationFlowTest (21), AuditServiceTest (4), ExportServiceTest (9), InvoiceServiceTest (4) - New tests: SuspendedUserSubscriberTest, RateLimiterSubscriberTest, MeilisearchServiceTest - New tests: Stripe webhook payment_failed (6) + charge.refunded (6) - New tests: BilletBuyer refund, User suspended, OrganizerInvitation expiration - JS tests: stock polling (6), data-confirm (2), copy-url restore (1), editor ARIA (2), XSS (9), tabs keyboard (9) - ESLint + PHP CS Fixer: 0 errors - SonarQube exclusions aligned with vitest coverage config Infra: - Meilisearch consistency command (app:meilisearch:check-consistency --fix) + cron daily 3am - MeilisearchService: getAllDocumentIds(), listIndexes() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 11:14:06 +01:00
$this->createService()->sendEmail('contact@test.com', 'Subject', '<p>Body</p>');
}
public function testSendEmailDispatchesForNonUnsubscribedUser(): void
{
$this->unsubscribeManager->method('isUnsubscribed')->willReturn(false);
$this->unsubscribeManager->method('generateToken')->willReturn('token123');
$this->urlGenerator->method('generate')->willReturn('https://example.com/url');
$this->em->expects(self::once())->method('persist');
$this->em->expects(self::once())->method('flush');
$this->bus->expects(self::once())->method('dispatch')->willReturn(new Envelope(new \stdClass()));
$this->createService()->sendEmail('user@example.com', 'Test', '<p>Content</p>');
}
public function testSendEmailWithoutUnsubscribeHeaders(): void
{
$this->urlGenerator->method('generate')->willReturn('https://example.com/url');
$this->em->expects(self::once())->method('persist');
$this->em->expects(self::once())->method('flush');
$this->bus->expects(self::once())->method('dispatch')->willReturn(new Envelope(new \stdClass()));
$this->createService()->sendEmail('user@example.com', 'Test', '<p>Content</p>', withUnsubscribe: false);
}
public function testSendEmailWithReplyTo(): void
{
$this->unsubscribeManager->method('isUnsubscribed')->willReturn(false);
$this->unsubscribeManager->method('generateToken')->willReturn('token');
$this->urlGenerator->method('generate')->willReturn('https://example.com/url');
$this->em->expects(self::once())->method('persist');
$this->em->expects(self::once())->method('flush');
$this->bus->expects(self::once())->method('dispatch')->willReturn(new Envelope(new \stdClass()));
$this->createService()->sendEmail('user@example.com', 'Test', '<p>Content</p>', replyTo: 'reply@example.com');
}
public function testSendEmailWithAttachments(): void
{
$tmpFile = $this->projectDir.'/public/test.txt';
file_put_contents($tmpFile, 'test content');
$this->unsubscribeManager->method('isUnsubscribed')->willReturn(false);
$this->unsubscribeManager->method('generateToken')->willReturn('token');
$this->urlGenerator->method('generate')->willReturn('https://example.com/url');
$this->em->expects(self::once())->method('persist');
$this->em->expects(self::once())->method('flush');
$this->bus->expects(self::once())->method('dispatch')->willReturn(new Envelope(new \stdClass()));
$this->createService()->sendEmail('user@example.com', 'Test', '<p>Content</p>', attachments: [
['path' => $tmpFile, 'name' => 'test.txt'],
]);
@unlink($tmpFile);
}
public function testSendAttachesPublicKey(): void
{
file_put_contents($this->projectDir.'/public/key.asc', 'fake-pgp-key');
$this->unsubscribeManager->method('isUnsubscribed')->willReturn(false);
$this->unsubscribeManager->method('generateToken')->willReturn('token');
$this->urlGenerator->method('generate')->willReturn('https://example.com/url');
$this->em->expects(self::once())->method('persist');
$this->em->expects(self::once())->method('flush');
$this->bus->expects(self::once())->method('dispatch')->willReturn(new Envelope(new \stdClass()));
$this->createService()->sendEmail('user@example.com', 'Test', '<p>Content</p>');
}
public function testSendSignsWithSmime(): void
{
if (!\extension_loaded('openssl')) {
self::markTestSkipped('OpenSSL extension required');
}
$privKey = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]);
$csr = openssl_csr_new(['commonName' => 'test'], $privKey);
$cert = openssl_csr_sign($csr, null, $privKey, 1);
openssl_x509_export($cert, $certPem);
openssl_pkey_export($privKey, $keyPem, 'testpass');
file_put_contents($this->projectDir.'/config/cert/certificate.pem', $certPem);
file_put_contents($this->projectDir.'/config/cert/private-key.pem', $keyPem);
$service = new MailerService(
$this->bus,
$this->projectDir,
'testpass',
Complete TASK_CHECKUP: security, UX, tests, coverage, accessibility, config externalization Billetterie: - Partial refund support (STATUS_PARTIALLY_REFUNDED, refundedAmount field, migration) - Race condition fix: PESSIMISTIC_WRITE lock on stock decrement in transaction - Idempotency key on PaymentIntent::create, reuse existing PI if stripeSessionId set - Disable checkout when event ended (server 400 + template hide) - Webhook deduplication via cache (24h TTL on stripe event.id) - Email validation (filter_var) in OrderController guest flow - JSON cart validation (structure check before processing) - Invitation expiration after 7 days (isExpired method + landing page message) - Stripe Checkout fallback when JS fails to load (noscript + redirect) Config externalization: - Move Stripe fees (STRIPE_FEE_RATE, STRIPE_FEE_FIXED) and admin email (ADMIN_EMAIL) to .env/services.yaml - Replace all hardcoded contact@e-cosplay.fr across 13 files - MailerService: getAdminEmail()/getAdminFrom(), default $from=null resolves to admin UX & Accessibility: - ARIA tabs: role=tablist/tab/tabpanel, aria-selected, keyboard nav (arrows, Home, End) - aria-label on cart +/- buttons and editor toolbar buttons - tabindex=0 on editor toolbar buttons for keyboard access - data-confirm handler in app.js (was only in admin.js) - Cart error feedback on checkout failure - Billet designer save feedback (loading/success/error states) - Stock polling every 30s with rupture/low stock badges - Back to event link on payment page Security: - HTML sanitizer: BLOCKED_TAGS list (script, style, iframe, svg, etc.) - content fully removed - Stripe polling timeout (15s max) with fallback redirect - Rate limiting on public order access (20/5min) - .catch() on all fetch() calls (sortable, billet-designer) Tests (92% PHP, 100% JS lines): - PCOV added to dev Dockerfile - Test DB setup: .env.test with DATABASE_URL, Redis auth, Meilisearch key - Rate limiter disabled in test env - Makefile: test_db_setup, test_db_reset, run_test_php, run_test_coverage_php/js - New tests: InvitationFlowTest (21), AuditServiceTest (4), ExportServiceTest (9), InvoiceServiceTest (4) - New tests: SuspendedUserSubscriberTest, RateLimiterSubscriberTest, MeilisearchServiceTest - New tests: Stripe webhook payment_failed (6) + charge.refunded (6) - New tests: BilletBuyer refund, User suspended, OrganizerInvitation expiration - JS tests: stock polling (6), data-confirm (2), copy-url restore (1), editor ARIA (2), XSS (9), tabs keyboard (9) - ESLint + PHP CS Fixer: 0 errors - SonarQube exclusions aligned with vitest coverage config Infra: - Meilisearch consistency command (app:meilisearch:check-consistency --fix) + cron daily 3am - MeilisearchService: getAllDocumentIds(), listIndexes() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 11:14:06 +01:00
'contact@test.com',
$this->urlGenerator,
$this->unsubscribeManager,
$this->em,
);
$this->unsubscribeManager->method('isUnsubscribed')->willReturn(false);
$this->unsubscribeManager->method('generateToken')->willReturn('token');
$this->urlGenerator->method('generate')->willReturn('https://example.com/url');
$this->em->expects(self::once())->method('persist');
$this->em->expects(self::once())->method('flush');
$this->bus->expects(self::once())->method('dispatch')->willReturn(new Envelope(new \stdClass()));
$service->sendEmail('user@example.com', 'Test', '<p>Signed</p>');
}
}