aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/test/queueing/threaded_consumer_test.rb
blob: a3ca46a261cf865e1bbe3c5af8d46f7f85fed318 (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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
require 'abstract_unit'
require 'active_support/queueing'
require "active_support/log_subscriber/test_helper"

class TestThreadConsumer < ActiveSupport::TestCase
  class Job
    attr_reader :id
    def initialize(id = 1, &block)
      @id = id
      @block = block
    end

    def run
      @block.call if @block
    end
  end

  def setup
    @logger = ActiveSupport::LogSubscriber::TestHelper::MockLogger.new
    @queue = ActiveSupport::Queue.new(logger: @logger)
  end

  def teardown
    @queue.drain
  end

  test "the jobs are executed" do
    ran = false
    job = Job.new { ran = true }

    @queue.push job
    @queue.drain

    assert_equal true, ran
  end

  test "the jobs are not executed synchronously" do
    run, ran = Queue.new, Queue.new
    job = Job.new { ran.push run.pop }

    @queue.consumer.start
    @queue.push job
    assert ran.empty?

    run.push true
    assert_equal true, ran.pop
  end

  test "shutting down the queue synchronously drains the jobs" do
    ran = false
    job = Job.new do
      sleep 0.1
      ran = true
    end

    @queue.consumer.start
    @queue.push job
    assert_equal false, ran

    @queue.consumer.shutdown
    assert_equal true, ran
  end

  test "log job that raises an exception" do
    job = Job.new { raise "RuntimeError: Error!" }

    @queue.push job
    consume_queue @queue

    assert_equal 1, @logger.logged(:error).size
    assert_match "Job Error: #{job.inspect}\nRuntimeError: Error!", @logger.logged(:error).last
  end

  test "logger defaults to stderr" do
    begin
      $stderr, old_stderr = StringIO.new, $stderr
      queue = ActiveSupport::Queue.new
      queue.push Job.new { raise "RuntimeError: Error!" }
      consume_queue queue
      assert_match 'Job Error', $stderr.string
    ensure
      $stderr = old_stderr
    end
  end

  test "test overriding exception handling" do
    @queue.consumer.instance_eval do
      def handle_exception(job, exception)
        @last_error = exception.message
      end

      def last_error
        @last_error
      end
    end

    job = Job.new { raise "RuntimeError: Error!" }

    @queue.push job
    consume_queue @queue

    assert_equal "RuntimeError: Error!", @queue.consumer.last_error
  end

  private
    def consume_queue(queue)
      queue.push nil
      queue.consumer.consume
    end
end