1 /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */
3 import { ChildProcess, exec, fork } from 'child_process'
4 import { join } from 'path'
5 import { root, wait } from '../miscs/miscs'
6 import { copy, pathExists, readdir, readFile, remove } from 'fs-extra'
7 import { expect } from 'chai'
8 import { VideoChannel } from '../../models/videos'
9 import { randomInt } from '../../core-utils/miscs/miscs'
11 interface ServerInfo {
20 internalServerNumber: number
34 customConfigFile?: string
37 videoChannel?: VideoChannel
53 videos?: { id: number, uuid: string }[]
56 function parallelTests () {
57 return process.env.MOCHA_PARALLEL === 'true'
60 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
64 return new Promise<ServerInfo[]>(res => {
65 function anotherServerDone (serverNumber, app) {
66 apps[serverNumber - 1] = app
68 if (i === totalServers) {
73 for (let j = 1; j <= totalServers; j++) {
74 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
79 function flushTests (serverNumber?: number) {
80 return new Promise<void>((res, rej) => {
81 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
83 return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
84 if (err || stderr) return rej(err || new Error(stderr))
91 function randomServer () {
95 return randomInt(low, high)
98 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = []) {
99 const parallel = parallelTests()
101 const internalServerNumber = parallel ? randomServer() : serverNumber
102 const port = 9000 + internalServerNumber
104 await flushTests(internalServerNumber)
106 const server: ServerInfo = {
109 internalServerNumber,
112 url: `http://localhost:${port}`,
113 host: `localhost:${port}`,
114 hostname: 'localhost',
125 return runServer(server, configOverride, args)
128 async function runServer (server: ServerInfo, configOverrideArg?: any, args = []) {
129 // These actions are async so we need to be sure that they have both been done
130 const serverRunString = {
131 'Server listening': false
133 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
134 serverRunString[key] = false
137 client_id: 'Client id: (.+)',
138 client_secret: 'Client secret: (.+)',
139 user_username: 'Username: (.+)',
140 user_password: 'User password: (.+)'
143 if (server.internalServerNumber !== server.serverNumber) {
144 const basePath = join(root(), 'config')
146 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
147 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
149 server.customConfigFile = tmpConfigFile
152 const configOverride: any = {}
154 if (server.parallel) {
155 Object.assign(configOverride, {
163 suffix: '_test' + server.internalServerNumber
166 tmp: `test${server.internalServerNumber}/tmp/`,
167 avatars: `test${server.internalServerNumber}/avatars/`,
168 videos: `test${server.internalServerNumber}/videos/`,
169 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
170 redundancy: `test${server.internalServerNumber}/redundancy/`,
171 logs: `test${server.internalServerNumber}/logs/`,
172 previews: `test${server.internalServerNumber}/previews/`,
173 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
174 torrents: `test${server.internalServerNumber}/torrents/`,
175 captions: `test${server.internalServerNumber}/captions/`,
176 cache: `test${server.internalServerNumber}/cache/`,
177 plugins: `test${server.internalServerNumber}/plugins/`
180 email: `admin${server.internalServerNumber}@example.com`
185 if (configOverrideArg !== undefined) {
186 Object.assign(configOverride, configOverrideArg)
189 // Share the environment
190 const env = Object.create(process.env)
191 env['NODE_ENV'] = 'test'
192 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
193 env['NODE_CONFIG'] = JSON.stringify(configOverride)
201 return new Promise<ServerInfo>(res => {
202 server.app = fork(join(root(), 'dist', 'server.js'), args, options)
203 server.app.stdout.on('data', function onStdout (data) {
204 let dontContinue = false
206 // Capture things if we want to
207 for (const key of Object.keys(regexps)) {
208 const regexp = regexps[key]
209 const matches = data.toString().match(regexp)
210 if (matches !== null) {
211 if (key === 'client_id') server.client.id = matches[1]
212 else if (key === 'client_secret') server.client.secret = matches[1]
213 else if (key === 'user_username') server.user.username = matches[1]
214 else if (key === 'user_password') server.user.password = matches[1]
218 // Check if all required sentences are here
219 for (const key of Object.keys(serverRunString)) {
220 if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
221 if (serverRunString[key] === false) dontContinue = true
224 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
225 if (dontContinue === true) return
227 server.app.stdout.removeListener('data', onStdout)
229 process.on('exit', () => {
231 process.kill(server.app.pid)
232 } catch { /* empty */ }
240 async function reRunServer (server: ServerInfo, configOverride?: any) {
241 const newServer = await runServer(server, configOverride)
242 server.app = newServer.app
247 function checkTmpIsEmpty (server: ServerInfo) {
248 return checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css' ])
251 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
252 const testDirectory = 'test' + server.internalServerNumber
254 const directoryPath = join(root(), testDirectory, directory)
256 const directoryExists = await pathExists(directoryPath)
257 expect(directoryExists).to.be.true
259 const files = await readdir(directoryPath)
260 const filtered = files.filter(f => exceptions.includes(f) === false)
262 expect(filtered).to.have.lengthOf(0)
265 function killallServers (servers: ServerInfo[]) {
266 for (const server of servers) {
267 if (!server.app) continue
269 process.kill(-server.app.pid)
274 function cleanupTests (servers: ServerInfo[]) {
275 killallServers(servers)
277 const p: Promise<any>[] = []
278 for (const server of servers) {
279 if (server.parallel) {
280 p.push(flushTests(server.internalServerNumber))
283 if (server.customConfigFile) {
284 p.push(remove(server.customConfigFile))
288 return Promise.all(p)
291 async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
292 const logfile = join(root(), 'test' + server.internalServerNumber, 'logs/peertube.log')
295 const buf = await readFile(logfile)
297 const matches = buf.toString().match(new RegExp(str, 'g'))
298 if (matches && matches.length === count) return
299 if (matches && strictCount === false && matches.length >= count) return
305 // ---------------------------------------------------------------------------
308 checkDirectoryIsEmpty,
313 flushAndRunMultipleServers,