commands.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. /**
  2. * @copyright Copyright (c) 2022 John Molakvoæ <skjnldsv@protonmail.com>
  3. *
  4. * @author John Molakvoæ <skjnldsv@protonmail.com>
  5. *
  6. * @license AGPL-3.0-or-later
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU Affero General Public License as
  10. * published by the Free Software Foundation, either version 3 of the
  11. * License, or (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU Affero General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. // eslint-disable-next-line n/no-extraneous-import
  23. import type { AxiosResponse } from 'axios'
  24. import axios from '@nextcloud/axios'
  25. import { addCommands, User } from '@nextcloud/cypress'
  26. import { basename } from 'path'
  27. // Add custom commands
  28. import 'cypress-if'
  29. import 'cypress-wait-until'
  30. addCommands()
  31. // Register this file's custom commands types
  32. declare global {
  33. // eslint-disable-next-line @typescript-eslint/no-namespace
  34. namespace Cypress {
  35. // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unused-vars
  36. interface Chainable<Subject = any> {
  37. /**
  38. * Enable or disable a given user
  39. */
  40. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  41. enableUser(user: User, enable?: boolean): Cypress.Chainable<Cypress.Response<any>>,
  42. /**
  43. * Upload a file from the fixtures folder to a given user storage.
  44. * **Warning**: Using this function will reset the previous session
  45. */
  46. uploadFile(user: User, fixture?: string, mimeType?: string, target?: string): Cypress.Chainable<void>,
  47. /**
  48. * Upload a raw content to a given user storage.
  49. * **Warning**: Using this function will reset the previous session
  50. */
  51. uploadContent(user: User, content: Blob, mimeType: string, target: string, mtime?: number): Cypress.Chainable<AxiosResponse>,
  52. /**
  53. * Create a new directory
  54. * **Warning**: Using this function will reset the previous session
  55. */
  56. mkdir(user: User, target: string): Cypress.Chainable<void>,
  57. /**
  58. * Set a file as favorite (or remove from favorite)
  59. */
  60. setFileAsFavorite(user: User, target: string, favorite?: boolean): Cypress.Chainable<void>,
  61. /**
  62. * Reset the admin theming entirely.
  63. * **Warning**: Using this function will reset the previous session
  64. */
  65. resetAdminTheming(): Cypress.Chainable<void>,
  66. /**
  67. * Reset the user theming settings.
  68. * If provided, will clear session and login as the given user.
  69. * **Warning**: Providing a user will reset the previous session.
  70. */
  71. resetUserTheming(user?: User): Cypress.Chainable<void>,
  72. /**
  73. * Run an occ command in the docker container.
  74. */
  75. runOccCommand(command: string, options?: Partial<Cypress.ExecOptions>): Cypress.Chainable<Cypress.Exec>,
  76. }
  77. }
  78. }
  79. const url = (Cypress.config('baseUrl') || '').replace(/\/index.php\/?$/g, '')
  80. Cypress.env('baseUrl', url)
  81. /**
  82. * Enable or disable a user
  83. * TODO: standardise in @nextcloud/cypress
  84. *
  85. * @param {User} user the user to dis- / enable
  86. * @param {boolean} enable True if the user should be enable, false to disable
  87. */
  88. Cypress.Commands.add('enableUser', (user: User, enable = true) => {
  89. const url = `${Cypress.config('baseUrl')}/ocs/v2.php/cloud/users/${user.userId}/${enable ? 'enable' : 'disable'}`.replace('index.php/', '')
  90. return cy.request({
  91. method: 'PUT',
  92. url,
  93. form: true,
  94. auth: {
  95. user: 'admin',
  96. password: 'admin',
  97. },
  98. headers: {
  99. 'OCS-ApiRequest': 'true',
  100. 'Content-Type': 'application/x-www-form-urlencoded',
  101. },
  102. }).then((response) => {
  103. cy.log(`Enabled user ${user}`, response.status)
  104. return cy.wrap(response)
  105. })
  106. })
  107. /**
  108. * cy.uploadedFile - uploads a file from the fixtures folder
  109. * TODO: standardise in @nextcloud/cypress
  110. *
  111. * @param {User} user the owner of the file, e.g. admin
  112. * @param {string} fixture the fixture file name, e.g. image1.jpg
  113. * @param {string} mimeType e.g. image/png
  114. * @param {string} [target] the target of the file relative to the user root
  115. */
  116. Cypress.Commands.add('uploadFile', (user, fixture = 'image.jpg', mimeType = 'image/jpeg', target = `/${fixture}`) => {
  117. // get fixture
  118. return cy.fixture(fixture, 'base64').then(async file => {
  119. // convert the base64 string to a blob
  120. const blob = Cypress.Blob.base64StringToBlob(file, mimeType)
  121. cy.uploadContent(user, blob, mimeType, target)
  122. })
  123. })
  124. Cypress.Commands.add('setFileAsFavorite', (user: User, target: string, favorite = true) => {
  125. // eslint-disable-next-line cypress/unsafe-to-chain-command
  126. cy.clearAllCookies()
  127. .then(async () => {
  128. try {
  129. const rootPath = `${Cypress.env('baseUrl')}/remote.php/dav/files/${encodeURIComponent(user.userId)}`
  130. const filePath = target.split('/').map(encodeURIComponent).join('/')
  131. const response = await axios({
  132. url: `${rootPath}${filePath}`,
  133. method: 'PROPPATCH',
  134. auth: {
  135. username: user.userId,
  136. password: user.password,
  137. },
  138. headers: {
  139. 'Content-Type': 'application/xml',
  140. },
  141. data: `<?xml version="1.0"?>
  142. <d:propertyupdate xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">
  143. <d:set>
  144. <d:prop>
  145. <oc:favorite>${favorite ? 1 : 0}</oc:favorite>
  146. </d:prop>
  147. </d:set>
  148. </d:propertyupdate>`
  149. })
  150. cy.log(`Created directory ${target}`, response)
  151. } catch (error) {
  152. cy.log('error', error)
  153. throw new Error('Unable to process fixture')
  154. }
  155. })
  156. })
  157. Cypress.Commands.add('mkdir', (user: User, target: string) => {
  158. // eslint-disable-next-line cypress/unsafe-to-chain-command
  159. cy.clearCookies()
  160. .then(async () => {
  161. try {
  162. const rootPath = `${Cypress.env('baseUrl')}/remote.php/dav/files/${encodeURIComponent(user.userId)}`
  163. const filePath = target.split('/').map(encodeURIComponent).join('/')
  164. const response = await axios({
  165. url: `${rootPath}${filePath}`,
  166. method: 'MKCOL',
  167. auth: {
  168. username: user.userId,
  169. password: user.password,
  170. },
  171. })
  172. cy.log(`Created directory ${target}`, response)
  173. } catch (error) {
  174. cy.log('error', error)
  175. throw new Error('Unable to process fixture')
  176. }
  177. })
  178. })
  179. /**
  180. * cy.uploadedContent - uploads a raw content
  181. * TODO: standardise in @nextcloud/cypress
  182. *
  183. * @param {User} user the owner of the file, e.g. admin
  184. * @param {Blob} blob the content to upload
  185. * @param {string} mimeType e.g. image/png
  186. * @param {string} target the target of the file relative to the user root
  187. */
  188. Cypress.Commands.add('uploadContent', (user, blob, mimeType, target, mtime = undefined) => {
  189. // eslint-disable-next-line cypress/unsafe-to-chain-command
  190. cy.clearCookies()
  191. .then(async () => {
  192. const fileName = basename(target)
  193. // Process paths
  194. const rootPath = `${Cypress.env('baseUrl')}/remote.php/dav/files/${encodeURIComponent(user.userId)}`
  195. const filePath = target.split('/').map(encodeURIComponent).join('/')
  196. try {
  197. const file = new File([blob], fileName, { type: mimeType })
  198. const response = await axios({
  199. url: `${rootPath}${filePath}`,
  200. method: 'PUT',
  201. data: file,
  202. headers: {
  203. 'Content-Type': mimeType,
  204. 'X-OC-MTime': mtime ? `${mtime}` : undefined,
  205. },
  206. auth: {
  207. username: user.userId,
  208. password: user.password,
  209. },
  210. })
  211. cy.log(`Uploaded content as ${fileName}`, response)
  212. return response
  213. } catch (error) {
  214. cy.log('error', error)
  215. throw new Error('Unable to process fixture')
  216. }
  217. })
  218. })
  219. /**
  220. * Reset the admin theming entirely
  221. */
  222. Cypress.Commands.add('resetAdminTheming', () => {
  223. const admin = new User('admin', 'admin')
  224. cy.clearCookies()
  225. cy.login(admin)
  226. // Clear all settings
  227. cy.request('/csrftoken').then(({ body }) => {
  228. const requestToken = body.token
  229. axios({
  230. method: 'POST',
  231. url: '/index.php/apps/theming/ajax/undoAllChanges',
  232. headers: {
  233. requesttoken: requestToken,
  234. },
  235. })
  236. })
  237. // Clear admin session
  238. cy.clearCookies()
  239. })
  240. /**
  241. * Reset the current or provided user theming settings
  242. * It does not reset the theme config as it is enforced in the
  243. * server config for cypress testing.
  244. */
  245. Cypress.Commands.add('resetUserTheming', (user?: User) => {
  246. if (user) {
  247. cy.clearCookies()
  248. cy.login(user)
  249. }
  250. // Reset background config
  251. cy.request('/csrftoken').then(({ body }) => {
  252. const requestToken = body.token
  253. cy.request({
  254. method: 'POST',
  255. url: '/apps/theming/background/default',
  256. headers: {
  257. requesttoken: requestToken,
  258. },
  259. })
  260. })
  261. if (user) {
  262. // Clear current session
  263. cy.clearCookies()
  264. }
  265. })
  266. Cypress.Commands.add('runOccCommand', (command: string, options?: Partial<Cypress.ExecOptions>) => {
  267. const env = Object.entries(options?.env ?? {}).map(([name, value]) => `-e '${name}=${value}'`).join(' ')
  268. return cy.exec(`docker exec --user www-data ${env} nextcloud-cypress-tests-server php ./occ ${command}`, options)
  269. })