Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Fix Twelve Data usage utilization rounding down to 0% (#5280)

Rajkamal7cb92b985df5
diff --git a/app/models/provider/twelve_data.rb b/app/models/provider/twelve_data.rb
index ce9bd2c779..e96fd1ff90 100644
--- a/app/models/provider/twelve_data.rb
+++ b/app/models/provider/twelve_data.rb
@@ -46,12 +46,15 @@ class Provider::TwelveData < Provider
limit = parsed.dig("plan_daily_limit")
used = parsed.dig("daily_usage")
- remaining = limit - used
+
+ unless used.is_a?(Numeric) && limit.is_a?(Numeric) && limit.positive?
+ raise Error, "Twelve Data returned no usable usage figures"
+ end
UsageData.new(
used: used,
limit: limit,
- utilization: used / limit * 100,
+ utilization: (used.to_f / limit * 100).round(1),
plan: parsed.dig("plan_category"),
)
end
diff --git a/test/models/provider/twelve_data_test.rb b/test/models/provider/twelve_data_test.rb
index f0984edc4b..198e78b7cc 100644
--- a/test/models/provider/twelve_data_test.rb
+++ b/test/models/provider/twelve_data_test.rb
@@ -5,6 +5,52 @@ class Provider::TwelveDataTest < ActiveSupport::TestCase
@provider = Provider::TwelveData.new("test_api_key")
end
+ # ================================
+ # Usage Tests
+ # ================================
+
+ def stub_usage(body)
+ mock_response = mock
+ mock_response.stubs(:body).returns(body.to_json)
+
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.stubs(:get).returns(mock_response)
+ end
+
+ test "usage reports utilization as a percentage of the daily limit" do
+ stub_usage("plan_category" => "basic", "daily_usage" => 400, "plan_daily_limit" => 800)
+
+ result = @provider.usage
+
+ assert result.success?
+ assert_equal 400, result.data.used
+ assert_equal 800, result.data.limit
+ assert_equal 50.0, result.data.utilization
+ end
+
+ test "usage keeps a fractional utilization below one percent" do
+ stub_usage("plan_category" => "basic", "daily_usage" => 1, "plan_daily_limit" => 800)
+
+ assert_equal 0.1, @provider.usage.data.utilization
+ end
+
+ test "usage fails when the daily limit is zero" do
+ stub_usage("plan_category" => "basic", "daily_usage" => 5, "plan_daily_limit" => 0)
+
+ result = @provider.usage
+
+ assert_not result.success?
+ assert_instance_of Provider::TwelveData::Error, result.error
+ end
+
+ test "usage fails when daily_usage is missing or not a number" do
+ [ {}, { "daily_usage" => "abc" } ].each do |figures|
+ stub_usage({ "plan_category" => "basic", "plan_daily_limit" => 800 }.merge(figures))
+
+ assert_not @provider.usage.success?
+ end
+ end
+
# ================================
# Rate Limit Detection Tests
# ================================