File: rack_attack_instrumentation_spec.rb

package info (click to toggle)
ruby-rack-attack 6.7.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 380 kB
  • sloc: ruby: 2,626; makefile: 4
file content (43 lines) | stat: -rw-r--r-- 1,244 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# frozen_string_literal: true

require_relative "spec_helper"
require 'active_support'

# ActiveSupport::Subscribers added in ~> 4.0.2.0
if ActiveSupport::VERSION::MAJOR > 3
  require_relative 'spec_helper'
  require 'active_support/subscriber'
  class CustomSubscriber < ActiveSupport::Subscriber
    @notification_count = 0

    class << self
      attr_accessor :notification_count
    end

    def throttle(_event)
      self.class.notification_count += 1
    end
  end

  describe 'Rack::Attack.instrument' do
    before do
      @period = 60 # Use a long period; failures due to cache key rotation less likely
      Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
      Rack::Attack.throttle('ip/sec', limit: 1, period: @period) { |req| req.ip }
    end

    describe "with throttling" do
      before do
        ActiveSupport::Notifications.stub(:notifier, ActiveSupport::Notifications::Fanout.new) do
          CustomSubscriber.attach_to("rack_attack")
          2.times { get '/', {}, 'REMOTE_ADDR' => '1.2.3.4' }
        end
      end

      it 'should instrument without error' do
        _(last_response.status).must_equal 429
        assert_equal 1, CustomSubscriber.notification_count
      end
    end
  end
end