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 const controllerURL = Cypress.env('controller_url');
32 const systemToken = Cypress.env('system_token');
33 let createdResources = [];
35 // Clean up on a 'before' hook to allow post-mortem analysis on individual tests.
36 beforeEach(function () {
37 if (createdResources.length === 0) {
40 cy.log(`Cleaning ${createdResources.length} previously created resource(s)`);
41 createdResources.forEach(function({suffix, uuid}) {
42 // Don't fail when a resource isn't already there, some objects may have
43 // been removed, directly or indirectly, from the test that created them.
44 cy.deleteResource(systemToken, suffix, uuid, false);
46 createdResources = [];
50 "doRequest", (method = 'GET', path = '', data = null, qs = null,
51 token = systemToken, auth = false, followRedirect = true, failOnStatusCode = true) => {
54 url: `${controllerURL.replace(/\/+$/, '')}/${path.replace(/^\/+/, '')}`,
56 qs: auth ? qs : Object.assign({ api_token: token }, qs),
57 auth: auth ? { bearer: `${token}` } : undefined,
58 followRedirect: followRedirect,
59 failOnStatusCode: failOnStatusCode
64 "getUser", (username, first_name = '', last_name = '', is_admin = false, is_active = true) => {
65 // Create user if not already created
66 return cy.doRequest('POST', '/auth/controller/callback', {
67 auth_info: JSON.stringify({
68 email: `${username}@example.local`,
70 first_name: first_name,
74 return_to: ',https://example.local'
75 }, null, systemToken, true, false) // Don't follow redirects so we can catch the token
76 .its('headers.location').as('location')
77 // Get its token and set the account up as admin and/or active
79 this.userToken = this.location.split("=")[1]
80 assert.isString(this.userToken)
81 return cy.doRequest('GET', '/arvados/v1/users', null, {
82 filters: `[["username", "=", "${username}"]]`
84 .its('body.items.0').as('aUser')
86 cy.doRequest('PUT', `/arvados/v1/users/${this.aUser.uuid}`, {
92 .its('body').as('theUser')
94 cy.doRequest('GET', '/arvados/v1/api_clients', null, {
95 filters: `[["is_trusted", "=", false]]`,
96 order: `["created_at desc"]`
98 .its('body.items').as('apiClients')
100 if (this.apiClients.length > 0) {
101 cy.doRequest('PUT', `/arvados/v1/api_clients/${this.apiClients[0].uuid}`, {
106 .its('body').as('updatedApiClient')
108 assert(this.updatedApiClient.is_trusted);
113 return { user: this.theUser, token: this.userToken };
121 Cypress.Commands.add(
122 "createLink", (token, data) => {
123 return cy.createResource(token, 'links', {
124 link: JSON.stringify(data)
129 Cypress.Commands.add(
130 "createGroup", (token, data) => {
131 return cy.createResource(token, 'groups', {
132 group: JSON.stringify(data),
133 ensure_unique_name: true
138 Cypress.Commands.add(
139 "trashGroup", (token, uuid) => {
140 return cy.deleteResource(token, 'groups', uuid);
145 Cypress.Commands.add(
146 "createWorkflow", (token, data) => {
147 return cy.createResource(token, 'workflows', {
148 workflow: JSON.stringify(data),
149 ensure_unique_name: true
154 Cypress.Commands.add(
155 "getCollection", (token, uuid) => {
156 return cy.getResource(token, 'collections', uuid)
160 Cypress.Commands.add(
161 "createCollection", (token, data) => {
162 return cy.createResource(token, 'collections', {
163 collection: JSON.stringify(data),
164 ensure_unique_name: true
169 Cypress.Commands.add(
170 "updateCollection", (token, uuid, data) => {
171 return cy.updateResource(token, 'collections', uuid, {
172 collection: JSON.stringify(data)
177 Cypress.Commands.add(
178 "getContainer", (token, uuid) => {
179 return cy.getResource(token, 'containers', uuid)
183 Cypress.Commands.add(
184 "updateContainer", (token, uuid, data) => {
185 return cy.updateResource(token, 'containers', uuid, {
186 container: JSON.stringify(data)
191 Cypress.Commands.add(
192 'createContainerRequest', (token, data) => {
193 return cy.createResource(token, 'container_requests', {
194 container_request: JSON.stringify(data),
195 ensure_unique_name: true
200 Cypress.Commands.add(
201 "updateContainerRequest", (token, uuid, data) => {
202 return cy.updateResource(token, 'container_requests', uuid, {
203 container_request: JSON.stringify(data)
208 Cypress.Commands.add(
209 "createLog", (token, data) => {
210 return cy.createResource(token, 'logs', {
211 log: JSON.stringify(data)
216 Cypress.Commands.add(
217 "logsForContainer", (token, uuid, logType, logTextArray = []) => {
219 for (const logText of logTextArray) {
220 logs.push(cy.createLog(token, {
226 }).as('lastLogRecord'))
228 cy.getAll('@lastLogRecord').then(function () {
234 Cypress.Commands.add(
235 "createVirtualMachine", (token, data) => {
236 return cy.createResource(token, 'virtual_machines', {
237 virtual_machine: JSON.stringify(data),
238 ensure_unique_name: true
243 Cypress.Commands.add(
244 "getResource", (token, suffix, uuid) => {
245 return cy.doRequest('GET', `/arvados/v1/${suffix}/${uuid}`, null, {}, token)
247 .then(function (resource) {
253 Cypress.Commands.add(
254 "createResource", (token, suffix, data) => {
255 return cy.doRequest('POST', '/arvados/v1/' + suffix, data, null, token, true)
257 .then(function (resource) {
258 createdResources.push({suffix, uuid: resource.uuid});
264 Cypress.Commands.add(
265 "deleteResource", (token, suffix, uuid, failOnStatusCode = true) => {
266 return cy.doRequest('DELETE', '/arvados/v1/' + suffix + '/' + uuid, null, null, token, false, true, failOnStatusCode)
268 .then(function (resource) {
274 Cypress.Commands.add(
275 "updateResource", (token, suffix, uuid, data) => {
276 return cy.doRequest('PATCH', '/arvados/v1/' + suffix + '/' + uuid, data, null, token, true)
278 .then(function (resource) {
284 Cypress.Commands.add(
285 "loginAs", (user) => {
287 cy.clearLocalStorage()
288 cy.visit(`/token/?api_token=${user.token}`);
289 cy.url({timeout: 10000}).should('contain', '/projects/');
290 cy.get('div#root').should('contain', 'Arvados Workbench (zzzzz)');
291 cy.get('div#root').should('not.contain', 'Your account is inactive');
295 Cypress.Commands.add(
296 "testEditProjectOrCollection", (container, oldName, newName, newDescription, isProject = true) => {
297 cy.get(container).contains(oldName).rightclick();
298 cy.get('[data-cy=context-menu]').contains(isProject ? 'Edit project' : 'Edit collection').click();
299 cy.get('[data-cy=form-dialog]').within(() => {
300 cy.get('input[name=name]').clear().type(newName);
301 cy.get(isProject ? 'div[contenteditable=true]' : 'input[name=description]').clear().type(newDescription);
302 cy.get('[data-cy=form-submit-btn]').click();
305 cy.get(container).contains(newName).rightclick();
306 cy.get('[data-cy=context-menu]').contains(isProject ? 'Edit project' : 'Edit collection').click();
307 cy.get('[data-cy=form-dialog]').within(() => {
308 cy.get('input[name=name]').should('have.value', newName);
311 cy.get('span[data-text=true]').contains(newDescription);
313 cy.get('input[name=description]').should('have.value', newDescription);
316 cy.get('[data-cy=form-cancel-btn]').click();
321 Cypress.Commands.add(
322 "doSearch", (searchTerm) => {
323 cy.get('[data-cy=searchbar-input-field]').type(`{selectall}${searchTerm}{enter}`);
327 Cypress.Commands.add(
328 "goToPath", (path) => {
329 return cy.window().its('appHistory').invoke('push', path);
333 Cypress.Commands.add('getAll', (...elements) => {
334 const promise = cy.wrap([], { log: false })
336 for (let element of elements) {
337 promise.then(arr => cy.get(element).then(got => cy.wrap([...arr, got])))
343 Cypress.Commands.add('shareWith', (srcUserToken, targetUserUUID, itemUUID, permission = 'can_write') => {
344 cy.createLink(srcUserToken, {
346 link_class: 'permission',
348 tail_uuid: targetUserUUID
352 Cypress.Commands.add('addToFavorites', (userToken, userUUID, itemUUID) => {
353 cy.createLink(userToken, {
357 owner_uuid: userUUID,
362 Cypress.Commands.add('createProject', ({
369 const writePermission = canWrite ? 'can_write' : 'can_read';
371 cy.createGroup(owningUser.token, {
372 name: `${projectName} ${Math.floor(Math.random() * 999999)}`,
373 group_class: 'project',
374 }).as(`${projectName}`).then((project) => {
375 if (targetUser && targetUser !== owningUser) {
376 cy.shareWith(owningUser.token, targetUser.user.uuid, project.uuid, writePermission);
378 if (addToFavorites) {
379 const user = targetUser ? targetUser : owningUser;
380 cy.addToFavorites(user.token, user.user.uuid, project.uuid);
385 Cypress.Commands.add(
388 prevSubject: 'element',
390 (subject, file, fileName) => {
391 cy.window().then(window => {
392 const blob = b64toBlob(file, '', 512);
393 const testFile = new window.File([blob], fileName);
395 cy.wrap(subject).trigger('drop', {
396 dataTransfer: { files: [testFile] },
402 function b64toBlob(b64Data, contentType = '', sliceSize = 512) {
403 const byteCharacters = atob(b64Data)
404 const byteArrays = []
406 for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
407 const slice = byteCharacters.slice(offset, offset + sliceSize);
409 const byteNumbers = new Array(slice.length);
410 for (let i = 0; i < slice.length; i++) {
411 byteNumbers[i] = slice.charCodeAt(i);
414 const byteArray = new Uint8Array(byteNumbers);
416 byteArrays.push(byteArray);
419 const blob = new Blob(byteArrays, { type: contentType });
423 // From https://github.com/cypress-io/cypress/issues/7306#issuecomment-1076451070=
424 // This command requires the async package (https://www.npmjs.com/package/async)
425 Cypress.Commands.add('waitForDom', () => {
427 // Don't timeout before waitForDom finishes
432 cy.log("Waiting for DOM mutations to complete");
434 return new Cypress.Promise((resolve) => {
435 // set the required variables
436 let async = require("async");
437 let observerConfig = { attributes: true, childList: true, subtree: true };
438 let items = Array.apply(null, { length: 50 }).map(Number.call, Number);
439 win.mutationCount = 0;
440 win.previousMutationCount = null;
442 // create an observer instance
443 let observer = new win.MutationObserver((mutations) => {
444 mutations.forEach((mutation) => {
445 // Only record "attributes" type mutations that are not a "class" mutation.
446 // If the mutation is not an "attributes" type, then we always record it.
447 if (mutation.type === 'attributes' && mutation.attributeName !== 'class') {
448 win.mutationCount += 1;
449 } else if (mutation.type !== 'attributes') {
450 win.mutationCount += 1;
454 // initialize the previousMutationCount
455 if (win.previousMutationCount == null) win.previousMutationCount = 0;
458 // watch the document body for the specified mutations
459 observer.observe(win.document.body, observerConfig);
461 // check the DOM for mutations up to 50 times for a maximum time of 5 seconds
462 async.eachSeries(items, function iteratee(item, callback) {
463 // keep track of the elapsed time so we can log it at the end of the command
464 timeElapsed = timeElapsed + 100;
466 // make each iteration of the loop 100ms apart
468 if (win.mutationCount === win.previousMutationCount) {
469 // pass an argument to the async callback to exit the loop
470 return callback('Resolved - DOM changes complete.');
471 } else if (win.previousMutationCount != null) {
472 // only set the previous count if the observer has checked the DOM at least once
473 win.previousMutationCount = win.mutationCount;
475 } else if (win.mutationCount === 0 && win.previousMutationCount == null && item === 4) {
476 // this is an early exit in case nothing is changing in the DOM. That way we only
477 // wait 500ms instead of the full 5 seconds when no DOM changes are occurring.
478 return callback('Resolved - Exiting early since no DOM changes were detected.');
480 // proceed to the next iteration
485 // Log the total wait time so users can see it
486 cy.log(`DOM mutations ${timeElapsed >= 5000 ? "did not complete" : "completed"} in ${timeElapsed} ms`);
488 // disconnect the observer and resolve the promise
489 observer.disconnect();