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'
20 interface ServerInfo {
31 internalServerNumber: number
45 customConfigFile?: string
49 videoChannel?: VideoChannel
70 videos?: { id: number, uuid: string }[]
72 bulkCommand?: BulkCommand
73 cliCommand?: CLICommand
74 customPageCommand?: CustomPagesCommand
75 feedCommand?: FeedCommand
76 logsCommand?: LogsCommand
77 abusesCommand?: AbusesCommand
78 overviewsCommand?: OverviewsCommand
79 searchCommand?: SearchCommand
82 function parallelTests () {
83 return process.env.MOCHA_PARALLEL === 'true'
86 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
90 return new Promise<ServerInfo[]>(res => {
91 function anotherServerDone (serverNumber, app) {
92 apps[serverNumber - 1] = app
94 if (i === totalServers) {
99 for (let j = 1; j <= totalServers; j++) {
100 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
105 function flushTests (serverNumber?: number) {
106 return new Promise<void>((res, rej) => {
107 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
109 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
110 if (err || stderr) return rej(err || new Error(stderr))
117 function randomServer () {
121 return randomInt(low, high)
124 function randomRTMP () {
128 return randomInt(low, high)
131 type RunServerOptions = {
136 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
137 const parallel = parallelTests()
139 const internalServerNumber = parallel ? randomServer() : serverNumber
140 const rtmpPort = parallel ? randomRTMP() : 1936
141 const port = 9000 + internalServerNumber
143 await flushTests(internalServerNumber)
145 const server: ServerInfo = {
148 internalServerNumber,
152 url: `http://localhost:${port}`,
153 host: `localhost:${port}`,
154 hostname: 'localhost',
165 return runServer(server, configOverride, args, options)
168 async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
169 // These actions are async so we need to be sure that they have both been done
170 const serverRunString = {
171 'HTTP server listening': false
173 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
174 serverRunString[key] = false
177 client_id: 'Client id: (.+)',
178 client_secret: 'Client secret: (.+)',
179 user_username: 'Username: (.+)',
180 user_password: 'User password: (.+)'
183 if (server.internalServerNumber !== server.serverNumber) {
184 const basePath = join(root(), 'config')
186 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
187 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
189 server.customConfigFile = tmpConfigFile
192 const configOverride: any = {}
194 if (server.parallel) {
195 Object.assign(configOverride, {
203 suffix: '_test' + server.internalServerNumber
206 tmp: `test${server.internalServerNumber}/tmp/`,
207 avatars: `test${server.internalServerNumber}/avatars/`,
208 videos: `test${server.internalServerNumber}/videos/`,
209 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
210 redundancy: `test${server.internalServerNumber}/redundancy/`,
211 logs: `test${server.internalServerNumber}/logs/`,
212 previews: `test${server.internalServerNumber}/previews/`,
213 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
214 torrents: `test${server.internalServerNumber}/torrents/`,
215 captions: `test${server.internalServerNumber}/captions/`,
216 cache: `test${server.internalServerNumber}/cache/`,
217 plugins: `test${server.internalServerNumber}/plugins/`
220 email: `admin${server.internalServerNumber}@example.com`
224 port: server.rtmpPort
230 if (configOverrideArg !== undefined) {
231 Object.assign(configOverride, configOverrideArg)
234 // Share the environment
235 const env = Object.create(process.env)
236 env['NODE_ENV'] = 'test'
237 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
238 env['NODE_CONFIG'] = JSON.stringify(configOverride)
240 const forkOptions = {
244 execArgv: options.execArgv || []
247 return new Promise<ServerInfo>(res => {
248 server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
249 server.app.stdout.on('data', function onStdout (data) {
250 let dontContinue = false
252 // Capture things if we want to
253 for (const key of Object.keys(regexps)) {
254 const regexp = regexps[key]
255 const matches = data.toString().match(regexp)
256 if (matches !== null) {
257 if (key === 'client_id') server.client.id = matches[1]
258 else if (key === 'client_secret') server.client.secret = matches[1]
259 else if (key === 'user_username') server.user.username = matches[1]
260 else if (key === 'user_password') server.user.password = matches[1]
264 // Check if all required sentences are here
265 for (const key of Object.keys(serverRunString)) {
266 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
267 if (serverRunString[key] === false) dontContinue = true
270 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
271 if (dontContinue === true) return
273 if (options.hideLogs === false) {
274 console.log(data.toString())
276 server.app.stdout.removeListener('data', onStdout)
279 process.on('exit', () => {
281 process.kill(server.app.pid)
282 } catch { /* empty */ }
285 server.bulkCommand = new BulkCommand(server)
286 server.cliCommand = new CLICommand(server)
287 server.customPageCommand = new CustomPagesCommand(server)
288 server.feedCommand = new FeedCommand(server)
289 server.logsCommand = new LogsCommand(server)
290 server.abusesCommand = new AbusesCommand(server)
291 server.overviewsCommand = new OverviewsCommand(server)
292 server.searchCommand = new SearchCommand(server)
299 async function reRunServer (server: ServerInfo, configOverride?: any) {
300 const newServer = await runServer(server, configOverride)
301 server.app = newServer.app
306 async function checkTmpIsEmpty (server: ServerInfo) {
307 await checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css', 'hls', 'resumable-uploads' ])
309 if (await pathExists(join('test' + server.internalServerNumber, 'tmp', 'hls'))) {
310 await checkDirectoryIsEmpty(server, 'tmp/hls')
314 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
315 const testDirectory = 'test' + server.internalServerNumber
317 const directoryPath = join(root(), testDirectory, directory)
319 const directoryExists = await pathExists(directoryPath)
320 expect(directoryExists).to.be.true
322 const files = await readdir(directoryPath)
323 const filtered = files.filter(f => exceptions.includes(f) === false)
325 expect(filtered).to.have.lengthOf(0)
328 function killallServers (servers: ServerInfo[]) {
329 for (const server of servers) {
330 if (!server.app) continue
332 process.kill(-server.app.pid)
337 async function cleanupTests (servers: ServerInfo[]) {
338 killallServers(servers)
341 await ensureDir('artifacts')
344 const p: Promise<any>[] = []
345 for (const server of servers) {
347 const origin = await buildServerDirectory(server, 'logs/peertube.log')
348 const destname = `peertube-${server.internalServerNumber}.log`
349 console.log('Saving logs %s.', destname)
351 await copy(origin, join('artifacts', destname))
354 if (server.parallel) {
355 p.push(flushTests(server.internalServerNumber))
358 if (server.customConfigFile) {
359 p.push(remove(server.customConfigFile))
363 return Promise.all(p)
366 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
367 const logfile = buildServerDirectory(server, 'logs/peertube.log')
370 const buf = await readFile(logfile)
372 const matches = buf.toString().match(new RegExp(str, 'g'))
373 if (matches && matches.length === count) return
374 if (matches && strictCount === false && matches.length >= count) return
380 async function getServerFileSize (server: ServerInfo, subPath: string) {
381 const path = buildServerDirectory(server, subPath)
383 return getFileSize(path)
386 function makePingRequest (server: ServerInfo) {
387 return makeGetRequest({
389 path: '/api/v1/ping',
390 statusCodeExpected: 200
394 // ---------------------------------------------------------------------------
397 checkDirectoryIsEmpty,
403 flushAndRunMultipleServers,