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 { ConfigCommand } from './config-command'
20 import { ContactFormCommand } from './contact-form-command'
21 import { DebugCommand } from './debug-command'
22 import { FollowsCommand } from './follows-command'
23 import { JobsCommand } from './jobs-command'
24 import { PluginsCommand } from './plugins-command'
25 import { RedundancyCommand } from './redundancy-command'
26 import { StatsCommand } from './stats-command'
28 interface ServerInfo {
39 internalServerNumber: number
53 customConfigFile?: string
57 videoChannel?: VideoChannel
78 videos?: { id: number, uuid: string }[]
80 bulkCommand?: BulkCommand
81 cliCommand?: CLICommand
82 customPageCommand?: CustomPagesCommand
83 feedCommand?: FeedCommand
84 logsCommand?: LogsCommand
85 abusesCommand?: AbusesCommand
86 overviewsCommand?: OverviewsCommand
87 searchCommand?: SearchCommand
88 contactFormCommand?: ContactFormCommand
89 debugCommand?: DebugCommand
90 followsCommand?: FollowsCommand
91 jobsCommand?: JobsCommand
92 pluginsCommand?: PluginsCommand
93 redundancyCommand?: RedundancyCommand
94 statsCommand?: StatsCommand
95 configCommand?: ConfigCommand
98 function parallelTests () {
99 return process.env.MOCHA_PARALLEL === 'true'
102 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
106 return new Promise<ServerInfo[]>(res => {
107 function anotherServerDone (serverNumber, app) {
108 apps[serverNumber - 1] = app
110 if (i === totalServers) {
115 for (let j = 1; j <= totalServers; j++) {
116 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
121 function flushTests (serverNumber?: number) {
122 return new Promise<void>((res, rej) => {
123 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
125 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
126 if (err || stderr) return rej(err || new Error(stderr))
133 function randomServer () {
137 return randomInt(low, high)
140 function randomRTMP () {
144 return randomInt(low, high)
147 type RunServerOptions = {
152 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
153 const parallel = parallelTests()
155 const internalServerNumber = parallel ? randomServer() : serverNumber
156 const rtmpPort = parallel ? randomRTMP() : 1936
157 const port = 9000 + internalServerNumber
159 await flushTests(internalServerNumber)
161 const server: ServerInfo = {
164 internalServerNumber,
168 url: `http://localhost:${port}`,
169 host: `localhost:${port}`,
170 hostname: 'localhost',
181 return runServer(server, configOverride, args, options)
184 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
185 // These actions are async so we need to be sure that they have both been done
186 const serverRunString = {
187 'HTTP server listening': false
189 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
190 serverRunString[key] = false
193 client_id: 'Client id: (.+)',
194 client_secret: 'Client secret: (.+)',
195 user_username: 'Username: (.+)',
196 user_password: 'User password: (.+)'
199 if (server.internalServerNumber !== server.serverNumber) {
200 const basePath = join(root(), 'config')
202 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
203 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
205 server.customConfigFile = tmpConfigFile
208 const configOverride: any = {}
210 if (server.parallel) {
211 Object.assign(configOverride, {
219 suffix: '_test' + server.internalServerNumber
222 tmp: `test${server.internalServerNumber}/tmp/`,
223 avatars: `test${server.internalServerNumber}/avatars/`,
224 videos: `test${server.internalServerNumber}/videos/`,
225 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
226 redundancy: `test${server.internalServerNumber}/redundancy/`,
227 logs: `test${server.internalServerNumber}/logs/`,
228 previews: `test${server.internalServerNumber}/previews/`,
229 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
230 torrents: `test${server.internalServerNumber}/torrents/`,
231 captions: `test${server.internalServerNumber}/captions/`,
232 cache: `test${server.internalServerNumber}/cache/`,
233 plugins: `test${server.internalServerNumber}/plugins/`
236 email: `admin${server.internalServerNumber}@example.com`
240 port: server.rtmpPort
246 if (configOverrideArg !== undefined) {
247 Object.assign(configOverride, configOverrideArg)
250 // Share the environment
251 const env = Object.create(process.env)
252 env['NODE_ENV'] = 'test'
253 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
254 env['NODE_CONFIG'] = JSON.stringify(configOverride)
256 const forkOptions = {
260 execArgv: options.execArgv || []
263 return new Promise<ServerInfo>(res => {
264 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
265 server.app.stdout.on('data', function onStdout (data) {
266 let dontContinue = false
268 // Capture things if we want to
269 for (const key of Object.keys(regexps)) {
270 const regexp = regexps[key]
271 const matches = data.toString().match(regexp)
272 if (matches !== null) {
273 if (key === 'client_id') server.client.id = matches[1]
274 else if (key === 'client_secret') server.client.secret = matches[1]
275 else if (key === 'user_username') server.user.username = matches[1]
276 else if (key === 'user_password') server.user.password = matches[1]
280 // Check if all required sentences are here
281 for (const key of Object.keys(serverRunString)) {
282 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
283 if (serverRunString[key] === false) dontContinue = true
286 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
287 if (dontContinue === true) return
289 if (options.hideLogs === false) {
290 console.log(data.toString())
292 server.app.stdout.removeListener('data', onStdout)
295 process.on('exit', () => {
297 process.kill(server.app.pid)
298 } catch { /* empty */ }
301 server.bulkCommand = new BulkCommand(server)
302 server.cliCommand = new CLICommand(server)
303 server.customPageCommand = new CustomPagesCommand(server)
304 server.feedCommand = new FeedCommand(server)
305 server.logsCommand = new LogsCommand(server)
306 server.abusesCommand = new AbusesCommand(server)
307 server.overviewsCommand = new OverviewsCommand(server)
308 server.searchCommand = new SearchCommand(server)
309 server.contactFormCommand = new ContactFormCommand(server)
310 server.debugCommand = new DebugCommand(server)
311 server.followsCommand = new FollowsCommand(server)
312 server.jobsCommand = new JobsCommand(server)
313 server.pluginsCommand = new PluginsCommand(server)
314 server.redundancyCommand = new RedundancyCommand(server)
315 server.statsCommand = new StatsCommand(server)
316 server.configCommand = new ConfigCommand(server)
323 async function reRunServer (server: ServerInfo, configOverride?: any) {
324 const newServer = await runServer(server, configOverride)
325 server.app = newServer.app
330 async function checkTmpIsEmpty (server: ServerInfo) {
331 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
333 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
334 await checkDirectoryIsEmpty(server, 'tmp/hls')
338 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
339 const testDirectory = 'test' + server.internalServerNumber
341 const directoryPath = join(root(), testDirectory, directory)
343 const directoryExists = await pathExists(directoryPath)
344 expect(directoryExists).to.be.true
346 const files = await readdir(directoryPath)
347 const filtered = files.filter(f => exceptions.includes(f) === false)
349 expect(filtered).to.have.lengthOf(0)
352 function killallServers (servers: ServerInfo[]) {
353 for (const server of servers) {
354 if (!server.app) continue
356 process.kill(-server.app.pid)
361 async function cleanupTests (servers: ServerInfo[]) {
362 killallServers(servers)
365 await ensureDir('artifacts')
368 const p: Promise<any>[] = []
369 for (const server of servers) {
371 const origin = await buildServerDirectory(server, 'logs/peertube.log')
372 const destname = `peertube-${server.internalServerNumber}.log`
373 console.log('Saving logs %s.', destname)
375 await copy(origin, join('artifacts', destname))
378 if (server.parallel) {
379 p.push(flushTests(server.internalServerNumber))
382 if (server.customConfigFile) {
383 p.push(remove(server.customConfigFile))
387 return Promise.all(p)
390 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
391 const logfile = buildServerDirectory(server, 'logs/peertube.log')
394 const buf = await readFile(logfile)
396 const matches = buf.toString().match(new RegExp(str, 'g'))
397 if (matches && matches.length === count) return
398 if (matches && strictCount === false && matches.length >= count) return
404 async function getServerFileSize (server: ServerInfo, subPath: string) {
405 const path = buildServerDirectory(server, subPath)
407 return getFileSize(path)
410 function makePingRequest (server: ServerInfo) {
411 return makeGetRequest({
413 path: '/api/v1/ping',
414 statusCodeExpected: 200
418 // ---------------------------------------------------------------------------
421 checkDirectoryIsEmpty,
427 flushAndRunMultipleServers,