tokenbucket-test.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. var vows = require('vows');
  2. var assert = require('assert');
  3. var TIMING_EPSILON = 10;
  4. var TokenBucket = require('../lib/tokenBucket');
  5. vows.describe('TokenBucket').addBatch({
  6. 'capacity 10, 1 per 100ms': {
  7. topic: new TokenBucket(10, 1, 100),
  8. 'is initialized empty': function(bucket) {
  9. assert.equal(bucket.bucketSize, 10);
  10. assert.equal(bucket.tokensPerInterval, 1);
  11. assert.equal(bucket.content, 0);
  12. },
  13. 'removing 10 tokens': {
  14. topic: function(bucket) {
  15. this.gStart = +new Date();
  16. bucket.removeTokens(10, this.callback);
  17. },
  18. 'takes 1 second': function(remainingTokens) {
  19. var duration = +new Date() - this.gStart;
  20. var diff = Math.abs(1000 - duration);
  21. assert.ok(diff < TIMING_EPSILON, diff+'');
  22. assert.equal(remainingTokens, 0);
  23. },
  24. 'and removing another 10 tokens': {
  25. topic: function(_, bucket) {
  26. this.gStart = +new Date();
  27. assert.equal(bucket.content, 0);
  28. bucket.removeTokens(10, this.callback);
  29. },
  30. 'takes 1 second': function() {
  31. var duration = +new Date() - this.gStart;
  32. var diff = Math.abs(1000 - duration);
  33. assert.ok(diff < TIMING_EPSILON, diff+'');
  34. }
  35. },
  36. 'and waiting 2 seconds': {
  37. topic: function(_, bucket) {
  38. var self = this;
  39. setTimeout(function() {
  40. self.gStart = +new Date();
  41. bucket.removeTokens(10, self.callback);
  42. }, 2000);
  43. },
  44. 'gives us only 10 tokens': function(remainingTokens) {
  45. var duration = +new Date() - this.gStart;
  46. assert.ok(duration < TIMING_EPSILON, duration+'');
  47. assert.equal(remainingTokens, 0);
  48. },
  49. 'and removing 1 token': {
  50. topic: function(_, _, bucket) {
  51. this.gStart = +new Date();
  52. bucket.removeTokens(1, this.callback);
  53. },
  54. 'takes 100ms': function() {
  55. var duration = +new Date() - this.gStart;
  56. var diff = Math.abs(100 - duration);
  57. assert.ok(diff < TIMING_EPSILON, diff+'');
  58. }
  59. }
  60. }
  61. }
  62. },
  63. }).export(module);