Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Improve Yahoo Finance reliability and Colombian listing support (#2738)

Camilo Agudelo7657f2d08cd7
diff --git a/app/controllers/settings/hostings_controller.rb b/app/controllers/settings/hostings_controller.rb
index 11f0b1c720..d1ae5f475b 100644
--- a/app/controllers/settings/hostings_controller.rb
+++ b/app/controllers/settings/hostings_controller.rb
@@ -45,6 +45,7 @@ class Settings::HostingsController < ApplicationController
if @show_yahoo_finance_settings
@yahoo_finance_provider = Provider::Registry.get_provider(:yahoo_finance)
+ @yahoo_finance_health_status = @yahoo_finance_provider&.health_status || :unknown
end
end
diff --git a/app/helpers/settings_helper.rb b/app/helpers/settings_helper.rb
index 155f8ec92b..9a4d6b1d7a 100644
--- a/app/helpers/settings_helper.rb
+++ b/app/helpers/settings_helper.rb
@@ -135,6 +135,38 @@ module SettingsHelper
end
end
+ def yahoo_finance_health_presentation(status)
+ status = status.to_sym if status.respond_to?(:to_sym)
+ status = :unknown unless %i[healthy rate_limited unavailable unknown].include?(status)
+
+ presentation = {
+ status_class: {
+ healthy: "bg-success",
+ rate_limited: "bg-warning",
+ unavailable: "bg-destructive",
+ unknown: "bg-surface-inset"
+ }.fetch(status),
+ status_text: t("settings.hostings.yahoo_finance_settings.status_#{status}")
+ }
+
+ presentation[:alert] = case status
+ when :rate_limited
+ {
+ title: t("settings.hostings.yahoo_finance_settings.rate_limited_title"),
+ message: t("settings.hostings.yahoo_finance_settings.rate_limited_message"),
+ variant: :warning
+ }
+ when :unavailable
+ {
+ title: t("settings.hostings.yahoo_finance_settings.unavailable_title"),
+ message: t("settings.hostings.yahoo_finance_settings.unavailable_message"),
+ variant: :warning
+ }
+ end
+
+ presentation
+ end
+
# Below this many synced accounts, the per-row pills already give the user
# enough at-a-glance signal and the strip is redundant chrome.
HEALTH_STRIP_MIN_ACCOUNTS = 10
diff --git a/app/jobs/yahoo_finance_health_check_job.rb b/app/jobs/yahoo_finance_health_check_job.rb
new file mode 100644
index 0000000000..f1a6f11746
--- /dev/null
+++ b/app/jobs/yahoo_finance_health_check_job.rb
@@ -0,0 +1,5 @@
+class YahooFinanceHealthCheckJob < ApplicationJob
+ def perform
+ Provider::YahooFinance.new.refresh_health_status
+ end
+end
diff --git a/app/models/provider/yahoo_finance.rb b/app/models/provider/yahoo_finance.rb
index 36a983f936..b4a4fdbdb3 100644
--- a/app/models/provider/yahoo_finance.rb
+++ b/app/models/provider/yahoo_finance.rb
@@ -19,6 +19,18 @@ class Provider::YahooFinance < Provider
# Even if cookie has longer expiry, cap it to avoid stale crumbs
MAX_CRUMB_CACHE_DURATION = 1.hour
+ HEALTH_STATUS_FRESHNESS = {
+ healthy: 15.minutes,
+ rate_limited: 30.minutes,
+ unavailable: 5.minutes
+ }.freeze
+ HEALTH_STATUS_RETENTION = 1.hour
+ HEALTH_LOCK_DURATION = 15.seconds
+ HEALTH_STATUS_CACHE_KEY = "yahoo_finance_health_status"
+ HEALTH_LOCK_CACHE_KEY = "yahoo_finance_health_status_lock"
+
+ INVALID_CRUMBS = Set.new([ "too many requests" ]).freeze
+
# Maximum lookback window for historical data (configurable)
MAX_LOOKBACK_WINDOW = 10.years
@@ -45,12 +57,51 @@ class Provider::YahooFinance < Provider
@cache_prefix = "yahoo_finance"
end
+ def health_status
+ assessment = read_health_cache(HEALTH_STATUS_CACHE_KEY)
+ return assessment[:status] if assessment_fresh?(assessment)
+
+ YahooFinanceHealthCheckJob.perform_later
+ assessment&.dig(:status) || :unknown
+ rescue HealthCacheError => e
+ record_health_cache_failure(e)
+ :unknown
+ end
+
+ def refresh_health_status
+ assessment = read_health_cache(HEALTH_STATUS_CACHE_KEY)
+ return assessment[:status] if assessment_fresh?(assessment)
+
+ lock_token = SecureRandom.uuid
+ lock_acquired = write_health_cache(
+ HEALTH_LOCK_CACHE_KEY,
+ lock_token,
+ expires_in: HEALTH_LOCK_DURATION,
+ unless_exist: true
+ )
+ return assessment&.dig(:status) || :unknown unless lock_acquired
+ return :unknown unless health_lock_owned?(lock_token)
+
+ result = perform_health_check
+ completed_assessment = result.merge(checked_at: Time.current)
+ unless publish_health_assessment(lock_token, completed_assessment)
+ return read_health_cache(HEALTH_STATUS_CACHE_KEY)&.dig(:status) || :unknown
+ end
+
+ record_health_transition(assessment, result)
+ status = result.fetch(:status)
+ released = release_health_lock(lock_token)
+ lock_token = nil
+ released ? status : :unknown
+ rescue HealthCacheError => e
+ record_health_cache_failure(e)
+ :unknown
+ ensure
+ release_health_lock(lock_token) if lock_token.present?
+ end
+
def healthy?
- data = fetch_authenticated_chart("AAPL", { "interval" => "1d", "range" => "1d" })
- result = data.dig("chart", "result")
- result.present? && result.any?
- rescue => e
- false
+ health_status == :healthy
end
def usage
@@ -158,12 +209,14 @@ class Provider::YahooFinance < Provider
quotes = data.dig("quotes") || []
securities = quotes.filter_map do |quote|
+ mic = map_exchange_mic(quote["exchange"])
+
Security.new(
symbol: quote["symbol"],
name: quote["longname"] || quote["shortname"] || quote["symbol"],
logo_url: nil, # Yahoo search doesn't provide logos
- exchange_operating_mic: map_exchange_mic(quote["exchange"]),
- country_code: map_country_code(quote["exchDisp"])
+ exchange_operating_mic: mic,
+ country_code: ::Security::EXCHANGES.dig(mic, "country") || map_country_code(quote["exchDisp"])
)
end
@@ -323,6 +376,185 @@ class Provider::YahooFinance < Provider
private
+ HealthCacheError = Class.new(StandardError)
+
+ def perform_health_check
+ stage = :cookie
+
+ cookie, crumb, stage = fetch_health_cookie_and_crumb
+
+ stage = :chart
+ chart_response = health_authenticated_client(cookie).get("#{base_url}/v8/finance/chart/AAPL") do |req|
+ req.params["interval"] = "1d"
+ req.params["range"] = "1d"
+ req.params["crumb"] = crumb
+ end
+ return health_result(:rate_limited, stage:, http_status: 429) if chart_response.status == 429
+ return health_result(:unavailable, stage:, http_status: chart_response.status) unless chart_response.success?
+
+ data = JSON.parse(chart_response.body)
+ if data.dig("chart", "error", "code") == "Unauthorized"
+ delete_health_cache("#{@cache_prefix}_auth_crumb")
+ return health_result(:unavailable, stage:, http_status: chart_response.status)
+ end
+ return health_result(:unavailable, stage:, http_status: chart_response.status) if data.dig("chart", "error").present?
+
+ results = data.dig("chart", "result")
+ health_result(results.present? ? :healthy : :unavailable, stage:, http_status: chart_response.status)
+ rescue HealthCacheError
+ raise
+ rescue Faraday::Error, JSON::ParserError => e
+ health_result(:unavailable, stage:, exception_class: e.class.name, http_status: faraday_status(e))
+ rescue RateLimitError => e
+ health_result(:rate_limited, stage: :crumb, exception_class: e.class.name, http_status: e.details&.dig(:status))
+ rescue AuthenticationError => e
+ health_result(:unavailable, stage:, exception_class: e.class.name, http_status: e.details&.dig(:status))
+ rescue => e
+ health_result(:unavailable, stage:, exception_class: e.class.name)
+ end
+
+ def health_result(status, stage:, exception_class: nil, http_status: nil)
+ {
+ status: status,
+ stage: stage,
+ exception_class: exception_class,
+ http_status: http_status
+ }.compact
+ end
+
+ def fetch_health_cookie_and_crumb
+ cache_key = "#{@cache_prefix}_auth_crumb"
+ cached = read_health_cache(cache_key)
+ if cached.present?
+ return [ cached.first, cached.second, :authentication_cache ] if valid_crumb?(cached.second)
+
+ delete_health_cache(cache_key)
+ end
+
+ cookie, crumb, cache_duration = request_cookie_and_crumb(health_auth_client)
+ write_health_cache!(cache_key, [ cookie, crumb ], expires_in: cache_duration)
+ [ cookie, crumb, :crumb ]
+ end
+
+ def faraday_status(error)
+ error.response&.dig(:status) if error.respond_to?(:response)
+ end
+
+ def health_auth_client
+ @health_auth_client ||= Faraday.new(ssl: self.class.faraday_ssl_options) do |faraday|
+ configure_health_client(faraday)
+ faraday.headers["Accept"] = "*/*"
+ end
+ end
+
+ def health_authenticated_client(cookie)
+ Faraday.new(url: base_url, ssl: self.class.faraday_ssl_options) do |faraday|
+ configure_health_client(faraday)
+ faraday.request :json
+ faraday.headers["Accept"] = "application/json"
+ faraday.headers["Cookie"] = cookie
+ end
+ end
+
+ def configure_health_client(faraday)
+ faraday.headers["User-Agent"] = random_user_agent
+ faraday.headers["Accept-Language"] = "en-US,en;q=0.9"
+ faraday.headers["Cache-Control"] = "no-cache"
+ faraday.headers["Pragma"] = "no-cache"
+ faraday.options.timeout = 5
+ faraday.options.open_timeout = 3
+ end
+
+ def read_health_cache(key)
+ Rails.cache.read(key)
+ rescue => e
+ raise HealthCacheError, e.class.name
+ end
+
+ def write_health_cache(key, value, **options)
+ Rails.cache.write(key, value, **options)
+ rescue => e
+ raise HealthCacheError, e.class.name
+ end
+
+ def write_health_cache!(key, value, **options)
+ return true if write_health_cache(key, value, **options)
+
+ raise HealthCacheError, "CacheWriteFailed"
+ end
+
+ def delete_health_cache(key)
+ Rails.cache.delete(key)
+ rescue => e
+ raise HealthCacheError, e.class.name
+ end
+
+ def publish_health_assessment(lock_token, assessment)
+ return false unless health_lock_owned?(lock_token)
+
+ write_health_cache!(HEALTH_STATUS_CACHE_KEY, assessment, expires_in: HEALTH_STATUS_RETENTION)
+ return true if health_lock_owned?(lock_token)
+
+ delete_health_cache(HEALTH_STATUS_CACHE_KEY) if read_health_cache(HEALTH_STATUS_CACHE_KEY) == assessment
+ false
+ end
+
+ def release_health_lock(lock_token)
+ return true unless health_lock_owned?(lock_token)
+
+ Rails.cache.delete(HEALTH_LOCK_CACHE_KEY)
+ true
+ rescue HealthCacheError => e
+ record_health_cache_failure(e)
+ false
+ rescue => e
+ record_health_cache_failure(HealthCacheError.new(e.class.name))
+ false
+ end
+
+ def health_lock_owned?(lock_token)
+ read_health_cache(HEALTH_LOCK_CACHE_KEY) == lock_token
+ end
+
+ def record_health_transition(previous_assessment, result)
+ previous_status = previous_assessment&.dig(:status)
+ return if previous_status == result[:status]
+
+ status = result.fetch(:status)
+ DebugLogEntry.capture(
+ category: "provider_health",
+ level: status == :healthy ? "info" : "warn",
+ message: "Yahoo Finance Provider Health Status changed to #{status}",
+ source: self.class.name,
+ provider_key: "yahoo_finance",
+ metadata: {
+ previous_state: previous_status || :unknown,
+ new_state: status,
+ health_check_stage: result[:stage],
+ exception_class: result[:exception_class],
+ http_status: result[:http_status]
+ }.compact
+ )
+ end
+
+ def record_health_cache_failure(error)
+ DebugLogEntry.capture(
+ category: "provider_health_cache",
+ level: "warn",
+ message: "Yahoo Finance Provider Health Status cache is unavailable",
+ source: self.class.name,
+ provider_key: "yahoo_finance",
+ metadata: { exception_class: error.message }
+ )
+ end
+
+ def assessment_fresh?(assessment)
+ return false unless assessment
+
+ freshness = HEALTH_STATUS_FRESHNESS[assessment[:status]]
+ freshness && assessment[:checked_at] >= freshness.ago
+ end
+
def base_url
ENV["YAHOO_FINANCE_URL"] || "https://query1.finance.yahoo.com"
end
@@ -337,7 +569,8 @@ class Provider::YahooFinance < Provider
# rank (lower = preferred). Adding a new market is a one-line hash entry.
EXCHANGE_CONFIG = {
"XNSE" => { yahoo_suffix: ".NS", default_currency: "INR", dual_list_group: :india, preference_rank: 0 },
- "XBOM" => { yahoo_suffix: ".BO", default_currency: "INR", dual_list_group: :india, preference_rank: 1 }
+ "XBOM" => { yahoo_suffix: ".BO", default_currency: "INR", dual_list_group: :india, preference_rank: 1 },
+ "XBOG" => { yahoo_suffix: ".CL", default_currency: "COP" }
}.freeze
# Yahoo Finance sometimes returns currencies in minor units (pence, cents)
@@ -631,31 +864,69 @@ class Provider::YahooFinance < Provider
def fetch_cookie_and_crumb
cache_key = "#{@cache_prefix}_auth_crumb"
cached = Rails.cache.read(cache_key)
- return cached if cached.present?
+ if cached.present?
+ return cached if valid_crumb?(cached.second)
+
+ Rails.cache.delete(cache_key)
+ end
+
+ cookie, crumb, cache_duration = request_cookie_and_crumb(auth_client)
+ result = [ cookie, crumb ]
+ Rails.cache.write(cache_key, result, expires_in: cache_duration)
+ result
+ rescue Faraday::TooManyRequestsError => e
+ raise RateLimitError.new(
+ "Yahoo Finance rate limit exceeded",
+ details: { status: e.response&.dig(:status) }
+ )
+ rescue Faraday::Error => e
+ raise AuthenticationError, "Failed to authenticate with Yahoo Finance: #{e.message}"
+ end
+
+ def request_cookie_and_crumb(authentication_client)
+ cookie_response = authentication_client.get("https://fc.yahoo.com")
+ if cookie_response.respond_to?(:status) && cookie_response.status == 429
+ raise RateLimitError.new(
+ "Yahoo Finance rate limit exceeded",
+ details: { status: cookie_response.status }
+ )
+ end
- # Step 1: Get cookie from Yahoo Finance
- cookie_response = auth_client.get("https://fc.yahoo.com")
cookie = extract_cookie(cookie_response)
cookie_max_age = extract_cookie_max_age(cookie_response)
-
raise AuthenticationError, "Failed to obtain Yahoo Finance cookie" if cookie.blank?
- # Step 2: Get crumb using the cookie
- crumb_response = auth_client.get("#{base_url}/v1/test/getcrumb") do |req|
+ crumb_response = authentication_client.get("#{base_url}/v1/test/getcrumb") do |req|
req.headers["Cookie"] = cookie
end
+ if crumb_response.status == 429
+ raise RateLimitError.new(
+ "Yahoo Finance rate limit exceeded",
+ details: { status: crumb_response.status }
+ )
+ end
+ unless crumb_response.success?
+ raise AuthenticationError.new(
+ "Failed to obtain Yahoo Finance crumb",
+ details: { status: crumb_response.status }
+ )
+ end
- crumb = crumb_response.body.strip
-
- raise AuthenticationError, "Failed to obtain Yahoo Finance crumb" if crumb.blank?
+ crumb = crumb_response.body.to_s.strip
+ unless valid_crumb?(crumb)
+ error_class = INVALID_CRUMBS.include?(crumb.downcase) ? RateLimitError : AuthenticationError
+ raise error_class.new(
+ "Failed to obtain Yahoo Finance crumb",
+ details: { status: crumb_response.status }
+ )
+ end
- # Cache the cookie/crumb pair using cookie's max-age, capped at MAX_CRUMB_CACHE_DURATION
cache_duration = [ cookie_max_age || MAX_CRUMB_CACHE_DURATION, MAX_CRUMB_CACHE_DURATION ].min
- result = [ cookie, crumb ]
- Rails.cache.write(cache_key, result, expires_in: cache_duration)
- result
- rescue Faraday::Error => e
- raise AuthenticationError, "Failed to authenticate with Yahoo Finance: #{e.message}"
+ [ cookie, crumb, cache_duration ]
+ end
+
+ def valid_crumb?(crumb)
+ crumb.present? && !INVALID_CRUMBS.include?(crumb.to_s.strip.downcase)
end
def clear_crumb_cache
@@ -835,6 +1106,8 @@ class Provider::YahooFinance < Provider
"XNSE" # National Stock Exchange of India
when "BSE", "BOM"
"XBOM" # BSE (Bombay Stock Exchange)
+ when "BVC"
+ "XBOG" # Colombian Securities Exchange
else
exchange_code.upcase
end
diff --git a/app/views/settings/hostings/_yahoo_finance_settings.html.erb b/app/views/settings/hostings/_yahoo_finance_settings.html.erb
index 1ed8044b66..2007f2a4ef 100644
--- a/app/views/settings/hostings/_yahoo_finance_settings.html.erb
+++ b/app/views/settings/hostings/_yahoo_finance_settings.html.erb
@@ -3,28 +3,20 @@
<h2 class="font-medium mb-1"><%= t(".title") %></h2>
<p class="text-secondary text-sm mb-4"><%= t(".description") %></p>
</div>
- <% if @yahoo_finance_provider&.healthy? %>
- <div class="space-y-4">
- <div class="flex items-center space-x-3">
- <div class="w-3 h-3 bg-success rounded-full"></div>
- <p class="text-sm text-secondary">
- <%= t(".status_active") %>
- </p>
- </div>
+ <% health = yahoo_finance_health_presentation(@yahoo_finance_health_status) %>
+ <div class="space-y-4">
+ <div class="flex items-center space-x-3">
+ <div class="w-3 h-3 <%= health[:status_class] %> rounded-full"></div>
+ <p class="text-sm text-secondary">
+ <%= health[:status_text] %>
+ </p>
</div>
- <% else %>
- <div class="space-y-4">
- <div class="flex items-center space-x-3">
- <div class="w-3 h-3 bg-destructive rounded-full"></div>
- <p class="text-sm text-secondary">
- <%= t(".status_inactive") %>
- </p>
- </div>
+ <% if health[:alert] %>
<%= render DS::Alert.new(
- title: t(".connection_failed"),
- message: t(".troubleshooting"),
- variant: :warning
+ title: health.dig(:alert, :title),
+ message: health.dig(:alert, :message),
+ variant: health.dig(:alert, :variant)
) %>
- </div>
- <% end %>
+ <% end %>
+ </div>
</div>
diff --git a/config/locales/views/settings/hostings/en.yml b/config/locales/views/settings/hostings/en.yml
index de372a7540..4ca4155aa5 100644
--- a/config/locales/views/settings/hostings/en.yml
+++ b/config/locales/views/settings/hostings/en.yml
@@ -144,10 +144,14 @@ en:
yahoo_finance_settings:
title: Yahoo Finance
description: Yahoo Finance provides free access to stock prices, exchange rates, and financial data without requiring an API key.
- status_active: Yahoo Finance is active and working
- status_inactive: Yahoo Finance connection failed
- connection_failed: Unable to connect to Yahoo Finance
- troubleshooting: Check your internet connection and firewall settings. Yahoo Finance may be temporarily unavailable.
+ status_healthy: Yahoo Finance is active and working.
+ status_rate_limited: Yahoo Finance is temporarily rate limiting requests.
+ rate_limited_title: Yahoo Finance rate limit reached.
+ rate_limited_message: No action is required. Sure will avoid additional health checks for 30 minutes. Price and exchange-rate operations continue independently.
+ status_unavailable: Yahoo Finance is currently unavailable.
+ unavailable_title: Could not verify Yahoo Finance.
+ unavailable_message: Yahoo Finance could not be reached or returned an unexpected response. Check your internet connection and try again later.
+ status_unknown: Yahoo Finance status is being checked.
tiingo_settings:
title: Tiingo
description: Enter the API token provided by Tiingo. Free tier supports 50 unique symbols per hour with 30+ years of historical data.
diff --git a/config/locales/views/settings/hostings/es.yml b/config/locales/views/settings/hostings/es.yml
index aff9d71f83..d0f5e82a1c 100644
--- a/config/locales/views/settings/hostings/es.yml
+++ b/config/locales/views/settings/hostings/es.yml
@@ -87,10 +87,14 @@ es:
yahoo_finance_settings:
title: Yahoo Finance
description: Yahoo Finance proporciona acceso gratuito a precios de acciones, tipos de cambio y datos financieros sin necesidad de una clave API.
- status_active: Yahoo Finance está activo y funcionando
- status_inactive: La conexión con Yahoo Finance falló
- connection_failed: No se pudo conectar con Yahoo Finance
- troubleshooting: Verifica tu conexión a internet y la configuración del firewall. Yahoo Finance puede estar temporalmente no disponible.
+ status_healthy: Yahoo Finance está activo y funcionando.
+ status_rate_limited: Yahoo Finance está limitando temporalmente las solicitudes.
+ rate_limited_title: Se alcanzó el límite de solicitudes de Yahoo Finance.
+ rate_limited_message: No es necesario realizar ninguna acción. Sure evitará comprobaciones de estado adicionales durante 30 minutos. Las operaciones de precios y tipos de cambio continuarán de forma independiente.
+ status_unavailable: Yahoo Finance no está disponible en este momento.
+ unavailable_title: No se pudo verificar Yahoo Finance.
+ unavailable_message: No se pudo contactar con Yahoo Finance o se recibió una respuesta inesperada. Comprueba tu conexión a internet e inténtalo de nuevo más tarde.
+ status_unknown: Se está comprobando el estado de Yahoo Finance.
twelve_data_settings:
api_calls_used: "%{used} / %{limit} llamadas diarias a la API utilizadas (%{percentage})"
description: Introduce la clave API proporcionada por Twelve Data
@@ -121,4 +125,4 @@ es:
auto_sync_time_description: Especifica la hora del día en la que debe ocurrir la sincronización automática.
include_pending_label: Incluir transacciones pendientes
include_pending_description: Cuando está habilitado, las transacciones pendientes (no liquidadas) se importarán y se conciliarán automáticamente cuando se confirmen. Desactívalo si tu banco proporciona datos pendientes poco fiables.
- env_configured_message: Este ajuste está desactivado porque hay una variable de entorno del proveedor (SIMPLEFIN_INCLUDE_PENDING o PLAID_INCLUDE_PENDING) definida. Elimínala para habilitar este ajuste aquí.
\ No newline at end of file
+ env_configured_message: Este ajuste está desactivado porque hay una variable de entorno del proveedor (SIMPLEFIN_INCLUDE_PENDING o PLAID_INCLUDE_PENDING) definida. Elimínala para habilitar este ajuste aquí.
diff --git a/test/controllers/settings/hostings_controller_test.rb b/test/controllers/settings/hostings_controller_test.rb
index b8892207ff..08191008c0 100644
--- a/test/controllers/settings/hostings_controller_test.rb
+++ b/test/controllers/settings/hostings_controller_test.rb
@@ -10,7 +10,7 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest
@provider = mock
Provider::Registry.stubs(:get_provider).with(:twelve_data).returns(@provider)
- @provider.stubs(:healthy?).returns(true)
+ @provider.stubs(:health_status).returns(:healthy)
Provider::Registry.stubs(:get_provider).with(:yahoo_finance).returns(@provider)
@provider.stubs(:usage).returns(provider_success_response(
OpenStruct.new(
@@ -50,6 +50,80 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest
end
end
+ test "shows Yahoo Finance rate limiting as a warning" do
+ @provider.stubs(:health_status).returns(:rate_limited)
+
+ with_env_overrides("EXCHANGE_RATE_PROVIDER" => "yahoo_finance") do
+ with_self_hosting do
+ get settings_hosting_url
+
+ assert_response :success
+ assert_select "div[class~=?]", "bg-warning/10"
+ assert_includes response.body, "Yahoo Finance is temporarily rate limiting requests."
+ assert_includes response.body, "Yahoo Finance rate limit reached."
+ assert_includes response.body, "No action is required."
+ assert_not_includes response.body, "firewall"
+ end
+ end
+ end
+
+ test "renders healthy unavailable and unknown Yahoo Finance states" do
+ @provider.stubs(:health_status).returns(:healthy, :unavailable, :unknown)
+
+ with_env_overrides("EXCHANGE_RATE_PROVIDER" => "yahoo_finance") do
+ with_self_hosting do
+ get settings_hosting_url
+ assert_includes response.body, "Yahoo Finance is active and working."
+ assert_select "div[class~=?]", "bg-success"
+
+ get settings_hosting_url
+ assert_includes response.body, "Yahoo Finance is currently unavailable."
+ assert_includes response.body, "Could not verify Yahoo Finance."
+ assert_includes response.body, "Check your internet connection and try again later."
+ assert_not_includes response.body, "firewall"
+ assert_select "div[class~=?]", "bg-destructive"
+
+ get settings_hosting_url
+ assert_includes response.body, "Yahoo Finance status is being checked."
+ assert_not_includes response.body, "Could not verify Yahoo Finance."
+ assert_not_includes response.body, "Yahoo Finance rate limit reached."
+ assert_select "div[class~=?]", "bg-surface-inset"
+ end
+ end
+ end
+
+ test "renders Spanish Yahoo Finance health guidance" do
+ @provider.stubs(:health_status).returns(:rate_limited, :unavailable, :unknown)
+
+ with_env_overrides("EXCHANGE_RATE_PROVIDER" => "yahoo_finance") do
+ with_self_hosting do
+ get settings_hosting_url(locale: :es)
+ assert_includes response.body, "Yahoo Finance está limitando temporalmente las solicitudes."
+ assert_includes response.body, "No es necesario realizar ninguna acción."
+
+ get settings_hosting_url(locale: :es)
+ assert_includes response.body, "Yahoo Finance no está disponible en este momento."
+ assert_includes response.body, "Comprueba tu conexión a internet"
+
+ get settings_hosting_url(locale: :es)
+ assert_includes response.body, "Se está comprobando el estado de Yahoo Finance."
+ end
+ end
+ end
+
+ test "falls back to English for untranslated Yahoo Finance health guidance" do
+ @provider.stubs(:health_status).returns(:rate_limited)
+
+ with_env_overrides("EXCHANGE_RATE_PROVIDER" => "yahoo_finance") do
+ with_self_hosting do
+ get settings_hosting_url(locale: :fr)
+
+ assert_includes response.body, "Yahoo Finance is temporarily rate limiting requests."
+ assert_not_includes response.body, "translation missing"
+ end
+ end
+ end
+
test "can update settings when self hosting is enabled" do
with_self_hosting do
patch settings_hosting_url, params: { setting: { twelve_data_api_key: "1234567890" } }
diff --git a/test/jobs/yahoo_finance_health_check_job_test.rb b/test/jobs/yahoo_finance_health_check_job_test.rb
new file mode 100644
index 0000000000..57c9e235e6
--- /dev/null
+++ b/test/jobs/yahoo_finance_health_check_job_test.rb
@@ -0,0 +1,11 @@
+require "test_helper"
+
+class YahooFinanceHealthCheckJobTest < ActiveJob::TestCase
+ test "refreshes Yahoo Finance health status" do
+ provider = mock
+ provider.expects(:refresh_health_status).once
+ Provider::YahooFinance.expects(:new).returns(provider)
+
+ YahooFinanceHealthCheckJob.perform_now
+ end
+end
diff --git a/test/models/provider/yahoo_finance_test.rb b/test/models/provider/yahoo_finance_test.rb
index da7ae6eb07..5d361b9163 100644
--- a/test/models/provider/yahoo_finance_test.rb
+++ b/test/models/provider/yahoo_finance_test.rb
@@ -1,49 +1,382 @@
require "test_helper"
class Provider::YahooFinanceTest < ActiveSupport::TestCase
+ include ActiveJob::TestHelper
+
setup do
@provider = Provider::YahooFinance.new
+ @cache = ActiveSupport::Cache::MemoryStore.new
+ Rails.stubs(:cache).returns(@cache)
+ DebugLogEntry.stubs(:capture)
end
# ================================
# Health Check Tests
# ================================
- test "healthy? returns true when API is working" do
- mock_response = mock
- mock_response.stubs(:body).returns('{"chart":{"result":[{"meta":{"symbol":"AAPL"}}]}}')
+ test "health_status returns cached status and schedules a stale refresh" do
+ @cache.write(
+ Provider::YahooFinance::HEALTH_STATUS_CACHE_KEY,
+ { status: :healthy, checked_at: 16.minutes.ago },
+ expires_in: Provider::YahooFinance::HEALTH_STATUS_RETENTION
+ )
+ @provider.expects(:perform_health_check).never
- @provider.stubs(:fetch_cookie_and_crumb).returns([ "test_cookie", "test_crumb" ])
- @provider.stubs(:authenticated_client).returns(mock_client = mock)
- mock_client.stubs(:get).returns(mock_response)
+ assert_enqueued_with(job: YahooFinanceHealthCheckJob) do
+ assert_equal :healthy, @provider.health_status
+ end
+ end
+
+ test "health_status returns unknown and schedules a cold refresh" do
+ @provider.expects(:perform_health_check).never
+
+ assert_enqueued_with(job: YahooFinanceHealthCheckJob) do
+ assert_equal :unknown, @provider.health_status
+ end
+ end
+
+ test "health_status does not schedule a refresh for fresh evidence" do
+ @cache.write(
+ Provider::YahooFinance::HEALTH_STATUS_CACHE_KEY,
+ { status: :healthy, checked_at: Time.current },
+ expires_in: Provider::YahooFinance::HEALTH_STATUS_RETENTION
+ )
- assert @provider.healthy?
+ assert_no_enqueued_jobs only: YahooFinanceHealthCheckJob do
+ assert_equal :healthy, @provider.health_status
+ end
end
- test "healthy? returns false when API fails" do
- @provider.stubs(:fetch_cookie_and_crumb).raises(Provider::YahooFinance::AuthenticationError.new("auth failed"))
+ test "health_status caches a healthy provider assessment" do
+ stub_successful_health_authentication
+ stub_health_chart_responses(healthy_chart_response)
- assert_not @provider.healthy?
+ assert_equal :healthy, @provider.refresh_health_status
+ assert_equal :healthy, @provider.refresh_health_status
end
- test "healthy? retries with fresh crumb on Unauthorized body response" do
- unauthorized_body = '{"chart":{"error":{"code":"Unauthorized","description":"No crumb"}}}'
- success_body = '{"chart":{"result":[{"meta":{"symbol":"AAPL"}}]}}'
+ test "health_status classifies a crumb HTTP 429 without retrying" do
+ cookie_response = health_response(
+ status: 404,
+ headers: { "set-cookie" => "A3=test-cookie; Max-Age=3600" }
+ )
+ crumb_response = health_response(status: 429, body: "secret response body")
+ auth_client = mock
+ auth_client.expects(:get).twice.returns(cookie_response, crumb_response)
+ @provider.stubs(:health_auth_client).returns(auth_client)
+ @provider.expects(:health_authenticated_client).never
- unauthorized_response = mock
- unauthorized_response.stubs(:body).returns(unauthorized_body)
+ assert_equal :rate_limited, @provider.refresh_health_status
+ end
- success_response = mock
- success_response.stubs(:body).returns(success_body)
+ test "health_status classifies a cookie HTTP 429 without continuing crumb acquisition" do
+ auth_client = mock
+ auth_client.expects(:get).once.returns(health_response(status: 429, body: "secret response body"))
+ @provider.stubs(:health_auth_client).returns(auth_client)
+ @provider.expects(:health_authenticated_client).never
- mock_client = mock
- mock_client.stubs(:get).returns(unauthorized_response, success_response)
+ assert_equal :rate_limited, @provider.refresh_health_status
+ end
- @provider.stubs(:fetch_cookie_and_crumb).returns([ "cookie1", "crumb1" ], [ "cookie2", "crumb2" ])
- @provider.stubs(:authenticated_client).returns(mock_client)
- @provider.expects(:clear_crumb_cache).once
+ test "health_status classifies a chart HTTP 429 without retrying" do
+ stub_successful_health_authentication
+ stub_health_chart_responses(health_response(status: 429, body: "secret response body"))
- assert @provider.healthy?
+ assert_equal :rate_limited, @provider.refresh_health_status
+ end
+
+ test "health_status classifies connection failures and timeouts as unavailable" do
+ [ Faraday::ConnectionFailed.new("connection failed"), Faraday::TimeoutError.new("timed out") ].each do |error|
+ provider = Provider::YahooFinance.new
+ @cache.clear
+ auth_client = mock
+ auth_client.expects(:get).once.raises(error)
+ provider.stubs(:health_auth_client).returns(auth_client)
+
+ assert_equal :unavailable, provider.refresh_health_status
+ end
+ end
+
+ test "health_status clears Unauthorized credentials without retrying immediately" do
+ auth_client = mock
+ auth_client.expects(:get).times(4).returns(
+ cookie_health_response("cookie-1"), health_response(status: 200, body: "crumb-1"),
+ cookie_health_response("cookie-2"), health_response(status: 200, body: "crumb-2")
+ )
+ @provider.stubs(:health_auth_client).returns(auth_client)
+ stub_health_chart_responses(
+ health_response(status: 200, body: '{"chart":{"error":{"code":"Unauthorized"}}}'),
+ healthy_chart_response
+ )
+
+ travel_to Time.zone.parse("2026-07-20 12:00:00") do
+ assert_equal :unavailable, @provider.refresh_health_status
+ travel 5.minutes + 1.second
+ assert_equal :healthy, @provider.refresh_health_status
+ end
+ end
+
+ test "health_status classifies malformed and empty chart responses as unavailable" do
+ stub_successful_health_authentication
+ stub_health_chart_responses(
+ health_response(status: 200, body: "not-json"),
+ health_response(status: 200, body: '{"chart":{"result":[]}}')
+ )
+
+ travel_to Time.zone.parse("2026-07-20 12:00:00") do
+ assert_equal :unavailable, @provider.refresh_health_status
+ travel 5.minutes + 1.second
+ assert_equal :unavailable, @provider.refresh_health_status
+ end
+ end
+
+ test "health_status applies status-specific freshness windows" do
+ [
+ [ healthy_chart_response, 15.minutes, :healthy ],
+ [ health_response(status: 429), 30.minutes, :rate_limited ],
+ [ health_response(status: 503), 5.minutes, :unavailable ]
+ ].each do |first_response, freshness, first_status|
+ provider = Provider::YahooFinance.new
+ @cache.clear
+ stub_successful_health_authentication(provider: provider)
+ stub_health_chart_responses(first_response, healthy_chart_response, provider: provider)
+
+ travel_to Time.zone.parse("2026-07-20 12:00:00") do
+ assert_equal first_status, provider.refresh_health_status
+ travel freshness - 1.second
+ assert_equal first_status, provider.refresh_health_status
+ travel 2.seconds
+ assert_equal :healthy, provider.refresh_health_status
+ end
+ end
+ end
+
+ test "health_status returns stale evidence while one refresh is in progress" do
+ stub_successful_health_authentication
+ started = Queue.new
+ finish = Queue.new
+ calls = 0
+ chart_client = Object.new
+ chart_client.define_singleton_method(:get) do |*_args|
+ calls += 1
+ next healthy_chart_response if calls == 1
+
+ started << true
+ finish.pop
+ health_response(status: 503)
+ end
+ chart_client.define_singleton_method(:healthy_chart_response) { health_response(status: 200, body: '{"chart":{"result":[{}]}}') }
+ chart_client.define_singleton_method(:health_response) do |status:, body: ""|
+ OpenStruct.new(status: status, body: body, headers: {}, success?: status.between?(200, 299))
+ end
+ @provider.stubs(:health_authenticated_client).returns(chart_client)
+
+ travel_to Time.zone.parse("2026-07-20 12:00:00") do
+ assert_equal :healthy, @provider.refresh_health_status
+ travel 15.minutes + 1.second
+
+ refreshing = Thread.new { @provider.refresh_health_status }
+ started.pop
+ assert_equal :healthy, Provider::YahooFinance.new.health_status
+ finish << true
+ assert_equal :unavailable, refreshing.value
+ end
+ end
+
+ test "health_status returns unknown during a cold concurrent refresh" do
+ stub_successful_health_authentication
+ started = Queue.new
+ finish = Queue.new
+ chart_client = Object.new
+ response = healthy_chart_response
+ chart_client.define_singleton_method(:get) do |*_args|
+ started << true
+ finish.pop
+ response
+ end
+ @provider.stubs(:health_authenticated_client).returns(chart_client)
+
+ refreshing = Thread.new { @provider.refresh_health_status }
+ started.pop
+ assert_equal :unknown, Provider::YahooFinance.new.health_status
+ finish << true
+ assert_equal :healthy, refreshing.value
+ end
+
+ test "health_status discards stale evidence after one hour" do
+ stub_successful_health_authentication(count: 2)
+ started = Queue.new
+ finish = Queue.new
+ calls = 0
+ first_response = healthy_chart_response
+ refresh_response = healthy_chart_response
+ chart_client = Object.new
+ chart_client.define_singleton_method(:get) do |*_args|
+ calls += 1
+ next first_response if calls == 1
+
+ started << true
+ finish.pop
+ refresh_response
+ end
+ @provider.stubs(:health_authenticated_client).returns(chart_client)
+
+ travel_to Time.zone.parse("2026-07-20 12:00:00") do
+ assert_equal :healthy, @provider.refresh_health_status
+ travel 1.hour + 1.second
+
+ refreshing = Thread.new { @provider.refresh_health_status }
+ started.pop
+ assert_equal :unknown, Provider::YahooFinance.new.health_status
+ finish << true
+ assert_equal :healthy, refreshing.value
+ end
+ end
+
+ test "health_status lock expires and an obsolete refresh cannot overwrite newer evidence" do
+ stub_successful_health_authentication
+ started = Queue.new
+ finish = Queue.new
+ obsolete_response = health_response(status: 503)
+ blocking_client = Object.new
+ blocking_client.define_singleton_method(:get) do |*_args|
+ started << true
+ finish.pop
+ obsolete_response
+ end
+ @provider.stubs(:health_authenticated_client).returns(blocking_client)
+
+ first_refresh = Thread.new { @provider.refresh_health_status }
+ started.pop
+ travel 15.seconds + 1.second do
+ replacement = Provider::YahooFinance.new
+ stub_health_chart_responses(healthy_chart_response, provider: replacement)
+ assert_equal :healthy, replacement.refresh_health_status
+ end
+ finish << true
+
+ assert_equal :healthy, first_refresh.value
+ assert_equal :healthy, Provider::YahooFinance.new.health_status
+ end
+
+ test "health_status returns unknown without contacting Yahoo when cache access fails" do
+ failing_cache = mock
+ failing_cache.expects(:read).once.raises(Redis::BaseError.new("cache details"))
+ Rails.stubs(:cache).returns(failing_cache)
+ @provider.expects(:perform_health_check).never
+ DebugLogEntry.expects(:capture).with do |attributes|
+ attributes[:category] == "provider_health_cache" &&
+ attributes[:metadata] == { exception_class: "Redis::BaseError" } &&
+ attributes.to_s.exclude?("cache details")
+ end
+
+ assert_equal :unknown, @provider.health_status
+ end
+
+ test "health_status reports a credential-cache failure as unknown" do
+ backing_cache = @cache
+ read_count = 0
+ failing_cache = Object.new
+ failing_cache.define_singleton_method(:read) do |key|
+ read_count += 1
+ raise Redis::BaseError, "cache details" if read_count == 3
+
+ backing_cache.read(key)
+ end
+ failing_cache.define_singleton_method(:write) { |key, value, **options| backing_cache.write(key, value, **options) }
+ failing_cache.define_singleton_method(:delete) { |key| backing_cache.delete(key) }
+ Rails.stubs(:cache).returns(failing_cache)
+ @provider.expects(:health_auth_client).never
+
+ diagnostics = []
+ DebugLogEntry.stubs(:capture).with { |attributes| diagnostics << attributes }
+
+ assert_equal :unknown, @provider.refresh_health_status
+ assert_equal [ "provider_health_cache" ], diagnostics.map { |entry| entry[:category] }
+ assert diagnostics.none? { |entry| entry.to_s.include?("cache details") }
+ end
+
+ test "health_status records only safe state transitions" do
+ stub_successful_health_authentication
+ stub_health_chart_responses(health_response(status: 429, body: "secret-body"))
+ DebugLogEntry.expects(:capture).with do |attributes|
+ attributes[:category] == "provider_health" &&
+ attributes[:level] == "warn" &&
+ attributes[:metadata] == {
+ previous_state: :unknown,
+ new_state: :rate_limited,
+ health_check_stage: :chart,
+ http_status: 429
+ } &&
+ attributes.to_s.exclude?("secret-body")
+ end
+
+ assert_equal :rate_limited, @provider.refresh_health_status
+ end
+
+ test "health_status omits repeated diagnostics and records healthy recovery" do
+ stub_successful_health_authentication(count: 2)
+ stub_health_chart_responses(
+ health_response(status: 429),
+ health_response(status: 429),
+ healthy_chart_response
+ )
+ events = []
+ DebugLogEntry.stubs(:capture).with { |attributes| events << attributes }
+
+ travel_to Time.zone.parse("2026-07-20 12:00:00") do
+ assert_equal :rate_limited, @provider.refresh_health_status
+ travel 30.minutes + 1.second
+ assert_equal :rate_limited, @provider.refresh_health_status
+ travel 30.minutes + 1.second
+ assert_equal :healthy, @provider.refresh_health_status
+ end
+
+ assert_equal %i[rate_limited healthy], events.map { |event| event.dig(:metadata, :new_state) }
+ assert_equal %w[warn info], events.map { |event| event[:level] }
+ end
+
+ test "healthy? is true only for healthy" do
+ %i[healthy rate_limited unavailable unknown].each do |status|
+ provider = Provider::YahooFinance.new
+ provider.stubs(:health_status).returns(status)
+
+ assert_equal status == :healthy, provider.healthy?
+ end
+ end
+
+ test "rate-limited health status does not gate or change normal price and exchange-rate operations" do
+ stub_successful_health_authentication
+ stub_health_chart_responses(health_response(status: 429))
+ assert_equal :rate_limited, @provider.refresh_health_status
+
+ @provider.stubs(:fetch_authenticated_chart).returns(
+ "chart" => {
+ "result" => [ {
+ "meta" => { "currency" => "USD", "exchangeName" => "NMS" },
+ "timestamp" => [ Time.utc(2026, 7, 17).to_i ],
+ "indicators" => { "quote" => [ { "close" => [ 210.25 ] } ] }
+ } ]
+ }
+ )
+ @provider.stubs(:throttle_request)
+
+ price_response = @provider.fetch_security_prices(
+ symbol: "AAPL",
+ exchange_operating_mic: "XNAS",
+ start_date: Date.new(2026, 7, 17),
+ end_date: Date.new(2026, 7, 17)
+ )
+ exchange_rate_response = @provider.fetch_exchange_rates(
+ from: "USD",
+ to: "EUR",
+ start_date: Date.new(2026, 7, 17),
+ end_date: Date.new(2026, 7, 17)
+ )
+
+ assert price_response.success?
+ assert exchange_rate_response.success?
+ assert_equal :rate_limited, @provider.refresh_health_status
end
# ================================
@@ -135,6 +468,51 @@ class Provider::YahooFinanceTest < ActiveSupport::TestCase
assert_equal [], response.data
end
+ test "search_securities returns canonical Colombian identity for Yahoo BVC listings" do
+ mock_response = mock
+ mock_response.stubs(:body).returns({
+ quotes: [ {
+ symbol: "CIBEST.CL",
+ longname: "Grupo Cibest S.A.",
+ exchange: "BVC",
+ exchDisp: "Colombia"
+ } ]
+ }.to_json)
+
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.stubs(:get).returns(mock_response)
+
+ response = @provider.search_securities("CIBEST.CL")
+
+ assert response.success?
+ security = response.data.sole
+ assert_equal "CIBEST.CL", security.symbol
+ assert_equal "XBOG", security.exchange_operating_mic
+ assert_equal "CO", security.country_code
+ end
+
+ test "search_securities preserves catalog countries and display-name fallback" do
+ mock_response = mock
+ mock_response.stubs(:body).returns({
+ quotes: [
+ { symbol: "AAPL", shortname: "Apple", exchange: "NMS", exchDisp: "NASDAQ" },
+ { symbol: "SAP.F", shortname: "SAP", exchange: "FRA", exchDisp: "Frankfurt" },
+ { symbol: "FALLBACK", shortname: "Fallback", exchange: "UNKNOWN", exchDisp: "Frankfurt" }
+ ]
+ }.to_json)
+
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.stubs(:get).returns(mock_response)
+
+ response = @provider.search_securities("company")
+
+ assert response.success?
+ results_by_symbol = response.data.index_by(&:symbol)
+ assert_equal "US", results_by_symbol.fetch("AAPL").country_code
+ assert_equal "DE", results_by_symbol.fetch("SAP.F").country_code
+ assert_equal "DE", results_by_symbol.fetch("FALLBACK").country_code
+ end
+
# ================================
# Security Price Tests
# ================================
@@ -148,6 +526,42 @@ class Provider::YahooFinanceTest < ActiveSupport::TestCase
assert_instance_of Provider::YahooFinance::Error, response.error
end
+ test "fetch_security_prices uses the Colombian Yahoo suffix once and COP fallback" do
+ date = Date.new(2024, 1, 15)
+ chart_response = mock
+ chart_response.stubs(:body).returns({
+ chart: {
+ result: [ {
+ meta: { exchangeName: "BVC" },
+ timestamp: [ Time.utc(2024, 1, 15).to_i ],
+ indicators: { quote: [ { close: [ 42_350.0 ] } ] }
+ } ]
+ }
+ }.to_json)
+ chart_client = mock
+ chart_client.expects(:get).with(regexp_matches(%r{/v8/finance/chart/CIBEST\.CL$})).twice.returns(chart_response)
+ @provider.stubs(:fetch_cookie_and_crumb).returns([ "cookie", "crumb" ])
+ @provider.stubs(:authenticated_client).with("cookie").returns(chart_client)
+ @provider.stubs(:throttle_request)
+
+ responses = [ "CIBEST", "CIBEST.CL" ].map do |symbol|
+ @provider.fetch_security_prices(
+ symbol: symbol,
+ exchange_operating_mic: "XBOG",
+ start_date: date,
+ end_date: date
+ )
+ end
+
+ responses.each do |response|
+ assert response.success?
+ price = response.data.sole
+ assert_equal "CIBEST.CL", price.symbol
+ assert_equal "COP", price.currency
+ assert_equal "XBOG", price.exchange_operating_mic
+ end
+ end
+
# ================================
# Caching Tests
# ================================
@@ -182,6 +596,26 @@ class Provider::YahooFinanceTest < ActiveSupport::TestCase
end
end
+ test "classifies a successful crumb response containing a rate limit body" do
+ cookie_response = mock
+ cookie_response.stubs(:headers).returns({ "set-cookie" => "A3=test-cookie; Max-Age=3600" })
+
+ crumb_response = mock
+ crumb_response.stubs(:status).returns(200)
+ crumb_response.stubs(:body).returns("Too Many Requests")
+ crumb_response.stubs(:success?).returns(true)
+
+ auth_client = mock
+ auth_client.stubs(:get).returns(cookie_response, crumb_response)
+ @provider.stubs(:auth_client).returns(auth_client)
+ @provider.stubs(:throttle_request)
+
+ result = @provider.fetch_security_info(symbol: "AAPL", exchange_operating_mic: "XNAS")
+
+ assert_not result.success?
+ assert_instance_of Provider::YahooFinance::RateLimitError, result.error
+ end
+
test "handles 401 unauthorized as authentication error" do
unauthorized_error = Faraday::UnauthorizedError.new("Unauthorized", { body: "Invalid Crumb" })
@@ -470,4 +904,47 @@ class Provider::YahooFinanceTest < ActiveSupport::TestCase
result = @provider.send(:deduplicate_dual_listings, securities)
assert_equal securities, result
end
+
+ private
+
+ def stub_successful_health_authentication(provider: @provider, count: 1)
+ responses = count.times.flat_map do |index|
+ [
+ cookie_health_response("test-cookie-#{index}"),
+ health_response(status: 200, body: "test-crumb-#{index}")
+ ]
+ end
+ auth_client = mock
+ auth_client.expects(:get).times(responses.length).returns(*responses)
+ provider.stubs(:health_auth_client).returns(auth_client)
+ end
+
+ def stub_health_chart_responses(*responses, provider: @provider)
+ chart_client = mock
+ chart_client.expects(:get).times(responses.length).returns(*responses)
+ provider.stubs(:health_authenticated_client).returns(chart_client)
+ end
+
+ def cookie_health_response(cookie)
+ health_response(
+ status: 404,
+ headers: { "set-cookie" => "A3=#{cookie}; Max-Age=3600" }
+ )
+ end
+
+ def healthy_chart_response
+ health_response(
+ status: 200,
+ body: '{"chart":{"result":[{"meta":{"symbol":"AAPL"}}]}}'
+ )
+ end
+
+ def health_response(status:, body: "", headers: {})
+ OpenStruct.new(
+ status: status,
+ body: body,
+ headers: headers,
+ success?: status.between?(200, 299)
+ )
+ end
end