commands.ts 8.2 KB

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