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 { LiveCommand } from '../videos'
22 import { ConfigCommand } from './config-command'
23 import { ContactFormCommand } from './contact-form-command'
24 import { DebugCommand } from './debug-command'
25 import { FollowsCommand } from './follows-command'
26 import { JobsCommand } from './jobs-command'
27 import { PluginsCommand } from './plugins-command'
28 import { RedundancyCommand } from './redundancy-command'
29 import { StatsCommand } from './stats-command'
31 interface ServerInfo {
42 internalServerNumber: number
56 customConfigFile?: string
60 videoChannel?: VideoChannel
81 videos?: { id: number, uuid: string }[]
83 bulkCommand?: BulkCommand
84 cliCommand?: CLICommand
85 customPageCommand?: CustomPagesCommand
86 feedCommand?: FeedCommand
87 logsCommand?: LogsCommand
88 abusesCommand?: AbusesCommand
89 overviewsCommand?: OverviewsCommand
90 searchCommand?: SearchCommand
91 contactFormCommand?: ContactFormCommand
92 debugCommand?: DebugCommand
93 followsCommand?: FollowsCommand
94 jobsCommand?: JobsCommand
95 pluginsCommand?: PluginsCommand
96 redundancyCommand?: RedundancyCommand
97 statsCommand?: StatsCommand
98 configCommand?: ConfigCommand
99 socketIOCommand?: SocketIOCommand
100 accountsCommand?: AccountsCommand
101 blocklistCommand?: BlocklistCommand
102 subscriptionsCommand?: SubscriptionsCommand
103 liveCommand?: LiveCommand
106 function parallelTests () {
107 return process.env.MOCHA_PARALLEL === 'true'
110 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
114 return new Promise<ServerInfo[]>(res => {
115 function anotherServerDone (serverNumber, app) {
116 apps[serverNumber - 1] = app
118 if (i === totalServers) {
123 for (let j = 1; j <= totalServers; j++) {
124 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
129 function flushTests (serverNumber?: number) {
130 return new Promise<void>((res, rej) => {
131 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
133 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
134 if (err || stderr) return rej(err || new Error(stderr))
141 function randomServer () {
145 return randomInt(low, high)
148 function randomRTMP () {
152 return randomInt(low, high)
155 type RunServerOptions = {
160 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
161 const parallel = parallelTests()
163 const internalServerNumber = parallel ? randomServer() : serverNumber
164 const rtmpPort = parallel ? randomRTMP() : 1936
165 const port = 9000 + internalServerNumber
167 await flushTests(internalServerNumber)
169 const server: ServerInfo = {
172 internalServerNumber,
176 url: `http://localhost:${port}`,
177 host: `localhost:${port}`,
178 hostname: 'localhost',
189 return runServer(server, configOverride, args, options)
192 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
193 // These actions are async so we need to be sure that they have both been done
194 const serverRunString = {
195 'HTTP server listening': false
197 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
198 serverRunString[key] = false
201 client_id: 'Client id: (.+)',
202 client_secret: 'Client secret: (.+)',
203 user_username: 'Username: (.+)',
204 user_password: 'User password: (.+)'
207 if (server.internalServerNumber !== server.serverNumber) {
208 const basePath = join(root(), 'config')
210 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
211 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
213 server.customConfigFile = tmpConfigFile
216 const configOverride: any = {}
218 if (server.parallel) {
219 Object.assign(configOverride, {
227 suffix: '_test' + server.internalServerNumber
230 tmp: `test${server.internalServerNumber}/tmp/`,
231 avatars: `test${server.internalServerNumber}/avatars/`,
232 videos: `test${server.internalServerNumber}/videos/`,
233 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
234 redundancy: `test${server.internalServerNumber}/redundancy/`,
235 logs: `test${server.internalServerNumber}/logs/`,
236 previews: `test${server.internalServerNumber}/previews/`,
237 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
238 torrents: `test${server.internalServerNumber}/torrents/`,
239 captions: `test${server.internalServerNumber}/captions/`,
240 cache: `test${server.internalServerNumber}/cache/`,
241 plugins: `test${server.internalServerNumber}/plugins/`
244 email: `admin${server.internalServerNumber}@example.com`
248 port: server.rtmpPort
254 if (configOverrideArg !== undefined) {
255 Object.assign(configOverride, configOverrideArg)
258 // Share the environment
259 const env = Object.create(process.env)
260 env['NODE_ENV'] = 'test'
261 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
262 env['NODE_CONFIG'] = JSON.stringify(configOverride)
264 const forkOptions = {
268 execArgv: options.execArgv || []
271 return new Promise<ServerInfo>(res => {
272 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
273 server.app.stdout.on('data', function onStdout (data) {
274 let dontContinue = false
276 // Capture things if we want to
277 for (const key of Object.keys(regexps)) {
278 const regexp = regexps[key]
279 const matches = data.toString().match(regexp)
280 if (matches !== null) {
281 if (key === 'client_id') server.client.id = matches[1]
282 else if (key === 'client_secret') server.client.secret = matches[1]
283 else if (key === 'user_username') server.user.username = matches[1]
284 else if (key === 'user_password') server.user.password = matches[1]
288 // Check if all required sentences are here
289 for (const key of Object.keys(serverRunString)) {
290 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
291 if (serverRunString[key] === false) dontContinue = true
294 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
295 if (dontContinue === true) return
297 if (options.hideLogs === false) {
298 console.log(data.toString())
300 server.app.stdout.removeListener('data', onStdout)
303 process.on('exit', () => {
305 process.kill(server.app.pid)
306 } catch { /* empty */ }
309 server.bulkCommand = new BulkCommand(server)
310 server.cliCommand = new CLICommand(server)
311 server.customPageCommand = new CustomPagesCommand(server)
312 server.feedCommand = new FeedCommand(server)
313 server.logsCommand = new LogsCommand(server)
314 server.abusesCommand = new AbusesCommand(server)
315 server.overviewsCommand = new OverviewsCommand(server)
316 server.searchCommand = new SearchCommand(server)
317 server.contactFormCommand = new ContactFormCommand(server)
318 server.debugCommand = new DebugCommand(server)
319 server.followsCommand = new FollowsCommand(server)
320 server.jobsCommand = new JobsCommand(server)
321 server.pluginsCommand = new PluginsCommand(server)
322 server.redundancyCommand = new RedundancyCommand(server)
323 server.statsCommand = new StatsCommand(server)
324 server.configCommand = new ConfigCommand(server)
325 server.socketIOCommand = new SocketIOCommand(server)
326 server.accountsCommand = new AccountsCommand(server)
327 server.blocklistCommand = new BlocklistCommand(server)
328 server.subscriptionsCommand = new SubscriptionsCommand(server)
329 server.liveCommand = new LiveCommand(server)
336 async function reRunServer (server: ServerInfo, configOverride?: any) {
337 const newServer = await runServer(server, configOverride)
338 server.app = newServer.app
343 async function checkTmpIsEmpty (server: ServerInfo) {
344 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
346 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
347 await checkDirectoryIsEmpty(server, 'tmp/hls')
351 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
352 const testDirectory = 'test' + server.internalServerNumber
354 const directoryPath = join(root(), testDirectory, directory)
356 const directoryExists = await pathExists(directoryPath)
357 expect(directoryExists).to.be.true
359 const files = await readdir(directoryPath)
360 const filtered = files.filter(f => exceptions.includes(f) === false)
362 expect(filtered).to.have.lengthOf(0)
365 function killallServers (servers: ServerInfo[]) {
366 for (const server of servers) {
367 if (!server.app) continue
369 process.kill(-server.app.pid)
374 async function cleanupTests (servers: ServerInfo[]) {
375 killallServers(servers)
378 await ensureDir('artifacts')
381 const p: Promise<any>[] = []
382 for (const server of servers) {
384 const origin = await buildServerDirectory(server, 'logs/peertube.log')
385 const destname = `peertube-${server.internalServerNumber}.log`
386 console.log('Saving logs %s.', destname)
388 await copy(origin, join('artifacts', destname))
391 if (server.parallel) {
392 p.push(flushTests(server.internalServerNumber))
395 if (server.customConfigFile) {
396 p.push(remove(server.customConfigFile))
400 return Promise.all(p)
403 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
404 const logfile = buildServerDirectory(server, 'logs/peertube.log')
407 const buf = await readFile(logfile)
409 const matches = buf.toString().match(new RegExp(str, 'g'))
410 if (matches && matches.length === count) return
411 if (matches && strictCount === false && matches.length >= count) return
417 async function getServerFileSize (server: ServerInfo, subPath: string) {
418 const path = buildServerDirectory(server, subPath)
420 return getFileSize(path)
423 function makePingRequest (server: ServerInfo) {
424 return makeGetRequest({
426 path: '/api/v1/ping',
427 statusCodeExpected: 200
431 // ---------------------------------------------------------------------------
434 checkDirectoryIsEmpty,
440 flushAndRunMultipleServers,