Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
refactor(tests): consolidate duplicated setup and near-identical cases
Josh Corbett9d5cdcb9b623
diff --git a/invokeai/frontend/webv2/src/workbench/projects/covers.test.ts b/invokeai/frontend/webv2/src/workbench/projects/covers.test.tsindex 0646ba1132..39997173c4 100644--- a/invokeai/frontend/webv2/src/workbench/projects/covers.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/covers.test.ts@@ -41,14 +41,7 @@ const createDeferred = <T = void>() => {beforeEach(async () => {vi.resetModules();api.__clientState.clear();- api.getClientStateValue.mockReset();- api.getClientStateValue.mockImplementation((key: string) => Promise.resolve(api.__clientState.get(key) ?? null));- api.setClientStateValue.mockReset();- api.setClientStateValue.mockImplementation((key: string, value: string) => {- api.__clientState.set(key, value);-- return Promise.resolve();- });+ vi.resetAllMocks();lifecycle = await import('@platform/state/accountLifecycle');covers = await import('./covers');diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.tsindex 718906bc41..5c43625935 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/archive.test.ts@@ -60,19 +60,6 @@ describe('writeArchive / readArchive', () => {expect(blob.size).toBeLessThan(repetitive.length / 2);});- it('drops directory records', async () => {- const blob = await writeArchive(- new Map([- ['images/a.png', binaryEntry(new Uint8Array([1]))],- ['images/b.png', binaryEntry(new Uint8Array([2]))],- ])- );-- const entries = await readArchive(await toBytes(blob));-- expect([...entries.keys()].sort()).toEqual(['images/a.png', 'images/b.png']);- });-it('reports a non-ZIP as not a project', async () => {await expect(readArchive(new TextEncoder().encode('this is not a zip'))).rejects.toMatchObject({reason: 'not-a-project',@@ -117,21 +104,23 @@ describe('writeArchive / readArchive', () => {await expect(readArchive(oversized)).rejects.toMatchObject({ reason: 'too-large' });});- it('refuses to write past the archive ceiling', async () => {- const oversized = new Map([['images/huge.png', { bytes: { byteLength: 5 * 1024 * 1024 * 1024 }, kind: 'binary' }]]);-- await expect(writeArchive(oversized as never)).rejects.toMatchObject({ reason: 'too-large' });- });-- it('refuses to write more entries than the ceiling allows', async () => {- const tooMany = new Map(- Array.from({ length: INVK_MAX_ENTRIES + 1 }, (_, index) => [- `images/${index}.png`,- binaryEntry(new Uint8Array([1])),- ])- );-- await expect(writeArchive(tooMany)).rejects.toMatchObject({ reason: 'too-large' });+ it.each([+ [+ 'a payload past the byte ceiling',+ () => new Map([['images/huge.png', { bytes: { byteLength: 5 * 1024 * 1024 * 1024 }, kind: 'binary' }]]),+ ],+ [+ 'more entries than the ceiling allows',+ () =>+ new Map(+ Array.from({ length: INVK_MAX_ENTRIES + 1 }, (_, index) => [+ `images/${index}.png`,+ binaryEntry(new Uint8Array([1])),+ ])+ ),+ ],+ ])('refuses to write %s', async (_label, build) => {+ await expect(writeArchive(build() as never)).rejects.toMatchObject({ reason: 'too-large' });});});@@ -214,20 +203,6 @@ describe('createExpansionBudget', () => {});describe('readArchive with the budget in the path', () => {- it('round-trips an ordinary archive, so the filter is permissive at real sizes', async () => {- const blob = await writeArchive(- new Map([- ['project.json', textEntry('a'.repeat(4096))],- ['images/a.png', binaryEntry(new Uint8Array(4096))],- ])- );-- const entries = await readArchive(new Uint8Array(await blob.arrayBuffer()));-- expect([...entries.keys()].sort()).toEqual(['images/a.png', 'project.json']);- expect(entries.get('images/a.png')!.byteLength).toBe(4096);- });-it('rejects a stored payload whose central directory understates its allocation', async () => {const blob = await writeArchive(new Map([['images/tampered.png', binaryEntry(new Uint8Array(1024 * 1024).fill(0xa5))]])diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.tsindex 9e278c2350..bdb806b6e6 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/assetTransport.test.ts@@ -1,8 +1,6 @@import { ApiError } from '@platform/transport/http';import { beforeEach, describe, expect, it, vi } from 'vitest';-import type * as assetTransportModule from './assetTransport';-import { INVK_MAX_ARCHIVE_BYTES } from './archive';const mocks = vi.hoisted(() => ({ apiFetch: vi.fn(), apiFetchJson: vi.fn(), apiFetchRaw: vi.fn() }));@@ -19,6 +17,7 @@ import {copyVideosToBoard,createAssetResponseReader,createStagingBoard,+ deleteArchiveImages,deleteArchiveVideos,deleteStagingBoard,fetchImageBytes,@@ -69,23 +68,13 @@ describe('import rollback transport', () => {});it('sends authoritative image and video identities to their batch-delete routes', async () => {- const transport = (await import('./assetTransport')) as typeof assetTransportModule & {- deleteArchiveImages?: (names: string[], signal?: AbortSignal) => Promise<void>;- deleteArchiveVideos?: (names: string[], signal?: AbortSignal) => Promise<void>;- };-- expect(transport.deleteArchiveImages).toBeTypeOf('function');- expect(transport.deleteArchiveVideos).toBeTypeOf('function');-- if (!transport.deleteArchiveImages || !transport.deleteArchiveVideos) {- return;- }-+ // Imported at the top rather than probed for: a `toBeTypeOf` guard with an early return passes+ // silently if the export ever disappears, which is the one thing this test exists to catch.const signal = new AbortController().signal;mocks.apiFetchJson.mockResolvedValue({});- await transport.deleteArchiveImages(['server-image.png'], signal);- await transport.deleteArchiveVideos(['server-video.mp4'], signal);+ await deleteArchiveImages(['server-image.png'], signal);+ await deleteArchiveVideos(['server-video.mp4'], signal);expect(mocks.apiFetchJson).toHaveBeenNthCalledWith(1, '/api/v1/images/delete', {body: JSON.stringify({ image_names: ['server-image.png'] }),@@ -118,38 +107,31 @@ describe('board media transport', () => {mocks.apiFetchJson.mockReset();});- it('uploads an image onto the staging board under its archived category', async () => {- mocks.apiFetch.mockResolvedValue(- new Response(JSON.stringify({ height: 2, image_name: 'fresh.png', width: 3 }), { status: 201 })- );-- await expect(- uploadBoardImage(new Uint8Array([1]), 'archived.png', {- boardId: 'staging',- category: 'control',- contentType: 'image/png',- })- ).resolves.toEqual({ height: 2, imageName: 'fresh.png', width: 3 });-- expect(Object.fromEntries(uploadQuery())).toEqual({- board_id: 'staging',- image_category: 'control',- is_intermediate: 'false',- });- });-- it('uploads a video onto the staging board under its archived category', async () => {- mocks.apiFetch.mockResolvedValue(new Response(JSON.stringify({ video_name: 'fresh.mp4' }), { status: 201 }));-- await expect(- uploadBoardVideo(new Uint8Array([1]), 'archived.mp4', { boardId: 'staging', category: 'user' })- ).resolves.toEqual({ videoName: 'fresh.mp4' });-- expect(Object.fromEntries(uploadQuery())).toEqual({- board_id: 'staging',- is_intermediate: 'false',- video_category: 'user',- });+ it.each([+ [+ 'image',+ () =>+ uploadBoardImage(new Uint8Array([1]), 'archived.png', {+ boardId: 'staging',+ category: 'control',+ contentType: 'image/png',+ }),+ { height: 2, image_name: 'fresh.png', width: 3 },+ { height: 2, imageName: 'fresh.png', width: 3 },+ { board_id: 'staging', image_category: 'control', is_intermediate: 'false' },+ ],+ [+ 'video',+ () => uploadBoardVideo(new Uint8Array([1]), 'archived.mp4', { boardId: 'staging', category: 'user' }),+ { video_name: 'fresh.mp4' },+ { videoName: 'fresh.mp4' },+ { board_id: 'staging', is_intermediate: 'false', video_category: 'user' },+ ],+ ])('uploads a %s onto the staging board under its archived category', async (_kind, upload, dto, expected, query) => {+ mocks.apiFetch.mockResolvedValue(new Response(JSON.stringify(dto), { status: 201 }));++ await expect(upload()).resolves.toEqual(expected);+ expect(Object.fromEntries(uploadQuery())).toEqual(query);});/**diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.tsindex 767f8b1f4c..f0ab3fbd98 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/duplicateProject.test.ts@@ -117,20 +117,19 @@ const restoredLayerName = (): string =>beforeEach(async () => {vi.resetModules();- vi.clearAllMocks();+ // Restores the hoisted `vi.fn(impl)` defaults; only `createProjectSettled`, which has none, is+ // re-established below.+ vi.resetAllMocks();const account = await import('@platform/state/accountLifecycle');account.accountLifecycle.activate('duplicate-user');owner = account.captureAccountScope();- transport.createStagingBoard.mockImplementation(() => Promise.resolve('staging-board'));+ // These two are hoisted as bare `vi.fn()` with no implementation, so unlike the rest they are+ // not restored by the reset above.transport.copyImagesToBoard.mockImplementation((names: readonly string[]) => Promise.resolve(copiesOf(names)));transport.copyVideosToBoard.mockImplementation((names: readonly string[]) => Promise.resolve(copiesOf(names)));- transport.findExistingImageNames.mockImplementation((names: readonly string[]) => Promise.resolve(new Set(names)));- transport.findExistingVideoNames.mockImplementation((names: readonly string[]) => Promise.resolve(new Set(names)));- transport.starImages.mockImplementation(() => Promise.resolve({ failed: [] }));- transport.starVideos.mockImplementation(() => Promise.resolve({ failed: [] }));api.createProjectSettled.mockImplementation((request: { board_id?: string; data: Record<string, unknown>; name: string; project_id: string }) =>Promise.resolve({diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.tsindex 038056a1f7..cf75b713f5 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/exportProject.test.ts@@ -56,10 +56,6 @@ describe('planInvkExport', () => {expect(planInvkExport(planInput).coverImageName).toBe('live-a.png');});- it('is pure — the same input yields the same plan', () => {- expect(planInvkExport(planInput)).toEqual(planInvkExport(planInput));- });-/*** The selection was already excluded from bundling; this is the other half —* it must not reach the archive at all, or the imported project opens@@ -259,56 +255,58 @@ describe('executeInvkExport', () => {* when the signal aborts, so treating those as "the server would not serve* it" would pack an archive holding nothing and download it.*/- it('rejects rather than downloading an archive when the fetches are aborted', async () => {- const download = vi.fn();- const abort = () => Promise.reject(new DOMException('The operation was aborted.', 'AbortError'));-- await expect(- executeInvkExport(planInvkExport(planInput), {- download,- fetchImageBytes: abort,- fetchImageThumbnail: abort,- })- ).rejects.toMatchObject({ name: 'AbortError' });-- expect(download).not.toHaveBeenCalled();- });-- it('rejects when the signal aborts after the last fetch but before packing', async () => {- const download = vi.fn();- const controller = new AbortController();-- await expect(- executeInvkExport(planInvkExport(planInput), {- download,- fetchImageBytes: (imageName) => {- controller.abort();-- return Promise.resolve(bytesFor(imageName));- },- fetchImageThumbnail: () => Promise.resolve(null),- signal: controller.signal,- })- ).rejects.toMatchObject({ name: 'AbortError' });+ /**+ * Cancellation is the one failure that is not a skip, wherever it lands: skipping every asset+ * would pack an archive of nothing and hand it over as a finished download.+ */+ it.each([+ [+ 'the fetches themselves abort',+ () => {+ const abort = () => Promise.reject(new DOMException('The operation was aborted.', 'AbortError'));- expect(download).not.toHaveBeenCalled();- });+ return { fetchImageBytes: abort, fetchImageThumbnail: abort };+ },+ ],+ [+ 'the signal aborts after the last fetch but before packing',+ () => {+ const controller = new AbortController();++ return {+ fetchImageBytes: (imageName: string) => {+ controller.abort();- it('rejects rather than downloading when cancellation occurs during packing', async () => {+ return Promise.resolve(bytesFor(imageName));+ },+ signal: controller.signal,+ };+ },+ ],+ [+ 'cancellation lands during packing',+ () => {+ const controller = new AbortController();++ return {+ onProgress: ({ phase }: { phase: string }) => {+ if (phase === 'packing') {+ controller.abort();+ }+ },+ signal: controller.signal,+ };+ },+ ],+ ])('rejects rather than downloading when %s', async (_label, build) => {const download = vi.fn();- const controller = new AbortController();await expect(executeInvkExport(planInvkExport(planInput), {download,fetchImageBytes: (imageName) => Promise.resolve(bytesFor(imageName)),fetchImageThumbnail: () => Promise.resolve(null),- onProgress: ({ phase }) => {- if (phase === 'packing') {- controller.abort();- }- },- signal: controller.signal,+ ...build(),})).rejects.toMatchObject({ name: 'AbortError' });diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.tsindex c481896105..77bf991357 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/importProject.test.ts@@ -3,7 +3,6 @@ import { describe, expect, it, vi } from 'vitest';import type { InvkBoardItem } from './board';import { binaryEntry, INVK_MAX_ARCHIVE_BYTES, textEntry, writeArchive } from './archive';-import { InvkFormatError } from './format';import { createArchiveMediaMaterializer, readInvkArchive, restoreArchiveMedia } from './importProject';import { createRestoredMediaLedger } from './restoreProjectMedia';@@ -156,35 +155,14 @@ describe('readInvkArchive', () => {await expect(readInvkArchive(file)).rejects.toMatchObject({ reason: 'legacy-canvas-project' });});- it('refuses an archive with no manifest', async () => {- await expect(readInvkArchive(await archiveFile({ 'project.json': '{}' }))).rejects.toMatchObject({- reason: 'not-a-project',- });- });-- it('refuses a file that is not a ZIP', async () => {- await expect(readInvkArchive(new File(['not a zip'], 'project.invk'))).rejects.toMatchObject({- reason: 'not-a-project',- });- });-- it('reports a manifest without a document as damaged', async () => {- const file = await archiveFile({ 'manifest.json': JSON.stringify(manifest()) });-- await expect(readInvkArchive(file)).rejects.toMatchObject({ reason: 'damaged' });- });-- it('reports an unparseable document as damaged', async () => {- const file = await validArchive({ 'project.json': 'not json' });-- await expect(readInvkArchive(file)).rejects.toBeInstanceOf(InvkFormatError);- await expect(readInvkArchive(file)).rejects.toMatchObject({ reason: 'damaged' });- });-- it('reports a document that is an array as damaged', async () => {- await expect(readInvkArchive(await validArchive({ 'project.json': '[]' }))).rejects.toMatchObject({- reason: 'damaged',- });+ it.each([+ ['an archive with no manifest', () => archiveFile({ 'project.json': '{}' }), 'not-a-project'],+ ['a file that is not a ZIP', () => new File(['not a zip'], 'project.invk'), 'not-a-project'],+ ['a manifest with no document', () => archiveFile({ 'manifest.json': JSON.stringify(manifest()) }), 'damaged'],+ ['an unparseable document', () => validArchive({ 'project.json': 'not json' }), 'damaged'],+ ['a document that is an array', () => validArchive({ 'project.json': '[]' }), 'damaged'],+ ])('refuses %s as %s', async (_label, build, reason) => {+ await expect(readInvkArchive(await build())).rejects.toMatchObject({ name: 'InvkFormatError', reason });});});diff --git a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.tsindex 92e896bb43..c864c968ae 100644--- a/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/invk/restoreProjectMedia.test.ts@@ -166,26 +166,6 @@ describe('board media', () => {).rejects.toBe(cancelled);});- it('reports a descriptor the source could not materialize', async () => {- const result = await restore(- { boardItems: [boardItem({ name: 'gone.png' })] },- {- materializeBoardMedia: (items, _boardId, onItemSettled) => {- onItemSettled();-- return Promise.resolve({- failed: items.map((item) => ({ kind: item.kind, name: item.name, reason: 'missing-entry' as const })),- materialized: [],- });- },- }- );-- expect(result.boardItemIssues).toEqual([{ kind: 'image', name: 'gone.png', reason: 'missing-entry' }]);- expect(result.documentReferenceIssues).toEqual([]);- expect(result.ledger.boardImageNames).toEqual([]);- });-/*** The invariant this module exists for. The old name is not neutral: on the same server it is* already taken, by the source project's own image.@@ -237,24 +217,6 @@ describe('board media', () => {expect(result.documentReferenceIssues).toEqual([]);});- it('reports a failure the materializer raised twice only once', async () => {- const result = await restore(- { boardItems: [boardItem({ name: 'twice.png' })], documentRefs: [imageRef('twice.png')] },- {- materializeBoardMedia: (items, _boardId, onItemSettled) => {- onItemSettled();-- const failed = items.map((item) => ({ kind: item.kind, name: item.name, reason: 'upload-failed' as const }));-- return Promise.resolve({ failed: [...failed, ...failed], materialized: [] });- },- }- );-- expect(result.boardItemIssues).toEqual([{ kind: 'image', name: 'twice.png', reason: 'upload-failed' }]);- expect(result.documentReferenceIssues).toEqual([{ kind: 'image', name: 'twice.png', reason: 'upload-failed' }]);- });-it('keeps two failures the board never described apart', async () => {// No descriptor position to derive from. Collapsing both onto index 0 would merge two unrelated// missing items into one dangling reference.@@ -279,14 +241,54 @@ describe('board media', () => {});/** A materializer that answers neither way has still not delivered the media. */- it('treats an unaccounted descriptor as a failure rather than a silent success', async () => {+ /**+ * Three ways a descriptor can fail to arrive, all of which must produce exactly one issue and one+ * placeholder: reported missing, reported twice, and not reported at all.+ */+ it.each([+ [+ 'the source could not materialize it',+ (items: readonly InvkBoardItem[]) =>+ items.map((item) => ({ kind: item.kind, name: item.name, reason: 'missing-entry' as const })),+ 'missing-entry' as const,+ ],+ [+ 'the materializer raised it twice',+ (items: readonly InvkBoardItem[]) => {+ const failed = items.map((item) => ({ kind: item.kind, name: item.name, reason: 'upload-failed' as const }));++ return [...failed, ...failed];+ },+ 'upload-failed' as const,+ ],+ ['the materializer never accounted for it', () => [], 'upload-failed' as const],+ ])('reports a board item once when %s', async (_label, failuresFor, reason) => {const result = await restore(- { boardItems: [boardItem({ name: 'ignored.png' })], documentRefs: [imageRef('ignored.png')] },- { materializeBoardMedia: () => Promise.resolve({ failed: [], materialized: [] }) }+ { boardItems: [boardItem({ name: 'gone.png' })], documentRefs: [imageRef('gone.png')] },+ {+ materializeBoardMedia: (items, _boardId, onItemSettled) => {+ onItemSettled();++ return Promise.resolve({ failed: failuresFor(items), materialized: [] });+ },+ });- expect(result.boardItemIssues).toEqual([{ kind: 'image', name: 'ignored.png', reason: 'upload-failed' }]);- expect(result.mappings.images.get('ignored.png')).toBe(`${PROJECT_ID}-missing-image-0`);+ expect(result.boardItemIssues).toEqual([{ kind: 'image', name: 'gone.png', reason }]);+ expect(result.documentReferenceIssues).toEqual([{ kind: 'image', name: 'gone.png', reason }]);+ expect(result.mappings.images.get('gone.png')).toBe(`${PROJECT_ID}-missing-image-0`);+ expect(result.ledger.boardImageNames).toEqual([]);+ });++ /** The document-reference issue above comes from the overlap, not from the board failure itself. */+ it('reports no document-reference issue for a failed item the document never named', async () => {+ const result = await restore(+ { boardItems: [boardItem({ name: 'gone.png' })] },+ { materializeBoardMedia: freshNameMaterializer({ fail: new Set(['gone.png']) }) }+ );++ expect(result.boardItemIssues).toEqual([{ kind: 'image', name: 'gone.png', reason: 'upload-failed' }]);+ expect(result.documentReferenceIssues).toEqual([]);});});diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.tsindex a0b51afe33..b7ca58f764 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectAssets.test.ts@@ -145,60 +145,35 @@ describe('collectLiveAssetRefs', () => {* assertion is the regression guard: the exclusion is by key, so it survives* `GalleryItem` spelling its name field the same way the canvas does.*/- it('excludes the gallery selection, of either kind', () => {- const refs = collectLiveAssetRefs(- projectDocument({- widgetInstances: {- 'gallery-1': {- state: {- values: {- selectedImage: { fullUrl: '', kind: 'video', name: 'selected.mp4' },- selectedImageName: 'video:selected.mp4',- selectedImageNames: ['video:selected.mp4'],- },- },- typeId: 'gallery',- },- },- })- );-- expect(refs.videos).toEqual(new Set());- expect(refs.images.has('selected.mp4')).toBe(false);- });-/**- * `compareImage` is a `GeneratedImageContract`, so it carries `imageName` and- * would otherwise be collected. A comparison left open is not project content.+ * `compareImage` is a `GeneratedImageContract`, so it carries `imageName` and would otherwise be+ * collected. A comparison left open is not project content. The last row guards the exclusion+ * against `selectedImage` starting to spell its name `imageName`, which no collector key matches+ * today only by accident.*/- it('excludes the compare selection', () => {- const { images } = collectLiveAssetRefs(- projectDocument({- widgetInstances: {- 'gallery-1': {- state: { values: { compareImage: { ...imageRef('compare.png'), imageUrl: '' } } },- typeId: 'gallery',- },- },- })- );-- expect(images.has('compare.png')).toBe(false);- });-- it('keeps excluding the gallery selection even if it starts spelling its name `imageName`', () => {- const { images } = collectLiveAssetRefs(- projectDocument({- widgetInstances: {- 'gallery-1': {- state: { values: { selectedImage: { imageName: 'selected.png', kind: 'image' } } },- typeId: 'gallery',- },- },- })+ it.each([+ [+ 'the selection, of either kind',+ {+ selectedImage: { fullUrl: '', kind: 'video', name: 'selected.mp4' },+ selectedImageName: 'video:selected.mp4',+ selectedImageNames: ['video:selected.mp4'],+ },+ 'selected.mp4',+ ],+ ['the compare selection', { compareImage: { ...imageRef('compare.png'), imageUrl: '' } }, 'compare.png'],+ [+ 'a selection spelling its name `imageName`',+ { selectedImage: { imageName: 'selected.png', kind: 'image' } },+ 'selected.png',+ ],+ ])('excludes %s', (_label, values, excluded) => {+ const refs = collectLiveAssetRefs(+ projectDocument({ widgetInstances: { 'gallery-1': { state: { values }, typeId: 'gallery' } } }));- expect(images.has('selected.png')).toBe(false);+ expect(refs.images.has(excluded)).toBe(false);+ expect(refs.videos.has(excluded)).toBe(false);});});@@ -236,12 +211,6 @@ describe('stripInstallationState', () => {expect(JSON.stringify(stripped)).toContain('recent.png');});- it('leaves a document with no selection identical', () => {- const document = { canvas: { document: { layers: [imageLayer('l1', 'a.png')] } }, id: 'p1' };-- expect(stripInstallationState(document)).toBe(document);- });-it('keeps the surrounding widget state intact', () => {const stripped = stripInstallationState({widgetInstances: {@@ -317,23 +286,22 @@ describe('stripInstallationState', () => {expect(JSON.stringify(stripped)).not.toContain('source-install');});- it('leaves an already-blank URL identical', () => {- const document = {- widgetStates: { gallery: { values: { recentImages: [{ imageName: 'a.png', imageUrl: '' }] } } },- };-- expect(stripInstallationState(document)).toBe(document);- });-/**- * Only the gallery widget's own two keys are installation state. A board named- * by a workflow node is an authored input and has to survive the round trip.+ * Subtrees with nothing to change keep their identity. The last row matters most: only the+ * gallery widget's own two keys are installation state, so a board named by a workflow node is an+ * authored input that has to survive the round trip.*/- it('keeps board references that mean something to the document', () => {- const document = {- workflow: { nodes: [{ inputs: { board: { value: { board_id: 'board-3' } } }, type: 'save_image' }] },- };-+ it.each([+ ['no selection', { canvas: { document: { layers: [imageLayer('l1', 'a.png')] } }, id: 'p1' }],+ [+ 'an already-blank URL',+ { widgetStates: { gallery: { values: { recentImages: [{ imageName: 'a.png', imageUrl: '' }] } } } },+ ],+ [+ 'a board reference that means something',+ { workflow: { nodes: [{ inputs: { board: { value: { board_id: 'board-3' } } }, type: 'save_image' }] } },+ ],+ ])('returns a document with %s unchanged', (_label, document) => {expect(stripInstallationState(document)).toBe(document);});});@@ -444,11 +412,10 @@ describe('selectCoverImageName', () => {).toBe('below.png');});- it('is null for a project that has produced nothing', () => {- expect(selectCoverImageName({ canvas: { document: { layers: [] } }, id: 'p', layout: {}, name: 'n' })).toBeNull();- });-- it('is null for a document missing the canvas entirely', () => {- expect(selectCoverImageName({ id: 'p', layout: {}, name: 'n' })).toBeNull();+ it.each([+ ['a project that has produced nothing', { canvas: { document: { layers: [] } }, id: 'p', layout: {}, name: 'n' }],+ ['a document missing the canvas entirely', { id: 'p', layout: {}, name: 'n' }],+ ])('is null for %s', (_label, document) => {+ expect(selectCoverImageName(document)).toBeNull();});});diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.tsindex 8273dbad4d..e914c42781 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFile.test.ts@@ -155,37 +155,9 @@ const acceptCreate = (): void => {beforeEach(async () => {vi.resetModules();- vi.clearAllMocks();- transport.fetchImageBytes.mockImplementation((imageName: string) =>- Promise.resolve(new TextEncoder().encode(`bytes:${imageName}`))- );- transport.fetchImageThumbnail.mockImplementation(() => Promise.resolve(null));- transport.findExistingImageNames.mockImplementation((_names: readonly string[]) =>- Promise.resolve(new Set<string>())- );- transport.findExistingVideoNames.mockImplementation((_names: readonly string[]) =>- Promise.resolve(new Set<string>())- );- transport.uploadArchiveImage.mockImplementation((_bytes: Uint8Array, fileName: string) =>- Promise.resolve({ height: 1, imageName: `server-${fileName}`, width: 1 })- );- transport.uploadArchiveVideo.mockImplementation((_bytes: Uint8Array, fileName: string) =>- Promise.resolve({ videoName: `server-${fileName}` })- );- transport.uploadBoardImage.mockImplementation((_bytes: Uint8Array, fileName: string) =>- Promise.resolve({ height: 1, imageName: `board-${fileName}`, width: 1 })- );- transport.uploadBoardVideo.mockImplementation((_bytes: Uint8Array, fileName: string) =>- Promise.resolve({ videoName: `board-${fileName}` })- );- transport.starImages.mockImplementation((_names: readonly string[]) => Promise.resolve({ failed: [] as string[] }));- transport.starVideos.mockImplementation((_names: readonly string[]) => Promise.resolve({ failed: [] as string[] }));- transport.createStagingBoard.mockImplementation(() => Promise.resolve('staging-board'));- transport.deleteStagingBoard.mockImplementation(() => Promise.resolve());- transport.deleteArchiveImages.mockImplementation(() => Promise.resolve());- transport.deleteArchiveVideos.mockImplementation(() => Promise.resolve());- api.getProjectBoardSnapshot.mockImplementation(() => Promise.resolve({ items: [] }));- api.getClientStateValue.mockImplementation(() => Promise.resolve(null));+ // `resetAllMocks` restores the implementations the hoisted `vi.fn(impl)` factories declare, so+ // the defaults do not need re-establishing here.+ vi.resetAllMocks();projectFile = await import('./projectFile');persistence = await import('./syncedPersistence');@@ -541,33 +513,6 @@ describe('importing a project board', () => {expect(api.createProjectSettled.mock.calls[0]![0]).not.toHaveProperty('board_id');});- it('creates no staging board for a document that will not rehydrate', async () => {- const { textEntry, writeArchive } = await import('./invk/archive');- const blob = await writeArchive(- new Map([- [- 'manifest.json',- textEntry(- JSON.stringify({- appVersion: '7.0',- contents: 'workbench-project',- createdAt: '',- name: 'No layout',- version: 2,- })- ),- ],- ['board.json', textEntry(JSON.stringify({ items: [], version: 1 }))],- ['project.json', textEntry(JSON.stringify({ name: 'No layout' }))],- ])- );-- await expect(projectFile.importProjectFile(new File([blob], 'broken.invk'))).rejects.toMatchObject({- reason: 'damaged',- });- expect(transport.createStagingBoard).not.toHaveBeenCalled();- });-it('deletes the media it created and then the staging board when the create fails', async () => {const account = await import('@platform/state/accountLifecycle');const primaryFailure = new ProjectCreateAbsentError(new Error('project create rejected'));@@ -678,28 +623,6 @@ describe('importProjectFile', () => {expect(transport.uploadArchiveImage).not.toHaveBeenCalled();});- it('refuses a legacy canvas project by reason', async () => {- const { binaryEntry, textEntry, writeArchive } = await import('./invk/archive');- const blob = await writeArchive(- new Map([- ['manifest.json', textEntry(JSON.stringify({ appVersion: '6.9', createdAt: '', name: 'C', version: 1 }))],- ['canvas_state.json', binaryEntry(new Uint8Array([1]))],- ])- );-- await expect(projectFile.importProjectFile(new File([blob], 'legacy.invk'))).rejects.toMatchObject({- reason: 'legacy-canvas-project',- });- expect(api.createProjectSettled).not.toHaveBeenCalled();- });-- it('refuses a file that is not an archive before touching the server', async () => {- await expect(projectFile.importProjectFile(new File(['{"some":"json"}'], 'x.invk'))).rejects.toMatchObject({- reason: 'not-a-project',- });- expect(api.createProjectSettled).not.toHaveBeenCalled();- });-it('refuses a damaged document before any asset or project mutation', async () => {const { binaryEntry, textEntry, writeArchive } = await import('./invk/archive');const blob = await writeArchive(@@ -734,6 +657,7 @@ describe('importProjectFile', () => {await expect(projectFile.importProjectFile(new File([blob], 'broken.invk'))).rejects.toMatchObject({reason: 'damaged',});+ expect(transport.createStagingBoard).not.toHaveBeenCalled();expect(transport.findExistingImageNames).not.toHaveBeenCalled();expect(transport.findExistingVideoNames).not.toHaveBeenCalled();expect(transport.uploadArchiveImage).not.toHaveBeenCalled();diff --git a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.tsindex 3fa1a4daae..82726dc5a6 100644--- a/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/projectFileToasts.test.ts@@ -136,75 +136,45 @@ describe('startProjectFileReport', () => {);});- it('finishes a clean run as a plain success with nothing to explain', () => {- const report = toasts.startProjectFileReport(t, 'projects.exporting');-- report.succeed('projects.exported', { boardItemIssues: [], documentReferenceIssues: [] });-- expect(toaster.update).toHaveBeenCalledWith('toast-1', {- duration: undefined,- title: 'projects.exported',- type: 'success',- });- });-- /** A project that lost forty layers must not read the same as one that lost none. */- it('finishes a lossy run as a warning naming the count', () => {- const report = toasts.startProjectFileReport(t, 'projects.exporting');-- report.succeed('projects.exported', {- boardItemIssues: [],- documentReferenceIssues: [- { kind: 'image', name: 'a.png', reason: 'fetch-failed' },- { kind: 'image', name: 'b.png', reason: 'fetch-failed' },- ],- });-- expect(toaster.update).toHaveBeenCalledWith('toast-1', {- description: 'projects.file.missingReferences({"count":2})',- duration: undefined,- title: 'projects.exported',- type: 'warning',- });- });-/*** Losing a board result and losing a canvas layer are different sizes of problem, so one count- * cannot stand for both.+ * cannot stand for both — and a project that lost forty layers must not read the same as one+ * that lost none.*/- it('counts board items and document references apart', () => {- const report = toasts.startProjectFileReport(t, 'projects.exporting');-- report.succeed('projects.exported', {- boardItemIssues: [{ kind: 'video', name: 'clip.mp4', reason: 'fetch-failed' }],- documentReferenceIssues: [- { kind: 'image', name: 'a.png', reason: 'fetch-failed' },- { kind: 'image', name: 'b.png', reason: 'fetch-failed' },- ],- });-- expect(toaster.update).toHaveBeenCalledWith('toast-1', {- description: 'projects.file.missingBoardItems({"count":1}) projects.file.missingReferences({"count":2})',- duration: undefined,- title: 'projects.exported',- type: 'warning',- });- });-- it('finishes a run that lost only board items as a warning about those', () => {+ it.each([+ ['nothing', [], [], { title: 'projects.exported', type: 'success' }],+ [+ 'only document references',+ [],+ ['a.png', 'b.png'],+ { description: 'projects.file.missingReferences({"count":2})', title: 'projects.exported', type: 'warning' },+ ],+ [+ 'only board items',+ ['unreferenced.png'],+ [],+ { description: 'projects.file.missingBoardItems({"count":1})', title: 'projects.exported', type: 'warning' },+ ],+ [+ 'both, counted apart',+ ['clip.mp4'],+ ['a.png', 'b.png'],+ {+ description: 'projects.file.missingBoardItems({"count":1}) projects.file.missingReferences({"count":2})',+ title: 'projects.exported',+ type: 'warning',+ },+ ],+ ])('settles a run that lost %s', (_label, boardNames, referenceNames, expected) => {+ const issue = (name: string) => ({ kind: 'image' as const, name, reason: 'fetch-failed' as const });const report = toasts.startProjectFileReport(t, 'projects.exporting');report.succeed('projects.exported', {- boardItemIssues: [{ kind: 'image', name: 'unreferenced.png', reason: 'fetch-failed' }],- documentReferenceIssues: [],+ boardItemIssues: boardNames.map(issue),+ documentReferenceIssues: referenceNames.map(issue),});- expect(toaster.update).toHaveBeenCalledWith('toast-1', {- description: 'projects.file.missingBoardItems({"count":1})',- duration: undefined,- title: 'projects.exported',- type: 'warning',- });+ expect(toaster.update).toHaveBeenCalledWith('toast-1', { duration: undefined, ...expected });});it('translates a format error into its reason rather than its message', async () => {diff --git a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.tsindex 63ca655174..7a310c0f9d 100644--- a/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts+++ b/invokeai/frontend/webv2/src/workbench/projects/syncedPersistence.test.ts@@ -747,61 +747,58 @@ describe('authoritative project boards', () => {* resolves, by design; the outcome is the only thing that distinguishes them.*/describe('what a flush reports', () => {- it('acknowledges a push the server took', async () => {+ /**+ * `arrange` runs after the project is open and before the flush, so each row states exactly+ * what makes its outcome different. The un-renamed row still pushes: hydration normalizes the+ * document, so its serialized form differs from what the server holds.+ */+ it.each([+ ['acknowledged', 'a push the server took', 'Edited', () => undefined],+ ['acknowledged', 'a project the server already holds unchanged', undefined, () => undefined],+ [+ 'unsynced',+ 'a push the server never took',+ 'Edited',+ () => {+ api.updateProject.mockRejectedValueOnce(new Error('the proxy refused the body'));+ },+ ],+ [+ 'superseded',+ 'a fork, because the id now holds the other version',+ 'My version',+ (id: string, project: Project) => {+ // The other device wins the race with content of its own, so this is a genuine+ // divergence rather than a revision that merely drifted.+ api.__records.set(id, {+ ...api.__records.get(id)!,+ data: persistence.serializeProjectDocument({ ...project, name: 'Their version' }),+ name: 'Their version',+ revision: 99,+ });+ },+ ],+ [+ 'superseded',+ 'a project deleted elsewhere',+ 'Edited locally',+ (id: string) => {+ api.__records.delete(id);+ },+ ],+ ])('reports %s for %s', async (kind, _label, rename, arrange) => {const project = seedServerProject('Synced');const opened = await service.hydrateProjectFromServer(project.id);- await expect(service.flushProjectToServer({ ...opened!, name: 'Edited' })).resolves.toMatchObject({- kind: 'acknowledged',- });- });+ arrange(project.id, project);- it('acknowledges a project the server already holds unchanged', async () => {- const project = seedServerProject('Synced');- const opened = await service.hydrateProjectFromServer(project.id);+ const flushed = rename === undefined ? opened! : { ...opened!, name: rename };- await expect(service.flushProjectToServer(opened!)).resolves.toMatchObject({ kind: 'acknowledged' });- });+ await expect(service.flushProjectToServer(flushed)).resolves.toMatchObject({ kind });- it('reports a push the server never took as unsynced', async () => {- const project = seedServerProject('Synced');- const opened = await service.hydrateProjectFromServer(project.id);-- api.updateProject.mockRejectedValueOnce(new Error('the proxy refused the body'));-- await expect(service.flushProjectToServer({ ...opened!, name: 'Edited' })).resolves.toMatchObject({- kind: 'unsynced',- });- expect(service.hasPendingChanges()).toBe(true);- });-- it('reports a fork as superseded, because the id now holds the other version', async () => {- const project = seedServerProject('Contested');- const opened = await service.hydrateProjectFromServer(project.id);-- // The other device wins the race with content of its own, so this is a genuine divergence- // rather than a revision that merely drifted.- api.__records.set(project.id, {- ...api.__records.get(project.id)!,- data: persistence.serializeProjectDocument({ ...project, name: 'Their version' }),- name: 'Their version',- revision: 99,- });-- await expect(service.flushProjectToServer({ ...opened!, name: 'My version' })).resolves.toMatchObject({- kind: 'superseded',- });- });-- it('reports a project deleted elsewhere as superseded', async () => {- const project = seedServerProject('Deleted elsewhere');- const opened = await service.hydrateProjectFromServer(project.id);-- api.__records.delete(project.id);-- await expect(service.flushProjectToServer({ ...opened!, name: 'Edited locally' })).resolves.toMatchObject({- kind: 'superseded',- });+ if (kind === 'unsynced') {+ expect(service.hasPendingChanges()).toBe(true);+ }});});diff --git a/tests/app/routers/conftest.py b/tests/app/routers/conftest.pyindex d91496bb3f..87e00f6048 100644--- a/tests/app/routers/conftest.py+++ b/tests/app/routers/conftest.py@@ -96,6 +96,12 @@ def _auth(token: str) -> dict[str, str]:return {"Authorization": f"Bearer {token}"}+def _create_board(client: TestClient, token: str, name: str = "Loose+Board") -> str:+ response = client.post(f"/api/v1/boards/?board_name={name}", headers=_auth(token))+ assert response.status_code == 201+ return response.json()["board_id"]++@pytest.fixturedef enable_multiuser(monkeypatch: Any, mock_invoker: Invoker):"""Enable multiuser mode and patch ApiDependencies across the routers covered by router-level tests.diff --git a/tests/app/routers/test_media_copy.py b/tests/app/routers/test_media_copy.pyindex d7dc736927..75c9af2f32 100644--- a/tests/app/routers/test_media_copy.py+++ b/tests/app/routers/test_media_copy.py@@ -23,21 +23,12 @@ from invokeai.app.services.images.images_common import ImageDTOfrom invokeai.app.services.invoker import Invokerfrom invokeai.app.services.names.names_default import SimpleNameServicefrom invokeai.app.services.urls.urls_default import LocalUrlService+from tests.app.routers.conftest import _auth, _create_boardSOURCE_METADATA = {"positive_prompt": "a cat", "seed": 12345}SOURCE_WORKFLOW = '{"name": "a workflow"}'-def _auth(token: str) -> dict[str, str]:- return {"Authorization": f"Bearer {token}"}---def _create_board(client: TestClient, token: str, name: str = "Target") -> str:- response = client.post(f"/api/v1/boards/?board_name={name}", headers=_auth(token))- assert response.status_code == status.HTTP_201_CREATED- return response.json()["board_id"]--def _owner_id(client: TestClient, token: str) -> str:board = client.post("/api/v1/boards/?board_name=Probe", headers=_auth(token))return board.json()["user_id"]@@ -142,25 +133,14 @@ def test_copying_an_image_leaves_the_source_untouched(copy_path = real_images.get_path(copy_name, image_subfolder=copy_record.image_subfolder)assert copy_path != source_pathassert copy_path.read_bytes() == source_bytes+ # Copied without a board, so it lands uncategorized rather than on one of the caller's.+ assert mock_invoker.services.images.get_dto(copy_name).board_id is None# And the source's own provenance still reads back the way it did before the copy.assert mock_invoker.services.images.get_workflow(source.image_name) == SOURCE_WORKFLOWsource_metadata = mock_invoker.services.images.get_metadata(source.image_name)assert source_metadata is not None and json.loads(source_metadata.model_dump_json()) == SOURCE_METADATA-def test_copying_without_a_board_leaves_the_copy_uncategorized(- client: TestClient, mock_invoker: Invoker, user1_token: str, real_images: DiskImageFileStorage-):- user_id = _owner_id(client, user1_token)- source = _create_source_image(mock_invoker, user_id)-- response = _copy_images(client, user1_token, image_names=[source.image_name])-- assert response.status_code == status.HTTP_200_OK- copy_name = response.json()["copied"][0]["image_name"]- assert mock_invoker.services.images.get_dto(copy_name).board_id is None--def test_one_unreadable_source_does_not_cost_the_batch(client: TestClient, mock_invoker: Invoker, user1_token: str, real_images: DiskImageFileStorage):diff --git a/tests/app/routers/test_projects.py b/tests/app/routers/test_projects.pyindex a7fbcd294a..b5a25d90f3 100644--- a/tests/app/routers/test_projects.py+++ b/tests/app/routers/test_projects.py@@ -12,16 +12,7 @@ from fastapi import statusfrom fastapi.testclient import TestClientfrom invokeai.app.services.invoker import Invoker---def _auth(token: str) -> dict[str, str]:- return {"Authorization": f"Bearer {token}"}---def _create_board(client: TestClient, token: str, name: str = "Loose+Board") -> str:- response = client.post(f"/api/v1/boards/?board_name={name}", headers=_auth(token))- assert response.status_code == status.HTTP_201_CREATED- return response.json()["board_id"]+from tests.app.routers.conftest import _auth, _create_boarddef _create_project(client: TestClient, token: str, **body: Any):diff --git a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_06_add_project_boards.py b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_06_add_project_boards.pyindex b6f3a20d69..855dc25651 100644--- a/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_06_add_project_boards.py+++ b/tests/app/services/shared/sqlite_migrator/migrations/test_migration_2026_08_06_add_project_boards.py@@ -1,10 +1,13 @@import jsonimport sqlite3+from collections.abc import Iteratorfrom logging import Loggerfrom pathlib import Pathfrom typing import Any, Optionalfrom unittest.mock import MagicMock+import pytest+from invokeai.app.services.shared.sqlite.sqlite_database import SqliteDatabasefrom invokeai.app.services.shared.sqlite_migrator.migration_loader import MigrationBuildContext, build_migrationsfrom invokeai.app.services.shared.sqlite_migrator.migrations.migration_2026_08_06_add_project_boards import (@@ -16,6 +19,16 @@ from invokeai.app.services.shared.sqlite_migrator.sqlite_migrator_impl import SqMIGRATION_ID = "2026_08_06_add_project_boards"+def db() -> Iterator[sqlite3.Connection]:+ """A schema-only database with one user, which is what all but a handful of these need."""+ connection = _make_db()++ _add_user(connection, "u1")+ yield connection+ connection.close()++def _make_db() -> sqlite3.Connection:"""A database holding just the tables this migration reads and writes."""db = sqlite3.connect(":memory:")@@ -155,9 +168,7 @@ def _run(db: sqlite3.Connection) -> AddProjectBoardsMigrationCallback:# --- adoption --------------------------------------------------------------------------------def test_adopts_the_single_valid_candidate_and_renames_it_to_the_project() -> None:- db = _make_db()- _add_user(db, "u1")+def test_adopts_the_single_valid_candidate_and_renames_it_to_the_project(db: sqlite3.Connection) -> None:_add_board(db, "board-1", name="Old board name")_add_project(db, "p1", name="My project", data=_gallery_document("board-1"))@@ -167,9 +178,7 @@ def test_adopts_the_single_valid_candidate_and_renames_it_to_the_project() -> Noassert db.execute("SELECT board_name FROM boards WHERE board_id = 'board-1';").fetchone()[0] == "My project"-def test_adopts_a_candidate_written_in_the_legacy_widget_states_shape() -> None:- db = _make_db()- _add_user(db, "u1")+def test_adopts_a_candidate_written_in_the_legacy_widget_states_shape(db: sqlite3.Connection) -> None:_add_board(db, "board-1")_add_project(db, "p1", data=_gallery_document("board-1", legacy=True))@@ -178,9 +187,7 @@ def test_adopts_a_candidate_written_in_the_legacy_widget_states_shape() -> None:assert _board_of(db, "p1") == "board-1"-def test_adopts_when_several_gallery_instances_name_the_same_board() -> None:- db = _make_db()- _add_user(db, "u1")+def test_adopts_when_several_gallery_instances_name_the_same_board(db: sqlite3.Connection) -> None:_add_board(db, "board-1")_add_project(db, "p1", data=_gallery_document("board-1", "board-1"))@@ -189,9 +196,7 @@ def test_adopts_when_several_gallery_instances_name_the_same_board() -> None:assert _board_of(db, "p1") == "board-1"-def test_creates_a_fresh_board_when_two_candidates_disagree() -> None:- db = _make_db()- _add_user(db, "u1")+def test_creates_a_fresh_board_when_two_candidates_disagree(db: sqlite3.Connection) -> None:_add_board(db, "board-1")_add_board(db, "board-2")_add_project(db, "p1", data=_gallery_document("board-1", "board-2"))@@ -201,10 +206,8 @@ def test_creates_a_fresh_board_when_two_candidates_disagree() -> None:assert _board_of(db, "p1") not in {"board-1", "board-2"}-def test_creates_a_fresh_board_for_each_disqualified_candidate() -> None:+def test_creates_a_fresh_board_for_each_disqualified_candidate(db: sqlite3.Connection) -> None:"""Every ownership test, one project each, so a regression names the rule it broke."""- db = _make_db()- _add_user(db, "u1")_add_user(db, "u2")_add_board(db, "board-foreign", user_id="u2")@@ -250,9 +253,7 @@ def test_creates_a_fresh_board_for_each_disqualified_candidate() -> None:assert _board_of(db, project_id) not in disqualified-def test_the_earlier_project_wins_a_board_two_projects_both_name() -> None:- db = _make_db()- _add_user(db, "u1")+def test_the_earlier_project_wins_a_board_two_projects_both_name(db: sqlite3.Connection) -> None:_add_board(db, "board-1")_add_project(db, "p-first", data=_gallery_document("board-1"))_add_project(db, "p-second", data=_gallery_document("board-1"))@@ -263,10 +264,8 @@ def test_the_earlier_project_wins_a_board_two_projects_both_name() -> None:assert _board_of(db, "p-second") != "board-1"-def test_two_users_may_share_a_project_id_and_still_get_distinct_boards() -> None:+def test_two_users_may_share_a_project_id_and_still_get_distinct_boards(db: sqlite3.Connection) -> None:"""`projects` is keyed (user_id, project_id), so the same id on two users is legal."""- db = _make_db()- _add_user(db, "u1")_add_user(db, "u2")_add_project(db, "shared-id", user_id="u1", name="Mine")_add_project(db, "shared-id", user_id="u2", name="Theirs")@@ -276,9 +275,7 @@ def test_two_users_may_share_a_project_id_and_still_get_distinct_boards() -> Nonassert _board_of(db, "shared-id", "u1") != _board_of(db, "shared-id", "u2")-def test_a_created_board_is_private_unarchived_and_owned_by_the_project_owner() -> None:- db = _make_db()- _add_user(db, "u1")+def test_a_created_board_is_private_unarchived_and_owned_by_the_project_owner(db: sqlite3.Connection) -> None:_add_project(db, "p1", name="Fresh project")_run(db)@@ -290,12 +287,10 @@ def test_a_created_board_is_private_unarchived_and_owned_by_the_project_owner()assert row == ("Fresh project", "u1", "private", 0)-def test_an_adopted_board_is_un_archived() -> None:+def test_an_adopted_board_is_un_archived(db: sqlite3.Connection) -> None:"""Someone who archived their project's gallery board before upgrading would otherwise end upwith a project whose board is hidden from every listing, and no route left to unhide it: thegeneric board API refuses `archived` on a claimed board, and there is no project archive API."""- db = _make_db()- _add_user(db, "u1")_add_board(db, "b1", name="Archived board", archived=True)_add_project(db, "p1", name="Project", data=_gallery_document("b1"))@@ -306,11 +301,9 @@ def test_an_adopted_board_is_un_archived() -> None:assert archived == 0-def test_a_refused_adoption_is_logged_with_its_reason() -> None:+def test_a_refused_adoption_is_logged_with_its_reason(db: sqlite3.Connection) -> None:"""A project that adopts nothing looks, to its owner, like a project that lost its images.Nothing else records which projects were affected or why."""- db = _make_db()- _add_user(db, "u1")_add_user(db, "u2")_add_board(db, "theirs", user_id="u2")_add_project(db, "p1", name="Mine", data=_gallery_document("theirs"))@@ -325,11 +318,9 @@ def test_a_refused_adoption_is_logged_with_its_reason() -> None:assert "another account" in warnings[0]-def test_a_project_whose_owner_is_gone_is_quarantined_before_the_live_table_is_rebuilt() -> None:+def test_a_project_whose_owner_is_gone_is_quarantined_before_the_live_table_is_rebuilt(db: sqlite3.Connection) -> None:"""The rebuilt table enforces the users foreign key that the old one did not. An orphan wouldabort the migration, and with it the app's ability to open the database at all."""- db = _make_db()- _add_user(db, "u1")_add_project(db, "kept", name="Kept")# Straight past the foreign key, the way a database that once ran without enforcement would.# The commit matters: the pragma is a no-op inside a transaction, and the insert above opened@@ -401,9 +392,7 @@ def test_a_project_on_a_database_with_no_users_table_is_quarantined_rather_than_assert any("no users table" in warning for warning in warnings)-def test_a_long_project_name_is_truncated_to_what_the_board_api_accepts() -> None:- db = _make_db()- _add_user(db, "u1")+def test_a_long_project_name_is_truncated_to_what_the_board_api_accepts(db: sqlite3.Connection) -> None:_add_project(db, "p1", name="x" * 400)_run(db)@@ -415,9 +404,7 @@ def test_a_long_project_name_is_truncated_to_what_the_board_api_accepts() -> Non# --- structure -------------------------------------------------------------------------------def test_every_project_gets_a_unique_board_and_the_column_rejects_reuse() -> None:- db = _make_db()- _add_user(db, "u1")+def test_every_project_gets_a_unique_board_and_the_column_rejects_reuse(db: sqlite3.Connection) -> None:for index in range(5):_add_project(db, f"p{index}")@@ -438,10 +425,8 @@ def test_every_project_gets_a_unique_board_and_the_column_rejects_reuse() -> Nonpass-def test_a_claimed_board_cannot_be_deleted_out_from_under_its_project() -> None:+def test_a_claimed_board_cannot_be_deleted_out_from_under_its_project(db: sqlite3.Connection) -> None:"""The FK is the database-level backstop behind the API's 409."""- db = _make_db()- _add_user(db, "u1")_add_project(db, "p1")_run(db)@@ -452,9 +437,7 @@ def test_a_claimed_board_cannot_be_deleted_out_from_under_its_project() -> None:pass-def test_board_membership_is_never_touched() -> None:- db = _make_db()- _add_user(db, "u1")+def test_board_membership_is_never_touched(db: sqlite3.Connection) -> None:_add_board(db, "board-1")_add_board(db, "board-2")db.execute("INSERT INTO images VALUES ('i1.png');")@@ -469,9 +452,7 @@ def test_board_membership_is_never_touched() -> None:assert db.execute("SELECT board_id, video_name FROM board_videos;").fetchall() == [("board-2", "v1.mp4")]-def test_the_rebuilt_table_keeps_its_key_columns_ordering_and_trigger() -> None:- db = _make_db()- _add_user(db, "u1")+def test_the_rebuilt_table_keeps_its_key_columns_ordering_and_trigger(db: sqlite3.Connection) -> None:db.execute("INSERT INTO projects (project_id, user_id, name, data, revision, created_at, updated_at)"" VALUES ('p1','u1','first','{}', 7, '2020-01-01 00:00:00.000', '2020-01-02 00:00:00.000');"@@ -504,9 +485,7 @@ def test_the_rebuilt_table_keeps_its_key_columns_ordering_and_trigger() -> None:)-def test_deleting_a_user_still_cascades_their_projects() -> None:- db = _make_db()- _add_user(db, "u1")+def test_deleting_a_user_still_cascades_their_projects(db: sqlite3.Connection) -> None:_add_project(db, "p1")_run(db)@@ -515,9 +494,7 @@ def test_deleting_a_user_still_cascades_their_projects() -> None:assert db.execute("SELECT COUNT(*) FROM projects;").fetchone()[0] == 0-def test_foreign_keys_are_consistent_afterwards() -> None:- db = _make_db()- _add_user(db, "u1")+def test_foreign_keys_are_consistent_afterwards(db: sqlite3.Connection) -> None:_add_board(db, "board-1")_add_project(db, "p1", data=_gallery_document("board-1"))_add_project(db, "p2")