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 anything that was created. You can temporarily add
40 // 'return' to the top if you need the resources to hang around to
41 // debug a specific test.
42 afterEach(function () {
43 if (createdResources.length === 0) {
46 cy.log(`Cleaning ${createdResources.length} previously created resource(s).`);
47 createdResources.forEach(function({suffix, uuid}) {
48 // Don't fail when a resource isn't already there, some objects may have
49 // been removed, directly or indirectly, from the test that created them.
50 cy.deleteResource(systemToken, suffix, uuid, false);
52 createdResources = [];
56 "doRequest", (method = 'GET', path = '', data = null, qs = null,
57 token = systemToken, auth = false, followRedirect = true, failOnStatusCode = true) => {
60 url: `${controllerURL.replace(/\/+$/, '')}/${path.replace(/^\/+/, '')}`,
62 qs: auth ? qs : Object.assign({ api_token: token }, qs),
63 auth: auth ? { bearer: `${token}` } : undefined,
64 followRedirect: followRedirect,
65 failOnStatusCode: failOnStatusCode
70 "doWebDAVRequest", (method = 'GET', path = '', data = null, qs = null,
71 token = systemToken, auth = false, followRedirect = true, failOnStatusCode = true) => {
72 return cy.doRequest('GET', '/arvados/v1/config', null, null).then(({body: config}) => {
75 url: `${config.Services.WebDAVDownload.ExternalURL.replace(/\/+$/, '')}/${path.replace(/^\/+/, '')}`,
77 qs: auth ? qs : Object.assign({ api_token: token }, qs),
78 auth: auth ? { bearer: `${token}` } : undefined,
79 followRedirect: followRedirect,
80 failOnStatusCode: failOnStatusCode
86 "getUser", (username, first_name = '', last_name = '', is_admin = false, is_active = true) => {
87 // Create user if not already created
88 return cy.doRequest('POST', '/auth/controller/callback', {
89 auth_info: JSON.stringify({
90 email: `${username}@example.local`,
92 first_name: first_name,
96 return_to: ',https://example.local'
97 }, null, systemToken, true, false) // Don't follow redirects so we can catch the token
98 .its('headers.location').as('location')
99 // Get its token and set the account up as admin and/or active
101 this.userToken = this.location.split("=")[1]
102 assert.isString(this.userToken)
103 return cy.doRequest('GET', '/arvados/v1/users', null, {
104 filters: `[["username", "=", "${username}"]]`
106 .its('body.items.0').as('aUser')
108 cy.doRequest('PUT', `/arvados/v1/users/${this.aUser.uuid}`, {
114 .its('body').as('theUser')
116 cy.doRequest('GET', '/arvados/v1/api_clients', null, {
117 filters: `[["is_trusted", "=", false]]`,
118 order: `["created_at desc"]`
120 .its('body.items').as('apiClients')
122 if (this.apiClients.length > 0) {
123 cy.doRequest('PUT', `/arvados/v1/api_clients/${this.apiClients[0].uuid}`, {
128 .its('body').as('updatedApiClient')
130 assert(this.updatedApiClient.is_trusted);
135 return { user: this.theUser, token: this.userToken };
143 Cypress.Commands.add(
144 "createLink", (token, data) => {
145 return cy.createResource(token, 'links', {
146 link: JSON.stringify(data)
151 Cypress.Commands.add(
152 "createGroup", (token, data) => {
153 return cy.createResource(token, 'groups', {
154 group: JSON.stringify(data),
155 ensure_unique_name: true
160 Cypress.Commands.add(
161 "trashGroup", (token, uuid) => {
162 return cy.deleteResource(token, 'groups', uuid);
167 Cypress.Commands.add(
168 "createWorkflow", (token, data) => {
169 return cy.createResource(token, 'workflows', {
170 workflow: JSON.stringify(data),
171 ensure_unique_name: true
176 Cypress.Commands.add(
177 "createCollection", (token, data) => {
178 return cy.createResource(token, 'collections', {
179 collection: JSON.stringify(data),
180 ensure_unique_name: true
185 Cypress.Commands.add(
186 "getCollection", (token, uuid) => {
187 return cy.getResource(token, 'collections', uuid)
191 Cypress.Commands.add(
192 "updateCollection", (token, uuid, data) => {
193 return cy.updateResource(token, 'collections', uuid, {
194 collection: JSON.stringify(data)
199 Cypress.Commands.add(
200 "collectionReplaceFiles", (token, uuid, data) => {
201 return cy.updateResource(token, 'collections', uuid, {
203 preserve_version: true,
205 replace_files: JSON.stringify(data)
210 Cypress.Commands.add(
211 "getContainer", (token, uuid) => {
212 return cy.getResource(token, 'containers', uuid)
216 Cypress.Commands.add(
217 "updateContainer", (token, uuid, data) => {
218 return cy.updateResource(token, 'containers', uuid, {
219 container: JSON.stringify(data)
224 Cypress.Commands.add(
225 "getContainerRequest", (token, uuid) => {
226 return cy.getResource(token, 'container_requests', uuid)
230 Cypress.Commands.add(
231 'createContainerRequest', (token, data) => {
232 return cy.createResource(token, 'container_requests', {
233 container_request: JSON.stringify(data),
234 ensure_unique_name: true
239 Cypress.Commands.add(
240 "updateContainerRequest", (token, uuid, data) => {
241 return cy.updateResource(token, 'container_requests', uuid, {
242 container_request: JSON.stringify(data)
248 * Requires an admin token for log_uuid modification to succeed
250 Cypress.Commands.add(
251 "appendLog", (token, crUuid, fileName, lines = []) => (
252 cy.getContainerRequest(token, crUuid).then((containerRequest) => {
253 if (containerRequest.log_uuid) {
254 cy.listContainerRequestLogs(token, crUuid).then((logFiles) => {
255 const filePath = `${containerRequest.log_uuid}/${containerLogFolderPrefix}${containerRequest.container_uuid}/${fileName}`;
256 if (logFiles.find((file) => (file.name === fileName))) {
257 // File exists, fetch and append
258 return cy.doWebDAVRequest(
265 .then(({ body: contents }) => cy.doWebDAVRequest(
268 contents.split("\n").concat(lines).join("\n"),
273 // File not exists, put new file
284 // Create log collection
285 return cy.createCollection(token, {
286 name: `Test log collection ${Math.floor(Math.random() * 999999)}`,
287 owner_uuid: containerRequest.owner_uuid,
289 }).then((collection) => {
290 // Update CR log_uuid to fake log collection
291 cy.updateContainerRequest(token, containerRequest.uuid, {
292 log_uuid: collection.uuid,
294 // Create empty directory for container uuid
295 cy.collectionReplaceFiles(token, collection.uuid, {
296 [`/${containerLogFolderPrefix}${containerRequest.container_uuid}`]: "d41d8cd98f00b204e9800998ecf8427e+0"
298 // Put new log file with contents into fake log collection
301 `c=${collection.uuid}/${containerLogFolderPrefix}${containerRequest.container_uuid}/${fileName}`,
314 Cypress.Commands.add(
315 "listContainerRequestLogs", (token, crUuid) => (
316 cy.getContainerRequest(token, crUuid).then((containerRequest) => (
317 cy.doWebDAVRequest('PROPFIND', `c=${containerRequest.log_uuid}/${containerLogFolderPrefix}${containerRequest.container_uuid}`, null, null, token)
318 .then(({body: data}) => {
319 return extractFilesData(new DOMParser().parseFromString(data, "text/xml"));
325 Cypress.Commands.add(
326 "createVirtualMachine", (token, data) => {
327 return cy.createResource(token, 'virtual_machines', {
328 virtual_machine: JSON.stringify(data),
329 ensure_unique_name: true
334 Cypress.Commands.add(
335 "getResource", (token, suffix, uuid) => {
336 return cy.doRequest('GET', `/arvados/v1/${suffix}/${uuid}`, null, {}, token)
338 .then(function (resource) {
344 Cypress.Commands.add(
345 "createResource", (token, suffix, data) => {
346 return cy.doRequest('POST', '/arvados/v1/' + suffix, data, null, token, true)
348 .then(function (resource) {
349 createdResources.push({suffix, uuid: resource.uuid});
355 Cypress.Commands.add(
356 "deleteResource", (token, suffix, uuid, failOnStatusCode = true) => {
357 return cy.doRequest('DELETE', '/arvados/v1/' + suffix + '/' + uuid, null, null, token, false, true, failOnStatusCode)
359 .then(function (resource) {
365 Cypress.Commands.add(
366 "updateResource", (token, suffix, uuid, data) => {
367 return cy.doRequest('PATCH', '/arvados/v1/' + suffix + '/' + uuid, data, null, token, true)
369 .then(function (resource) {
375 Cypress.Commands.add(
376 "loginAs", (user) => {
378 cy.clearLocalStorage()
379 cy.visit(`/token/?api_token=${user.token}`);
380 cy.url({timeout: 10000}).should('contain', '/projects/');
381 cy.get('div#root').should('contain', 'Arvados Workbench (zzzzz)');
382 cy.get('div#root').should('not.contain', 'Your account is inactive');
386 Cypress.Commands.add(
387 "testEditProjectOrCollection", (container, oldName, newName, newDescription, isProject = true) => {
388 cy.get(container).contains(oldName).rightclick();
389 cy.get('[data-cy=context-menu]').contains(isProject ? 'Edit project' : 'Edit collection').click();
390 cy.get('[data-cy=form-dialog]').within(() => {
391 cy.get('input[name=name]').clear().type(newName);
392 cy.get(isProject ? 'div[contenteditable=true]' : 'input[name=description]').clear().type(newDescription);
393 cy.get('[data-cy=form-submit-btn]').click();
396 cy.get(container).contains(newName).rightclick();
397 cy.get('[data-cy=context-menu]').contains(isProject ? 'Edit project' : 'Edit collection').click();
398 cy.get('[data-cy=form-dialog]').within(() => {
399 cy.get('input[name=name]').should('have.value', newName);
402 cy.get('span[data-text=true]').contains(newDescription);
404 cy.get('input[name=description]').should('have.value', newDescription);
407 cy.get('[data-cy=form-cancel-btn]').click();
412 Cypress.Commands.add(
413 "doSearch", (searchTerm) => {
414 cy.get('[data-cy=searchbar-input-field]').type(`{selectall}${searchTerm}{enter}`);
418 Cypress.Commands.add(
419 "goToPath", (path) => {
420 return cy.window().its('appHistory').invoke('push', path);
424 Cypress.Commands.add('getAll', (...elements) => {
425 const promise = cy.wrap([], { log: false })
427 for (let element of elements) {
428 promise.then(arr => cy.get(element).then(got => cy.wrap([...arr, got])))
434 Cypress.Commands.add('shareWith', (srcUserToken, targetUserUUID, itemUUID, permission = 'can_write') => {
435 cy.createLink(srcUserToken, {
437 link_class: 'permission',
439 tail_uuid: targetUserUUID
443 Cypress.Commands.add('addToFavorites', (userToken, userUUID, itemUUID) => {
444 cy.createLink(userToken, {
448 owner_uuid: userUUID,
453 Cypress.Commands.add('createProject', ({
460 const writePermission = canWrite ? 'can_write' : 'can_read';
462 cy.createGroup(owningUser.token, {
463 name: `${projectName} ${Math.floor(Math.random() * 999999)}`,
464 group_class: 'project',
465 }).as(`${projectName}`).then((project) => {
466 if (targetUser && targetUser !== owningUser) {
467 cy.shareWith(owningUser.token, targetUser.user.uuid, project.uuid, writePermission);
469 if (addToFavorites) {
470 const user = targetUser ? targetUser : owningUser;
471 cy.addToFavorites(user.token, user.user.uuid, project.uuid);
476 Cypress.Commands.add(
479 prevSubject: 'element',
481 (subject, file, fileName, binaryMode = true) => {
482 cy.window().then(window => {
483 const blob = binaryMode
484 ? b64toBlob(file, '', 512)
485 : new Blob([file], {type: 'text/plain'});
486 const testFile = new window.File([blob], fileName);
488 cy.wrap(subject).trigger('drop', {
489 dataTransfer: { files: [testFile] },
495 function b64toBlob(b64Data, contentType = '', sliceSize = 512) {
496 const byteCharacters = atob(b64Data)
497 const byteArrays = []
499 for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
500 const slice = byteCharacters.slice(offset, offset + sliceSize);
502 const byteNumbers = new Array(slice.length);
503 for (let i = 0; i < slice.length; i++) {
504 byteNumbers[i] = slice.charCodeAt(i);
507 const byteArray = new Uint8Array(byteNumbers);
509 byteArrays.push(byteArray);
512 const blob = new Blob(byteArrays, { type: contentType });
516 // From https://github.com/cypress-io/cypress/issues/7306#issuecomment-1076451070=
517 // This command requires the async package (https://www.npmjs.com/package/async)
518 Cypress.Commands.add('waitForDom', () => {
520 // Don't timeout before waitForDom finishes
525 cy.log("Waiting for DOM mutations to complete");
527 return new Cypress.Promise((resolve) => {
528 // set the required variables
529 let async = require("async");
530 let observerConfig = { attributes: true, childList: true, subtree: true };
531 let items = Array.apply(null, { length: 50 }).map(Number.call, Number);
532 win.mutationCount = 0;
533 win.previousMutationCount = null;
535 // create an observer instance
536 let observer = new win.MutationObserver((mutations) => {
537 mutations.forEach((mutation) => {
538 // Only record "attributes" type mutations that are not a "class" mutation.
539 // If the mutation is not an "attributes" type, then we always record it.
540 if (mutation.type === 'attributes' && mutation.attributeName !== 'class') {
541 win.mutationCount += 1;
542 } else if (mutation.type !== 'attributes') {
543 win.mutationCount += 1;
547 // initialize the previousMutationCount
548 if (win.previousMutationCount == null) win.previousMutationCount = 0;
551 // watch the document body for the specified mutations
552 observer.observe(win.document.body, observerConfig);
554 // check the DOM for mutations up to 50 times for a maximum time of 5 seconds
555 async.eachSeries(items, function iteratee(item, callback) {
556 // keep track of the elapsed time so we can log it at the end of the command
557 timeElapsed = timeElapsed + 100;
559 // make each iteration of the loop 100ms apart
561 if (win.mutationCount === win.previousMutationCount) {
562 // pass an argument to the async callback to exit the loop
563 return callback('Resolved - DOM changes complete.');
564 } else if (win.previousMutationCount != null) {
565 // only set the previous count if the observer has checked the DOM at least once
566 win.previousMutationCount = win.mutationCount;
568 } else if (win.mutationCount === 0 && win.previousMutationCount == null && item === 4) {
569 // this is an early exit in case nothing is changing in the DOM. That way we only
570 // wait 500ms instead of the full 5 seconds when no DOM changes are occurring.
571 return callback('Resolved - Exiting early since no DOM changes were detected.');
573 // proceed to the next iteration
578 // Log the total wait time so users can see it
579 cy.log(`DOM mutations ${timeElapsed >= 5000 ? "did not complete" : "completed"} in ${timeElapsed} ms`);
581 // disconnect the observer and resolve the promise
582 observer.disconnect();