Merge branch '16115-sharing-links'. Closes #16115
[arvados-workbench2.git] / cypress / support / commands.js
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 // ***********************************************
6 // This example commands.js shows you how to
7 // create various custom commands and overwrite
8 // existing commands.
9 //
10 // For more comprehensive examples of custom
11 // commands please read more here:
12 // https://on.cypress.io/custom-commands
13 // ***********************************************
14 //
15 //
16 // -- This is a parent command --
17 // Cypress.Commands.add("login", (email, password) => { ... })
18 //
19 //
20 // -- This is a child command --
21 // Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... })
22 //
23 //
24 // -- This is a dual command --
25 // Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... })
26 //
27 //
28 // -- This will overwrite an existing command --
29 // Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... })
30
31 const controllerURL = Cypress.env('controller_url');
32 const systemToken = Cypress.env('system_token');
33 let createdResources = [];
34
35 // Clean up on a 'before' hook to allow post-mortem analysis on individual tests.
36 beforeEach(function () {
37     if (createdResources.length === 0) {
38         return;
39     }
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);
45     });
46     createdResources = [];
47 });
48
49 Cypress.Commands.add(
50     "doRequest", (method = 'GET', path = '', data = null, qs = null,
51         token = systemToken, auth = false, followRedirect = true, failOnStatusCode = true) => {
52     return cy.request({
53         method: method,
54         url: `${controllerURL.replace(/\/+$/, '')}/${path.replace(/^\/+/, '')}`,
55         body: data,
56         qs: auth ? qs : Object.assign({ api_token: token }, qs),
57         auth: auth ? { bearer: `${token}` } : undefined,
58         followRedirect: followRedirect,
59         failOnStatusCode: failOnStatusCode
60     });
61 });
62
63 Cypress.Commands.add(
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`,
69                 username: username,
70                 first_name: first_name,
71                 last_name: last_name,
72                 alternate_emails: []
73             }),
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
78         .then(function () {
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}"]]`
83             })
84             .its('body.items.0').as('aUser')
85             .then(function () {
86                 cy.doRequest('PUT', `/arvados/v1/users/${this.aUser.uuid}`, {
87                     user: {
88                         is_admin: is_admin,
89                         is_active: is_active
90                     }
91                 })
92                 .its('body').as('theUser')
93                 .then(function () {
94                     cy.doRequest('GET', '/arvados/v1/api_clients', null, {
95                         filters: `[["is_trusted", "=", false]]`,
96                         order: `["created_at desc"]`
97                     })
98                     .its('body.items').as('apiClients')
99                     .then(function () {
100                         if (this.apiClients.length > 0) {
101                             cy.doRequest('PUT', `/arvados/v1/api_clients/${this.apiClients[0].uuid}`, {
102                                 api_client: {
103                                     is_trusted: true
104                                 }
105                             })
106                             .its('body').as('updatedApiClient')
107                             .then(function() {
108                                 assert(this.updatedApiClient.is_trusted);
109                             })
110                         }
111                     })
112                     .then(function () {
113                         return { user: this.theUser, token: this.userToken };
114                     })
115                 })
116             })
117         })
118     }
119 )
120
121 Cypress.Commands.add(
122     "createLink", (token, data) => {
123         return cy.createResource(token, 'links', {
124             link: JSON.stringify(data)
125         })
126     }
127 )
128
129 Cypress.Commands.add(
130     "createGroup", (token, data) => {
131         return cy.createResource(token, 'groups', {
132             group: JSON.stringify(data),
133             ensure_unique_name: true
134         })
135     }
136 )
137
138 Cypress.Commands.add(
139     "trashGroup", (token, uuid) => {
140         return cy.deleteResource(token, 'groups', uuid);
141     }
142 )
143
144
145 Cypress.Commands.add(
146     "createWorkflow", (token, data) => {
147         return cy.createResource(token, 'workflows', {
148             workflow: JSON.stringify(data),
149             ensure_unique_name: true
150         })
151     }
152 )
153
154 Cypress.Commands.add(
155     "getCollection", (token, uuid) => {
156         return cy.getResource(token, 'collections', uuid)
157     }
158 )
159
160 Cypress.Commands.add(
161     "createCollection", (token, data) => {
162         return cy.createResource(token, 'collections', {
163             collection: JSON.stringify(data),
164             ensure_unique_name: true
165         })
166     }
167 )
168
169 Cypress.Commands.add(
170     "updateCollection", (token, uuid, data) => {
171         return cy.updateResource(token, 'collections', uuid, {
172             collection: JSON.stringify(data)
173         })
174     }
175 )
176
177 Cypress.Commands.add(
178     "getContainer", (token, uuid) => {
179         return cy.getResource(token, 'containers', uuid)
180     }
181 )
182
183 Cypress.Commands.add(
184     "updateContainer", (token, uuid, data) => {
185         return cy.updateResource(token, 'containers', uuid, {
186             container: JSON.stringify(data)
187         })
188     }
189 )
190
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
196         })
197     }
198 )
199
200 Cypress.Commands.add(
201     "updateContainerRequest", (token, uuid, data) => {
202         return cy.updateResource(token, 'container_requests', uuid, {
203             container_request: JSON.stringify(data)
204         })
205     }
206 )
207
208 Cypress.Commands.add(
209     "createLog", (token, data) => {
210         return cy.createResource(token, 'logs', {
211             log: JSON.stringify(data)
212         })
213     }
214 )
215
216 Cypress.Commands.add(
217     "logsForContainer", (token, uuid, logType, logTextArray = []) => {
218         let logs = [];
219         for (const logText of logTextArray) {
220             logs.push(cy.createLog(token, {
221                 object_uuid: uuid,
222                 event_type: logType,
223                 properties: {
224                     text: logText
225                 }
226             }).as('lastLogRecord'))
227         }
228         cy.getAll('@lastLogRecord').then(function () {
229             return logs;
230         })
231     }
232 )
233
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
239         })
240     }
241 )
242
243 Cypress.Commands.add(
244     "getResource", (token, suffix, uuid) => {
245         return cy.doRequest('GET', `/arvados/v1/${suffix}/${uuid}`, null, {}, token)
246             .its('body')
247             .then(function (resource) {
248                 return resource;
249             })
250     }
251 )
252
253 Cypress.Commands.add(
254     "createResource", (token, suffix, data) => {
255         return cy.doRequest('POST', '/arvados/v1/' + suffix, data, null, token, true)
256             .its('body')
257             .then(function (resource) {
258                 createdResources.push({suffix, uuid: resource.uuid});
259                 return resource;
260             })
261     }
262 )
263
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)
267             .its('body')
268             .then(function (resource) {
269                 return resource;
270             })
271     }
272 )
273
274 Cypress.Commands.add(
275     "updateResource", (token, suffix, uuid, data) => {
276         return cy.doRequest('PATCH', '/arvados/v1/' + suffix + '/' + uuid, data, null, token, true)
277             .its('body')
278             .then(function (resource) {
279                 return resource;
280             })
281     }
282 )
283
284 Cypress.Commands.add(
285     "loginAs", (user) => {
286         cy.clearCookies()
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');
292     }
293 )
294
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();
303         });
304
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);
309
310             if (isProject) {
311                 cy.get('span[data-text=true]').contains(newDescription);
312             } else {
313                 cy.get('input[name=description]').should('have.value', newDescription);
314             }
315
316             cy.get('[data-cy=form-cancel-btn]').click();
317         });
318     }
319 )
320
321 Cypress.Commands.add(
322     "doSearch", (searchTerm) => {
323         cy.get('[data-cy=searchbar-input-field]').type(`{selectall}${searchTerm}{enter}`);
324     }
325 )
326
327 Cypress.Commands.add(
328     "goToPath", (path) => {
329         return cy.window().its('appHistory').invoke('push', path);
330     }
331 )
332
333 Cypress.Commands.add('getAll', (...elements) => {
334     const promise = cy.wrap([], { log: false })
335
336     for (let element of elements) {
337         promise.then(arr => cy.get(element).then(got => cy.wrap([...arr, got])))
338     }
339
340     return promise
341 })
342
343 Cypress.Commands.add('shareWith', (srcUserToken, targetUserUUID, itemUUID, permission = 'can_write') => {
344     cy.createLink(srcUserToken, {
345         name: permission,
346         link_class: 'permission',
347         head_uuid: itemUUID,
348         tail_uuid: targetUserUUID
349     });
350 })
351
352 Cypress.Commands.add('addToFavorites', (userToken, userUUID, itemUUID) => {
353     cy.createLink(userToken, {
354         head_uuid: itemUUID,
355         link_class: 'star',
356         name: '',
357         owner_uuid: userUUID,
358         tail_uuid: userUUID,
359     });
360 })
361
362 Cypress.Commands.add('createProject', ({
363     owningUser,
364     targetUser,
365     projectName,
366     canWrite,
367     addToFavorites
368 }) => {
369     const writePermission = canWrite ? 'can_write' : 'can_read';
370
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);
377         }
378         if (addToFavorites) {
379             const user = targetUser ? targetUser : owningUser;
380             cy.addToFavorites(user.token, user.user.uuid, project.uuid);
381         }
382     });
383 });
384
385 Cypress.Commands.add(
386     'upload',
387     {
388         prevSubject: 'element',
389     },
390     (subject, file, fileName) => {
391         cy.window().then(window => {
392             const blob = b64toBlob(file, '', 512);
393             const testFile = new window.File([blob], fileName);
394
395             cy.wrap(subject).trigger('drop', {
396                 dataTransfer: { files: [testFile] },
397             });
398         })
399     }
400 )
401
402 function b64toBlob(b64Data, contentType = '', sliceSize = 512) {
403     const byteCharacters = atob(b64Data)
404     const byteArrays = []
405
406     for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
407         const slice = byteCharacters.slice(offset, offset + sliceSize);
408
409         const byteNumbers = new Array(slice.length);
410         for (let i = 0; i < slice.length; i++) {
411             byteNumbers[i] = slice.charCodeAt(i);
412         }
413
414         const byteArray = new Uint8Array(byteNumbers);
415
416         byteArrays.push(byteArray);
417     }
418
419     const blob = new Blob(byteArrays, { type: contentType });
420     return blob
421 }
422
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', () => {
426     cy.window().then({
427         // Don't timeout before waitForDom finishes
428         timeout: 10000
429     }, win => {
430       let timeElapsed = 0;
431
432       cy.log("Waiting for DOM mutations to complete");
433
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;
441
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;
451             }
452           });
453
454           // initialize the previousMutationCount
455           if (win.previousMutationCount == null) win.previousMutationCount = 0;
456         });
457
458         // watch the document body for the specified mutations
459         observer.observe(win.document.body, observerConfig);
460
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;
465
466           // make each iteration of the loop 100ms apart
467           setTimeout(() => {
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;
474               return callback();
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.');
479             } else {
480               // proceed to the next iteration
481               return callback();
482             }
483           }, 100);
484         }, function done() {
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`);
487
488           // disconnect the observer and resolve the promise
489           observer.disconnect();
490           resolve();
491         });
492       });
493     });
494   });