Class: TestbeatRestRequest

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

Instance Method Summary collapse

Constructor Details

#initialize(node, testbeat) ⇒ TestbeatRestRequest

Returns a new instance of TestbeatRestRequest.



381
382
383
384
385
386
# File 'lib/rspec/spec_helper.rb', line 381

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)



390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
# File 'lib/rspec/spec_helper.rb', line 390

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|

    if not HTTP_VERBS.has_key?(@testbeat.method)
      raise "Testbeat can't find HTTP verb #{@testbeat.method}"
    end

    req = HTTP_VERBS[@testbeat.method].new(@testbeat.resource)
    if @testbeat.headers?
      @testbeat.headers.each {|name, value| req[name] = value }
    end
    if @testbeat.form?
      if not req.methods.include? :set_form_data
        raise "Testbeat can't set form data for HTTP verb #{@testbeat.method}"
      end
      req.set_form_data(@testbeat.form)
    end
    if @testbeat.body?
      if not req.request_body_permitted?
        raise "Testbeat can't set body for HTTP verb #{@testbeat.method}"
      end
      req.body = @testbeat.body
    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