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, 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, root, wait } from '../miscs/miscs'
11 interface ServerInfo {
22 internalServerNumber: number
36 customConfigFile?: string
39 videoChannel?: VideoChannel
55 videos?: { id: number, uuid: string }[]
58 function parallelTests () {
59 return process.env.MOCHA_PARALLEL === 'true'
62 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
66 return new Promise<ServerInfo[]>(res => {
67 function anotherServerDone (serverNumber, app) {
68 apps[serverNumber - 1] = app
70 if (i === totalServers) {
75 for (let j = 1; j <= totalServers; j++) {
76 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
81 function flushTests (serverNumber?: number) {
82 return new Promise<void>((res, rej) => {
83 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
85 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
86 if (err || stderr) return rej(err || new Error(stderr))
93 function randomServer () {
97 return randomInt(low, high)
100 function randomRTMP () {
104 return randomInt(low, high)
107 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], silent = true) {
108 const parallel = parallelTests()
110 const internalServerNumber = parallel ? randomServer() : serverNumber
111 const rtmpPort = parallel ? randomRTMP() : 1936
112 const port = 9000 + internalServerNumber
114 await flushTests(internalServerNumber)
116 const server: ServerInfo = {
119 internalServerNumber,
123 url: `http://localhost:${port}`,
124 host: `localhost:${port}`,
125 hostname: 'localhost',
136 return runServer(server, configOverride, args, silent)
139 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], silent?: boolean) {
140 // These actions are async so we need to be sure that they have both been done
141 const serverRunString = {
142 'Server listening': false
144 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
145 serverRunString[key] = false
148 client_id: 'Client id: (.+)',
149 client_secret: 'Client secret: (.+)',
150 user_username: 'Username: (.+)',
151 user_password: 'User password: (.+)'
154 if (server.internalServerNumber !== server.serverNumber) {
155 const basePath = join(root(), 'config')
157 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
158 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
160 server.customConfigFile = tmpConfigFile
163 const configOverride: any = {}
165 if (server.parallel) {
166 Object.assign(configOverride, {
174 suffix: '_test' + server.internalServerNumber
177 tmp: `test${server.internalServerNumber}/tmp/`,
178 avatars: `test${server.internalServerNumber}/avatars/`,
179 videos: `test${server.internalServerNumber}/videos/`,
180 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
181 redundancy: `test${server.internalServerNumber}/redundancy/`,
182 logs: `test${server.internalServerNumber}/logs/`,
183 previews: `test${server.internalServerNumber}/previews/`,
184 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
185 torrents: `test${server.internalServerNumber}/torrents/`,
186 captions: `test${server.internalServerNumber}/captions/`,
187 cache: `test${server.internalServerNumber}/cache/`,
188 plugins: `test${server.internalServerNumber}/plugins/`
191 email: `admin${server.internalServerNumber}@example.com`
195 port: server.rtmpPort
201 if (configOverrideArg !== undefined) {
202 Object.assign(configOverride, configOverrideArg)
205 // Share the environment
206 const env = Object.create(process.env)
207 env['NODE_ENV'] = 'test'
208 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
209 env['NODE_CONFIG'] = JSON.stringify(configOverride)
217 return new Promise<ServerInfo>(res => {
218 server.app = fork(join(root(), 'dist', 'server.js'), args, options)
219 server.app.stdout.on('data', function onStdout (data) {
220 let dontContinue = false
222 // Capture things if we want to
223 for (const key of Object.keys(regexps)) {
224 const regexp = regexps[key]
225 const matches = data.toString().match(regexp)
226 if (matches !== null) {
227 if (key === 'client_id') server.client.id = matches[1]
228 else if (key === 'client_secret') server.client.secret = matches[1]
229 else if (key === 'user_username') server.user.username = matches[1]
230 else if (key === 'user_password') server.user.password = matches[1]
234 // Check if all required sentences are here
235 for (const key of Object.keys(serverRunString)) {
236 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
237 if (serverRunString[key] === false) dontContinue = true
240 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
241 if (dontContinue === true) return
243 if (silent === false) {
244 console.log(data.toString())
246 server.app.stdout.removeListener('data', onStdout)
249 process.on('exit', () => {
251 process.kill(server.app.pid)
252 } catch { /* empty */ }
260 async function reRunServer (server: ServerInfo, configOverride?: any) {
261 const newServer = await runServer(server, configOverride)
262 server.app = newServer.app
267 function checkTmpIsEmpty (server: ServerInfo) {
268 return checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css' ])
271 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
272 const testDirectory = 'test' + server.internalServerNumber
274 const directoryPath = join(root(), testDirectory, directory)
276 const directoryExists = await pathExists(directoryPath)
277 expect(directoryExists).to.be.true
279 const files = await readdir(directoryPath)
280 const filtered = files.filter(f => exceptions.includes(f) === false)
282 expect(filtered).to.have.lengthOf(0)
285 function killallServers (servers: ServerInfo[]) {
286 for (const server of servers) {
287 if (!server.app) continue
289 process.kill(-server.app.pid)
294 function cleanupTests (servers: ServerInfo[]) {
295 killallServers(servers)
297 const p: Promise<any>[] = []
298 for (const server of servers) {
299 if (server.parallel) {
300 p.push(flushTests(server.internalServerNumber))
303 if (server.customConfigFile) {
304 p.push(remove(server.customConfigFile))
308 return Promise.all(p)
311 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
312 const logfile = buildServerDirectory(server, 'logs/peertube.log')
315 const buf = await readFile(logfile)
317 const matches = buf.toString().match(new RegExp(str, 'g'))
318 if (matches && matches.length === count) return
319 if (matches && strictCount === false && matches.length >= count) return
325 async function getServerFileSize (server: ServerInfo, subPath: string) {
326 const path = buildServerDirectory(server, subPath)
328 return getFileSize(path)
331 // ---------------------------------------------------------------------------
334 checkDirectoryIsEmpty,
340 flushAndRunMultipleServers,