diff --git a/e2e/recipe-api.spec.ts b/e2e/recipe-api.spec.ts index be0f6ab..e1d8d54 100644 --- a/e2e/recipe-api.spec.ts +++ b/e2e/recipe-api.spec.ts @@ -5,10 +5,19 @@ import { mkdtemp, readFile, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { Pool } from 'pg'; -import { expect, test, type BrowserContext, type Page } from '@playwright/test'; +import sharp from 'sharp'; +import { + expect, + test, + type Browser, + type BrowserContext, + type Page, +} from '@playwright/test'; import { createApp } from '../apps/api/src/app.js'; import { createAuthRepository } from '../apps/api/src/features/auth/authRepository.js'; import { createAuthService } from '../apps/api/src/features/auth/authService.js'; +import { createRecipeRepository } from '../apps/api/src/features/recipes/recipeRepository.js'; +import { createImageStore } from '../apps/api/src/features/recipes/imageStore.js'; if (existsSync('.env')) process.loadEnvFile('.env'); test.skip( @@ -95,16 +104,77 @@ async function register(page: Page, email: string) { ).toBeVisible(); } -test('persists recipes, uploaded images and ratings through the real API', async ({ - page, - context, - browser, -}) => { - test.setTimeout(90000); +/* + * Independent scenarios. Each creates its own users and recipes, so a + * failure points at one feature and does not hide the rest. Users are + * created through the auth service (registration through the UI is rate + * limited to 5 per minute per IP) and get a real session cookie; the + * end-to-end journey at the bottom still registers through the UI. + */ +async function signedIn(browser: Browser, name: string) { + const { user, sessionToken } = await createAuthService( + createAuthRepository(pool, pool, schema), + ).register(name, `${randomUUID()}@example.com`, 'browser-test-password'); + const context = await browser.newContext({ + baseURL: 'http://127.0.0.1:4173/project2/', + }); await connect(context); - await register(page, 'owner@example.com'); + await context.addCookies([ + { + name: 't31_project2_session', + value: sessionToken, + domain: '127.0.0.1', + path: '/', + httpOnly: true, + sameSite: 'Lax', + }, + ]); + return { user, context, page: await context.newPage() }; +} + +/** Stores a PNG as an upload of the user, as the upload API would. */ +async function uploadImage(userId: string) { + // Realistically sized: the page uses srcset width descriptors, and the + // browser scales naturalWidth by the chosen density, so a 1 px image + // would report 0 even when it loads. + const png = await sharp({ + create: { width: 600, height: 400, channels: 3, background: '#f9a825' }, + }) + .png() + .toBuffer(); + return createImageStore(pool, schema, imageDirectory).upload(userId, png); +} + +/** Creates a public recipe directly in the database for a scenario. */ +async function createRecipe( + authorId: string, + title: string, + imageUrl: string | null = null, +) { + const recipe = await createRecipeRepository(pool, schema).create( + { + title, + description: 'Created for a browser test.', + imageUrl, + category: 'soup', + cuisine: null, + difficulty: 'easy', + visibility: 'public', + prepMinutes: 5, + cookMinutes: 10, + servings: 2, + ingredients: [{ name: 'Water', amount: 1, unit: 'l', note: null }], + instructions: ['Boil water.'], + tags: [], + }, + authorId, + ); + return `recipes/${recipe.id}`; +} + +async function fillRecipeForm(page: Page, title: string) { await page.goto('recipes/new'); - await page.getByLabel(/Recipe title/).fill('Browser soup'); + await page.getByLabel(/Recipe title/).fill(title); await page.getByLabel(/Preparation time/).fill('5'); await page.getByLabel(/Cooking time/).fill('10'); await page.getByLabel(/Difficulty/).selectOption('medium'); @@ -114,127 +184,306 @@ test('persists recipes, uploaded images and ratings through the real API', async await page.getByLabel('Ingredient 1 amount').fill('1'); await page.getByLabel('Ingredient 1 unit').selectOption('l'); await page.getByLabel('Step 1', { exact: true }).fill('Boil water.'); - const image = await page.evaluate(() => { - const canvas = document.createElement('canvas'); - canvas.width = 300; - canvas.height = 200; - const context = canvas.getContext('2d')!; - context.fillStyle = '#f9a825'; - context.fillRect(0, 0, 300, 200); - return canvas.toDataURL('image/png').split(',')[1]!; - }); - await page - .getByLabel('Upload a recipe image', { exact: true }) - .setInputFiles({ - name: 'soup.png', - mimeType: 'image/png', - buffer: Buffer.from(image, 'base64'), +} + +test('publishes a recipe with an uploaded image that persists, then removes the image', async ({ + browser, +}) => { + const owner = await signedIn(browser, 'Image Chef'); + const { page } = owner; + try { + await fillRecipeForm(page, 'Browser soup'); + const image = await page.evaluate(() => { + const canvas = document.createElement('canvas'); + canvas.width = 300; + canvas.height = 200; + const context = canvas.getContext('2d')!; + context.fillStyle = '#f9a825'; + context.fillRect(0, 0, 300, 200); + return canvas.toDataURL('image/png').split(',')[1]!; }); - await page.getByRole('button', { name: 'Use image' }).click(); - await expect(page.getByRole('img', { name: 'Recipe preview' })).toBeVisible(); - await page.getByRole('button', { name: 'Publish recipe' }).click(); - await expect( - page.getByRole('heading', { name: 'Browser soup' }), - ).toBeVisible(); - const recipeUrl = page.url(); - await page.reload(); - await expect( - page.getByRole('heading', { name: 'Browser soup' }), - ).toBeVisible(); - await expect( - page.getByRole('img', { name: 'Browser soup', exact: true }), - ).toBeVisible(); - expect( await page - .getByRole('img', { name: 'Browser soup', exact: true }) - .evaluate((image: HTMLImageElement) => image.naturalWidth), - ).toBeGreaterThan(0); - await page.getByRole('link', { name: 'Edit Recipe' }).click(); - await page.getByLabel(/Recipe title/).fill('Edited browser soup'); - await page.getByRole('button', { name: 'Save changes' }).click(); - await expect( - page.getByRole('heading', { name: 'Edited browser soup' }), - ).toBeVisible(); + .getByLabel('Upload a recipe image', { exact: true }) + .setInputFiles({ + name: 'soup.png', + mimeType: 'image/png', + buffer: Buffer.from(image, 'base64'), + }); + await page.getByRole('button', { name: 'Use image' }).click(); + await expect( + page.getByRole('img', { name: 'Recipe preview' }), + ).toBeVisible(); + await page.getByRole('button', { name: 'Publish recipe' }).click(); + await expect( + page.getByRole('heading', { name: 'Browser soup' }), + ).toBeVisible(); + await page.reload(); + const shown = page.getByRole('img', { name: 'Browser soup', exact: true }); + await expect(shown).toBeVisible(); + // Poll: the element can be visible before the image has finished loading. + await expect + .poll(() => + shown.evaluate((element: HTMLImageElement) => element.naturalWidth), + ) + .toBeGreaterThan(0); - const readerContext = await browser.newContext({ - baseURL: 'http://127.0.0.1:4173/project2/', - }); + await page.getByRole('link', { name: 'Edit Recipe' }).click(); + await page.getByRole('button', { name: 'Remove image' }).click(); + await page.getByRole('button', { name: 'Save changes' }).click(); + await expect( + page.getByRole('heading', { name: 'Browser soup' }), + ).toBeVisible(); + await expect( + page.getByRole('img', { name: 'Browser soup', exact: true }), + ).toHaveCount(0); + } finally { + await owner.context.close(); + } +}); + +test('edits a recipe, keeping its uploaded image, and another user saves the edited recipe', async ({ + browser, +}) => { + const owner = await signedIn(browser, 'Editing Chef'); + const reader = await signedIn(browser, 'Edited Reader'); + const page = owner.page; + /** The recipe's image, loaded from the server (not a broken image). */ + async function expectImage(title: string) { + const image = page.getByRole('img', { name: title, exact: true }); + await expect(image).toBeVisible(); + await expect + .poll(() => + image.evaluate((element: HTMLImageElement) => element.naturalWidth), + ) + .toBeGreaterThan(0); + return image.getAttribute('src'); + } try { - await connect(readerContext); - const reader = await readerContext.newPage(); - await register(reader, 'reader@example.com'); - await reader.goto(recipeUrl); - await reader.getByRole('button', { name: 'Increase servings' }).click(); - await reader + const imageUrl = await uploadImage(owner.user.id); + const recipeUrl = await createRecipe( + owner.user.id, + 'Soup to edit', + imageUrl, + ); + await page.goto(recipeUrl); + const before = await expectImage('Soup to edit'); + await page.getByRole('link', { name: 'Edit Recipe' }).click(); + // The editor shows the existing image; editing only the title keeps it. + await expect( + page.getByRole('img', { name: 'Recipe preview' }), + ).toBeVisible(); + await page.getByLabel(/Recipe title/).fill('Edited browser soup'); + await page.getByRole('button', { name: 'Save changes' }).click(); + // Wait for the save to finish before reloading. + await expect( + page.getByRole('heading', { name: 'Edited browser soup' }), + ).toBeVisible(); + await page.reload(); + await expect( + page.getByRole('heading', { name: 'Edited browser soup' }), + ).toBeVisible(); + expect(await expectImage('Edited browser soup')).toBe(before); + + // Another user saves the edited recipe and sees its new title in + // My Cookbook, not the old one. + await reader.page.goto(recipeUrl); + await reader.page.getByRole('button', { name: 'Save to Cookbook' }).click(); + await expect( + reader.page.getByRole('button', { name: 'Saved', exact: true }), + ).toBeVisible(); + await reader.page.goto('cookbook?view=saved'); + await expect( + reader.page.getByRole('link', { name: 'Edited browser soup' }), + ).toBeVisible(); + await expect( + reader.page.getByRole('link', { name: 'Soup to edit' }), + ).toHaveCount(0); + } finally { + await owner.context.close(); + await reader.context.close(); + } +}); + +test('another user rates a recipe, changes and removes the rating, saving right after each', async ({ + browser, +}) => { + const owner = await signedIn(browser, 'Rated Chef'); + const reader = await signedIn(browser, 'Rating Reader'); + try { + const recipeUrl = await createRecipe(owner.user.id, 'Soup to rate'); + const page = reader.page; + await page.goto(recipeUrl); + await page + .getByRole('button', { name: 'Increase servings' }) + .first() + .click(); + await page .getByRole('button', { name: 'Rate this recipe', exact: true }) .click(); - await reader.getByRole('radio', { name: '5 stars' }).check(); - await reader.getByRole('button', { name: 'Save rating' }).click(); + await page.getByRole('radio', { name: '5 stars' }).check(); + await page.getByRole('button', { name: 'Save rating' }).click(); await expect( - reader.getByText('Rating saved.', { exact: true }), + page.getByText('Rating saved.', { exact: true }), ).toBeVisible(); + // Rating does not reset the chosen servings. await expect( - reader + page .getByRole('region', { name: 'Ingredients' }) .getByText('3 servings', { exact: true }), ).toBeVisible(); + await page.reload(); + await page.getByRole('button', { name: 'Your rating: 5/5' }).click(); + await page.getByRole('radio', { name: '3 stars' }).check(); + await page.getByRole('button', { name: 'Save rating' }).click(); + // Saving straight after changing the rating keeps both. + await page.getByRole('button', { name: 'Save to Cookbook' }).click(); await expect( - reader.getByRole('button', { name: 'Your rating: 5/5' }), + page.getByRole('button', { name: 'Saved', exact: true }), ).toBeVisible(); - await reader.reload(); - await reader.getByRole('button', { name: 'Your rating: 5/5' }).click(); - await reader.getByRole('radio', { name: '3 stars' }).check(); - await reader.getByRole('button', { name: 'Save rating' }).click(); - await reader.getByRole('button', { name: 'Your rating: 3/5' }).click(); - await reader.getByRole('button', { name: 'Remove rating' }).click(); await expect( - reader.getByRole('button', { name: 'Rate Recipe' }), + page.getByRole('button', { name: 'Your rating: 3/5' }), ).toBeVisible(); - await reader.getByRole('button', { name: 'Save to Cookbook' }).click(); + + await page.getByRole('button', { name: 'Your rating: 3/5' }).click(); + await page.getByRole('button', { name: 'Remove rating' }).click(); await expect( - reader.getByRole('button', { name: 'Saved', exact: true }), + page.getByRole('button', { name: 'Rate Recipe' }), ).toBeVisible(); - await reader.goto('cookbook?view=saved'); + // Unsaving and saving again straight after removing the rating. + await page.getByRole('button', { name: 'Saved', exact: true }).click(); + await page.getByRole('button', { name: 'Unsave', exact: true }).click(); + await page.getByRole('button', { name: 'Save to Cookbook' }).click(); await expect( - reader.getByRole('link', { name: 'Edited browser soup' }), + page.getByRole('button', { name: 'Saved', exact: true }), ).toBeVisible(); - await reader - .getByRole('button', { - name: 'Remove Edited browser soup from My Cookbook', - }) - .click(); - await reader.getByRole('button', { name: 'Unsave', exact: true }).click(); await expect( - reader.getByRole('heading', { name: 'No saved recipes yet' }), + page.getByRole('button', { name: 'Rate Recipe' }), ).toBeVisible(); - await page.getByRole('link', { name: 'Edit Recipe' }).click(); - await page.getByRole('button', { name: 'Remove image' }).click(); - await page.getByLabel('Private', { exact: true }).check(); - await page.getByRole('button', { name: 'Save changes' }).click(); + // Both are persisted: saved, and no rating. + await page.reload(); await expect( - page.getByRole('heading', { name: 'Edited browser soup' }), + page.getByRole('button', { name: 'Saved', exact: true }), ).toBeVisible(); await expect( - page.getByRole('img', { name: 'Edited browser soup', exact: true }), - ).toHaveCount(0); - await reader.goto(recipeUrl); + page.getByRole('button', { name: 'Rate Recipe' }), + ).toBeVisible(); + } finally { + await owner.context.close(); + await reader.context.close(); + } +}); + +test('another user saves a recipe to My Cookbook and unsaves it there', async ({ + browser, +}) => { + const owner = await signedIn(browser, 'Saved Chef'); + const reader = await signedIn(browser, 'Saving Reader'); + try { + const recipeUrl = await createRecipe(owner.user.id, 'Soup to save'); + const page = reader.page; + await page.goto(recipeUrl); + await page.getByRole('button', { name: 'Save to Cookbook' }).click(); await expect( - reader.getByRole('heading', { name: 'Recipe not found' }), + page.getByRole('button', { name: 'Saved', exact: true }), + ).toBeVisible(); + await page.goto('cookbook?view=saved'); + await expect( + page.getByRole('link', { name: 'Soup to save' }), ).toBeVisible(); await page + .getByRole('button', { name: 'Remove Soup to save from My Cookbook' }) + .click(); + await page.getByRole('button', { name: 'Unsave', exact: true }).click(); + await expect( + page.getByRole('heading', { name: 'No saved recipes yet' }), + ).toBeVisible(); + } finally { + await owner.context.close(); + await reader.context.close(); + } +}); + +test('a private recipe is hidden from other users, and a deleted recipe is gone', async ({ + browser, +}) => { + const owner = await signedIn(browser, 'Private Chef'); + const reader = await signedIn(browser, 'Curious Reader'); + try { + const recipeUrl = await createRecipe(owner.user.id, 'Secret soup'); + await owner.page.goto(recipeUrl); + await owner.page.getByRole('link', { name: 'Edit Recipe' }).click(); + await owner.page.getByLabel('Private', { exact: true }).check(); + await owner.page.getByRole('button', { name: 'Save changes' }).click(); + await expect( + owner.page.getByRole('heading', { name: 'Secret soup' }), + ).toBeVisible(); + await reader.page.goto(recipeUrl); + await expect( + reader.page.getByRole('heading', { name: 'Recipe not found' }), + ).toBeVisible(); + await owner.page .getByRole('button', { name: 'Delete Recipe', exact: true }) .click(); - await page + await owner.page .getByRole('button', { name: 'Delete recipe', exact: true }) .click(); await expect( - page.getByRole('heading', { name: 'My Cookbook' }), + owner.page.getByRole('heading', { name: 'My Cookbook' }), ).toBeVisible(); - await page.goto(recipeUrl); + await owner.page.goto(recipeUrl); await expect( - page.getByRole('heading', { name: 'Recipe not found' }), + owner.page.getByRole('heading', { name: 'Recipe not found' }), ).toBeVisible(); + } finally { + await owner.context.close(); + await reader.context.close(); + } +}); + +test('end-to-end journey: register, publish, find it in Explore, and another user saves it', async ({ + page, + context, + browser, +}) => { + test.setTimeout(60000); + const title = `Journey soup ${randomUUID().slice(0, 8)}`; + await connect(context); + await register(page, `${randomUUID()}@example.com`); + await fillRecipeForm(page, title); + await page.getByRole('button', { name: 'Publish recipe' }).click(); + await expect(page.getByRole('heading', { name: title })).toBeVisible(); + + const readerContext = await browser.newContext({ + baseURL: 'http://127.0.0.1:4173/project2/', + }); + try { + await connect(readerContext); + const reader = await readerContext.newPage(); + await register(reader, `${randomUUID()}@example.com`); + // The new recipe is already on the first Explore page, so first check + // that searching filters it out; only then is finding it meaningful. + await expect(reader.getByRole('link', { name: title })).toBeVisible(); + await reader.getByRole('searchbox').fill('unrelated porridge'); + await reader.getByRole('searchbox').press('Enter'); + // Wait for the search result itself: while results load, the old list + // is gone too, so a missing link alone would prove nothing. + await expect( + reader.getByRole('heading', { + name: 'No recipes found for “unrelated porridge”', + }), + ).toBeVisible(); + await expect(reader.getByRole('link', { name: title })).toHaveCount(0); + await reader.getByRole('searchbox').fill(title); + await reader.getByRole('searchbox').press('Enter'); + await reader.getByRole('link', { name: title }).click(); + await expect(reader.getByRole('heading', { name: title })).toBeVisible(); + await reader.getByRole('button', { name: 'Save to Cookbook' }).click(); + await expect( + reader.getByRole('button', { name: 'Saved', exact: true }), + ).toBeVisible(); + await reader.goto('cookbook?view=saved'); + await expect(reader.getByRole('link', { name: title })).toBeVisible(); } finally { await readerContext.close(); }