Skip to content

Instantly share code, notes, and snippets.

@technoweenie
Created March 16, 2009 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save technoweenie/79664 to your computer and use it in GitHub Desktop.
Save technoweenie/79664 to your computer and use it in GitHub Desktop.
class Test::Unit::TestCase
def upload_it(path, file, params, opts)
@request = Rack::MockRequest.new(Sinatra::Application)
input = FiveRuns::Multipart::FileUpload.new(file, params, opts)
opts[:input] ||= input.to_s
opts['CONTENT_TYPE'] = input.content_type
opts['CONTENT_LENGTH'] = opts[:input].length
@response = @request.request("POST", path, opts)
end
end
# http://www.mikeperham.com/2009/01/21/testing-multipart-upload-with-sinatra/
module FiveRuns
module Multipart
class FileUpload
BOUNDARY_ROOT = 'B0UND~F0R~UPL0AD'
attr_reader :file, :params, :rack_opts
def initialize(file, params={}, rack_opts = {})
@to_s = nil
@file = file
@params = params
@rack_opts = rack_opts
rack_opts[:content_type] ||= 'application/octet-stream'
rack_opts[:filename] ||= 'uploaded.file'
end
def content_type
%(multipart/form-data, boundary="#{boundary}")
end
def to_s
@to_s ||= %(#{parts}\r\n#{separator}--)
end
########
# private
########
def boundary
"#{BOUNDARY_ROOT}*#{nonce}"
end
def parts
params.merge(:photo => file).map do |name, value|
[
separator,
headers_for(name, value)
].flatten.join(crlf) + crlf + crlf + content_of(value)
end.flatten.join(crlf)
end
def separator
%(--#{boundary})
end
def crlf
@crlf ||= "\r\n"
end
def headers_for(name, value)
if value.respond_to?(:read)
[
%(Content-Disposition: form-data; name="#{name}"; filename="#{rack_opts.delete(:filename)}"),
%(Content-Transfer-Encoding: binary),
%(Content-Type: #{rack_opts.delete(:content_type)})
]
else
[ %(Content-Disposition: form-data; name="#{name}") ]
end
end
def nonce( time = Time.now.utc )
@nonce ||= (time.to_f * 1000).to_i
end
def content_of(value)
value.respond_to?(:read) ? value.read : value.to_s
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment