]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - shared/extra-utils/server/servers.ts
Add hook filters tests
[github/Chocobozzz/PeerTube.git] / shared / extra-utils / server / servers.ts
1 /* tslint:disable:no-unused-expression */
2
3 import { ChildProcess, exec, fork } from 'child_process'
4 import { join } from 'path'
5 import { root, wait } from '../miscs/miscs'
6 import { copy, pathExists, readdir, readFile, remove } from 'fs-extra'
7 import { existsSync } from 'fs'
8 import { expect } from 'chai'
9 import { VideoChannel } from '../../models/videos'
10 import { randomInt } from '../../core-utils/miscs/miscs'
11
12 interface ServerInfo {
13 app: ChildProcess,
14 url: string
15 host: string
16
17 port: number
18 parallel: boolean
19 internalServerNumber: number
20 serverNumber: number
21
22 client: {
23 id: string,
24 secret: string
25 }
26
27 user: {
28 username: string,
29 password: string,
30 email?: string
31 }
32
33 customConfigFile?: string
34
35 accessToken?: string
36 videoChannel?: VideoChannel
37
38 video?: {
39 id: number
40 uuid: string
41 name: string
42 account: {
43 name: string
44 }
45 }
46
47 remoteVideo?: {
48 id: number
49 uuid: string
50 }
51
52 videos?: { id: number, uuid: string }[]
53 }
54
55 function parallelTests () {
56 return process.env.MOCHA_PARALLEL === 'true'
57 }
58
59 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
60 let apps = []
61 let i = 0
62
63 return new Promise<ServerInfo[]>(res => {
64 function anotherServerDone (serverNumber, app) {
65 apps[serverNumber - 1] = app
66 i++
67 if (i === totalServers) {
68 return res(apps)
69 }
70 }
71
72 for (let j = 1; j <= totalServers; j++) {
73 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
74 }
75 })
76 }
77
78 function flushTests (serverNumber?: number) {
79 return new Promise<void>((res, rej) => {
80 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
81
82 return exec('npm run clean:server:test' + suffix, err => {
83 if (err) return rej(err)
84
85 return res()
86 })
87 })
88 }
89
90 function randomServer () {
91 const low = 10
92 const high = 10000
93
94 return randomInt(low, high)
95 }
96
97 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = []) {
98 const parallel = parallelTests()
99
100 const internalServerNumber = parallel ? randomServer() : serverNumber
101 const port = 9000 + internalServerNumber
102
103 await flushTests(internalServerNumber)
104
105 const server: ServerInfo = {
106 app: null,
107 port,
108 internalServerNumber,
109 parallel,
110 serverNumber,
111 url: `http://localhost:${port}`,
112 host: `localhost:${port}`,
113 client: {
114 id: null,
115 secret: null
116 },
117 user: {
118 username: null,
119 password: null
120 }
121 }
122
123 return runServer(server, configOverride, args)
124 }
125
126 async function runServer (server: ServerInfo, configOverrideArg?: any, args = []) {
127 // These actions are async so we need to be sure that they have both been done
128 const serverRunString = {
129 'Server listening': false
130 }
131 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
132 serverRunString[key] = false
133
134 const regexps = {
135 client_id: 'Client id: (.+)',
136 client_secret: 'Client secret: (.+)',
137 user_username: 'Username: (.+)',
138 user_password: 'User password: (.+)'
139 }
140
141 if (server.internalServerNumber !== server.serverNumber) {
142 const basePath = join(root(), 'config')
143
144 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
145 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
146
147 server.customConfigFile = tmpConfigFile
148 }
149
150 const configOverride: any = {}
151
152 if (server.parallel) {
153 Object.assign(configOverride, {
154 listen: {
155 port: server.port
156 },
157 webserver: {
158 port: server.port
159 },
160 database: {
161 suffix: '_test' + server.internalServerNumber
162 },
163 storage: {
164 tmp: `test${server.internalServerNumber}/tmp/`,
165 avatars: `test${server.internalServerNumber}/avatars/`,
166 videos: `test${server.internalServerNumber}/videos/`,
167 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
168 redundancy: `test${server.internalServerNumber}/redundancy/`,
169 logs: `test${server.internalServerNumber}/logs/`,
170 previews: `test${server.internalServerNumber}/previews/`,
171 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
172 torrents: `test${server.internalServerNumber}/torrents/`,
173 captions: `test${server.internalServerNumber}/captions/`,
174 cache: `test${server.internalServerNumber}/cache/`,
175 plugins: `test${server.internalServerNumber}/plugins/`
176 },
177 admin: {
178 email: `admin${server.internalServerNumber}@example.com`
179 }
180 })
181 }
182
183 if (configOverrideArg !== undefined) {
184 Object.assign(configOverride, configOverrideArg)
185 }
186
187 // Share the environment
188 const env = Object.create(process.env)
189 env['NODE_ENV'] = 'test'
190 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
191 env['NODE_CONFIG'] = JSON.stringify(configOverride)
192
193 const options = {
194 silent: true,
195 env,
196 detached: true
197 }
198
199 return new Promise<ServerInfo>(res => {
200 server.app = fork(join(root(), 'dist', 'server.js'), args, options)
201 server.app.stdout.on('data', function onStdout (data) {
202 let dontContinue = false
203
204 // Capture things if we want to
205 for (const key of Object.keys(regexps)) {
206 const regexp = regexps[ key ]
207 const matches = data.toString().match(regexp)
208 if (matches !== null) {
209 if (key === 'client_id') server.client.id = matches[ 1 ]
210 else if (key === 'client_secret') server.client.secret = matches[ 1 ]
211 else if (key === 'user_username') server.user.username = matches[ 1 ]
212 else if (key === 'user_password') server.user.password = matches[ 1 ]
213 }
214 }
215
216 // Check if all required sentences are here
217 for (const key of Object.keys(serverRunString)) {
218 if (data.toString().indexOf(key) !== -1) serverRunString[ key ] = true
219 if (serverRunString[ key ] === false) dontContinue = true
220 }
221
222 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
223 if (dontContinue === true) return
224
225 server.app.stdout.removeListener('data', onStdout)
226
227 process.on('exit', () => {
228 try {
229 process.kill(server.app.pid)
230 } catch { /* empty */ }
231 })
232
233 res(server)
234 })
235 })
236 }
237
238 async function reRunServer (server: ServerInfo, configOverride?: any) {
239 const newServer = await runServer(server, configOverride)
240 server.app = newServer.app
241
242 return server
243 }
244
245 function checkTmpIsEmpty (server: ServerInfo) {
246 return checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css' ])
247 }
248
249 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
250 const testDirectory = 'test' + server.internalServerNumber
251
252 const directoryPath = join(root(), testDirectory, directory)
253
254 const directoryExists = await pathExists(directoryPath)
255 expect(directoryExists).to.be.true
256
257 const files = await readdir(directoryPath)
258 const filtered = files.filter(f => exceptions.includes(f) === false)
259
260 expect(filtered).to.have.lengthOf(0)
261 }
262
263 function killallServers (servers: ServerInfo[]) {
264 for (const server of servers) {
265 if (!server.app) continue
266
267 process.kill(-server.app.pid)
268 server.app = null
269 }
270 }
271
272 function cleanupTests (servers: ServerInfo[]) {
273 killallServers(servers)
274
275 const p: Promise<any>[] = []
276 for (const server of servers) {
277 if (server.parallel) {
278 p.push(flushTests(server.internalServerNumber))
279 }
280
281 if (server.customConfigFile) {
282 p.push(remove(server.customConfigFile))
283 }
284 }
285
286 return Promise.all(p)
287 }
288
289 async function waitUntilLog (server: ServerInfo, str: string, count = 1) {
290 const logfile = join(root(), 'test' + server.internalServerNumber, 'logs/peertube.log')
291
292 while (true) {
293 const buf = await readFile(logfile)
294
295 const matches = buf.toString().match(new RegExp(str, 'g'))
296 if (matches && matches.length === count) return
297
298 await wait(1000)
299 }
300 }
301
302 // ---------------------------------------------------------------------------
303
304 export {
305 checkDirectoryIsEmpty,
306 checkTmpIsEmpty,
307 ServerInfo,
308 parallelTests,
309 cleanupTests,
310 flushAndRunMultipleServers,
311 flushTests,
312 flushAndRunServer,
313 killallServers,
314 reRunServer,
315 waitUntilLog
316 }