added various tests for playwright

This commit is contained in:
Codex Agent
2025-12-19 21:56:39 +01:00
parent 778ffc8bb9
commit 18297aa3f1
23 changed files with 818 additions and 109 deletions

View File

@@ -68,6 +68,45 @@ class PaddleWebhookControllerTest extends TestCase
);
}
public function test_duplicate_transaction_is_idempotent(): void
{
config(['paddle.webhook_secret' => 'test_secret']);
[$tenant, $package, $session] = $this->prepareSession();
$payload = [
'event_type' => 'transaction.completed',
'data' => [
'id' => 'txn_dup',
'status' => 'completed',
'checkout_id' => 'chk_dup',
'metadata' => [
'checkout_session_id' => $session->id,
'tenant_id' => (string) $tenant->id,
'package_id' => (string) $package->id,
],
],
];
$signature = hash_hmac('sha256', json_encode($payload), 'test_secret');
$first = $this->withHeader('Paddle-Webhook-Signature', $signature)
->postJson('/paddle/webhook', $payload);
$first->assertOk()->assertJson(['status' => 'processed']);
$second = $this->withHeader('Paddle-Webhook-Signature', $signature)
->postJson('/paddle/webhook', $payload);
$second->assertStatus(200)->assertJson(['status' => 'processed']);
$this->assertSame(1, PackagePurchase::query()->count());
$session->refresh();
$this->assertEquals(CheckoutSession::STATUS_COMPLETED, $session->status);
$this->assertEquals('txn_dup', Arr::get($session->provider_metadata, 'paddle_transaction_id'));
}
public function test_rejects_invalid_signature(): void
{
config(['paddle.webhook_secret' => 'secret']);

View File

@@ -0,0 +1,103 @@
<?php
namespace Tests\Feature;
use Fruitcake\Cors\CorsService;
use Illuminate\Http\Middleware\HandleCors;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Tests\TestCase;
class SecurityHeadersTest extends TestCase
{
public function test_marketing_and_auth_responses_have_security_headers_and_csrf_cookie(): void
{
$originalEnv = app()->environment();
app()->detectEnvironment(fn () => 'production');
config([
'app.debug' => false,
'app.url' => 'https://test-y0k0.fotospiel.app',
'security_headers.force_hsts' => true,
'cors.allowed_origins' => ['https://test-y0k0.fotospiel.app'],
'cors.paths' => ['*'],
]);
Route::middleware('web')->get('/__test/marketing', fn () => response('ok'));
Route::middleware('web')->get('/__test/auth', fn () => response('ok'));
try {
$response = $this->withServerVariables([
'HTTPS' => 'on',
'HTTP_ORIGIN' => 'https://test-y0k0.fotospiel.app',
])->get('/__test/marketing');
$response->assertOk();
$response->assertHeader('X-Frame-Options', 'SAMEORIGIN');
$response->assertHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
$response->assertHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
$response->assertHeader('Content-Security-Policy');
$response->assertHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
$response->assertCookie('XSRF-TOKEN');
$login = $this->withServerVariables([
'HTTPS' => 'on',
'HTTP_ORIGIN' => 'https://test-y0k0.fotospiel.app',
])->get('/__test/auth');
$login->assertOk();
$login->assertHeader('Content-Security-Policy');
$login->assertHeader('X-Frame-Options', 'SAMEORIGIN');
$login->assertCookie('XSRF-TOKEN');
} finally {
app()->detectEnvironment(fn () => $originalEnv);
}
}
public function test_cors_headers_present_for_api_requests_and_error_responses_keep_headers(): void
{
$originalEnv = app()->environment();
app()->detectEnvironment(fn () => 'production');
$corsConfig = config('cors');
$corsConfig['paths'] = ['*'];
$corsConfig['allowed_origins'] = ['https://test-y0k0.fotospiel.app'];
config([
'app.debug' => false,
'app.url' => 'https://test-y0k0.fotospiel.app',
'cors' => $corsConfig,
]);
Route::middleware('web')->get('/__test/error', fn () => throw new \RuntimeException('boom'));
try {
$corsMiddleware = new HandleCors(app(), new CorsService(config('cors')));
$this->assertContains('*', config('cors.paths'));
$this->assertContains('https://test-y0k0.fotospiel.app', config('cors.allowed_origins'));
$corsRequest = Request::create(
uri: '/api/__test/cors',
method: 'OPTIONS',
server: [
'HTTP_ORIGIN' => 'https://test-y0k0.fotospiel.app',
'HTTPS' => 'on',
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'GET',
],
);
$this->assertSame('https://test-y0k0.fotospiel.app', $corsRequest->headers->get('Origin'));
$corsResponse = $corsMiddleware->handle($corsRequest, fn () => response()->noContent());
$this->assertSame('https://test-y0k0.fotospiel.app', $corsResponse->headers->get('Access-Control-Allow-Origin'));
$error = $this->withServerVariables([
'HTTPS' => 'on',
])->get('/__test/error');
$error->assertStatus(500);
$error->assertHeader('Content-Security-Policy');
$error->assertHeader('X-Frame-Options', 'SAMEORIGIN');
} finally {
app()->detectEnvironment(fn () => $originalEnv);
}
}
}

View File

@@ -0,0 +1,58 @@
<?php
namespace Tests\Feature;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tests\TestCase;
class SentryReportingTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
config(['sentry.dsn' => 'https://example@sentry.test/1']);
}
public function test_reports_server_errors_to_sentry(): void
{
$fake = new class
{
public int $captured = 0;
public function captureException(mixed $exception = null): void
{
$this->captured++;
}
};
$this->app->instance('sentry', $fake);
$handler = $this->app->make(\App\Exceptions\Handler::class);
$handler->report(new \RuntimeException('boom'));
$this->assertSame(1, $fake->captured, 'Sentry should receive server errors');
}
public function test_ignores_client_errors_for_sentry(): void
{
$fake = new class
{
public int $captured = 0;
public function captureException(mixed $exception = null): void
{
$this->captured++;
}
};
$this->app->instance('sentry', $fake);
$handler = $this->app->make(\App\Exceptions\Handler::class);
$handler->report(new HttpException(404));
$this->assertSame(0, $fake->captured, 'Sentry should ignore 4xx errors');
}
}

