From 1c4373857f24df945290cff32f6b244c5cad4a4d Mon Sep 17 00:00:00 2001
From: Alex Reisner <alex@alexreisner.com>
Date: Fri, 21 Dec 2012 15:29:38 -0500
Subject: [PATCH] Raise InvalidApiKey exception for Bing.

---
 lib/geocoder/lookups/bing.rb   | 6 ++++--
 test/fixtures/bing_invalid_key | 1 +
 test/lookup_test.rb            | 2 +-
 3 files changed, 6 insertions(+), 3 deletions(-)
 create mode 100644 test/fixtures/bing_invalid_key

diff --git a/lib/geocoder/lookups/bing.rb b/lib/geocoder/lookups/bing.rb
index c4ce5453..125dcdcf 100644
--- a/lib/geocoder/lookups/bing.rb
+++ b/lib/geocoder/lookups/bing.rb
@@ -21,12 +21,14 @@ module Geocoder::Lookup
     def results(query)
       return [] unless doc = fetch_data(query)
 
-      if doc['statusDescription'] == "OK"
+      if doc['statusCode'] == 200
         return doc['resourceSets'].first['estimatedTotal'] > 0 ? doc['resourceSets'].first['resources'] : []
+      elsif doc['statusCode'] == 401 and doc["authenticationResultCode"] == "InvalidCredentials"
+        raise_error(Geocoder::InvalidApiKey) || warn("Invalid Bing API key.")
       else
         warn "Bing Geocoding API error: #{doc['statusCode']} (#{doc['statusDescription']})."
-        return []
       end
+      return []
     end
 
     def query_url_params(query)
diff --git a/test/fixtures/bing_invalid_key b/test/fixtures/bing_invalid_key
new file mode 100644
index 00000000..d34e1e93
--- /dev/null
+++ b/test/fixtures/bing_invalid_key
@@ -0,0 +1 @@
+{"authenticationResultCode":"InvalidCredentials","brandLogoUri":"http:\\/\\/dev.virtualearth.net\\/Branding\\/logo_powered_by.png","copyright":"Copyright \xC2\xA9 2012 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.","errorDetails":["Access was denied. You may have entered your credentials incorrectly, or you might not have access to the requested resource or operation."],"resourceSets":[],"statusCode":401,"statusDescription":"Unauthorized","traceId":"5c539f6e70c44b2e858741b6c932318e|EWRM001670|02.00.83.1900|"}
diff --git a/test/lookup_test.rb b/test/lookup_test.rb
index 6ad02c52..190f638a 100644
--- a/test/lookup_test.rb
+++ b/test/lookup_test.rb
@@ -23,7 +23,7 @@ class LookupTest < Test::Unit::TestCase
   def test_raises_exception_on_invalid_key
     Geocoder.configure(:always_raise => [Geocoder::InvalidApiKey])
     #Geocoder::Lookup.all_services_except_test.each do |l|
-    [:yahoo, :yandex, :maxmind].each do |l|
+    [:bing, :yahoo, :yandex, :maxmind].each do |l|
       lookup = Geocoder::Lookup.get(l)
       assert_raises Geocoder::InvalidApiKey do
         lookup.send(:results, Geocoder::Query.new("invalid key"))
-- 
GitLab