Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
4.8 KB
Raw Blame
require "test_helper"

class MarketDataSchedulerTest < ActiveSupport::TestCase
  # Stubbed instead of hitting real Sidekiq::Cron (Redis): the JOB_NAME key
  # is global, so parallel test workers sharing the same Redis instance can
  # race and destroy each other's job mid-test (flaky NoMethodError on nil).
  setup do
    @job = OpenStruct.new(valid?: true)
  end

  test "sync! creates a cron job with the correct UTC cron string when enabled" do
    Setting.stubs(:market_data_sync_enabled?).returns(true)
    Setting.stubs(:market_data_sync_enabled).returns(true)
    Setting.stubs(:market_data_sync_time).returns("18:00")
    Setting.stubs(:market_data_sync_timezone).returns("UTC")

    Sidekiq::Cron::Job.expects(:create).with(
      name: MarketDataScheduler::JOB_NAME,
      cron: "0 18 * * 1-5 Etc/UTC",
      class: "ImportMarketDataJob",
      active_job: true,
      queue: "scheduled",
      args: { mode: "full", clear_cache: false },
      description: "Imports market data daily (Mon-Fri) at the configured time"
    ).returns(@job)

    MarketDataScheduler.sync!
  end

  test "upsert_job embeds the configured IANA timezone instead of converting to UTC" do
    Setting.stubs(:market_data_sync_time).returns("22:00")
    Setting.stubs(:market_data_sync_timezone).returns("Pacific Time (US & Canada)")

    # The local hour/weekday are preserved verbatim (no UTC conversion), so
    # the job always fires at 22:00 local time regardless of daylight-saving
    # transitions or how far the local date is from the UTC date boundary.
    Sidekiq::Cron::Job.expects(:create).with(
      has_entries(cron: "0 22 * * 1-5 America/Los_Angeles")
    ).returns(@job)

    MarketDataScheduler.upsert_job
  end

  test "sync! removes the cron job when disabled" do
    Setting.stubs(:market_data_sync_enabled?).returns(false)
    Setting.stubs(:market_data_sync_enabled).returns(false)
    Setting.stubs(:market_data_sync_time).returns("18:00")
    Sidekiq::Cron::Job.expects(:find).with(MarketDataScheduler::JOB_NAME).returns(@job)
    @job.expects(:destroy)

    MarketDataScheduler.sync!
  end

  test "upsert_job falls back to the default time on an invalid time format" do
    Setting.stubs(:market_data_sync_time).returns("not-a-time")
    Setting.stubs(:market_data_sync_timezone).returns("UTC")

    Sidekiq::Cron::Job.expects(:create).with(
      has_entries(cron: "0 22 * * 1-5 Etc/UTC")
    ).returns(@job)

    MarketDataScheduler.upsert_job
  end

  test "the timezone-suffixed cron formats MarketDataScheduler emits are accepted by the installed Sidekiq::Cron parser" do
    # Unlike the tests above, this hits real Sidekiq::Cron (Redis) to confirm
    # the installed sidekiq-cron/fugit version actually parses and persists a
    # cron string with a trailing IANA timezone. Mocking Job.create everywhere
    # would let a parser/version regression slip through unnoticed. Covers
    # both a UTC alias and a non-UTC zone, since MarketDataScheduler emits
    # both. Uses random job names (not JOB_NAME) so this can't race with
    # other tests/workers touching MarketDataScheduler's job.
    [ "0 18 * * 1-5 Etc/UTC", "0 22 * * 1-5 America/Los_Angeles" ].each do |cron|
      job_name = "market_data_scheduler_cron_contract_test_#{SecureRandom.hex(8)}"

      begin
        created = Sidekiq::Cron::Job.create(
          name: job_name,
          cron: cron,
          class: "ImportMarketDataJob"
        )
        assert created, "Expected Sidekiq::Cron to accept cron string: #{cron}"

        job = Sidekiq::Cron::Job.find(job_name)
        assert job, "Expected the cron job to be persisted for: #{cron}"
        assert job.valid?, job.errors.to_a.join(", ")
        assert_equal cron, job.cron
      ensure
        Sidekiq::Cron::Job.find(job_name)&.destroy
      end
    end
  end

  test "capture_sync_failure writes an error entry to the debug log" do
    Setting.stubs(:market_data_sync_time).returns("18:30")
    Setting.stubs(:market_data_sync_timezone).returns("Europe/Berlin")

    assert_difference -> { DebugLogEntry.where(category: "market_data_schedule").count }, 1 do
      MarketDataScheduler.capture_sync_failure(StandardError.new("redis down"), source: "Sidekiq startup")
    end

    entry = DebugLogEntry.where(category: "market_data_schedule").last
    assert_equal "error", entry.level
    assert_equal "Sidekiq startup", entry.source
    assert_equal "redis down", entry.metadata["exception_message"]
    assert_equal "18:30", entry.metadata["time"]
    assert_equal "Europe/Berlin", entry.metadata["timezone"]
  end

  test "capture_sync_failure never raises when the settings cannot be read" do
    Setting.stubs(:market_data_sync_time).raises(ActiveRecord::ConnectionNotEstablished)

    assert_no_difference -> { DebugLogEntry.count } do
      assert_nil MarketDataScheduler.capture_sync_failure(StandardError.new("boom"), source: "Sidekiq startup")
    end
  end
end