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'
24 ChangeOwnershipCommand,
31 import { ConfigCommand } from './config-command'
32 import { ContactFormCommand } from './contact-form-command'
33 import { DebugCommand } from './debug-command'
34 import { FollowsCommand } from './follows-command'
35 import { JobsCommand } from './jobs-command'
36 import { PluginsCommand } from './plugins-command'
37 import { RedundancyCommand } from './redundancy-command'
38 import { StatsCommand } from './stats-command'
40 interface ServerInfo {
51 internalServerNumber: number
65 customConfigFile?: string
69 videoChannel?: VideoChannel
90 videos?: { id: number, uuid: string }[]
92 bulkCommand?: BulkCommand
93 cliCommand?: CLICommand
94 customPageCommand?: CustomPagesCommand
95 feedCommand?: FeedCommand
96 logsCommand?: LogsCommand
97 abusesCommand?: AbusesCommand
98 overviewsCommand?: OverviewsCommand
99 searchCommand?: SearchCommand
100 contactFormCommand?: ContactFormCommand
101 debugCommand?: DebugCommand
102 followsCommand?: FollowsCommand
103 jobsCommand?: JobsCommand
104 pluginsCommand?: PluginsCommand
105 redundancyCommand?: RedundancyCommand
106 statsCommand?: StatsCommand
107 configCommand?: ConfigCommand
108 socketIOCommand?: SocketIOCommand
109 accountsCommand?: AccountsCommand
110 blocklistCommand?: BlocklistCommand
111 subscriptionsCommand?: SubscriptionsCommand
112 liveCommand?: LiveCommand
113 servicesCommand?: ServicesCommand
114 blacklistCommand?: BlacklistCommand
115 captionsCommand?: CaptionsCommand
116 changeOwnershipCommand?: ChangeOwnershipCommand
117 playlistsCommand?: PlaylistsCommand
118 historyCommand?: HistoryCommand
119 importsCommand?: ImportsCommand
122 function parallelTests () {
123 return process.env.MOCHA_PARALLEL === 'true'
126 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
130 return new Promise<ServerInfo[]>(res => {
131 function anotherServerDone (serverNumber, app) {
132 apps[serverNumber - 1] = app
134 if (i === totalServers) {
139 for (let j = 1; j <= totalServers; j++) {
140 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
145 function flushTests (serverNumber?: number) {
146 return new Promise<void>((res, rej) => {
147 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
149 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
150 if (err || stderr) return rej(err || new Error(stderr))
157 function randomServer () {
161 return randomInt(low, high)
164 function randomRTMP () {
168 return randomInt(low, high)
171 type RunServerOptions = {
176 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
177 const parallel = parallelTests()
179 const internalServerNumber = parallel ? randomServer() : serverNumber
180 const rtmpPort = parallel ? randomRTMP() : 1936
181 const port = 9000 + internalServerNumber
183 await flushTests(internalServerNumber)
185 const server: ServerInfo = {
188 internalServerNumber,
192 url: `http://localhost:${port}`,
193 host: `localhost:${port}`,
194 hostname: 'localhost',
205 return runServer(server, configOverride, args, options)
208 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
209 // These actions are async so we need to be sure that they have both been done
210 const serverRunString = {
211 'HTTP server listening': false
213 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
214 serverRunString[key] = false
217 client_id: 'Client id: (.+)',
218 client_secret: 'Client secret: (.+)',
219 user_username: 'Username: (.+)',
220 user_password: 'User password: (.+)'
223 if (server.internalServerNumber !== server.serverNumber) {
224 const basePath = join(root(), 'config')
226 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
227 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
229 server.customConfigFile = tmpConfigFile
232 const configOverride: any = {}
234 if (server.parallel) {
235 Object.assign(configOverride, {
243 suffix: '_test' + server.internalServerNumber
246 tmp: `test${server.internalServerNumber}/tmp/`,
247 avatars: `test${server.internalServerNumber}/avatars/`,
248 videos: `test${server.internalServerNumber}/videos/`,
249 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
250 redundancy: `test${server.internalServerNumber}/redundancy/`,
251 logs: `test${server.internalServerNumber}/logs/`,
252 previews: `test${server.internalServerNumber}/previews/`,
253 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
254 torrents: `test${server.internalServerNumber}/torrents/`,
255 captions: `test${server.internalServerNumber}/captions/`,
256 cache: `test${server.internalServerNumber}/cache/`,
257 plugins: `test${server.internalServerNumber}/plugins/`
260 email: `admin${server.internalServerNumber}@example.com`
264 port: server.rtmpPort
270 if (configOverrideArg !== undefined) {
271 Object.assign(configOverride, configOverrideArg)
274 // Share the environment
275 const env = Object.create(process.env)
276 env['NODE_ENV'] = 'test'
277 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
278 env['NODE_CONFIG'] = JSON.stringify(configOverride)
280 const forkOptions = {
284 execArgv: options.execArgv || []
287 return new Promise<ServerInfo>(res => {
288 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
289 server.app.stdout.on('data', function onStdout (data) {
290 let dontContinue = false
292 // Capture things if we want to
293 for (const key of Object.keys(regexps)) {
294 const regexp = regexps[key]
295 const matches = data.toString().match(regexp)
296 if (matches !== null) {
297 if (key === 'client_id') server.client.id = matches[1]
298 else if (key === 'client_secret') server.client.secret = matches[1]
299 else if (key === 'user_username') server.user.username = matches[1]
300 else if (key === 'user_password') server.user.password = matches[1]
304 // Check if all required sentences are here
305 for (const key of Object.keys(serverRunString)) {
306 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
307 if (serverRunString[key] === false) dontContinue = true
310 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
311 if (dontContinue === true) return
313 if (options.hideLogs === false) {
314 console.log(data.toString())
316 server.app.stdout.removeListener('data', onStdout)
319 process.on('exit', () => {
321 process.kill(server.app.pid)
322 } catch { /* empty */ }
325 server.bulkCommand = new BulkCommand(server)
326 server.cliCommand = new CLICommand(server)
327 server.customPageCommand = new CustomPagesCommand(server)
328 server.feedCommand = new FeedCommand(server)
329 server.logsCommand = new LogsCommand(server)
330 server.abusesCommand = new AbusesCommand(server)
331 server.overviewsCommand = new OverviewsCommand(server)
332 server.searchCommand = new SearchCommand(server)
333 server.contactFormCommand = new ContactFormCommand(server)
334 server.debugCommand = new DebugCommand(server)
335 server.followsCommand = new FollowsCommand(server)
336 server.jobsCommand = new JobsCommand(server)
337 server.pluginsCommand = new PluginsCommand(server)
338 server.redundancyCommand = new RedundancyCommand(server)
339 server.statsCommand = new StatsCommand(server)
340 server.configCommand = new ConfigCommand(server)
341 server.socketIOCommand = new SocketIOCommand(server)
342 server.accountsCommand = new AccountsCommand(server)
343 server.blocklistCommand = new BlocklistCommand(server)
344 server.subscriptionsCommand = new SubscriptionsCommand(server)
345 server.liveCommand = new LiveCommand(server)
346 server.servicesCommand = new ServicesCommand(server)
347 server.blacklistCommand = new BlacklistCommand(server)
348 server.captionsCommand = new CaptionsCommand(server)
349 server.changeOwnershipCommand = new ChangeOwnershipCommand(server)
350 server.playlistsCommand = new PlaylistsCommand(server)
351 server.historyCommand = new HistoryCommand(server)
352 server.importsCommand = new ImportsCommand(server)
359 async function reRunServer (server: ServerInfo, configOverride?: any) {
360 const newServer = await runServer(server, configOverride)
361 server.app = newServer.app
366 async function checkTmpIsEmpty (server: ServerInfo) {
367 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
369 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
370 await checkDirectoryIsEmpty(server, 'tmp/hls')
374 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
375 const testDirectory = 'test' + server.internalServerNumber
377 const directoryPath = join(root(), testDirectory, directory)
379 const directoryExists = await pathExists(directoryPath)
380 expect(directoryExists).to.be.true
382 const files = await readdir(directoryPath)
383 const filtered = files.filter(f => exceptions.includes(f) === false)
385 expect(filtered).to.have.lengthOf(0)
388 function killallServers (servers: ServerInfo[]) {
389 for (const server of servers) {
390 if (!server.app) continue
392 process.kill(-server.app.pid)
397 async function cleanupTests (servers: ServerInfo[]) {
398 killallServers(servers)
401 await ensureDir('artifacts')
404 const p: Promise<any>[] = []
405 for (const server of servers) {
407 const origin = await buildServerDirectory(server, 'logs/peertube.log')
408 const destname = `peertube-${server.internalServerNumber}.log`
409 console.log('Saving logs %s.', destname)
411 await copy(origin, join('artifacts', destname))
414 if (server.parallel) {
415 p.push(flushTests(server.internalServerNumber))
418 if (server.customConfigFile) {
419 p.push(remove(server.customConfigFile))
423 return Promise.all(p)
426 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
427 const logfile = buildServerDirectory(server, 'logs/peertube.log')
430 const buf = await readFile(logfile)
432 const matches = buf.toString().match(new RegExp(str, 'g'))
433 if (matches && matches.length === count) return
434 if (matches && strictCount === false && matches.length >= count) return
440 async function getServerFileSize (server: ServerInfo, subPath: string) {
441 const path = buildServerDirectory(server, subPath)
443 return getFileSize(path)
446 function makePingRequest (server: ServerInfo) {
447 return makeGetRequest({
449 path: '/api/v1/ping',
450 statusCodeExpected: 200
454 // ---------------------------------------------------------------------------
457 checkDirectoryIsEmpty,
463 flushAndRunMultipleServers,