testrequest.rb 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. require 'yaml'
  2. require 'net/http'
  3. require 'rack/lint'
  4. class TestRequest
  5. NOSERIALIZE = [Method, Proc, Rack::Lint::InputWrapper]
  6. def call(env)
  7. status = env["QUERY_STRING"] =~ /secret/ ? 403 : 200
  8. env["test.postdata"] = env["rack.input"].read
  9. minienv = env.dup
  10. # This may in the future want to replace with a dummy value instead.
  11. minienv.delete_if { |k,v| NOSERIALIZE.any? { |c| v.kind_of?(c) } }
  12. body = minienv.to_yaml
  13. size = body.respond_to?(:bytesize) ? body.bytesize : body.size
  14. [status, {"Content-Type" => "text/yaml", "Content-Length" => size.to_s}, [body]]
  15. end
  16. module Helpers
  17. attr_reader :status, :response
  18. ROOT = File.expand_path(File.dirname(__FILE__) + "/..")
  19. ENV["RUBYOPT"] = "-I#{ROOT}/lib -rubygems"
  20. def root
  21. ROOT
  22. end
  23. def rackup
  24. "#{ROOT}/bin/rackup"
  25. end
  26. def GET(path, header={})
  27. Net::HTTP.start(@host, @port) { |http|
  28. user = header.delete(:user)
  29. passwd = header.delete(:passwd)
  30. get = Net::HTTP::Get.new(path, header)
  31. get.basic_auth user, passwd if user && passwd
  32. http.request(get) { |response|
  33. @status = response.code.to_i
  34. begin
  35. @response = YAML.load(response.body)
  36. rescue TypeError, ArgumentError
  37. @response = nil
  38. end
  39. }
  40. }
  41. end
  42. def POST(path, formdata={}, header={})
  43. Net::HTTP.start(@host, @port) { |http|
  44. user = header.delete(:user)
  45. passwd = header.delete(:passwd)
  46. post = Net::HTTP::Post.new(path, header)
  47. post.form_data = formdata
  48. post.basic_auth user, passwd if user && passwd
  49. http.request(post) { |response|
  50. @status = response.code.to_i
  51. @response = YAML.load(response.body)
  52. }
  53. }
  54. end
  55. end
  56. end
  57. class StreamingRequest
  58. def self.call(env)
  59. [200, {"Content-Type" => "text/plain"}, new]
  60. end
  61. def each
  62. yield "hello there!\n"
  63. sleep 5
  64. yield "that is all.\n"
  65. end
  66. end