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'
22 interface ServerInfo {
33 internalServerNumber: number
47 customConfigFile?: string
51 videoChannel?: VideoChannel
72 videos?: { id: number, uuid: string }[]
74 bulkCommand?: BulkCommand
75 cliCommand?: CLICommand
76 customPageCommand?: CustomPagesCommand
77 feedCommand?: FeedCommand
78 logsCommand?: LogsCommand
79 abusesCommand?: AbusesCommand
80 overviewsCommand?: OverviewsCommand
81 searchCommand?: SearchCommand
82 contactFormCommand?: ContactFormCommand
83 debugCommand?: DebugCommand
86 function parallelTests () {
87 return process.env.MOCHA_PARALLEL === 'true'
90 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
94 return new Promise<ServerInfo[]>(res => {
95 function anotherServerDone (serverNumber, app) {
96 apps[serverNumber - 1] = app
98 if (i === totalServers) {
103 for (let j = 1; j <= totalServers; j++) {
104 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
109 function flushTests (serverNumber?: number) {
110 return new Promise<void>((res, rej) => {
111 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
113 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
114 if (err || stderr) return rej(err || new Error(stderr))
121 function randomServer () {
125 return randomInt(low, high)
128 function randomRTMP () {
132 return randomInt(low, high)
135 type RunServerOptions = {
140 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
141 const parallel = parallelTests()
143 const internalServerNumber = parallel ? randomServer() : serverNumber
144 const rtmpPort = parallel ? randomRTMP() : 1936
145 const port = 9000 + internalServerNumber
147 await flushTests(internalServerNumber)
149 const server: ServerInfo = {
152 internalServerNumber,
156 url: `http://localhost:${port}`,
157 host: `localhost:${port}`,
158 hostname: 'localhost',
169 return runServer(server, configOverride, args, options)
172 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
173 // These actions are async so we need to be sure that they have both been done
174 const serverRunString = {
175 'HTTP server listening': false
177 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
178 serverRunString[key] = false
181 client_id: 'Client id: (.+)',
182 client_secret: 'Client secret: (.+)',
183 user_username: 'Username: (.+)',
184 user_password: 'User password: (.+)'
187 if (server.internalServerNumber !== server.serverNumber) {
188 const basePath = join(root(), 'config')
190 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
191 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
193 server.customConfigFile = tmpConfigFile
196 const configOverride: any = {}
198 if (server.parallel) {
199 Object.assign(configOverride, {
207 suffix: '_test' + server.internalServerNumber
210 tmp: `test${server.internalServerNumber}/tmp/`,
211 avatars: `test${server.internalServerNumber}/avatars/`,
212 videos: `test${server.internalServerNumber}/videos/`,
213 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
214 redundancy: `test${server.internalServerNumber}/redundancy/`,
215 logs: `test${server.internalServerNumber}/logs/`,
216 previews: `test${server.internalServerNumber}/previews/`,
217 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
218 torrents: `test${server.internalServerNumber}/torrents/`,
219 captions: `test${server.internalServerNumber}/captions/`,
220 cache: `test${server.internalServerNumber}/cache/`,
221 plugins: `test${server.internalServerNumber}/plugins/`
224 email: `admin${server.internalServerNumber}@example.com`
228 port: server.rtmpPort
234 if (configOverrideArg !== undefined) {
235 Object.assign(configOverride, configOverrideArg)
238 // Share the environment
239 const env = Object.create(process.env)
240 env['NODE_ENV'] = 'test'
241 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
242 env['NODE_CONFIG'] = JSON.stringify(configOverride)
244 const forkOptions = {
248 execArgv: options.execArgv || []
251 return new Promise<ServerInfo>(res => {
252 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
253 server.app.stdout.on('data', function onStdout (data) {
254 let dontContinue = false
256 // Capture things if we want to
257 for (const key of Object.keys(regexps)) {
258 const regexp = regexps[key]
259 const matches = data.toString().match(regexp)
260 if (matches !== null) {
261 if (key === 'client_id') server.client.id = matches[1]
262 else if (key === 'client_secret') server.client.secret = matches[1]
263 else if (key === 'user_username') server.user.username = matches[1]
264 else if (key === 'user_password') server.user.password = matches[1]
268 // Check if all required sentences are here
269 for (const key of Object.keys(serverRunString)) {
270 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
271 if (serverRunString[key] === false) dontContinue = true
274 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
275 if (dontContinue === true) return
277 if (options.hideLogs === false) {
278 console.log(data.toString())
280 server.app.stdout.removeListener('data', onStdout)
283 process.on('exit', () => {
285 process.kill(server.app.pid)
286 } catch { /* empty */ }
289 server.bulkCommand = new BulkCommand(server)
290 server.cliCommand = new CLICommand(server)
291 server.customPageCommand = new CustomPagesCommand(server)
292 server.feedCommand = new FeedCommand(server)
293 server.logsCommand = new LogsCommand(server)
294 server.abusesCommand = new AbusesCommand(server)
295 server.overviewsCommand = new OverviewsCommand(server)
296 server.searchCommand = new SearchCommand(server)
297 server.contactFormCommand = new ContactFormCommand(server)
298 server.debugCommand = new DebugCommand(server)
305 async function reRunServer (server: ServerInfo, configOverride?: any) {
306 const newServer = await runServer(server, configOverride)
307 server.app = newServer.app
312 async function checkTmpIsEmpty (server: ServerInfo) {
313 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
315 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
316 await checkDirectoryIsEmpty(server, 'tmp/hls')
320 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
321 const testDirectory = 'test' + server.internalServerNumber
323 const directoryPath = join(root(), testDirectory, directory)
325 const directoryExists = await pathExists(directoryPath)
326 expect(directoryExists).to.be.true
328 const files = await readdir(directoryPath)
329 const filtered = files.filter(f => exceptions.includes(f) === false)
331 expect(filtered).to.have.lengthOf(0)
334 function killallServers (servers: ServerInfo[]) {
335 for (const server of servers) {
336 if (!server.app) continue
338 process.kill(-server.app.pid)
343 async function cleanupTests (servers: ServerInfo[]) {
344 killallServers(servers)
347 await ensureDir('artifacts')
350 const p: Promise<any>[] = []
351 for (const server of servers) {
353 const origin = await buildServerDirectory(server, 'logs/peertube.log')
354 const destname = `peertube-${server.internalServerNumber}.log`
355 console.log('Saving logs %s.', destname)
357 await copy(origin, join('artifacts', destname))
360 if (server.parallel) {
361 p.push(flushTests(server.internalServerNumber))
364 if (server.customConfigFile) {
365 p.push(remove(server.customConfigFile))
369 return Promise.all(p)
372 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
373 const logfile = buildServerDirectory(server, 'logs/peertube.log')
376 const buf = await readFile(logfile)
378 const matches = buf.toString().match(new RegExp(str, 'g'))
379 if (matches && matches.length === count) return
380 if (matches && strictCount === false && matches.length >= count) return
386 async function getServerFileSize (server: ServerInfo, subPath: string) {
387 const path = buildServerDirectory(server, subPath)
389 return getFileSize(path)
392 function makePingRequest (server: ServerInfo) {
393 return makeGetRequest({
395 path: '/api/v1/ping',
396 statusCodeExpected: 200
400 // ---------------------------------------------------------------------------
403 checkDirectoryIsEmpty,
409 flushAndRunMultipleServers,