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'
25 interface ServerInfo {
36 internalServerNumber: number
50 customConfigFile?: string
54 videoChannel?: VideoChannel
75 videos?: { id: number, uuid: string }[]
77 bulkCommand?: BulkCommand
78 cliCommand?: CLICommand
79 customPageCommand?: CustomPagesCommand
80 feedCommand?: FeedCommand
81 logsCommand?: LogsCommand
82 abusesCommand?: AbusesCommand
83 overviewsCommand?: OverviewsCommand
84 searchCommand?: SearchCommand
85 contactFormCommand?: ContactFormCommand
86 debugCommand?: DebugCommand
87 followsCommand?: FollowsCommand
88 jobsCommand?: JobsCommand
89 pluginsCommand?: PluginsCommand
92 function parallelTests () {
93 return process.env.MOCHA_PARALLEL === 'true'
96 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
100 return new Promise<ServerInfo[]>(res => {
101 function anotherServerDone (serverNumber, app) {
102 apps[serverNumber - 1] = app
104 if (i === totalServers) {
109 for (let j = 1; j <= totalServers; j++) {
110 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
115 function flushTests (serverNumber?: number) {
116 return new Promise<void>((res, rej) => {
117 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
119 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
120 if (err || stderr) return rej(err || new Error(stderr))
127 function randomServer () {
131 return randomInt(low, high)
134 function randomRTMP () {
138 return randomInt(low, high)
141 type RunServerOptions = {
146 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
147 const parallel = parallelTests()
149 const internalServerNumber = parallel ? randomServer() : serverNumber
150 const rtmpPort = parallel ? randomRTMP() : 1936
151 const port = 9000 + internalServerNumber
153 await flushTests(internalServerNumber)
155 const server: ServerInfo = {
158 internalServerNumber,
162 url: `http://localhost:${port}`,
163 host: `localhost:${port}`,
164 hostname: 'localhost',
175 return runServer(server, configOverride, args, options)
178 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
179 // These actions are async so we need to be sure that they have both been done
180 const serverRunString = {
181 'HTTP server listening': false
183 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
184 serverRunString[key] = false
187 client_id: 'Client id: (.+)',
188 client_secret: 'Client secret: (.+)',
189 user_username: 'Username: (.+)',
190 user_password: 'User password: (.+)'
193 if (server.internalServerNumber !== server.serverNumber) {
194 const basePath = join(root(), 'config')
196 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
197 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
199 server.customConfigFile = tmpConfigFile
202 const configOverride: any = {}
204 if (server.parallel) {
205 Object.assign(configOverride, {
213 suffix: '_test' + server.internalServerNumber
216 tmp: `test${server.internalServerNumber}/tmp/`,
217 avatars: `test${server.internalServerNumber}/avatars/`,
218 videos: `test${server.internalServerNumber}/videos/`,
219 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
220 redundancy: `test${server.internalServerNumber}/redundancy/`,
221 logs: `test${server.internalServerNumber}/logs/`,
222 previews: `test${server.internalServerNumber}/previews/`,
223 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
224 torrents: `test${server.internalServerNumber}/torrents/`,
225 captions: `test${server.internalServerNumber}/captions/`,
226 cache: `test${server.internalServerNumber}/cache/`,
227 plugins: `test${server.internalServerNumber}/plugins/`
230 email: `admin${server.internalServerNumber}@example.com`
234 port: server.rtmpPort
240 if (configOverrideArg !== undefined) {
241 Object.assign(configOverride, configOverrideArg)
244 // Share the environment
245 const env = Object.create(process.env)
246 env['NODE_ENV'] = 'test'
247 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
248 env['NODE_CONFIG'] = JSON.stringify(configOverride)
250 const forkOptions = {
254 execArgv: options.execArgv || []
257 return new Promise<ServerInfo>(res => {
258 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
259 server.app.stdout.on('data', function onStdout (data) {
260 let dontContinue = false
262 // Capture things if we want to
263 for (const key of Object.keys(regexps)) {
264 const regexp = regexps[key]
265 const matches = data.toString().match(regexp)
266 if (matches !== null) {
267 if (key === 'client_id') server.client.id = matches[1]
268 else if (key === 'client_secret') server.client.secret = matches[1]
269 else if (key === 'user_username') server.user.username = matches[1]
270 else if (key === 'user_password') server.user.password = matches[1]
274 // Check if all required sentences are here
275 for (const key of Object.keys(serverRunString)) {
276 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
277 if (serverRunString[key] === false) dontContinue = true
280 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
281 if (dontContinue === true) return
283 if (options.hideLogs === false) {
284 console.log(data.toString())
286 server.app.stdout.removeListener('data', onStdout)
289 process.on('exit', () => {
291 process.kill(server.app.pid)
292 } catch { /* empty */ }
295 server.bulkCommand = new BulkCommand(server)
296 server.cliCommand = new CLICommand(server)
297 server.customPageCommand = new CustomPagesCommand(server)
298 server.feedCommand = new FeedCommand(server)
299 server.logsCommand = new LogsCommand(server)
300 server.abusesCommand = new AbusesCommand(server)
301 server.overviewsCommand = new OverviewsCommand(server)
302 server.searchCommand = new SearchCommand(server)
303 server.contactFormCommand = new ContactFormCommand(server)
304 server.debugCommand = new DebugCommand(server)
305 server.followsCommand = new FollowsCommand(server)
306 server.jobsCommand = new JobsCommand(server)
307 server.pluginsCommand = new PluginsCommand(server)
314 async function reRunServer (server: ServerInfo, configOverride?: any) {
315 const newServer = await runServer(server, configOverride)
316 server.app = newServer.app
321 async function checkTmpIsEmpty (server: ServerInfo) {
322 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
324 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
325 await checkDirectoryIsEmpty(server, 'tmp/hls')
329 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
330 const testDirectory = 'test' + server.internalServerNumber
332 const directoryPath = join(root(), testDirectory, directory)
334 const directoryExists = await pathExists(directoryPath)
335 expect(directoryExists).to.be.true
337 const files = await readdir(directoryPath)
338 const filtered = files.filter(f => exceptions.includes(f) === false)
340 expect(filtered).to.have.lengthOf(0)
343 function killallServers (servers: ServerInfo[]) {
344 for (const server of servers) {
345 if (!server.app) continue
347 process.kill(-server.app.pid)
352 async function cleanupTests (servers: ServerInfo[]) {
353 killallServers(servers)
356 await ensureDir('artifacts')
359 const p: Promise<any>[] = []
360 for (const server of servers) {
362 const origin = await buildServerDirectory(server, 'logs/peertube.log')
363 const destname = `peertube-${server.internalServerNumber}.log`
364 console.log('Saving logs %s.', destname)
366 await copy(origin, join('artifacts', destname))
369 if (server.parallel) {
370 p.push(flushTests(server.internalServerNumber))
373 if (server.customConfigFile) {
374 p.push(remove(server.customConfigFile))
378 return Promise.all(p)
381 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
382 const logfile = buildServerDirectory(server, 'logs/peertube.log')
385 const buf = await readFile(logfile)
387 const matches = buf.toString().match(new RegExp(str, 'g'))
388 if (matches && matches.length === count) return
389 if (matches && strictCount === false && matches.length >= count) return
395 async function getServerFileSize (server: ServerInfo, subPath: string) {
396 const path = buildServerDirectory(server, subPath)
398 return getFileSize(path)
401 function makePingRequest (server: ServerInfo) {
402 return makeGetRequest({
404 path: '/api/v1/ping',
405 statusCodeExpected: 200
409 // ---------------------------------------------------------------------------
412 checkDirectoryIsEmpty,
418 flushAndRunMultipleServers,