2018-11-19 21:01:13 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-10-24 03:47:03 -04:00
|
|
|
# rubocop:disable Style/ClassVars
|
|
|
|
|
2017-10-23 05:19:56 -04:00
|
|
|
module Gitlab
|
|
|
|
module Testing
|
|
|
|
class RequestInspectorMiddleware
|
|
|
|
@@log_requests = Concurrent::AtomicBoolean.new(false)
|
|
|
|
@@logged_requests = Concurrent::Array.new
|
2017-10-30 16:06:08 -04:00
|
|
|
@@inject_headers = Concurrent::Hash.new
|
2017-10-23 05:19:56 -04:00
|
|
|
|
|
|
|
# Resets the current request log and starts logging requests
|
2017-10-30 16:06:08 -04:00
|
|
|
def self.log_requests!(headers = {})
|
|
|
|
@@inject_headers.replace(headers)
|
2017-10-23 05:19:56 -04:00
|
|
|
@@logged_requests.replace([])
|
|
|
|
@@log_requests.value = true
|
|
|
|
end
|
|
|
|
|
|
|
|
# Stops logging requests
|
|
|
|
def self.stop_logging!
|
|
|
|
@@log_requests.value = false
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.requests
|
|
|
|
@@logged_requests
|
|
|
|
end
|
|
|
|
|
|
|
|
def initialize(app)
|
|
|
|
@app = app
|
|
|
|
end
|
|
|
|
|
|
|
|
def call(env)
|
|
|
|
return @app.call(env) unless @@log_requests.true?
|
|
|
|
|
|
|
|
url = env['REQUEST_URI']
|
2017-10-30 16:06:08 -04:00
|
|
|
env.merge! http_headers_env(@@inject_headers) if @@inject_headers.any?
|
2017-10-23 05:19:56 -04:00
|
|
|
request_headers = env_http_headers(env)
|
|
|
|
status, headers, body = @app.call(env)
|
|
|
|
|
2018-11-19 21:01:13 -05:00
|
|
|
full_body = +''
|
2018-09-25 04:07:47 -04:00
|
|
|
body.each { |b| full_body << b }
|
|
|
|
|
2017-10-24 03:47:03 -04:00
|
|
|
request = OpenStruct.new(
|
2017-10-23 05:19:56 -04:00
|
|
|
url: url,
|
|
|
|
status_code: status,
|
|
|
|
request_headers: request_headers,
|
2018-09-25 04:07:47 -04:00
|
|
|
response_headers: headers,
|
|
|
|
body: full_body
|
2017-10-24 03:47:03 -04:00
|
|
|
)
|
|
|
|
log_request request
|
2017-10-23 05:19:56 -04:00
|
|
|
|
|
|
|
[status, headers, body]
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def env_http_headers(env)
|
2017-11-02 11:20:11 -04:00
|
|
|
Hash[*env.select { |k, v| k.start_with? 'HTTP_' }
|
|
|
|
.collect { |k, v| [k.sub(/^HTTP_/, ''), v] }
|
|
|
|
.collect { |k, v| [k.split('_').collect(&:capitalize).join('-'), v] }
|
2017-10-23 05:19:56 -04:00
|
|
|
.sort
|
|
|
|
.flatten]
|
|
|
|
end
|
|
|
|
|
2017-10-30 16:06:08 -04:00
|
|
|
def http_headers_env(headers)
|
|
|
|
Hash[*headers
|
2017-11-02 11:20:11 -04:00
|
|
|
.collect { |k, v| [k.split('-').collect(&:upcase).join('_'), v] }
|
|
|
|
.collect { |k, v| [k.prepend('HTTP_'), v] }
|
2017-10-30 16:06:08 -04:00
|
|
|
.flatten]
|
|
|
|
end
|
|
|
|
|
2017-10-24 03:47:03 -04:00
|
|
|
def log_request(response)
|
2017-10-23 05:19:56 -04:00
|
|
|
@@logged_requests.push(response)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|