# $Id: tc_hash.rb,v 1.3 2003/03/01 11:29:01 knu Exp $

require 'test/unit'
begin
  require 'features/ruby18/hash'
rescue LoadError; end

class TC_Hash < Test::Unit::TestCase
  def test_select
    # test 1
    assert_equal([2,4], {1=>2,3=>4,5=>6}.select(1,3))

    # test 2
    assert_equal([ENV['PATH'],ENV['USER']], ENV.select('PATH','USER'))
  end

  def test_update
    # test 1 - without block
    hash0 = { 1 => 'once', 2 => 'twice', 3 => 'thrice' }
    hash1 = hash0.clone
    hash2 = { 3 => 'three times',  4 => 'four times' }

    assert_same(hash1, hash1.update(hash2))
    assert_equal({ 1 => 'once', 2 => 'twice',
		   3 => 'three times',  4 => 'four times' }, hash1)

    # test 2 - with block
    hash1 = hash0.clone
    called = false
    ret = hash1.update(hash2) { |*args|
      assert_equal([3, 'thrice', 'three times'], args)
      called = true
      args[1]
    }
    called or
      flunk("block wasn't yielded once.")
    assert_same(hash1, ret)
    assert_equal({ 1 => 'once', 2 => 'twice',
		   3 => 'thrice',  4 => 'four times' }, hash1)
  end

  def test_merge
    # test 1 - without block
    hash0 = { 1 => 'once', 2 => 'twice', 3 => 'thrice' }
    hash1 = hash0.clone
    hash2 = { 3 => 'three times',  4 => 'four times' }

    ret = hash1.merge(hash2)
    assert_not_same(hash1, ret)
    assert_equal({ 1 => 'once', 2 => 'twice',
		   3 => 'three times',  4 => 'four times' }, ret)

    # test 2 - with block
    hash1 = hash0.clone
    called = false
    ret = hash1.merge(hash2) { |*args|
      assert_equal([3, 'thrice', 'three times'], args)
      called = true
      args[1]
    }
    called or
      flunk("block wasn't yielded once.")
    assert_not_same(hash1, ret)
    assert_equal({ 1 => 'once', 2 => 'twice',
		   3 => 'thrice',  4 => 'four times' }, ret)
  end
end
