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