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 { LiveCommand, ServicesCommand, BlacklistCommand, CaptionsCommand } 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
109 function parallelTests () {
110 return process.env.MOCHA_PARALLEL === 'true'
113 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
117 return new Promise<ServerInfo[]>(res => {
118 function anotherServerDone (serverNumber, app) {
119 apps[serverNumber - 1] = app
121 if (i === totalServers) {
126 for (let j = 1; j <= totalServers; j++) {
127 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
132 function flushTests (serverNumber?: number) {
133 return new Promise<void>((res, rej) => {
134 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
136 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
137 if (err || stderr) return rej(err || new Error(stderr))
144 function randomServer () {
148 return randomInt(low, high)
151 function randomRTMP () {
155 return randomInt(low, high)
158 type RunServerOptions = {
163 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
164 const parallel = parallelTests()
166 const internalServerNumber = parallel ? randomServer() : serverNumber
167 const rtmpPort = parallel ? randomRTMP() : 1936
168 const port = 9000 + internalServerNumber
170 await flushTests(internalServerNumber)
172 const server: ServerInfo = {
175 internalServerNumber,
179 url: `http://localhost:${port}`,
180 host: `localhost:${port}`,
181 hostname: 'localhost',
192 return runServer(server, configOverride, args, options)
195 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
196 // These actions are async so we need to be sure that they have both been done
197 const serverRunString = {
198 'HTTP server listening': false
200 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
201 serverRunString[key] = false
204 client_id: 'Client id: (.+)',
205 client_secret: 'Client secret: (.+)',
206 user_username: 'Username: (.+)',
207 user_password: 'User password: (.+)'
210 if (server.internalServerNumber !== server.serverNumber) {
211 const basePath = join(root(), 'config')
213 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
214 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
216 server.customConfigFile = tmpConfigFile
219 const configOverride: any = {}
221 if (server.parallel) {
222 Object.assign(configOverride, {
230 suffix: '_test' + server.internalServerNumber
233 tmp: `test${server.internalServerNumber}/tmp/`,
234 avatars: `test${server.internalServerNumber}/avatars/`,
235 videos: `test${server.internalServerNumber}/videos/`,
236 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
237 redundancy: `test${server.internalServerNumber}/redundancy/`,
238 logs: `test${server.internalServerNumber}/logs/`,
239 previews: `test${server.internalServerNumber}/previews/`,
240 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
241 torrents: `test${server.internalServerNumber}/torrents/`,
242 captions: `test${server.internalServerNumber}/captions/`,
243 cache: `test${server.internalServerNumber}/cache/`,
244 plugins: `test${server.internalServerNumber}/plugins/`
247 email: `admin${server.internalServerNumber}@example.com`
251 port: server.rtmpPort
257 if (configOverrideArg !== undefined) {
258 Object.assign(configOverride, configOverrideArg)
261 // Share the environment
262 const env = Object.create(process.env)
263 env['NODE_ENV'] = 'test'
264 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
265 env['NODE_CONFIG'] = JSON.stringify(configOverride)
267 const forkOptions = {
271 execArgv: options.execArgv || []
274 return new Promise<ServerInfo>(res => {
275 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
276 server.app.stdout.on('data', function onStdout (data) {
277 let dontContinue = false
279 // Capture things if we want to
280 for (const key of Object.keys(regexps)) {
281 const regexp = regexps[key]
282 const matches = data.toString().match(regexp)
283 if (matches !== null) {
284 if (key === 'client_id') server.client.id = matches[1]
285 else if (key === 'client_secret') server.client.secret = matches[1]
286 else if (key === 'user_username') server.user.username = matches[1]
287 else if (key === 'user_password') server.user.password = matches[1]
291 // Check if all required sentences are here
292 for (const key of Object.keys(serverRunString)) {
293 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
294 if (serverRunString[key] === false) dontContinue = true
297 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
298 if (dontContinue === true) return
300 if (options.hideLogs === false) {
301 console.log(data.toString())
303 server.app.stdout.removeListener('data', onStdout)
306 process.on('exit', () => {
308 process.kill(server.app.pid)
309 } catch { /* empty */ }
312 server.bulkCommand = new BulkCommand(server)
313 server.cliCommand = new CLICommand(server)
314 server.customPageCommand = new CustomPagesCommand(server)
315 server.feedCommand = new FeedCommand(server)
316 server.logsCommand = new LogsCommand(server)
317 server.abusesCommand = new AbusesCommand(server)
318 server.overviewsCommand = new OverviewsCommand(server)
319 server.searchCommand = new SearchCommand(server)
320 server.contactFormCommand = new ContactFormCommand(server)
321 server.debugCommand = new DebugCommand(server)
322 server.followsCommand = new FollowsCommand(server)
323 server.jobsCommand = new JobsCommand(server)
324 server.pluginsCommand = new PluginsCommand(server)
325 server.redundancyCommand = new RedundancyCommand(server)
326 server.statsCommand = new StatsCommand(server)
327 server.configCommand = new ConfigCommand(server)
328 server.socketIOCommand = new SocketIOCommand(server)
329 server.accountsCommand = new AccountsCommand(server)
330 server.blocklistCommand = new BlocklistCommand(server)
331 server.subscriptionsCommand = new SubscriptionsCommand(server)
332 server.liveCommand = new LiveCommand(server)
333 server.servicesCommand = new ServicesCommand(server)
334 server.blacklistCommand = new BlacklistCommand(server)
335 server.captionsCommand = new CaptionsCommand(server)
342 async function reRunServer (server: ServerInfo, configOverride?: any) {
343 const newServer = await runServer(server, configOverride)
344 server.app = newServer.app
349 async function checkTmpIsEmpty (server: ServerInfo) {
350 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
352 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
353 await checkDirectoryIsEmpty(server, 'tmp/hls')
357 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
358 const testDirectory = 'test' + server.internalServerNumber
360 const directoryPath = join(root(), testDirectory, directory)
362 const directoryExists = await pathExists(directoryPath)
363 expect(directoryExists).to.be.true
365 const files = await readdir(directoryPath)
366 const filtered = files.filter(f => exceptions.includes(f) === false)
368 expect(filtered).to.have.lengthOf(0)
371 function killallServers (servers: ServerInfo[]) {
372 for (const server of servers) {
373 if (!server.app) continue
375 process.kill(-server.app.pid)
380 async function cleanupTests (servers: ServerInfo[]) {
381 killallServers(servers)
384 await ensureDir('artifacts')
387 const p: Promise<any>[] = []
388 for (const server of servers) {
390 const origin = await buildServerDirectory(server, 'logs/peertube.log')
391 const destname = `peertube-${server.internalServerNumber}.log`
392 console.log('Saving logs %s.', destname)
394 await copy(origin, join('artifacts', destname))
397 if (server.parallel) {
398 p.push(flushTests(server.internalServerNumber))
401 if (server.customConfigFile) {
402 p.push(remove(server.customConfigFile))
406 return Promise.all(p)
409 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
410 const logfile = buildServerDirectory(server, 'logs/peertube.log')
413 const buf = await readFile(logfile)
415 const matches = buf.toString().match(new RegExp(str, 'g'))
416 if (matches && matches.length === count) return
417 if (matches && strictCount === false && matches.length >= count) return
423 async function getServerFileSize (server: ServerInfo, subPath: string) {
424 const path = buildServerDirectory(server, subPath)
426 return getFileSize(path)
429 function makePingRequest (server: ServerInfo) {
430 return makeGetRequest({
432 path: '/api/v1/ping',
433 statusCodeExpected: 200
437 // ---------------------------------------------------------------------------
440 checkDirectoryIsEmpty,
446 flushAndRunMultipleServers,