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 StreamingPlaylistsCommand
33 import { ConfigCommand } from './config-command'
34 import { ContactFormCommand } from './contact-form-command'
35 import { DebugCommand } from './debug-command'
36 import { FollowsCommand } from './follows-command'
37 import { JobsCommand } from './jobs-command'
38 import { PluginsCommand } from './plugins-command'
39 import { RedundancyCommand } from './redundancy-command'
40 import { StatsCommand } from './stats-command'
42 interface ServerInfo {
53 internalServerNumber: number
67 customConfigFile?: string
71 videoChannel?: VideoChannel
92 videos?: { id: number, uuid: string }[]
94 bulkCommand?: BulkCommand
95 cliCommand?: CLICommand
96 customPageCommand?: CustomPagesCommand
97 feedCommand?: FeedCommand
98 logsCommand?: LogsCommand
99 abusesCommand?: AbusesCommand
100 overviewsCommand?: OverviewsCommand
101 searchCommand?: SearchCommand
102 contactFormCommand?: ContactFormCommand
103 debugCommand?: DebugCommand
104 followsCommand?: FollowsCommand
105 jobsCommand?: JobsCommand
106 pluginsCommand?: PluginsCommand
107 redundancyCommand?: RedundancyCommand
108 statsCommand?: StatsCommand
109 configCommand?: ConfigCommand
110 socketIOCommand?: SocketIOCommand
111 accountsCommand?: AccountsCommand
112 blocklistCommand?: BlocklistCommand
113 subscriptionsCommand?: SubscriptionsCommand
114 liveCommand?: LiveCommand
115 servicesCommand?: ServicesCommand
116 blacklistCommand?: BlacklistCommand
117 captionsCommand?: CaptionsCommand
118 changeOwnershipCommand?: ChangeOwnershipCommand
119 playlistsCommand?: PlaylistsCommand
120 historyCommand?: HistoryCommand
121 importsCommand?: ImportsCommand
122 streamingPlaylistsCommand?: StreamingPlaylistsCommand
123 channelsCommand?: ChannelsCommand
126 function parallelTests () {
127 return process.env.MOCHA_PARALLEL === 'true'
130 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
134 return new Promise<ServerInfo[]>(res => {
135 function anotherServerDone (serverNumber, app) {
136 apps[serverNumber - 1] = app
138 if (i === totalServers) {
143 for (let j = 1; j <= totalServers; j++) {
144 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
149 function flushTests (serverNumber?: number) {
150 return new Promise<void>((res, rej) => {
151 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
153 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
154 if (err || stderr) return rej(err || new Error(stderr))
161 function randomServer () {
165 return randomInt(low, high)
168 function randomRTMP () {
172 return randomInt(low, high)
175 type RunServerOptions = {
180 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
181 const parallel = parallelTests()
183 const internalServerNumber = parallel ? randomServer() : serverNumber
184 const rtmpPort = parallel ? randomRTMP() : 1936
185 const port = 9000 + internalServerNumber
187 await flushTests(internalServerNumber)
189 const server: ServerInfo = {
192 internalServerNumber,
196 url: `http://localhost:${port}`,
197 host: `localhost:${port}`,
198 hostname: 'localhost',
209 return runServer(server, configOverride, args, options)
212 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
213 // These actions are async so we need to be sure that they have both been done
214 const serverRunString = {
215 'HTTP server listening': false
217 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
218 serverRunString[key] = false
221 client_id: 'Client id: (.+)',
222 client_secret: 'Client secret: (.+)',
223 user_username: 'Username: (.+)',
224 user_password: 'User password: (.+)'
227 if (server.internalServerNumber !== server.serverNumber) {
228 const basePath = join(root(), 'config')
230 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
231 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
233 server.customConfigFile = tmpConfigFile
236 const configOverride: any = {}
238 if (server.parallel) {
239 Object.assign(configOverride, {
247 suffix: '_test' + server.internalServerNumber
250 tmp: `test${server.internalServerNumber}/tmp/`,
251 avatars: `test${server.internalServerNumber}/avatars/`,
252 videos: `test${server.internalServerNumber}/videos/`,
253 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
254 redundancy: `test${server.internalServerNumber}/redundancy/`,
255 logs: `test${server.internalServerNumber}/logs/`,
256 previews: `test${server.internalServerNumber}/previews/`,
257 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
258 torrents: `test${server.internalServerNumber}/torrents/`,
259 captions: `test${server.internalServerNumber}/captions/`,
260 cache: `test${server.internalServerNumber}/cache/`,
261 plugins: `test${server.internalServerNumber}/plugins/`
264 email: `admin${server.internalServerNumber}@example.com`
268 port: server.rtmpPort
274 if (configOverrideArg !== undefined) {
275 Object.assign(configOverride, configOverrideArg)
278 // Share the environment
279 const env = Object.create(process.env)
280 env['NODE_ENV'] = 'test'
281 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
282 env['NODE_CONFIG'] = JSON.stringify(configOverride)
284 const forkOptions = {
288 execArgv: options.execArgv || []
291 return new Promise<ServerInfo>(res => {
292 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
293 server.app.stdout.on('data', function onStdout (data) {
294 let dontContinue = false
296 // Capture things if we want to
297 for (const key of Object.keys(regexps)) {
298 const regexp = regexps[key]
299 const matches = data.toString().match(regexp)
300 if (matches !== null) {
301 if (key === 'client_id') server.client.id = matches[1]
302 else if (key === 'client_secret') server.client.secret = matches[1]
303 else if (key === 'user_username') server.user.username = matches[1]
304 else if (key === 'user_password') server.user.password = matches[1]
308 // Check if all required sentences are here
309 for (const key of Object.keys(serverRunString)) {
310 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
311 if (serverRunString[key] === false) dontContinue = true
314 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
315 if (dontContinue === true) return
317 if (options.hideLogs === false) {
318 console.log(data.toString())
320 server.app.stdout.removeListener('data', onStdout)
323 process.on('exit', () => {
325 process.kill(server.app.pid)
326 } catch { /* empty */ }
329 server.bulkCommand = new BulkCommand(server)
330 server.cliCommand = new CLICommand(server)
331 server.customPageCommand = new CustomPagesCommand(server)
332 server.feedCommand = new FeedCommand(server)
333 server.logsCommand = new LogsCommand(server)
334 server.abusesCommand = new AbusesCommand(server)
335 server.overviewsCommand = new OverviewsCommand(server)
336 server.searchCommand = new SearchCommand(server)
337 server.contactFormCommand = new ContactFormCommand(server)
338 server.debugCommand = new DebugCommand(server)
339 server.followsCommand = new FollowsCommand(server)
340 server.jobsCommand = new JobsCommand(server)
341 server.pluginsCommand = new PluginsCommand(server)
342 server.redundancyCommand = new RedundancyCommand(server)
343 server.statsCommand = new StatsCommand(server)
344 server.configCommand = new ConfigCommand(server)
345 server.socketIOCommand = new SocketIOCommand(server)
346 server.accountsCommand = new AccountsCommand(server)
347 server.blocklistCommand = new BlocklistCommand(server)
348 server.subscriptionsCommand = new SubscriptionsCommand(server)
349 server.liveCommand = new LiveCommand(server)
350 server.servicesCommand = new ServicesCommand(server)
351 server.blacklistCommand = new BlacklistCommand(server)
352 server.captionsCommand = new CaptionsCommand(server)
353 server.changeOwnershipCommand = new ChangeOwnershipCommand(server)
354 server.playlistsCommand = new PlaylistsCommand(server)
355 server.historyCommand = new HistoryCommand(server)
356 server.importsCommand = new ImportsCommand(server)
357 server.streamingPlaylistsCommand = new StreamingPlaylistsCommand(server)
358 server.channelsCommand = new ChannelsCommand(server)
365 async function reRunServer (server: ServerInfo, configOverride?: any) {
366 const newServer = await runServer(server, configOverride)
367 server.app = newServer.app
372 async function checkTmpIsEmpty (server: ServerInfo) {
373 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
375 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
376 await checkDirectoryIsEmpty(server, 'tmp/hls')
380 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
381 const testDirectory = 'test' + server.internalServerNumber
383 const directoryPath = join(root(), testDirectory, directory)
385 const directoryExists = await pathExists(directoryPath)
386 expect(directoryExists).to.be.true
388 const files = await readdir(directoryPath)
389 const filtered = files.filter(f => exceptions.includes(f) === false)
391 expect(filtered).to.have.lengthOf(0)
394 function killallServers (servers: ServerInfo[]) {
395 for (const server of servers) {
396 if (!server.app) continue
398 process.kill(-server.app.pid)
403 async function cleanupTests (servers: ServerInfo[]) {
404 killallServers(servers)
407 await ensureDir('artifacts')
410 const p: Promise<any>[] = []
411 for (const server of servers) {
413 const origin = await buildServerDirectory(server, 'logs/peertube.log')
414 const destname = `peertube-${server.internalServerNumber}.log`
415 console.log('Saving logs %s.', destname)
417 await copy(origin, join('artifacts', destname))
420 if (server.parallel) {
421 p.push(flushTests(server.internalServerNumber))
424 if (server.customConfigFile) {
425 p.push(remove(server.customConfigFile))
429 return Promise.all(p)
432 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
433 const logfile = buildServerDirectory(server, 'logs/peertube.log')
436 const buf = await readFile(logfile)
438 const matches = buf.toString().match(new RegExp(str, 'g'))
439 if (matches && matches.length === count) return
440 if (matches && strictCount === false && matches.length >= count) return
446 async function getServerFileSize (server: ServerInfo, subPath: string) {
447 const path = buildServerDirectory(server, subPath)
449 return getFileSize(path)
452 function makePingRequest (server: ServerInfo) {
453 return makeGetRequest({
455 path: '/api/v1/ping',
456 statusCodeExpected: 200
460 // ---------------------------------------------------------------------------
463 checkDirectoryIsEmpty,
469 flushAndRunMultipleServers,