aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/tests/plugins/plugin-websocket.ts
blob: adaa28b1d962401d971418776b681f725e8b03fd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */

import WebSocket from 'ws'
import { cleanupTests, createSingleServer, PeerTubeServer, PluginsCommand, setAccessTokensToServers } from '@shared/server-commands'

function buildWebSocket (server: PeerTubeServer, path: string) {
  return new WebSocket('ws://' + server.host + path)
}

function expectErrorOrTimeout (server: PeerTubeServer, path: string, expectedTimeout: number) {
  return new Promise<void>((res, rej) => {
    const ws = buildWebSocket(server, path)
    ws.on('error', () => res())

    const timeout = setTimeout(() => res(), expectedTimeout)

    ws.on('open', () => {
      clearTimeout(timeout)

      return rej(new Error('Connect did not timeout'))
    })
  })
}

describe('Test plugin websocket', function () {
  let server: PeerTubeServer
  const basePaths = [
    '/plugins/test-websocket/ws/',
    '/plugins/test-websocket/0.0.1/ws/'
  ]

  before(async function () {
    this.timeout(30000)

    server = await createSingleServer(1)
    await setAccessTokensToServers([ server ])

    await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-websocket') })
  })

  it('Should not connect to the websocket without the appropriate path', async function () {
    const paths = [
      '/plugins/unknown/ws/',
      '/plugins/unknown/0.0.1/ws/'
    ]

    for (const path of paths) {
      await expectErrorOrTimeout(server, path, 1000)
    }
  })

  it('Should not connect to the websocket without the appropriate sub path', async function () {
    for (const path of basePaths) {
      await expectErrorOrTimeout(server, path + '/unknown', 1000)
    }
  })

  it('Should connect to the websocket and receive pong', function (done) {
    const ws = buildWebSocket(server, basePaths[0])

    ws.on('open', () => ws.send('ping'))
    ws.on('message', data => {
      if (data.toString() === 'pong') return done()
    })
  })

  after(async function () {
    await cleanupTests([ server ])
  })
})