Acceptance test throttling with a dynamic limit

This commit is contained in:
Gonzalo Rodriguez 2018-03-20 19:06:54 -03:00
parent 8b4f27827d
commit e17d2d8974
No known key found for this signature in database
GPG key ID: 5DB8B81B049B8AB1

View file

@ -2,9 +2,11 @@ require_relative "../spec_helper"
require "timecop"
describe "#throttle" do
it "allows one request per minute by IP" do
before do
Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
end
it "allows one request per minute by IP" do
Rack::Attack.throttle("by ip", limit: 1, period: 60) do |request|
request.ip
end
@ -29,4 +31,35 @@ describe "#throttle" do
assert_equal 200, last_response.status
end
end
it "supports limit to be dynamic" do
# Could be used to have different rate limits for authorized
# vs general requests
limit_proc = lambda do |request|
if request.get_header("X-APIKey") == "private-secret"
2
else
1
end
end
Rack::Attack.throttle("by ip", limit: limit_proc, period: 60) do |request|
request.ip
end
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 200, last_response.status
get "/", {}, "REMOTE_ADDR" => "1.2.3.4"
assert_equal 429, last_response.status
get "/", {}, "REMOTE_ADDR" => "5.6.7.8", "X-APIKey" => "private-secret"
assert_equal 200, last_response.status
get "/", {}, "REMOTE_ADDR" => "5.6.7.8", "X-APIKey" => "private-secret"
assert_equal 200, last_response.status
get "/", {}, "REMOTE_ADDR" => "5.6.7.8", "X-APIKey" => "private-secret"
assert_equal 429, last_response.status
end
end