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 { BlacklistCommand, CaptionsCommand, ChangeOwnershipCommand, HistoryCommand, LiveCommand, PlaylistsCommand, ServicesCommand } 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
104 servicesCommand?: ServicesCommand
105 blacklistCommand?: BlacklistCommand
106 captionsCommand?: CaptionsCommand
107 changeOwnershipCommand?: ChangeOwnershipCommand
108 playlistsCommand?: PlaylistsCommand
109 historyCommand?: HistoryCommand
112 function parallelTests () {
113 return process.env.MOCHA_PARALLEL === 'true'
116 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
120 return new Promise<ServerInfo[]>(res => {
121 function anotherServerDone (serverNumber, app) {
122 apps[serverNumber - 1] = app
124 if (i === totalServers) {
129 for (let j = 1; j <= totalServers; j++) {
130 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
135 function flushTests (serverNumber?: number) {
136 return new Promise<void>((res, rej) => {
137 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
139 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
140 if (err || stderr) return rej(err || new Error(stderr))
147 function randomServer () {
151 return randomInt(low, high)
154 function randomRTMP () {
158 return randomInt(low, high)
161 type RunServerOptions = {
166 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
167 const parallel = parallelTests()
169 const internalServerNumber = parallel ? randomServer() : serverNumber
170 const rtmpPort = parallel ? randomRTMP() : 1936
171 const port = 9000 + internalServerNumber
173 await flushTests(internalServerNumber)
175 const server: ServerInfo = {
178 internalServerNumber,
182 url: `http://localhost:${port}`,
183 host: `localhost:${port}`,
184 hostname: 'localhost',
195 return runServer(server, configOverride, args, options)
198 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
199 // These actions are async so we need to be sure that they have both been done
200 const serverRunString = {
201 'HTTP server listening': false
203 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
204 serverRunString[key] = false
207 client_id: 'Client id: (.+)',
208 client_secret: 'Client secret: (.+)',
209 user_username: 'Username: (.+)',
210 user_password: 'User password: (.+)'
213 if (server.internalServerNumber !== server.serverNumber) {
214 const basePath = join(root(), 'config')
216 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
217 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
219 server.customConfigFile = tmpConfigFile
222 const configOverride: any = {}
224 if (server.parallel) {
225 Object.assign(configOverride, {
233 suffix: '_test' + server.internalServerNumber
236 tmp: `test${server.internalServerNumber}/tmp/`,
237 avatars: `test${server.internalServerNumber}/avatars/`,
238 videos: `test${server.internalServerNumber}/videos/`,
239 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
240 redundancy: `test${server.internalServerNumber}/redundancy/`,
241 logs: `test${server.internalServerNumber}/logs/`,
242 previews: `test${server.internalServerNumber}/previews/`,
243 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
244 torrents: `test${server.internalServerNumber}/torrents/`,
245 captions: `test${server.internalServerNumber}/captions/`,
246 cache: `test${server.internalServerNumber}/cache/`,
247 plugins: `test${server.internalServerNumber}/plugins/`
250 email: `admin${server.internalServerNumber}@example.com`
254 port: server.rtmpPort
260 if (configOverrideArg !== undefined) {
261 Object.assign(configOverride, configOverrideArg)
264 // Share the environment
265 const env = Object.create(process.env)
266 env['NODE_ENV'] = 'test'
267 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
268 env['NODE_CONFIG'] = JSON.stringify(configOverride)
270 const forkOptions = {
274 execArgv: options.execArgv || []
277 return new Promise<ServerInfo>(res => {
278 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
279 server.app.stdout.on('data', function onStdout (data) {
280 let dontContinue = false
282 // Capture things if we want to
283 for (const key of Object.keys(regexps)) {
284 const regexp = regexps[key]
285 const matches = data.toString().match(regexp)
286 if (matches !== null) {
287 if (key === 'client_id') server.client.id = matches[1]
288 else if (key === 'client_secret') server.client.secret = matches[1]
289 else if (key === 'user_username') server.user.username = matches[1]
290 else if (key === 'user_password') server.user.password = matches[1]
294 // Check if all required sentences are here
295 for (const key of Object.keys(serverRunString)) {
296 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
297 if (serverRunString[key] === false) dontContinue = true
300 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
301 if (dontContinue === true) return
303 if (options.hideLogs === false) {
304 console.log(data.toString())
306 server.app.stdout.removeListener('data', onStdout)
309 process.on('exit', () => {
311 process.kill(server.app.pid)
312 } catch { /* empty */ }
315 server.bulkCommand = new BulkCommand(server)
316 server.cliCommand = new CLICommand(server)
317 server.customPageCommand = new CustomPagesCommand(server)
318 server.feedCommand = new FeedCommand(server)
319 server.logsCommand = new LogsCommand(server)
320 server.abusesCommand = new AbusesCommand(server)
321 server.overviewsCommand = new OverviewsCommand(server)
322 server.searchCommand = new SearchCommand(server)
323 server.contactFormCommand = new ContactFormCommand(server)
324 server.debugCommand = new DebugCommand(server)
325 server.followsCommand = new FollowsCommand(server)
326 server.jobsCommand = new JobsCommand(server)
327 server.pluginsCommand = new PluginsCommand(server)
328 server.redundancyCommand = new RedundancyCommand(server)
329 server.statsCommand = new StatsCommand(server)
330 server.configCommand = new ConfigCommand(server)
331 server.socketIOCommand = new SocketIOCommand(server)
332 server.accountsCommand = new AccountsCommand(server)
333 server.blocklistCommand = new BlocklistCommand(server)
334 server.subscriptionsCommand = new SubscriptionsCommand(server)
335 server.liveCommand = new LiveCommand(server)
336 server.servicesCommand = new ServicesCommand(server)
337 server.blacklistCommand = new BlacklistCommand(server)
338 server.captionsCommand = new CaptionsCommand(server)
339 server.changeOwnershipCommand = new ChangeOwnershipCommand(server)
340 server.playlistsCommand = new PlaylistsCommand(server)
341 server.historyCommand = new HistoryCommand(server)
348 async function reRunServer (server: ServerInfo, configOverride?: any) {
349 const newServer = await runServer(server, configOverride)
350 server.app = newServer.app
355 async function checkTmpIsEmpty (server: ServerInfo) {
356 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
358 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
359 await checkDirectoryIsEmpty(server, 'tmp/hls')
363 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
364 const testDirectory = 'test' + server.internalServerNumber
366 const directoryPath = join(root(), testDirectory, directory)
368 const directoryExists = await pathExists(directoryPath)
369 expect(directoryExists).to.be.true
371 const files = await readdir(directoryPath)
372 const filtered = files.filter(f => exceptions.includes(f) === false)
374 expect(filtered).to.have.lengthOf(0)
377 function killallServers (servers: ServerInfo[]) {
378 for (const server of servers) {
379 if (!server.app) continue
381 process.kill(-server.app.pid)
386 async function cleanupTests (servers: ServerInfo[]) {
387 killallServers(servers)
390 await ensureDir('artifacts')
393 const p: Promise<any>[] = []
394 for (const server of servers) {
396 const origin = await buildServerDirectory(server, 'logs/peertube.log')
397 const destname = `peertube-${server.internalServerNumber}.log`
398 console.log('Saving logs %s.', destname)
400 await copy(origin, join('artifacts', destname))
403 if (server.parallel) {
404 p.push(flushTests(server.internalServerNumber))
407 if (server.customConfigFile) {
408 p.push(remove(server.customConfigFile))
412 return Promise.all(p)
415 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
416 const logfile = buildServerDirectory(server, 'logs/peertube.log')
419 const buf = await readFile(logfile)
421 const matches = buf.toString().match(new RegExp(str, 'g'))
422 if (matches && matches.length === count) return
423 if (matches && strictCount === false && matches.length >= count) return
429 async function getServerFileSize (server: ServerInfo, subPath: string) {
430 const path = buildServerDirectory(server, subPath)
432 return getFileSize(path)
435 function makePingRequest (server: ServerInfo) {
436 return makeGetRequest({
438 path: '/api/v1/ping',
439 statusCodeExpected: 200
443 // ---------------------------------------------------------------------------
446 checkDirectoryIsEmpty,
452 flushAndRunMultipleServers,