Commit 9b3736c

mo khan <mo@mokhan.ca>
2014-11-11 22:00:12
raise error when invalid token is given.
1 parent b82e2b6
Changed files (2)
lib
spec
lib/urkel/connection.rb
@@ -1,4 +1,6 @@
 module Urkel
+  class InvalidAPITokenError < StandardError; end
+
   class Connection
     API_ENDPOINT="/api/v1/failures"
 
@@ -11,6 +13,17 @@ module Urkel
       response.is_a?(Net::HTTPOK)
     end
 
+    def publish!(error)
+      response = @configuration.request(request_for(error))
+      if response.is_a? Net::HTTPOK
+        true
+      elsif response.is_a? Net::HTTPUnauthorized
+        raise InvalidAPITokenError.new
+      else
+        false
+      end
+    end
+
     private
 
     def request_for(error)
spec/lib/urkel/connection_spec.rb
@@ -5,6 +5,18 @@ module Urkel
     subject { Connection.new(configuration) }
 
     describe "#publish" do
+      let(:hostname) { Socket.gethostname }
+      let(:error_hash) do  
+        { 
+          "error"=> 
+          { 
+            "message" => error.message, 
+            "hostname" => hostname, 
+            "error_type" => error.class.name, 
+            "backtrace" => error.backtrace.last
+          } 
+        } 
+      end
       let(:error) do
         begin
           1/0
@@ -15,21 +27,26 @@ module Urkel
 
       context "given proper credentials" do
         let(:configuration) { Configuration.new('http://localhost:3000', '02513a35-b875-40a1-a1fc-f2d2582bdcc5') }
-        let(:hostname) { Socket.gethostname }
 
         it 'publishes a new error' do
-          stub_request(:post, "http://localhost:3000/api/v1/failures").
-            with(body: {
-            "error"=>
-            {
-              "message" => error.message,
-              "hostname" => hostname,
-              "error_type" => error.class.name,
-              "backtrace" => error.backtrace
-            }
-          }, :headers => { 'Authorization'=>'Token token=02513a35-b875-40a1-a1fc-f2d2582bdcc5' })
+          stub_request(:post, "http://localhost:3000/api/v1/failures")
+            .with(body: error_hash, headers: { 'Authorization'=>'Token token=02513a35-b875-40a1-a1fc-f2d2582bdcc5' })
             .to_return(status: 200, body: "", headers: {})
-            expect(subject.publish(error)).to be_truthy
+          expect(subject.publish(error)).to be_truthy
+          expect(subject.publish!(error)).to be_truthy
+        end
+      end
+
+      context "when invalid credentials" do
+        let(:configuration) { Configuration.new('http://localhost:3000', 'blah') }
+
+        it 'raises a meaningful error' do
+          stub_request(:post, "http://localhost:3000/api/v1/failures")
+            .with(body: error_hash, headers: { 'Authorization' => 'Token token=blah' })
+            .to_return(status: 401, body: "HTTP Token: Access denied.", headers: {})
+
+          expect(subject.publish(error)).to be_falsey
+          expect(-> { subject.publish!(error) }).to raise_error(InvalidAPITokenError)
         end
       end
     end