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'
11 interface ServerInfo {
22 internalServerNumber: number
36 customConfigFile?: string
39 videoChannel?: VideoChannel
56 videos?: { id: number, uuid: string }[]
59 function parallelTests () {
60 return process.env.MOCHA_PARALLEL === 'true'
63 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
67 return new Promise<ServerInfo[]>(res => {
68 function anotherServerDone (serverNumber, app) {
69 apps[serverNumber - 1] = app
71 if (i === totalServers) {
76 for (let j = 1; j <= totalServers; j++) {
77 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
82 function flushTests (serverNumber?: number) {
83 return new Promise<void>((res, rej) => {
84 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
86 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
87 if (err || stderr) return rej(err || new Error(stderr))
94 function randomServer () {
98 return randomInt(low, high)
101 function randomRTMP () {
105 return randomInt(low, high)
108 type RunServerOptions = {
113 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
114 const parallel = parallelTests()
116 const internalServerNumber = parallel ? randomServer() : serverNumber
117 const rtmpPort = parallel ? randomRTMP() : 1936
118 const port = 9000 + internalServerNumber
120 await flushTests(internalServerNumber)
122 const server: ServerInfo = {
125 internalServerNumber,
129 url: `http://localhost:${port}`,
130 host: `localhost:${port}`,
131 hostname: 'localhost',
142 return runServer(server, configOverride, args, options)
145 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
146 // These actions are async so we need to be sure that they have both been done
147 const serverRunString = {
148 'Server listening': false
150 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
151 serverRunString[key] = false
154 client_id: 'Client id: (.+)',
155 client_secret: 'Client secret: (.+)',
156 user_username: 'Username: (.+)',
157 user_password: 'User password: (.+)'
160 if (server.internalServerNumber !== server.serverNumber) {
161 const basePath = join(root(), 'config')
163 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
164 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
166 server.customConfigFile = tmpConfigFile
169 const configOverride: any = {}
171 if (server.parallel) {
172 Object.assign(configOverride, {
180 suffix: '_test' + server.internalServerNumber
183 tmp: `test${server.internalServerNumber}/tmp/`,
184 avatars: `test${server.internalServerNumber}/avatars/`,
185 videos: `test${server.internalServerNumber}/videos/`,
186 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
187 redundancy: `test${server.internalServerNumber}/redundancy/`,
188 logs: `test${server.internalServerNumber}/logs/`,
189 previews: `test${server.internalServerNumber}/previews/`,
190 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
191 torrents: `test${server.internalServerNumber}/torrents/`,
192 captions: `test${server.internalServerNumber}/captions/`,
193 cache: `test${server.internalServerNumber}/cache/`,
194 plugins: `test${server.internalServerNumber}/plugins/`
197 email: `admin${server.internalServerNumber}@example.com`
201 port: server.rtmpPort
207 if (configOverrideArg !== undefined) {
208 Object.assign(configOverride, configOverrideArg)
211 // Share the environment
212 const env = Object.create(process.env)
213 env['NODE_ENV'] = 'test'
214 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
215 env['NODE_CONFIG'] = JSON.stringify(configOverride)
217 const forkOptions = {
221 execArgv: options.execArgv || []
224 return new Promise<ServerInfo>(res => {
225 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
226 server.app.stdout.on('data', function onStdout (data) {
227 let dontContinue = false
229 // Capture things if we want to
230 for (const key of Object.keys(regexps)) {
231 const regexp = regexps[key]
232 const matches = data.toString().match(regexp)
233 if (matches !== null) {
234 if (key === 'client_id') server.client.id = matches[1]
235 else if (key === 'client_secret') server.client.secret = matches[1]
236 else if (key === 'user_username') server.user.username = matches[1]
237 else if (key === 'user_password') server.user.password = matches[1]
241 // Check if all required sentences are here
242 for (const key of Object.keys(serverRunString)) {
243 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
244 if (serverRunString[key] === false) dontContinue = true
247 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
248 if (dontContinue === true) return
250 if (options.hideLogs === false) {
251 console.log(data.toString())
253 server.app.stdout.removeListener('data', onStdout)
256 process.on('exit', () => {
258 process.kill(server.app.pid)
259 } catch { /* empty */ }
267 async function reRunServer (server: ServerInfo, configOverride?: any) {
268 const newServer = await runServer(server, configOverride)
269 server.app = newServer.app
274 function checkTmpIsEmpty (server: ServerInfo) {
275 return checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css' ])
278 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
279 const testDirectory = 'test' + server.internalServerNumber
281 const directoryPath = join(root(), testDirectory, directory)
283 const directoryExists = await pathExists(directoryPath)
284 expect(directoryExists).to.be.true
286 const files = await readdir(directoryPath)
287 const filtered = files.filter(f => exceptions.includes(f) === false)
289 expect(filtered).to.have.lengthOf(0)
292 function killallServers (servers: ServerInfo[]) {
293 for (const server of servers) {
294 if (!server.app) continue
296 process.kill(-server.app.pid)
301 async function cleanupTests (servers: ServerInfo[]) {
302 killallServers(servers)
305 await ensureDir('artifacts')
308 const p: Promise<any>[] = []
309 for (const server of servers) {
311 const origin = await buildServerDirectory(server, 'logs/peertube.log')
312 const destname = `peertube-${server.internalServerNumber}.log`
313 console.log('Saving logs %s.', destname)
315 await copy(origin, join('artifacts', destname))
318 if (server.parallel) {
319 p.push(flushTests(server.internalServerNumber))
322 if (server.customConfigFile) {
323 p.push(remove(server.customConfigFile))
327 return Promise.all(p)
330 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
331 const logfile = buildServerDirectory(server, 'logs/peertube.log')
334 const buf = await readFile(logfile)
336 const matches = buf.toString().match(new RegExp(str, 'g'))
337 if (matches && matches.length === count) return
338 if (matches && strictCount === false && matches.length >= count) return
344 async function getServerFileSize (server: ServerInfo, subPath: string) {
345 const path = buildServerDirectory(server, subPath)
347 return getFileSize(path)
350 // ---------------------------------------------------------------------------
353 checkDirectoryIsEmpty,
359 flushAndRunMultipleServers,