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 { SQLCommand } from '../miscs'
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
130 function parallelTests () {
131 return process.env.MOCHA_PARALLEL === 'true'
134 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
138 return new Promise<ServerInfo[]>(res => {
139 function anotherServerDone (serverNumber, app) {
140 apps[serverNumber - 1] = app
142 if (i === totalServers) {
147 for (let j = 1; j <= totalServers; j++) {
148 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
153 function flushTests (serverNumber?: number) {
154 return new Promise<void>((res, rej) => {
155 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
157 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
158 if (err || stderr) return rej(err || new Error(stderr))
165 function randomServer () {
169 return randomInt(low, high)
172 function randomRTMP () {
176 return randomInt(low, high)
179 type RunServerOptions = {
184 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
185 const parallel = parallelTests()
187 const internalServerNumber = parallel ? randomServer() : serverNumber
188 const rtmpPort = parallel ? randomRTMP() : 1936
189 const port = 9000 + internalServerNumber
191 await flushTests(internalServerNumber)
193 const server: ServerInfo = {
196 internalServerNumber,
200 url: `http://localhost:${port}`,
201 host: `localhost:${port}`,
202 hostname: 'localhost',
213 return runServer(server, configOverride, args, options)
216 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
217 // These actions are async so we need to be sure that they have both been done
218 const serverRunString = {
219 'HTTP server listening': false
221 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
222 serverRunString[key] = false
225 client_id: 'Client id: (.+)',
226 client_secret: 'Client secret: (.+)',
227 user_username: 'Username: (.+)',
228 user_password: 'User password: (.+)'
231 if (server.internalServerNumber !== server.serverNumber) {
232 const basePath = join(root(), 'config')
234 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
235 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
237 server.customConfigFile = tmpConfigFile
240 const configOverride: any = {}
242 if (server.parallel) {
243 Object.assign(configOverride, {
251 suffix: '_test' + server.internalServerNumber
254 tmp: `test${server.internalServerNumber}/tmp/`,
255 avatars: `test${server.internalServerNumber}/avatars/`,
256 videos: `test${server.internalServerNumber}/videos/`,
257 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
258 redundancy: `test${server.internalServerNumber}/redundancy/`,
259 logs: `test${server.internalServerNumber}/logs/`,
260 previews: `test${server.internalServerNumber}/previews/`,
261 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
262 torrents: `test${server.internalServerNumber}/torrents/`,
263 captions: `test${server.internalServerNumber}/captions/`,
264 cache: `test${server.internalServerNumber}/cache/`,
265 plugins: `test${server.internalServerNumber}/plugins/`
268 email: `admin${server.internalServerNumber}@example.com`
272 port: server.rtmpPort
278 if (configOverrideArg !== undefined) {
279 Object.assign(configOverride, configOverrideArg)
282 // Share the environment
283 const env = Object.create(process.env)
284 env['NODE_ENV'] = 'test'
285 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
286 env['NODE_CONFIG'] = JSON.stringify(configOverride)
288 const forkOptions = {
292 execArgv: options.execArgv || []
295 return new Promise<ServerInfo>(res => {
296 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
297 server.app.stdout.on('data', function onStdout (data) {
298 let dontContinue = false
300 // Capture things if we want to
301 for (const key of Object.keys(regexps)) {
302 const regexp = regexps[key]
303 const matches = data.toString().match(regexp)
304 if (matches !== null) {
305 if (key === 'client_id') server.client.id = matches[1]
306 else if (key === 'client_secret') server.client.secret = matches[1]
307 else if (key === 'user_username') server.user.username = matches[1]
308 else if (key === 'user_password') server.user.password = matches[1]
312 // Check if all required sentences are here
313 for (const key of Object.keys(serverRunString)) {
314 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
315 if (serverRunString[key] === false) dontContinue = true
318 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
319 if (dontContinue === true) return
321 if (options.hideLogs === false) {
322 console.log(data.toString())
324 server.app.stdout.removeListener('data', onStdout)
327 process.on('exit', () => {
329 process.kill(server.app.pid)
330 } catch { /* empty */ }
333 assignCommands(server)
340 function assignCommands (server: ServerInfo) {
341 server.bulkCommand = new BulkCommand(server)
342 server.cliCommand = new CLICommand(server)
343 server.customPageCommand = new CustomPagesCommand(server)
344 server.feedCommand = new FeedCommand(server)
345 server.logsCommand = new LogsCommand(server)
346 server.abusesCommand = new AbusesCommand(server)
347 server.overviewsCommand = new OverviewsCommand(server)
348 server.searchCommand = new SearchCommand(server)
349 server.contactFormCommand = new ContactFormCommand(server)
350 server.debugCommand = new DebugCommand(server)
351 server.followsCommand = new FollowsCommand(server)
352 server.jobsCommand = new JobsCommand(server)
353 server.pluginsCommand = new PluginsCommand(server)
354 server.redundancyCommand = new RedundancyCommand(server)
355 server.statsCommand = new StatsCommand(server)
356 server.configCommand = new ConfigCommand(server)
357 server.socketIOCommand = new SocketIOCommand(server)
358 server.accountsCommand = new AccountsCommand(server)
359 server.blocklistCommand = new BlocklistCommand(server)
360 server.subscriptionsCommand = new SubscriptionsCommand(server)
361 server.liveCommand = new LiveCommand(server)
362 server.servicesCommand = new ServicesCommand(server)
363 server.blacklistCommand = new BlacklistCommand(server)
364 server.captionsCommand = new CaptionsCommand(server)
365 server.changeOwnershipCommand = new ChangeOwnershipCommand(server)
366 server.playlistsCommand = new PlaylistsCommand(server)
367 server.historyCommand = new HistoryCommand(server)
368 server.importsCommand = new ImportsCommand(server)
369 server.streamingPlaylistsCommand = new StreamingPlaylistsCommand(server)
370 server.channelsCommand = new ChannelsCommand(server)
371 server.commentsCommand = new CommentsCommand(server)
372 server.sqlCommand = new SQLCommand(server)
375 async function reRunServer (server: ServerInfo, configOverride?: any) {
376 const newServer = await runServer(server, configOverride)
377 server.app = newServer.app
382 async function checkTmpIsEmpty (server: ServerInfo) {
383 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
385 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
386 await checkDirectoryIsEmpty(server, 'tmp/hls')
390 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
391 const testDirectory = 'test' + server.internalServerNumber
393 const directoryPath = join(root(), testDirectory, directory)
395 const directoryExists = await pathExists(directoryPath)
396 expect(directoryExists).to.be.true
398 const files = await readdir(directoryPath)
399 const filtered = files.filter(f => exceptions.includes(f) === false)
401 expect(filtered).to.have.lengthOf(0)
404 async function killallServers (servers: ServerInfo[]) {
405 for (const server of servers) {
406 if (!server.app) continue
408 await server.sqlCommand.cleanup()
410 process.kill(-server.app.pid)
416 async function cleanupTests (servers: ServerInfo[]) {
417 await killallServers(servers)
420 await ensureDir('artifacts')
423 const p: Promise<any>[] = []
424 for (const server of servers) {
426 const origin = await buildServerDirectory(server, 'logs/peertube.log')
427 const destname = `peertube-${server.internalServerNumber}.log`
428 console.log('Saving logs %s.', destname)
430 await copy(origin, join('artifacts', destname))
433 if (server.parallel) {
434 p.push(flushTests(server.internalServerNumber))
437 if (server.customConfigFile) {
438 p.push(remove(server.customConfigFile))
442 return Promise.all(p)
445 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
446 const logfile = buildServerDirectory(server, 'logs/peertube.log')
449 const buf = await readFile(logfile)
451 const matches = buf.toString().match(new RegExp(str, 'g'))
452 if (matches && matches.length === count) return
453 if (matches && strictCount === false && matches.length >= count) return
459 async function getServerFileSize (server: ServerInfo, subPath: string) {
460 const path = buildServerDirectory(server, subPath)
462 return getFileSize(path)
465 function makePingRequest (server: ServerInfo) {
466 return makeGetRequest({
468 path: '/api/v1/ping',
469 statusCodeExpected: 200
473 // ---------------------------------------------------------------------------
476 checkDirectoryIsEmpty,
482 flushAndRunMultipleServers,