|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +RSpec.describe Millrace::RateLimit do |
| 4 | + let(:subject) do |
| 5 | + described_class.new( |
| 6 | + name: "test", |
| 7 | + rate: 10, |
| 8 | + window: 2, |
| 9 | + penalty: penalty, |
| 10 | + ) |
| 11 | + end |
| 12 | + |
| 13 | + let(:penalty) { 1 } |
| 14 | + |
| 15 | + let(:controller) do |
| 16 | + double(:controller, request: double(:request, remote_ip: to_s)) |
| 17 | + end |
| 18 | + |
| 19 | + describe "#before" do |
| 20 | + it "rate limits" do |
| 21 | + # Fill the bucket |
| 22 | + 20.times { subject.before(controller) } |
| 23 | + |
| 24 | + # hit the threshold and get a penalty |
| 25 | + expect { subject.before(controller) }.to raise_error Millrace::RateLimited |
| 26 | + |
| 27 | + sleep 1 |
| 28 | + # Still blocked for the penalty duration |
| 29 | + expect { subject.before(controller) }.to raise_error Millrace::RateLimited |
| 30 | + |
| 31 | + # Not blocked after the penalty duration is over |
| 32 | + sleep 1 |
| 33 | + subject.before(controller) |
| 34 | + end |
| 35 | + |
| 36 | + it "returns an exeption with the correct name" do |
| 37 | + # Fill the bucket |
| 38 | + 20.times { subject.before(controller) } |
| 39 | + |
| 40 | + # hit the threshold and get an error |
| 41 | + expect { subject.before(controller) }.to raise_error do |exception| |
| 42 | + expect(exception.limit_name).to eq "test" |
| 43 | + end |
| 44 | + end |
| 45 | + |
| 46 | + it "returns an exeption with the correct retry time" do |
| 47 | + # Fill the bucket |
| 48 | + 20.times { subject.before(controller) } |
| 49 | + |
| 50 | + # hit the threshold and get an error |
| 51 | + expect { subject.before(controller) }.to raise_error do |exception| |
| 52 | + expect(exception.retry_after).to eq 1 |
| 53 | + end |
| 54 | + end |
| 55 | + |
| 56 | + context "a longer penalty" do |
| 57 | + let(:penalty) { 10 } |
| 58 | + |
| 59 | + it "returns an exeption with the correct retry time" do |
| 60 | + # Fill the bucket |
| 61 | + 20.times { subject.before(controller) } |
| 62 | + |
| 63 | + # hit the threshold and get an error |
| 64 | + expect { subject.before(controller) }.to raise_error do |exception| |
| 65 | + expect(exception.retry_after).to eq 10 |
| 66 | + end |
| 67 | + end |
| 68 | + end |
| 69 | + |
| 70 | + context "additional requests" do |
| 71 | + let(:penalty) { 0 } |
| 72 | + |
| 73 | + it "returns an exeption with the correct retry time" do |
| 74 | + # Fill the bucket |
| 75 | + 40.times do |
| 76 | + subject.before(controller) |
| 77 | + # Keep making requests even though we are rate limited |
| 78 | + rescue Millrace::RateLimited |
| 79 | + nil |
| 80 | + end |
| 81 | + |
| 82 | + # hit the threshold and get an error |
| 83 | + expect { subject.before(controller) }.to raise_error do |exception| |
| 84 | + expect(exception.retry_after).to eq 2 |
| 85 | + end |
| 86 | + end |
| 87 | + end |
| 88 | + end |
| 89 | +end |
0 commit comments