Class: TestbeatRestRequest

Inherits:
Object
  • Object
show all
Defined in:
lib/spec_helper.rb

Instance Method Summary collapse

Constructor Details

#initialize(node, testbeat) ⇒ TestbeatRestRequest

Returns a new instance of TestbeatRestRequest.



359
360
361
362
363
364
# File 'lib/spec_helper.rb', line 359

def initialize(node, testbeat)
  #@headers = {}
  @timeout = 10
  @node = node
  @testbeat = testbeat
end

Instance Method Details

#runObject

Initiate the request and return Net::HTTPResponse object, supporting response [:responseHeaderName], .body (string), .code (int), .msg (string)



368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# File 'lib/spec_helper.rb', line 368

def run
  reuse_id = @testbeat.context_block_id
  previous = $_testbeat_rest_reuse[reuse_id]
  if previous
    @response = previous
    @testbeat.logger.info{ "Request reused within #{reuse_id} responded #{@response.code} #{@response.message}" }
    return @response
  end
  # If there's no built in auth support in Net::HTTP we can check for 401 here and re-run the request with auth header
  Net::HTTP.start(@node.host,
    :use_ssl => !@testbeat.unencrypted?,
    :verify_mode => OpenSSL::SSL::VERIFY_NONE,  # Ideally verify should be enabled for non-labs hosts (anything with a FQDN including dots)
    :open_timeout => @timeout,
    :read_timeout => @timeout
    ) do |http|

    req = Net::HTTP::Get.new(@testbeat.resource)
    if @testbeat.method == 'POST'
      req = Net::HTTP::Post.new(@testbeat.resource)
      if @testbeat.form?
        req.set_form_data(@testbeat.form)
      end
      if @testbeat.body?
        req.body = @testbeat.body
      end
    end
    if @testbeat.headers?
      @testbeat.headers.each {|name, value| req[name] = value }
    end

    @response = http.request(req) # Net::HTTPResponse object

    if @response.code == "401" and @testbeat.user and not @testbeat.unauthenticated?
      u = @testbeat.user
      @testbeat.logger.info{ "Authenticating to #{@testbeat.resource} with #{u[:username]}:#{u[:password]}" }
      req.basic_auth u[:username], u[:password]
      @response = http.request(req)
    end

    @testbeat.logger.info{ "Request #{@testbeat.resource} responded #{@response.code} #{@response.message}" }
    $_testbeat_rest_reuse[reuse_id] = @response
    return @response
  end
end