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 { CustomPagesCommand } from '../custom-pages'
12 import { FeedCommand } from '../feeds'
13 import { buildServerDirectory, getFileSize, isGithubCI, root, wait } from '../miscs/miscs'
14 import { makeGetRequest } from '../requests/requests'
16 interface ServerInfo {
27 internalServerNumber: number
41 customConfigFile?: string
45 videoChannel?: VideoChannel
66 videos?: { id: number, uuid: string }[]
68 bulkCommand?: BulkCommand
69 cliCommand?: CLICommand
70 customPageCommand?: CustomPagesCommand
71 feedCommand?: FeedCommand
74 function parallelTests () {
75 return process.env.MOCHA_PARALLEL === 'true'
78 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
82 return new Promise<ServerInfo[]>(res => {
83 function anotherServerDone (serverNumber, app) {
84 apps[serverNumber - 1] = app
86 if (i === totalServers) {
91 for (let j = 1; j <= totalServers; j++) {
92 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
97 function flushTests (serverNumber?: number) {
98 return new Promise<void>((res, rej) => {
99 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
101 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
102 if (err || stderr) return rej(err || new Error(stderr))
109 function randomServer () {
113 return randomInt(low, high)
116 function randomRTMP () {
120 return randomInt(low, high)
123 type RunServerOptions = {
128 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
129 const parallel = parallelTests()
131 const internalServerNumber = parallel ? randomServer() : serverNumber
132 const rtmpPort = parallel ? randomRTMP() : 1936
133 const port = 9000 + internalServerNumber
135 await flushTests(internalServerNumber)
137 const server: ServerInfo = {
140 internalServerNumber,
144 url: `http://localhost:${port}`,
145 host: `localhost:${port}`,
146 hostname: 'localhost',
157 return runServer(server, configOverride, args, options)
160 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
161 // These actions are async so we need to be sure that they have both been done
162 const serverRunString = {
163 'HTTP server listening': false
165 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
166 serverRunString[key] = false
169 client_id: 'Client id: (.+)',
170 client_secret: 'Client secret: (.+)',
171 user_username: 'Username: (.+)',
172 user_password: 'User password: (.+)'
175 if (server.internalServerNumber !== server.serverNumber) {
176 const basePath = join(root(), 'config')
178 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
179 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
181 server.customConfigFile = tmpConfigFile
184 const configOverride: any = {}
186 if (server.parallel) {
187 Object.assign(configOverride, {
195 suffix: '_test' + server.internalServerNumber
198 tmp: `test${server.internalServerNumber}/tmp/`,
199 avatars: `test${server.internalServerNumber}/avatars/`,
200 videos: `test${server.internalServerNumber}/videos/`,
201 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
202 redundancy: `test${server.internalServerNumber}/redundancy/`,
203 logs: `test${server.internalServerNumber}/logs/`,
204 previews: `test${server.internalServerNumber}/previews/`,
205 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
206 torrents: `test${server.internalServerNumber}/torrents/`,
207 captions: `test${server.internalServerNumber}/captions/`,
208 cache: `test${server.internalServerNumber}/cache/`,
209 plugins: `test${server.internalServerNumber}/plugins/`
212 email: `admin${server.internalServerNumber}@example.com`
216 port: server.rtmpPort
222 if (configOverrideArg !== undefined) {
223 Object.assign(configOverride, configOverrideArg)
226 // Share the environment
227 const env = Object.create(process.env)
228 env['NODE_ENV'] = 'test'
229 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
230 env['NODE_CONFIG'] = JSON.stringify(configOverride)
232 const forkOptions = {
236 execArgv: options.execArgv || []
239 return new Promise<ServerInfo>(res => {
240 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
241 server.app.stdout.on('data', function onStdout (data) {
242 let dontContinue = false
244 // Capture things if we want to
245 for (const key of Object.keys(regexps)) {
246 const regexp = regexps[key]
247 const matches = data.toString().match(regexp)
248 if (matches !== null) {
249 if (key === 'client_id') server.client.id = matches[1]
250 else if (key === 'client_secret') server.client.secret = matches[1]
251 else if (key === 'user_username') server.user.username = matches[1]
252 else if (key === 'user_password') server.user.password = matches[1]
256 // Check if all required sentences are here
257 for (const key of Object.keys(serverRunString)) {
258 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
259 if (serverRunString[key] === false) dontContinue = true
262 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
263 if (dontContinue === true) return
265 if (options.hideLogs === false) {
266 console.log(data.toString())
268 server.app.stdout.removeListener('data', onStdout)
271 process.on('exit', () => {
273 process.kill(server.app.pid)
274 } catch { /* empty */ }
277 server.bulkCommand = new BulkCommand(server)
278 server.cliCommand = new CLICommand(server)
279 server.customPageCommand = new CustomPagesCommand(server)
280 server.feedCommand = new FeedCommand(server)
287 async function reRunServer (server: ServerInfo, configOverride?: any) {
288 const newServer = await runServer(server, configOverride)
289 server.app = newServer.app
294 async function checkTmpIsEmpty (server: ServerInfo) {
295 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
297 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
298 await checkDirectoryIsEmpty(server, 'tmp/hls')
302 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
303 const testDirectory = 'test' + server.internalServerNumber
305 const directoryPath = join(root(), testDirectory, directory)
307 const directoryExists = await pathExists(directoryPath)
308 expect(directoryExists).to.be.true
310 const files = await readdir(directoryPath)
311 const filtered = files.filter(f => exceptions.includes(f) === false)
313 expect(filtered).to.have.lengthOf(0)
316 function killallServers (servers: ServerInfo[]) {
317 for (const server of servers) {
318 if (!server.app) continue
320 process.kill(-server.app.pid)
325 async function cleanupTests (servers: ServerInfo[]) {
326 killallServers(servers)
329 await ensureDir('artifacts')
332 const p: Promise<any>[] = []
333 for (const server of servers) {
335 const origin = await buildServerDirectory(server, 'logs/peertube.log')
336 const destname = `peertube-${server.internalServerNumber}.log`
337 console.log('Saving logs %s.', destname)
339 await copy(origin, join('artifacts', destname))
342 if (server.parallel) {
343 p.push(flushTests(server.internalServerNumber))
346 if (server.customConfigFile) {
347 p.push(remove(server.customConfigFile))
351 return Promise.all(p)
354 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
355 const logfile = buildServerDirectory(server, 'logs/peertube.log')
358 const buf = await readFile(logfile)
360 const matches = buf.toString().match(new RegExp(str, 'g'))
361 if (matches && matches.length === count) return
362 if (matches && strictCount === false && matches.length >= count) return
368 async function getServerFileSize (server: ServerInfo, subPath: string) {
369 const path = buildServerDirectory(server, subPath)
371 return getFileSize(path)
374 function makePingRequest (server: ServerInfo) {
375 return makeGetRequest({
377 path: '/api/v1/ping',
378 statusCodeExpected: 200
382 // ---------------------------------------------------------------------------
385 checkDirectoryIsEmpty,
391 flushAndRunMultipleServers,