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 { SQLCommand } from '../miscs'
15 import { buildServerDirectory, getFileSize, isGithubCI, root, wait } from '../miscs/miscs'
16 import { AbusesCommand } from '../moderation'
17 import { OverviewsCommand } from '../overviews'
18 import { makeGetRequest } from '../requests/requests'
19 import { SearchCommand } from '../search'
20 import { SocketIOCommand } from '../socket'
21 import { AccountsCommand, BlocklistCommand, NotificationsCommand, SubscriptionsCommand } from '../users'
25 ChangeOwnershipCommand,
32 StreamingPlaylistsCommand
34 import { CommentsCommand } from '../videos/comments-command'
35 import { ConfigCommand } from './config-command'
36 import { ContactFormCommand } from './contact-form-command'
37 import { DebugCommand } from './debug-command'
38 import { FollowsCommand } from './follows-command'
39 import { JobsCommand } from './jobs-command'
40 import { PluginsCommand } from './plugins-command'
41 import { RedundancyCommand } from './redundancy-command'
42 import { StatsCommand } from './stats-command'
44 interface ServerInfo {
55 internalServerNumber: number
69 customConfigFile?: string
73 videoChannel?: VideoChannel
94 videos?: { id: number, uuid: string }[]
96 bulkCommand?: BulkCommand
97 cliCommand?: CLICommand
98 customPageCommand?: CustomPagesCommand
99 feedCommand?: FeedCommand
100 logsCommand?: LogsCommand
101 abusesCommand?: AbusesCommand
102 overviewsCommand?: OverviewsCommand
103 searchCommand?: SearchCommand
104 contactFormCommand?: ContactFormCommand
105 debugCommand?: DebugCommand
106 followsCommand?: FollowsCommand
107 jobsCommand?: JobsCommand
108 pluginsCommand?: PluginsCommand
109 redundancyCommand?: RedundancyCommand
110 statsCommand?: StatsCommand
111 configCommand?: ConfigCommand
112 socketIOCommand?: SocketIOCommand
113 accountsCommand?: AccountsCommand
114 blocklistCommand?: BlocklistCommand
115 subscriptionsCommand?: SubscriptionsCommand
116 liveCommand?: LiveCommand
117 servicesCommand?: ServicesCommand
118 blacklistCommand?: BlacklistCommand
119 captionsCommand?: CaptionsCommand
120 changeOwnershipCommand?: ChangeOwnershipCommand
121 playlistsCommand?: PlaylistsCommand
122 historyCommand?: HistoryCommand
123 importsCommand?: ImportsCommand
124 streamingPlaylistsCommand?: StreamingPlaylistsCommand
125 channelsCommand?: ChannelsCommand
126 commentsCommand?: CommentsCommand
127 sqlCommand?: SQLCommand
128 notificationsCommand?: NotificationsCommand
131 function parallelTests () {
132 return process.env.MOCHA_PARALLEL === 'true'
135 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
139 return new Promise<ServerInfo[]>(res => {
140 function anotherServerDone (serverNumber, app) {
141 apps[serverNumber - 1] = app
143 if (i === totalServers) {
148 for (let j = 1; j <= totalServers; j++) {
149 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
154 function flushTests (serverNumber?: number) {
155 return new Promise<void>((res, rej) => {
156 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
158 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
159 if (err || stderr) return rej(err || new Error(stderr))
166 function randomServer () {
170 return randomInt(low, high)
173 function randomRTMP () {
177 return randomInt(low, high)
180 type RunServerOptions = {
185 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
186 const parallel = parallelTests()
188 const internalServerNumber = parallel ? randomServer() : serverNumber
189 const rtmpPort = parallel ? randomRTMP() : 1936
190 const port = 9000 + internalServerNumber
192 await flushTests(internalServerNumber)
194 const server: ServerInfo = {
197 internalServerNumber,
201 url: `http://localhost:${port}`,
202 host: `localhost:${port}`,
203 hostname: 'localhost',
214 return runServer(server, configOverride, args, options)
217 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
218 // These actions are async so we need to be sure that they have both been done
219 const serverRunString = {
220 'HTTP server listening': false
222 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
223 serverRunString[key] = false
226 client_id: 'Client id: (.+)',
227 client_secret: 'Client secret: (.+)',
228 user_username: 'Username: (.+)',
229 user_password: 'User password: (.+)'
232 if (server.internalServerNumber !== server.serverNumber) {
233 const basePath = join(root(), 'config')
235 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
236 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
238 server.customConfigFile = tmpConfigFile
241 const configOverride: any = {}
243 if (server.parallel) {
244 Object.assign(configOverride, {
252 suffix: '_test' + server.internalServerNumber
255 tmp: `test${server.internalServerNumber}/tmp/`,
256 avatars: `test${server.internalServerNumber}/avatars/`,
257 videos: `test${server.internalServerNumber}/videos/`,
258 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
259 redundancy: `test${server.internalServerNumber}/redundancy/`,
260 logs: `test${server.internalServerNumber}/logs/`,
261 previews: `test${server.internalServerNumber}/previews/`,
262 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
263 torrents: `test${server.internalServerNumber}/torrents/`,
264 captions: `test${server.internalServerNumber}/captions/`,
265 cache: `test${server.internalServerNumber}/cache/`,
266 plugins: `test${server.internalServerNumber}/plugins/`
269 email: `admin${server.internalServerNumber}@example.com`
273 port: server.rtmpPort
279 if (configOverrideArg !== undefined) {
280 Object.assign(configOverride, configOverrideArg)
283 // Share the environment
284 const env = Object.create(process.env)
285 env['NODE_ENV'] = 'test'
286 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
287 env['NODE_CONFIG'] = JSON.stringify(configOverride)
289 const forkOptions = {
293 execArgv: options.execArgv || []
296 return new Promise<ServerInfo>(res => {
297 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
298 server.app.stdout.on('data', function onStdout (data) {
299 let dontContinue = false
301 // Capture things if we want to
302 for (const key of Object.keys(regexps)) {
303 const regexp = regexps[key]
304 const matches = data.toString().match(regexp)
305 if (matches !== null) {
306 if (key === 'client_id') server.client.id = matches[1]
307 else if (key === 'client_secret') server.client.secret = matches[1]
308 else if (key === 'user_username') server.user.username = matches[1]
309 else if (key === 'user_password') server.user.password = matches[1]
313 // Check if all required sentences are here
314 for (const key of Object.keys(serverRunString)) {
315 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
316 if (serverRunString[key] === false) dontContinue = true
319 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
320 if (dontContinue === true) return
322 if (options.hideLogs === false) {
323 console.log(data.toString())
325 server.app.stdout.removeListener('data', onStdout)
328 process.on('exit', () => {
330 process.kill(server.app.pid)
331 } catch { /* empty */ }
334 assignCommands(server)
341 function assignCommands (server: ServerInfo) {
342 server.bulkCommand = new BulkCommand(server)
343 server.cliCommand = new CLICommand(server)
344 server.customPageCommand = new CustomPagesCommand(server)
345 server.feedCommand = new FeedCommand(server)
346 server.logsCommand = new LogsCommand(server)
347 server.abusesCommand = new AbusesCommand(server)
348 server.overviewsCommand = new OverviewsCommand(server)
349 server.searchCommand = new SearchCommand(server)
350 server.contactFormCommand = new ContactFormCommand(server)
351 server.debugCommand = new DebugCommand(server)
352 server.followsCommand = new FollowsCommand(server)
353 server.jobsCommand = new JobsCommand(server)
354 server.pluginsCommand = new PluginsCommand(server)
355 server.redundancyCommand = new RedundancyCommand(server)
356 server.statsCommand = new StatsCommand(server)
357 server.configCommand = new ConfigCommand(server)
358 server.socketIOCommand = new SocketIOCommand(server)
359 server.accountsCommand = new AccountsCommand(server)
360 server.blocklistCommand = new BlocklistCommand(server)
361 server.subscriptionsCommand = new SubscriptionsCommand(server)
362 server.liveCommand = new LiveCommand(server)
363 server.servicesCommand = new ServicesCommand(server)
364 server.blacklistCommand = new BlacklistCommand(server)
365 server.captionsCommand = new CaptionsCommand(server)
366 server.changeOwnershipCommand = new ChangeOwnershipCommand(server)
367 server.playlistsCommand = new PlaylistsCommand(server)
368 server.historyCommand = new HistoryCommand(server)
369 server.importsCommand = new ImportsCommand(server)
370 server.streamingPlaylistsCommand = new StreamingPlaylistsCommand(server)
371 server.channelsCommand = new ChannelsCommand(server)
372 server.commentsCommand = new CommentsCommand(server)
373 server.sqlCommand = new SQLCommand(server)
374 server.notificationsCommand = new NotificationsCommand(server)
377 async function reRunServer (server: ServerInfo, configOverride?: any) {
378 const newServer = await runServer(server, configOverride)
379 server.app = newServer.app
384 async function checkTmpIsEmpty (server: ServerInfo) {
385 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
387 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
388 await checkDirectoryIsEmpty(server, 'tmp/hls')
392 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
393 const testDirectory = 'test' + server.internalServerNumber
395 const directoryPath = join(root(), testDirectory, directory)
397 const directoryExists = await pathExists(directoryPath)
398 expect(directoryExists).to.be.true
400 const files = await readdir(directoryPath)
401 const filtered = files.filter(f => exceptions.includes(f) === false)
403 expect(filtered).to.have.lengthOf(0)
406 async function killallServers (servers: ServerInfo[]) {
407 for (const server of servers) {
408 if (!server.app) continue
410 await server.sqlCommand.cleanup()
412 process.kill(-server.app.pid)
418 async function cleanupTests (servers: ServerInfo[]) {
419 await killallServers(servers)
422 await ensureDir('artifacts')
425 const p: Promise<any>[] = []
426 for (const server of servers) {
428 const origin = await buildServerDirectory(server, 'logs/peertube.log')
429 const destname = `peertube-${server.internalServerNumber}.log`
430 console.log('Saving logs %s.', destname)
432 await copy(origin, join('artifacts', destname))
435 if (server.parallel) {
436 p.push(flushTests(server.internalServerNumber))
439 if (server.customConfigFile) {
440 p.push(remove(server.customConfigFile))
444 return Promise.all(p)
447 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
448 const logfile = buildServerDirectory(server, 'logs/peertube.log')
451 const buf = await readFile(logfile)
453 const matches = buf.toString().match(new RegExp(str, 'g'))
454 if (matches && matches.length === count) return
455 if (matches && strictCount === false && matches.length >= count) return
461 async function getServerFileSize (server: ServerInfo, subPath: string) {
462 const path = buildServerDirectory(server, subPath)
464 return getFileSize(path)
467 function makePingRequest (server: ServerInfo) {
468 return makeGetRequest({
470 path: '/api/v1/ping',
471 statusCodeExpected: 200
475 // ---------------------------------------------------------------------------
478 checkDirectoryIsEmpty,
484 flushAndRunMultipleServers,