View File

@@ -0,0 +1,30 @@
import { test, expect } from '@playwright/test';
const shouldRun = process.env.E2E_BRUTEFORCE === '1';
test.describe('Login brute-force throttle', () => {
test.skip(!shouldRun, 'Set E2E_BRUTEFORCE=1 to run brute-force throttle check against the live/staging site.');
test('repeated bad logins eventually trigger throttle', async ({ request }) => {
const attemptPayload = {
email: 'nonexistent-user@example.com',
password: 'WrongPass123!',
};
const statuses: number[] = [];
const bodies: string[] = [];
for (let i = 0; i < 8; i += 1) {
const response = await request.post('/login', {
form: attemptPayload,
failOnStatusCode: false,
});
statuses.push(response.status());
bodies.push(await response.text());
}
const hitThrottle = statuses.includes(429) || bodies.some((body) => /too many.+attempt/i.test(body));
expect(hitThrottle).toBeTruthy();
});
});

View File

@@ -0,0 +1,41 @@
import { expect, test } from '@playwright/test';
const shouldRun = process.env.E2E_CONTACT_SPAM === '1';
const baseUrl = process.env.E2E_BASE_URL ?? 'https://test-y0k0.fotospiel.app';
test.describe('Marketing contact form spam/throttle', () => {
test.skip(!shouldRun, 'Set E2E_CONTACT_SPAM=1 to run contact spam/throttle check on staging.');
test('honeypot rejects bot submission and throttling kicks in', async ({ page }) => {
await page.goto(`${baseUrl}/de#contact`);
const acceptCookies = page.getByRole('button', { name: /akzeptieren|accept/i });
if (await acceptCookies.isVisible()) {
await acceptCookies.click();
}
// Fill visible fields
await page.fill('input[name="name"]', 'Spam Bot');
await page.fill('input[name="email"]', 'spam@example.com');
await page.fill('textarea[name="message"]', 'Test spam message');
// Trip honeypot
await page.$eval('input[name="nickname"]', (el: HTMLInputElement) => {
el.value = 'bot-field';
});
const submit = page.getByRole('button', { name: /senden|absenden|submit/i }).first();
await submit.click();
await expect(page.locator('text=/error|ungültig|invalid/i')).toBeVisible();
// Rapid resubmits to trigger throttle (best-effort)
for (let i = 0; i < 5; i += 1) {
await submit.click();
}
// Either error message or no success flash should be present
const success = page.locator('text=/Danke|Erfolg|success/i');
await expect(success).not.toBeVisible({ timeout: 1000 });
});
});

