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'
26 interface ServerInfo {
37 internalServerNumber: number
51 customConfigFile?: string
55 videoChannel?: VideoChannel
76 videos?: { id: number, uuid: string }[]
78 bulkCommand?: BulkCommand
79 cliCommand?: CLICommand
80 customPageCommand?: CustomPagesCommand
81 feedCommand?: FeedCommand
82 logsCommand?: LogsCommand
83 abusesCommand?: AbusesCommand
84 overviewsCommand?: OverviewsCommand
85 searchCommand?: SearchCommand
86 contactFormCommand?: ContactFormCommand
87 debugCommand?: DebugCommand
88 followsCommand?: FollowsCommand
89 jobsCommand?: JobsCommand
90 pluginsCommand?: PluginsCommand
91 redundancyCommand?: RedundancyCommand
94 function parallelTests () {
95 return process.env.MOCHA_PARALLEL === 'true'
98 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
102 return new Promise<ServerInfo[]>(res => {
103 function anotherServerDone (serverNumber, app) {
104 apps[serverNumber - 1] = app
106 if (i === totalServers) {
111 for (let j = 1; j <= totalServers; j++) {
112 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
117 function flushTests (serverNumber?: number) {
118 return new Promise<void>((res, rej) => {
119 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
121 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
122 if (err || stderr) return rej(err || new Error(stderr))
129 function randomServer () {
133 return randomInt(low, high)
136 function randomRTMP () {
140 return randomInt(low, high)
143 type RunServerOptions = {
148 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
149 const parallel = parallelTests()
151 const internalServerNumber = parallel ? randomServer() : serverNumber
152 const rtmpPort = parallel ? randomRTMP() : 1936
153 const port = 9000 + internalServerNumber
155 await flushTests(internalServerNumber)
157 const server: ServerInfo = {
160 internalServerNumber,
164 url: `http://localhost:${port}`,
165 host: `localhost:${port}`,
166 hostname: 'localhost',
177 return runServer(server, configOverride, args, options)
180 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
181 // These actions are async so we need to be sure that they have both been done
182 const serverRunString = {
183 'HTTP server listening': false
185 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
186 serverRunString[key] = false
189 client_id: 'Client id: (.+)',
190 client_secret: 'Client secret: (.+)',
191 user_username: 'Username: (.+)',
192 user_password: 'User password: (.+)'
195 if (server.internalServerNumber !== server.serverNumber) {
196 const basePath = join(root(), 'config')
198 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
199 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
201 server.customConfigFile = tmpConfigFile
204 const configOverride: any = {}
206 if (server.parallel) {
207 Object.assign(configOverride, {
215 suffix: '_test' + server.internalServerNumber
218 tmp: `test${server.internalServerNumber}/tmp/`,
219 avatars: `test${server.internalServerNumber}/avatars/`,
220 videos: `test${server.internalServerNumber}/videos/`,
221 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
222 redundancy: `test${server.internalServerNumber}/redundancy/`,
223 logs: `test${server.internalServerNumber}/logs/`,
224 previews: `test${server.internalServerNumber}/previews/`,
225 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
226 torrents: `test${server.internalServerNumber}/torrents/`,
227 captions: `test${server.internalServerNumber}/captions/`,
228 cache: `test${server.internalServerNumber}/cache/`,
229 plugins: `test${server.internalServerNumber}/plugins/`
232 email: `admin${server.internalServerNumber}@example.com`
236 port: server.rtmpPort
242 if (configOverrideArg !== undefined) {
243 Object.assign(configOverride, configOverrideArg)
246 // Share the environment
247 const env = Object.create(process.env)
248 env['NODE_ENV'] = 'test'
249 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
250 env['NODE_CONFIG'] = JSON.stringify(configOverride)
252 const forkOptions = {
256 execArgv: options.execArgv || []
259 return new Promise<ServerInfo>(res => {
260 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
261 server.app.stdout.on('data', function onStdout (data) {
262 let dontContinue = false
264 // Capture things if we want to
265 for (const key of Object.keys(regexps)) {
266 const regexp = regexps[key]
267 const matches = data.toString().match(regexp)
268 if (matches !== null) {
269 if (key === 'client_id') server.client.id = matches[1]
270 else if (key === 'client_secret') server.client.secret = matches[1]
271 else if (key === 'user_username') server.user.username = matches[1]
272 else if (key === 'user_password') server.user.password = matches[1]
276 // Check if all required sentences are here
277 for (const key of Object.keys(serverRunString)) {
278 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
279 if (serverRunString[key] === false) dontContinue = true
282 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
283 if (dontContinue === true) return
285 if (options.hideLogs === false) {
286 console.log(data.toString())
288 server.app.stdout.removeListener('data', onStdout)
291 process.on('exit', () => {
293 process.kill(server.app.pid)
294 } catch { /* empty */ }
297 server.bulkCommand = new BulkCommand(server)
298 server.cliCommand = new CLICommand(server)
299 server.customPageCommand = new CustomPagesCommand(server)
300 server.feedCommand = new FeedCommand(server)
301 server.logsCommand = new LogsCommand(server)
302 server.abusesCommand = new AbusesCommand(server)
303 server.overviewsCommand = new OverviewsCommand(server)
304 server.searchCommand = new SearchCommand(server)
305 server.contactFormCommand = new ContactFormCommand(server)
306 server.debugCommand = new DebugCommand(server)
307 server.followsCommand = new FollowsCommand(server)
308 server.jobsCommand = new JobsCommand(server)
309 server.pluginsCommand = new PluginsCommand(server)
310 server.redundancyCommand = new RedundancyCommand(server)
317 async function reRunServer (server: ServerInfo, configOverride?: any) {
318 const newServer = await runServer(server, configOverride)
319 server.app = newServer.app
324 async function checkTmpIsEmpty (server: ServerInfo) {
325 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
327 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
328 await checkDirectoryIsEmpty(server, 'tmp/hls')
332 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
333 const testDirectory = 'test' + server.internalServerNumber
335 const directoryPath = join(root(), testDirectory, directory)
337 const directoryExists = await pathExists(directoryPath)
338 expect(directoryExists).to.be.true
340 const files = await readdir(directoryPath)
341 const filtered = files.filter(f => exceptions.includes(f) === false)
343 expect(filtered).to.have.lengthOf(0)
346 function killallServers (servers: ServerInfo[]) {
347 for (const server of servers) {
348 if (!server.app) continue
350 process.kill(-server.app.pid)
355 async function cleanupTests (servers: ServerInfo[]) {
356 killallServers(servers)
359 await ensureDir('artifacts')
362 const p: Promise<any>[] = []
363 for (const server of servers) {
365 const origin = await buildServerDirectory(server, 'logs/peertube.log')
366 const destname = `peertube-${server.internalServerNumber}.log`
367 console.log('Saving logs %s.', destname)
369 await copy(origin, join('artifacts', destname))
372 if (server.parallel) {
373 p.push(flushTests(server.internalServerNumber))
376 if (server.customConfigFile) {
377 p.push(remove(server.customConfigFile))
381 return Promise.all(p)
384 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
385 const logfile = buildServerDirectory(server, 'logs/peertube.log')
388 const buf = await readFile(logfile)
390 const matches = buf.toString().match(new RegExp(str, 'g'))
391 if (matches && matches.length === count) return
392 if (matches && strictCount === false && matches.length >= count) return
398 async function getServerFileSize (server: ServerInfo, subPath: string) {
399 const path = buildServerDirectory(server, subPath)
401 return getFileSize(path)
404 function makePingRequest (server: ServerInfo) {
405 return makeGetRequest({
407 path: '/api/v1/ping',
408 statusCodeExpected: 200
412 // ---------------------------------------------------------------------------
415 checkDirectoryIsEmpty,
421 flushAndRunMultipleServers,