Skip to content

Commit

Permalink
Merge 905d3a8 into a9b2dec
Browse files Browse the repository at this point in the history
  • Loading branch information
dgb committed Oct 3, 2018
2 parents a9b2dec + 905d3a8 commit 17a10a2
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 7 deletions.
22 changes: 19 additions & 3 deletions lib/yt/http_request.rb
Expand Up @@ -121,9 +121,12 @@ def set_request_headers!(request)

# Run the request and memoize the response or the server error received.
def response
@response ||= Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
puts as_curl if Yt.configuration.developing?
http.request http_request
instrument do |data|
@response ||= Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
puts as_curl if Yt.configuration.developing?
http.request http_request
end
data[:response] = @response
end
rescue *server_errors => e
raise Yt::ConnectionError, e.message
Expand All @@ -149,5 +152,18 @@ def parse_response!
def error_message
@error_message.call response.body
end

def instrument(&block)
data = {
request: http_request,
method: http_request.method,
request_uri: uri
}
if defined?(ActiveSupport::Notifications)
ActiveSupport::Notifications.instrument 'request.yt', data, &block
else
block.call(data)
end
end
end
end
29 changes: 25 additions & 4 deletions spec/http_request_spec.rb
Expand Up @@ -2,16 +2,37 @@

describe 'Yt::HTTPRequest#run' do
context 'given a valid GET request to a YouTube JSON API' do
path = '/discovery/v1/apis/youtube/v3/rest'
headers = {'User-Agent' => 'Yt::HTTPRequest'}
params = {verbose: 1}
request = Yt::HTTPRequest.new path: path, headers: headers, params: params
let(:path) { '/discovery/v1/apis/youtube/v3/rest' }
let(:headers) { {'User-Agent' => 'Yt::HTTPRequest'} }
let(:params) { {verbose: 1} }
let(:request) { Yt::HTTPRequest.new path: path, headers: headers, params: params }

it 'returns the HTTP response with the JSON-parsed body' do
response = request.run
expect(response).to be_a Net::HTTPOK
expect(response.body).to be_a Hash
end

it 'instruments when ActiveSupport::Notifications are around' do
fake_notifier_klass = Class.new do
attr_reader :label, :data
def instrument(label, data)
@label = label
@data = data
yield data
end
end
fake_notifier = fake_notifier_klass.new
stub_const("ActiveSupport::Notifications", fake_notifier)

response = request.run

expect(fake_notifier.label).to eql('request.yt')
expect(fake_notifier.data[:method]).to eql('GET')
expect(fake_notifier.data[:request].path).to eql('/discovery/v1/apis/youtube/v3/rest?verbose=1')
expect(fake_notifier.data[:request_uri].to_s).to eql('https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest?verbose=1')
expect(fake_notifier.data[:response].code).to eql("200")
end
end

context 'when developing' do
Expand Down

0 comments on commit 17a10a2

Please sign in to comment.