Skip to content

Instantly share code, notes, and snippets.

@bosb
Last active March 12, 2018 15:13
Show Gist options
  • Save bosb/1304de49766d16bd56c4228f5035cd5c to your computer and use it in GitHub Desktop.
Save bosb/1304de49766d16bd56c4228f5035cd5c to your computer and use it in GitHub Desktop.
API stubbing for frontend testing: proxy method
require 'ap'
require 'json'
require 'webrick'
require 'webrick/httpproxy'
# API stubbing for frontend testing: proxy method
# Thorsten Bosbach 03/2018
if ARGV.count != 3
ap "Usage: ruby proxy.rb port request-path file"
# ruby proxy.rb 7070 /notification-center/api/nc profiles_vomp_mixed_aggregated.json
return
end
puts "port: #{ARGV[0]}\n"
puts "path: #{ARGV[1]}\n"
puts "file: #{ARGV[2]}\n"
handler = proc do |req, res|
# save original body response to file for edit
if req.path != nil
ap req.path
path = req.path.gsub '/', '_'
file = File.expand_path("../#{path}", __FILE__)
open(file, 'w') { |f|
f.puts res.body
}
end
# act on defined path
if req.path == "#{ARGV[1]}" then
file = File.expand_path("../#{ARGV[2]}", __FILE__)
http_body = File.read(file)
JSON.parse(http_body) # 'validation'
res.body = http_body
res.content_type = 'application/json'
res.status = '200'
res.header.delete('content-encoding')
res.header.delete('etag') # no caching in browser
end
end
# https://stackoverflow.com/questions/4996170/handle-the-put-method-in-webrick
class CustomWEBrickProxyServer < WEBrick::HTTPProxyServer
# prevent ERROR unsupported method `PUT'.
def do_PUT(req, res)
perform_proxy_request(req, res) do |http, path, header|
http.put(path, req.body || "", header)
end
end
# This method is not needed for PUT but I added for completeness
def do_OPTIONS(req, res)
res['allow'] = "GET,HEAD,POST,OPTIONS,CONNECT,PUT"
end
end
proxy = CustomWEBrickProxyServer.new Port: ARGV[0], ProxyContentHandler: handler, AccessLog: [], Logger: WEBrick::Log.new(nil)
trap 'INT' do proxy.shutdown end
trap 'TERM' do proxy.shutdown end
trap 'SIGINT' do proxy.shutdown end
proxy.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment