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 } 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
107 function parallelTests () {
108 return process.env.MOCHA_PARALLEL === 'true'
111 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
115 return new Promise<ServerInfo[]>(res => {
116 function anotherServerDone (serverNumber, app) {
117 apps[serverNumber - 1] = app
119 if (i === totalServers) {
124 for (let j = 1; j <= totalServers; j++) {
125 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
130 function flushTests (serverNumber?: number) {
131 return new Promise<void>((res, rej) => {
132 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
134 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
135 if (err || stderr) return rej(err || new Error(stderr))
142 function randomServer () {
146 return randomInt(low, high)
149 function randomRTMP () {
153 return randomInt(low, high)
156 type RunServerOptions = {
161 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
162 const parallel = parallelTests()
164 const internalServerNumber = parallel ? randomServer() : serverNumber
165 const rtmpPort = parallel ? randomRTMP() : 1936
166 const port = 9000 + internalServerNumber
168 await flushTests(internalServerNumber)
170 const server: ServerInfo = {
173 internalServerNumber,
177 url: `http://localhost:${port}`,
178 host: `localhost:${port}`,
179 hostname: 'localhost',
190 return runServer(server, configOverride, args, options)
193 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
194 // These actions are async so we need to be sure that they have both been done
195 const serverRunString = {
196 'HTTP server listening': false
198 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
199 serverRunString[key] = false
202 client_id: 'Client id: (.+)',
203 client_secret: 'Client secret: (.+)',
204 user_username: 'Username: (.+)',
205 user_password: 'User password: (.+)'
208 if (server.internalServerNumber !== server.serverNumber) {
209 const basePath = join(root(), 'config')
211 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
212 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
214 server.customConfigFile = tmpConfigFile
217 const configOverride: any = {}
219 if (server.parallel) {
220 Object.assign(configOverride, {
228 suffix: '_test' + server.internalServerNumber
231 tmp: `test${server.internalServerNumber}/tmp/`,
232 avatars: `test${server.internalServerNumber}/avatars/`,
233 videos: `test${server.internalServerNumber}/videos/`,
234 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
235 redundancy: `test${server.internalServerNumber}/redundancy/`,
236 logs: `test${server.internalServerNumber}/logs/`,
237 previews: `test${server.internalServerNumber}/previews/`,
238 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
239 torrents: `test${server.internalServerNumber}/torrents/`,
240 captions: `test${server.internalServerNumber}/captions/`,
241 cache: `test${server.internalServerNumber}/cache/`,
242 plugins: `test${server.internalServerNumber}/plugins/`
245 email: `admin${server.internalServerNumber}@example.com`
249 port: server.rtmpPort
255 if (configOverrideArg !== undefined) {
256 Object.assign(configOverride, configOverrideArg)
259 // Share the environment
260 const env = Object.create(process.env)
261 env['NODE_ENV'] = 'test'
262 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
263 env['NODE_CONFIG'] = JSON.stringify(configOverride)
265 const forkOptions = {
269 execArgv: options.execArgv || []
272 return new Promise<ServerInfo>(res => {
273 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
274 server.app.stdout.on('data', function onStdout (data) {
275 let dontContinue = false
277 // Capture things if we want to
278 for (const key of Object.keys(regexps)) {
279 const regexp = regexps[key]
280 const matches = data.toString().match(regexp)
281 if (matches !== null) {
282 if (key === 'client_id') server.client.id = matches[1]
283 else if (key === 'client_secret') server.client.secret = matches[1]
284 else if (key === 'user_username') server.user.username = matches[1]
285 else if (key === 'user_password') server.user.password = matches[1]
289 // Check if all required sentences are here
290 for (const key of Object.keys(serverRunString)) {
291 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
292 if (serverRunString[key] === false) dontContinue = true
295 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
296 if (dontContinue === true) return
298 if (options.hideLogs === false) {
299 console.log(data.toString())
301 server.app.stdout.removeListener('data', onStdout)
304 process.on('exit', () => {
306 process.kill(server.app.pid)
307 } catch { /* empty */ }
310 server.bulkCommand = new BulkCommand(server)
311 server.cliCommand = new CLICommand(server)
312 server.customPageCommand = new CustomPagesCommand(server)
313 server.feedCommand = new FeedCommand(server)
314 server.logsCommand = new LogsCommand(server)
315 server.abusesCommand = new AbusesCommand(server)
316 server.overviewsCommand = new OverviewsCommand(server)
317 server.searchCommand = new SearchCommand(server)
318 server.contactFormCommand = new ContactFormCommand(server)
319 server.debugCommand = new DebugCommand(server)
320 server.followsCommand = new FollowsCommand(server)
321 server.jobsCommand = new JobsCommand(server)
322 server.pluginsCommand = new PluginsCommand(server)
323 server.redundancyCommand = new RedundancyCommand(server)
324 server.statsCommand = new StatsCommand(server)
325 server.configCommand = new ConfigCommand(server)
326 server.socketIOCommand = new SocketIOCommand(server)
327 server.accountsCommand = new AccountsCommand(server)
328 server.blocklistCommand = new BlocklistCommand(server)
329 server.subscriptionsCommand = new SubscriptionsCommand(server)
330 server.liveCommand = new LiveCommand(server)
331 server.servicesCommand = new ServicesCommand(server)
338 async function reRunServer (server: ServerInfo, configOverride?: any) {
339 const newServer = await runServer(server, configOverride)
340 server.app = newServer.app
345 async function checkTmpIsEmpty (server: ServerInfo) {
346 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
348 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
349 await checkDirectoryIsEmpty(server, 'tmp/hls')
353 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
354 const testDirectory = 'test' + server.internalServerNumber
356 const directoryPath = join(root(), testDirectory, directory)
358 const directoryExists = await pathExists(directoryPath)
359 expect(directoryExists).to.be.true
361 const files = await readdir(directoryPath)
362 const filtered = files.filter(f => exceptions.includes(f) === false)
364 expect(filtered).to.have.lengthOf(0)
367 function killallServers (servers: ServerInfo[]) {
368 for (const server of servers) {
369 if (!server.app) continue
371 process.kill(-server.app.pid)
376 async function cleanupTests (servers: ServerInfo[]) {
377 killallServers(servers)
380 await ensureDir('artifacts')
383 const p: Promise<any>[] = []
384 for (const server of servers) {
386 const origin = await buildServerDirectory(server, 'logs/peertube.log')
387 const destname = `peertube-${server.internalServerNumber}.log`
388 console.log('Saving logs %s.', destname)
390 await copy(origin, join('artifacts', destname))
393 if (server.parallel) {
394 p.push(flushTests(server.internalServerNumber))
397 if (server.customConfigFile) {
398 p.push(remove(server.customConfigFile))
402 return Promise.all(p)
405 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
406 const logfile = buildServerDirectory(server, 'logs/peertube.log')
409 const buf = await readFile(logfile)
411 const matches = buf.toString().match(new RegExp(str, 'g'))
412 if (matches && matches.length === count) return
413 if (matches && strictCount === false && matches.length >= count) return
419 async function getServerFileSize (server: ServerInfo, subPath: string) {
420 const path = buildServerDirectory(server, subPath)
422 return getFileSize(path)
425 function makePingRequest (server: ServerInfo) {
426 return makeGetRequest({
428 path: '/api/v1/ping',
429 statusCodeExpected: 200
433 // ---------------------------------------------------------------------------
436 checkDirectoryIsEmpty,
442 flushAndRunMultipleServers,