View File

@@ -1,82 +0,0 @@
import { test, expect } from '@playwright/test';
import { execSync } from 'child_process'; // Für artisan seed
test.describe('Marketing Package Flow: Auswahl → Registrierung → Kauf (Free & Paid)', () => {
test.beforeAll(async () => {
// Seed Test-Tenant (einmalig)
execSync('php artisan tenant:add-dummy --email=test@example.com --password=password123 --first_name=Test --last_name=User --address="Teststr. 1" --phone="+49123"');
// Mock Verifizierung: Update DB (in Test-Env)
execSync('php artisan tinker --execute="App\\Models\\User::where(\'email\', \'test@example.com\')->update([\'email_verified_at\' => now()]);"');
});
test('Free-Paket-Flow mit Wizard (ID=1, Starter, eingeloggter User)', async ({ page }) => {
// Login first
await page.goto('http://localhost:8000/de/login');
await page.fill('[name="email"]', 'test@example.com');
await page.fill('[name="password"]', 'password123');
await page.getByRole('button', { name: 'Anmelden' }).click();
await expect(page).toHaveURL(/\/dashboard/);
// Go to Wizard
await page.goto('http://localhost:8000/purchase-wizard/10');
await expect(page.locator('text=Sie sind bereits eingeloggt')).toBeVisible();
await page.getByRole('button', { name: 'Weiter zum Zahlungsschritt' }).click();
await expect(page).toHaveURL(/\/purchase-wizard\/1/); // Next step
await page.screenshot({ path: 'wizard-logged-in.png', fullPage: true });
// Payment (Free: Success)
await expect(page.locator('text=Free package assigned')).toBeVisible();
await page.screenshot({ path: 'wizard-free-success.png', fullPage: true });
});
test('Wizard Login-Fehler mit Toast', async ({ page }) => {
await page.goto('http://localhost:8000/purchase-wizard/10');
// Switch to Login
await page.getByRole('button', { name: 'Anmelden' }).click();
await page.fill('[name="email"]', 'wrong@example.com');
await page.fill('[name="password"]', 'wrong');
await page.getByRole('button', { name: 'Anmelden' }).click();
await expect(page.locator('[data-testid="toast"]')).toBeVisible(); // Toast for error
await expect(page.locator('text=Ungültige Anmeldedaten')).toBeVisible(); // Inline error
await page.screenshot({ path: 'wizard-login-error.png', fullPage: true });
});
test('Wizard Registrierung-Fehler mit Toast', async ({ page }) => {
await page.goto('http://localhost:8000/purchase-wizard/10');
// Reg form with invalid data
await page.fill('[name="email"]', 'invalid');
await page.getByRole('button', { name: 'Registrieren' }).click();
await expect(page.locator('[data-testid="toast"]')).toBeVisible();
await expect(page.locator('text=Das E-Mail muss eine gültige E-Mail-Adresse sein')).toBeVisible();
await page.screenshot({ path: 'wizard-reg-error.png', fullPage: true });
});
test('Wizard Erfolgreiche Reg mit Success-Message', async ({ page }) => {
await page.goto('http://localhost:8000/purchase-wizard/10');
// Fill valid reg data (use unique email)
await page.fill('[name="first_name"]', 'TestReg');
await page.fill('[name="last_name"]', 'User');
await page.fill('[name="email"]', 'testreg@example.com');
await page.fill('[name="username"]', 'testreguser');
await page.fill('[name="address"]', 'Teststr. 1');
await page.fill('[name="phone"]', '+49123');
await page.fill('[name="password"]', 'Password123!');
await page.fill('[name="password_confirmation"]', 'Password123!');
await page.check('[name="privacy_consent"]');
await page.getByRole('button', { name: 'Registrieren' }).click();
await expect(page.locator('text=Sie sind nun eingeloggt')).toBeVisible(); // Success message
await page.waitForTimeout(2000); // Auto-next
await expect(page).toHaveURL(/\/purchase-wizard\/1/); // Payment step
await page.screenshot({ path: 'wizard-reg-success.png', fullPage: true });
});
test('Paid-Paket-Flow (ID=2, Pro mit Paddle)', async ({ page }) => {
// Ähnlich wie Free, aber package_id=2
await page.goto('http://localhost:8000/de/packages');
await page.getByRole('button', { name: 'Details anzeigen' }).nth(1).click(); // Zweites Paket (Paid)
// ... (Modal, Register/Login wie oben)
await expect(page).toHaveURL(/\/buy-packages\/2/);
await expect(page.getByAltText('Paddle')).toBeVisible();
});
});

