import { expect, test } from '@playwright/test'; /** * E2E tests for the admin area (M6). The Vite dev-server proxy is * intercepted with page.route, so these tests run without a backend. * * The admin area manages the article domain: * - list/search/sort/paginate articles (GET /api/v1/admin/articles) * - create articles (POST /api/v1/admin/articles) with a Lexical editor * - edit articles (PUT /api/v1/admin/articles/:id) * - delete articles (DELETE /api/v1/admin/articles/:id) * - reference data: GET /api/v1/admin/authors, /api/v1/admin/categories */ type WireAuthor = { id: number; name: string; email: string; bio: string | null }; type WireCategory = { id: number; name: string; slug: string }; type WireArticle = { id: number; title: string; content: string; author_id: number; category_id: number; created_at: string; published: boolean; author: WireAuthor; category: WireCategory; }; const AUTHORS: WireAuthor[] = [ { id: 1, name: 'Ada Lovelace', email: 'ada@example.com', bio: null }, { id: 2, name: 'Grace Hopper', email: 'grace@example.com', bio: null }, { id: 3, name: 'Alan Turing', email: 'alan@example.com', bio: null }, ]; const CATEGORIES: WireCategory[] = [ { id: 1, name: 'Technology', slug: 'technology' }, { id: 2, name: 'Science', slug: 'science' }, { id: 3, name: 'Sports', slug: 'sports' }, { id: 4, name: 'Culture', slug: 'culture' }, ]; function seedArticles(): WireArticle[] { return [ { id: 1, title: 'Fusion milestone: net energy gain repeated', content: '

Scientists again drew net energy from the reactor, marking the third repeat of the landmark result.

', author_id: 2, category_id: 2, created_at: '2024-05-03T11:30:00Z', published: true, author: AUTHORS[1], category: CATEGORIES[1], }, { id: 2, title: 'City marathon sets record turnout', content: '

First-timers flooded the course on Sunday as organizers beat last year\u2019s turnout.

', author_id: 3, category_id: 3, created_at: '2024-05-02T09:15:00Z', published: false, author: AUTHORS[2], category: CATEGORIES[2], }, { id: 3, title: 'Inside the new wave of open-source language models', content: '

Open-weight language models are reshaping who can build and deploy AI.

', author_id: 1, category_id: 1, created_at: '2024-05-01T10:00:00Z', published: true, author: AUTHORS[0], category: CATEGORIES[0], }, ]; } async function mockAdminApi( page: import('@playwright/test').Page, opts: { admin?: boolean; token?: string; signedOut?: boolean } = {}, ) { const store = seedArticles(); const nextId = { value: 100 }; const token = opts.token ?? (opts.admin === false ? 'user-token' : 'admin-token'); await page.route('**/api/v1/auth/me', async (route) => { if (opts.signedOut) { return route.fulfill({ status: 401, contentType: 'application/json', body: JSON.stringify({ detail: 'Not authenticated', code: 'unauthorized' }), }); } if (opts.admin === false) { return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ id: 2, username: 'user', is_admin: false }), }); } return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ id: 1, username: 'admin', is_admin: true }), }); }); await page.route('**/api/v1/auth/logout', async (route) => route.fulfill({ status: 204, contentType: 'application/json', body: JSON.stringify({}), }), ); await page.route('**/api/v1/admin/authors', async (route) => { if (opts.admin === false) { return route.fulfill({ status: 403, contentType: 'application/json', body: JSON.stringify({ detail: 'Admin access required', code: 'forbidden' }), }); } return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(AUTHORS), }); }); await page.route('**/api/v1/admin/categories', async (route) => { if (opts.admin === false) { return route.fulfill({ status: 403, contentType: 'application/json', body: JSON.stringify({ detail: 'Admin access required', code: 'forbidden' }), }); } return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(CATEGORIES), }); }); await page.route('**/api/v1/admin/articles**', async (route) => { const url = new URL(route.request().url()); const idMatch = url.pathname.match(/\/api\/v1\/admin\/articles\/(\d+)/); if (idMatch) { const id = Number(idMatch[1]); const article = store.find((a) => a.id === id); const method = route.request().method(); if (method === 'GET') { if (!article) { return route.fulfill({ status: 404, contentType: 'application/json', body: JSON.stringify({ detail: 'Article not found', code: 'not_found' }), }); } return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(article), }); } if (method === 'PUT') { if (!article) { return route.fulfill({ status: 404, contentType: 'application/json', body: JSON.stringify({ detail: 'Article not found', code: 'not_found' }), }); } const body = JSON.parse(route.request().postData() ?? '{}') as { title: string; content: string; author_id: number; category_id: number; published: boolean; }; Object.assign(article, { title: body.title, content: body.content, author_id: body.author_id, category_id: body.category_id, published: body.published, }); return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(article), }); } if (method === 'DELETE') { if (!article) { return route.fulfill({ status: 404, contentType: 'application/json', body: JSON.stringify({ detail: 'Article not found', code: 'not_found' }), }); } const index = store.indexOf(article); if (index >= 0) store.splice(index, 1); return route.fulfill({ status: 204, body: '' }); } return route.fulfill({ status: 405, contentType: 'application/json', body: JSON.stringify({ detail: 'Method not allowed', code: 'method_not_allowed' }), }); } const method = route.request().method(); if (method === 'GET') { const search = (url.searchParams.get('search') ?? '').toLowerCase(); const sortBy = url.searchParams.get('sort_by') ?? 'created_at'; const sortOrder = url.searchParams.get('sort_order') ?? 'desc'; const page = Number(url.searchParams.get('page') ?? '1'); const pageSize = Number(url.searchParams.get('page_size') ?? '20'); const filtered = store.filter( (a) => !search || a.title.toLowerCase().includes(search) || a.content.toLowerCase().includes(search), ); const direction = sortOrder === 'asc' ? 1 : -1; filtered.sort((a, b) => { if (sortBy === 'title') { return a.title.localeCompare(b.title) * direction; } return a.created_at.localeCompare(b.created_at) * direction; }); const start = (page - 1) * pageSize; const slice = filtered.slice(start, start + pageSize); return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ articles: slice, total: filtered.length, page, page_size: pageSize, total_pages: Math.max(1, Math.ceil(filtered.length / pageSize)), }), }); } if (method === 'POST') { const body = JSON.parse(route.request().postData() ?? '{}') as { title: string; content: string; author_id: number; category_id: number; published: boolean; }; const article: WireArticle = { id: nextId.value++, title: body.title, content: body.content, author_id: body.author_id, category_id: body.category_id, created_at: new Date().toISOString(), published: body.published, author: AUTHORS.find((a) => a.id === body.author_id) ?? AUTHORS[0], category: CATEGORIES.find((c) => c.id === body.category_id) ?? CATEGORIES[0], }; store.push(article); return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify(article), }); } return route.fulfill({ status: 405, contentType: 'application/json', body: JSON.stringify({ detail: 'Method not allowed', code: 'method_not_allowed' }), }); }); return { store, token, count: () => store.length, all: () => store.map((a) => a.id).sort((a, b) => a - b), byId: (id: number) => store.find((a) => a.id === id), }; } test.describe('Admin area (E2E)', () => { test('redirects signed-out users to /login', async ({ page }) => { await mockAdminApi(page, { signedOut: true }); // No token in storage: RequireAuth redirects to /login (the intended // path is remembered in router state, not a query parameter). await page.goto('/admin'); await expect(page).toHaveURL('/login'); }); test('redirects non-admin users away with a 403 message', async ({ page }) => { const { token } = await mockAdminApi(page, { admin: false, token: 'user-token' }); await page.addInitScript( (value) => localStorage.setItem('AUTH_TOKEN', value), token, ); await page.goto('/admin'); // RequireAdmin shows the 403 page in place (no redirect). await expect(page.getByRole('heading', { level: 1, name: '403' })).toBeVisible(); await expect( page.getByText(/does not have access to the admin area/i), ).toBeVisible(); await expect(page).toHaveURL('/admin'); }); test('renders the admin dashboard with all articles and the Admin header link', async ({ page, }) => { const { token, count } = await mockAdminApi(page, { admin: true }); await page.addInitScript( (value) => localStorage.setItem('AUTH_TOKEN', value), token, ); await page.goto('/admin'); // Dashboard heading + rows. await expect(page.getByRole('heading', { level: 1, name: 'Articles' })).toBeVisible(); await expect(page.getByText('Fusion milestone: net energy gain repeated')).toBeVisible(); await expect(page.getByText('City marathon sets record turnout')).toBeVisible(); await expect(page.getByText('Inside the new wave of open-source language models')).toBeVisible(); // Author and category columns. await expect(page.getByText('Grace Hopper')).toBeVisible(); await expect(page.getByText('Technology')).toBeVisible(); // Pagination summary. await expect(page.getByText('Showing 1–3 of 3')).toBeVisible(); // The admin shell shows the signed-in admin and a link back to the public site. await expect(page.getByText('Signed in as')).toBeVisible(); await expect(page.getByRole('link', { name: /back to newzy/i })).toBeVisible(); expect(count()).toBe(3); }); test('hides the Admin header link for non-admins', async ({ page }) => { const { token } = await mockAdminApi(page, { admin: false, token: 'user-token' }); await page.addInitScript( (value) => localStorage.setItem('AUTH_TOKEN', value), token, ); await page.goto('/'); await page.waitForTimeout(200); await expect(page.getByRole('link', { name: /^admin$/i })).toHaveCount(0); }); test('search filters articles by title or content', async ({ page }) => { const { token } = await mockAdminApi(page, { admin: true }); await page.addInitScript( (value) => localStorage.setItem('AUTH_TOKEN', value), token, ); await page.goto('/admin'); await expect(page.getByText('Fusion milestone: net energy gain repeated')).toBeVisible(); // Title match. const search = page.getByLabel('Search articles'); await search.fill('fusion'); await expect(page.getByText('Fusion milestone: net energy gain repeated')).toBeVisible(); await expect(page.getByText('City marathon sets record turnout')).toHaveCount(0); await expect(page.getByText('Inside the new wave of open-source language models')).toHaveCount(0); await expect(page.getByText('Showing 1–1 of 1')).toBeVisible(); // Content match. await search.fill('course'); await expect(page.getByText('City marathon sets record turnout')).toBeVisible(); await expect(page.getByText('Fusion milestone: net energy gain repeated')).toHaveCount(0); }); test('sorts by title in both directions', async ({ page }) => { const { token } = await mockAdminApi(page, { admin: true }); await page.addInitScript( (value) => localStorage.setItem('AUTH_TOKEN', value), token, ); await page.goto('/admin'); const firstCell = () => page.locator('tbody tr').first().locator('td').first(); const titleButton = page.getByRole('button', { name: /sort by title/i }); // Default ordering is newest first (created_at desc). await expect(firstCell()).toContainText('Fusion milestone: net energy gain repeated'); // Click title → ascending: City… is first. await titleButton.click(); await expect(firstCell()).toContainText('City marathon sets record turnout'); // Click again → descending: Inside… is first. await titleButton.click(); await expect(firstCell()).toContainText('Inside the new wave of open-source language models'); }); test('creates an article with the Lexical editor and navigates back', async ({ page, }) => { const { token, byId, all } = await mockAdminApi(page, { admin: true }); await page.addInitScript( (value) => localStorage.setItem('AUTH_TOKEN', value), token, ); await page.goto('/admin/articles/new'); await expect( page.getByRole('heading', { level: 1, name: 'New article' }), ).toBeVisible(); await page.getByLabel(/^Title/).fill('E2E: fresh story from the admin area'); await page.getByLabel(/^Author/).selectOption('2'); await page.getByLabel(/^Category/).selectOption('4'); await page.getByLabel(/^Published/).check(); const editable = page.getByLabel('Article content'); await editable.click(); await page.keyboard.type('Written with the Lexical editor.'); await page.getByRole('button', { name: /create article/i }).click(); await page.waitForURL('/admin'); await expect(page.getByRole('status')).toContainText('was saved'); // Exact match: the success notice also quotes the title. await expect( page.getByText('E2E: fresh story from the admin area', { exact: true }), ).toBeVisible(); const created = byId(Math.max(...all())); expect(created?.title).toBe('E2E: fresh story from the admin area'); expect(created?.author_id).toBe(2); expect(created?.category_id).toBe(4); expect(created?.published).toBe(true); expect(created?.content).toContain('Written with the Lexical editor.'); }); test('edits an article and persists the changes', async ({ page }) => { const { token, byId } = await mockAdminApi(page, { admin: true }); await page.addInitScript( (value) => localStorage.setItem('AUTH_TOKEN', value), token, ); await page.goto('/admin'); await page .getByRole('row', { name: /Fusion milestone: net energy gain repeated/ }) .getByRole('link', { name: /edit/i }) .click(); await expect(page).toHaveURL(/\/admin\/articles\/1\/edit$/); await expect( page.getByRole('heading', { level: 1, name: /edit article/i }), ).toBeVisible(); const titleInput = page.getByLabel(/^Title/); await expect(titleInput).toHaveValue('Fusion milestone: net energy gain repeated'); const editable = page.getByLabel('Article content'); await expect(editable).toContainText('Scientists again drew net energy'); await titleInput.fill('Fusion milestone: record energy gain'); await page.getByRole('button', { name: /save changes/i }).click(); await page.waitForURL('/admin'); await expect(page.getByRole('status')).toContainText('was saved'); // Exact match: the success notice also quotes the title. await expect( page.getByText('Fusion milestone: record energy gain', { exact: true }), ).toBeVisible(); expect(byId(1)?.title).toBe('Fusion milestone: record energy gain'); expect(byId(1)?.published).toBe(true); expect(byId(1)?.author_id).toBe(2); }); test('deletes an article only after explicit confirmation', async ({ page }) => { const { token, count, all } = await mockAdminApi(page, { admin: true }); await page.addInitScript( (value) => localStorage.setItem('AUTH_TOKEN', value), token, ); await page.goto('/admin'); const targetRow = page.getByRole('row', { name: /City marathon sets record turnout/, }); await targetRow.getByRole('button', { name: /delete/i }).click(); const dialog = page.getByRole('dialog'); await expect( dialog.getByRole('heading', { name: /are you sure you want to delete/i }), ).toBeVisible(); await expect(dialog).toContainText('City marathon sets record turnout'); await expect(dialog).toContainText(/cannot be undone/i); // Cancel: nothing is deleted. await dialog.getByRole('button', { name: /cancel/i }).click(); await expect(dialog).toHaveCount(0); expect(count()).toBe(3); expect(all()).toEqual([1, 2, 3]); // Confirm: the article is removed. await targetRow.getByRole('button', { name: /delete/i }).click(); await expect(page.getByRole('dialog')).toBeVisible(); await page.getByRole('button', { name: /yes, delete/i }).click(); await expect(page.getByRole('status')).toContainText('was deleted'); // The row is gone (the success notice still quotes the title). await expect( page.getByRole('row', { name: /City marathon sets record turnout/ }), ).toHaveCount(0); expect(count()).toBe(2); expect(all()).toEqual([1, 3]); }); test('pagination controls stay disabled with a single page', async ({ page, }) => { const { token } = await mockAdminApi(page, { admin: true }); await page.addInitScript( (value) => localStorage.setItem('AUTH_TOKEN', value), token, ); await page.goto('/admin'); await expect(page.getByText('Showing 1–3 of 3')).toBeVisible(); await expect(page.getByRole('button', { name: /previous/i })).toBeDisabled(); await expect(page.getByRole('button', { name: /next/i })).toBeDisabled(); // The page size control round-trips without moving pages. const perPage = page.getByLabel('Rows per page'); await perPage.selectOption('50'); await perPage.selectOption('20'); await expect(page.getByText('Showing 1–3 of 3')).toBeVisible(); }); test('editor sanitizes hostile HTML from stored content', async ({ page }) => { const mock = await mockAdminApi(page, { admin: true }); // Simulate a hostile article body persisted by the backend. mock.store[0].content = [ '

Safe text

', '', '', '', 'click', ].join(''); const dialogs: string[] = []; const pageErrors: string[] = []; page.on('dialog', (dialog) => { dialogs.push(dialog.message()); void dialog.dismiss(); }); page.on('pageerror', (error) => pageErrors.push(error.message)); await page.addInitScript( (value) => localStorage.setItem('AUTH_TOKEN', value), mock.token, ); await page.goto('/admin/articles/1/edit'); const editable = page.getByLabel('Article content'); await expect(editable).toContainText('Safe'); const html = await editable.evaluate( (el) => (el as HTMLElement).innerHTML, ); expect(html).not.toContain('