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 { LogsCommand } from '../logs'
14 import { buildServerDirectory, getFileSize, isGithubCI, root, wait } from '../miscs/miscs'
15 import { AbusesCommand } from '../moderation'
16 import { makeGetRequest } from '../requests/requests'
18 interface ServerInfo {
29 internalServerNumber: number
43 customConfigFile?: string
47 videoChannel?: VideoChannel
68 videos?: { id: number, uuid: string }[]
70 bulkCommand?: BulkCommand
71 cliCommand?: CLICommand
72 customPageCommand?: CustomPagesCommand
73 feedCommand?: FeedCommand
74 logsCommand?: LogsCommand
75 abusesCommand?: AbusesCommand
78 function parallelTests () {
79 return process.env.MOCHA_PARALLEL === 'true'
82 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
86 return new Promise<ServerInfo[]>(res => {
87 function anotherServerDone (serverNumber, app) {
88 apps[serverNumber - 1] = app
90 if (i === totalServers) {
95 for (let j = 1; j <= totalServers; j++) {
96 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
101 function flushTests (serverNumber?: number) {
102 return new Promise<void>((res, rej) => {
103 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
105 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
106 if (err || stderr) return rej(err || new Error(stderr))
113 function randomServer () {
117 return randomInt(low, high)
120 function randomRTMP () {
124 return randomInt(low, high)
127 type RunServerOptions = {
132 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
133 const parallel = parallelTests()
135 const internalServerNumber = parallel ? randomServer() : serverNumber
136 const rtmpPort = parallel ? randomRTMP() : 1936
137 const port = 9000 + internalServerNumber
139 await flushTests(internalServerNumber)
141 const server: ServerInfo = {
144 internalServerNumber,
148 url: `http://localhost:${port}`,
149 host: `localhost:${port}`,
150 hostname: 'localhost',
161 return runServer(server, configOverride, args, options)
164 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
165 // These actions are async so we need to be sure that they have both been done
166 const serverRunString = {
167 'HTTP server listening': false
169 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
170 serverRunString[key] = false
173 client_id: 'Client id: (.+)',
174 client_secret: 'Client secret: (.+)',
175 user_username: 'Username: (.+)',
176 user_password: 'User password: (.+)'
179 if (server.internalServerNumber !== server.serverNumber) {
180 const basePath = join(root(), 'config')
182 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
183 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
185 server.customConfigFile = tmpConfigFile
188 const configOverride: any = {}
190 if (server.parallel) {
191 Object.assign(configOverride, {
199 suffix: '_test' + server.internalServerNumber
202 tmp: `test${server.internalServerNumber}/tmp/`,
203 avatars: `test${server.internalServerNumber}/avatars/`,
204 videos: `test${server.internalServerNumber}/videos/`,
205 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
206 redundancy: `test${server.internalServerNumber}/redundancy/`,
207 logs: `test${server.internalServerNumber}/logs/`,
208 previews: `test${server.internalServerNumber}/previews/`,
209 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
210 torrents: `test${server.internalServerNumber}/torrents/`,
211 captions: `test${server.internalServerNumber}/captions/`,
212 cache: `test${server.internalServerNumber}/cache/`,
213 plugins: `test${server.internalServerNumber}/plugins/`
216 email: `admin${server.internalServerNumber}@example.com`
220 port: server.rtmpPort
226 if (configOverrideArg !== undefined) {
227 Object.assign(configOverride, configOverrideArg)
230 // Share the environment
231 const env = Object.create(process.env)
232 env['NODE_ENV'] = 'test'
233 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
234 env['NODE_CONFIG'] = JSON.stringify(configOverride)
236 const forkOptions = {
240 execArgv: options.execArgv || []
243 return new Promise<ServerInfo>(res => {
244 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
245 server.app.stdout.on('data', function onStdout (data) {
246 let dontContinue = false
248 // Capture things if we want to
249 for (const key of Object.keys(regexps)) {
250 const regexp = regexps[key]
251 const matches = data.toString().match(regexp)
252 if (matches !== null) {
253 if (key === 'client_id') server.client.id = matches[1]
254 else if (key === 'client_secret') server.client.secret = matches[1]
255 else if (key === 'user_username') server.user.username = matches[1]
256 else if (key === 'user_password') server.user.password = matches[1]
260 // Check if all required sentences are here
261 for (const key of Object.keys(serverRunString)) {
262 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
263 if (serverRunString[key] === false) dontContinue = true
266 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
267 if (dontContinue === true) return
269 if (options.hideLogs === false) {
270 console.log(data.toString())
272 server.app.stdout.removeListener('data', onStdout)
275 process.on('exit', () => {
277 process.kill(server.app.pid)
278 } catch { /* empty */ }
281 server.bulkCommand = new BulkCommand(server)
282 server.cliCommand = new CLICommand(server)
283 server.customPageCommand = new CustomPagesCommand(server)
284 server.feedCommand = new FeedCommand(server)
285 server.logsCommand = new LogsCommand(server)
286 server.abusesCommand = new AbusesCommand(server)
293 async function reRunServer (server: ServerInfo, configOverride?: any) {
294 const newServer = await runServer(server, configOverride)
295 server.app = newServer.app
300 async function checkTmpIsEmpty (server: ServerInfo) {
301 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
303 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
304 await checkDirectoryIsEmpty(server, 'tmp/hls')
308 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
309 const testDirectory = 'test' + server.internalServerNumber
311 const directoryPath = join(root(), testDirectory, directory)
313 const directoryExists = await pathExists(directoryPath)
314 expect(directoryExists).to.be.true
316 const files = await readdir(directoryPath)
317 const filtered = files.filter(f => exceptions.includes(f) === false)
319 expect(filtered).to.have.lengthOf(0)
322 function killallServers (servers: ServerInfo[]) {
323 for (const server of servers) {
324 if (!server.app) continue
326 process.kill(-server.app.pid)
331 async function cleanupTests (servers: ServerInfo[]) {
332 killallServers(servers)
335 await ensureDir('artifacts')
338 const p: Promise<any>[] = []
339 for (const server of servers) {
341 const origin = await buildServerDirectory(server, 'logs/peertube.log')
342 const destname = `peertube-${server.internalServerNumber}.log`
343 console.log('Saving logs %s.', destname)
345 await copy(origin, join('artifacts', destname))
348 if (server.parallel) {
349 p.push(flushTests(server.internalServerNumber))
352 if (server.customConfigFile) {
353 p.push(remove(server.customConfigFile))
357 return Promise.all(p)
360 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
361 const logfile = buildServerDirectory(server, 'logs/peertube.log')
364 const buf = await readFile(logfile)
366 const matches = buf.toString().match(new RegExp(str, 'g'))
367 if (matches && matches.length === count) return
368 if (matches && strictCount === false && matches.length >= count) return
374 async function getServerFileSize (server: ServerInfo, subPath: string) {
375 const path = buildServerDirectory(server, subPath)
377 return getFileSize(path)
380 function makePingRequest (server: ServerInfo) {
381 return makeGetRequest({
383 path: '/api/v1/ping',
384 statusCodeExpected: 200
388 // ---------------------------------------------------------------------------
391 checkDirectoryIsEmpty,
397 flushAndRunMultipleServers,