From 2923c8805dc5ba0311a9f5de444ba8eb3206f493 Mon Sep 17 00:00:00 2001 From: Jacob Harris Date: Thu, 7 Jul 2016 12:27:47 -0400 Subject: [PATCH] SwaggerChecker falls back to a local load --- lib/apivore/swagger_checker.rb | 25 +++++++++++++++++++++---- spec/swagger_checker_spec.rb | 25 +++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 4 deletions(-) create mode 100644 spec/swagger_checker_spec.rb diff --git a/lib/apivore/swagger_checker.rb b/lib/apivore/swagger_checker.rb index aee87f1..7e08232 100644 --- a/lib/apivore/swagger_checker.rb +++ b/lib/apivore/swagger_checker.rb @@ -72,12 +72,29 @@ def load_swagger_doc! def fetch_swagger! session = ActionDispatch::Integration::Session.new(Rails.application) + body = nil + http_error = true + begin - session.get(swagger_path) - rescue - fail "Unable to perform GET request for swagger json: #{swagger_path} - #{$!}." + response_code = session.get(swagger_path) + + if response_code == 200 + http_error = false + body = session.response.body + end + rescue URI::InvalidURIError + # http_error is true end - JSON.parse(session.response.body) + + if http_error + begin + open(swagger_path) {|file| body = file.read } + rescue Errno::ENOENT + fail "Unable to perform GET request for swagger json: #{swagger_path} - #{$!}." + end + end + + JSON.parse(body) end def validate_swagger! diff --git a/spec/swagger_checker_spec.rb b/spec/swagger_checker_spec.rb new file mode 100644 index 0000000..5b70a8d --- /dev/null +++ b/spec/swagger_checker_spec.rb @@ -0,0 +1,25 @@ +require 'spec_helper' + +describe Apivore::SwaggerChecker do + describe '#instance_of' do + let(:sample_file_path) { File.join(File.dirname(__FILE__), 'data', '01_sample2.0.json') } + + it 'should be able to load the file via ActionDispatch::Integration' do + json = nil + open(sample_file_path) { |file| json = file.read } + response_double = double('response', body: json) + session_double = double('integration', response: response_double, get: 200) + allow(ActionDispatch::Integration::Session).to receive(:new).and_return(session_double) + + expect { Apivore::SwaggerChecker.instance_for("/random/url.json") }.to_not raise_error + end + + it 'should be able to load the swagger file locally' do + expect { Apivore::SwaggerChecker.instance_for(sample_file_path) }.to_not raise_error + end + + it 'should throw an exception if it is unable to load the file' do + expect { Apivore::SwaggerChecker.instance_for('not_found.json') }.to raise_error(RuntimeError) + end + end +end