Skip to content

Commit 97a9a8c

Browse files
committed
Improve error handling in package metadata fetching and ensure packages method returns an array for malformed responses
1 parent 3f8fb0c commit 97a9a8c

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

app/models/ecosystem/julia.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,9 @@ def install_command(package, version = nil)
5252

5353
def packages
5454
@packages ||= begin
55-
get_json("#{@registry_url}/app/packages/info")['packages']
55+
result = get_json("#{@registry_url}/app/packages/info")
56+
packages_data = result.is_a?(Hash) ? result['packages'] : nil
57+
packages_data.is_a?(Array) ? packages_data : []
5658
rescue
5759
[]
5860
end
@@ -71,6 +73,7 @@ def recently_updated_package_names
7173
end
7274

7375
def fetch_package_metadata(name)
76+
return nil unless packages.is_a?(Array)
7477
packages.find{|pkg| pkg['name'] == name}
7578
end
7679

test/models/ecosystem/julia_test.rb

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,4 +165,37 @@ class JuliaTest < ActiveSupport::TestCase
165165
# Should return empty array when all_package_names is empty and no existing packages
166166
assert_equal @registry.missing_package_names, []
167167
end
168+
169+
test 'fetch_package_metadata handles malformed API response' do
170+
# Test when API returns a String instead of Hash with packages array
171+
stub_request(:get, "https://juliahub.com/app/packages/info")
172+
.to_return({ status: 200, body: "invalid json response" })
173+
174+
# Should not raise "undefined method 'find' for an instance of String"
175+
assert_nothing_raised do
176+
result = @ecosystem.fetch_package_metadata('SomePackage')
177+
assert_nil result
178+
end
179+
end
180+
181+
test 'fetch_package_metadata handles missing packages key' do
182+
# Test when API returns valid JSON but without packages key
183+
stub_request(:get, "https://juliahub.com/app/packages/info")
184+
.to_return({ status: 200, body: '{"other_key": "value"}' })
185+
186+
# Should not raise "undefined method 'find' for an instance of String"
187+
assert_nothing_raised do
188+
result = @ecosystem.fetch_package_metadata('SomePackage')
189+
assert_nil result
190+
end
191+
end
192+
193+
test 'packages method returns array even with malformed response' do
194+
stub_request(:get, "https://juliahub.com/app/packages/info")
195+
.to_return({ status: 200, body: "not json" })
196+
197+
packages = @ecosystem.packages
198+
assert_kind_of Array, packages
199+
assert_equal packages, []
200+
end
168201
end

0 commit comments

Comments
 (0)