|
| 1 | +const assert = require('assert'); |
| 2 | + |
| 3 | +const { RateLimitClient } = require('../../../../../lib/api/apiUtils/rateLimit/client'); |
| 4 | + |
| 5 | +class RedisStub { |
| 6 | + constructor() { |
| 7 | + this.data = {}; |
| 8 | + this.execErr = null; |
| 9 | + } |
| 10 | + |
| 11 | + pipeline() { |
| 12 | + return new PipelineStub(this.execErr); |
| 13 | + } |
| 14 | + |
| 15 | + setExecErr(err) { |
| 16 | + this.execErr = err; |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +class PipelineStub { |
| 21 | + constructor(execErr) { |
| 22 | + this.ops = []; |
| 23 | + this.execErr = execErr; |
| 24 | + } |
| 25 | + |
| 26 | + updateCounter(key, cost) { |
| 27 | + this.ops.push([key, cost]); |
| 28 | + } |
| 29 | + |
| 30 | + exec(cb) { |
| 31 | + if (this.execErr) { |
| 32 | + cb(this.execErr); |
| 33 | + } else { |
| 34 | + cb(null, this.ops.map(v => [1, v[1]])); |
| 35 | + } |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +describe('test RateLimitClient', () => { |
| 40 | + let client; |
| 41 | + |
| 42 | + before(() => { |
| 43 | + client = new RateLimitClient({}); |
| 44 | + }); |
| 45 | + |
| 46 | + beforeEach(() => { |
| 47 | + client.redis = new RedisStub(); |
| 48 | + }); |
| 49 | + |
| 50 | + it('should update a batch of counters', done => { |
| 51 | + const batch = [ |
| 52 | + { key: 'foo', cost: 100 }, |
| 53 | + { key: 'bar', cost: 200 }, |
| 54 | + { key: 'qux', cost: 300 }, |
| 55 | + ]; |
| 56 | + |
| 57 | + client.updateLocalCounters(batch, (err, results) => { |
| 58 | + assert.ifError(err); |
| 59 | + assert.deepStrictEqual(results, [ |
| 60 | + { key: 'foo', value: 100 }, |
| 61 | + { key: 'bar', value: 200 }, |
| 62 | + { key: 'qux', value: 300 }, |
| 63 | + ]); |
| 64 | + done(); |
| 65 | + }); |
| 66 | + }); |
| 67 | + |
| 68 | + it('should pass through errors', done => { |
| 69 | + const execErr = new Error('bad stuff'); |
| 70 | + client.redis.setExecErr(execErr); |
| 71 | + const batch = [ |
| 72 | + { key: 'foo', cost: 100 }, |
| 73 | + { key: 'bar', cost: 200 }, |
| 74 | + { key: 'qux', cost: 300 }, |
| 75 | + ]; |
| 76 | + |
| 77 | + client.updateLocalCounters(batch, (err, results) => { |
| 78 | + assert.strictEqual(err, execErr); |
| 79 | + assert.strictEqual(results, undefined); |
| 80 | + done(); |
| 81 | + }); |
| 82 | + }); |
| 83 | +}); |
0 commit comments