1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 // ***********************************************
6 // This example commands.js shows you how to
7 // create various custom commands and overwrite
10 // For more comprehensive examples of custom
11 // commands please read more here:
12 // https://on.cypress.io/custom-commands
13 // ***********************************************
16 // -- This is a parent command --
17 // Cypress.Commands.add("login", (email, password) => { ... })
20 // -- This is a child command --
21 // Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... })
24 // -- This is a dual command --
25 // Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... })
28 // -- This will overwrite an existing command --
29 // Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... })
31 import { extractFilesData } from "services/collection-service/collection-service-files-response";
33 const controllerURL = Cypress.env('controller_url');
34 const systemToken = Cypress.env('system_token');
35 let createdResources = [];
37 const containerLogFolderPrefix = 'log for container ';
39 // Clean up on a 'before' hook to allow post-mortem analysis on individual tests.
40 beforeEach(function () {
41 if (createdResources.length === 0) {
44 cy.log(`Cleaning ${createdResources.length} previously created resource(s)`);
45 createdResources.forEach(function({suffix, uuid}) {
46 // Don't fail when a resource isn't already there, some objects may have
47 // been removed, directly or indirectly, from the test that created them.
48 cy.deleteResource(systemToken, suffix, uuid, false);
50 createdResources = [];
54 "doRequest", (method = 'GET', path = '', data = null, qs = null,
55 token = systemToken, auth = false, followRedirect = true, failOnStatusCode = true) => {
58 url: `${controllerURL.replace(/\/+$/, '')}/${path.replace(/^\/+/, '')}`,
60 qs: auth ? qs : Object.assign({ api_token: token }, qs),
61 auth: auth ? { bearer: `${token}` } : undefined,
62 followRedirect: followRedirect,
63 failOnStatusCode: failOnStatusCode
68 "doWebDAVRequest", (method = 'GET', path = '', data = null, qs = null,
69 token = systemToken, auth = false, followRedirect = true, failOnStatusCode = true) => {
70 return cy.doRequest('GET', '/arvados/v1/config', null, null).then(({body: config}) => {
73 url: `${config.Services.WebDAVDownload.ExternalURL.replace(/\/+$/, '')}/${path.replace(/^\/+/, '')}`,
75 qs: auth ? qs : Object.assign({ api_token: token }, qs),
76 auth: auth ? { bearer: `${token}` } : undefined,
77 followRedirect: followRedirect,
78 failOnStatusCode: failOnStatusCode
84 "getUser", (username, first_name = '', last_name = '', is_admin = false, is_active = true) => {
85 // Create user if not already created
86 return cy.doRequest('POST', '/auth/controller/callback', {
87 auth_info: JSON.stringify({
88 email: `${username}@example.local`,
90 first_name: first_name,
94 return_to: ',https://example.local'
95 }, null, systemToken, true, false) // Don't follow redirects so we can catch the token
96 .its('headers.location').as('location')
97 // Get its token and set the account up as admin and/or active
99 this.userToken = this.location.split("=")[1]
100 assert.isString(this.userToken)
101 return cy.doRequest('GET', '/arvados/v1/users', null, {
102 filters: `[["username", "=", "${username}"]]`
104 .its('body.items.0').as('aUser')
106 cy.doRequest('PUT', `/arvados/v1/users/${this.aUser.uuid}`, {
112 .its('body').as('theUser')
114 cy.doRequest('GET', '/arvados/v1/api_clients', null, {
115 filters: `[["is_trusted", "=", false]]`,
116 order: `["created_at desc"]`
118 .its('body.items').as('apiClients')
120 if (this.apiClients.length > 0) {
121 cy.doRequest('PUT', `/arvados/v1/api_clients/${this.apiClients[0].uuid}`, {
126 .its('body').as('updatedApiClient')
128 assert(this.updatedApiClient.is_trusted);
133 return { user: this.theUser, token: this.userToken };
141 Cypress.Commands.add(
142 "createLink", (token, data) => {
143 return cy.createResource(token, 'links', {
144 link: JSON.stringify(data)
149 Cypress.Commands.add(
150 "createGroup", (token, data) => {
151 return cy.createResource(token, 'groups', {
152 group: JSON.stringify(data),
153 ensure_unique_name: true
158 Cypress.Commands.add(
159 "trashGroup", (token, uuid) => {
160 return cy.deleteResource(token, 'groups', uuid);
165 Cypress.Commands.add(
166 "createWorkflow", (token, data) => {
167 return cy.createResource(token, 'workflows', {
168 workflow: JSON.stringify(data),
169 ensure_unique_name: true
174 Cypress.Commands.add(
175 "createCollection", (token, data) => {
176 return cy.createResource(token, 'collections', {
177 collection: JSON.stringify(data),
178 ensure_unique_name: true
183 Cypress.Commands.add(
184 "getCollection", (token, uuid) => {
185 return cy.getResource(token, 'collections', uuid)
189 Cypress.Commands.add(
190 "updateCollection", (token, uuid, data) => {
191 return cy.updateResource(token, 'collections', uuid, {
192 collection: JSON.stringify(data)
197 Cypress.Commands.add(
198 "collectionReplaceFiles", (token, uuid, data) => {
199 return cy.updateResource(token, 'collections', uuid, {
201 preserve_version: true,
203 replace_files: JSON.stringify(data)
208 Cypress.Commands.add(
209 "getContainer", (token, uuid) => {
210 return cy.getResource(token, 'containers', uuid)
214 Cypress.Commands.add(
215 "updateContainer", (token, uuid, data) => {
216 return cy.updateResource(token, 'containers', uuid, {
217 container: JSON.stringify(data)
222 Cypress.Commands.add(
223 "getContainerRequest", (token, uuid) => {
224 return cy.getResource(token, 'container_requests', uuid)
228 Cypress.Commands.add(
229 'createContainerRequest', (token, data) => {
230 return cy.createResource(token, 'container_requests', {
231 container_request: JSON.stringify(data),
232 ensure_unique_name: true
237 Cypress.Commands.add(
238 "updateContainerRequest", (token, uuid, data) => {
239 return cy.updateResource(token, 'container_requests', uuid, {
240 container_request: JSON.stringify(data)
246 * Requires an admin token for log_uuid modification to succeed
248 Cypress.Commands.add(
249 "appendLog", (token, crUuid, fileName, lines = []) => (
250 cy.getContainerRequest(token, crUuid).then((containerRequest) => {
251 if (containerRequest.log_uuid) {
252 cy.listContainerRequestLogs(token, crUuid).then((logFiles) => {
253 const filePath = `${containerRequest.log_uuid}/${containerLogFolderPrefix}${containerRequest.container_uuid}/${fileName}`;
254 if (logFiles.find((file) => (file.name === fileName))) {
255 // File exists, fetch and append
256 return cy.doWebDAVRequest(
263 .then(({ body: contents }) => cy.doWebDAVRequest(
266 contents.split("\n").concat(lines).join("\n"),
271 // File not exists, put new file
282 // Create log collection
283 return cy.createCollection(token, {
284 name: `Test log collection ${Math.floor(Math.random() * 999999)}`,
285 owner_uuid: containerRequest.owner_uuid,
287 }).then((collection) => {
288 // Update CR log_uuid to fake log collection
289 cy.updateContainerRequest(token, containerRequest.uuid, {
290 log_uuid: collection.uuid,
292 // Create empty directory for container uuid
293 cy.collectionReplaceFiles(token, collection.uuid, {
294 [`/${containerLogFolderPrefix}${containerRequest.container_uuid}`]: "d41d8cd98f00b204e9800998ecf8427e+0"
296 // Put new log file with contents into fake log collection
299 `c=${collection.uuid}/${containerLogFolderPrefix}${containerRequest.container_uuid}/${fileName}`,
312 Cypress.Commands.add(
313 "listContainerRequestLogs", (token, crUuid) => (
314 cy.getContainerRequest(token, crUuid).then((containerRequest) => (
315 cy.doWebDAVRequest('PROPFIND', `c=${containerRequest.log_uuid}/${containerLogFolderPrefix}${containerRequest.container_uuid}`, null, null, token)
316 .then(({body: data}) => {
317 return extractFilesData(new DOMParser().parseFromString(data, "text/xml"));
323 Cypress.Commands.add(
324 "createVirtualMachine", (token, data) => {
325 return cy.createResource(token, 'virtual_machines', {
326 virtual_machine: JSON.stringify(data),
327 ensure_unique_name: true
332 Cypress.Commands.add(
333 "getResource", (token, suffix, uuid) => {
334 return cy.doRequest('GET', `/arvados/v1/${suffix}/${uuid}`, null, {}, token)
336 .then(function (resource) {
342 Cypress.Commands.add(
343 "createResource", (token, suffix, data) => {
344 return cy.doRequest('POST', '/arvados/v1/' + suffix, data, null, token, true)
346 .then(function (resource) {
347 createdResources.push({suffix, uuid: resource.uuid});
353 Cypress.Commands.add(
354 "deleteResource", (token, suffix, uuid, failOnStatusCode = true) => {
355 return cy.doRequest('DELETE', '/arvados/v1/' + suffix + '/' + uuid, null, null, token, false, true, failOnStatusCode)
357 .then(function (resource) {
363 Cypress.Commands.add(
364 "updateResource", (token, suffix, uuid, data) => {
365 return cy.doRequest('PATCH', '/arvados/v1/' + suffix + '/' + uuid, data, null, token, true)
367 .then(function (resource) {
373 Cypress.Commands.add(
374 "loginAs", (user) => {
376 cy.clearLocalStorage()
377 cy.visit(`/token/?api_token=${user.token}`);
378 cy.url({timeout: 10000}).should('contain', '/projects/');
379 cy.get('div#root').should('contain', 'Arvados Workbench (zzzzz)');
380 cy.get('div#root').should('not.contain', 'Your account is inactive');
384 Cypress.Commands.add(
385 "testEditProjectOrCollection", (container, oldName, newName, newDescription, isProject = true) => {
386 cy.get(container).contains(oldName).rightclick();
387 cy.get('[data-cy=context-menu]').contains(isProject ? 'Edit project' : 'Edit collection').click();
388 cy.get('[data-cy=form-dialog]').within(() => {
389 cy.get('input[name=name]').clear().type(newName);
390 cy.get(isProject ? 'div[contenteditable=true]' : 'input[name=description]').clear().type(newDescription);
391 cy.get('[data-cy=form-submit-btn]').click();
394 cy.get(container).contains(newName).rightclick();
395 cy.get('[data-cy=context-menu]').contains(isProject ? 'Edit project' : 'Edit collection').click();
396 cy.get('[data-cy=form-dialog]').within(() => {
397 cy.get('input[name=name]').should('have.value', newName);
400 cy.get('span[data-text=true]').contains(newDescription);
402 cy.get('input[name=description]').should('have.value', newDescription);
405 cy.get('[data-cy=form-cancel-btn]').click();
410 Cypress.Commands.add(
411 "doSearch", (searchTerm) => {
412 cy.get('[data-cy=searchbar-input-field]').type(`{selectall}${searchTerm}{enter}`);
416 Cypress.Commands.add(
417 "goToPath", (path) => {
418 return cy.window().its('appHistory').invoke('push', path);
422 Cypress.Commands.add('getAll', (...elements) => {
423 const promise = cy.wrap([], { log: false })
425 for (let element of elements) {
426 promise.then(arr => cy.get(element).then(got => cy.wrap([...arr, got])))
432 Cypress.Commands.add('shareWith', (srcUserToken, targetUserUUID, itemUUID, permission = 'can_write') => {
433 cy.createLink(srcUserToken, {
435 link_class: 'permission',
437 tail_uuid: targetUserUUID
441 Cypress.Commands.add('addToFavorites', (userToken, userUUID, itemUUID) => {
442 cy.createLink(userToken, {
446 owner_uuid: userUUID,
451 Cypress.Commands.add('createProject', ({
458 const writePermission = canWrite ? 'can_write' : 'can_read';
460 cy.createGroup(owningUser.token, {
461 name: `${projectName} ${Math.floor(Math.random() * 999999)}`,
462 group_class: 'project',
463 }).as(`${projectName}`).then((project) => {
464 if (targetUser && targetUser !== owningUser) {
465 cy.shareWith(owningUser.token, targetUser.user.uuid, project.uuid, writePermission);
467 if (addToFavorites) {
468 const user = targetUser ? targetUser : owningUser;
469 cy.addToFavorites(user.token, user.user.uuid, project.uuid);
474 Cypress.Commands.add(
477 prevSubject: 'element',
479 (subject, file, fileName, binaryMode = true) => {
480 cy.window().then(window => {
481 const blob = binaryMode
482 ? b64toBlob(file, '', 512)
483 : new Blob([file], {type: 'text/plain'});
484 const testFile = new window.File([blob], fileName);
486 cy.wrap(subject).trigger('drop', {
487 dataTransfer: { files: [testFile] },
493 function b64toBlob(b64Data, contentType = '', sliceSize = 512) {
494 const byteCharacters = atob(b64Data)
495 const byteArrays = []
497 for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
498 const slice = byteCharacters.slice(offset, offset + sliceSize);
500 const byteNumbers = new Array(slice.length);
501 for (let i = 0; i < slice.length; i++) {
502 byteNumbers[i] = slice.charCodeAt(i);
505 const byteArray = new Uint8Array(byteNumbers);
507 byteArrays.push(byteArray);
510 const blob = new Blob(byteArrays, { type: contentType });
514 // From https://github.com/cypress-io/cypress/issues/7306#issuecomment-1076451070=
515 // This command requires the async package (https://www.npmjs.com/package/async)
516 Cypress.Commands.add('waitForDom', () => {
518 // Don't timeout before waitForDom finishes
523 cy.log("Waiting for DOM mutations to complete");
525 return new Cypress.Promise((resolve) => {
526 // set the required variables
527 let async = require("async");
528 let observerConfig = { attributes: true, childList: true, subtree: true };
529 let items = Array.apply(null, { length: 50 }).map(Number.call, Number);
530 win.mutationCount = 0;
531 win.previousMutationCount = null;
533 // create an observer instance
534 let observer = new win.MutationObserver((mutations) => {
535 mutations.forEach((mutation) => {
536 // Only record "attributes" type mutations that are not a "class" mutation.
537 // If the mutation is not an "attributes" type, then we always record it.
538 if (mutation.type === 'attributes' && mutation.attributeName !== 'class') {
539 win.mutationCount += 1;
540 } else if (mutation.type !== 'attributes') {
541 win.mutationCount += 1;
545 // initialize the previousMutationCount
546 if (win.previousMutationCount == null) win.previousMutationCount = 0;
549 // watch the document body for the specified mutations
550 observer.observe(win.document.body, observerConfig);
552 // check the DOM for mutations up to 50 times for a maximum time of 5 seconds
553 async.eachSeries(items, function iteratee(item, callback) {
554 // keep track of the elapsed time so we can log it at the end of the command
555 timeElapsed = timeElapsed + 100;
557 // make each iteration of the loop 100ms apart
559 if (win.mutationCount === win.previousMutationCount) {
560 // pass an argument to the async callback to exit the loop
561 return callback('Resolved - DOM changes complete.');
562 } else if (win.previousMutationCount != null) {
563 // only set the previous count if the observer has checked the DOM at least once
564 win.previousMutationCount = win.mutationCount;
566 } else if (win.mutationCount === 0 && win.previousMutationCount == null && item === 4) {
567 // this is an early exit in case nothing is changing in the DOM. That way we only
568 // wait 500ms instead of the full 5 seconds when no DOM changes are occurring.
569 return callback('Resolved - Exiting early since no DOM changes were detected.');
571 // proceed to the next iteration
576 // Log the total wait time so users can see it
577 cy.log(`DOM mutations ${timeElapsed >= 5000 ? "did not complete" : "completed"} in ${timeElapsed} ms`);
579 // disconnect the observer and resolve the promise
580 observer.disconnect();