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 'cypress-wait-until';
32 import { extractFilesData } from "services/collection-service/collection-service-files-response";
34 const controllerURL = Cypress.env("controller_url");
35 const systemToken = Cypress.env("system_token");
36 let createdResources = [];
38 const containerLogFolderPrefix = "log for container ";
40 // Clean up anything that was created. You can temporarily add
41 // 'return' to the top if you need the resources to hang around to
42 // debug a specific test.
43 afterEach(function () {
44 if (createdResources.length === 0) {
47 cy.log(`Cleaning ${createdResources.length} previously created resource(s).`);
48 // delete them in FIFO order because later created resources may
49 // be linked to the earlier ones.
50 createdResources.reverse().forEach(function ({ suffix, uuid }) {
51 // Don't fail when a resource isn't already there, some objects may have
52 // been removed, directly or indirectly, from the test that created them.
53 cy.deleteResource(systemToken, suffix, uuid, false);
55 createdResources = [];
60 (method = "GET", path = "", data = null, qs = null, token = systemToken, auth = false, followRedirect = true, failOnStatusCode = true) => {
63 url: `${controllerURL.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`,
65 qs: auth ? qs : Object.assign({ api_token: token }, qs),
66 auth: auth ? { bearer: `${token}` } : undefined,
67 followRedirect: followRedirect,
68 failOnStatusCode: failOnStatusCode,
75 (method = "GET", path = "", data = null, qs = null, token = systemToken, auth = false, followRedirect = true, failOnStatusCode = true) => {
76 return cy.doRequest("GET", "/arvados/v1/config", null, null).then(({ body: config }) => {
79 url: `${config.Services.WebDAVDownload.ExternalURL.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`,
81 qs: auth ? qs : Object.assign({ api_token: token }, qs),
82 auth: auth ? { bearer: `${token}` } : undefined,
83 followRedirect: followRedirect,
84 failOnStatusCode: failOnStatusCode,
90 Cypress.Commands.add("getUser", (username, first_name = "", last_name = "", is_admin = false, is_active = true) => {
91 // Create user if not already created
96 "/auth/controller/callback",
98 auth_info: JSON.stringify({
99 email: `${username}@example.local`,
101 first_name: first_name,
102 last_name: last_name,
103 alternate_emails: [],
105 return_to: ",https://controller.api.client.invalid",
111 ) // Don't follow redirects so we can catch the token
112 .its("headers.location")
114 // Get its token and set the account up as admin and/or active
116 this.userToken = this.location.split("=")[1];
117 assert.isString(this.userToken);
119 .doRequest("GET", "/arvados/v1/users", null, {
120 filters: `[["username", "=", "${username}"]]`,
125 cy.doRequest("PUT", `/arvados/v1/users/${this.aUser.uuid}`, {
128 is_active: is_active,
134 return { user: this.theUser, token: this.userToken };
141 Cypress.Commands.add("createLink", (token, data) => {
142 return cy.createResource(token, "links", {
143 link: JSON.stringify(data),
147 Cypress.Commands.add("createGroup", (token, data) => {
148 return cy.createResource(token, "groups", {
149 group: JSON.stringify(data),
150 ensure_unique_name: true,
154 Cypress.Commands.add("trashGroup", (token, uuid) => {
155 return cy.deleteResource(token, "groups", uuid);
158 Cypress.Commands.add("createWorkflow", (token, data) => {
159 return cy.createResource(token, "workflows", {
160 workflow: JSON.stringify(data),
161 ensure_unique_name: true,
165 Cypress.Commands.add("createCollection", (token, data, keep = false) => {
166 return cy.createResource(token, "collections", {
167 collection: JSON.stringify(data),
168 ensure_unique_name: true,
172 Cypress.Commands.add("getCollection", (token, uuid) => {
173 return cy.getResource(token, "collections", uuid);
176 Cypress.Commands.add("updateCollection", (token, uuid, data) => {
177 return cy.updateResource(token, "collections", uuid, {
178 collection: JSON.stringify(data),
182 Cypress.Commands.add("collectionReplaceFiles", (token, uuid, data) => {
183 return cy.updateResource(token, "collections", uuid, {
185 preserve_version: true,
187 replace_files: JSON.stringify(data),
191 Cypress.Commands.add("getContainer", (token, uuid) => {
192 return cy.getResource(token, "containers", uuid);
195 Cypress.Commands.add("updateContainer", (token, uuid, data) => {
196 return cy.updateResource(token, "containers", uuid, {
197 container: JSON.stringify(data),
201 Cypress.Commands.add("getContainerRequest", (token, uuid) => {
202 return cy.getResource(token, "container_requests", uuid);
205 Cypress.Commands.add("createContainerRequest", (token, data) => {
206 return cy.createResource(token, "container_requests", {
207 container_request: JSON.stringify(data),
208 ensure_unique_name: true,
212 Cypress.Commands.add("updateContainerRequest", (token, uuid, data) => {
213 return cy.updateResource(token, "container_requests", uuid, {
214 container_request: JSON.stringify(data),
219 * Requires an admin token for log_uuid modification to succeed
221 Cypress.Commands.add("appendLog", (token, crUuid, fileName, lines = []) =>
222 cy.getContainerRequest(token, crUuid).then(containerRequest => {
223 if (containerRequest.log_uuid) {
224 cy.listContainerRequestLogs(token, crUuid).then(logFiles => {
225 const filePath = `${containerRequest.log_uuid}/${containerLogFolderPrefix}${containerRequest.container_uuid}/${fileName}`;
226 if (logFiles.find(file => file.name === fileName)) {
227 // File exists, fetch and append
229 .doWebDAVRequest("GET", `c=${filePath}`, null, null, token)
230 .then(({ body: contents }) =>
231 cy.doWebDAVRequest("PUT", `c=${filePath}`, contents.split("\n").concat(lines).join("\n"), null, token)
234 // File not exists, put new file
235 cy.doWebDAVRequest("PUT", `c=${filePath}`, lines.join("\n"), null, token);
239 // Create log collection
241 .createCollection(token, {
242 name: `Test log collection ${Math.floor(Math.random() * 999999)}`,
243 owner_uuid: containerRequest.owner_uuid,
246 .then(collection => {
247 // Update CR log_uuid to fake log collection
248 cy.updateContainerRequest(token, containerRequest.uuid, {
249 log_uuid: collection.uuid,
251 // Create empty directory for container uuid
253 .collectionReplaceFiles(token, collection.uuid, {
254 [`/${containerLogFolderPrefix}${containerRequest.container_uuid}`]: "d41d8cd98f00b204e9800998ecf8427e+0",
257 // Put new log file with contents into fake log collection
260 `c=${collection.uuid}/${containerLogFolderPrefix}${containerRequest.container_uuid}/${fileName}`,
272 Cypress.Commands.add("listContainerRequestLogs", (token, crUuid) =>
273 cy.getContainerRequest(token, crUuid).then(containerRequest =>
277 `c=${containerRequest.log_uuid}/${containerLogFolderPrefix}${containerRequest.container_uuid}`,
282 .then(({ body: data }) => {
283 return extractFilesData(new DOMParser().parseFromString(data, "text/xml"));
288 Cypress.Commands.add("createVirtualMachine", (token, data) => {
289 return cy.createResource(token, "virtual_machines", {
290 virtual_machine: JSON.stringify(data),
291 ensure_unique_name: true,
295 Cypress.Commands.add("getResource", (token, suffix, uuid) => {
297 .doRequest("GET", `/arvados/v1/${suffix}/${uuid}`, null, {}, token)
299 .then(function (resource) {
304 Cypress.Commands.add("createResource", (token, suffix, data, keep = false) => {
306 .doRequest("POST", "/arvados/v1/" + suffix, data, null, token, true)
308 .then(function (resource) {
310 createdResources.push({ suffix, uuid: resource.uuid });
317 Cypress.Commands.add("deleteResource", (token, suffix, uuid, failOnStatusCode = true) => {
319 .doRequest("DELETE", "/arvados/v1/" + suffix + "/" + uuid, null, null, token, false, true, failOnStatusCode)
321 .then(function (resource) {
326 Cypress.Commands.add("updateResource", (token, suffix, uuid, data) => {
328 .doRequest("PATCH", "/arvados/v1/" + suffix + "/" + uuid, data, null, token, true)
330 .then(function (resource) {
335 Cypress.Commands.add("loginAs", user => {
336 // This shouldn't be necessary unless we need to call loginAs multiple times
339 cy.clearAllLocalStorage();
340 cy.clearAllSessionStorage();
341 cy.visit(`/token/?api_token=${user.token}`);
342 // Use waitUntil to avoid permafail race conditions with window.location being undefined
343 cy.waitUntil(() => cy.window().then(win =>
344 win?.location?.href &&
345 win.location.href.includes("/projects/")
346 ), { timeout: 15000 });
347 // Wait for page to settle before getting elements
349 cy.get("div#root").should("contain", "Arvados Workbench (zzzzz)");
350 cy.get("div#root").should("not.contain", "Your account is inactive");
353 Cypress.Commands.add("testEditProjectOrCollection", (container, oldName, newName, newDescription, isProject = true) => {
354 cy.get(container).contains(oldName).rightclick();
355 cy.get("[data-cy=context-menu]")
356 .contains(isProject ? "Edit project" : "Edit collection")
358 cy.get("[data-cy=form-dialog]").within(() => {
359 cy.get("input[name=name]").clear().type(newName);
360 cy.get(isProject ? "div[contenteditable=true]" : "input[name=description]")
362 .type(newDescription);
363 cy.get("[data-cy=form-submit-btn]").click();
366 cy.get(container).contains(newName).rightclick();
367 cy.get("[data-cy=context-menu]")
368 .contains(isProject ? "Edit project" : "Edit collection")
370 cy.get("[data-cy=form-dialog]").within(() => {
371 cy.get("input[name=name]").should("have.value", newName);
374 cy.get("span[data-text=true]").contains(newDescription);
376 cy.get("input[name=description]").should("have.value", newDescription);
379 cy.get("[data-cy=form-cancel-btn]").click();
383 Cypress.Commands.add("doSearch", searchTerm => {
384 cy.get("[data-cy=searchbar-input-field]").type(`{selectall}${searchTerm}{enter}`);
387 Cypress.Commands.add("goToPath", path => {
388 return cy.window().its("appHistory").invoke("push", path);
391 Cypress.Commands.add("getAll", (...elements) => {
392 const promise = cy.wrap([], { log: false });
394 for (let element of elements) {
395 promise.then(arr => cy.get(element).then(got => cy.wrap([...arr, got])));
401 Cypress.Commands.add("shareWith", (srcUserToken, targetUserUUID, itemUUID, permission = "can_write") => {
402 cy.createLink(srcUserToken, {
404 link_class: "permission",
406 tail_uuid: targetUserUUID,
410 Cypress.Commands.add("addToFavorites", (userToken, userUUID, itemUUID) => {
411 cy.createLink(userToken, {
415 owner_uuid: userUUID,
420 Cypress.Commands.add("createProject", ({ owningUser, targetUser, projectName, canWrite, addToFavorites }) => {
421 const writePermission = canWrite ? "can_write" : "can_read";
423 cy.createGroup(owningUser.token, {
424 name: `${projectName} ${Math.floor(Math.random() * 999999)}`,
425 group_class: "project",
427 .as(`${projectName}`)
429 if (targetUser && targetUser !== owningUser) {
430 cy.shareWith(owningUser.token, targetUser.user.uuid, project.uuid, writePermission);
432 if (addToFavorites) {
433 const user = targetUser ? targetUser : owningUser;
434 cy.addToFavorites(user.token, user.user.uuid, project.uuid);
439 Cypress.Commands.add(
442 prevSubject: "element",
444 (subject, file, fileName, binaryMode = true) => {
445 cy.window().then(window => {
446 const blob = binaryMode ? b64toBlob(file, "", 512) : new Blob([file], { type: "text/plain" });
447 const testFile = new window.File([blob], fileName);
449 cy.wrap(subject).trigger("drop", {
450 dataTransfer: { files: [testFile] },
456 function b64toBlob(b64Data, contentType = "", sliceSize = 512) {
457 const byteCharacters = atob(b64Data);
458 const byteArrays = [];
460 for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
461 const slice = byteCharacters.slice(offset, offset + sliceSize);
463 const byteNumbers = new Array(slice.length);
464 for (let i = 0; i < slice.length; i++) {
465 byteNumbers[i] = slice.charCodeAt(i);
468 const byteArray = new Uint8Array(byteNumbers);
470 byteArrays.push(byteArray);
473 const blob = new Blob(byteArrays, { type: contentType });
477 // From https://github.com/cypress-io/cypress/issues/7306#issuecomment-1076451070=
478 // This command requires the async package (https://www.npmjs.com/package/async)
479 Cypress.Commands.add("waitForDom", () => {
480 cy.window({ timeout: 10000 }).then(
482 // Don't timeout before waitForDom finishes
488 cy.log("Waiting for DOM mutations to complete");
490 return new Cypress.Promise(resolve => {
491 // set the required variables
492 let async = require("async");
493 let observerConfig = { attributes: true, childList: true, subtree: true };
494 let items = Array.apply(null, { length: 50 }).map(Number.call, Number);
495 win.mutationCount = 0;
496 win.previousMutationCount = null;
498 // create an observer instance
499 let observer = new win.MutationObserver(mutations => {
500 mutations.forEach(mutation => {
501 // Only record "attributes" type mutations that are not a "class" mutation.
502 // If the mutation is not an "attributes" type, then we always record it.
503 if (mutation.type === "attributes" && mutation.attributeName !== "class") {
504 win.mutationCount += 1;
505 } else if (mutation.type !== "attributes") {
506 win.mutationCount += 1;
510 // initialize the previousMutationCount
511 if (win.previousMutationCount == null) win.previousMutationCount = 0;
514 // watch the document body for the specified mutations
515 observer.observe(win.document.body, observerConfig);
517 // check the DOM for mutations up to 50 times for a maximum time of 5 seconds
520 function iteratee(item, callback) {
521 // keep track of the elapsed time so we can log it at the end of the command
522 timeElapsed = timeElapsed + 100;
524 // make each iteration of the loop 100ms apart
526 if (win.mutationCount === win.previousMutationCount) {
527 // pass an argument to the async callback to exit the loop
528 return callback("Resolved - DOM changes complete.");
529 } else if (win.previousMutationCount != null) {
530 // only set the previous count if the observer has checked the DOM at least once
531 win.previousMutationCount = win.mutationCount;
533 } else if (win.mutationCount === 0 && win.previousMutationCount == null && item === 4) {
534 // this is an early exit in case nothing is changing in the DOM. That way we only
535 // wait 500ms instead of the full 5 seconds when no DOM changes are occurring.
536 return callback("Resolved - Exiting early since no DOM changes were detected.");
538 // proceed to the next iteration
544 // Log the total wait time so users can see it
545 cy.log(`DOM mutations ${timeElapsed >= 5000 ? "did not complete" : "completed"} in ${timeElapsed} ms`);
547 // disconnect the observer and resolve the promise
548 observer.disconnect();
557 Cypress.Commands.add("setupDockerImage", (image_name) => {
558 // Create a collection that will be used as a docker image for the tests.
562 cy.getUser("admin", "Admin", "User", true, true)
565 adminUser = this.adminUser;
568 cy.getUser('activeuser', 'Active', 'User', false, true)
569 .as('activeUser').then(function () {
570 activeUser = this.activeUser;
573 cy.getAll('@activeUser', '@adminUser').then(([activeUser, adminUser]) => {
574 cy.createCollection(adminUser.token, {
575 name: "docker_image",
577 ". d21353cfe035e3e384563ee55eadbb2f+67108864 5c77a43e329b9838cbec18ff42790e57+55605760 0:122714624:sha256:d8309758b8fe2c81034ffc8a10c36460b77db7bc5e7b448c4e5b684f9d95a678.tar\n",
580 .then(function (dockerImage) {
581 // Give read permissions to the active user on the docker image.
582 cy.createLink(adminUser.token, {
583 link_class: "permission",
585 tail_uuid: activeUser.user.uuid,
586 head_uuid: dockerImage.uuid,
588 .as("dockerImagePermission")
590 // Set-up docker image collection tags
591 cy.createLink(activeUser.token, {
592 link_class: "docker_image_repo+tag",
594 head_uuid: dockerImage.uuid,
595 }).as("dockerImageRepoTag");
596 cy.createLink(activeUser.token, {
597 link_class: "docker_image_hash",
598 name: "sha256:d8309758b8fe2c81034ffc8a10c36460b77db7bc5e7b448c4e5b684f9d95a678",
599 head_uuid: dockerImage.uuid,
600 }).as("dockerImageHash");
604 return cy.getAll("@dockerImage", "@dockerImageRepoTag", "@dockerImageHash", "@dockerImagePermission").then(function ([dockerImage]) {