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 { BulkCommand } from '../bulk'
10 import { CLICommand } from '../cli'
11 import { buildServerDirectory, getFileSize, isGithubCI, root, wait } from '../miscs/miscs'
12 import { makeGetRequest } from '../requests/requests'
14 interface ServerInfo {
25 internalServerNumber: number
39 customConfigFile?: string
43 videoChannel?: VideoChannel
64 videos?: { id: number, uuid: string }[]
66 bulkCommand?: BulkCommand
67 cliCommand?: CLICommand
70 function parallelTests () {
71 return process.env.MOCHA_PARALLEL === 'true'
74 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
78 return new Promise<ServerInfo[]>(res => {
79 function anotherServerDone (serverNumber, app) {
80 apps[serverNumber - 1] = app
82 if (i === totalServers) {
87 for (let j = 1; j <= totalServers; j++) {
88 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
93 function flushTests (serverNumber?: number) {
94 return new Promise<void>((res, rej) => {
95 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
97 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
98 if (err || stderr) return rej(err || new Error(stderr))
105 function randomServer () {
109 return randomInt(low, high)
112 function randomRTMP () {
116 return randomInt(low, high)
119 type RunServerOptions = {
124 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
125 const parallel = parallelTests()
127 const internalServerNumber = parallel ? randomServer() : serverNumber
128 const rtmpPort = parallel ? randomRTMP() : 1936
129 const port = 9000 + internalServerNumber
131 await flushTests(internalServerNumber)
133 const server: ServerInfo = {
136 internalServerNumber,
140 url: `http://localhost:${port}`,
141 host: `localhost:${port}`,
142 hostname: 'localhost',
153 return runServer(server, configOverride, args, options)
156 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
157 // These actions are async so we need to be sure that they have both been done
158 const serverRunString = {
159 'HTTP server listening': false
161 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
162 serverRunString[key] = false
165 client_id: 'Client id: (.+)',
166 client_secret: 'Client secret: (.+)',
167 user_username: 'Username: (.+)',
168 user_password: 'User password: (.+)'
171 if (server.internalServerNumber !== server.serverNumber) {
172 const basePath = join(root(), 'config')
174 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
175 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
177 server.customConfigFile = tmpConfigFile
180 const configOverride: any = {}
182 if (server.parallel) {
183 Object.assign(configOverride, {
191 suffix: '_test' + server.internalServerNumber
194 tmp: `test${server.internalServerNumber}/tmp/`,
195 avatars: `test${server.internalServerNumber}/avatars/`,
196 videos: `test${server.internalServerNumber}/videos/`,
197 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
198 redundancy: `test${server.internalServerNumber}/redundancy/`,
199 logs: `test${server.internalServerNumber}/logs/`,
200 previews: `test${server.internalServerNumber}/previews/`,
201 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
202 torrents: `test${server.internalServerNumber}/torrents/`,
203 captions: `test${server.internalServerNumber}/captions/`,
204 cache: `test${server.internalServerNumber}/cache/`,
205 plugins: `test${server.internalServerNumber}/plugins/`
208 email: `admin${server.internalServerNumber}@example.com`
212 port: server.rtmpPort
218 if (configOverrideArg !== undefined) {
219 Object.assign(configOverride, configOverrideArg)
222 // Share the environment
223 const env = Object.create(process.env)
224 env['NODE_ENV'] = 'test'
225 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
226 env['NODE_CONFIG'] = JSON.stringify(configOverride)
228 const forkOptions = {
232 execArgv: options.execArgv || []
235 return new Promise<ServerInfo>(res => {
236 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
237 server.app.stdout.on('data', function onStdout (data) {
238 let dontContinue = false
240 // Capture things if we want to
241 for (const key of Object.keys(regexps)) {
242 const regexp = regexps[key]
243 const matches = data.toString().match(regexp)
244 if (matches !== null) {
245 if (key === 'client_id') server.client.id = matches[1]
246 else if (key === 'client_secret') server.client.secret = matches[1]
247 else if (key === 'user_username') server.user.username = matches[1]
248 else if (key === 'user_password') server.user.password = matches[1]
252 // Check if all required sentences are here
253 for (const key of Object.keys(serverRunString)) {
254 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
255 if (serverRunString[key] === false) dontContinue = true
258 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
259 if (dontContinue === true) return
261 if (options.hideLogs === false) {
262 console.log(data.toString())
264 server.app.stdout.removeListener('data', onStdout)
267 process.on('exit', () => {
269 process.kill(server.app.pid)
270 } catch { /* empty */ }
273 server.bulkCommand = new BulkCommand(server)
274 server.cliCommand = new CLICommand(server)
281 async function reRunServer (server: ServerInfo, configOverride?: any) {
282 const newServer = await runServer(server, configOverride)
283 server.app = newServer.app
288 async function checkTmpIsEmpty (server: ServerInfo) {
289 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
291 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
292 await checkDirectoryIsEmpty(server, 'tmp/hls')
296 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
297 const testDirectory = 'test' + server.internalServerNumber
299 const directoryPath = join(root(), testDirectory, directory)
301 const directoryExists = await pathExists(directoryPath)
302 expect(directoryExists).to.be.true
304 const files = await readdir(directoryPath)
305 const filtered = files.filter(f => exceptions.includes(f) === false)
307 expect(filtered).to.have.lengthOf(0)
310 function killallServers (servers: ServerInfo[]) {
311 for (const server of servers) {
312 if (!server.app) continue
314 process.kill(-server.app.pid)
319 async function cleanupTests (servers: ServerInfo[]) {
320 killallServers(servers)
323 await ensureDir('artifacts')
326 const p: Promise<any>[] = []
327 for (const server of servers) {
329 const origin = await buildServerDirectory(server, 'logs/peertube.log')
330 const destname = `peertube-${server.internalServerNumber}.log`
331 console.log('Saving logs %s.', destname)
333 await copy(origin, join('artifacts', destname))
336 if (server.parallel) {
337 p.push(flushTests(server.internalServerNumber))
340 if (server.customConfigFile) {
341 p.push(remove(server.customConfigFile))
345 return Promise.all(p)
348 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
349 const logfile = buildServerDirectory(server, 'logs/peertube.log')
352 const buf = await readFile(logfile)
354 const matches = buf.toString().match(new RegExp(str, 'g'))
355 if (matches && matches.length === count) return
356 if (matches && strictCount === false && matches.length >= count) return
362 async function getServerFileSize (server: ServerInfo, subPath: string) {
363 const path = buildServerDirectory(server, subPath)
365 return getFileSize(path)
368 function makePingRequest (server: ServerInfo) {
369 return makeGetRequest({
371 path: '/api/v1/ping',
372 statusCodeExpected: 200
376 // ---------------------------------------------------------------------------
379 checkDirectoryIsEmpty,
385 flushAndRunMultipleServers,