20219: Switch log panel requests to use live log endpoint, adjust tests to match
[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 import { extractFilesData } from "services/collection-service/collection-service-files-response";
32
33 const controllerURL = Cypress.env('controller_url');
34 const systemToken = Cypress.env('system_token');
35 let createdResources = [];
36
37 const containerLogFolderPrefix = 'log for container ';
38
39 // Clean up on a 'before' hook to allow post-mortem analysis on individual tests.
40 beforeEach(function () {
41     if (createdResources.length === 0) {
42         return;
43     }
44     cy.log(`Cleaning ${createdResources.length} previously created resource(s)`);
45     createdResources.forEach(function({suffix, uuid}) {
46         // Don't fail when a resource isn't already there, some objects may have
47         // been removed, directly or indirectly, from the test that created them.
48         cy.deleteResource(systemToken, suffix, uuid, false);
49     });
50     createdResources = [];
51 });
52
53 Cypress.Commands.add(
54     "doRequest", (method = 'GET', path = '', data = null, qs = null,
55         token = systemToken, auth = false, followRedirect = true, failOnStatusCode = true) => {
56     return cy.request({
57         method: method,
58         url: `${controllerURL.replace(/\/+$/, '')}/${path.replace(/^\/+/, '')}`,
59         body: data,
60         qs: auth ? qs : Object.assign({ api_token: token }, qs),
61         auth: auth ? { bearer: `${token}` } : undefined,
62         followRedirect: followRedirect,
63         failOnStatusCode: failOnStatusCode
64     });
65 });
66
67 Cypress.Commands.add(
68     "doKeepRequest", (method = 'GET', path = '', data = null, qs = null,
69         token = systemToken, auth = false, followRedirect = true, failOnStatusCode = true) => {
70     return cy.doRequest('GET', '/arvados/v1/config', null, null).then(({body: config}) => {
71         return cy.request({
72             method: method,
73             url: `${config.Services.WebDAVDownload.ExternalURL.replace(/\/+$/, '')}/${path.replace(/^\/+/, '')}`,
74             body: data,
75             qs: auth ? qs : Object.assign({ api_token: token }, qs),
76             auth: auth ? { bearer: `${token}` } : undefined,
77             followRedirect: followRedirect,
78             failOnStatusCode: failOnStatusCode
79         });
80     });
81 });
82
83 Cypress.Commands.add(
84     "getUser", (username, first_name = '', last_name = '', is_admin = false, is_active = true) => {
85         // Create user if not already created
86         return cy.doRequest('POST', '/auth/controller/callback', {
87             auth_info: JSON.stringify({
88                 email: `${username}@example.local`,
89                 username: username,
90                 first_name: first_name,
91                 last_name: last_name,
92                 alternate_emails: []
93             }),
94             return_to: ',https://example.local'
95         }, null, systemToken, true, false) // Don't follow redirects so we can catch the token
96         .its('headers.location').as('location')
97         // Get its token and set the account up as admin and/or active
98         .then(function () {
99             this.userToken = this.location.split("=")[1]
100             assert.isString(this.userToken)
101             return cy.doRequest('GET', '/arvados/v1/users', null, {
102                 filters: `[["username", "=", "${username}"]]`
103             })
104             .its('body.items.0').as('aUser')
105             .then(function () {
106                 cy.doRequest('PUT', `/arvados/v1/users/${this.aUser.uuid}`, {
107                     user: {
108                         is_admin: is_admin,
109                         is_active: is_active
110                     }
111                 })
112                 .its('body').as('theUser')
113                 .then(function () {
114                     cy.doRequest('GET', '/arvados/v1/api_clients', null, {
115                         filters: `[["is_trusted", "=", false]]`,
116                         order: `["created_at desc"]`
117                     })
118                     .its('body.items').as('apiClients')
119                     .then(function () {
120                         if (this.apiClients.length > 0) {
121                             cy.doRequest('PUT', `/arvados/v1/api_clients/${this.apiClients[0].uuid}`, {
122                                 api_client: {
123                                     is_trusted: true
124                                 }
125                             })
126                             .its('body').as('updatedApiClient')
127                             .then(function() {
128                                 assert(this.updatedApiClient.is_trusted);
129                             })
130                         }
131                     })
132                     .then(function () {
133                         return { user: this.theUser, token: this.userToken };
134                     })
135                 })
136             })
137         })
138     }
139 )
140
141 Cypress.Commands.add(
142     "createLink", (token, data) => {
143         return cy.createResource(token, 'links', {
144             link: JSON.stringify(data)
145         })
146     }
147 )
148
149 Cypress.Commands.add(
150     "createGroup", (token, data) => {
151         return cy.createResource(token, 'groups', {
152             group: JSON.stringify(data),
153             ensure_unique_name: true
154         })
155     }
156 )
157
158 Cypress.Commands.add(
159     "trashGroup", (token, uuid) => {
160         return cy.deleteResource(token, 'groups', uuid);
161     }
162 )
163
164
165 Cypress.Commands.add(
166     "createWorkflow", (token, data) => {
167         return cy.createResource(token, 'workflows', {
168             workflow: JSON.stringify(data),
169             ensure_unique_name: true
170         })
171     }
172 )
173
174 Cypress.Commands.add(
175     "createCollection", (token, data) => {
176         return cy.createResource(token, 'collections', {
177             collection: JSON.stringify(data),
178             ensure_unique_name: true
179         })
180     }
181 )
182
183 Cypress.Commands.add(
184     "getCollection", (token, uuid) => {
185         return cy.getResource(token, 'collections', uuid)
186     }
187 )
188
189 Cypress.Commands.add(
190     "updateCollection", (token, uuid, data) => {
191         return cy.updateResource(token, 'collections', uuid, {
192             collection: JSON.stringify(data)
193         })
194     }
195 )
196
197 Cypress.Commands.add(
198     "collectionReplaceFiles", (token, uuid, data) => {
199         return cy.updateResource(token, 'collections', uuid, JSON.stringify(data))
200     }
201 )
202
203 Cypress.Commands.add(
204     "getContainer", (token, uuid) => {
205         return cy.getResource(token, 'containers', uuid)
206     }
207 )
208
209 Cypress.Commands.add(
210     "updateContainer", (token, uuid, data) => {
211         return cy.updateResource(token, 'containers', uuid, {
212             container: JSON.stringify(data)
213         })
214     }
215 )
216
217 Cypress.Commands.add(
218     "getContainerRequest", (token, uuid) => {
219         return cy.getResource(token, 'container_requests', uuid)
220     }
221 )
222
223 Cypress.Commands.add(
224     'createContainerRequest', (token, data) => {
225         return cy.createResource(token, 'container_requests', {
226             container_request: JSON.stringify(data),
227             ensure_unique_name: true
228         })
229     }
230 )
231
232 Cypress.Commands.add(
233     "updateContainerRequest", (token, uuid, data) => {
234         return cy.updateResource(token, 'container_requests', uuid, {
235             container_request: JSON.stringify(data)
236         })
237     }
238 )
239
240 /**
241  * Requires an admin token for log_uuid modification to succeed
242  */
243 Cypress.Commands.add(
244     "appendLog", (token, crUuid, fileName, lines = []) => (
245         cy.getContainerRequest(token, crUuid).then((containerRequest) => {
246             if (containerRequest.log_uuid) {
247                 cy.listContainerRequestLogs(token, crUuid).then((logFiles) => {
248                     const filePath = `${containerRequest.log_uuid}/${containerLogFolderPrefix}${containerRequest.container_uuid}/${fileName}`;
249                     if (logFiles.find((file) => (file.name === fileName))) {
250                         // File exists, fetch and append
251                         return cy.doKeepRequest(
252                                 "GET",
253                                 `c=${filePath}`,
254                                 null,
255                                 null,
256                                 token
257                             )
258                             .then(({ body: contents }) => cy.doKeepRequest(
259                                 "PUT",
260                                 `c=${filePath}`,
261                                 contents.split("\n").concat(lines).join("\n"),
262                                 null,
263                                 token
264                             ));
265                     } else {
266                         // File not exists, put new file
267                         cy.doKeepRequest(
268                             "PUT",
269                             `c=${filePath}`,
270                             lines.join("\n"),
271                             null,
272                             token
273                         )
274                     }
275                 });
276             } else {
277                 // Create log collection
278                 return cy.createCollection(token, {
279                     name: `Test log collection ${Math.floor(Math.random() * 999999)}`,
280                     owner_uuid: containerRequest.owner_uuid,
281                     manifest_text: ""
282                 }).then((collection) => {
283                     // Update CR log_uuid to fake log collection
284                     cy.updateContainerRequest(token, containerRequest.uuid, {
285                         log_uuid: collection.uuid,
286                     }).then(() => (
287                         // Create empty directory for container uuid
288                         cy.collectionReplaceFiles(token, collection.uuid, {
289                             collection: {
290                                 preserve_version: true,
291                             },
292                             replace_files: {
293                                 [`/${containerLogFolderPrefix}${containerRequest.container_uuid}`]: "d41d8cd98f00b204e9800998ecf8427e+0"
294                             }
295                         }).then(() => (
296                             // Put new log file with contents into fake log collection
297                             cy.doKeepRequest(
298                                 'PUT',
299                                 `c=${collection.uuid}/${containerLogFolderPrefix}${containerRequest.container_uuid}/${fileName}`,
300                                 lines.join('\n'),
301                                 null,
302                                 token
303                             )
304                         ))
305                     ));
306                 });
307             }
308         })
309     )
310 )
311
312 Cypress.Commands.add(
313     "listContainerRequestLogs", (token, crUuid) => (
314         cy.getContainerRequest(token, crUuid).then((containerRequest) => (
315             cy.doKeepRequest('PROPFIND', `c=${containerRequest.log_uuid}/${containerLogFolderPrefix}${containerRequest.container_uuid}`, null, null, token)
316                 .then(({body: data}) => {
317                     return extractFilesData(new DOMParser().parseFromString(data, "text/xml"));
318                 })
319         ))
320     )
321 );
322
323 Cypress.Commands.add(
324     "createVirtualMachine", (token, data) => {
325         return cy.createResource(token, 'virtual_machines', {
326             virtual_machine: JSON.stringify(data),
327             ensure_unique_name: true
328         })
329     }
330 )
331
332 Cypress.Commands.add(
333     "getResource", (token, suffix, uuid) => {
334         return cy.doRequest('GET', `/arvados/v1/${suffix}/${uuid}`, null, {}, token)
335             .its('body')
336             .then(function (resource) {
337                 return resource;
338             })
339     }
340 )
341
342 Cypress.Commands.add(
343     "createResource", (token, suffix, data) => {
344         return cy.doRequest('POST', '/arvados/v1/' + suffix, data, null, token, true)
345             .its('body')
346             .then(function (resource) {
347                 createdResources.push({suffix, uuid: resource.uuid});
348                 return resource;
349             })
350     }
351 )
352
353 Cypress.Commands.add(
354     "deleteResource", (token, suffix, uuid, failOnStatusCode = true) => {
355         return cy.doRequest('DELETE', '/arvados/v1/' + suffix + '/' + uuid, null, null, token, false, true, failOnStatusCode)
356             .its('body')
357             .then(function (resource) {
358                 return resource;
359             })
360     }
361 )
362
363 Cypress.Commands.add(
364     "updateResource", (token, suffix, uuid, data) => {
365         return cy.doRequest('PATCH', '/arvados/v1/' + suffix + '/' + uuid, data, null, token, true)
366             .its('body')
367             .then(function (resource) {
368                 return resource;
369             })
370     }
371 )
372
373 Cypress.Commands.add(
374     "loginAs", (user) => {
375         cy.clearCookies()
376         cy.clearLocalStorage()
377         cy.visit(`/token/?api_token=${user.token}`);
378         cy.url({timeout: 10000}).should('contain', '/projects/');
379         cy.get('div#root').should('contain', 'Arvados Workbench (zzzzz)');
380         cy.get('div#root').should('not.contain', 'Your account is inactive');
381     }
382 )
383
384 Cypress.Commands.add(
385     "testEditProjectOrCollection", (container, oldName, newName, newDescription, isProject = true) => {
386         cy.get(container).contains(oldName).rightclick();
387         cy.get('[data-cy=context-menu]').contains(isProject ? 'Edit project' : 'Edit collection').click();
388         cy.get('[data-cy=form-dialog]').within(() => {
389             cy.get('input[name=name]').clear().type(newName);
390             cy.get(isProject ? 'div[contenteditable=true]' : 'input[name=description]').clear().type(newDescription);
391             cy.get('[data-cy=form-submit-btn]').click();
392         });
393
394         cy.get(container).contains(newName).rightclick();
395         cy.get('[data-cy=context-menu]').contains(isProject ? 'Edit project' : 'Edit collection').click();
396         cy.get('[data-cy=form-dialog]').within(() => {
397             cy.get('input[name=name]').should('have.value', newName);
398
399             if (isProject) {
400                 cy.get('span[data-text=true]').contains(newDescription);
401             } else {
402                 cy.get('input[name=description]').should('have.value', newDescription);
403             }
404
405             cy.get('[data-cy=form-cancel-btn]').click();
406         });
407     }
408 )
409
410 Cypress.Commands.add(
411     "doSearch", (searchTerm) => {
412         cy.get('[data-cy=searchbar-input-field]').type(`{selectall}${searchTerm}{enter}`);
413     }
414 )
415
416 Cypress.Commands.add(
417     "goToPath", (path) => {
418         return cy.window().its('appHistory').invoke('push', path);
419     }
420 )
421
422 Cypress.Commands.add('getAll', (...elements) => {
423     const promise = cy.wrap([], { log: false })
424
425     for (let element of elements) {
426         promise.then(arr => cy.get(element).then(got => cy.wrap([...arr, got])))
427     }
428
429     return promise
430 })
431
432 Cypress.Commands.add('shareWith', (srcUserToken, targetUserUUID, itemUUID, permission = 'can_write') => {
433     cy.createLink(srcUserToken, {
434         name: permission,
435         link_class: 'permission',
436         head_uuid: itemUUID,
437         tail_uuid: targetUserUUID
438     });
439 })
440
441 Cypress.Commands.add('addToFavorites', (userToken, userUUID, itemUUID) => {
442     cy.createLink(userToken, {
443         head_uuid: itemUUID,
444         link_class: 'star',
445         name: '',
446         owner_uuid: userUUID,
447         tail_uuid: userUUID,
448     });
449 })
450
451 Cypress.Commands.add('createProject', ({
452     owningUser,
453     targetUser,
454     projectName,
455     canWrite,
456     addToFavorites
457 }) => {
458     const writePermission = canWrite ? 'can_write' : 'can_read';
459
460     cy.createGroup(owningUser.token, {
461         name: `${projectName} ${Math.floor(Math.random() * 999999)}`,
462         group_class: 'project',
463     }).as(`${projectName}`).then((project) => {
464         if (targetUser && targetUser !== owningUser) {
465             cy.shareWith(owningUser.token, targetUser.user.uuid, project.uuid, writePermission);
466         }
467         if (addToFavorites) {
468             const user = targetUser ? targetUser : owningUser;
469             cy.addToFavorites(user.token, user.user.uuid, project.uuid);
470         }
471     });
472 });
473
474 Cypress.Commands.add(
475     'upload',
476     {
477         prevSubject: 'element',
478     },
479     (subject, file, fileName, binaryMode = true) => {
480         cy.window().then(window => {
481             const blob = binaryMode
482                 ? b64toBlob(file, '', 512)
483                 : new Blob([file], {type: 'text/plain'});
484             const testFile = new window.File([blob], fileName);
485
486             cy.wrap(subject).trigger('drop', {
487                 dataTransfer: { files: [testFile] },
488             });
489         })
490     }
491 )
492
493 function b64toBlob(b64Data, contentType = '', sliceSize = 512) {
494     const byteCharacters = atob(b64Data)
495     const byteArrays = []
496
497     for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
498         const slice = byteCharacters.slice(offset, offset + sliceSize);
499
500         const byteNumbers = new Array(slice.length);
501         for (let i = 0; i < slice.length; i++) {
502             byteNumbers[i] = slice.charCodeAt(i);
503         }
504
505         const byteArray = new Uint8Array(byteNumbers);
506
507         byteArrays.push(byteArray);
508     }
509
510     const blob = new Blob(byteArrays, { type: contentType });
511     return blob
512 }
513
514 // From https://github.com/cypress-io/cypress/issues/7306#issuecomment-1076451070=
515 // This command requires the async package (https://www.npmjs.com/package/async)
516 Cypress.Commands.add('waitForDom', () => {
517     cy.window().then({
518         // Don't timeout before waitForDom finishes
519         timeout: 10000
520     }, win => {
521       let timeElapsed = 0;
522
523       cy.log("Waiting for DOM mutations to complete");
524
525       return new Cypress.Promise((resolve) => {
526         // set the required variables
527         let async = require("async");
528         let observerConfig = { attributes: true, childList: true, subtree: true };
529         let items = Array.apply(null, { length: 50 }).map(Number.call, Number);
530         win.mutationCount = 0;
531         win.previousMutationCount = null;
532
533         // create an observer instance
534         let observer = new win.MutationObserver((mutations) => {
535           mutations.forEach((mutation) => {
536             // Only record "attributes" type mutations that are not a "class" mutation.
537             // If the mutation is not an "attributes" type, then we always record it.
538             if (mutation.type === 'attributes' && mutation.attributeName !== 'class') {
539               win.mutationCount += 1;
540             } else if (mutation.type !== 'attributes') {
541               win.mutationCount += 1;
542             }
543           });
544
545           // initialize the previousMutationCount
546           if (win.previousMutationCount == null) win.previousMutationCount = 0;
547         });
548
549         // watch the document body for the specified mutations
550         observer.observe(win.document.body, observerConfig);
551
552         // check the DOM for mutations up to 50 times for a maximum time of 5 seconds
553         async.eachSeries(items, function iteratee(item, callback) {
554           // keep track of the elapsed time so we can log it at the end of the command
555           timeElapsed = timeElapsed + 100;
556
557           // make each iteration of the loop 100ms apart
558           setTimeout(() => {
559             if (win.mutationCount === win.previousMutationCount) {
560               // pass an argument to the async callback to exit the loop
561               return callback('Resolved - DOM changes complete.');
562             } else if (win.previousMutationCount != null) {
563               // only set the previous count if the observer has checked the DOM at least once
564               win.previousMutationCount = win.mutationCount;
565               return callback();
566             } else if (win.mutationCount === 0 && win.previousMutationCount == null && item === 4) {
567               // this is an early exit in case nothing is changing in the DOM. That way we only
568               // wait 500ms instead of the full 5 seconds when no DOM changes are occurring.
569               return callback('Resolved - Exiting early since no DOM changes were detected.');
570             } else {
571               // proceed to the next iteration
572               return callback();
573             }
574           }, 100);
575         }, function done() {
576           // Log the total wait time so users can see it
577           cy.log(`DOM mutations ${timeElapsed >= 5000 ? "did not complete" : "completed"} in ${timeElapsed} ms`);
578
579           // disconnect the observer and resolve the promise
580           observer.disconnect();
581           resolve();
582         });
583       });
584     });
585   });