Merge branch '18215-collection-update-without-manifest' into main.
[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     "createCollection", (token, data) => {
138         return cy.createResource(token, 'collections', {
139             collection: JSON.stringify(data),
140             ensure_unique_name: true
141         })
142     }
143 )
144
145 Cypress.Commands.add(
146     "updateCollection", (token, uuid, data) => {
147         return cy.updateResource(token, 'collections', uuid, {
148             collection: JSON.stringify(data)
149         })
150     }
151 )
152
153 Cypress.Commands.add(
154     "createResource", (token, suffix, data) => {
155         return cy.doRequest('POST', '/arvados/v1/' + suffix, data, null, token, true)
156             .its('body').as('resource')
157             .then(function () {
158                 createdResources.push({suffix, uuid: this.resource.uuid});
159                 return this.resource;
160             })
161     }
162 )
163
164 Cypress.Commands.add(
165     "deleteResource", (token, suffix, uuid, failOnStatusCode = true) => {
166         return cy.doRequest('DELETE', '/arvados/v1/' + suffix + '/' + uuid, null, null, token, false, true, failOnStatusCode)
167             .its('body').as('resource')
168             .then(function () {
169                 return this.resource;
170             })
171     }
172 )
173
174 Cypress.Commands.add(
175     "updateResource", (token, suffix, uuid, data) => {
176         return cy.doRequest('PUT', '/arvados/v1/' + suffix + '/' + uuid, data, null, token, true)
177             .its('body').as('resource')
178             .then(function () {
179                 return this.resource;
180             })
181     }
182 )
183
184 Cypress.Commands.add(
185     "loginAs", (user) => {
186         cy.clearCookies()
187         cy.clearLocalStorage()
188         cy.visit(`/token/?api_token=${user.token}`);
189         cy.url({timeout: 10000}).should('contain', '/projects/');
190         cy.get('div#root').should('contain', 'Arvados Workbench (zzzzz)');
191         cy.get('div#root').should('not.contain', 'Your account is inactive');
192     }
193 )
194
195 Cypress.Commands.add(
196     "testEditProjectOrCollection", (container, oldName, newName, newDescription, isProject = true) => {
197         cy.get(container).contains(oldName).rightclick();
198         cy.get('[data-cy=context-menu]').contains(isProject ? 'Edit project' : 'Edit collection').click();
199         cy.get('[data-cy=form-dialog]').within(() => {
200             cy.get('input[name=name]').clear().type(newName);
201             cy.get(isProject ? 'div[contenteditable=true]' : 'input[name=description]').clear().type(newDescription);
202             cy.get('[data-cy=form-submit-btn]').click();
203         });
204
205         cy.get(container).contains(newName).rightclick();
206         cy.get('[data-cy=context-menu]').contains(isProject ? 'Edit project' : 'Edit collection').click();
207         cy.get('[data-cy=form-dialog]').within(() => {
208             cy.get('input[name=name]').should('have.value', newName);
209
210             if (isProject) {
211                 cy.get('span[data-text=true]').contains(newDescription);
212             } else {
213                 cy.get('input[name=description]').should('have.value', newDescription);
214             }
215
216             cy.get('[data-cy=form-cancel-btn]').click();
217         });
218     }
219 )
220
221 Cypress.Commands.add(
222     "doSearch", (searchTerm) => {
223         cy.get('[data-cy=searchbar-input-field]').type(`{selectall}${searchTerm}{enter}`);
224     }
225 )
226
227 Cypress.Commands.add(
228     "goToPath", (path) => {
229         return cy.window().its('appHistory').invoke('push', path);
230     }
231 )
232
233 Cypress.Commands.add('getAll', (...elements) => {
234     const promise = cy.wrap([], { log: false })
235
236     for (let element of elements) {
237         promise.then(arr => cy.get(element).then(got => cy.wrap([...arr, got])))
238     }
239
240     return promise
241 })
242
243 Cypress.Commands.add('shareWith', (srcUserToken, targetUserUUID, itemUUID, permission = 'can_write') => {
244     cy.createLink(srcUserToken, {
245         name: permission,
246         link_class: 'permission',
247         head_uuid: itemUUID,
248         tail_uuid: targetUserUUID
249     });
250 })
251
252 Cypress.Commands.add('addToFavorites', (userToken, userUUID, itemUUID) => {
253     cy.createLink(userToken, {
254         head_uuid: itemUUID,
255         link_class: 'star',
256         name: '',
257         owner_uuid: userUUID,
258         tail_uuid: userUUID,
259     });
260 })
261
262 Cypress.Commands.add('createProject', ({
263     owningUser,
264     targetUser,
265     projectName,
266     canWrite,
267     addToFavorites
268 }) => {
269     const writePermission = canWrite ? 'can_write' : 'can_read';
270
271     cy.createGroup(owningUser.token, {
272         name: `${projectName} ${Math.floor(Math.random() * 999999)}`,
273         group_class: 'project',
274     }).as(`${projectName}`).then((project) => {
275         if (targetUser && targetUser !== owningUser) {
276             cy.shareWith(owningUser.token, targetUser.user.uuid, project.uuid, writePermission);
277         }
278         if (addToFavorites) {
279             const user = targetUser ? targetUser : owningUser;
280             cy.addToFavorites(user.token, user.user.uuid, project.uuid);
281         }
282     });
283 });