feat(admin): rebuild admin area around the Article domain
The admin area was managing a Hacker News-style Item model that the
public site never consumed, so the homepage always fell back to sample
data. Rebuild the admin area around the real public content model.
Backend:
- Remove the Item model, schema and admin API
- Admin API now manages articles at /api/v1/admin/articles (CRUD) with
/api/v1/admin/authors and /api/v1/admin/categories reference data
- Add public read-only article endpoints (/api/v1/articles,
/api/v1/articles/{id}): no auth, published-only, newest-first
- Rewrite Article schemas; ArticleRead embeds author and category
- Add idempotent seed_content.py dev seeder (3 authors, 4 categories,
6 published articles)
Frontend:
- Admin UI rewritten around articles: AdminDashboard list, new
EditArticlePage (create/edit, author/category selects, published
toggle, Lexical editor, debounced auto-save)
- Replace AdminItem types and api client with the article domain
- Update App routes, AdminLayout sidebar, DeleteConfirmation, Lexical
editor labels and Home/client comments to article terminology
Tests:
- Rewrite admin unit tests and the Playwright admin e2e spec for the
article domain; add test_articles.py for the public endpoints and
seeder
This commit is contained in:
29 files changed
+2465
-1658
No files matched your search
@@ -1,421 +1,547 @@
|
||||
import { expect, test, type Page } from '@playwright/test';
|
||||
import { expect, test } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* E2E tests for the admin area (M6) with a fully mocked backend
|
||||
* (in-memory item store + token-based auth), following the approach of
|
||||
* the other specs in this directory.
|
||||
* 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
|
||||
*/
|
||||
|
||||
const ADMIN_TOKEN = 'mock-admin-token';
|
||||
const USER_TOKEN = 'mock-user-token';
|
||||
const TOKEN_KEY = 'AUTH_TOKEN';
|
||||
|
||||
interface Item {
|
||||
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;
|
||||
url: string;
|
||||
points: number;
|
||||
username: string;
|
||||
content: string;
|
||||
author_id: number;
|
||||
category_id: number;
|
||||
created_at: string;
|
||||
}
|
||||
published: boolean;
|
||||
author: WireAuthor;
|
||||
category: WireCategory;
|
||||
};
|
||||
|
||||
const envelope = (detail: string, code: string) => JSON.stringify({ detail, code });
|
||||
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' },
|
||||
];
|
||||
|
||||
/** Build the auth + admin API mock with a per-test item store. */
|
||||
function mockAdminApi(page: Page): { store: Item[]; nextId: () => number } {
|
||||
let idCounter = 100;
|
||||
const store: Item[] = [
|
||||
function seedArticles(): WireArticle[] {
|
||||
return [
|
||||
{
|
||||
id: 1,
|
||||
title: 'Breaking: local cat discovers keyboard',
|
||||
url: 'https://example.com/cat-keyboard',
|
||||
points: 42,
|
||||
username: 'alice',
|
||||
content: '<p>Amazing news.</p>',
|
||||
created_at: '2024-05-01T10:00:00Z',
|
||||
title: 'Fusion milestone: net energy gain repeated',
|
||||
content:
|
||||
'<p>Scientists again drew net energy from the reactor, marking the third repeat of the landmark result.</p>',
|
||||
author_id: 2,
|
||||
category_id: 2,
|
||||
created_at: '2024-05-03T11:30:00Z',
|
||||
published: true,
|
||||
author: AUTHORS[1],
|
||||
category: CATEGORIES[1],
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
title: 'Study: coffee improves code reviews',
|
||||
url: 'https://example.com/coffee-reviews',
|
||||
points: 17,
|
||||
username: 'bob',
|
||||
content: '<p>Peer-reviewed.</p>',
|
||||
created_at: '2024-05-02T11:30:00Z',
|
||||
title: 'City marathon sets record turnout',
|
||||
content:
|
||||
'<p>First-timers flooded the course on Sunday as organizers beat last year\u2019s turnout.</p>',
|
||||
author_id: 3,
|
||||
category_id: 3,
|
||||
created_at: '2024-05-02T09:15:00Z',
|
||||
published: false,
|
||||
author: AUTHORS[2],
|
||||
category: CATEGORIES[2],
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
title: 'Show HN: I built a tiny news app',
|
||||
url: 'https://example.com/show-hn-newz',
|
||||
points: 5,
|
||||
username: 'alice',
|
||||
content: '<p>Feedback welcome.</p>',
|
||||
created_at: '2024-05-03T09:15:00Z',
|
||||
title: 'Inside the new wave of open-source language models',
|
||||
content:
|
||||
'<p>Open-weight language models are reshaping who can build and deploy AI.</p>',
|
||||
author_id: 1,
|
||||
category_id: 1,
|
||||
created_at: '2024-05-01T10:00:00Z',
|
||||
published: true,
|
||||
author: AUTHORS[0],
|
||||
category: CATEGORIES[0],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const requireAdmin = (route: Parameters<Parameters<Page['route']>[1]>[0]): boolean => {
|
||||
const header = route.request().headers()['authorization'];
|
||||
if (header !== `Bearer ${ADMIN_TOKEN}`) {
|
||||
route.fulfill({
|
||||
status: 403,
|
||||
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: envelope('Admin access required', 'forbidden'),
|
||||
body: JSON.stringify({ detail: 'Not authenticated', code: 'unauthorized' }),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
page.route('**/api/v1/auth/me', (route) => {
|
||||
const header = route.request().headers()['authorization'];
|
||||
if (header === `Bearer ${ADMIN_TOKEN}`) {
|
||||
if (opts.admin === false) {
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ username: 'alice', is_admin: true }),
|
||||
});
|
||||
}
|
||||
if (header === `Bearer ${USER_TOKEN}`) {
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ username: 'bob', is_admin: false }),
|
||||
body: JSON.stringify({ id: 2, username: 'user', is_admin: false }),
|
||||
});
|
||||
}
|
||||
return route.fulfill({
|
||||
status: 401,
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: envelope('Invalid or expired token', 'unauthorized'),
|
||||
body: JSON.stringify({ id: 1, username: 'admin', is_admin: true }),
|
||||
});
|
||||
});
|
||||
page.route('**/api/v1/auth/logout', (route) => route.fulfill({ status: 204 }));
|
||||
|
||||
// Collection endpoint: GET (list) + POST (create).
|
||||
page.route(/\/api\/v1\/admin\/items(\?.*)?$/, (route) => {
|
||||
const request = route.request();
|
||||
if (request.method() === 'GET') {
|
||||
if (!requireAdmin(route)) return;
|
||||
const url = new URL(request.url());
|
||||
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') as keyof Item;
|
||||
const sortBy = url.searchParams.get('sort_by') ?? 'created_at';
|
||||
const sortOrder = url.searchParams.get('sort_order') ?? 'desc';
|
||||
const pageSize = Number(url.searchParams.get('page_size') ?? 20);
|
||||
const page_ = Number(url.searchParams.get('page') ?? 1);
|
||||
const page = Number(url.searchParams.get('page') ?? '1');
|
||||
const pageSize = Number(url.searchParams.get('page_size') ?? '20');
|
||||
|
||||
const filtered = store.filter(
|
||||
(item) =>
|
||||
!search ||
|
||||
item.title.toLowerCase().includes(search) ||
|
||||
item.url.toLowerCase().includes(search),
|
||||
(a) => !search || a.title.toLowerCase().includes(search) || a.content.toLowerCase().includes(search),
|
||||
);
|
||||
const direction = sortOrder === 'asc' ? 1 : -1;
|
||||
filtered.sort((a, b) => {
|
||||
const cmp = String(a[sortBy]).localeCompare(String(b[sortBy]));
|
||||
return sortOrder === 'asc' ? cmp : -cmp;
|
||||
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 start = (page - 1) * pageSize;
|
||||
const slice = filtered.slice(start, start + pageSize);
|
||||
|
||||
return route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
items: slice,
|
||||
articles: slice,
|
||||
total: filtered.length,
|
||||
page: page_,
|
||||
page,
|
||||
page_size: pageSize,
|
||||
total_pages: Math.ceil(filtered.length / pageSize) || 0,
|
||||
total_pages: Math.max(1, Math.ceil(filtered.length / pageSize)),
|
||||
}),
|
||||
});
|
||||
}
|
||||
if (request.method() === 'POST') {
|
||||
if (!requireAdmin(route)) return;
|
||||
const body = request.postDataJSON() as Partial<Item>;
|
||||
const item: Item = {
|
||||
id: ++idCounter,
|
||||
title: body.title ?? '',
|
||||
url: body.url ?? '',
|
||||
points: body.points ?? 0,
|
||||
username: body.username ?? 'alice',
|
||||
content: body.content ?? '',
|
||||
created_at: new Date().toISOString(),
|
||||
|
||||
if (method === 'POST') {
|
||||
const body = JSON.parse(route.request().postData() ?? '{}') as {
|
||||
title: string;
|
||||
content: string;
|
||||
author_id: number;
|
||||
category_id: number;
|
||||
published: boolean;
|
||||
};
|
||||
store.push(item);
|
||||
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(item),
|
||||
body: JSON.stringify(article),
|
||||
});
|
||||
}
|
||||
return route.fulfill({ status: 405, contentType: 'application/json', body: envelope('Method not allowed', 'method_not_allowed') });
|
||||
|
||||
return route.fulfill({
|
||||
status: 405,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ detail: 'Method not allowed', code: 'method_not_allowed' }),
|
||||
});
|
||||
});
|
||||
|
||||
// Item endpoint: GET / PUT / DELETE by id.
|
||||
page.route('**/api/v1/admin/items/*', (route) => {
|
||||
const request = route.request();
|
||||
const id = Number(request.url().split('/').pop());
|
||||
if (!requireAdmin(route)) return;
|
||||
const item = store.find((entry) => entry.id === id);
|
||||
|
||||
if (request.method() === 'GET') {
|
||||
if (!item) {
|
||||
return route.fulfill({
|
||||
status: 404,
|
||||
contentType: 'application/json',
|
||||
body: envelope('Item not found', 'not_found'),
|
||||
});
|
||||
}
|
||||
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(item) });
|
||||
}
|
||||
if (request.method() === 'PUT') {
|
||||
if (!item) {
|
||||
return route.fulfill({
|
||||
status: 404,
|
||||
contentType: 'application/json',
|
||||
body: envelope('Item not found', 'not_found'),
|
||||
});
|
||||
}
|
||||
const body = request.postDataJSON() as Partial<Item>;
|
||||
Object.assign(item, body);
|
||||
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(item) });
|
||||
}
|
||||
if (request.method() === 'DELETE') {
|
||||
if (!item) {
|
||||
return route.fulfill({
|
||||
status: 404,
|
||||
contentType: 'application/json',
|
||||
body: envelope('Item not found', 'not_found'),
|
||||
});
|
||||
}
|
||||
store.splice(store.indexOf(item), 1);
|
||||
return route.fulfill({ status: 204 });
|
||||
}
|
||||
return route.fulfill({ status: 405, contentType: 'application/json', body: envelope('Method not allowed', 'method_not_allowed') });
|
||||
});
|
||||
|
||||
return { store, nextId: () => idCounter };
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
async function seedToken(page: Page, token: string | null): Promise<void> {
|
||||
if (token === null) {
|
||||
await page.addInitScript((key) => localStorage.removeItem(key), TOKEN_KEY);
|
||||
} else {
|
||||
await page.addInitScript(
|
||||
([key, value]) => localStorage.setItem(key, value),
|
||||
[TOKEN_KEY, token] as const,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
test.describe('admin area (M6)', () => {
|
||||
test('signed-out users are redirected to /login', async ({ page }) => {
|
||||
mockAdminApi(page);
|
||||
await seedToken(page, null);
|
||||
|
||||
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('non-admins see the 403 page', async ({ page }) => {
|
||||
mockAdminApi(page);
|
||||
await seedToken(page, USER_TOKEN);
|
||||
|
||||
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.getByTestId('forbidden-page').getByText(/admin area/i),
|
||||
page.getByText(/does not have access to the admin area/i),
|
||||
).toBeVisible();
|
||||
await expect(page).toHaveURL('/admin');
|
||||
});
|
||||
|
||||
test('admins see the dashboard with all items and an Admin header link', async ({
|
||||
test('renders the admin dashboard with all articles and the Admin header link', async ({
|
||||
page,
|
||||
}) => {
|
||||
mockAdminApi(page);
|
||||
await seedToken(page, ADMIN_TOKEN);
|
||||
|
||||
// The header exposes the admin link for admin accounts.
|
||||
await page.goto('/');
|
||||
await expect(page.getByRole('navigation', { name: 'Main navigation' }).getByRole('link', { name: /admin/i })).toBeVisible();
|
||||
const { token, count } = await mockAdminApi(page, { admin: true });
|
||||
await page.addInitScript(
|
||||
(value) => localStorage.setItem('AUTH_TOKEN', value),
|
||||
token,
|
||||
);
|
||||
|
||||
await page.goto('/admin');
|
||||
|
||||
await expect(page.getByRole('heading', { level: 1, name: 'Items' })).toBeVisible();
|
||||
await expect(page.getByText('Breaking: local cat discovers keyboard')).toBeVisible();
|
||||
await expect(page.getByText('Study: coffee improves code reviews')).toBeVisible();
|
||||
await expect(page.getByText('Show HN: I built a tiny news app')).toBeVisible();
|
||||
// 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('non-admin accounts do not get the Admin header link', async ({ page }) => {
|
||||
mockAdminApi(page);
|
||||
await seedToken(page, USER_TOKEN);
|
||||
|
||||
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 expect(
|
||||
page.getByRole('navigation', { name: 'Main navigation' }).getByRole('link', { name: /admin/i }),
|
||||
).toHaveCount(0);
|
||||
await page.waitForTimeout(200);
|
||||
await expect(page.getByRole('link', { name: /^admin$/i })).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('search filters the list by title or URL', async ({ page }) => {
|
||||
mockAdminApi(page);
|
||||
await seedToken(page, ADMIN_TOKEN);
|
||||
|
||||
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('Breaking: local cat discovers keyboard')).toBeVisible();
|
||||
await expect(page.getByText('Fusion milestone: net energy gain repeated')).toBeVisible();
|
||||
|
||||
await page.getByLabel('Search items').fill('coffee');
|
||||
await expect(page.getByText('Study: coffee improves code reviews')).toBeVisible();
|
||||
await expect(
|
||||
page.getByText('Breaking: local cat discovers keyboard'),
|
||||
).toHaveCount(0);
|
||||
|
||||
// URL search (case-insensitive on the server side).
|
||||
await page.getByLabel('Search items').fill('EXAMPLE.COM/CAT');
|
||||
await expect(page.getByText('Breaking: local cat discovers keyboard')).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('sorting by title toggles direction', async ({ page }) => {
|
||||
mockAdminApi(page);
|
||||
await seedToken(page, ADMIN_TOKEN);
|
||||
|
||||
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 firstTitle = page.locator('tbody tr').first().locator('td').first().locator('span, a').first();
|
||||
|
||||
// Default: created_at desc -> newest first.
|
||||
await expect(firstTitle).toHaveText('Show HN: I built a tiny news app');
|
||||
const firstCell = () => page.locator('tbody tr').first().locator('td').first();
|
||||
const titleButton = page.getByRole('button', { name: /sort by title/i });
|
||||
|
||||
await page.getByRole('button', { name: /sort by title/i }).click();
|
||||
await expect(firstTitle).toHaveText('Breaking: local cat discovers keyboard');
|
||||
// Default ordering is newest first (created_at desc).
|
||||
await expect(firstCell()).toContainText('Fusion milestone: net energy gain repeated');
|
||||
|
||||
await page.getByRole('button', { name: /sort by title/i }).click();
|
||||
await expect(firstTitle).toHaveText('Study: coffee improves code reviews');
|
||||
// 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('create: fills the form, saves with the Lexical editor and lists the item', async ({
|
||||
test('creates an article with the Lexical editor and navigates back', async ({
|
||||
page,
|
||||
}) => {
|
||||
const { store } = mockAdminApi(page);
|
||||
await seedToken(page, ADMIN_TOKEN);
|
||||
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 page.goto('/admin/items/new');
|
||||
await expect(page.getByRole('heading', { level: 1, name: 'New item' })).toBeVisible();
|
||||
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(/^URL/).fill('https://example.com/e2e-story');
|
||||
await page.getByLabel('Points').fill('3');
|
||||
// The author is pre-filled from the session.
|
||||
await expect(page.getByLabel('Author')).toHaveValue('alice');
|
||||
|
||||
// Type into the Lexical contenteditable (rich text editor).
|
||||
await page.getByLabel('Item content').click();
|
||||
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.getByRole('button', { name: /create item/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();
|
||||
|
||||
// Back on the dashboard with the success notice.
|
||||
await expect(page).toHaveURL('/admin');
|
||||
await expect(page.getByRole('status')).toHaveText(/was saved/i);
|
||||
await expect(page.getByText('E2E: fresh story from the admin area', { exact: true })).toBeVisible();
|
||||
|
||||
// The backend received the rich content.
|
||||
const created = store.find((item) =>
|
||||
item.title.includes('E2E: fresh story'),
|
||||
);
|
||||
expect(created).toBeTruthy();
|
||||
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.');
|
||||
expect(created?.points).toBe(3);
|
||||
expect(created?.username).toBe('alice');
|
||||
});
|
||||
|
||||
test('edit: loads the item, updates fields and saves', async ({ page }) => {
|
||||
const { store } = mockAdminApi(page);
|
||||
await seedToken(page, ADMIN_TOKEN);
|
||||
|
||||
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.locator('tbody tr', { hasText: 'Breaking: local cat' }).getByRole('link', { name: /edit/i }).click();
|
||||
|
||||
await expect(page.getByRole('heading', { level: 1, name: /edit item/i })).toBeVisible();
|
||||
await expect(page.getByLabel(/^Title/)).toHaveValue('Breaking: local cat discovers keyboard');
|
||||
await expect(page.getByLabel('Points')).toHaveValue('42');
|
||||
// The stored body loads into the WYSIWYG editor.
|
||||
await expect(page.getByLabel('Item content')).toContainText('Amazing news.');
|
||||
await page
|
||||
.getByRole('row', { name: /Fusion milestone: net energy gain repeated/ })
|
||||
.getByRole('link', { name: /edit/i })
|
||||
.click();
|
||||
|
||||
await page.getByLabel(/^Title/).fill('Breaking: local cat becomes famous');
|
||||
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 expect(page).toHaveURL('/admin');
|
||||
await expect(page.getByRole('status')).toHaveText(/was saved/i);
|
||||
await expect(page.getByRole('cell', { name: 'Breaking: local cat becomes famous', exact: true })).toBeVisible();
|
||||
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();
|
||||
|
||||
const updated = store.find((item) => item.id === 1);
|
||||
expect(updated?.title).toBe('Breaking: local cat becomes famous');
|
||||
// Untouched fields survive the partial save.
|
||||
expect(updated?.points).toBe(42);
|
||||
expect(byId(1)?.title).toBe('Fusion milestone: record energy gain');
|
||||
expect(byId(1)?.published).toBe(true);
|
||||
expect(byId(1)?.author_id).toBe(2);
|
||||
});
|
||||
|
||||
test('delete: requires confirmation, then removes the item', async ({ page }) => {
|
||||
const { store } = mockAdminApi(page);
|
||||
await seedToken(page, ADMIN_TOKEN);
|
||||
|
||||
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 target = page.getByText('Study: coffee improves code reviews');
|
||||
await expect(target).toBeVisible();
|
||||
|
||||
// Open the confirmation dialog (first row's delete button).
|
||||
page.locator('tbody tr', { hasText: 'Study: coffee' }).getByRole('button', { name: /delete/i }).click();
|
||||
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).toBeVisible();
|
||||
await expect(
|
||||
dialog.getByRole('heading', { name: /are you sure you want to delete/i }),
|
||||
).toBeVisible();
|
||||
await expect(dialog.getByText(/cannot be undone/i)).toBeVisible();
|
||||
await expect(dialog).toContainText('City marathon sets record turnout');
|
||||
await expect(dialog).toContainText(/cannot be undone/i);
|
||||
|
||||
// Cancel keeps the item.
|
||||
// Cancel: nothing is deleted.
|
||||
await dialog.getByRole('button', { name: /cancel/i }).click();
|
||||
await expect(dialog).toHaveCount(0);
|
||||
await expect(target).toBeVisible();
|
||||
expect(store).toHaveLength(3);
|
||||
expect(count()).toBe(3);
|
||||
expect(all()).toEqual([1, 2, 3]);
|
||||
|
||||
// Confirm with the explicit "Yes, delete" action.
|
||||
page.locator('tbody tr', { hasText: 'Study: coffee' }).getByRole('button', { name: /delete/i }).click();
|
||||
// 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.getByText('Breaking: local cat discovers keyboard')).toBeVisible();
|
||||
await expect(page.getByRole('cell', { name: 'Study: coffee improves code reviews', exact: true })).toHaveCount(0);
|
||||
await expect(page.getByRole('status')).toHaveText(/was deleted/i);
|
||||
expect(store).toHaveLength(2);
|
||||
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: next/previous and the page size selector work', async ({ page }) => {
|
||||
mockAdminApi(page);
|
||||
await seedToken(page, ADMIN_TOKEN);
|
||||
|
||||
await page.goto('/admin');
|
||||
|
||||
// 3 seeded items fit on one page: navigation is disabled.
|
||||
await expect(page.getByRole('button', { name: /next/i })).toBeDisabled();
|
||||
await expect(page.getByRole('button', { name: /previous/i })).toBeDisabled();
|
||||
|
||||
// Smaller page size splits the list across pages.
|
||||
await page.getByLabel('Rows per page').selectOption('10');
|
||||
await expect(page).toHaveURL(/\/admin/);
|
||||
// (Still one page for 3 items — assert the selector round-trips.)
|
||||
await expect(page.getByLabel('Rows per page')).toHaveValue('10');
|
||||
});
|
||||
|
||||
test('editor sanitizes hostile stored HTML (no scripts or handlers survive)', async ({
|
||||
test('pagination controls stay disabled with a single page', async ({
|
||||
page,
|
||||
}) => {
|
||||
const { store } = mockAdminApi(page);
|
||||
await seedToken(page, ADMIN_TOKEN);
|
||||
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();
|
||||
|
||||
// Simulate a hostile item body persisted by the backend.
|
||||
store[0].content = [
|
||||
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 = [
|
||||
'<p>Safe <strong>text</strong></p>',
|
||||
'<script>alert(1)</script>',
|
||||
'<img src="x" onerror="alert(1)"/>',
|
||||
@@ -431,12 +557,18 @@ test.describe('admin area (M6)', () => {
|
||||
});
|
||||
page.on('pageerror', (error) => pageErrors.push(error.message));
|
||||
|
||||
await page.goto('/admin/items/1/edit');
|
||||
await page.addInitScript(
|
||||
(value) => localStorage.setItem('AUTH_TOKEN', value),
|
||||
mock.token,
|
||||
);
|
||||
await page.goto('/admin/articles/1/edit');
|
||||
|
||||
const editable = page.getByLabel('Item content');
|
||||
const editable = page.getByLabel('Article content');
|
||||
await expect(editable).toContainText('Safe');
|
||||
|
||||
const html = await editable.evaluate((el) => el.innerHTML);
|
||||
const html = await editable.evaluate(
|
||||
(el) => (el as HTMLElement).innerHTML,
|
||||
);
|
||||
expect(html).not.toContain('<script');
|
||||
expect(html).not.toContain('onerror');
|
||||
expect(html).not.toContain('onload');
|
||||
|
||||
Reference in new issue
Block a user