1 /* tslint:disable:no-unused-expression */
3 import { ChildProcess, exec, fork } from 'child_process'
4 import { join } from 'path'
5 import { root, wait } from '../miscs/miscs'
6 import { copy, readdir, readFile, remove } from 'fs-extra'
7 import { existsSync } from 'fs'
8 import { expect } from 'chai'
9 import { VideoChannel } from '../../models/videos'
10 import { randomInt } from '../../core-utils/miscs/miscs'
12 interface ServerInfo {
19 internalServerNumber: number
33 customConfigFile?: string
36 videoChannel?: VideoChannel
52 videos?: { id: number, uuid: string }[]
55 function parallelTests () {
56 return process.env.MOCHA_PARALLEL === 'true'
59 function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
63 return new Promise<ServerInfo[]>(res => {
64 function anotherServerDone (serverNumber, app) {
65 apps[serverNumber - 1] = app
67 if (i === totalServers) {
72 for (let j = 1; j <= totalServers; j++) {
73 flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
78 function flushTests (serverNumber?: number) {
79 return new Promise<void>((res, rej) => {
80 const suffix = serverNumber ? ` -- ${serverNumber}` : ''
82 return exec('npm run clean:server:test' + suffix, err => {
83 if (err) return rej(err)
90 function randomServer () {
94 return randomInt(low, high)
97 async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = []) {
98 const parallel = parallelTests()
100 const internalServerNumber = parallel ? randomServer() : serverNumber
101 const port = 9000 + internalServerNumber
103 await flushTests(internalServerNumber)
105 const server: ServerInfo = {
108 internalServerNumber,
111 url: `http://localhost:${port}`,
112 host: `localhost:${port}`,
123 return runServer(server, configOverride, args)
126 async function runServer (server: ServerInfo, configOverrideArg?: any, args = []) {
127 // These actions are async so we need to be sure that they have both been done
128 const serverRunString = {
129 'Server listening': false
131 const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
132 serverRunString[key] = false
135 client_id: 'Client id: (.+)',
136 client_secret: 'Client secret: (.+)',
137 user_username: 'Username: (.+)',
138 user_password: 'User password: (.+)'
141 if (server.internalServerNumber !== server.serverNumber) {
142 const basePath = join(root(), 'config')
144 const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
145 await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
147 server.customConfigFile = tmpConfigFile
150 const configOverride: any = {}
152 if (server.parallel) {
153 Object.assign(configOverride, {
161 suffix: '_test' + server.internalServerNumber
164 tmp: `test${server.internalServerNumber}/tmp/`,
165 avatars: `test${server.internalServerNumber}/avatars/`,
166 videos: `test${server.internalServerNumber}/videos/`,
167 streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
168 redundancy: `test${server.internalServerNumber}/redundancy/`,
169 logs: `test${server.internalServerNumber}/logs/`,
170 previews: `test${server.internalServerNumber}/previews/`,
171 thumbnails: `test${server.internalServerNumber}/thumbnails/`,
172 torrents: `test${server.internalServerNumber}/torrents/`,
173 captions: `test${server.internalServerNumber}/captions/`,
174 cache: `test${server.internalServerNumber}/cache/`
177 email: `admin${server.internalServerNumber}@example.com`
182 if (configOverrideArg !== undefined) {
183 Object.assign(configOverride, configOverrideArg)
186 // Share the environment
187 const env = Object.create(process.env)
188 env['NODE_ENV'] = 'test'
189 env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
190 env['NODE_CONFIG'] = JSON.stringify(configOverride)
198 return new Promise<ServerInfo>(res => {
199 server.app = fork(join(root(), 'dist', 'server.js'), args, options)
200 server.app.stdout.on('data', function onStdout (data) {
201 let dontContinue = false
203 // Capture things if we want to
204 for (const key of Object.keys(regexps)) {
205 const regexp = regexps[ key ]
206 const matches = data.toString().match(regexp)
207 if (matches !== null) {
208 if (key === 'client_id') server.client.id = matches[ 1 ]
209 else if (key === 'client_secret') server.client.secret = matches[ 1 ]
210 else if (key === 'user_username') server.user.username = matches[ 1 ]
211 else if (key === 'user_password') server.user.password = matches[ 1 ]
215 // Check if all required sentences are here
216 for (const key of Object.keys(serverRunString)) {
217 if (data.toString().indexOf(key) !== -1) serverRunString[ key ] = true
218 if (serverRunString[ key ] === false) dontContinue = true
221 // If no, there is maybe one thing not already initialized (client/user credentials generation...)
222 if (dontContinue === true) return
224 server.app.stdout.removeListener('data', onStdout)
226 process.on('exit', () => {
228 process.kill(server.app.pid)
229 } catch { /* empty */ }
237 async function reRunServer (server: ServerInfo, configOverride?: any) {
238 const newServer = await runServer(server, configOverride)
239 server.app = newServer.app
244 async function checkTmpIsEmpty (server: ServerInfo) {
245 return checkDirectoryIsEmpty(server, 'tmp')
248 async function checkDirectoryIsEmpty (server: ServerInfo, directory: string) {
249 const testDirectory = 'test' + server.serverNumber
251 const directoryPath = join(root(), testDirectory, directory)
253 const directoryExists = existsSync(directoryPath)
254 expect(directoryExists).to.be.true
256 const files = await readdir(directoryPath)
257 expect(files).to.have.lengthOf(0)
260 function killallServers (servers: ServerInfo[]) {
261 for (const server of servers) {
262 if (!server.app) continue
264 process.kill(-server.app.pid)
269 function cleanupTests (servers: ServerInfo[]) {
270 killallServers(servers)
272 const p: Promise<any>[] = []
273 for (const server of servers) {
274 if (server.parallel) {
275 p.push(flushTests(server.internalServerNumber))
278 if (server.customConfigFile) {
279 p.push(remove(server.customConfigFile))
283 return Promise.all(p)
286 async function waitUntilLog (server: ServerInfo, str: string, count = 1) {
287 const logfile = join(root(), 'test' + server.serverNumber, 'logs/peertube.log')
290 const buf = await readFile(logfile)
292 const matches = buf.toString().match(new RegExp(str, 'g'))
293 if (matches && matches.length === count) return
299 // ---------------------------------------------------------------------------
302 checkDirectoryIsEmpty,
307 flushAndRunMultipleServers,