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 { CommentsCommand } from '../videos/comments-command'
34 import { ConfigCommand } from './config-command'
35 import { ContactFormCommand } from './contact-form-command'
36 import { DebugCommand } from './debug-command'
37 import { FollowsCommand } from './follows-command'
38 import { JobsCommand } from './jobs-command'
39 import { PluginsCommand } from './plugins-command'
40 import { RedundancyCommand } from './redundancy-command'
41 import { StatsCommand } from './stats-command'
43 interface ServerInfo {
54 internalServerNumber: number
68 customConfigFile?: string
72 videoChannel?: VideoChannel
93 videos?: { id: number, uuid: string }[]
95 bulkCommand?: BulkCommand
96 cliCommand?: CLICommand
97 customPageCommand?: CustomPagesCommand
98 feedCommand?: FeedCommand
99 logsCommand?: LogsCommand
100 abusesCommand?: AbusesCommand
101 overviewsCommand?: OverviewsCommand
102 searchCommand?: SearchCommand
103 contactFormCommand?: ContactFormCommand
104 debugCommand?: DebugCommand
105 followsCommand?: FollowsCommand
106 jobsCommand?: JobsCommand
107 pluginsCommand?: PluginsCommand
108 redundancyCommand?: RedundancyCommand
109 statsCommand?: StatsCommand
110 configCommand?: ConfigCommand
111 socketIOCommand?: SocketIOCommand
112 accountsCommand?: AccountsCommand
113 blocklistCommand?: BlocklistCommand
114 subscriptionsCommand?: SubscriptionsCommand
115 liveCommand?: LiveCommand
116 servicesCommand?: ServicesCommand
117 blacklistCommand?: BlacklistCommand
118 captionsCommand?: CaptionsCommand
119 changeOwnershipCommand?: ChangeOwnershipCommand
120 playlistsCommand?: PlaylistsCommand
121 historyCommand?: HistoryCommand
122 importsCommand?: ImportsCommand
123 streamingPlaylistsCommand?: StreamingPlaylistsCommand
124 channelsCommand?: ChannelsCommand
125 commentsCommand?: CommentsCommand
128 function parallelTests () {
129 return process.env.MOCHA_PARALLEL === 'true'
132 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
136 return new Promise<ServerInfo[]>(res => {
137 function anotherServerDone (serverNumber, app) {
138 apps[serverNumber - 1] = app
140 if (i === totalServers) {
145 for (let j = 1; j <= totalServers; j++) {
146 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
151 function flushTests (serverNumber?: number) {
152 return new Promise<void>((res, rej) => {
153 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
155 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
156 if (err || stderr) return rej(err || new Error(stderr))
163 function randomServer () {
167 return randomInt(low, high)
170 function randomRTMP () {
174 return randomInt(low, high)
177 type RunServerOptions = {
182 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
183 const parallel = parallelTests()
185 const internalServerNumber = parallel ? randomServer() : serverNumber
186 const rtmpPort = parallel ? randomRTMP() : 1936
187 const port = 9000 + internalServerNumber
189 await flushTests(internalServerNumber)
191 const server: ServerInfo = {
194 internalServerNumber,
198 url: `http://localhost:${port}`,
199 host: `localhost:${port}`,
200 hostname: 'localhost',
211 return runServer(server, configOverride, args, options)
214 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
215 // These actions are async so we need to be sure that they have both been done
216 const serverRunString = {
217 'HTTP server listening': false
219 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
220 serverRunString[key] = false
223 client_id: 'Client id: (.+)',
224 client_secret: 'Client secret: (.+)',
225 user_username: 'Username: (.+)',
226 user_password: 'User password: (.+)'
229 if (server.internalServerNumber !== server.serverNumber) {
230 const basePath = join(root(), 'config')
232 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
233 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
235 server.customConfigFile = tmpConfigFile
238 const configOverride: any = {}
240 if (server.parallel) {
241 Object.assign(configOverride, {
249 suffix: '_test' + server.internalServerNumber
252 tmp: `test${server.internalServerNumber}/tmp/`,
253 avatars: `test${server.internalServerNumber}/avatars/`,
254 videos: `test${server.internalServerNumber}/videos/`,
255 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
256 redundancy: `test${server.internalServerNumber}/redundancy/`,
257 logs: `test${server.internalServerNumber}/logs/`,
258 previews: `test${server.internalServerNumber}/previews/`,
259 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
260 torrents: `test${server.internalServerNumber}/torrents/`,
261 captions: `test${server.internalServerNumber}/captions/`,
262 cache: `test${server.internalServerNumber}/cache/`,
263 plugins: `test${server.internalServerNumber}/plugins/`
266 email: `admin${server.internalServerNumber}@example.com`
270 port: server.rtmpPort
276 if (configOverrideArg !== undefined) {
277 Object.assign(configOverride, configOverrideArg)
280 // Share the environment
281 const env = Object.create(process.env)
282 env['NODE_ENV'] = 'test'
283 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
284 env['NODE_CONFIG'] = JSON.stringify(configOverride)
286 const forkOptions = {
290 execArgv: options.execArgv || []
293 return new Promise<ServerInfo>(res => {
294 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
295 server.app.stdout.on('data', function onStdout (data) {
296 let dontContinue = false
298 // Capture things if we want to
299 for (const key of Object.keys(regexps)) {
300 const regexp = regexps[key]
301 const matches = data.toString().match(regexp)
302 if (matches !== null) {
303 if (key === 'client_id') server.client.id = matches[1]
304 else if (key === 'client_secret') server.client.secret = matches[1]
305 else if (key === 'user_username') server.user.username = matches[1]
306 else if (key === 'user_password') server.user.password = matches[1]
310 // Check if all required sentences are here
311 for (const key of Object.keys(serverRunString)) {
312 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
313 if (serverRunString[key] === false) dontContinue = true
316 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
317 if (dontContinue === true) return
319 if (options.hideLogs === false) {
320 console.log(data.toString())
322 server.app.stdout.removeListener('data', onStdout)
325 process.on('exit', () => {
327 process.kill(server.app.pid)
328 } catch { /* empty */ }
331 server.bulkCommand = new BulkCommand(server)
332 server.cliCommand = new CLICommand(server)
333 server.customPageCommand = new CustomPagesCommand(server)
334 server.feedCommand = new FeedCommand(server)
335 server.logsCommand = new LogsCommand(server)
336 server.abusesCommand = new AbusesCommand(server)
337 server.overviewsCommand = new OverviewsCommand(server)
338 server.searchCommand = new SearchCommand(server)
339 server.contactFormCommand = new ContactFormCommand(server)
340 server.debugCommand = new DebugCommand(server)
341 server.followsCommand = new FollowsCommand(server)
342 server.jobsCommand = new JobsCommand(server)
343 server.pluginsCommand = new PluginsCommand(server)
344 server.redundancyCommand = new RedundancyCommand(server)
345 server.statsCommand = new StatsCommand(server)
346 server.configCommand = new ConfigCommand(server)
347 server.socketIOCommand = new SocketIOCommand(server)
348 server.accountsCommand = new AccountsCommand(server)
349 server.blocklistCommand = new BlocklistCommand(server)
350 server.subscriptionsCommand = new SubscriptionsCommand(server)
351 server.liveCommand = new LiveCommand(server)
352 server.servicesCommand = new ServicesCommand(server)
353 server.blacklistCommand = new BlacklistCommand(server)
354 server.captionsCommand = new CaptionsCommand(server)
355 server.changeOwnershipCommand = new ChangeOwnershipCommand(server)
356 server.playlistsCommand = new PlaylistsCommand(server)
357 server.historyCommand = new HistoryCommand(server)
358 server.importsCommand = new ImportsCommand(server)
359 server.streamingPlaylistsCommand = new StreamingPlaylistsCommand(server)
360 server.channelsCommand = new ChannelsCommand(server)
361 server.commentsCommand = new CommentsCommand(server)
368 async function reRunServer (server: ServerInfo, configOverride?: any) {
369 const newServer = await runServer(server, configOverride)
370 server.app = newServer.app
375 async function checkTmpIsEmpty (server: ServerInfo) {
376 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
378 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
379 await checkDirectoryIsEmpty(server, 'tmp/hls')
383 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
384 const testDirectory = 'test' + server.internalServerNumber
386 const directoryPath = join(root(), testDirectory, directory)
388 const directoryExists = await pathExists(directoryPath)
389 expect(directoryExists).to.be.true
391 const files = await readdir(directoryPath)
392 const filtered = files.filter(f => exceptions.includes(f) === false)
394 expect(filtered).to.have.lengthOf(0)
397 function killallServers (servers: ServerInfo[]) {
398 for (const server of servers) {
399 if (!server.app) continue
401 process.kill(-server.app.pid)
406 async function cleanupTests (servers: ServerInfo[]) {
407 killallServers(servers)
410 await ensureDir('artifacts')
413 const p: Promise<any>[] = []
414 for (const server of servers) {
416 const origin = await buildServerDirectory(server, 'logs/peertube.log')
417 const destname = `peertube-${server.internalServerNumber}.log`
418 console.log('Saving logs %s.', destname)
420 await copy(origin, join('artifacts', destname))
423 if (server.parallel) {
424 p.push(flushTests(server.internalServerNumber))
427 if (server.customConfigFile) {
428 p.push(remove(server.customConfigFile))
432 return Promise.all(p)
435 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
436 const logfile = buildServerDirectory(server, 'logs/peertube.log')
439 const buf = await readFile(logfile)
441 const matches = buf.toString().match(new RegExp(str, 'g'))
442 if (matches && matches.length === count) return
443 if (matches && strictCount === false && matches.length >= count) return
449 async function getServerFileSize (server: ServerInfo, subPath: string) {
450 const path = buildServerDirectory(server, subPath)
452 return getFileSize(path)
455 function makePingRequest (server: ServerInfo) {
456 return makeGetRequest({
458 path: '/api/v1/ping',
459 statusCodeExpected: 200
463 // ---------------------------------------------------------------------------
466 checkDirectoryIsEmpty,
472 flushAndRunMultipleServers,