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 { ConfigCommand } from './config-command'
21 import { ContactFormCommand } from './contact-form-command'
22 import { DebugCommand } from './debug-command'
23 import { FollowsCommand } from './follows-command'
24 import { JobsCommand } from './jobs-command'
25 import { PluginsCommand } from './plugins-command'
26 import { RedundancyCommand } from './redundancy-command'
27 import { StatsCommand } from './stats-command'
29 interface ServerInfo {
40 internalServerNumber: number
54 customConfigFile?: string
58 videoChannel?: VideoChannel
79 videos?: { id: number, uuid: string }[]
81 bulkCommand?: BulkCommand
82 cliCommand?: CLICommand
83 customPageCommand?: CustomPagesCommand
84 feedCommand?: FeedCommand
85 logsCommand?: LogsCommand
86 abusesCommand?: AbusesCommand
87 overviewsCommand?: OverviewsCommand
88 searchCommand?: SearchCommand
89 contactFormCommand?: ContactFormCommand
90 debugCommand?: DebugCommand
91 followsCommand?: FollowsCommand
92 jobsCommand?: JobsCommand
93 pluginsCommand?: PluginsCommand
94 redundancyCommand?: RedundancyCommand
95 statsCommand?: StatsCommand
96 configCommand?: ConfigCommand
97 socketIOCommand?: SocketIOCommand
100 function parallelTests () {
101 return process.env.MOCHA_PARALLEL === 'true'
104 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
108 return new Promise<ServerInfo[]>(res => {
109 function anotherServerDone (serverNumber, app) {
110 apps[serverNumber - 1] = app
112 if (i === totalServers) {
117 for (let j = 1; j <= totalServers; j++) {
118 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
123 function flushTests (serverNumber?: number) {
124 return new Promise<void>((res, rej) => {
125 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
127 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
128 if (err || stderr) return rej(err || new Error(stderr))
135 function randomServer () {
139 return randomInt(low, high)
142 function randomRTMP () {
146 return randomInt(low, high)
149 type RunServerOptions = {
154 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
155 const parallel = parallelTests()
157 const internalServerNumber = parallel ? randomServer() : serverNumber
158 const rtmpPort = parallel ? randomRTMP() : 1936
159 const port = 9000 + internalServerNumber
161 await flushTests(internalServerNumber)
163 const server: ServerInfo = {
166 internalServerNumber,
170 url: `http://localhost:${port}`,
171 host: `localhost:${port}`,
172 hostname: 'localhost',
183 return runServer(server, configOverride, args, options)
186 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
187 // These actions are async so we need to be sure that they have both been done
188 const serverRunString = {
189 'HTTP server listening': false
191 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
192 serverRunString[key] = false
195 client_id: 'Client id: (.+)',
196 client_secret: 'Client secret: (.+)',
197 user_username: 'Username: (.+)',
198 user_password: 'User password: (.+)'
201 if (server.internalServerNumber !== server.serverNumber) {
202 const basePath = join(root(), 'config')
204 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
205 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
207 server.customConfigFile = tmpConfigFile
210 const configOverride: any = {}
212 if (server.parallel) {
213 Object.assign(configOverride, {
221 suffix: '_test' + server.internalServerNumber
224 tmp: `test${server.internalServerNumber}/tmp/`,
225 avatars: `test${server.internalServerNumber}/avatars/`,
226 videos: `test${server.internalServerNumber}/videos/`,
227 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
228 redundancy: `test${server.internalServerNumber}/redundancy/`,
229 logs: `test${server.internalServerNumber}/logs/`,
230 previews: `test${server.internalServerNumber}/previews/`,
231 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
232 torrents: `test${server.internalServerNumber}/torrents/`,
233 captions: `test${server.internalServerNumber}/captions/`,
234 cache: `test${server.internalServerNumber}/cache/`,
235 plugins: `test${server.internalServerNumber}/plugins/`
238 email: `admin${server.internalServerNumber}@example.com`
242 port: server.rtmpPort
248 if (configOverrideArg !== undefined) {
249 Object.assign(configOverride, configOverrideArg)
252 // Share the environment
253 const env = Object.create(process.env)
254 env['NODE_ENV'] = 'test'
255 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
256 env['NODE_CONFIG'] = JSON.stringify(configOverride)
258 const forkOptions = {
262 execArgv: options.execArgv || []
265 return new Promise<ServerInfo>(res => {
266 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
267 server.app.stdout.on('data', function onStdout (data) {
268 let dontContinue = false
270 // Capture things if we want to
271 for (const key of Object.keys(regexps)) {
272 const regexp = regexps[key]
273 const matches = data.toString().match(regexp)
274 if (matches !== null) {
275 if (key === 'client_id') server.client.id = matches[1]
276 else if (key === 'client_secret') server.client.secret = matches[1]
277 else if (key === 'user_username') server.user.username = matches[1]
278 else if (key === 'user_password') server.user.password = matches[1]
282 // Check if all required sentences are here
283 for (const key of Object.keys(serverRunString)) {
284 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
285 if (serverRunString[key] === false) dontContinue = true
288 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
289 if (dontContinue === true) return
291 if (options.hideLogs === false) {
292 console.log(data.toString())
294 server.app.stdout.removeListener('data', onStdout)
297 process.on('exit', () => {
299 process.kill(server.app.pid)
300 } catch { /* empty */ }
303 server.bulkCommand = new BulkCommand(server)
304 server.cliCommand = new CLICommand(server)
305 server.customPageCommand = new CustomPagesCommand(server)
306 server.feedCommand = new FeedCommand(server)
307 server.logsCommand = new LogsCommand(server)
308 server.abusesCommand = new AbusesCommand(server)
309 server.overviewsCommand = new OverviewsCommand(server)
310 server.searchCommand = new SearchCommand(server)
311 server.contactFormCommand = new ContactFormCommand(server)
312 server.debugCommand = new DebugCommand(server)
313 server.followsCommand = new FollowsCommand(server)
314 server.jobsCommand = new JobsCommand(server)
315 server.pluginsCommand = new PluginsCommand(server)
316 server.redundancyCommand = new RedundancyCommand(server)
317 server.statsCommand = new StatsCommand(server)
318 server.configCommand = new ConfigCommand(server)
319 server.socketIOCommand = new SocketIOCommand(server)
326 async function reRunServer (server: ServerInfo, configOverride?: any) {
327 const newServer = await runServer(server, configOverride)
328 server.app = newServer.app
333 async function checkTmpIsEmpty (server: ServerInfo) {
334 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
336 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
337 await checkDirectoryIsEmpty(server, 'tmp/hls')
341 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
342 const testDirectory = 'test' + server.internalServerNumber
344 const directoryPath = join(root(), testDirectory, directory)
346 const directoryExists = await pathExists(directoryPath)
347 expect(directoryExists).to.be.true
349 const files = await readdir(directoryPath)
350 const filtered = files.filter(f => exceptions.includes(f) === false)
352 expect(filtered).to.have.lengthOf(0)
355 function killallServers (servers: ServerInfo[]) {
356 for (const server of servers) {
357 if (!server.app) continue
359 process.kill(-server.app.pid)
364 async function cleanupTests (servers: ServerInfo[]) {
365 killallServers(servers)
368 await ensureDir('artifacts')
371 const p: Promise<any>[] = []
372 for (const server of servers) {
374 const origin = await buildServerDirectory(server, 'logs/peertube.log')
375 const destname = `peertube-${server.internalServerNumber}.log`
376 console.log('Saving logs %s.', destname)
378 await copy(origin, join('artifacts', destname))
381 if (server.parallel) {
382 p.push(flushTests(server.internalServerNumber))
385 if (server.customConfigFile) {
386 p.push(remove(server.customConfigFile))
390 return Promise.all(p)
393 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
394 const logfile = buildServerDirectory(server, 'logs/peertube.log')
397 const buf = await readFile(logfile)
399 const matches = buf.toString().match(new RegExp(str, 'g'))
400 if (matches && matches.length === count) return
401 if (matches && strictCount === false && matches.length >= count) return
407 async function getServerFileSize (server: ServerInfo, subPath: string) {
408 const path = buildServerDirectory(server, subPath)
410 return getFileSize(path)
413 function makePingRequest (server: ServerInfo) {
414 return makeGetRequest({
416 path: '/api/v1/ping',
417 statusCodeExpected: 200
421 // ---------------------------------------------------------------------------
424 checkDirectoryIsEmpty,
430 flushAndRunMultipleServers,