View File

@@ -0,0 +1,44 @@
import { test, expect } from '@playwright/test';
test.describe('Marketing frontend smoke', () => {
test('landing renders without console errors and CTA leads to packages', async ({ page }) => {
const consoleErrors: string[] = [];
page.on('console', (msg) => {
if (msg.type() === 'error') {
consoleErrors.push(msg.text());
}
});
const response = await page.goto('/');
expect(response?.ok()).toBeTruthy();
const acceptCookies = page.getByRole('button', { name: /akzeptieren|accept/i });
if (await acceptCookies.isVisible()) {
await acceptCookies.click();
}
await expect(page.getByRole('heading', { level: 1, name: /Dein Event|Fotospiel/i })).toBeVisible();
const heroCta = page.getByRole('link', { name: /paket|packages|starten|ausprobieren/i }).first();
await expect(heroCta).toBeVisible();
await heroCta.click();
await expect(page).toHaveURL(/\/packages/);
await expect(page.getByRole('heading', { level: 1 })).toBeVisible();
expect(consoleErrors).toEqual([]);
});
test('packages page lists packages and register CTAs', async ({ page }) => {
const response = await page.goto('/packages');
expect(response?.ok()).toBeTruthy();
const acceptCookies = page.getByRole('button', { name: /akzeptieren|accept/i });
if (await acceptCookies.isVisible()) {
await acceptCookies.click();
}
const packageCards = page.locator('section >> text=/Starter|Standard|Premium/');
await expect(packageCards.first()).toBeVisible();
});
});

View File

@@ -0,0 +1,38 @@
import { expect, test } from '@playwright/test';
const shouldRun = process.env.E2E_PADDLE_SANDBOX === '1';
test.describe('Paddle sandbox checkout (staging)', () => {
test.skip(!shouldRun, 'Set E2E_PADDLE_SANDBOX=1 to run live sandbox checkout on staging.');
test('creates Paddle checkout session from packages page', async ({ page }) => {
const base = process.env.E2E_BASE_URL ?? 'https://test-y0k0.fotospiel.app';
await page.goto(`${base}/packages`);
const acceptCookies = page.getByRole('button', { name: /akzeptieren|accept/i });
if (await acceptCookies.isVisible()) {
await acceptCookies.click();
}
const checkoutButtons = page.locator('a:has-text("Paket") , a:has-text("Checkout"), a:has-text("Jetzt"), button:has-text("Checkout")');
const count = await checkoutButtons.count();
if (count === 0) {
test.skip('No checkout CTA found on packages page');
}
const [requestPromise] = await Promise.all([
page.waitForRequest('**/paddle/create-checkout'),
checkoutButtons.first().click(),
]);
const checkoutRequest = await requestPromise.response();
expect(checkoutRequest, 'Expected paddle/create-checkout request to resolve').toBeTruthy();
expect(checkoutRequest!.status()).toBeLessThan(400);
const body = await checkoutRequest!.json();
const checkoutUrl = body.checkout_url ?? body.url ?? '';
expect(checkoutUrl).toContain('paddle');
});
});

