|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require "test_helper" |
| 4 | +require "mocha/minitest" |
| 5 | + |
| 6 | +class TimerTaskTest < ActiveSupport::TestCase |
| 7 | + test "initialization requires a block" do |
| 8 | + assert_raises(ArgumentError) do |
| 9 | + SolidQueue::TimerTask.new(execution_interval: 1) |
| 10 | + end |
| 11 | + end |
| 12 | + |
| 13 | + test "task runs immediate when run now true" do |
| 14 | + executed = false |
| 15 | + |
| 16 | + task = SolidQueue::TimerTask.new(run_now: true, execution_interval: 1) do |
| 17 | + executed = true |
| 18 | + end |
| 19 | + |
| 20 | + sleep 0.1 |
| 21 | + |
| 22 | + assert executed, "Task should have executed immediately" |
| 23 | + task.shutdown |
| 24 | + end |
| 25 | + |
| 26 | + test "task does not run immediately when run with run_now false" do |
| 27 | + executed = false |
| 28 | + |
| 29 | + task = SolidQueue::TimerTask.new(run_now: false, execution_interval: 1) do |
| 30 | + executed = true |
| 31 | + end |
| 32 | + |
| 33 | + sleep 0.1 |
| 34 | + |
| 35 | + assert_not executed, "Task should have executed immediately" |
| 36 | + task.shutdown |
| 37 | + end |
| 38 | + |
| 39 | + test "task repeats" do |
| 40 | + executions = 0 |
| 41 | + |
| 42 | + task = SolidQueue::TimerTask.new(execution_interval: 0.1, run_now: false) do |
| 43 | + executions += 1 |
| 44 | + end |
| 45 | + |
| 46 | + sleep(0.5) # Wait to accumulate some executions |
| 47 | + |
| 48 | + assert executions > 3, "The block should be executed repeatedly" |
| 49 | + |
| 50 | + task.shutdown |
| 51 | + end |
| 52 | + |
| 53 | + test "task stops on shutdown" do |
| 54 | + executions = 0 |
| 55 | + |
| 56 | + task = SolidQueue::TimerTask.new(execution_interval: 0.1, run_now: false) { executions += 1 } |
| 57 | + |
| 58 | + sleep(0.3) # Let the task run a few times |
| 59 | + |
| 60 | + task.shutdown |
| 61 | + |
| 62 | + current_executions = executions |
| 63 | + |
| 64 | + sleep(0.5) # Ensure no more executions after shutdown |
| 65 | + |
| 66 | + assert_equal current_executions, executions, "The task should stop executing after shutdown" |
| 67 | + end |
| 68 | + |
| 69 | + test "calls handle_thread_error if task raises" do |
| 70 | + task = SolidQueue::TimerTask.new(execution_interval: 0.1) do |
| 71 | + raise ExpectedTestError.new |
| 72 | + end |
| 73 | + task.expects(:handle_thread_error).with(instance_of(ExpectedTestError)) |
| 74 | + |
| 75 | + sleep(0.2) # Give some time for the task to run and handle the error |
| 76 | + |
| 77 | + task.shutdown |
| 78 | + end |
| 79 | +end |
0 commit comments