diff options
Diffstat (limited to 'cypress/support')
-rw-r--r-- | cypress/support/commands.ts | 182 | ||||
-rw-r--r-- | cypress/support/commonUtils.ts | 29 | ||||
-rw-r--r-- | cypress/support/component-index.html | 4 | ||||
-rw-r--r-- | cypress/support/component.ts | 61 | ||||
-rw-r--r-- | cypress/support/cypress-component.d.ts | 17 | ||||
-rw-r--r-- | cypress/support/cypress-e2e.d.ts | 64 | ||||
-rw-r--r-- | cypress/support/e2e.ts | 26 | ||||
-rw-r--r-- | cypress/support/utils/assertions.ts | 40 |
8 files changed, 247 insertions, 176 deletions
diff --git a/cypress/support/commands.ts b/cypress/support/commands.ts index 477a366a421..ad486a8a8f7 100644 --- a/cypress/support/commands.ts +++ b/cypress/support/commands.ts @@ -1,94 +1,24 @@ /** - * @copyright Copyright (c) 2022 John Molakvoæ <skjnldsv@protonmail.com> - * - * @author John Molakvoæ <skjnldsv@protonmail.com> - * - * @license AGPL-3.0-or-later - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ -/* eslint-disable n/no-unpublished-import */ -import axios from '@nextcloud/axios' +// eslint-disable-next-line n/no-extraneous-import +import axios from 'axios' import { addCommands, User } from '@nextcloud/cypress' import { basename } from 'path' // Add custom commands +import '@testing-library/cypress/add-commands' import 'cypress-if' import 'cypress-wait-until' addCommands() -// Register this file's custom commands types -declare global { - // eslint-disable-next-line @typescript-eslint/no-namespace - namespace Cypress { - interface Chainable<Subject = any> { - /** - * Enable or disable a given user - */ - enableUser(user: User, enable?: boolean): Cypress.Chainable<Cypress.Response<any>>, - - /** - * Upload a file from the fixtures folder to a given user storage. - * **Warning**: Using this function will reset the previous session - */ - uploadFile(user: User, fixture?: string, mimeType?: string, target?: string): Cypress.Chainable<void>, - - /** - * Upload a raw content to a given user storage. - * **Warning**: Using this function will reset the previous session - */ - uploadContent(user: User, content: Blob, mimeType: string, target: string, mtime?: number): Cypress.Chainable<void>, - - /** - * Create a new directory - * **Warning**: Using this function will reset the previous session - */ - mkdir(user: User, target: string): Cypress.Chainable<void>, - - /** - * Set a file as favorite (or remove from favorite) - */ - setFileAsFavorite(user: User, target: string, favorite?: boolean): Cypress.Chainable<void>, - - /** - * Reset the admin theming entirely. - * **Warning**: Using this function will reset the previous session - */ - resetAdminTheming(): Cypress.Chainable<void>, - - /** - * Reset the user theming settings. - * If provided, will clear session and login as the given user. - * **Warning**: Providing a user will reset the previous session. - */ - resetUserTheming(user?: User): Cypress.Chainable<void>, - - /** - * Run an occ command in the docker container. - */ - runOccCommand(command: string, options?: Partial<Cypress.ExecOptions>): Cypress.Chainable<Cypress.Exec>, - } - } -} - const url = (Cypress.config('baseUrl') || '').replace(/\/index.php\/?$/g, '') Cypress.env('baseUrl', url) /** * Enable or disable a user - * TODO: standardise in @nextcloud/cypress + * TODO: standardize in @nextcloud/cypress * * @param {User} user the user to dis- / enable * @param {boolean} enable True if the user should be enable, false to disable @@ -115,7 +45,7 @@ Cypress.Commands.add('enableUser', (user: User, enable = true) => { /** * cy.uploadedFile - uploads a file from the fixtures folder - * TODO: standardise in @nextcloud/cypress + * TODO: standardize in @nextcloud/cypress * * @param {User} user the owner of the file, e.g. admin * @param {string} fixture the fixture file name, e.g. image1.jpg @@ -124,12 +54,12 @@ Cypress.Commands.add('enableUser', (user: User, enable = true) => { */ Cypress.Commands.add('uploadFile', (user, fixture = 'image.jpg', mimeType = 'image/jpeg', target = `/${fixture}`) => { // get fixture - return cy.fixture(fixture, 'base64').then(async file => { - // convert the base64 string to a blob - const blob = Cypress.Blob.base64StringToBlob(file, mimeType) - - cy.uploadContent(user, blob, mimeType, target) - }) + return cy.fixture(fixture, 'base64') + .then((file) => ( + // convert the base64 string to a blob + Cypress.Blob.base64StringToBlob(file, mimeType) + )) + .then((blob) => cy.uploadContent(user, blob, mimeType, target)) }) Cypress.Commands.add('setFileAsFavorite', (user: User, target: string, favorite = true) => { @@ -156,7 +86,7 @@ Cypress.Commands.add('setFileAsFavorite', (user: User, target: string, favorite <oc:favorite>${favorite ? 1 : 0}</oc:favorite> </d:prop> </d:set> - </d:propertyupdate>` + </d:propertyupdate>`, }) cy.log(`Created directory ${target}`, response) } catch (error) { @@ -168,7 +98,7 @@ Cypress.Commands.add('setFileAsFavorite', (user: User, target: string, favorite Cypress.Commands.add('mkdir', (user: User, target: string) => { // eslint-disable-next-line cypress/unsafe-to-chain-command - cy.clearCookies() + return cy.clearCookies() .then(async () => { try { const rootPath = `${Cypress.env('baseUrl')}/remote.php/dav/files/${encodeURIComponent(user.userId)}` @@ -182,55 +112,79 @@ Cypress.Commands.add('mkdir', (user: User, target: string) => { }, }) cy.log(`Created directory ${target}`, response) + return response } catch (error) { cy.log('error', error) - throw new Error('Unable to process fixture') + throw new Error('Unable to create directory') } }) }) -/** - * cy.uploadedContent - uploads a raw content - * TODO: standardise in @nextcloud/cypress - * - * @param {User} user the owner of the file, e.g. admin - * @param {Blob} blob the content to upload - * @param {string} mimeType e.g. image/png - * @param {string} target the target of the file relative to the user root - */ -Cypress.Commands.add('uploadContent', (user, blob, mimeType, target, mtime = undefined) => { +Cypress.Commands.add('rm', (user: User, target: string) => { // eslint-disable-next-line cypress/unsafe-to-chain-command cy.clearCookies() .then(async () => { - const fileName = basename(target) - - // Process paths - const rootPath = `${Cypress.env('baseUrl')}/remote.php/dav/files/${encodeURIComponent(user.userId)}` - const filePath = target.split('/').map(encodeURIComponent).join('/') try { - const file = new File([blob], fileName, { type: mimeType }) + const rootPath = `${Cypress.env('baseUrl')}/remote.php/dav/files/${encodeURIComponent(user.userId)}` + const filePath = target.split('/').map(encodeURIComponent).join('/') const response = await axios({ url: `${rootPath}${filePath}`, - method: 'PUT', - data: file, - headers: { - 'Content-Type': mimeType, - 'X-OC-MTime': mtime ? `${mtime}` : undefined, - }, + method: 'DELETE', auth: { username: user.userId, password: user.password, }, }) - cy.log(`Uploaded content as ${fileName}`, response) + cy.log(`delete file or directory ${target}`, response) } catch (error) { cy.log('error', error) - throw new Error('Unable to process fixture') + throw new Error('Unable to delete file or directory') } }) }) /** + * cy.uploadedContent - uploads a raw content + * TODO: standardize in @nextcloud/cypress + * + * @param {User} user the owner of the file, e.g. admin + * @param {Blob} blob the content to upload + * @param {string} mimeType e.g. image/png + * @param {string} target the target of the file relative to the user root + */ +Cypress.Commands.add('uploadContent', (user: User, blob: Blob, mimeType: string, target: string, mtime?: number) => { + cy.clearCookies() + return cy.then(async () => { + const fileName = basename(target) + + // Process paths + const rootPath = `${Cypress.env('baseUrl')}/remote.php/dav/files/${encodeURIComponent(user.userId)}` + const filePath = target.split('/').map(encodeURIComponent).join('/') + try { + const file = new File([blob], fileName, { type: mimeType }) + const response = await axios({ + url: `${rootPath}${filePath}`, + method: 'PUT', + data: file, + headers: { + 'Content-Type': mimeType, + 'X-OC-MTime': mtime ? `${mtime}` : undefined, + }, + auth: { + username: user.userId, + password: user.password, + }, + }) + cy.log(`Uploaded content as ${fileName}`, response) + return response + } catch (error) { + cy.log('error', error) + throw new Error('Unable to process fixture') + } + }) +}) + +/** * Reset the admin theming entirely */ Cypress.Commands.add('resetAdminTheming', () => { @@ -286,7 +240,9 @@ Cypress.Commands.add('resetUserTheming', (user?: User) => { } }) -Cypress.Commands.add('runOccCommand', (command: string, options?: Partial<Cypress.ExecOptions>) => { - const env = Object.entries(options?.env ?? {}).map(([name, value]) => `-e '${name}=${value}'`).join(' ') - return cy.exec(`docker exec --user www-data ${env} nextcloud-cypress-tests-server php ./occ ${command}`, options) +Cypress.Commands.add('userFileExists', (user: string, path: string) => { + user.replaceAll('"', '\\"') + path.replaceAll('"', '\\"').replaceAll(/^\/+/gm, '') + return cy.runCommand(`stat --printf="%s" "data/${user}/files/${path}"`, { failOnNonZeroExit: true }) + .then((exec) => Number.parseInt(exec.stdout || '0')) }) diff --git a/cypress/support/commonUtils.ts b/cypress/support/commonUtils.ts index 82c55c8e91e..8d02ace151b 100644 --- a/cypress/support/commonUtils.ts +++ b/cypress/support/commonUtils.ts @@ -1,4 +1,11 @@ /** + * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { basename } from 'path' + +/** * Get the header navigation bar */ export function getNextcloudHeader() { @@ -44,9 +51,13 @@ export function installTestApp() { cy.runOccCommand('-V').then((output) => { const version = output.stdout.match(/(\d\d+)\.\d+\.\d+/)?.[1] cy.wrap(version).should('not.be.undefined') - cy.exec(`docker cp '${testAppPath}' nextcloud-cypress-tests-server:/var/www/html/apps`, { log: true }) - cy.exec(`docker exec nextcloud-cypress-tests-server sed -i -e 's|-version="[0-9]\\+|-version="${version}|g' apps/testapp/appinfo/info.xml`) - cy.runOccCommand('app:enable testapp') + getContainerName() + .then(containerName => { + cy.exec(`docker cp '${testAppPath}' ${containerName}:/var/www/html/apps`, { log: true }) + cy.exec(`docker exec --workdir /var/www/html ${containerName} chown -R www-data:www-data /var/www/html/apps/testapp`) + }) + cy.runCommand(`sed -i -e 's|-version=\\"[0-9]\\+|-version=\\"${version}|g' apps/testapp/appinfo/info.xml`) + cy.runOccCommand('app:enable --force testapp') }) } @@ -55,5 +66,15 @@ export function installTestApp() { */ export function uninstallTestApp() { cy.runOccCommand('app:remove testapp', { failOnNonZeroExit: false }) - cy.exec('docker exec nextcloud-cypress-tests-server rm -fr apps/testapp/appinfo/info.xml') + cy.runCommand('rm -fr apps/testapp/appinfo/info.xml') +} + +/** + * + */ +export function getContainerName(): Cypress.Chainable<string> { + return cy.exec('pwd') + .then(({ stdout }) => { + return cy.wrap(`nextcloud-cypress-tests_${basename(stdout).replace(' ', '')}`) + }) } diff --git a/cypress/support/component-index.html b/cypress/support/component-index.html index ac6e79fd83d..e525b445373 100644 --- a/cypress/support/component-index.html +++ b/cypress/support/component-index.html @@ -1,4 +1,8 @@ <!DOCTYPE html> +<!-- + - SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors + - SPDX-License-Identifier: AGPL-3.0-or-later +--> <html> <head> <meta charset="utf-8"> diff --git a/cypress/support/component.ts b/cypress/support/component.ts index da56f124826..853609bb4dd 100644 --- a/cypress/support/component.ts +++ b/cypress/support/component.ts @@ -1,52 +1,28 @@ /** - * @copyright Copyright (c) 2022 John Molakvoæ <skjnldsv@protonmail.com> - * - * @author John Molakvoæ <skjnldsv@protonmail.com> - * - * @license AGPL-3.0-or-later - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ + +import '@testing-library/cypress/add-commands' import 'cypress-axe' +// styles +import '../../apps/theming/css/default.css' +import '../../core/css/server.css' + /* eslint-disable */ import { mount } from '@cypress/vue2' -// Example use: -// cy.mount(MyComponent) -Cypress.Commands.add('mount', (component, optionsOrProps) => { - let instance = null - const oldMounted = component?.mounted || false +Cypress.Commands.add('mount', (component, options = {}) => { + // Setup options object + options.extensions = options.extensions || {} + options.extensions.plugins = options.extensions.plugins || [] + options.extensions.components = options.extensions.components || {} - // Override the mounted method to expose - // the component instance to cypress - component.mounted = function() { - // eslint-disable-next-line - instance = this - if (oldMounted) { - oldMounted() - } - } - - // Expose the component with cy.get('@component') - return mount(component, optionsOrProps).then(() => { - return cy.wrap(instance).as('component') - }) + return mount(component, options) }) -Cypress.Commands.add('mockInitialState', (app: string, key: string, value: any) => { +Cypress.Commands.add('mockInitialState', (app: string, key: string, value: unknown) => { cy.document().then(($document) => { const input = $document.createElement('input') input.setAttribute('type', 'hidden') @@ -57,8 +33,13 @@ Cypress.Commands.add('mockInitialState', (app: string, key: string, value: any) }) Cypress.Commands.add('unmockInitialState', (app?: string, key?: string) => { + cy.window().then(($window) => { + // @ts-expect-error internal value + delete $window._nc_initial_state + }) + cy.document().then(($document) => { $document.querySelectorAll('body > input[type="hidden"]' + (app ? `[id="initial-state-${app}-${key}"]` : '')) .forEach((node) => $document.body.removeChild(node)) }) -})
\ No newline at end of file +}) diff --git a/cypress/support/cypress-component.d.ts b/cypress/support/cypress-component.d.ts new file mode 100644 index 00000000000..735db871e35 --- /dev/null +++ b/cypress/support/cypress-component.d.ts @@ -0,0 +1,17 @@ +/*! + * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import type { mount } from '@cypress/vue2' + +declare global { + // eslint-disable-next-line @typescript-eslint/no-namespace + namespace Cypress { + interface Chainable { + mount: typeof mount + mockInitialState: (app: string, key: string, value: unknown) => Cypress.Chainable<void> + unmockInitialState: (app?: string, key?: string) => Cypress.Chainable<void> + } + } +} diff --git a/cypress/support/cypress-e2e.d.ts b/cypress/support/cypress-e2e.d.ts new file mode 100644 index 00000000000..97385ac070b --- /dev/null +++ b/cypress/support/cypress-e2e.d.ts @@ -0,0 +1,64 @@ +/*! + * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +// eslint-disable-next-line n/no-extraneous-import +import type { AxiosResponse } from 'axios' + +declare global { + // eslint-disable-next-line @typescript-eslint/no-namespace + namespace Cypress { + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unused-vars + interface Chainable<Subject = any> { + /** + * Enable or disable a given user + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + enableUser(user: User, enable?: boolean): Cypress.Chainable<Cypress.Response<any>>, + + /** + * Upload a file from the fixtures folder to a given user storage. + * **Warning**: Using this function will reset the previous session + */ + uploadFile(user: User, fixture?: string, mimeType?: string, target?: string): Cypress.Chainable<AxiosResponse>, + + /** + * Upload a raw content to a given user storage. + * **Warning**: Using this function will reset the previous session + */ + uploadContent(user: User, content: Blob, mimeType: string, target: string, mtime?: number): Cypress.Chainable<AxiosResponse>, + + /** + * Delete a file or directory + */ + rm(user: User, target: string): Cypress.Chainable<AxiosResponse>, + + /** + * Create a new directory + * **Warning**: Using this function will reset the previous session + */ + mkdir(user: User, target: string): Cypress.Chainable<AxiosResponse>, + + /** + * Set a file as favorite (or remove from favorite) + */ + setFileAsFavorite(user: User, target: string, favorite?: boolean): Cypress.Chainable<void>, + + /** + * Reset the admin theming entirely. + * **Warning**: Using this function will reset the previous session + */ + resetAdminTheming(): Cypress.Chainable<void>, + + /** + * Reset the user theming settings. + * If provided, will clear session and login as the given user. + * **Warning**: Providing a user will reset the previous session. + */ + resetUserTheming(user?: User): Cypress.Chainable<void>, + + userFileExists(user: string, path: string): Cypress.Chainable<number> + } + } +} diff --git a/cypress/support/e2e.ts b/cypress/support/e2e.ts index 6cf83e94961..65fb4b2a110 100644 --- a/cypress/support/e2e.ts +++ b/cypress/support/e2e.ts @@ -1,27 +1,15 @@ /** - * @copyright Copyright (c) 2022 John Molakvoæ <skjnldsv@protonmail.com> - * - * @author John Molakvoæ <skjnldsv@protonmail.com> - * - * @license AGPL-3.0-or-later - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ import 'cypress-axe' import './commands.ts' +// Remove with Node 22 +// Ensure that we can use `Promise.withResolvers` - works in browser but on Node we need Node 22+ +import 'core-js/actual/promise/with-resolvers.js' + // Fix ResizeObserver loop limit exceeded happening in Cypress only // @see https://github.com/cypress-io/cypress/issues/20341 Cypress.on('uncaught:exception', err => !err.message.includes('ResizeObserver loop limit exceeded')) +Cypress.on('uncaught:exception', err => !err.message.includes('ResizeObserver loop completed with undelivered notifications')) diff --git a/cypress/support/utils/assertions.ts b/cypress/support/utils/assertions.ts new file mode 100644 index 00000000000..08b93b32e86 --- /dev/null +++ b/cypress/support/utils/assertions.ts @@ -0,0 +1,40 @@ +/*! + * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +import { ZipReader } from '@zip.js/zip.js' +/** + * Assert that a file contains a list of expected files + * @param expectedFiles List of expected filenames + * @example + * ```js + * cy.readFile('file', null, { ... }) + * .should(zipFileContains(['file.txt'])) + * ``` + */ +export function zipFileContains(expectedFiles: string[]) { + return async (buffer: Buffer) => { + const blob = new Blob([buffer]) + const zip = new ZipReader(blob.stream()) + // check the real file names + const entries = (await zip.getEntries()).map((e) => e.filename).sort() + console.info('Zip contains entries:', entries) + expect(entries).to.deep.equal(expectedFiles.sort()) + } +} + +/** + * Check validity of an input element + * @param validity The expected validity message (empty string means it is valid) + * @example + * ```js + * cy.findByRole('textbox') + * .should(haveValidity(/must not be empty/i)) + * ``` + */ +export const haveValidity = (validity: string | RegExp) => { + if (typeof validity === 'string') { + return (el: JQuery<HTMLElement>) => expect((el.get(0) as HTMLInputElement).validationMessage).to.equal(validity) + } + return (el: JQuery<HTMLElement>) => expect((el.get(0) as HTMLInputElement).validationMessage).to.match(validity) +} |