19049: Cypress don't timeout before waitfordom finishes
[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')
85                     .as('aUser')
86                     .then(function () {
87                         cy.doRequest('PUT', `/arvados/v1/users/${this.aUser.uuid}`, {
88                             user: {
89                                 is_admin: is_admin,
90                                 is_active: is_active
91                             }
92                         })
93                             .its('body')
94                             .as('theUser')
95                             .then(function () {
96                                 return { user: this.theUser, token: this.userToken };
97                             })
98                     })
99             })
100     }
101 )
102
103 Cypress.Commands.add(
104     "createLink", (token, data) => {
105         return cy.createResource(token, 'links', {
106             link: JSON.stringify(data)
107         })
108     }
109 )
110
111 Cypress.Commands.add(
112     "createGroup", (token, data) => {
113         return cy.createResource(token, 'groups', {
114             group: JSON.stringify(data),
115             ensure_unique_name: true
116         })
117     }
118 )
119
120 Cypress.Commands.add(
121     "trashGroup", (token, uuid) => {
122         return cy.deleteResource(token, 'groups', uuid);
123     }
124 )
125
126
127 Cypress.Commands.add(
128     "createWorkflow", (token, data) => {
129         return cy.createResource(token, 'workflows', {
130             workflow: JSON.stringify(data),
131             ensure_unique_name: true
132         })
133     }
134 )
135
136 Cypress.Commands.add(
137     "getCollection", (token, uuid) => {
138         return cy.getResource(token, 'collections', uuid)
139     }
140 )
141
142 Cypress.Commands.add(
143     "createCollection", (token, data) => {
144         return cy.createResource(token, 'collections', {
145             collection: JSON.stringify(data),
146             ensure_unique_name: true
147         })
148     }
149 )
150
151 Cypress.Commands.add(
152     "updateCollection", (token, uuid, data) => {
153         return cy.updateResource(token, 'collections', uuid, {
154             collection: JSON.stringify(data)
155         })
156     }
157 )
158
159 Cypress.Commands.add(
160     "getContainer", (token, uuid) => {
161         return cy.getResource(token, 'containers', uuid)
162     }
163 )
164
165 Cypress.Commands.add(
166     "updateContainer", (token, uuid, data) => {
167         return cy.updateResource(token, 'containers', uuid, {
168             container: JSON.stringify(data)
169         })
170     }
171 )
172
173 Cypress.Commands.add(
174     'createContainerRequest', (token, data) => {
175         return cy.createResource(token, 'container_requests', {
176             container_request: JSON.stringify(data),
177             ensure_unique_name: true
178         })
179     }
180 )
181
182 Cypress.Commands.add(
183     "updateContainerRequest", (token, uuid, data) => {
184         return cy.updateResource(token, 'container_requests', uuid, {
185             container_request: JSON.stringify(data)
186         })
187     }
188 )
189
190 Cypress.Commands.add(
191     "createLog", (token, data) => {
192         return cy.createResource(token, 'logs', {
193             log: JSON.stringify(data)
194         })
195     }
196 )
197
198 Cypress.Commands.add(
199     "logsForContainer", (token, uuid, logType, logTextArray = []) => {
200         let logs = [];
201         for (const logText of logTextArray) {
202             logs.push(cy.createLog(token, {
203                 object_uuid: uuid,
204                 event_type: logType,
205                 properties: {
206                     text: logText
207                 }
208             }).as('lastLogRecord'))
209         }
210         cy.getAll('@lastLogRecord').then(function () {
211             return logs;
212         })
213     }
214 )
215
216 Cypress.Commands.add(
217     "createVirtualMachine", (token, data) => {
218         return cy.createResource(token, 'virtual_machines', {
219             virtual_machine: JSON.stringify(data),
220             ensure_unique_name: true
221         })
222     }
223 )
224
225 Cypress.Commands.add(
226     "getResource", (token, suffix, uuid) => {
227         return cy.doRequest('GET', `/arvados/v1/${suffix}/${uuid}`, null, {}, token)
228             .its('body')
229             .then(function (resource) {
230                 return resource;
231             })
232     }
233 )
234
235 Cypress.Commands.add(
236     "createResource", (token, suffix, data) => {
237         return cy.doRequest('POST', '/arvados/v1/' + suffix, data, null, token, true)
238             .its('body')
239             .then(function (resource) {
240                 createdResources.push({suffix, uuid: resource.uuid});
241                 return resource;
242             })
243     }
244 )
245
246 Cypress.Commands.add(
247     "deleteResource", (token, suffix, uuid, failOnStatusCode = true) => {
248         return cy.doRequest('DELETE', '/arvados/v1/' + suffix + '/' + uuid, null, null, token, false, true, failOnStatusCode)
249             .its('body')
250             .then(function (resource) {
251                 return resource;
252             })
253     }
254 )
255
256 Cypress.Commands.add(
257     "updateResource", (token, suffix, uuid, data) => {
258         return cy.doRequest('PATCH', '/arvados/v1/' + suffix + '/' + uuid, data, null, token, true)
259             .its('body')
260             .then(function (resource) {
261                 return resource;
262             })
263     }
264 )
265
266 Cypress.Commands.add(
267     "loginAs", (user) => {
268         cy.clearCookies()
269         cy.clearLocalStorage()
270         cy.visit(`/token/?api_token=${user.token}`);
271         cy.url({timeout: 10000}).should('contain', '/projects/');
272         cy.get('div#root').should('contain', 'Arvados Workbench (zzzzz)');
273         cy.get('div#root').should('not.contain', 'Your account is inactive');
274     }
275 )
276
277 Cypress.Commands.add(
278     "testEditProjectOrCollection", (container, oldName, newName, newDescription, isProject = true) => {
279         cy.get(container).contains(oldName).rightclick();
280         cy.get('[data-cy=context-menu]').contains(isProject ? 'Edit project' : 'Edit collection').click();
281         cy.get('[data-cy=form-dialog]').within(() => {
282             cy.get('input[name=name]').clear().type(newName);
283             cy.get(isProject ? 'div[contenteditable=true]' : 'input[name=description]').clear().type(newDescription);
284             cy.get('[data-cy=form-submit-btn]').click();
285         });
286
287         cy.get(container).contains(newName).rightclick();
288         cy.get('[data-cy=context-menu]').contains(isProject ? 'Edit project' : 'Edit collection').click();
289         cy.get('[data-cy=form-dialog]').within(() => {
290             cy.get('input[name=name]').should('have.value', newName);
291
292             if (isProject) {
293                 cy.get('span[data-text=true]').contains(newDescription);
294             } else {
295                 cy.get('input[name=description]').should('have.value', newDescription);
296             }
297
298             cy.get('[data-cy=form-cancel-btn]').click();
299         });
300     }
301 )
302
303 Cypress.Commands.add(
304     "doSearch", (searchTerm) => {
305         cy.get('[data-cy=searchbar-input-field]').type(`{selectall}${searchTerm}{enter}`);
306     }
307 )
308
309 Cypress.Commands.add(
310     "goToPath", (path) => {
311         return cy.window().its('appHistory').invoke('push', path);
312     }
313 )
314
315 Cypress.Commands.add('getAll', (...elements) => {
316     const promise = cy.wrap([], { log: false })
317
318     for (let element of elements) {
319         promise.then(arr => cy.get(element).then(got => cy.wrap([...arr, got])))
320     }
321
322     return promise
323 })
324
325 Cypress.Commands.add('shareWith', (srcUserToken, targetUserUUID, itemUUID, permission = 'can_write') => {
326     cy.createLink(srcUserToken, {
327         name: permission,
328         link_class: 'permission',
329         head_uuid: itemUUID,
330         tail_uuid: targetUserUUID
331     });
332 })
333
334 Cypress.Commands.add('addToFavorites', (userToken, userUUID, itemUUID) => {
335     cy.createLink(userToken, {
336         head_uuid: itemUUID,
337         link_class: 'star',
338         name: '',
339         owner_uuid: userUUID,
340         tail_uuid: userUUID,
341     });
342 })
343
344 Cypress.Commands.add('createProject', ({
345     owningUser,
346     targetUser,
347     projectName,
348     canWrite,
349     addToFavorites
350 }) => {
351     const writePermission = canWrite ? 'can_write' : 'can_read';
352
353     cy.createGroup(owningUser.token, {
354         name: `${projectName} ${Math.floor(Math.random() * 999999)}`,
355         group_class: 'project',
356     }).as(`${projectName}`).then((project) => {
357         if (targetUser && targetUser !== owningUser) {
358             cy.shareWith(owningUser.token, targetUser.user.uuid, project.uuid, writePermission);
359         }
360         if (addToFavorites) {
361             const user = targetUser ? targetUser : owningUser;
362             cy.addToFavorites(user.token, user.user.uuid, project.uuid);
363         }
364     });
365 });
366
367 Cypress.Commands.add(
368     'upload',
369     {
370         prevSubject: 'element',
371     },
372     (subject, file, fileName) => {
373         cy.window().then(window => {
374             const blob = b64toBlob(file, '', 512);
375             const testFile = new window.File([blob], fileName);
376
377             cy.wrap(subject).trigger('drop', {
378                 dataTransfer: { files: [testFile] },
379             });
380         })
381     }
382 )
383
384 function b64toBlob(b64Data, contentType = '', sliceSize = 512) {
385     const byteCharacters = atob(b64Data)
386     const byteArrays = []
387
388     for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
389         const slice = byteCharacters.slice(offset, offset + sliceSize);
390
391         const byteNumbers = new Array(slice.length);
392         for (let i = 0; i < slice.length; i++) {
393             byteNumbers[i] = slice.charCodeAt(i);
394         }
395
396         const byteArray = new Uint8Array(byteNumbers);
397
398         byteArrays.push(byteArray);
399     }
400
401     const blob = new Blob(byteArrays, { type: contentType });
402     return blob
403 }
404
405 // From https://github.com/cypress-io/cypress/issues/7306#issuecomment-1076451070=
406 // This command requires the async package (https://www.npmjs.com/package/async)
407 Cypress.Commands.add('waitForDom', () => {
408     cy.window().then({
409         // Don't timeout before waitForDom finishes
410         timeout: 10000
411     }, win => {
412       let timeElapsed = 0;
413
414       cy.log("Waiting for DOM mutations to complete");
415
416       return new Cypress.Promise((resolve) => {
417         // set the required variables
418         let async = require("async");
419         let observerConfig = { attributes: true, childList: true, subtree: true };
420         let items = Array.apply(null, { length: 50 }).map(Number.call, Number);
421         win.mutationCount = 0;
422         win.previousMutationCount = null;
423
424         // create an observer instance
425         let observer = new win.MutationObserver((mutations) => {
426           mutations.forEach((mutation) => {
427             // Only record "attributes" type mutations that are not a "class" mutation.
428             // If the mutation is not an "attributes" type, then we always record it.
429             if (mutation.type === 'attributes' && mutation.attributeName !== 'class') {
430               win.mutationCount += 1;
431             } else if (mutation.type !== 'attributes') {
432               win.mutationCount += 1;
433             }
434           });
435
436           // initialize the previousMutationCount
437           if (win.previousMutationCount == null) win.previousMutationCount = 0;
438         });
439
440         // watch the document body for the specified mutations
441         observer.observe(win.document.body, observerConfig);
442
443         // check the DOM for mutations up to 50 times for a maximum time of 5 seconds
444         async.eachSeries(items, function iteratee(item, callback) {
445           // keep track of the elapsed time so we can log it at the end of the command
446           timeElapsed = timeElapsed + 100;
447
448           // make each iteration of the loop 100ms apart
449           setTimeout(() => {
450             if (win.mutationCount === win.previousMutationCount) {
451               // pass an argument to the async callback to exit the loop
452               return callback('Resolved - DOM changes complete.');
453             } else if (win.previousMutationCount != null) {
454               // only set the previous count if the observer has checked the DOM at least once
455               win.previousMutationCount = win.mutationCount;
456               return callback();
457             } else if (win.mutationCount === 0 && win.previousMutationCount == null && item === 4) {
458               // this is an early exit in case nothing is changing in the DOM. That way we only
459               // wait 500ms instead of the full 5 seconds when no DOM changes are occurring.
460               return callback('Resolved - Exiting early since no DOM changes were detected.');
461             } else {
462               // proceed to the next iteration
463               return callback();
464             }
465           }, 100);
466         }, function done() {
467           // Log the total wait time so users can see it
468           cy.log(`DOM mutations ${timeElapsed >= 5000 ? "did not complete" : "completed"} in ${timeElapsed} ms`);
469
470           // disconnect the observer and resolve the promise
471           observer.disconnect();
472           resolve();
473         });
474       });
475     });
476   });