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 { ContactFormCommand } from './contact-form-command'
20 import { DebugCommand } from './debug-command'
21 import { FollowsCommand } from './follows-command'
22 import { JobsCommand } from './jobs-command'
23 import { PluginsCommand } from './plugins-command'
24 import { RedundancyCommand } from './redundancy-command'
25 import { StatsCommand } from './stats-command'
27 interface ServerInfo {
38 internalServerNumber: number
52 customConfigFile?: string
56 videoChannel?: VideoChannel
77 videos?: { id: number, uuid: string }[]
79 bulkCommand?: BulkCommand
80 cliCommand?: CLICommand
81 customPageCommand?: CustomPagesCommand
82 feedCommand?: FeedCommand
83 logsCommand?: LogsCommand
84 abusesCommand?: AbusesCommand
85 overviewsCommand?: OverviewsCommand
86 searchCommand?: SearchCommand
87 contactFormCommand?: ContactFormCommand
88 debugCommand?: DebugCommand
89 followsCommand?: FollowsCommand
90 jobsCommand?: JobsCommand
91 pluginsCommand?: PluginsCommand
92 redundancyCommand?: RedundancyCommand
93 statsCommand?: StatsCommand
96 function parallelTests () {
97 return process.env.MOCHA_PARALLEL === 'true'
100 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
104 return new Promise<ServerInfo[]>(res => {
105 function anotherServerDone (serverNumber, app) {
106 apps[serverNumber - 1] = app
108 if (i === totalServers) {
113 for (let j = 1; j <= totalServers; j++) {
114 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
119 function flushTests (serverNumber?: number) {
120 return new Promise<void>((res, rej) => {
121 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
123 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
124 if (err || stderr) return rej(err || new Error(stderr))
131 function randomServer () {
135 return randomInt(low, high)
138 function randomRTMP () {
142 return randomInt(low, high)
145 type RunServerOptions = {
150 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
151 const parallel = parallelTests()
153 const internalServerNumber = parallel ? randomServer() : serverNumber
154 const rtmpPort = parallel ? randomRTMP() : 1936
155 const port = 9000 + internalServerNumber
157 await flushTests(internalServerNumber)
159 const server: ServerInfo = {
162 internalServerNumber,
166 url: `http://localhost:${port}`,
167 host: `localhost:${port}`,
168 hostname: 'localhost',
179 return runServer(server, configOverride, args, options)
182 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
183 // These actions are async so we need to be sure that they have both been done
184 const serverRunString = {
185 'HTTP server listening': false
187 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
188 serverRunString[key] = false
191 client_id: 'Client id: (.+)',
192 client_secret: 'Client secret: (.+)',
193 user_username: 'Username: (.+)',
194 user_password: 'User password: (.+)'
197 if (server.internalServerNumber !== server.serverNumber) {
198 const basePath = join(root(), 'config')
200 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
201 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
203 server.customConfigFile = tmpConfigFile
206 const configOverride: any = {}
208 if (server.parallel) {
209 Object.assign(configOverride, {
217 suffix: '_test' + server.internalServerNumber
220 tmp: `test${server.internalServerNumber}/tmp/`,
221 avatars: `test${server.internalServerNumber}/avatars/`,
222 videos: `test${server.internalServerNumber}/videos/`,
223 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
224 redundancy: `test${server.internalServerNumber}/redundancy/`,
225 logs: `test${server.internalServerNumber}/logs/`,
226 previews: `test${server.internalServerNumber}/previews/`,
227 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
228 torrents: `test${server.internalServerNumber}/torrents/`,
229 captions: `test${server.internalServerNumber}/captions/`,
230 cache: `test${server.internalServerNumber}/cache/`,
231 plugins: `test${server.internalServerNumber}/plugins/`
234 email: `admin${server.internalServerNumber}@example.com`
238 port: server.rtmpPort
244 if (configOverrideArg !== undefined) {
245 Object.assign(configOverride, configOverrideArg)
248 // Share the environment
249 const env = Object.create(process.env)
250 env['NODE_ENV'] = 'test'
251 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
252 env['NODE_CONFIG'] = JSON.stringify(configOverride)
254 const forkOptions = {
258 execArgv: options.execArgv || []
261 return new Promise<ServerInfo>(res => {
262 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
263 server.app.stdout.on('data', function onStdout (data) {
264 let dontContinue = false
266 // Capture things if we want to
267 for (const key of Object.keys(regexps)) {
268 const regexp = regexps[key]
269 const matches = data.toString().match(regexp)
270 if (matches !== null) {
271 if (key === 'client_id') server.client.id = matches[1]
272 else if (key === 'client_secret') server.client.secret = matches[1]
273 else if (key === 'user_username') server.user.username = matches[1]
274 else if (key === 'user_password') server.user.password = matches[1]
278 // Check if all required sentences are here
279 for (const key of Object.keys(serverRunString)) {
280 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
281 if (serverRunString[key] === false) dontContinue = true
284 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
285 if (dontContinue === true) return
287 if (options.hideLogs === false) {
288 console.log(data.toString())
290 server.app.stdout.removeListener('data', onStdout)
293 process.on('exit', () => {
295 process.kill(server.app.pid)
296 } catch { /* empty */ }
299 server.bulkCommand = new BulkCommand(server)
300 server.cliCommand = new CLICommand(server)
301 server.customPageCommand = new CustomPagesCommand(server)
302 server.feedCommand = new FeedCommand(server)
303 server.logsCommand = new LogsCommand(server)
304 server.abusesCommand = new AbusesCommand(server)
305 server.overviewsCommand = new OverviewsCommand(server)
306 server.searchCommand = new SearchCommand(server)
307 server.contactFormCommand = new ContactFormCommand(server)
308 server.debugCommand = new DebugCommand(server)
309 server.followsCommand = new FollowsCommand(server)
310 server.jobsCommand = new JobsCommand(server)
311 server.pluginsCommand = new PluginsCommand(server)
312 server.redundancyCommand = new RedundancyCommand(server)
313 server.statsCommand = new StatsCommand(server)
320 async function reRunServer (server: ServerInfo, configOverride?: any) {
321 const newServer = await runServer(server, configOverride)
322 server.app = newServer.app
327 async function checkTmpIsEmpty (server: ServerInfo) {
328 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
330 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
331 await checkDirectoryIsEmpty(server, 'tmp/hls')
335 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
336 const testDirectory = 'test' + server.internalServerNumber
338 const directoryPath = join(root(), testDirectory, directory)
340 const directoryExists = await pathExists(directoryPath)
341 expect(directoryExists).to.be.true
343 const files = await readdir(directoryPath)
344 const filtered = files.filter(f => exceptions.includes(f) === false)
346 expect(filtered).to.have.lengthOf(0)
349 function killallServers (servers: ServerInfo[]) {
350 for (const server of servers) {
351 if (!server.app) continue
353 process.kill(-server.app.pid)
358 async function cleanupTests (servers: ServerInfo[]) {
359 killallServers(servers)
362 await ensureDir('artifacts')
365 const p: Promise<any>[] = []
366 for (const server of servers) {
368 const origin = await buildServerDirectory(server, 'logs/peertube.log')
369 const destname = `peertube-${server.internalServerNumber}.log`
370 console.log('Saving logs %s.', destname)
372 await copy(origin, join('artifacts', destname))
375 if (server.parallel) {
376 p.push(flushTests(server.internalServerNumber))
379 if (server.customConfigFile) {
380 p.push(remove(server.customConfigFile))
384 return Promise.all(p)
387 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
388 const logfile = buildServerDirectory(server, 'logs/peertube.log')
391 const buf = await readFile(logfile)
393 const matches = buf.toString().match(new RegExp(str, 'g'))
394 if (matches && matches.length === count) return
395 if (matches && strictCount === false && matches.length >= count) return
401 async function getServerFileSize (server: ServerInfo, subPath: string) {
402 const path = buildServerDirectory(server, subPath)
404 return getFileSize(path)
407 function makePingRequest (server: ServerInfo) {
408 return makeGetRequest({
410 path: '/api/v1/ping',
411 statusCodeExpected: 200
415 // ---------------------------------------------------------------------------
418 checkDirectoryIsEmpty,
424 flushAndRunMultipleServers,