1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
|
/**
* SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
// eslint-disable-next-line n/no-extraneous-import
import axios from 'axios'
import { addCommands, User } from '@nextcloud/cypress'
import { basename } from 'path'
// Add custom commands
import '@testing-library/cypress/add-commands'
import 'cypress-if'
import 'cypress-wait-until'
addCommands()
const url = (Cypress.config('baseUrl') || '').replace(/\/index.php\/?$/g, '')
Cypress.env('baseUrl', url)
/**
* Enable or disable a user
* TODO: standardize in @nextcloud/cypress
*
* @param {User} user the user to dis- / enable
* @param {boolean} enable True if the user should be enable, false to disable
*/
Cypress.Commands.add('enableUser', (user: User, enable = true) => {
const url = `${Cypress.config('baseUrl')}/ocs/v2.php/cloud/users/${user.userId}/${enable ? 'enable' : 'disable'}`.replace('index.php/', '')
return cy.request({
method: 'PUT',
url,
form: true,
auth: {
user: 'admin',
password: 'admin',
},
headers: {
'OCS-ApiRequest': 'true',
'Content-Type': 'application/x-www-form-urlencoded',
},
}).then((response) => {
cy.log(`Enabled user ${user}`, response.status)
return cy.wrap(response)
})
})
/**
* cy.uploadedFile - uploads a file from the fixtures folder
* TODO: standardize in @nextcloud/cypress
*
* @param {User} user the owner of the file, e.g. admin
* @param {string} fixture the fixture file name, e.g. image1.jpg
* @param {string} mimeType e.g. image/png
* @param {string} [target] the target of the file relative to the user root
*/
Cypress.Commands.add('uploadFile', (user, fixture = 'image.jpg', mimeType = 'image/jpeg', target = `/${fixture}`) => {
// get fixture
return cy.fixture(fixture, 'base64').then(async file => {
// convert the base64 string to a blob
const blob = Cypress.Blob.base64StringToBlob(file, mimeType)
cy.uploadContent(user, blob, mimeType, target)
})
})
Cypress.Commands.add('setFileAsFavorite', (user: User, target: string, favorite = true) => {
// eslint-disable-next-line cypress/unsafe-to-chain-command
cy.clearAllCookies()
.then(async () => {
try {
const rootPath = `${Cypress.env('baseUrl')}/remote.php/dav/files/${encodeURIComponent(user.userId)}`
const filePath = target.split('/').map(encodeURIComponent).join('/')
const response = await axios({
url: `${rootPath}${filePath}`,
method: 'PROPPATCH',
auth: {
username: user.userId,
password: user.password,
},
headers: {
'Content-Type': 'application/xml',
},
data: `<?xml version="1.0"?>
<d:propertyupdate xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">
<d:set>
<d:prop>
<oc:favorite>${favorite ? 1 : 0}</oc:favorite>
</d:prop>
</d:set>
</d:propertyupdate>`,
})
cy.log(`Created directory ${target}`, response)
} catch (error) {
cy.log('error', error)
throw new Error('Unable to process fixture')
}
})
})
Cypress.Commands.add('mkdir', (user: User, target: string) => {
// eslint-disable-next-line cypress/unsafe-to-chain-command
cy.clearCookies()
.then(async () => {
try {
const rootPath = `${Cypress.env('baseUrl')}/remote.php/dav/files/${encodeURIComponent(user.userId)}`
const filePath = target.split('/').map(encodeURIComponent).join('/')
const response = await axios({
url: `${rootPath}${filePath}`,
method: 'MKCOL',
auth: {
username: user.userId,
password: user.password,
},
})
cy.log(`Created directory ${target}`, response)
} catch (error) {
cy.log('error', error)
throw new Error('Unable to create directory')
}
})
})
/**
* cy.uploadedContent - uploads a raw content
* TODO: standardize in @nextcloud/cypress
*
* @param {User} user the owner of the file, e.g. admin
* @param {Blob} blob the content to upload
* @param {string} mimeType e.g. image/png
* @param {string} target the target of the file relative to the user root
*/
Cypress.Commands.add('uploadContent', (user: User, blob: Blob, mimeType: string, target: string, mtime?: number) => {
cy.clearCookies()
return cy.then(async () => {
const fileName = basename(target)
// Process paths
const rootPath = `${Cypress.env('baseUrl')}/remote.php/dav/files/${encodeURIComponent(user.userId)}`
const filePath = target.split('/').map(encodeURIComponent).join('/')
try {
const file = new File([blob], fileName, { type: mimeType })
const response = await axios({
url: `${rootPath}${filePath}`,
method: 'PUT',
data: file,
headers: {
'Content-Type': mimeType,
'X-OC-MTime': mtime ? `${mtime}` : undefined,
},
auth: {
username: user.userId,
password: user.password,
},
})
cy.log(`Uploaded content as ${fileName}`, response)
return response
} catch (error) {
cy.log('error', error)
throw new Error('Unable to process fixture')
}
})
})
/**
* Reset the admin theming entirely
*/
Cypress.Commands.add('resetAdminTheming', () => {
const admin = new User('admin', 'admin')
cy.clearCookies()
cy.login(admin)
// Clear all settings
cy.request('/csrftoken').then(({ body }) => {
const requestToken = body.token
axios({
method: 'POST',
url: '/index.php/apps/theming/ajax/undoAllChanges',
headers: {
requesttoken: requestToken,
},
})
})
// Clear admin session
cy.clearCookies()
})
/**
* Reset the current or provided user theming settings
* It does not reset the theme config as it is enforced in the
* server config for cypress testing.
*/
Cypress.Commands.add('resetUserTheming', (user?: User) => {
if (user) {
cy.clearCookies()
cy.login(user)
}
// Reset background config
cy.request('/csrftoken').then(({ body }) => {
const requestToken = body.token
cy.request({
method: 'POST',
url: '/apps/theming/background/default',
headers: {
requesttoken: requestToken,
},
})
})
if (user) {
// Clear current session
cy.clearCookies()
}
})
Cypress.Commands.add('runOccCommand', (command: string, options?: Partial<Cypress.ExecOptions>) => {
const env = Object.entries(options?.env ?? {}).map(([name, value]) => `-e '${name}=${value}'`).join(' ')
return cy.exec(`docker exec --user www-data ${env} nextcloud-cypress-tests-server php ./occ ${command}`, options)
})
Cypress.Commands.add('userFileExists', (user: string, path: string) => {
user.replaceAll('"', '\\"')
path.replaceAll('"', '\\"').replaceAll(/^\/+/gm, '')
return cy.exec(`docker exec --user www-data nextcloud-cypress-tests-server stat --printf="%s" "data/${user}/files/${path}"`, { failOnNonZeroExit: true })
.then((exec) => Number.parseInt(exec.stdout || '0'))
})
Cypress.Commands.add('backupDB', (): Cypress.Chainable<string> => {
const randomString = Math.random().toString(36).substring(7)
cy.exec(`docker exec --user www-data nextcloud-cypress-tests-server cp /var/www/html/data/owncloud.db /var/www/html/data/owncloud.db-${randomString}`)
cy.log(`Created snapshot ${randomString}`)
return cy.wrap(randomString)
})
Cypress.Commands.add('restoreDB', (snapshot: string = 'init') => {
cy.exec(`docker exec --user www-data nextcloud-cypress-tests-server cp /var/www/html/data/owncloud.db-${snapshot} /var/www/html/data/owncloud.db`)
cy.log(`Restored snapshot ${snapshot}`)
})
Cypress.Commands.add('backupData', (users: string[] = ['admin']) => {
const snapshot = Math.random().toString(36).substring(7)
const toBackup = users.map((user) => `'${user.replaceAll('\\', '').replaceAll('\'', '\\\'')}'`).join(' ')
cy.exec(`docker exec --user www-data rm /var/www/html/data/data-${snapshot}.tar`, { failOnNonZeroExit: false })
cy.exec(`docker exec --user www-data --workdir /var/www/html/data nextcloud-cypress-tests-server tar cf /var/www/html/data/data-${snapshot}.tar ${toBackup}`)
return cy.wrap(snapshot as string)
})
Cypress.Commands.add('restoreData', (snapshot?: string) => {
snapshot = snapshot ?? 'init'
snapshot.replaceAll('\\', '').replaceAll('"', '\\"')
cy.exec(`docker exec --user www-data --workdir /var/www/html/data nextcloud-cypress-tests-server rm -vfr $(tar --exclude='*/*' -tf '/var/www/html/data/data-${snapshot}.tar')`)
cy.exec(`docker exec --user www-data --workdir /var/www/html/data nextcloud-cypress-tests-server tar -xf '/var/www/html/data/data-${snapshot}.tar'`)
})
|