process_delayed_jobs_spec.rb 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. require 'rails_helper'
  3. class SampleDelayedJob < ApplicationJob
  4. def perform
  5. Rails.logger.debug 'performing SampleTestJob'
  6. end
  7. end
  8. RSpec.describe BackgroundServices::Service::ProcessDelayedJobs, ensure_threads_exited: true do
  9. before do
  10. stub_const "#{described_class}::SLEEP_IF_EMPTY", 0.5
  11. end
  12. let(:instance) { described_class.new }
  13. describe '#run' do
  14. context 'with a queued job' do
  15. before do
  16. Delayed::Job.destroy_all
  17. SampleDelayedJob.perform_later
  18. end
  19. it 'processes a job' do
  20. expect do
  21. ensure_block_keeps_running do
  22. described_class.new.run
  23. end
  24. end.to change(Delayed::Job, :count).by(-1)
  25. end
  26. it 'runs loop multiple times', :aggregate_failures do
  27. allow(instance).to receive(:process_results)
  28. # Delayed::Worker uses `rescue Exception` heavily which would swallow our timeout errors,
  29. # causing the tests to fail. Avoid calling it.
  30. allow(Benchmark).to receive(:realtime).and_return(1)
  31. ensure_block_keeps_running { instance.run }
  32. expect(instance).to have_received(:process_results).at_least(1)
  33. end
  34. end
  35. end
  36. describe '#process_results' do
  37. it 'sleeps & loops when no jobs processed', :aggregate_failures do
  38. allow(Rails.logger).to receive(:debug)
  39. instance.send(:process_results, [0, 0], 1)
  40. expect(Rails.logger).to have_received(:debug).with(no_args) do |&block|
  41. expect(block.call).to match(%r{loop})
  42. end
  43. end
  44. it 'loops immediatelly when there was anything to process', :aggregate_failures do
  45. allow(Rails.logger).to receive(:debug)
  46. instance.send(:process_results, [1, 0], 1)
  47. expect(Rails.logger).to have_received(:debug).with(no_args) do |&block|
  48. expect(block.call).to match(%r{jobs processed})
  49. end
  50. end
  51. end
  52. describe '.pre_run' do
  53. it 'cleans up DelayedJobs' do
  54. allow(described_class::CleanupAction).to receive(:cleanup_delayed_jobs)
  55. described_class.pre_run
  56. expect(described_class::CleanupAction).to have_received(:cleanup_delayed_jobs)
  57. end
  58. it 'cleans up ImportJobs' do
  59. allow(ImportJob).to receive(:cleanup_import_jobs)
  60. described_class.pre_run
  61. expect(ImportJob).to have_received(:cleanup_import_jobs)
  62. end
  63. it 'runs in scheduler context' do
  64. handle_info = nil
  65. allow(described_class)
  66. .to receive(:pre_launch).and_invoke(-> { handle_info = ApplicationHandleInfo.current })
  67. described_class.pre_run
  68. expect(handle_info).to eq 'scheduler'
  69. end
  70. end
  71. end