View File

@@ -0,0 +1,79 @@
import { expect, test } from '@playwright/test';
import { test as base } from '../helpers/test-fixtures';
const shouldRun = process.env.E2E_PADDLE_SANDBOX === '1';
const baseUrl = process.env.E2E_BASE_URL ?? 'https://test-y0k0.fotospiel.app';
const sandboxEmail = process.env.E2E_PADDLE_EMAIL ?? 'playwright-buyer@example.com';
test.describe('Paddle sandbox full flow (staging)', () => {
test.skip(!shouldRun, 'Set E2E_PADDLE_SANDBOX=1 to run live sandbox checkout on staging.');
test('create checkout, simulate webhook completion, and verify session completion', async ({ page, request }) => {
// Jump directly into wizard for Standard package (2)
await page.goto(`${baseUrl}/purchase-wizard/2`);
const acceptCookies = page.getByRole('button', { name: /akzeptieren|accept/i });
if (await acceptCookies.isVisible()) {
await acceptCookies.click();
}
// If login/register step is present, choose guest path or continue
const continueButtons = page.getByRole('button', { name: /weiter|continue/i });
if (await continueButtons.first().isVisible()) {
await continueButtons.first().click();
}
// Fill minimal registration form to reach payment step
await page.fill('input[name="first_name"]', 'Play');
await page.fill('input[name="last_name"]', 'Wright');
await page.fill('input[name="email"]', sandboxEmail);
await page.fill('input[name="address"]', 'Teststrasse 1, 12345 Berlin');
await page.fill('input[name="phone"]', '+49123456789');
await page.fill('input[name="username"]', 'playwright-buyer');
await page.fill('input[name="password"]', 'Password123!');
await page.fill('input[name="password_confirmation"]', 'Password123!');
const checkoutCta = page.getByRole('button', { name: /weiter zum zahlungsschritt|continue to payment|Weiter/i }).first();
await expect(checkoutCta).toBeVisible({ timeout: 20000 });
const [apiResponse] = await Promise.all([
page.waitForResponse((resp) => resp.url().includes('/paddle/create-checkout') && resp.status() < 500),
checkoutCta.click(),
]);
const checkoutPayload = await apiResponse.json();
const checkoutUrl: string = checkoutPayload.checkout_url ?? checkoutPayload.url ?? '';
expect(checkoutUrl).toContain('paddle');
// Navigate to checkout to ensure it loads (hosted page). Use sandbox card data if needed later.
await page.goto(checkoutUrl);
await expect(page).toHaveURL(/paddle/);
// Fetch latest session for this buyer
const latestSession = await request.get('/api/_testing/checkout/sessions/latest', {
params: { email: sandboxEmail },
});
expect(latestSession.status()).toBe(200);
const sessionJson = await latestSession.json();
const sessionId: string | undefined = sessionJson?.data?.id;
expect(sessionId, 'checkout session id').toBeTruthy();
// Simulate Paddle webhook completion
const simulate = await request.post(`/api/_testing/checkout/sessions/${sessionId}/simulate-paddle`, {
data: {
status: 'completed',
transaction_id: 'txn_playwright_' + Date.now(),
},
});
expect(simulate.status()).toBe(200);
// Confirm session is marked completed
const latestCompleted = await request.get('/api/_testing/checkout/sessions/latest', {
params: { status: 'completed', email: sandboxEmail },
});
expect(latestCompleted.status()).toBe(200);
});
});