/ test / request-handler.js
request-handler.js
 1  import Client from '../index.js'
 2  import common from './common.js'
 3  import fixtures from 'webtorrent-fixtures'
 4  import test from 'tape'
 5  import Server from '../server.js'
 6  
 7  const peerId = Buffer.from('01234567890123456789')
 8  
 9  function testRequestHandler (t, serverType) {
10    t.plan(5)
11  
12    const opts = { serverType } // this is test-suite-only option
13  
14    class Swarm extends Server.Swarm {
15      announce (params, cb) {
16        super.announce(params, (err, response) => {
17          if (cb && err) return cb(response)
18          response.complete = 246
19          response.extraData = 'hi'
20          if (cb) cb(null, response)
21        })
22      }
23    }
24  
25    // Use a custom Swarm implementation for this test only
26    const OldSwarm = Server.Swarm
27    Server.Swarm = Swarm
28    t.on('end', () => {
29      Server.Swarm = OldSwarm
30    })
31  
32    common.createServer(t, opts, (server, announceUrl) => {
33      const client1 = new Client({
34        infoHash: fixtures.alice.parsedTorrent.infoHash,
35        announce: announceUrl,
36        peerId,
37        port: 6881,
38        wrtc: {}
39      })
40  
41      client1.on('error', err => { t.error(err) })
42      if (serverType === 'ws') common.mockWebsocketTracker(client1)
43  
44      server.once('start', () => {
45        t.pass('got start message from client1')
46      })
47  
48      client1.once('update', data => {
49        t.equal(data.complete, 246)
50        t.equal(Buffer.from(data.extraData).toString(), 'hi')
51  
52        client1.destroy(() => {
53          t.pass('client1 destroyed')
54        })
55  
56        server.close(() => {
57          t.pass('server destroyed')
58        })
59      })
60  
61      client1.start()
62    })
63  }
64  
65  test('http: request handler option intercepts announce requests and responses', t => {
66    testRequestHandler(t, 'http')
67  })
68  
69  test('ws: request handler option intercepts announce requests and responses', t => {
70    testRequestHandler(t, 'ws')
71  })
72  
73  // NOTE: it's not possible to include extra data in a UDP response, because it's compact and accepts only params that are in the spec!