]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/tests/utils/miscs/miscs.ts
7ac60a983b5faf68358ced7c13bd47a48f260b22
[github/Chocobozzz/PeerTube.git] / server / tests / utils / miscs / miscs.ts
1 /* tslint:disable:no-unused-expression */
2
3 import * as chai from 'chai'
4 import { isAbsolute, join } from 'path'
5 import * as request from 'supertest'
6 import * as WebTorrent from 'webtorrent'
7 import { readFileBufferPromise } from '../../../helpers/core-utils'
8 import { ServerInfo } from '..'
9
10 const expect = chai.expect
11 let webtorrent = new WebTorrent()
12
13 function immutableAssign <T, U> (target: T, source: U) {
14 return Object.assign<{}, T, U>({}, target, source)
15 }
16
17 // Default interval -> 5 minutes
18 function dateIsValid (dateString: string, interval = 300000) {
19 const dateToCheck = new Date(dateString)
20 const now = new Date()
21
22 return Math.abs(now.getTime() - dateToCheck.getTime()) <= interval
23 }
24
25 function wait (milliseconds: number) {
26 return new Promise(resolve => setTimeout(resolve, milliseconds))
27 }
28
29 function webtorrentAdd (torrent: string, refreshWebTorrent = false) {
30 if (refreshWebTorrent === true) webtorrent = new WebTorrent()
31
32 return new Promise<WebTorrent.Torrent>(res => webtorrent.add(torrent, res))
33 }
34
35 function root () {
36 // We are in server/tests/utils/miscs
37 return join(__dirname, '..', '..', '..', '..')
38 }
39
40 async function testImage (url: string, imageName: string, imagePath: string, extension = '.jpg') {
41 // Don't test images if the node env is not set
42 // Because we need a special ffmpeg version for this test
43 if (process.env[ 'NODE_TEST_IMAGE' ]) {
44 const res = await request(url)
45 .get(imagePath)
46 .expect(200)
47
48 const body = res.body
49
50 const data = await readFileBufferPromise(join(__dirname, '..', '..', 'fixtures', imageName + extension))
51 const minLength = body.length - ((20 * body.length) / 100)
52 const maxLength = body.length + ((20 * body.length) / 100)
53
54 expect(data.length).to.be.above(minLength)
55 expect(data.length).to.be.below(maxLength)
56 } else {
57 console.log('Do not test images. Enable it by setting NODE_TEST_IMAGE env variable.')
58 return true
59 }
60 }
61
62 function buildAbsoluteFixturePath (path: string) {
63 if (isAbsolute(path)) {
64 return path
65 }
66
67 return join(__dirname, '..', '..', 'fixtures', path)
68 }
69
70 // ---------------------------------------------------------------------------
71
72 export {
73 dateIsValid,
74 wait,
75 webtorrentAdd,
76 immutableAssign,
77 testImage,
78 buildAbsoluteFixturePath,
79 root
80 }