如何测试限速HTTP请求功能?

问题描述 投票:0回答:1

我有一个外部服务,正在从 Node.js 发出 HTTP 请求。该服务当前存在限制,每秒只能发出 10 个请求。我写了一个天真的速率限制器,我正在尝试测试它,但在它的时间上失败了。我知道 Javascript 时间不是很准确,但我得到了截然不同的波动,最多有 50 毫秒的差异。

这是我正在做的事情的要点:

var RATE_LIMIT_MS = 100 // No more than 10 requests per second
var NEXT_WAIT_MS = 0

function goGetRequest(...) {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            function complete() {
                // Rollback next time after this request finishes
                NEXT_WAIT_MS = Math.max(0, NEXT_WAIT_MS - RATE_LIMIT_MS)
            }

            // ... requests are fired off here asynchronously...
            http.get(...).then(complete)

        }, NEXT_WAIT_MS)

        // Push time back on the queue
        NEXT_WAIT_MS += RATE_LIMIT_MS
    })
}

var chai = require('chai')
var expect = chai.expect

it('should rate limit requests properly', function() {
    var iterations = [0, 1, 2, 3, 4]
    var lastResponseMs = 0

    var promises = iterations.map(function(i) {
        return goGetRequest(...).
            then(function(result) {
                // Diff the times
                var thisResponseMs = Date.now()
                var thisDiffMs = Math.abs(thisResponseMs - lastResponseMs)

                expect(wrapper.results).to.not.be.empty
                expect(thisDiffMs, 'failed on pass ' + i).to.be.at.least(RATE_LIMIT_MS)

                // Move last response time forward
                lastResponseMs = thisResponseMs
            })
    })

    return Promise.all(promises)
})

接下来发生的事情是测试将随机失败。第 2 遍的时间差为 92 毫秒,第 4 遍的时间差为 68 毫秒......我在这里错过了什么?谢谢!

javascript node.js mocha.js chai rate-limiting
1个回答
0
投票

Javascript setTimeout 和 setInterval (与任何非实时代码一样)从来都不是精确的。但是,如果您使用 NodeJS,您可以尝试使用 Nanotimer:

https://www.npmjs.com/package/nanotimer

var NanoTimer = require('nanotimer'); var timerA = new NanoTimer(); timerA.setTimeout(yourFunction, '', NEXT_WAIT_MS);

或者,我建议简单地测试

是否发生速率限制,而不必太担心精确度。如果你连续向它发送 11 个请求(希望时间应该不到一秒),并且它被阻止,一秒后就没事了,那么你的测试可以被视为通过。

最终的解决方案是使用

exec()

 并调用操作系统 
sleep
 命令,这明显更精确。

© www.soinside.com 2019 - 2024. All rights reserved.