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 { OverviewsCommand } from '../overviews'
17 import { makeGetRequest } from '../requests/requests'
18 import { SearchCommand } from '../search'
19 import { SocketIOCommand } from '../socket'
20 import { AccountsCommand, BlocklistCommand, SubscriptionsCommand } from '../users'
21 import { ConfigCommand } from './config-command'
22 import { ContactFormCommand } from './contact-form-command'
23 import { DebugCommand } from './debug-command'
24 import { FollowsCommand } from './follows-command'
25 import { JobsCommand } from './jobs-command'
26 import { PluginsCommand } from './plugins-command'
27 import { RedundancyCommand } from './redundancy-command'
28 import { StatsCommand } from './stats-command'
30 interface ServerInfo {
41 internalServerNumber: number
55 customConfigFile?: string
59 videoChannel?: VideoChannel
80 videos?: { id: number, uuid: string }[]
82 bulkCommand?: BulkCommand
83 cliCommand?: CLICommand
84 customPageCommand?: CustomPagesCommand
85 feedCommand?: FeedCommand
86 logsCommand?: LogsCommand
87 abusesCommand?: AbusesCommand
88 overviewsCommand?: OverviewsCommand
89 searchCommand?: SearchCommand
90 contactFormCommand?: ContactFormCommand
91 debugCommand?: DebugCommand
92 followsCommand?: FollowsCommand
93 jobsCommand?: JobsCommand
94 pluginsCommand?: PluginsCommand
95 redundancyCommand?: RedundancyCommand
96 statsCommand?: StatsCommand
97 configCommand?: ConfigCommand
98 socketIOCommand?: SocketIOCommand
99 accountsCommand?: AccountsCommand
100 blocklistCommand?: BlocklistCommand
101 subscriptionsCommand?: SubscriptionsCommand
104 function parallelTests () {
105 return process.env.MOCHA_PARALLEL === 'true'
108 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
112 return new Promise<ServerInfo[]>(res => {
113 function anotherServerDone (serverNumber, app) {
114 apps[serverNumber - 1] = app
116 if (i === totalServers) {
121 for (let j = 1; j <= totalServers; j++) {
122 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
127 function flushTests (serverNumber?: number) {
128 return new Promise<void>((res, rej) => {
129 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
131 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
132 if (err || stderr) return rej(err || new Error(stderr))
139 function randomServer () {
143 return randomInt(low, high)
146 function randomRTMP () {
150 return randomInt(low, high)
153 type RunServerOptions = {
158 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
159 const parallel = parallelTests()
161 const internalServerNumber = parallel ? randomServer() : serverNumber
162 const rtmpPort = parallel ? randomRTMP() : 1936
163 const port = 9000 + internalServerNumber
165 await flushTests(internalServerNumber)
167 const server: ServerInfo = {
170 internalServerNumber,
174 url: `http://localhost:${port}`,
175 host: `localhost:${port}`,
176 hostname: 'localhost',
187 return runServer(server, configOverride, args, options)
190 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
191 // These actions are async so we need to be sure that they have both been done
192 const serverRunString = {
193 'HTTP server listening': false
195 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
196 serverRunString[key] = false
199 client_id: 'Client id: (.+)',
200 client_secret: 'Client secret: (.+)',
201 user_username: 'Username: (.+)',
202 user_password: 'User password: (.+)'
205 if (server.internalServerNumber !== server.serverNumber) {
206 const basePath = join(root(), 'config')
208 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
209 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
211 server.customConfigFile = tmpConfigFile
214 const configOverride: any = {}
216 if (server.parallel) {
217 Object.assign(configOverride, {
225 suffix: '_test' + server.internalServerNumber
228 tmp: `test${server.internalServerNumber}/tmp/`,
229 avatars: `test${server.internalServerNumber}/avatars/`,
230 videos: `test${server.internalServerNumber}/videos/`,
231 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
232 redundancy: `test${server.internalServerNumber}/redundancy/`,
233 logs: `test${server.internalServerNumber}/logs/`,
234 previews: `test${server.internalServerNumber}/previews/`,
235 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
236 torrents: `test${server.internalServerNumber}/torrents/`,
237 captions: `test${server.internalServerNumber}/captions/`,
238 cache: `test${server.internalServerNumber}/cache/`,
239 plugins: `test${server.internalServerNumber}/plugins/`
242 email: `admin${server.internalServerNumber}@example.com`
246 port: server.rtmpPort
252 if (configOverrideArg !== undefined) {
253 Object.assign(configOverride, configOverrideArg)
256 // Share the environment
257 const env = Object.create(process.env)
258 env['NODE_ENV'] = 'test'
259 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
260 env['NODE_CONFIG'] = JSON.stringify(configOverride)
262 const forkOptions = {
266 execArgv: options.execArgv || []
269 return new Promise<ServerInfo>(res => {
270 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
271 server.app.stdout.on('data', function onStdout (data) {
272 let dontContinue = false
274 // Capture things if we want to
275 for (const key of Object.keys(regexps)) {
276 const regexp = regexps[key]
277 const matches = data.toString().match(regexp)
278 if (matches !== null) {
279 if (key === 'client_id') server.client.id = matches[1]
280 else if (key === 'client_secret') server.client.secret = matches[1]
281 else if (key === 'user_username') server.user.username = matches[1]
282 else if (key === 'user_password') server.user.password = matches[1]
286 // Check if all required sentences are here
287 for (const key of Object.keys(serverRunString)) {
288 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
289 if (serverRunString[key] === false) dontContinue = true
292 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
293 if (dontContinue === true) return
295 if (options.hideLogs === false) {
296 console.log(data.toString())
298 server.app.stdout.removeListener('data', onStdout)
301 process.on('exit', () => {
303 process.kill(server.app.pid)
304 } catch { /* empty */ }
307 server.bulkCommand = new BulkCommand(server)
308 server.cliCommand = new CLICommand(server)
309 server.customPageCommand = new CustomPagesCommand(server)
310 server.feedCommand = new FeedCommand(server)
311 server.logsCommand = new LogsCommand(server)
312 server.abusesCommand = new AbusesCommand(server)
313 server.overviewsCommand = new OverviewsCommand(server)
314 server.searchCommand = new SearchCommand(server)
315 server.contactFormCommand = new ContactFormCommand(server)
316 server.debugCommand = new DebugCommand(server)
317 server.followsCommand = new FollowsCommand(server)
318 server.jobsCommand = new JobsCommand(server)
319 server.pluginsCommand = new PluginsCommand(server)
320 server.redundancyCommand = new RedundancyCommand(server)
321 server.statsCommand = new StatsCommand(server)
322 server.configCommand = new ConfigCommand(server)
323 server.socketIOCommand = new SocketIOCommand(server)
324 server.accountsCommand = new AccountsCommand(server)
325 server.blocklistCommand = new BlocklistCommand(server)
326 server.subscriptionsCommand = new SubscriptionsCommand(server)
333 async function reRunServer (server: ServerInfo, configOverride?: any) {
334 const newServer = await runServer(server, configOverride)
335 server.app = newServer.app
340 async function checkTmpIsEmpty (server: ServerInfo) {
341 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
343 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
344 await checkDirectoryIsEmpty(server, 'tmp/hls')
348 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
349 const testDirectory = 'test' + server.internalServerNumber
351 const directoryPath = join(root(), testDirectory, directory)
353 const directoryExists = await pathExists(directoryPath)
354 expect(directoryExists).to.be.true
356 const files = await readdir(directoryPath)
357 const filtered = files.filter(f => exceptions.includes(f) === false)
359 expect(filtered).to.have.lengthOf(0)
362 function killallServers (servers: ServerInfo[]) {
363 for (const server of servers) {
364 if (!server.app) continue
366 process.kill(-server.app.pid)
371 async function cleanupTests (servers: ServerInfo[]) {
372 killallServers(servers)
375 await ensureDir('artifacts')
378 const p: Promise<any>[] = []
379 for (const server of servers) {
381 const origin = await buildServerDirectory(server, 'logs/peertube.log')
382 const destname = `peertube-${server.internalServerNumber}.log`
383 console.log('Saving logs %s.', destname)
385 await copy(origin, join('artifacts', destname))
388 if (server.parallel) {
389 p.push(flushTests(server.internalServerNumber))
392 if (server.customConfigFile) {
393 p.push(remove(server.customConfigFile))
397 return Promise.all(p)
400 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
401 const logfile = buildServerDirectory(server, 'logs/peertube.log')
404 const buf = await readFile(logfile)
406 const matches = buf.toString().match(new RegExp(str, 'g'))
407 if (matches && matches.length === count) return
408 if (matches && strictCount === false && matches.length >= count) return
414 async function getServerFileSize (server: ServerInfo, subPath: string) {
415 const path = buildServerDirectory(server, subPath)
417 return getFileSize(path)
420 function makePingRequest (server: ServerInfo) {
421 return makeGetRequest({
423 path: '/api/v1/ping',
424 statusCodeExpected: 200
428 // ---------------------------------------------------------------------------
431 checkDirectoryIsEmpty,
437 flushAndRunMultipleServers,