logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma

rate_limit_plug_test.exs (1558B)


      1 defmodule Pleroma.Plugs.RateLimitPlugTest do
      2   use ExUnit.Case, async: true
      3   use Plug.Test
      4 
      5   alias Pleroma.Plugs.RateLimitPlug
      6 
      7   @opts RateLimitPlug.init(%{max_requests: 5, interval: 1})
      8 
      9   setup do
     10     enabled = Pleroma.Config.get([:app_account_creation, :enabled])
     11 
     12     Pleroma.Config.put([:app_account_creation, :enabled], true)
     13 
     14     on_exit(fn ->
     15       Pleroma.Config.put([:app_account_creation, :enabled], enabled)
     16     end)
     17 
     18     :ok
     19   end
     20 
     21   test "it restricts by opts" do
     22     conn = conn(:get, "/")
     23     bucket_name = conn.remote_ip |> Tuple.to_list() |> Enum.join(".")
     24     ms = 1000
     25 
     26     conn = RateLimitPlug.call(conn, @opts)
     27     {1, 4, _, _, _} = ExRated.inspect_bucket(bucket_name, ms, 5)
     28     conn = RateLimitPlug.call(conn, @opts)
     29     {2, 3, _, _, _} = ExRated.inspect_bucket(bucket_name, ms, 5)
     30     conn = RateLimitPlug.call(conn, @opts)
     31     {3, 2, _, _, _} = ExRated.inspect_bucket(bucket_name, ms, 5)
     32     conn = RateLimitPlug.call(conn, @opts)
     33     {4, 1, _, _, _} = ExRated.inspect_bucket(bucket_name, ms, 5)
     34     conn = RateLimitPlug.call(conn, @opts)
     35     {5, 0, to_reset, _, _} = ExRated.inspect_bucket(bucket_name, ms, 5)
     36     conn = RateLimitPlug.call(conn, @opts)
     37     assert conn.status == 403
     38     assert conn.halted
     39     assert conn.resp_body == "{\"error\":\"Rate limit exceeded.\"}"
     40 
     41     Process.sleep(to_reset)
     42 
     43     conn = conn(:get, "/")
     44     conn = RateLimitPlug.call(conn, @opts)
     45     {1, 4, _, _, _} = ExRated.inspect_bucket(bucket_name, ms, 5)
     46     refute conn.status == 403
     47     refute conn.halted
     48     refute conn.resp_body
     49   end
     50 end