1 /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */
3 import { expect } from 'chai'
4 import { ChildProcess, exec, fork } from 'child_process'
5 import { copy, ensureDir, pathExists, readdir, readFile, remove } from 'fs-extra'
6 import { join } from 'path'
7 import { randomInt } from '../../core-utils/miscs/miscs'
8 import { VideoChannel } from '../../models/videos'
9 import { buildServerDirectory, getFileSize, isGithubCI, root, wait } from '../miscs/miscs'
10 import { makeGetRequest } from '../requests/requests'
12 interface ServerInfo {
23 internalServerNumber: number
37 customConfigFile?: string
41 videoChannel?: VideoChannel
58 videos?: { id: number, uuid: string }[]
61 function parallelTests () {
62 return process.env.MOCHA_PARALLEL === 'true'
65 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
69 return new Promise<ServerInfo[]>(res => {
70 function anotherServerDone (serverNumber, app) {
71 apps[serverNumber - 1] = app
73 if (i === totalServers) {
78 for (let j = 1; j <= totalServers; j++) {
79 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
84 function flushTests (serverNumber?: number) {
85 return new Promise<void>((res, rej) => {
86 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
88 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
89 if (err || stderr) return rej(err || new Error(stderr))
96 function randomServer () {
100 return randomInt(low, high)
103 function randomRTMP () {
107 return randomInt(low, high)
110 type RunServerOptions = {
115 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
116 const parallel = parallelTests()
118 const internalServerNumber = parallel ? randomServer() : serverNumber
119 const rtmpPort = parallel ? randomRTMP() : 1936
120 const port = 9000 + internalServerNumber
122 await flushTests(internalServerNumber)
124 const server: ServerInfo = {
127 internalServerNumber,
131 url: `http://localhost:${port}`,
132 host: `localhost:${port}`,
133 hostname: 'localhost',
144 return runServer(server, configOverride, args, options)
147 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
148 // These actions are async so we need to be sure that they have both been done
149 const serverRunString = {
150 'HTTP server listening': false
152 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
153 serverRunString[key] = false
156 client_id: 'Client id: (.+)',
157 client_secret: 'Client secret: (.+)',
158 user_username: 'Username: (.+)',
159 user_password: 'User password: (.+)'
162 if (server.internalServerNumber !== server.serverNumber) {
163 const basePath = join(root(), 'config')
165 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
166 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
168 server.customConfigFile = tmpConfigFile
171 const configOverride: any = {}
173 if (server.parallel) {
174 Object.assign(configOverride, {
182 suffix: '_test' + server.internalServerNumber
185 tmp: `test${server.internalServerNumber}/tmp/`,
186 avatars: `test${server.internalServerNumber}/avatars/`,
187 videos: `test${server.internalServerNumber}/videos/`,
188 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
189 redundancy: `test${server.internalServerNumber}/redundancy/`,
190 logs: `test${server.internalServerNumber}/logs/`,
191 previews: `test${server.internalServerNumber}/previews/`,
192 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
193 torrents: `test${server.internalServerNumber}/torrents/`,
194 captions: `test${server.internalServerNumber}/captions/`,
195 cache: `test${server.internalServerNumber}/cache/`,
196 plugins: `test${server.internalServerNumber}/plugins/`
199 email: `admin${server.internalServerNumber}@example.com`
203 port: server.rtmpPort
209 if (configOverrideArg !== undefined) {
210 Object.assign(configOverride, configOverrideArg)
213 // Share the environment
214 const env = Object.create(process.env)
215 env['NODE_ENV'] = 'test'
216 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
217 env['NODE_CONFIG'] = JSON.stringify(configOverride)
219 const forkOptions = {
223 execArgv: options.execArgv || []
226 return new Promise<ServerInfo>(res => {
227 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
228 server.app.stdout.on('data', function onStdout (data) {
229 let dontContinue = false
231 // Capture things if we want to
232 for (const key of Object.keys(regexps)) {
233 const regexp = regexps[key]
234 const matches = data.toString().match(regexp)
235 if (matches !== null) {
236 if (key === 'client_id') server.client.id = matches[1]
237 else if (key === 'client_secret') server.client.secret = matches[1]
238 else if (key === 'user_username') server.user.username = matches[1]
239 else if (key === 'user_password') server.user.password = matches[1]
243 // Check if all required sentences are here
244 for (const key of Object.keys(serverRunString)) {
245 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
246 if (serverRunString[key] === false) dontContinue = true
249 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
250 if (dontContinue === true) return
252 if (options.hideLogs === false) {
253 console.log(data.toString())
255 server.app.stdout.removeListener('data', onStdout)
258 process.on('exit', () => {
260 process.kill(server.app.pid)
261 } catch { /* empty */ }
269 async function reRunServer (server: ServerInfo, configOverride?: any) {
270 const newServer = await runServer(server, configOverride)
271 server.app = newServer.app
276 async function checkTmpIsEmpty (server: ServerInfo) {
277 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls' ])
279 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
280 await checkDirectoryIsEmpty(server, 'tmp/hls')
284 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
285 const testDirectory = 'test' + server.internalServerNumber
287 const directoryPath = join(root(), testDirectory, directory)
289 const directoryExists = await pathExists(directoryPath)
290 expect(directoryExists).to.be.true
292 const files = await readdir(directoryPath)
293 const filtered = files.filter(f => exceptions.includes(f) === false)
295 expect(filtered).to.have.lengthOf(0)
298 function killallServers (servers: ServerInfo[]) {
299 for (const server of servers) {
300 if (!server.app) continue
302 process.kill(-server.app.pid)
307 async function cleanupTests (servers: ServerInfo[]) {
308 killallServers(servers)
311 await ensureDir('artifacts')
314 const p: Promise<any>[] = []
315 for (const server of servers) {
317 const origin = await buildServerDirectory(server, 'logs/peertube.log')
318 const destname = `peertube-${server.internalServerNumber}.log`
319 console.log('Saving logs %s.', destname)
321 await copy(origin, join('artifacts', destname))
324 if (server.parallel) {
325 p.push(flushTests(server.internalServerNumber))
328 if (server.customConfigFile) {
329 p.push(remove(server.customConfigFile))
333 return Promise.all(p)
336 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
337 const logfile = buildServerDirectory(server, 'logs/peertube.log')
340 const buf = await readFile(logfile)
342 const matches = buf.toString().match(new RegExp(str, 'g'))
343 if (matches && matches.length === count) return
344 if (matches && strictCount === false && matches.length >= count) return
350 async function getServerFileSize (server: ServerInfo, subPath: string) {
351 const path = buildServerDirectory(server, subPath)
353 return getFileSize(path)
356 function makePingRequest (server: ServerInfo) {
357 return makeGetRequest({
359 path: '/api/v1/ping',
360 statusCodeExpected: 200
364 // ---------------------------------------------------------------------------
367 checkDirectoryIsEmpty,
373 flushAndRunMultipleServers,