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 import { extractFilesData } from "services/collection-service/collection-service-files-response";
33 const controllerURL = Cypress.env("controller_url");
34 const systemToken = Cypress.env("system_token");
35 let createdResources = [];
37 const containerLogFolderPrefix = "log for container ";
39 // Clean up anything that was created. You can temporarily add
40 // 'return' to the top if you need the resources to hang around to
41 // debug a specific test.
42 afterEach(function () {
43 if (createdResources.length === 0) {
46 cy.log(`Cleaning ${createdResources.length} previously created resource(s).`);
47 createdResources.forEach(function ({ suffix, uuid }) {
48 // Don't fail when a resource isn't already there, some objects may have
49 // been removed, directly or indirectly, from the test that created them.
50 cy.deleteResource(systemToken, suffix, uuid, false);
52 createdResources = [];
57 (method = "GET", path = "", data = null, qs = null, token = systemToken, auth = false, followRedirect = true, failOnStatusCode = true) => {
60 url: `${controllerURL.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`,
62 qs: auth ? qs : Object.assign({ api_token: token }, qs),
63 auth: auth ? { bearer: `${token}` } : undefined,
64 followRedirect: followRedirect,
65 failOnStatusCode: failOnStatusCode,
72 (method = "GET", path = "", data = null, qs = null, token = systemToken, auth = false, followRedirect = true, failOnStatusCode = true) => {
73 return cy.doRequest("GET", "/arvados/v1/config", null, null).then(({ body: config }) => {
76 url: `${config.Services.WebDAVDownload.ExternalURL.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`,
78 qs: auth ? qs : Object.assign({ api_token: token }, qs),
79 auth: auth ? { bearer: `${token}` } : undefined,
80 followRedirect: followRedirect,
81 failOnStatusCode: failOnStatusCode,
87 Cypress.Commands.add("getUser", (username, first_name = "", last_name = "", is_admin = false, is_active = true) => {
88 // Create user if not already created
93 "/auth/controller/callback",
95 auth_info: JSON.stringify({
96 email: `${username}@example.local`,
98 first_name: first_name,
100 alternate_emails: [],
102 return_to: ",https://controller.api.client.invalid",
108 ) // Don't follow redirects so we can catch the token
109 .its("headers.location")
111 // Get its token and set the account up as admin and/or active
113 this.userToken = this.location.split("=")[1];
114 assert.isString(this.userToken);
116 .doRequest("GET", "/arvados/v1/users", null, {
117 filters: `[["username", "=", "${username}"]]`,
122 cy.doRequest("PUT", `/arvados/v1/users/${this.aUser.uuid}`, {
125 is_active: is_active,
131 cy.doRequest("GET", "/arvados/v1/api_clients", null, {
132 filters: `[["is_trusted", "=", false]]`,
133 order: `["created_at desc"]`,
138 if (this.apiClients.length > 0) {
139 cy.doRequest("PUT", `/arvados/v1/api_clients/${this.apiClients[0].uuid}`, {
145 .as("updatedApiClient")
147 assert(this.updatedApiClient.is_trusted);
152 return { user: this.theUser, token: this.userToken };
160 Cypress.Commands.add("createLink", (token, data) => {
161 return cy.createResource(token, "links", {
162 link: JSON.stringify(data),
166 Cypress.Commands.add("createGroup", (token, data) => {
167 return cy.createResource(token, "groups", {
168 group: JSON.stringify(data),
169 ensure_unique_name: true,
173 Cypress.Commands.add("trashGroup", (token, uuid) => {
174 return cy.deleteResource(token, "groups", uuid);
177 Cypress.Commands.add("createWorkflow", (token, data) => {
178 return cy.createResource(token, "workflows", {
179 workflow: JSON.stringify(data),
180 ensure_unique_name: true,
184 Cypress.Commands.add("createCollection", (token, data) => {
185 return cy.createResource(token, "collections", {
186 collection: JSON.stringify(data),
187 ensure_unique_name: true,
191 Cypress.Commands.add("getCollection", (token, uuid) => {
192 return cy.getResource(token, "collections", uuid);
195 Cypress.Commands.add("updateCollection", (token, uuid, data) => {
196 return cy.updateResource(token, "collections", uuid, {
197 collection: JSON.stringify(data),
201 Cypress.Commands.add("collectionReplaceFiles", (token, uuid, data) => {
202 return cy.updateResource(token, "collections", uuid, {
204 preserve_version: true,
206 replace_files: JSON.stringify(data),
210 Cypress.Commands.add("getContainer", (token, uuid) => {
211 return cy.getResource(token, "containers", uuid);
214 Cypress.Commands.add("updateContainer", (token, uuid, data) => {
215 return cy.updateResource(token, "containers", uuid, {
216 container: JSON.stringify(data),
220 Cypress.Commands.add("getContainerRequest", (token, uuid) => {
221 return cy.getResource(token, "container_requests", uuid);
224 Cypress.Commands.add("createContainerRequest", (token, data) => {
225 return cy.createResource(token, "container_requests", {
226 container_request: JSON.stringify(data),
227 ensure_unique_name: true,
231 Cypress.Commands.add("updateContainerRequest", (token, uuid, data) => {
232 return cy.updateResource(token, "container_requests", uuid, {
233 container_request: JSON.stringify(data),
238 * Requires an admin token for log_uuid modification to succeed
240 Cypress.Commands.add("appendLog", (token, crUuid, fileName, lines = []) =>
241 cy.getContainerRequest(token, crUuid).then(containerRequest => {
242 if (containerRequest.log_uuid) {
243 cy.listContainerRequestLogs(token, crUuid).then(logFiles => {
244 const filePath = `${containerRequest.log_uuid}/${containerLogFolderPrefix}${containerRequest.container_uuid}/${fileName}`;
245 if (logFiles.find(file => file.name === fileName)) {
246 // File exists, fetch and append
248 .doWebDAVRequest("GET", `c=${filePath}`, null, null, token)
249 .then(({ body: contents }) =>
250 cy.doWebDAVRequest("PUT", `c=${filePath}`, contents.split("\n").concat(lines).join("\n"), null, token)
253 // File not exists, put new file
254 cy.doWebDAVRequest("PUT", `c=${filePath}`, lines.join("\n"), null, token);
258 // Create log collection
260 .createCollection(token, {
261 name: `Test log collection ${Math.floor(Math.random() * 999999)}`,
262 owner_uuid: containerRequest.owner_uuid,
265 .then(collection => {
266 // Update CR log_uuid to fake log collection
267 cy.updateContainerRequest(token, containerRequest.uuid, {
268 log_uuid: collection.uuid,
270 // Create empty directory for container uuid
272 .collectionReplaceFiles(token, collection.uuid, {
273 [`/${containerLogFolderPrefix}${containerRequest.container_uuid}`]: "d41d8cd98f00b204e9800998ecf8427e+0",
276 // Put new log file with contents into fake log collection
279 `c=${collection.uuid}/${containerLogFolderPrefix}${containerRequest.container_uuid}/${fileName}`,
291 Cypress.Commands.add("listContainerRequestLogs", (token, crUuid) =>
292 cy.getContainerRequest(token, crUuid).then(containerRequest =>
296 `c=${containerRequest.log_uuid}/${containerLogFolderPrefix}${containerRequest.container_uuid}`,
301 .then(({ body: data }) => {
302 return extractFilesData(new DOMParser().parseFromString(data, "text/xml"));
307 Cypress.Commands.add("createVirtualMachine", (token, data) => {
308 return cy.createResource(token, "virtual_machines", {
309 virtual_machine: JSON.stringify(data),
310 ensure_unique_name: true,
314 Cypress.Commands.add("getResource", (token, suffix, uuid) => {
316 .doRequest("GET", `/arvados/v1/${suffix}/${uuid}`, null, {}, token)
318 .then(function (resource) {
323 Cypress.Commands.add("createResource", (token, suffix, data) => {
325 .doRequest("POST", "/arvados/v1/" + suffix, data, null, token, true)
327 .then(function (resource) {
328 createdResources.push({ suffix, uuid: resource.uuid });
333 Cypress.Commands.add("deleteResource", (token, suffix, uuid, failOnStatusCode = true) => {
335 .doRequest("DELETE", "/arvados/v1/" + suffix + "/" + uuid, null, null, token, false, true, failOnStatusCode)
337 .then(function (resource) {
342 Cypress.Commands.add("updateResource", (token, suffix, uuid, data) => {
344 .doRequest("PATCH", "/arvados/v1/" + suffix + "/" + uuid, data, null, token, true)
346 .then(function (resource) {
351 Cypress.Commands.add("loginAs", user => {
353 cy.clearLocalStorage();
354 cy.visit(`/token/?api_token=${user.token}`);
355 cy.url({ timeout: 10000 }).should("contain", "/projects/");
356 cy.get("div#root").should("contain", "Arvados Workbench (zzzzz)");
357 cy.get("div#root").should("not.contain", "Your account is inactive");
360 Cypress.Commands.add("testEditProjectOrCollection", (container, oldName, newName, newDescription, isProject = true) => {
361 cy.get(container).contains(oldName).rightclick();
362 cy.get("[data-cy=context-menu]")
363 .contains(isProject ? "Edit project" : "Edit collection")
365 cy.get("[data-cy=form-dialog]").within(() => {
366 cy.get("input[name=name]").clear().type(newName);
367 cy.get(isProject ? "div[contenteditable=true]" : "input[name=description]")
369 .type(newDescription);
370 cy.get("[data-cy=form-submit-btn]").click();
373 cy.get(container).contains(newName).rightclick();
374 cy.get("[data-cy=context-menu]")
375 .contains(isProject ? "Edit project" : "Edit collection")
377 cy.get("[data-cy=form-dialog]").within(() => {
378 cy.get("input[name=name]").should("have.value", newName);
381 cy.get("span[data-text=true]").contains(newDescription);
383 cy.get("input[name=description]").should("have.value", newDescription);
386 cy.get("[data-cy=form-cancel-btn]").click();
390 Cypress.Commands.add("doSearch", searchTerm => {
391 cy.get("[data-cy=searchbar-input-field]").type(`{selectall}${searchTerm}{enter}`);
394 Cypress.Commands.add("goToPath", path => {
395 return cy.window().its("appHistory").invoke("push", path);
398 Cypress.Commands.add("getAll", (...elements) => {
399 const promise = cy.wrap([], { log: false });
401 for (let element of elements) {
402 promise.then(arr => cy.get(element).then(got => cy.wrap([...arr, got])));
408 Cypress.Commands.add("shareWith", (srcUserToken, targetUserUUID, itemUUID, permission = "can_write") => {
409 cy.createLink(srcUserToken, {
411 link_class: "permission",
413 tail_uuid: targetUserUUID,
417 Cypress.Commands.add("addToFavorites", (userToken, userUUID, itemUUID) => {
418 cy.createLink(userToken, {
422 owner_uuid: userUUID,
427 Cypress.Commands.add("createProject", ({ owningUser, targetUser, projectName, canWrite, addToFavorites }) => {
428 const writePermission = canWrite ? "can_write" : "can_read";
430 cy.createGroup(owningUser.token, {
431 name: `${projectName} ${Math.floor(Math.random() * 999999)}`,
432 group_class: "project",
434 .as(`${projectName}`)
436 if (targetUser && targetUser !== owningUser) {
437 cy.shareWith(owningUser.token, targetUser.user.uuid, project.uuid, writePermission);
439 if (addToFavorites) {
440 const user = targetUser ? targetUser : owningUser;
441 cy.addToFavorites(user.token, user.user.uuid, project.uuid);
446 Cypress.Commands.add(
449 prevSubject: "element",
451 (subject, file, fileName, binaryMode = true) => {
452 cy.window().then(window => {
453 const blob = binaryMode ? b64toBlob(file, "", 512) : new Blob([file], { type: "text/plain" });
454 const testFile = new window.File([blob], fileName);
456 cy.wrap(subject).trigger("drop", {
457 dataTransfer: { files: [testFile] },
463 function b64toBlob(b64Data, contentType = "", sliceSize = 512) {
464 const byteCharacters = atob(b64Data);
465 const byteArrays = [];
467 for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
468 const slice = byteCharacters.slice(offset, offset + sliceSize);
470 const byteNumbers = new Array(slice.length);
471 for (let i = 0; i < slice.length; i++) {
472 byteNumbers[i] = slice.charCodeAt(i);
475 const byteArray = new Uint8Array(byteNumbers);
477 byteArrays.push(byteArray);
480 const blob = new Blob(byteArrays, { type: contentType });
484 // From https://github.com/cypress-io/cypress/issues/7306#issuecomment-1076451070=
485 // This command requires the async package (https://www.npmjs.com/package/async)
486 Cypress.Commands.add("waitForDom", () => {
489 // Don't timeout before waitForDom finishes
495 cy.log("Waiting for DOM mutations to complete");
497 return new Cypress.Promise(resolve => {
498 // set the required variables
499 let async = require("async");
500 let observerConfig = { attributes: true, childList: true, subtree: true };
501 let items = Array.apply(null, { length: 50 }).map(Number.call, Number);
502 win.mutationCount = 0;
503 win.previousMutationCount = null;
505 // create an observer instance
506 let observer = new win.MutationObserver(mutations => {
507 mutations.forEach(mutation => {
508 // Only record "attributes" type mutations that are not a "class" mutation.
509 // If the mutation is not an "attributes" type, then we always record it.
510 if (mutation.type === "attributes" && mutation.attributeName !== "class") {
511 win.mutationCount += 1;
512 } else if (mutation.type !== "attributes") {
513 win.mutationCount += 1;
517 // initialize the previousMutationCount
518 if (win.previousMutationCount == null) win.previousMutationCount = 0;
521 // watch the document body for the specified mutations
522 observer.observe(win.document.body, observerConfig);
524 // check the DOM for mutations up to 50 times for a maximum time of 5 seconds
527 function iteratee(item, callback) {
528 // keep track of the elapsed time so we can log it at the end of the command
529 timeElapsed = timeElapsed + 100;
531 // make each iteration of the loop 100ms apart
533 if (win.mutationCount === win.previousMutationCount) {
534 // pass an argument to the async callback to exit the loop
535 return callback("Resolved - DOM changes complete.");
536 } else if (win.previousMutationCount != null) {
537 // only set the previous count if the observer has checked the DOM at least once
538 win.previousMutationCount = win.mutationCount;
540 } else if (win.mutationCount === 0 && win.previousMutationCount == null && item === 4) {
541 // this is an early exit in case nothing is changing in the DOM. That way we only
542 // wait 500ms instead of the full 5 seconds when no DOM changes are occurring.
543 return callback("Resolved - Exiting early since no DOM changes were detected.");
545 // proceed to the next iteration
551 // Log the total wait time so users can see it
552 cy.log(`DOM mutations ${timeElapsed >= 5000 ? "did not complete" : "completed"} in ${timeElapsed} ms`);
554 // disconnect the observer and resolve the promise
555 observer.disconnect();