Skip to content

Instantly share code, notes, and snippets.

@glennpratt
Created August 3, 2017 07:25
Show Gist options
  • Save glennpratt/51de98e74c3b71947f87e52eb0b3daca to your computer and use it in GitHub Desktop.
Save glennpratt/51de98e74c3b71947f87e52eb0b3daca to your computer and use it in GitHub Desktop.
TestHTTPServer
require 'thread'
require 'webrick'
class TestHTTPServer
class Servlet < WEBrick::HTTPServlet::AbstractServlet
def initialize(server, requests)
@requests = requests
super
end
def do_POST(request, resp) # rubocop:disable MethodName
# Make the body real, it will be nil if we don't load it
# before the request closes.
request.body
# warn request.inspect
@requests.push(request)
end
end
def initialize(requests)
@requests = requests
@server = WEBrick::HTTPServer.new(
BindAddress: '127.0.0.1', # IPv4 only.
Port: 0, # Let the kernel pick.
AccessLog: [],
Logger: WEBrick::Log.new("/dev/null")
)
@server.mount('/', Servlet, @requests)
end
def run
# @TODO Try to wait for running...
@thread = Thread.new do
@server.start
end
end
def url
addr = @server.listeners.first.addr
url = "http://#{addr[2]}:#{addr[1]}"
url
end
def stop
@server.shutdown
ensure
@thread.kill if @thread
end
# Array of all requests received so far. Requests are removed from a queue
# and will not be included in subsequent calls.
def pop_requests_received
Array.new(@requests.size) { @requests.pop }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment