aboutsummaryrefslogtreecommitdiffstats
path: root/railties/test/rack_logger_test.rb
blob: e14eff41ce7bf01514388f22d2164dc35daa9e52 (plain) (blame)
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
require "abstract_unit"
require "active_support/testing/autorun"
require "active_support/test_case"
require "rails/rack/logger"
require "logger"

module Rails
  module Rack
    class LoggerTest < ActiveSupport::TestCase
      class TestLogger < Rails::Rack::Logger
        NULL = ::Logger.new File::NULL

        attr_reader :logger

        def initialize(logger = NULL, taggers = nil, &block)
          super(->(_) { block.call; [200, {}, []] }, taggers)
          @logger = logger
        end

        def development?; false; end
      end

      class Subscriber < Struct.new(:starts, :finishes)
        def initialize(starts = [], finishes = [])
          super
        end

        def start(name, id, payload)
          starts << [name, id, payload]
        end

        def finish(name, id, payload)
          finishes << [name, id, payload]
        end
      end

      attr_reader :subscriber, :notifier

      def setup
        @subscriber = Subscriber.new
        @notifier = ActiveSupport::Notifications.notifier
        @subscription = notifier.subscribe "request.action_dispatch", subscriber
      end

      def teardown
        notifier.unsubscribe @subscription
      end

      def test_notification
        logger = TestLogger.new { }

        assert_difference("subscriber.starts.length") do
          assert_difference("subscriber.finishes.length") do
            logger.call("REQUEST_METHOD" => "GET").last.close
          end
        end
      end

      def test_notification_on_raise
        logger = TestLogger.new do
          # using an exception class that is not a StandardError subclass on purpose
          raise NotImplementedError
        end

        assert_difference("subscriber.starts.length") do
          assert_difference("subscriber.finishes.length") do
            assert_raises(NotImplementedError) do
              logger.call "REQUEST_METHOD" => "GET"
            end
          end
        end
      end
    end
  end
end