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 createdResources.forEach(function ({ suffix, uuid }) {
49 // Don't fail when a resource isn't already there, some objects may have
50 // been removed, directly or indirectly, from the test that created them.
51 cy.deleteResource(systemToken, suffix, uuid, false);
53 createdResources = [];
58 (method = "GET", path = "", data = null, qs = null, token = systemToken, auth = false, followRedirect = true, failOnStatusCode = true) => {
61 url: `${controllerURL.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`,
63 qs: auth ? qs : Object.assign({ api_token: token }, qs),
64 auth: auth ? { bearer: `${token}` } : undefined,
65 followRedirect: followRedirect,
66 failOnStatusCode: failOnStatusCode,
73 (method = "GET", path = "", data = null, qs = null, token = systemToken, auth = false, followRedirect = true, failOnStatusCode = true) => {
74 return cy.doRequest("GET", "/arvados/v1/config", null, null).then(({ body: config }) => {
77 url: `${config.Services.WebDAVDownload.ExternalURL.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`,
79 qs: auth ? qs : Object.assign({ api_token: token }, qs),
80 auth: auth ? { bearer: `${token}` } : undefined,
81 followRedirect: followRedirect,
82 failOnStatusCode: failOnStatusCode,
88 Cypress.Commands.add("getUser", (username, first_name = "", last_name = "", is_admin = false, is_active = true) => {
89 // Create user if not already created
94 "/auth/controller/callback",
96 auth_info: JSON.stringify({
97 email: `${username}@example.local`,
99 first_name: first_name,
100 last_name: last_name,
101 alternate_emails: [],
103 return_to: ",https://controller.api.client.invalid",
109 ) // Don't follow redirects so we can catch the token
110 .its("headers.location")
112 // Get its token and set the account up as admin and/or active
114 this.userToken = this.location.split("=")[1];
115 assert.isString(this.userToken);
117 .doRequest("GET", "/arvados/v1/users", null, {
118 filters: `[["username", "=", "${username}"]]`,
123 cy.doRequest("PUT", `/arvados/v1/users/${this.aUser.uuid}`, {
126 is_active: is_active,
132 cy.doRequest("GET", "/arvados/v1/api_clients", null, {
133 filters: `[["is_trusted", "=", false]]`,
134 order: `["created_at desc"]`,
139 if (this.apiClients.length > 0) {
140 cy.doRequest("PUT", `/arvados/v1/api_clients/${this.apiClients[0].uuid}`, {
146 .as("updatedApiClient")
148 assert(this.updatedApiClient.is_trusted);
153 return { user: this.theUser, token: this.userToken };
161 Cypress.Commands.add("createLink", (token, data) => {
162 return cy.createResource(token, "links", {
163 link: JSON.stringify(data),
167 Cypress.Commands.add("createGroup", (token, data) => {
168 return cy.createResource(token, "groups", {
169 group: JSON.stringify(data),
170 ensure_unique_name: true,
174 Cypress.Commands.add("trashGroup", (token, uuid) => {
175 return cy.deleteResource(token, "groups", uuid);
178 Cypress.Commands.add("createWorkflow", (token, data) => {
179 return cy.createResource(token, "workflows", {
180 workflow: JSON.stringify(data),
181 ensure_unique_name: true,
185 Cypress.Commands.add("createCollection", (token, data) => {
186 return cy.createResource(token, "collections", {
187 collection: JSON.stringify(data),
188 ensure_unique_name: true,
192 Cypress.Commands.add("getCollection", (token, uuid) => {
193 return cy.getResource(token, "collections", uuid);
196 Cypress.Commands.add("updateCollection", (token, uuid, data) => {
197 return cy.updateResource(token, "collections", uuid, {
198 collection: JSON.stringify(data),
202 Cypress.Commands.add("collectionReplaceFiles", (token, uuid, data) => {
203 return cy.updateResource(token, "collections", uuid, {
205 preserve_version: true,
207 replace_files: JSON.stringify(data),
211 Cypress.Commands.add("getContainer", (token, uuid) => {
212 return cy.getResource(token, "containers", uuid);
215 Cypress.Commands.add("updateContainer", (token, uuid, data) => {
216 return cy.updateResource(token, "containers", uuid, {
217 container: JSON.stringify(data),
221 Cypress.Commands.add("getContainerRequest", (token, uuid) => {
222 return cy.getResource(token, "container_requests", uuid);
225 Cypress.Commands.add("createContainerRequest", (token, data) => {
226 return cy.createResource(token, "container_requests", {
227 container_request: JSON.stringify(data),
228 ensure_unique_name: true,
232 Cypress.Commands.add("updateContainerRequest", (token, uuid, data) => {
233 return cy.updateResource(token, "container_requests", uuid, {
234 container_request: JSON.stringify(data),
239 * Requires an admin token for log_uuid modification to succeed
241 Cypress.Commands.add("appendLog", (token, crUuid, fileName, lines = []) =>
242 cy.getContainerRequest(token, crUuid).then(containerRequest => {
243 if (containerRequest.log_uuid) {
244 cy.listContainerRequestLogs(token, crUuid).then(logFiles => {
245 const filePath = `${containerRequest.log_uuid}/${containerLogFolderPrefix}${containerRequest.container_uuid}/${fileName}`;
246 if (logFiles.find(file => file.name === fileName)) {
247 // File exists, fetch and append
249 .doWebDAVRequest("GET", `c=${filePath}`, null, null, token)
250 .then(({ body: contents }) =>
251 cy.doWebDAVRequest("PUT", `c=${filePath}`, contents.split("\n").concat(lines).join("\n"), null, token)
254 // File not exists, put new file
255 cy.doWebDAVRequest("PUT", `c=${filePath}`, lines.join("\n"), null, token);
259 // Create log collection
261 .createCollection(token, {
262 name: `Test log collection ${Math.floor(Math.random() * 999999)}`,
263 owner_uuid: containerRequest.owner_uuid,
266 .then(collection => {
267 // Update CR log_uuid to fake log collection
268 cy.updateContainerRequest(token, containerRequest.uuid, {
269 log_uuid: collection.uuid,
271 // Create empty directory for container uuid
273 .collectionReplaceFiles(token, collection.uuid, {
274 [`/${containerLogFolderPrefix}${containerRequest.container_uuid}`]: "d41d8cd98f00b204e9800998ecf8427e+0",
277 // Put new log file with contents into fake log collection
280 `c=${collection.uuid}/${containerLogFolderPrefix}${containerRequest.container_uuid}/${fileName}`,
292 Cypress.Commands.add("listContainerRequestLogs", (token, crUuid) =>
293 cy.getContainerRequest(token, crUuid).then(containerRequest =>
297 `c=${containerRequest.log_uuid}/${containerLogFolderPrefix}${containerRequest.container_uuid}`,
302 .then(({ body: data }) => {
303 return extractFilesData(new DOMParser().parseFromString(data, "text/xml"));
308 Cypress.Commands.add("createVirtualMachine", (token, data) => {
309 return cy.createResource(token, "virtual_machines", {
310 virtual_machine: JSON.stringify(data),
311 ensure_unique_name: true,
315 Cypress.Commands.add("getResource", (token, suffix, uuid) => {
317 .doRequest("GET", `/arvados/v1/${suffix}/${uuid}`, null, {}, token)
319 .then(function (resource) {
324 Cypress.Commands.add("createResource", (token, suffix, data) => {
326 .doRequest("POST", "/arvados/v1/" + suffix, data, null, token, true)
328 .then(function (resource) {
329 createdResources.push({ suffix, uuid: resource.uuid });
334 Cypress.Commands.add("deleteResource", (token, suffix, uuid, failOnStatusCode = true) => {
336 .doRequest("DELETE", "/arvados/v1/" + suffix + "/" + uuid, null, null, token, false, true, failOnStatusCode)
338 .then(function (resource) {
343 Cypress.Commands.add("updateResource", (token, suffix, uuid, data) => {
345 .doRequest("PATCH", "/arvados/v1/" + suffix + "/" + uuid, data, null, token, true)
347 .then(function (resource) {
352 Cypress.Commands.add("loginAs", user => {
354 cy.clearLocalStorage();
355 cy.visit(`/token/?api_token=${user.token}`);
356 // Use waitUntil to avoid permafail race conditions with window.location being undefined
357 cy.waitUntil(() => cy.window().then(win =>
358 win?.location?.href &&
359 win.location.href.includes("/projects/")
360 ), { timeout: 15000 });
361 // Wait for page to settle before getting elements
363 cy.get("div#root").should("contain", "Arvados Workbench (zzzzz)");
364 cy.get("div#root").should("not.contain", "Your account is inactive");
367 Cypress.Commands.add("testEditProjectOrCollection", (container, oldName, newName, newDescription, isProject = true) => {
368 cy.get(container).contains(oldName).rightclick();
369 cy.get("[data-cy=context-menu]")
370 .contains(isProject ? "Edit project" : "Edit collection")
372 cy.get("[data-cy=form-dialog]").within(() => {
373 cy.get("input[name=name]").clear().type(newName);
374 cy.get(isProject ? "div[contenteditable=true]" : "input[name=description]")
376 .type(newDescription);
377 cy.get("[data-cy=form-submit-btn]").click();
380 cy.get(container).contains(newName).rightclick();
381 cy.get("[data-cy=context-menu]")
382 .contains(isProject ? "Edit project" : "Edit collection")
384 cy.get("[data-cy=form-dialog]").within(() => {
385 cy.get("input[name=name]").should("have.value", newName);
388 cy.get("span[data-text=true]").contains(newDescription);
390 cy.get("input[name=description]").should("have.value", newDescription);
393 cy.get("[data-cy=form-cancel-btn]").click();
397 Cypress.Commands.add("doSearch", searchTerm => {
398 cy.get("[data-cy=searchbar-input-field]").type(`{selectall}${searchTerm}{enter}`);
401 Cypress.Commands.add("goToPath", path => {
402 return cy.window().its("appHistory").invoke("push", path);
405 Cypress.Commands.add("getAll", (...elements) => {
406 const promise = cy.wrap([], { log: false });
408 for (let element of elements) {
409 promise.then(arr => cy.get(element).then(got => cy.wrap([...arr, got])));
415 Cypress.Commands.add("shareWith", (srcUserToken, targetUserUUID, itemUUID, permission = "can_write") => {
416 cy.createLink(srcUserToken, {
418 link_class: "permission",
420 tail_uuid: targetUserUUID,
424 Cypress.Commands.add("addToFavorites", (userToken, userUUID, itemUUID) => {
425 cy.createLink(userToken, {
429 owner_uuid: userUUID,
434 Cypress.Commands.add("createProject", ({ owningUser, targetUser, projectName, canWrite, addToFavorites }) => {
435 const writePermission = canWrite ? "can_write" : "can_read";
437 cy.createGroup(owningUser.token, {
438 name: `${projectName} ${Math.floor(Math.random() * 999999)}`,
439 group_class: "project",
441 .as(`${projectName}`)
443 if (targetUser && targetUser !== owningUser) {
444 cy.shareWith(owningUser.token, targetUser.user.uuid, project.uuid, writePermission);
446 if (addToFavorites) {
447 const user = targetUser ? targetUser : owningUser;
448 cy.addToFavorites(user.token, user.user.uuid, project.uuid);
453 Cypress.Commands.add(
456 prevSubject: "element",
458 (subject, file, fileName, binaryMode = true) => {
459 cy.window().then(window => {
460 const blob = binaryMode ? b64toBlob(file, "", 512) : new Blob([file], { type: "text/plain" });
461 const testFile = new window.File([blob], fileName);
463 cy.wrap(subject).trigger("drop", {
464 dataTransfer: { files: [testFile] },
470 function b64toBlob(b64Data, contentType = "", sliceSize = 512) {
471 const byteCharacters = atob(b64Data);
472 const byteArrays = [];
474 for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
475 const slice = byteCharacters.slice(offset, offset + sliceSize);
477 const byteNumbers = new Array(slice.length);
478 for (let i = 0; i < slice.length; i++) {
479 byteNumbers[i] = slice.charCodeAt(i);
482 const byteArray = new Uint8Array(byteNumbers);
484 byteArrays.push(byteArray);
487 const blob = new Blob(byteArrays, { type: contentType });
491 // From https://github.com/cypress-io/cypress/issues/7306#issuecomment-1076451070=
492 // This command requires the async package (https://www.npmjs.com/package/async)
493 Cypress.Commands.add("waitForDom", () => {
496 // Don't timeout before waitForDom finishes
502 cy.log("Waiting for DOM mutations to complete");
504 return new Cypress.Promise(resolve => {
505 // set the required variables
506 let async = require("async");
507 let observerConfig = { attributes: true, childList: true, subtree: true };
508 let items = Array.apply(null, { length: 50 }).map(Number.call, Number);
509 win.mutationCount = 0;
510 win.previousMutationCount = null;
512 // create an observer instance
513 let observer = new win.MutationObserver(mutations => {
514 mutations.forEach(mutation => {
515 // Only record "attributes" type mutations that are not a "class" mutation.
516 // If the mutation is not an "attributes" type, then we always record it.
517 if (mutation.type === "attributes" && mutation.attributeName !== "class") {
518 win.mutationCount += 1;
519 } else if (mutation.type !== "attributes") {
520 win.mutationCount += 1;
524 // initialize the previousMutationCount
525 if (win.previousMutationCount == null) win.previousMutationCount = 0;
528 // watch the document body for the specified mutations
529 observer.observe(win.document.body, observerConfig);
531 // check the DOM for mutations up to 50 times for a maximum time of 5 seconds
534 function iteratee(item, callback) {
535 // keep track of the elapsed time so we can log it at the end of the command
536 timeElapsed = timeElapsed + 100;
538 // make each iteration of the loop 100ms apart
540 if (win.mutationCount === win.previousMutationCount) {
541 // pass an argument to the async callback to exit the loop
542 return callback("Resolved - DOM changes complete.");
543 } else if (win.previousMutationCount != null) {
544 // only set the previous count if the observer has checked the DOM at least once
545 win.previousMutationCount = win.mutationCount;
547 } else if (win.mutationCount === 0 && win.previousMutationCount == null && item === 4) {
548 // this is an early exit in case nothing is changing in the DOM. That way we only
549 // wait 500ms instead of the full 5 seconds when no DOM changes are occurring.
550 return callback("Resolved - Exiting early since no DOM changes were detected.");
552 // proceed to the next iteration
558 // Log the total wait time so users can see it
559 cy.log(`DOM mutations ${timeElapsed >= 5000 ? "did not complete" : "completed"} in ${timeElapsed} ms`);
561 // disconnect the observer and resolve the promise
562 observer.disconnect();