|
| 1 | +const { expect } = require('chai'); |
| 2 | +const sinon = require('sinon'); |
| 3 | +const httpProxy = require('http-proxy'); |
| 4 | +const https = require('https'); |
| 5 | +const config = require('./utils/config'); |
| 6 | +const { DBSQLClient } = require('../..'); |
| 7 | + |
| 8 | +class HttpProxyMock { |
| 9 | + constructor(target, port) { |
| 10 | + this.requests = []; |
| 11 | + |
| 12 | + this.config = { |
| 13 | + protocol: 'http', |
| 14 | + host: 'localhost', |
| 15 | + port, |
| 16 | + }; |
| 17 | + |
| 18 | + this.target = `https://${config.host}`; |
| 19 | + |
| 20 | + this.proxy = httpProxy.createServer({ |
| 21 | + target: this.target, |
| 22 | + agent: new https.Agent({ |
| 23 | + rejectUnauthorized: false, |
| 24 | + }), |
| 25 | + }); |
| 26 | + |
| 27 | + this.proxy.on('proxyRes', (proxyRes) => { |
| 28 | + const req = proxyRes.req; |
| 29 | + this.requests.push({ |
| 30 | + method: req.method?.toUpperCase(), |
| 31 | + url: `${req.protocol}//${req.host}${req.path}`, |
| 32 | + requestHeaders: { ...req.getHeaders() }, |
| 33 | + responseHeaders: proxyRes.headers, |
| 34 | + }); |
| 35 | + }); |
| 36 | + |
| 37 | + this.proxy.listen(port); |
| 38 | + console.log(`Proxy listening at ${this.config.host}:${this.config.port} -> ${this.target}`); |
| 39 | + } |
| 40 | + |
| 41 | + close() { |
| 42 | + this.proxy.close(() => { |
| 43 | + console.log(`Proxy stopped at ${this.config.host}:${this.config.port}`); |
| 44 | + }); |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +describe('Proxy', () => { |
| 49 | + it('should use http proxy', async () => { |
| 50 | + const proxy = new HttpProxyMock(`https://${config.host}`, 9090); |
| 51 | + try { |
| 52 | + const client = new DBSQLClient(); |
| 53 | + const clientConfig = client.getConfig(); |
| 54 | + sinon.stub(client, 'getConfig').returns(clientConfig); |
| 55 | + |
| 56 | + const connection = await client.connect({ |
| 57 | + host: config.host, |
| 58 | + path: config.path, |
| 59 | + token: config.token, |
| 60 | + proxy: proxy.config, |
| 61 | + }); |
| 62 | + |
| 63 | + const session = await connection.openSession({ |
| 64 | + initialCatalog: config.database[0], |
| 65 | + initialSchema: config.database[1], |
| 66 | + }); |
| 67 | + |
| 68 | + expect(proxy.requests.length).to.be.gte(1); |
| 69 | + expect(proxy.requests[0].method).to.be.eq('POST'); |
| 70 | + expect(proxy.requests[0].url).to.be.eq(`https://${config.host}${config.path}`); |
| 71 | + } finally { |
| 72 | + proxy.close(); |
| 73 | + } |
| 74 | + }); |
| 75 | +}); |
0 commit comments