Merge test/deflake-vacuous-tests: make vacuous feed/SSE tests real
Fix the SSE listener (ticket flow) and replace assert-nothing tests with real coverage: like toggle/count semantics, comment→SSE delivery, SSE reconnect on visibility change, per-tab SSE connection, and remove a safe-area no-op.
This commit is contained in:
@@ -3,8 +3,9 @@
|
|||||||
* `like-update` arrived for upload X within 5 seconds" without driving a
|
* `like-update` arrived for upload X within 5 seconds" without driving a
|
||||||
* second browser tab.
|
* second browser tab.
|
||||||
*
|
*
|
||||||
* The backend authenticates the SSE endpoint via `?token=` query param
|
* The backend authenticates the SSE endpoint via a single-use `?ticket=` minted
|
||||||
* (the EventSource API can't set headers).
|
* at POST /api/v1/stream/ticket (the raw JWT is never put in the URL). This helper
|
||||||
|
* does that exchange internally, so callers still just pass a JWT to `start()`.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export type SseEvent = { type: string; data: any; receivedAt: number };
|
export type SseEvent = { type: string; data: any; receivedAt: number };
|
||||||
@@ -17,7 +18,17 @@ export class SseListener {
|
|||||||
constructor(private baseUrl: string = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101') {}
|
constructor(private baseUrl: string = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101') {}
|
||||||
|
|
||||||
async start(token: string): Promise<void> {
|
async start(token: string): Promise<void> {
|
||||||
const url = `${this.baseUrl}/api/v1/stream?token=${encodeURIComponent(token)}`;
|
// Exchange the JWT for a single-use SSE ticket (the stream endpoint no longer
|
||||||
|
// accepts ?token=).
|
||||||
|
const ticketRes = await fetch(`${this.baseUrl}/api/v1/stream/ticket`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
});
|
||||||
|
if (ticketRes.status !== 200) {
|
||||||
|
throw new Error(`SSE ticket mint failed: ${ticketRes.status} ${await ticketRes.text()}`);
|
||||||
|
}
|
||||||
|
const { ticket } = await ticketRes.json();
|
||||||
|
const url = `${this.baseUrl}/api/v1/stream?ticket=${encodeURIComponent(ticket)}`;
|
||||||
// Use fetch with streaming since Node has no EventSource by default.
|
// Use fetch with streaming since Node has no EventSource by default.
|
||||||
const res = await fetch(url, { signal: this.controller.signal });
|
const res = await fetch(url, { signal: this.controller.signal });
|
||||||
if (!res.body) throw new Error('SSE response has no body');
|
if (!res.body) throw new Error('SSE response has no body');
|
||||||
|
|||||||
@@ -1,36 +1,100 @@
|
|||||||
/**
|
/**
|
||||||
* USER_JOURNEYS.md §7 — liking and commenting. SSE round-trip is
|
* USER_JOURNEYS.md §7 — liking and commenting.
|
||||||
* asserted by opening a second tab as a different user.
|
*
|
||||||
|
* Like behavior is asserted deterministically via the feed snapshot; the comment
|
||||||
|
* SSE round-trip is asserted by subscribing to the stream as a second user and
|
||||||
|
* waiting for the `new-comment` event to arrive.
|
||||||
*/
|
*/
|
||||||
import { test, expect } from '../../fixtures/test';
|
import { test, expect } from '../../fixtures/test';
|
||||||
import { SseListener } from '../../helpers/sse-listener';
|
import { SseListener } from '../../helpers/sse-listener';
|
||||||
|
import { uploadRaw, JPEG_MAGIC } from '../../helpers/upload-client';
|
||||||
|
|
||||||
|
const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
|
||||||
|
|
||||||
|
async function seedUpload(jwt: string, db: any, caption?: string): Promise<string> {
|
||||||
|
const body = new Uint8Array(1024);
|
||||||
|
body.set(JPEG_MAGIC, 0);
|
||||||
|
const res = await uploadRaw(jwt, body, { filename: 'a.jpg', contentType: 'image/jpeg', caption });
|
||||||
|
if (res.status !== 201) throw new Error(`seed upload failed: ${res.status} ${await res.text()}`);
|
||||||
|
const { id } = await res.json();
|
||||||
|
await db.setUploadCompressionStatus(id, 'done');
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function like(jwt: string, uploadId: string): Promise<number> {
|
||||||
|
const res = await fetch(`${BASE}/api/v1/upload/${uploadId}/like`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { Authorization: `Bearer ${jwt}` },
|
||||||
|
});
|
||||||
|
return res.status;
|
||||||
|
}
|
||||||
|
|
||||||
|
function findRow(feed: any, id: string): any {
|
||||||
|
const list: any[] = feed.uploads ?? feed.items ?? feed;
|
||||||
|
return list.find((u: any) => u.id === id);
|
||||||
|
}
|
||||||
|
|
||||||
test.describe('Feed — like + comment', () => {
|
test.describe('Feed — like + comment', () => {
|
||||||
test('like is idempotent against rapid double-click', async ({ api, guest }) => {
|
test('a like counts once per user and toggles off on repeat (no double-count)', async ({ api, guest, db }) => {
|
||||||
const a = await guest('Liker');
|
const author = await guest('Author');
|
||||||
// Seed an upload from a second user so `a` has something to like.
|
const liker = await guest('Liker');
|
||||||
const b = await guest('Author');
|
const uploadId = await seedUpload(author.jwt, db);
|
||||||
// Without a multipart helper in Node, we exercise the like endpoint directly
|
|
||||||
// and assert behavior via the public feed snapshot.
|
// Baseline: nobody has liked yet.
|
||||||
// (Spec is a placeholder until we add a Node-side upload helper or do
|
let row = findRow(await api.getFeed(liker.jwt), uploadId);
|
||||||
// the seed via UI.)
|
expect(row.like_count).toBe(0);
|
||||||
const feed = await api.getFeed(a.jwt);
|
expect(row.liked_by_me).toBe(false);
|
||||||
void feed;
|
|
||||||
void b;
|
// First like → counted exactly once.
|
||||||
|
expect(await like(liker.jwt, uploadId)).toBe(204);
|
||||||
|
row = findRow(await api.getFeed(liker.jwt), uploadId);
|
||||||
|
expect(row.like_count).toBe(1);
|
||||||
|
expect(row.liked_by_me).toBe(true);
|
||||||
|
|
||||||
|
// Liking again is a toggle → back to zero (guards against a regression that
|
||||||
|
// double-counts a repeated like instead of removing it).
|
||||||
|
expect(await like(liker.jwt, uploadId)).toBe(204);
|
||||||
|
row = findRow(await api.getFeed(liker.jwt), uploadId);
|
||||||
|
expect(row.like_count).toBe(0);
|
||||||
|
expect(row.liked_by_me).toBe(false);
|
||||||
|
|
||||||
|
// A second distinct user's like is counted independently (per-user semantics).
|
||||||
|
expect(await like(liker.jwt, uploadId)).toBe(204); // liker likes again → 1
|
||||||
|
expect(await like(author.jwt, uploadId)).toBe(204); // author likes too → 2
|
||||||
|
row = findRow(await api.getFeed(liker.jwt), uploadId);
|
||||||
|
expect(row.like_count).toBe(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('comment by user A → SSE new-comment delivered to user B', async ({ guest }) => {
|
test('comment by user A → SSE new-comment delivered to user B', async ({ guest, db }) => {
|
||||||
const a = await guest('A');
|
// SSE frames can take a keep-alive tick to flush through the reverse proxy, so
|
||||||
const b = await guest('B');
|
// both the stream connect and the delivery may cost up to ~30s each.
|
||||||
|
test.setTimeout(120_000);
|
||||||
|
const a = await guest('CommenterA');
|
||||||
|
const b = await guest('ListenerB');
|
||||||
|
|
||||||
|
// B subscribes to the stream BEFORE A comments, so the broadcast is captured.
|
||||||
const sse = new SseListener();
|
const sse = new SseListener();
|
||||||
await sse.start(b.jwt);
|
await sse.start(b.jwt);
|
||||||
|
|
||||||
// Without an upload helper, this currently only verifies that the SSE stream
|
try {
|
||||||
// *connects* for a guest. The comment send + receive assertion lands as soon
|
const uploadId = await seedUpload(a.jwt, db, 'pic');
|
||||||
// as we add a backend-side helper to inject uploads bypassing multipart.
|
const cRes = await fetch(`${BASE}/api/v1/upload/${uploadId}/comments`, {
|
||||||
expect(sse.allEvents().length).toBeGreaterThanOrEqual(0);
|
method: 'POST',
|
||||||
sse.stop();
|
headers: { Authorization: `Bearer ${a.jwt}`, 'Content-Type': 'application/json' },
|
||||||
void a;
|
body: JSON.stringify({ body: 'hello from A' }),
|
||||||
|
});
|
||||||
|
expect(cRes.status).toBe(201);
|
||||||
|
|
||||||
|
// B must receive the new-comment event for this upload. Generous timeout: SSE
|
||||||
|
// frames flush on the keep-alive tick through the compressing reverse proxy.
|
||||||
|
const evt = await sse.waitForEvent(
|
||||||
|
'new-comment',
|
||||||
|
(e) => e.data?.upload_id === uploadId,
|
||||||
|
45_000
|
||||||
|
);
|
||||||
|
expect(evt.data.comment_count).toBe(1);
|
||||||
|
} finally {
|
||||||
|
sse.stop();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,27 +1,51 @@
|
|||||||
/**
|
/**
|
||||||
* SSE reconnection after tab background. USER_JOURNEYS.md §17 / edge cases.
|
* SSE reconnection after tab background. USER_JOURNEYS.md §17 / edge cases.
|
||||||
|
*
|
||||||
|
* The app closes the EventSource on `document.hidden` and reopens it (minting a
|
||||||
|
* fresh ticket + new EventSource) when the tab becomes visible again — see
|
||||||
|
* frontend/src/lib/sse.ts. We assert the reconnect by counting stream-open
|
||||||
|
* requests rather than event delivery, which keeps the test fast and independent
|
||||||
|
* of the reverse proxy's SSE buffering.
|
||||||
*/
|
*/
|
||||||
import { test, expect } from '../../fixtures/test';
|
import { test, expect } from '../../fixtures/test';
|
||||||
|
|
||||||
|
/** Count EventSource opens (GET /api/v1/stream?ticket=…), not the ticket POST. */
|
||||||
|
function trackStreamOpens(page: import('@playwright/test').Page): () => number {
|
||||||
|
let n = 0;
|
||||||
|
page.on('request', (req) => {
|
||||||
|
if (req.method() === 'GET' && req.url().includes('/api/v1/stream?')) n++;
|
||||||
|
});
|
||||||
|
return () => n;
|
||||||
|
}
|
||||||
|
|
||||||
test.describe('Feed — SSE behavior', () => {
|
test.describe('Feed — SSE behavior', () => {
|
||||||
test('SSE reconnects after tab visibility goes hidden then visible', async ({ page, guest, signIn }) => {
|
test('backgrounding then foregrounding the tab opens a fresh SSE connection', async ({ page, guest, signIn }) => {
|
||||||
const h = await guest('SseReconnect');
|
const g = await guest('SseReconnect');
|
||||||
await signIn(page, h);
|
const streamOpens = trackStreamOpens(page);
|
||||||
await page.goto('/feed');
|
|
||||||
|
|
||||||
// Force-fire a visibilitychange to hidden, then back to visible. The app's
|
await signIn(page, g); // lands on /feed, which calls connectSse() on mount
|
||||||
// sse.ts is expected to close + reopen the EventSource around this.
|
// Initial connection established.
|
||||||
|
await expect.poll(streamOpens, { timeout: 10_000 }).toBeGreaterThanOrEqual(1);
|
||||||
|
const afterInitial = streamOpens();
|
||||||
|
|
||||||
|
// Background: the visibility handler reads document.hidden, so override that
|
||||||
|
// (not just visibilityState) before dispatching, or the close never fires.
|
||||||
await page.evaluate(() => {
|
await page.evaluate(() => {
|
||||||
Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });
|
Object.defineProperty(document, 'hidden', { configurable: true, get: () => true });
|
||||||
|
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'hidden' });
|
||||||
document.dispatchEvent(new Event('visibilitychange'));
|
document.dispatchEvent(new Event('visibilitychange'));
|
||||||
});
|
});
|
||||||
await page.waitForTimeout(500);
|
// Foreground again → connectSse() mints a new ticket and opens a new EventSource.
|
||||||
await page.evaluate(() => {
|
await page.evaluate(() => {
|
||||||
Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });
|
Object.defineProperty(document, 'hidden', { configurable: true, get: () => false });
|
||||||
|
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'visible' });
|
||||||
document.dispatchEvent(new Event('visibilitychange'));
|
document.dispatchEvent(new Event('visibilitychange'));
|
||||||
});
|
});
|
||||||
|
|
||||||
// App should still be functional — assert the bottom nav remains visible.
|
// A reconnect means a brand-new stream GET beyond the initial one.
|
||||||
|
await expect.poll(streamOpens, { timeout: 10_000 }).toBeGreaterThan(afterInitial);
|
||||||
|
|
||||||
|
// And the app is still functional.
|
||||||
await expect(page.getByRole('link', { name: 'Galerie' })).toBeVisible();
|
await expect(page.getByRole('link', { name: 'Galerie' })).toBeVisible();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -5,16 +5,30 @@
|
|||||||
import { test, expect } from '../../fixtures/test';
|
import { test, expect } from '../../fixtures/test';
|
||||||
|
|
||||||
test.describe('Browser chaos — multi-tab', () => {
|
test.describe('Browser chaos — multi-tab', () => {
|
||||||
test('same user in two tabs — SSE delivers to both', async ({ page, context, guest, signIn }) => {
|
test('same user in two tabs — each tab establishes its own SSE stream', async ({ page, context, guest, signIn }) => {
|
||||||
const g = await guest('Twin');
|
const g = await guest('Twin');
|
||||||
await signIn(page, g);
|
|
||||||
await page.goto('/feed');
|
// Count each tab's own EventSource open (GET /api/v1/stream?ticket=…). Asserting
|
||||||
|
// *connection establishment* is fast and reliable; asserting event *delivery* would
|
||||||
|
// depend on the reverse proxy's ~30s SSE buffering and isn't worth the flake here.
|
||||||
|
const streamOpens = (p: import('@playwright/test').Page) => {
|
||||||
|
let n = 0;
|
||||||
|
p.on('request', (req) => {
|
||||||
|
if (req.method() === 'GET' && req.url().includes('/api/v1/stream?')) n++;
|
||||||
|
});
|
||||||
|
return () => n;
|
||||||
|
};
|
||||||
|
|
||||||
|
const opens1 = streamOpens(page);
|
||||||
|
await signIn(page, g); // → /feed, connectSse() on mount
|
||||||
|
await expect.poll(opens1, { timeout: 10_000 }).toBeGreaterThanOrEqual(1);
|
||||||
|
|
||||||
const tab2 = await context.newPage();
|
const tab2 = await context.newPage();
|
||||||
|
const opens2 = streamOpens(tab2);
|
||||||
await signIn(tab2, g);
|
await signIn(tab2, g);
|
||||||
await tab2.goto('/feed');
|
await expect.poll(opens2, { timeout: 10_000 }).toBeGreaterThanOrEqual(1);
|
||||||
|
|
||||||
// Both tabs should mount the bottom nav.
|
// Both tabs mounted and each opened its own independent stream.
|
||||||
await expect(page.getByRole('link', { name: 'Galerie' })).toBeVisible();
|
await expect(page.getByRole('link', { name: 'Galerie' })).toBeVisible();
|
||||||
await expect(tab2.getByRole('link', { name: 'Galerie' })).toBeVisible();
|
await expect(tab2.getByRole('link', { name: 'Galerie' })).toBeVisible();
|
||||||
await tab2.close();
|
await tab2.close();
|
||||||
|
|||||||
@@ -45,20 +45,8 @@ test.describe('Mobile — safe-area insets', () => {
|
|||||||
expect(distanceFromBottom).toBeLessThanOrEqual(2);
|
expect(distanceFromBottom).toBeLessThanOrEqual(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('context sheet (when opened) carries the same safe-area declaration', async ({ page }) => {
|
// (A vacuous `/join` probe that only asserted `Array.isArray(...)` — always true —
|
||||||
// We can't easily open the context sheet without a feed card to long-press,
|
// was removed; the real sheet-level env() check is the structural test below.)
|
||||||
// but the markup lives in the layout once the route mounts. We probe by
|
|
||||||
// scanning every element with a `style` attribute for the env() reference.
|
|
||||||
await page.goto('/join');
|
|
||||||
const candidateStyles: string[] = await page.evaluate(() => {
|
|
||||||
return Array.from(document.querySelectorAll<HTMLElement>('[style]'))
|
|
||||||
.map((el) => el.getAttribute('style') ?? '')
|
|
||||||
.filter((s) => s.includes('env(safe-area-inset-bottom)'));
|
|
||||||
});
|
|
||||||
// On /join there may be zero — the assertion is more of a sanity check.
|
|
||||||
// On /feed and /account it would be ≥ 1. We assert that on /feed below.
|
|
||||||
expect(Array.isArray(candidateStyles)).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('upload sheet and context sheet both honor env() (structural check)', async ({ page, guest, signIn }) => {
|
test('upload sheet and context sheet both honor env() (structural check)', async ({ page, guest, signIn }) => {
|
||||||
const g = await guest('SafeAreaSheets');
|
const g = await guest('SafeAreaSheets');
|
||||||
|
|||||||
Reference in New Issue
Block a user