require 'test/unit'
require 'test_helper'
require 'multipart_form_data'


#
# Test the MultipartFormData class functionality.
#
class MultipartFormDataTest < Test::Unit::TestCase

  include TestHelper

  def setup
    @generalized_content_type = 'multipart/form-data; boundary=Boundary_00.00'
  end

  def test_initialization_with_text_and_file_params
    params = {  # this will fail if params reorders the key/value pairs.
      # symbol and string keys acceptable
      :name => 'Betty Crocker',
      'address' => '1234 Doughboy Lane',
      'pie_pic' => Pathname.new(sd('/image.jpg'))
    }
    fd = MultipartFormData.new(params)
    expected_content = IO.read(sd('/form_data.msg'))

    assert_equal_content_type @generalized_content_type, fd.content_type
    assert_equal_mime_message expected_content, fd.content
    assert_equal fd.to_s, fd.content  # check alias
  end

  def test_initialization_with_unknown_file
    params = { 'file_to_upload' => Pathname.new(sd('/unknown.yyy')) }
    fd = MultipartFormData.new(params)
    expected_content = IO.read(sd('/form_data_unknown.msg'))

    assert_equal_content_type @generalized_content_type, fd.content_type
    assert_equal_mime_message expected_content, fd.content
  end

  def test_initialization_with_valid_parameter_values
    params = Hash.new
    valid_params = ['some string', Pathname.new(sd('/image.jpg'))]

    valid_params.each do |valid_param|
      params['field'] = valid_param
      assert_nothing_raised {MultipartFormData.new(params)}
    end
  end

  def test_initialization_with_invalid_parameter_values
    params = Hash.new
    invalid_params = [1, [1,2,3], {:key=>'value'}]

    invalid_params.each do |invalid_param|
      params['field'] = invalid_param
      err = assert_raise(RuntimeError) {MultipartFormData.new(params)}
      assert_equal 'invalid parameter', err.message
    end
  end

end
