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, 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
105 blacklistCommand?: BlacklistCommand
106 captionsCommand?: CaptionsCommand
107 changeOwnershipCommand?: ChangeOwnershipCommand
110 function parallelTests () {
111 return process.env.MOCHA_PARALLEL === 'true'
114 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
118 return new Promise<ServerInfo[]>(res => {
119 function anotherServerDone (serverNumber, app) {
120 apps[serverNumber - 1] = app
122 if (i === totalServers) {
127 for (let j = 1; j <= totalServers; j++) {
128 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
133 function flushTests (serverNumber?: number) {
134 return new Promise<void>((res, rej) => {
135 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
137 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
138 if (err || stderr) return rej(err || new Error(stderr))
145 function randomServer () {
149 return randomInt(low, high)
152 function randomRTMP () {
156 return randomInt(low, high)
159 type RunServerOptions = {
164 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
165 const parallel = parallelTests()
167 const internalServerNumber = parallel ? randomServer() : serverNumber
168 const rtmpPort = parallel ? randomRTMP() : 1936
169 const port = 9000 + internalServerNumber
171 await flushTests(internalServerNumber)
173 const server: ServerInfo = {
176 internalServerNumber,
180 url: `http://localhost:${port}`,
181 host: `localhost:${port}`,
182 hostname: 'localhost',
193 return runServer(server, configOverride, args, options)
196 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
197 // These actions are async so we need to be sure that they have both been done
198 const serverRunString = {
199 'HTTP server listening': false
201 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
202 serverRunString[key] = false
205 client_id: 'Client id: (.+)',
206 client_secret: 'Client secret: (.+)',
207 user_username: 'Username: (.+)',
208 user_password: 'User password: (.+)'
211 if (server.internalServerNumber !== server.serverNumber) {
212 const basePath = join(root(), 'config')
214 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
215 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
217 server.customConfigFile = tmpConfigFile
220 const configOverride: any = {}
222 if (server.parallel) {
223 Object.assign(configOverride, {
231 suffix: '_test' + server.internalServerNumber
234 tmp: `test${server.internalServerNumber}/tmp/`,
235 avatars: `test${server.internalServerNumber}/avatars/`,
236 videos: `test${server.internalServerNumber}/videos/`,
237 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
238 redundancy: `test${server.internalServerNumber}/redundancy/`,
239 logs: `test${server.internalServerNumber}/logs/`,
240 previews: `test${server.internalServerNumber}/previews/`,
241 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
242 torrents: `test${server.internalServerNumber}/torrents/`,
243 captions: `test${server.internalServerNumber}/captions/`,
244 cache: `test${server.internalServerNumber}/cache/`,
245 plugins: `test${server.internalServerNumber}/plugins/`
248 email: `admin${server.internalServerNumber}@example.com`
252 port: server.rtmpPort
258 if (configOverrideArg !== undefined) {
259 Object.assign(configOverride, configOverrideArg)
262 // Share the environment
263 const env = Object.create(process.env)
264 env['NODE_ENV'] = 'test'
265 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
266 env['NODE_CONFIG'] = JSON.stringify(configOverride)
268 const forkOptions = {
272 execArgv: options.execArgv || []
275 return new Promise<ServerInfo>(res => {
276 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
277 server.app.stdout.on('data', function onStdout (data) {
278 let dontContinue = false
280 // Capture things if we want to
281 for (const key of Object.keys(regexps)) {
282 const regexp = regexps[key]
283 const matches = data.toString().match(regexp)
284 if (matches !== null) {
285 if (key === 'client_id') server.client.id = matches[1]
286 else if (key === 'client_secret') server.client.secret = matches[1]
287 else if (key === 'user_username') server.user.username = matches[1]
288 else if (key === 'user_password') server.user.password = matches[1]
292 // Check if all required sentences are here
293 for (const key of Object.keys(serverRunString)) {
294 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
295 if (serverRunString[key] === false) dontContinue = true
298 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
299 if (dontContinue === true) return
301 if (options.hideLogs === false) {
302 console.log(data.toString())
304 server.app.stdout.removeListener('data', onStdout)
307 process.on('exit', () => {
309 process.kill(server.app.pid)
310 } catch { /* empty */ }
313 server.bulkCommand = new BulkCommand(server)
314 server.cliCommand = new CLICommand(server)
315 server.customPageCommand = new CustomPagesCommand(server)
316 server.feedCommand = new FeedCommand(server)
317 server.logsCommand = new LogsCommand(server)
318 server.abusesCommand = new AbusesCommand(server)
319 server.overviewsCommand = new OverviewsCommand(server)
320 server.searchCommand = new SearchCommand(server)
321 server.contactFormCommand = new ContactFormCommand(server)
322 server.debugCommand = new DebugCommand(server)
323 server.followsCommand = new FollowsCommand(server)
324 server.jobsCommand = new JobsCommand(server)
325 server.pluginsCommand = new PluginsCommand(server)
326 server.redundancyCommand = new RedundancyCommand(server)
327 server.statsCommand = new StatsCommand(server)
328 server.configCommand = new ConfigCommand(server)
329 server.socketIOCommand = new SocketIOCommand(server)
330 server.accountsCommand = new AccountsCommand(server)
331 server.blocklistCommand = new BlocklistCommand(server)
332 server.subscriptionsCommand = new SubscriptionsCommand(server)
333 server.liveCommand = new LiveCommand(server)
334 server.servicesCommand = new ServicesCommand(server)
335 server.blacklistCommand = new BlacklistCommand(server)
336 server.captionsCommand = new CaptionsCommand(server)
337 server.changeOwnershipCommand = new ChangeOwnershipCommand(server)
344 async function reRunServer (server: ServerInfo, configOverride?: any) {
345 const newServer = await runServer(server, configOverride)
346 server.app = newServer.app
351 async function checkTmpIsEmpty (server: ServerInfo) {
352 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
354 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
355 await checkDirectoryIsEmpty(server, 'tmp/hls')
359 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
360 const testDirectory = 'test' + server.internalServerNumber
362 const directoryPath = join(root(), testDirectory, directory)
364 const directoryExists = await pathExists(directoryPath)
365 expect(directoryExists).to.be.true
367 const files = await readdir(directoryPath)
368 const filtered = files.filter(f => exceptions.includes(f) === false)
370 expect(filtered).to.have.lengthOf(0)
373 function killallServers (servers: ServerInfo[]) {
374 for (const server of servers) {
375 if (!server.app) continue
377 process.kill(-server.app.pid)
382 async function cleanupTests (servers: ServerInfo[]) {
383 killallServers(servers)
386 await ensureDir('artifacts')
389 const p: Promise<any>[] = []
390 for (const server of servers) {
392 const origin = await buildServerDirectory(server, 'logs/peertube.log')
393 const destname = `peertube-${server.internalServerNumber}.log`
394 console.log('Saving logs %s.', destname)
396 await copy(origin, join('artifacts', destname))
399 if (server.parallel) {
400 p.push(flushTests(server.internalServerNumber))
403 if (server.customConfigFile) {
404 p.push(remove(server.customConfigFile))
408 return Promise.all(p)
411 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
412 const logfile = buildServerDirectory(server, 'logs/peertube.log')
415 const buf = await readFile(logfile)
417 const matches = buf.toString().match(new RegExp(str, 'g'))
418 if (matches && matches.length === count) return
419 if (matches && strictCount === false && matches.length >= count) return
425 async function getServerFileSize (server: ServerInfo, subPath: string) {
426 const path = buildServerDirectory(server, subPath)
428 return getFileSize(path)
431 function makePingRequest (server: ServerInfo) {
432 return makeGetRequest({
434 path: '/api/v1/ping',
435 statusCodeExpected: 200
439 // ---------------------------------------------------------------------------
442 checkDirectoryIsEmpty,
448 flushAndRunMultipleServers,