pax_global_header00006660000000000000000000000064125554172510014521gustar00rootroot0000000000000052 comment=0ba0eda72d0ffd465206b3a6cfb93fc1e0b61ba8 ruby-multipart-post-2.0.0/000077500000000000000000000000001255541725100155035ustar00rootroot00000000000000ruby-multipart-post-2.0.0/.gitignore000066400000000000000000000000451255541725100174720ustar00rootroot00000000000000doc pkg *~ *.swo *.swp /Gemfile.lock ruby-multipart-post-2.0.0/.travis.yml000066400000000000000000000001021255541725100176050ustar00rootroot00000000000000rvm: - 1.9.3 - 2.0.0 - jruby branches: only: - master ruby-multipart-post-2.0.0/Gemfile000066400000000000000000000002611255541725100167750ustar00rootroot00000000000000source 'https://rubygems.org' gemspec platforms :mri_19 do gem 'ruby-debug19' end platforms :mri_18 do gem 'ruby-debug' end group :development, :test do gem 'rake' end ruby-multipart-post-2.0.0/History.txt000066400000000000000000000030741255541725100177110ustar00rootroot00000000000000=== 2.0.0 / 2013-12-21 - Drop Ruby 1.8 compatibility - GH #21: Fix FilePart length calculation for Ruby 1.9 when filename contains multibyte characters (hexfet) - GH #20: Ensure upload responds to both #content_type and #original_filename (Steven Davidovitz) - GH #31: Support setting headers on any part of the request (Socrates Vicente) - GH #30: Support array values for params (Gustav Ernberg) - GH #32: Fix respond_to? signature (Leo Cassarani) - GH #33: Update README to markdown (Jagtesh Chadha) - GH #35: Improved handling of array-type parameters (Steffen Grunwald) === 1.2.0 / 2013-02-25 - #25: Ruby 2 compatibility (thanks mislav) === 1.1.5 / 2012-02-12 - Fix length/bytesize of parts in 1.9 (#7, #14) (Jason Moore) - Allow CompositeIO objects to be re-read by rewinding, like other IO objects. (Luke Redpath) === 1.1.4 / 2011-11-23 - Non-functional changes in release (switch to Bundler gem tasks) === 1.1.3 / 2011-07-25 - More configurable header specification for parts (Gerrit Riessen) === 1.1.2 / 2011-05-24 - Fix CRLF file part miscalculation (Johannes Wagener) - Fix Epilogue CRLF issue (suggestion by Neil Spring) === 1.1.1 / 2011-05-13 - GH# 9: Fixed Ruby 1.9.2 StringIO bug (thanks Alex Koppel) === 1.1.0 / 2011-01-11 - API CHANGE: UploadIO.convert! removed in favor of UploadIO.new (Jeff Hodges) === 1.0.1 / 2010-04-27 - Doc updates, make gemspec based on more modern Rubygems === 1.0 / 2009-02-12 - Many fixes from mlooney, seems to work now. Putting the 0.9 seal of approval on it. === 0.1 / 2008-08-12 * 1 major enhancement * Birthday! ruby-multipart-post-2.0.0/Manifest.txt000066400000000000000000000002651255541725100200150ustar00rootroot00000000000000lib/composite_io.rb lib/multipartable.rb lib/parts.rb lib/net/http/post/multipart.rb Manifest.txt Rakefile README.txt test/test_composite_io.rb test/net/http/post/test_multipart.rb ruby-multipart-post-2.0.0/README.md000066400000000000000000000051111255541725100167600ustar00rootroot00000000000000## multipart-post * http://github.com/nicksieger/multipart-post ![build status](https://travis-ci.org/nicksieger/multipart-post.png) #### DESCRIPTION: Adds a streamy multipart form post capability to Net::HTTP. Also supports other methods besides POST. #### FEATURES/PROBLEMS: * Appears to actually work. A good feature to have. * Encapsulates posting of file/binary parts and name/value parameter parts, similar to most browsers' file upload forms. * Provides an UploadIO helper class to prepare IO objects for inclusion in the params hash of the multipart post object. #### SYNOPSIS: require 'net/http/post/multipart' url = URI.parse('http://www.example.com/upload') File.open("./image.jpg") do |jpg| req = Net::HTTP::Post::Multipart.new url.path, "file" => UploadIO.new(jpg, "image/jpeg", "image.jpg") res = Net::HTTP.start(url.host, url.port) do |http| http.request(req) end end To post multiple files or attachments, simply include multiple parameters with UploadIO values: require 'net/http/post/multipart' url = URI.parse('http://www.example.com/upload') req = Net::HTTP::Post::Multipart.new url.path, "file1" => UploadIO.new(File.new("./image.jpg"), "image/jpeg", "image.jpg"), "file2" => UploadIO.new(File.new("./image2.jpg"), "image/jpeg", "image2.jpg") res = Net::HTTP.start(url.host, url.port) do |http| http.request(req) end #### REQUIREMENTS: None #### INSTALL: gem install multipart-post #### LICENSE: (The MIT License) Copyright (c) 2007-2013 Nick Sieger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ruby-multipart-post-2.0.0/Rakefile000066400000000000000000000002541255541725100171510ustar00rootroot00000000000000require "bundler/gem_tasks" task :default => :test require 'rake/testtask' Rake::TestTask.new do |t| t.libs << "test" t.test_files = FileList['test/**/test*.rb'] end ruby-multipart-post-2.0.0/lib/000077500000000000000000000000001255541725100162515ustar00rootroot00000000000000ruby-multipart-post-2.0.0/lib/composite_io.rb000066400000000000000000000062361255541725100212760ustar00rootroot00000000000000#-- # Copyright (c) 2007-2012 Nick Sieger. # See the file README.txt included with the distribution for # software license details. #++ # Concatenate together multiple IO objects into a single, composite IO object # for purposes of reading as a single stream. # # Usage: # # crio = CompositeReadIO.new(StringIO.new('one'), StringIO.new('two'), StringIO.new('three')) # puts crio.read # => "onetwothree" # class CompositeReadIO # Create a new composite-read IO from the arguments, all of which should # respond to #read in a manner consistent with IO. def initialize(*ios) @ios = ios.flatten @index = 0 end # Read from IOs in order until `length` bytes have been received. def read(length = nil, outbuf = nil) got_result = false outbuf = outbuf ? outbuf.replace("") : "" while io = current_io if result = io.read(length) got_result ||= !result.nil? result.force_encoding("BINARY") if result.respond_to?(:force_encoding) outbuf << result length -= result.length if length break if length == 0 end advance_io end (!got_result && length) ? nil : outbuf end def rewind @ios.each { |io| io.rewind } @index = 0 end private def current_io @ios[@index] end def advance_io @index += 1 end end # Convenience methods for dealing with files and IO that are to be uploaded. class UploadIO # Create an upload IO suitable for including in the params hash of a # Net::HTTP::Post::Multipart. # # Can take two forms. The first accepts a filename and content type, and # opens the file for reading (to be closed by finalizer). # # The second accepts an already-open IO, but also requires a third argument, # the filename from which it was opened (particularly useful/recommended if # uploading directly from a form in a framework, which often save the file to # an arbitrarily named RackMultipart file in /tmp). # # Usage: # # UploadIO.new("file.txt", "text/plain") # UploadIO.new(file_io, "text/plain", "file.txt") # attr_reader :content_type, :original_filename, :local_path, :io, :opts def initialize(filename_or_io, content_type, filename = nil, opts = {}) io = filename_or_io local_path = "" if io.respond_to? :read # in Ruby 1.9.2, StringIOs no longer respond to path # (since they respond to :length, so we don't need their local path, see parts.rb:41) local_path = filename_or_io.respond_to?(:path) ? filename_or_io.path : "local.path" else io = File.open(filename_or_io) local_path = filename_or_io end filename ||= local_path @content_type = content_type @original_filename = File.basename(filename) @local_path = local_path @io = io @opts = opts end def self.convert!(io, content_type, original_filename, local_path) raise ArgumentError, "convert! has been removed. You must now wrap IOs using:\nUploadIO.new(filename_or_io, content_type, filename=nil)\nPlease update your code." end def method_missing(*args) @io.send(*args) end def respond_to?(meth, include_all = false) @io.respond_to?(meth, include_all) || super(meth, include_all) end end ruby-multipart-post-2.0.0/lib/multipart_post.rb000066400000000000000000000002661255541725100216700ustar00rootroot00000000000000#-- # Copyright (c) 2007-2013 Nick Sieger. # See the file README.txt included with the distribution for # software license details. #++ module MultipartPost VERSION = "2.0.0" end ruby-multipart-post-2.0.0/lib/multipartable.rb000066400000000000000000000020461255541725100214450ustar00rootroot00000000000000#-- # Copyright (c) 2007-2013 Nick Sieger. # See the file README.txt included with the distribution for # software license details. #++ require 'parts' module Multipartable DEFAULT_BOUNDARY = "-----------RubyMultipartPost" def initialize(path, params, headers={}, boundary = DEFAULT_BOUNDARY) headers = headers.clone # don't want to modify the original variable parts_headers = headers.delete(:parts) || {} super(path, headers) parts = params.map do |k,v| case v when Array v.map {|item| Parts::Part.new(boundary, k, item, parts_headers[k]) } else Parts::Part.new(boundary, k, v, parts_headers[k]) end end.flatten parts << Parts::EpiloguePart.new(boundary) ios = parts.map {|p| p.to_io } self.set_content_type(headers["Content-Type"] || "multipart/form-data", { "boundary" => boundary }) self.content_length = parts.inject(0) {|sum,i| sum + i.length } self.body_stream = CompositeReadIO.new(*ios) end end ruby-multipart-post-2.0.0/lib/net/000077500000000000000000000000001255541725100170375ustar00rootroot00000000000000ruby-multipart-post-2.0.0/lib/net/http/000077500000000000000000000000001255541725100200165ustar00rootroot00000000000000ruby-multipart-post-2.0.0/lib/net/http/post/000077500000000000000000000000001255541725100210035ustar00rootroot00000000000000ruby-multipart-post-2.0.0/lib/net/http/post/multipart.rb000066400000000000000000000007601255541725100233540ustar00rootroot00000000000000#-- # Copyright (c) 2007-2012 Nick Sieger. # See the file README.txt included with the distribution for # software license details. #++ require 'net/http' require 'stringio' require 'cgi' require 'composite_io' require 'multipartable' require 'parts' module Net #:nodoc: class HTTP #:nodoc: class Put class Multipart < Put include Multipartable end end class Post #:nodoc: class Multipart < Post include Multipartable end end end end ruby-multipart-post-2.0.0/lib/parts.rb000066400000000000000000000053631255541725100177360ustar00rootroot00000000000000#-- # Copyright (c) 2007-2013 Nick Sieger. # See the file README.txt included with the distribution for # software license details. #++ module Parts module Part #:nodoc: def self.new(boundary, name, value, headers = {}) headers ||= {} # avoid nil values if file?(value) FilePart.new(boundary, name, value, headers) else ParamPart.new(boundary, name, value, headers) end end def self.file?(value) value.respond_to?(:content_type) && value.respond_to?(:original_filename) end def length @part.length end def to_io @io end end class ParamPart include Part def initialize(boundary, name, value, headers = {}) @part = build_part(boundary, name, value, headers) @io = StringIO.new(@part) end def length @part.bytesize end def build_part(boundary, name, value, headers = {}) part = '' part << "--#{boundary}\r\n" part << "Content-Disposition: form-data; name=\"#{name.to_s}\"\r\n" part << "Content-Type: #{headers["Content-Type"]}\r\n" if headers["Content-Type"] part << "\r\n" part << "#{value}\r\n" end end # Represents a part to be filled from file IO. class FilePart include Part attr_reader :length def initialize(boundary, name, io, headers = {}) file_length = io.respond_to?(:length) ? io.length : File.size(io.local_path) @head = build_head(boundary, name, io.original_filename, io.content_type, file_length, io.respond_to?(:opts) ? io.opts.merge(headers) : headers) @foot = "\r\n" @length = @head.bytesize + file_length + @foot.length @io = CompositeReadIO.new(StringIO.new(@head), io, StringIO.new(@foot)) end def build_head(boundary, name, filename, type, content_len, opts = {}, headers = {}) trans_encoding = opts["Content-Transfer-Encoding"] || "binary" content_disposition = opts["Content-Disposition"] || "form-data" part = '' part << "--#{boundary}\r\n" part << "Content-Disposition: #{content_disposition}; name=\"#{name.to_s}\"; filename=\"#{filename}\"\r\n" part << "Content-Length: #{content_len}\r\n" if content_id = opts["Content-ID"] part << "Content-ID: #{content_id}\r\n" end if headers["Content-Type"] != nil part << "Content-Type: " + headers["Content-Type"] + "\r\n" else part << "Content-Type: #{type}\r\n" end part << "Content-Transfer-Encoding: #{trans_encoding}\r\n" part << "\r\n" end end # Represents the epilogue or closing boundary. class EpiloguePart include Part def initialize(boundary) @part = "--#{boundary}--\r\n\r\n" @io = StringIO.new(@part) end end end ruby-multipart-post-2.0.0/metadata.yml000066400000000000000000000033061255541725100200100ustar00rootroot00000000000000--- !ruby/object:Gem::Specification name: multipart-post version: !ruby/object:Gem::Version version: 2.0.0 prerelease: platform: ruby authors: - Nick Sieger autorequire: bindir: bin cert_chain: [] date: 2013-12-21 00:00:00.000000000 Z dependencies: [] description: ! 'Use with Net::HTTP to do multipart form posts. IO values that have #content_type, #original_filename, and #local_path will be posted as a binary file.' email: - nick@nicksieger.com executables: [] extensions: [] extra_rdoc_files: [] files: - .gitignore - .travis.yml - Gemfile - History.txt - Manifest.txt - README.md - Rakefile - lib/composite_io.rb - lib/multipart_post.rb - lib/multipartable.rb - lib/net/http/post/multipart.rb - lib/parts.rb - multipart-post.gemspec - test/multibyte.txt - test/net/http/post/test_multipart.rb - test/test_composite_io.rb - test/test_parts.rb homepage: https://github.com/nicksieger/multipart-post licenses: - MIT post_install_message: rdoc_options: - --main - README.md - -SHN - -f - darkfish require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' segments: - 0 hash: 3851181222699685043 required_rubygems_version: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' segments: - 0 hash: 3851181222699685043 requirements: [] rubyforge_project: caldersphere rubygems_version: 1.8.23 signing_key: specification_version: 3 summary: A multipart form post accessory for Net::HTTP. test_files: - test/multibyte.txt - test/net/http/post/test_multipart.rb - test/test_composite_io.rb - test/test_parts.rb ruby-multipart-post-2.0.0/multipart-post.gemspec000066400000000000000000000016751255541725100220650ustar00rootroot00000000000000# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "multipart_post" Gem::Specification.new do |s| s.name = "multipart-post" s.version = MultipartPost::VERSION s.authors = ["Nick Sieger"] s.email = ["nick@nicksieger.com"] s.homepage = "https://github.com/nicksieger/multipart-post" s.summary = %q{A multipart form post accessory for Net::HTTP.} s.license = "MIT" s.description = %q{Use with Net::HTTP to do multipart form posts. IO values that have #content_type, #original_filename, and #local_path will be posted as a binary file.} s.rubyforge_project = "caldersphere" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.rdoc_options = ["--main", "README.md", "-SHN", "-f", "darkfish"] s.require_paths = ["lib"] end ruby-multipart-post-2.0.0/test/000077500000000000000000000000001255541725100164625ustar00rootroot00000000000000ruby-multipart-post-2.0.0/test/multibyte.txt000066400000000000000000000000151255541725100212350ustar00rootroot00000000000000ファイル ruby-multipart-post-2.0.0/test/net/000077500000000000000000000000001255541725100172505ustar00rootroot00000000000000ruby-multipart-post-2.0.0/test/net/http/000077500000000000000000000000001255541725100202275ustar00rootroot00000000000000ruby-multipart-post-2.0.0/test/net/http/post/000077500000000000000000000000001255541725100212145ustar00rootroot00000000000000ruby-multipart-post-2.0.0/test/net/http/post/test_multipart.rb000066400000000000000000000074111255541725100246240ustar00rootroot00000000000000#-- # Copyright (c) 2007-2013 Nick Sieger. # See the file README.txt included with the distribution for # software license details. #++ require 'net/http/post/multipart' require 'test/unit' class Net::HTTP::Post::MultiPartTest < Test::Unit::TestCase TEMP_FILE = "temp.txt" HTTPPost = Struct.new("HTTPPost", :content_length, :body_stream, :content_type) HTTPPost.module_eval do def set_content_type(type, params = {}) self.content_type = type + params.map{|k,v|"; #{k}=#{v}"}.join('') end end def teardown File.delete(TEMP_FILE) rescue nil end def test_form_multipart_body File.open(TEMP_FILE, "w") {|f| f << "1234567890"} @io = File.open(TEMP_FILE) @io = UploadIO.new @io, "text/plain", TEMP_FILE assert_results Net::HTTP::Post::Multipart.new("/foo/bar", :foo => 'bar', :file => @io) end def test_form_multipart_body_put File.open(TEMP_FILE, "w") {|f| f << "1234567890"} @io = File.open(TEMP_FILE) @io = UploadIO.new @io, "text/plain", TEMP_FILE assert_results Net::HTTP::Put::Multipart.new("/foo/bar", :foo => 'bar', :file => @io) end def test_form_multipart_body_with_stringio @io = StringIO.new("1234567890") @io = UploadIO.new @io, "text/plain", TEMP_FILE assert_results Net::HTTP::Post::Multipart.new("/foo/bar", :foo => 'bar', :file => @io) end def test_form_multiparty_body_with_parts_headers @io = StringIO.new("1234567890") @io = UploadIO.new @io, "text/plain", TEMP_FILE parts = { :text => 'bar', :file => @io } headers = { :parts => { :text => { "Content-Type" => "part/type" }, :file => { "Content-Transfer-Encoding" => "part-encoding" } } } request = Net::HTTP::Post::Multipart.new("/foo/bar", parts, headers) assert_results request assert_additional_headers_added(request, headers[:parts]) end def test_form_multipart_body_with_array_value File.open(TEMP_FILE, "w") {|f| f << "1234567890"} @io = File.open(TEMP_FILE) @io = UploadIO.new @io, "text/plain", TEMP_FILE params = {:foo => ['bar', 'quux'], :file => @io} headers = { :parts => { :foo => { "Content-Type" => "application/json; charset=UTF-8" } } } post = Net::HTTP::Post::Multipart.new("/foo/bar", params, headers, Net::HTTP::Post::Multipart::DEFAULT_BOUNDARY) assert post.content_length && post.content_length > 0 assert post.body_stream body = post.body_stream.read assert_equal 2, body.lines.grep(/name="foo"/).length assert body =~ /Content-Type: application\/json; charset=UTF-8/, body end def test_form_multipart_body_with_arrayparam File.open(TEMP_FILE, "w") {|f| f << "1234567890"} @io = File.open(TEMP_FILE) @io = UploadIO.new @io, "text/plain", TEMP_FILE assert_results Net::HTTP::Post::Multipart.new("/foo/bar", :multivalueParam => ['bar','bah'], :file => @io) end def assert_results(post) assert post.content_length && post.content_length > 0 assert post.body_stream assert_equal "multipart/form-data; boundary=#{Multipartable::DEFAULT_BOUNDARY}", post['content-type'] body = post.body_stream.read boundary_regex = Regexp.quote Multipartable::DEFAULT_BOUNDARY assert body =~ /1234567890/ # ensure there is at least one boundary assert body =~ /^--#{boundary_regex}\r\n/ # ensure there is an epilogue assert body =~ /^--#{boundary_regex}--\r\n/ assert body =~ /text\/plain/ if (body =~ /multivalueParam/) assert_equal 2, body.scan(/^.*multivalueParam.*$/).size end end def assert_additional_headers_added(post, parts_headers) post.body_stream.rewind body = post.body_stream.read parts_headers.each do |part, headers| headers.each do |k,v| assert body =~ /#{k}: #{v}/ end end end end ruby-multipart-post-2.0.0/test/test_composite_io.rb000066400000000000000000000055141255541725100225440ustar00rootroot00000000000000#-- # Copyright (c) 2007-2013 Nick Sieger. # See the file README.txt included with the distribution for # software license details. #++ require 'composite_io' require 'stringio' require 'test/unit' require 'timeout' class CompositeReadIOTest < Test::Unit::TestCase def setup @io = CompositeReadIO.new(CompositeReadIO.new(StringIO.new('the '), StringIO.new('quick ')), StringIO.new('brown '), StringIO.new('fox')) end def test_full_read_from_several_ios assert_equal 'the quick brown fox', @io.read end unless RUBY_VERSION < '1.9' def test_read_from_multibyte utf8 = File.open(File.dirname(__FILE__)+'/multibyte.txt') binary = StringIO.new("\x86") @io = CompositeReadIO.new(binary,utf8) expect = "\x86\xE3\x83\x95\xE3\x82\xA1\xE3\x82\xA4\xE3\x83\xAB\n" expect.force_encoding('BINARY') if expect.respond_to?(:force_encoding) assert_equal expect, @io.read end end def test_partial_read assert_equal 'the quick', @io.read(9) end def test_partial_read_to_boundary assert_equal 'the quick ', @io.read(10) end def test_read_with_size_larger_than_available assert_equal 'the quick brown fox', @io.read(32) end def test_read_into_buffer buf = '' @io.read(nil, buf) assert_equal 'the quick brown fox', buf end def test_multiple_reads assert_equal 'the ', @io.read(4) assert_equal 'quic', @io.read(4) assert_equal 'k br', @io.read(4) assert_equal 'own ', @io.read(4) assert_equal 'fox', @io.read(4) end def test_read_after_end @io.read assert_equal "", @io.read end def test_read_after_end_with_amount @io.read(32) assert_equal nil, @io.read(32) end def test_second_full_read_after_rewinding @io.read @io.rewind assert_equal 'the quick brown fox', @io.read end def test_convert_error assert_raises(ArgumentError) { UploadIO.convert!('tmp.txt', 'text/plain', 'tmp.txt', 'tmp.txt') } end ## FIXME excluding on JRuby due to ## http://jira.codehaus.org/browse/JRUBY-7109 if IO.respond_to?(:copy_stream) && !defined?(JRUBY_VERSION) def test_compatible_with_copy_stream target_io = StringIO.new Timeout.timeout(1) do IO.copy_stream(@io, target_io) end assert_equal "the quick brown fox", target_io.string end end def test_empty io = CompositeReadIO.new assert_equal "", io.read end def test_empty_limited io = CompositeReadIO.new assert_nil io.read(1) end def test_empty_parts io = CompositeReadIO.new(StringIO.new, StringIO.new('the '), StringIO.new, StringIO.new('quick')) assert_equal "the", io.read(3) assert_equal " qu", io.read(3) assert_equal "ick", io.read(4) end def test_all_empty_parts io = CompositeReadIO.new(StringIO.new, StringIO.new) assert_nil io.read(1) end end ruby-multipart-post-2.0.0/test/test_parts.rb000066400000000000000000000041121255541725100211750ustar00rootroot00000000000000#-- # Copyright (c) 2007-2012 Nick Sieger. # See the file README.txt included with the distribution for # software license details. #++ require 'test/unit' require 'parts' require 'stringio' require 'composite_io' require 'tempfile' MULTIBYTE = File.dirname(__FILE__)+'/multibyte.txt' TEMP_FILE = "temp.txt" module AssertPartLength def assert_part_length(part) bytes = part.to_io.read bytesize = bytes.respond_to?(:bytesize) ? bytes.bytesize : bytes.length assert_equal bytesize, part.length end end class PartTest < Test::Unit::TestCase def setup @string_with_content_type = Class.new(String) do def content_type; 'application/data'; end end end def test_file_with_upload_io assert Parts::Part.file?(UploadIO.new(__FILE__, "text/plain")) end def test_file_with_modified_string assert !Parts::Part.file?(@string_with_content_type.new("Hello")) end def test_new_with_modified_string assert_kind_of Parts::ParamPart, Parts::Part.new("boundary", "multibyte", @string_with_content_type.new("Hello")) end end class FilePartTest < Test::Unit::TestCase include AssertPartLength def setup File.open(TEMP_FILE, "w") {|f| f << "1234567890"} io = UploadIO.new(TEMP_FILE, "text/plain") @part = Parts::FilePart.new("boundary", "afile", io) end def teardown File.delete(TEMP_FILE) rescue nil end def test_correct_length assert_part_length @part end def test_multibyte_file_length assert_part_length Parts::FilePart.new("boundary", "multibyte", UploadIO.new(MULTIBYTE, "text/plain")) end def test_multibyte_filename name = File.read(MULTIBYTE, 300) file = Tempfile.new(name.respond_to?(:force_encoding) ? name.force_encoding("UTF-8") : name) assert_part_length Parts::FilePart.new("boundary", "multibyte", UploadIO.new(file, "text/plain")) file.close end end class ParamPartTest < Test::Unit::TestCase include AssertPartLength def setup @part = Parts::ParamPart.new("boundary", "multibyte", File.read(MULTIBYTE)) end def test_correct_length assert_part_length @part end end