diff --git a/app/cypress.config.js b/app/cypress.config.js index 50c2ed4d..1e57b0e4 100644 --- a/app/cypress.config.js +++ b/app/cypress.config.js @@ -1,8 +1,79 @@ const path = require("path"); +const fs = require("fs"); const { defineConfig } = require("cypress"); +/* + * Real-file tasks for the FileBrowser e2e tests. + * + * The tests exercise the live stack (delete/rename/move really happen), so every task is + * jailed to one sandbox directory inside the media directory. `test/` also holds shared + * fixtures the whole suite depends on -- a task that could write or delete outside the + * sandbox would let a buggy test destroy them. + */ +const MEDIA_DIR = process.env.WROLPI_MEDIA_DIR || path.resolve(__dirname, "..", "test"); +const SANDBOX_NAME = "cypress-fb"; +const SANDBOX_DIR = path.join(MEDIA_DIR, SANDBOX_NAME); + +function sandboxPath(relativePath) { + const resolved = path.resolve(SANDBOX_DIR, relativePath || "."); + if (resolved !== SANDBOX_DIR && !resolved.startsWith(SANDBOX_DIR + path.sep)) { + throw new Error(`Refusing to touch path outside the sandbox: ${relativePath}`); + } + return resolved; +} + +const fileBrowserTasks = { + // Wipe the sandbox (including leftovers from a crashed run) and create the given files. + // `files` maps sandbox-relative paths to file content; a trailing '/' makes a bare directory. + "fb:reset": ({ files }) => { + fs.rmSync(SANDBOX_DIR, { recursive: true, force: true }); + fs.mkdirSync(SANDBOX_DIR, { recursive: true }); + for (const [relativePath, content] of Object.entries(files || {})) { + if (relativePath.endsWith("/")) { + fs.mkdirSync(sandboxPath(relativePath), { recursive: true }); + } else { + const filePath = sandboxPath(relativePath); + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + fs.writeFileSync(filePath, content ?? ""); + } + } + return SANDBOX_NAME; + }, + // Add files to the existing sandbox without wiping it (e.g. behind the UI's back). + "fb:seed": ({ files }) => { + for (const [relativePath, content] of Object.entries(files || {})) { + const filePath = sandboxPath(relativePath); + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + fs.writeFileSync(filePath, content ?? ""); + } + return true; + }, + "fb:exists": (relativePath) => fs.existsSync(sandboxPath(relativePath)), + "fb:readdir": (relativePath) => { + const dir = sandboxPath(relativePath); + return fs.existsSync(dir) ? fs.readdirSync(dir).sort() : null; + }, + "fb:cleanup": () => { + fs.rmSync(SANDBOX_DIR, { recursive: true, force: true }); + return true; + }, + // Tagging creates a hardlink under /tags//, and a force-deleted file + // leaves that link behind (the tags-directory sync refuses to remove it). Only tag + // directories created by these tests may be removed: the name must start with 'CypressFB'. + "fb:cleanup-tag-dir": (tagName) => { + if (!/^CypressFB[A-Za-z0-9]*$/.test(tagName)) { + throw new Error(`Refusing to remove tag directory not owned by the tests: ${tagName}`); + } + fs.rmSync(path.join(MEDIA_DIR, "tags", tagName), { recursive: true, force: true }); + return true; + }, +}; + module.exports = defineConfig({ e2e: { + setupNodeEvents(on) { + on("task", fileBrowserTasks); + }, // Use HTTP for CI, HTTPS for local development baseUrl: process.env.CI ? 'http://localhost:3000' : 'https://localhost:8443', specPattern: 'cypress/e2e/**/*.cy.js', diff --git a/app/cypress/e2e/files/footer-delete.cy.js b/app/cypress/e2e/files/footer-delete.cy.js new file mode 100644 index 00000000..f46cef05 --- /dev/null +++ b/app/cypress/e2e/files/footer-delete.cy.js @@ -0,0 +1,136 @@ +/* + * The Delete button in the FileBrowser's sticky footer, exercised against the live stack. + * + * Real files: the fb:* tasks seed a `cypress-fb/` sandbox in the media directory and the UI + * deletes them through the real API (POST /api/files/delete runs synchronously). Deleting a + * TAGGED file is refused with FILE_GROUP_IS_TAGGED, which opens a second confirmation listing + * the tagged files; confirming there force-deletes. + */ +import { + assertWROLModeOff, + dialog, + footerButton, + row, + selectRow, + setupFileBrowser, + teardownFileBrowser, +} from '../../support/file-browser'; + +// Requires the full stack (API + real media directory); CI runs only the React dev server. +(Cypress.env('CI') ? describe.skip : describe)('FileBrowser footer: Delete', () => { + + const seedFiles = { + 'fb-notes.txt': 'delete me', + 'fb-other.txt': 'leave me alone', + 'fb-alpha/fb-one.txt': 'child one', + 'fb-alpha/fb-two.txt': 'child two', + 'fb-tagged.txt': 'tagged, delete needs force', + }; + + const TAG_NAME = 'CypressFBDelete'; + + // Remove the suite's tag wherever a failed run may have left it, along with the + // tags// directory: force-deleting a tagged file strands its hardlink there. + // failOnStatusCode: false throughout -- a failed command aborts the rest of its hook, + // and this runs in teardown, where an API hiccup must not skip the disk cleanup. + const deleteTestTag = () => { + cy.request({url: '/api/tag', failOnStatusCode: false}).then(({body}) => { + const tag = ((body && body.tags) || []).find((t) => t.name === TAG_NAME); + if (tag) { + cy.request({ + method: 'DELETE', + url: `/api/tag/${tag.id}`, + failOnStatusCode: false, + }); + } + }); + cy.task('fb:cleanup-tag-dir', TAG_NAME); + }; + + before(() => { + assertWROLModeOff(); + deleteTestTag(); + }); + + beforeEach(() => setupFileBrowser(seedFiles, 'fb-notes.txt')); + + after(() => { + deleteTestTag(); + teardownFileBrowser(); + }); + + // The footer Delete goes through APIButton's confirmation first. + const confirmDialog = () => { + dialog().should('be.visible') + .should('contain.text', 'Are you sure you want to delete these files?'); + return dialog(); + }; + + it('cancelling the confirmation deletes nothing', () => { + selectRow('fb-notes.txt'); + footerButton('Delete').click(); + + confirmDialog().contains('button', 'Cancel').click(); + dialog().should('not.exist'); + + row('fb-notes.txt').should('be.visible'); + cy.task('fb:exists', 'fb-notes.txt').should('be.true'); + }); + + it('deletes one file from disk', () => { + selectRow('fb-notes.txt'); + footerButton('Delete').click(); + confirmDialog().contains('button', 'Delete').click(); + + cy.contains('tr', 'fb-notes.txt').should('not.exist'); + cy.task('fb:exists', 'fb-notes.txt').should('be.false'); + cy.task('fb:exists', 'fb-other.txt').should('be.true'); + }); + + it('deletes an open directory recursively without breaking the table', () => { + // Open the folder first so it is in openFolders; deleting it must also prune it + // from openFolders or the next fetch requests a directory that no longer exists. + cy.contains('.file-path', 'fb-alpha').click(); + row('fb-one.txt').should('be.visible'); + + selectRow('fb-alpha'); + footerButton('Delete').click(); + confirmDialog().contains('button', 'Delete').click(); + + cy.contains('tr', /fb-alpha$/).should('not.exist'); + cy.task('fb:exists', 'fb-alpha').should('be.false'); + + // The table still renders the remaining files -- no failed re-fetch. + row('fb-other.txt').should('be.visible'); + }); + + it('a tagged file needs the second, force-delete confirmation', () => { + // Tag the file through the real API; the FileGroup exists because setup refreshed. + cy.request('POST', '/api/tag', {name: TAG_NAME, color: '#ff0000'}); + cy.request('POST', '/api/files/tag', { + tag_name: TAG_NAME, + file_group_primary_path: 'cypress-fb/fb-tagged.txt', + }); + + // First attempt: cancel at the tagged-files warning; nothing is deleted. + selectRow('fb-tagged.txt'); + footerButton('Delete').click(); + confirmDialog().contains('button', 'Delete').click(); + + dialog().should('contain.text', 'Tagged Files Will Be Deleted') + .should('contain.text', 'cypress-fb/fb-tagged.txt') + .should('contain.text', TAG_NAME); + dialog().contains('button', 'Cancel').click(); + dialog().should('not.exist'); + cy.task('fb:exists', 'fb-tagged.txt').should('be.true'); + + // Second attempt: confirm the warning; the file is force-deleted. + footerButton('Delete').click(); + confirmDialog().contains('button', 'Delete').click(); + dialog().should('contain.text', 'Tagged Files Will Be Deleted'); + dialog().contains('button', 'Delete').click(); + + cy.contains('tr', 'fb-tagged.txt').should('not.exist'); + cy.task('fb:exists', 'fb-tagged.txt').should('be.false'); + }); +}); diff --git a/app/cypress/e2e/files/footer-ignore-upload-refresh.cy.js b/app/cypress/e2e/files/footer-ignore-upload-refresh.cy.js new file mode 100644 index 00000000..76a0682f --- /dev/null +++ b/app/cypress/e2e/files/footer-ignore-upload-refresh.cy.js @@ -0,0 +1,140 @@ +/* + * The Ignore, Upload, and Refresh buttons in the FileBrowser's sticky footer, against the + * live stack. Ignore/Upload only make sense with a single directory selected, so this spec + * also carries their enable-state rules. + */ +import { + assertWROLModeOff, + deselectRow, + dialog, + footerButton, + row, + selectRow, + setupFileBrowser, + teardownFileBrowser, +} from '../../support/file-browser'; + +// Requires the full stack (API + real media directory); CI runs only the React dev server. +(Cypress.env('CI') ? describe.skip : describe)('FileBrowser footer: Ignore, Upload, Refresh', () => { + + const seedFiles = { + 'fb-notes.txt': 'a file', + 'fb-beta/fb-inside.txt': 'inside the directory', + }; + + const IGNORED_DIR = 'cypress-fb/fb-beta'; + + before(assertWROLModeOff); + + beforeEach(() => setupFileBrowser(seedFiles, 'fb-notes.txt')); + + // Un-ignore after EVERY test: a failure mid-ignore must not leave the sandbox in the + // ignored_directories config for the spec's later tests (or the user's stack). + afterEach(() => { + cy.request({ + method: 'POST', + url: '/api/files/unignore_directory', + body: {path: `/media/wrolpi/${IGNORED_DIR}`}, + failOnStatusCode: false, + }); + }); + + after(teardownFileBrowser); + + // cy.task has no built-in retry; background work (uploads) lands on disk asynchronously. + const waitForDisk = (relativePath, timeout = 30000) => { + const deadline = Date.now() + timeout; + const poll = () => { + cy.task('fb:exists', relativePath).then((exists) => { + if (exists) return; + expect(Date.now(), `${relativePath} did not appear on disk within ${timeout}ms`) + .to.be.lessThan(deadline); + cy.wait(500); + poll(); + }); + }; + poll(); + }; + + it('Upload and Ignore require a single directory selection', () => { + // Nothing selected: Upload targets the media directory, Ignore has no directory. + footerButton('Upload').should('be.enabled'); + footerButton('Ignore').should('be.disabled'); + + selectRow('fb-notes.txt'); + footerButton('Upload').should('be.disabled'); + footerButton('Ignore').should('be.disabled'); + deselectRow('fb-notes.txt'); + + selectRow('fb-beta'); + footerButton('Upload').should('be.enabled'); + footerButton('Ignore').should('be.enabled'); + + selectRow('fb-notes.txt'); + footerButton('Upload').should('be.disabled'); + footerButton('Ignore').should('be.disabled'); + }); + + it('ignores and un-ignores a directory through the config', () => { + selectRow('fb-beta'); + footerButton('Ignore').click(); + + dialog().should('contain.text', 'Ignore Directory') + .should('contain.text', `/media/wrolpi/${IGNORED_DIR}`); + dialog().contains('button', 'Ignore').click(); + + // The directory lands in the settings config. + cy.request('/api/settings').its('body.ignored_directories') + .should('include', IGNORED_DIR); + + // With the settings reloaded the same button now offers the reverse action. + footerButton('Unignore').should('be.enabled').click(); + dialog().should('contain.text', 'Remove Ignore Directory'); + dialog().contains('button', 'Un-ignore').click(); + + cy.request('/api/settings').its('body.ignored_directories') + .should('not.include', IGNORED_DIR); + footerButton('Ignore').should('be.enabled'); + }); + + it('uploads a file into the selected directory', () => { + selectRow('fb-beta'); + footerButton('Upload').click(); + + dialog().should('contain.text', `Upload to: /media/wrolpi/${IGNORED_DIR}`); + dialog().find('input[type="file"]').selectFile({ + contents: Cypress.Buffer.from('uploaded by cypress'), + fileName: 'fb-uploaded.txt', + }, {force: true}); + + waitForDisk('fb-beta/fb-uploaded.txt'); + dialog().contains('button', 'Close').click(); + dialog().should('not.exist'); + + // The upload landed exactly where the selection pointed. + cy.task('fb:readdir', 'fb-beta').should('deep.equal', ['fb-inside.txt', 'fb-uploaded.txt']); + }); + + it('Refresh with a selection runs a scoped refresh end-to-end', () => { + // Drop a file behind the UI's back; only a refresh makes the backend index it. + cy.task('fb:seed', {files: {'fb-sneaky.txt': 'added behind the UI'}}); + + selectRow('cypress-fb'); + cy.serverNow().then((since) => { + footerButton('Refresh').click(); + // The button's refresh is scoped to the selection -- the completion event + // names the sandbox, a global refresh would say 'Global refresh completed'. + cy.waitForEvent({ + since, + event: 'directory_refresh', + message: 'Refreshed: cypress-fb', + timeout: 30000, + }); + }); + + // The browse table does not refetch after a refresh, so reload to see the result. + // The open folders live in the ?folders= query, so the sandbox stays open. + cy.reload(); + row('fb-sneaky.txt').should('be.visible'); + }); +}); diff --git a/app/cypress/e2e/files/footer-move.cy.js b/app/cypress/e2e/files/footer-move.cy.js new file mode 100644 index 00000000..5c92cdcb --- /dev/null +++ b/app/cypress/e2e/files/footer-move.cy.js @@ -0,0 +1,128 @@ +/* + * The Move button in the FileBrowser's sticky footer, exercised against the live stack. + * + * Real files: the fb:* tasks seed a `cypress-fb/` sandbox in the media directory and the + * UI moves them through the real API. Unlike rename, POST /api/files/move only QUEUES a + * background job and returns immediately -- the modal closes before anything moved -- so + * each move waits on the `file_move_completed` event before asserting the disk. + */ +import { + assertWROLModeOff, + dialog, + footerButton, + row, + selectRow, + setupFileBrowser, + teardownFileBrowser, +} from '../../support/file-browser'; + +// Requires the full stack (API + real media directory); CI runs only the React dev server. +(Cypress.env('CI') ? describe.skip : describe)('FileBrowser footer: Move', () => { + + const seedFiles = { + 'fb-notes.txt': 'move me', + 'fb-other.txt': 'leave me alone', + 'fb-alpha/fb-one.txt': 'child one', + 'fb-alpha/fb-two.txt': 'child two', + 'fb-beta/': null, + }; + + before(assertWROLModeOff); + + beforeEach(() => setupFileBrowser(seedFiles, 'fb-notes.txt')); + + after(teardownFileBrowser); + + // Type a destination into the MoveModal's DirectorySearch and pick it from the results. + const chooseDestination = (destination) => { + dialog().find('.wrolpi-searchbox-input').type(destination); + dialog().find('[role="listbox"] [role="option"]') + .contains('.wrolpi-searchbox-result-title', destination) + .click(); + }; + + // Start the clock, run the move via `act`, then wait for the background job to finish. + // The completion event names the destination ('Moved N items to /media/wrolpi/...'); match + // it so an unrelated move finishing at the same moment cannot satisfy this wait. + const moveAndWait = (destination, act) => { + cy.serverNow().then((since) => { + act(); + dialog().should('not.exist'); + cy.waitForEvent({ + since, + event: 'file_move_completed', + messageContains: `/media/wrolpi/${destination}`, + failureEvent: 'file_move_failed', + timeout: 30000, + }); + }); + }; + + it('is enabled for any selection, disabled for none', () => { + footerButton('Move').should('be.disabled'); + selectRow('fb-notes.txt'); + footerButton('Move').should('be.enabled'); + selectRow('fb-other.txt'); + footerButton('Move').should('be.enabled'); + }); + + it('moves one file into a sibling directory on disk', () => { + selectRow('fb-notes.txt'); + footerButton('Move').click(); + + dialog().should('be.visible').within(() => { + // The source column lists the path being moved. + cy.contains('pre', 'cypress-fb/fb-notes.txt'); + }); + chooseDestination('cypress-fb/fb-beta'); + // The destination column previews where the file will land. + dialog().contains('pre', 'cypress-fb/fb-beta/fb-notes.txt'); + + moveAndWait('cypress-fb/fb-beta', () => dialog().contains('button', 'Move').click()); + + cy.task('fb:exists', 'fb-beta/fb-notes.txt').should('be.true'); + cy.task('fb:exists', 'fb-notes.txt').should('be.false'); + cy.task('fb:exists', 'fb-other.txt').should('be.true'); + + // The table catches up: the file now lists under fb-beta. + cy.reload(); + cy.contains('.file-path', 'fb-beta').click(); + row('fb-notes.txt').should('be.visible'); + }); + + it('moves several selected files in one operation', () => { + cy.contains('.file-path', 'fb-alpha').click(); + row('fb-one.txt').should('be.visible'); + selectRow('fb-one.txt'); + selectRow('fb-two.txt'); + + footerButton('Move').click(); + dialog().within(() => { + cy.contains('pre', 'cypress-fb/fb-alpha/fb-one.txt'); + cy.contains('pre', 'cypress-fb/fb-alpha/fb-two.txt'); + }); + chooseDestination('cypress-fb/fb-beta'); + + moveAndWait('cypress-fb/fb-beta', () => dialog().contains('button', 'Move').click()); + + cy.task('fb:readdir', 'fb-beta').should('deep.equal', ['fb-one.txt', 'fb-two.txt']); + cy.task('fb:readdir', 'fb-alpha').should('deep.equal', []); + }); + + it('Reset clears the chosen destination, and closing moves nothing', () => { + selectRow('fb-notes.txt'); + footerButton('Move').click(); + + chooseDestination('cypress-fb/fb-beta'); + dialog().contains('pre', 'cypress-fb/fb-beta/fb-notes.txt'); + + dialog().contains('button', 'Reset').click(); + // Without a destination the second column falls back to the bare file name. + dialog().contains('pre', 'cypress-fb/fb-beta/fb-notes.txt').should('not.exist'); + + cy.get('body').type('{esc}'); + dialog().should('not.exist'); + cy.task('fb:exists', 'fb-notes.txt').should('be.true'); + cy.task('fb:exists', 'fb-beta/fb-notes.txt').should('be.false'); + }); +}); diff --git a/app/cypress/e2e/files/footer-rename.cy.js b/app/cypress/e2e/files/footer-rename.cy.js new file mode 100644 index 00000000..843397cd --- /dev/null +++ b/app/cypress/e2e/files/footer-rename.cy.js @@ -0,0 +1,129 @@ +/* + * The Rename button in the FileBrowser's sticky footer, exercised against the live stack. + * + * No API mocking: the fb:* tasks (cypress.config.js) seed real files into the media + * directory's `cypress-fb/` sandbox, the UI renames them through the real API, and the + * assertions check the disk as well as the table. The browse endpoint lists the real + * filesystem, so seeded files appear without waiting for any refresh/indexing. + */ +import { + assertWROLModeOff, + deselectRow, + dialog, + footerButton, + row, + selectRow, + setupFileBrowser, + teardownFileBrowser, +} from '../../support/file-browser'; + +// Requires the full stack (API + real media directory); CI runs only the React dev server. +(Cypress.env('CI') ? describe.skip : describe)('FileBrowser footer: Rename', () => { + + // Distinctive names so cy.contains cannot match the shared fixtures in the media directory. + const seedFiles = { + 'fb-notes.txt': 'rename me', + 'fb-other.txt': 'leave me alone', + 'fb-alpha/fb-one.txt': 'child one', + 'fb-alpha/fb-two.txt': 'child two', + }; + + before(assertWROLModeOff); + + beforeEach(() => setupFileBrowser(seedFiles, 'fb-notes.txt')); + + after(teardownFileBrowser); + + it('is enabled only when exactly one row is selected', () => { + footerButton('Rename').should('be.disabled'); + + selectRow('fb-notes.txt'); + footerButton('Rename').should('be.enabled'); + + selectRow('fb-other.txt'); + footerButton('Rename').should('be.disabled'); + + deselectRow('fb-other.txt'); + footerButton('Rename').should('be.enabled'); + }); + + it('opens prefilled, only enables Rename once the name changes, and Reset restores it', () => { + selectRow('fb-notes.txt'); + footerButton('Rename').click(); + + dialog().should('be.visible').within(() => { + cy.contains('Rename: fb-notes.txt'); + cy.get('input').should('have.value', 'fb-notes.txt'); + // The preview shows where the renamed file will live. + cy.get('pre').should('contain.text', 'cypress-fb/fb-notes.txt'); + + cy.contains('button', 'Rename').should('be.disabled'); + cy.get('input').type('2'); + cy.contains('button', 'Rename').should('be.enabled'); + cy.get('pre').should('contain.text', 'cypress-fb/fb-notes.txt2'); + + cy.contains('button', 'Reset').click(); + cy.get('input').should('have.value', 'fb-notes.txt'); + cy.contains('button', 'Rename').should('be.disabled'); + }); + + // Escape closes the modal without renaming anything. + cy.get('body').type('{esc}'); + dialog().should('not.exist'); + cy.task('fb:exists', 'fb-notes.txt').should('be.true'); + }); + + // A rename queues a refresh of the parent directory AFTER responding. Events carry no + // job id, so a test must not leave that refresh in flight: the next test's own refresh + // wait could be satisfied by this straggler while the DB still reflects the old tree. + const drainQueuedRefresh = (act) => { + cy.serverNow().then((since) => { + act(); + cy.waitForEvent({since, event: 'directory_refresh', message: 'Refreshed: cypress-fb'}); + }); + }; + + it('renames a file on disk', () => { + selectRow('fb-notes.txt'); + footerButton('Rename').click(); + + drainQueuedRefresh(() => { + dialog().within(() => { + cy.get('input').clear().type('fb-renamed.txt'); + cy.contains('button', 'Rename').click(); + }); + + dialog().should('not.exist'); + row('fb-renamed.txt').should('be.visible'); + cy.contains('tr', 'fb-notes.txt').should('not.exist'); + + cy.task('fb:exists', 'fb-renamed.txt').should('be.true'); + cy.task('fb:exists', 'fb-notes.txt').should('be.false'); + // The neighboring file was not touched. + cy.task('fb:exists', 'fb-other.txt').should('be.true'); + }); + }); + + it('renames a directory and its children move with it on disk', () => { + selectRow('fb-alpha'); + footerButton('Rename').click(); + + drainQueuedRefresh(() => { + dialog().within(() => { + cy.get('input').clear().type('fb-alpha-renamed'); + cy.contains('button', 'Rename').click(); + }); + + // A directory rename runs as a file-worker move job; the modal stays open until + // the job finishes, which takes longer than the default timeout. + cy.get('[role="dialog"]', {timeout: 30000}).should('not.exist'); + row('fb-alpha-renamed').should('be.visible'); + // The folder row's text is just the name, so anchoring excludes 'fb-alpha-renamed'. + cy.contains('tr', /fb-alpha$/).should('not.exist'); + + cy.task('fb:readdir', 'fb-alpha-renamed') + .should('deep.equal', ['fb-one.txt', 'fb-two.txt']); + cy.task('fb:exists', 'fb-alpha').should('be.false'); + }); + }); +}); diff --git a/app/cypress/support/commands.js b/app/cypress/support/commands.js index ecda4089..1ff08fe6 100644 --- a/app/cypress/support/commands.js +++ b/app/cypress/support/commands.js @@ -2,3 +2,82 @@ import {mount} from 'cypress/react' // Cypress 14 dropped the separate cypress/react18 entry point; cypress/react mounts React 18 itself. Cypress.Commands.add('mount', mount); + +/* + * Waiting on WROLPi background work. + * + * Most mutating file endpoints only QUEUE a job for the background file worker (move, refresh), + * and /api/files/worker_status reads 'idle' while jobs are still waiting in its queue, so + * neither the response nor the status endpoint says anything about completion. The reliable + * signal is the completion event on /api/events/feed. The pattern: capture the server's clock + * BEFORE starting the work, then poll the feed for a matching event newer than that timestamp. + * + * Events carry no job id, so the match is by name/message and cannot prove WHICH job finished. + * A test that leaves a job queued (e.g. rename queues a parent-directory refresh) must drain + * it before ending, or the next test's wait may be satisfied by the straggler. + */ + +// The API decides what time it is (the frontend does the same, in case of clock drift). +Cypress.Commands.add('serverNow', () => + cy.request('/api/events/feed').its('body.now')); + +/* + * cy.waitForEvent({since, event, message?, messagePrefix?, messageContains?, failureEvent?, timeout?}) + * + * Poll the events feed until an event newer than `since` matches. `event` is a name or a + * list of names; narrow further with an exact `message`, a `messagePrefix`, or a + * `messageContains` substring. If a `failureEvent` (name or list) shows up first, fail + * immediately with its message instead of timing out. + * + * cy.serverNow().then((since) => { + * // ...start the background work... + * cy.waitForEvent({since, event: 'file_move_completed', failureEvent: 'file_move_failed'}); + * }); + */ +Cypress.Commands.add('waitForEvent', ({since, event, message, messagePrefix, messageContains, failureEvent, timeout = 60000}) => { + const wanted = [].concat(event); + const failures = failureEvent ? [].concat(failureEvent) : []; + const matches = (e) => { + if (!wanted.includes(e.event)) return false; + if (message) return e.message === message; + if (messagePrefix) return (e.message || '').startsWith(messagePrefix); + if (messageContains) return (e.message || '').includes(messageContains); + return true; + }; + + const deadline = Date.now() + timeout; + const poll = () => { + cy.request(`/api/events/feed?after=${encodeURIComponent(since)}`).then(({body}) => { + const events = body.events || []; + const failed = events.find((e) => failures.includes(e.event)); + expect(failed, failed && `${failed.event}: ${failed.message}`).to.be.undefined; + if (events.some(matches)) return; + expect(Date.now(), `event '${wanted}' not seen within ${timeout}ms -- ` + + 'the file worker may be wedged (restart the api service)').to.be.lessThan(deadline); + cy.wait(1000); + poll(); + }); + }; + poll(); +}); + +/* + * cy.refreshFiles(paths, options) -- refresh files on the live stack and wait for completion. + * + * cy.refreshFiles(['cypress-fb']); // refresh one directory + * cy.refreshFiles([], {timeout: 300000}); // global refresh, longer timeout + */ +Cypress.Commands.add('refreshFiles', (paths = [], {timeout = 60000} = {}) => { + // Refresh-completed event names, by scope (wrolpi/files/worker.py). + const completionEvents = ['directory_refresh', 'files_refreshed', 'global_after_refresh_completed']; + // A single directory announces itself by name; match exactly so another test's refresh + // finishing at the same moment cannot satisfy this wait. + const singleDirectory = paths.length === 1 && !/\.[^/]+$/.test(paths[0]); + const message = singleDirectory ? `Refreshed: ${paths[0].replace(/\/$/, '')}` : undefined; + + cy.serverNow().then((since) => { + const body = paths.length ? {paths} : undefined; + cy.request('POST', '/api/files/refresh', body); + cy.waitForEvent({since, event: completionEvents, message, timeout}); + }); +}); diff --git a/app/cypress/support/file-browser.js b/app/cypress/support/file-browser.js new file mode 100644 index 00000000..81262d4b --- /dev/null +++ b/app/cypress/support/file-browser.js @@ -0,0 +1,79 @@ +/* + * Shared helpers for the FileBrowser e2e specs (cypress/e2e/files/). + * + * These specs run against the live stack with real files: the fb:* tasks + * (cypress.config.js) seed a `cypress-fb/` sandbox inside the media directory, + * and cy.refreshFiles (support/commands.js) keeps the DB in sync with it. + */ + +export const SANDBOX = 'cypress-fb'; + +export const footerButton = (label) => cy.get('.sticky-footer').contains('button', label); +export const row = (name) => cy.contains('tr', name); +export const selectRow = (name) => row(name).find('input[type="checkbox"]').check({force: true}); +export const deselectRow = (name) => row(name).find('input[type="checkbox"]').uncheck({force: true}); +export const dialog = () => cy.get('[role="dialog"]'); + +// WROL mode silently disables most footer buttons; fail loudly instead of reporting +// false failures. Call once from a spec's before(). +export const assertWROLModeOff = () => { + cy.request('/api/settings').its('body.wrol_mode').then((wrolMode) => { + expect(wrolMode, 'WROL mode must be OFF for FileBrowser e2e tests (Admin > Settings)') + .to.be.false; + }); +}; + +/* + * Seed the sandbox, sync the DB, open /files, and open the sandbox folder. + * `firstRow` should be a seeded name that proves the folder's children rendered. + */ +export const setupFileBrowser = (seedFiles, firstRow) => { + cy.task('fb:reset', {files: seedFiles}); + cy.refreshFiles([SANDBOX]); + // The footer shows labeled buttons only when it is at least 1050px wide. + cy.viewport(1280, 800); + cy.visit('/files'); + // A fresh page load replays recent events as toasts (each test run adds more), and + // they stack over the sticky footer, making cy.click() refuse the buttons. These + // specs assert on the disk and the table, not toasts, so hide the notification layer. + cy.document().then((doc) => { + const style = doc.createElement('style'); + style.textContent = '.mantine-Notifications-root { display: none !important; }'; + doc.head.appendChild(style); + }); + cy.contains('.file-path', SANDBOX).click(); + row(firstRow).should('be.visible'); +}; + +// Empty the sandbox on disk, let a refresh purge its rows from the DB, then remove the +// empty directory itself so nothing stale survives into the next run. Call from after(). +// +// The refresh is best-effort and never fails: a failed command aborts the rest of its hook, +// and the disk wipe below must always run. The next run's setup refresh repairs the DB +// even when this purge is missed. +export const teardownFileBrowser = () => { + cy.task('fb:reset', {files: {}}); + cy.serverNow().then((since) => { + cy.request({ + method: 'POST', + url: '/api/files/refresh', + body: {paths: [SANDBOX]}, + failOnStatusCode: false, + }); + const deadline = Date.now() + 30000; + const poll = () => { + cy.request({ + url: `/api/events/feed?after=${encodeURIComponent(since)}`, + failOnStatusCode: false, + }).then(({body}) => { + const done = ((body && body.events) || []).some((e) => + e.event === 'directory_refresh' && e.message === `Refreshed: ${SANDBOX}`); + if (done || Date.now() > deadline) return; + cy.wait(1000); + poll(); + }); + }; + poll(); + }); + cy.task('fb:cleanup'); +};