# $Id: tc_io.rb,v 1.6 2003/04/22 06:18:08 knu Exp $

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

class TC_IO < Test::Unit::TestCase
  def test_s_for_fd
    open(__FILE__) { |f1|
      called = false

      fd = f1.fileno
      f2 = IO.for_fd(fd) { called = true }
      assert_equal(false, called)

      assert_kind_of(IO, f2)
      assert_not_same(f1, f2)
      assert_equal(fd, f2.fileno)

      #f2.close
    }
  end

  def test_s_read
    assert_raises(Errno::ENOENT) { IO.read("nonexistent_file") }

    s = nil

    open(__FILE__) { |f| s = f.read }

    assert_equal(s, IO.read(__FILE__))
  end

  def test_fsync
    file = '.unit.test.file'

    open(file, "w") { |f|
      assert_nothing_raised { f.fsync }
    }

    open(file, "r") { |f|
      assert_raises(IOError) { f.fsync }
    }
  ensure
    File.unlink(file) rescue nil
  end

  def test_sysseek
    open(__FILE__) { |f|
      assert_equal(2, f.sysseek(2))
      assert_equal(3, f.sysseek(1, IO::SEEK_CUR))

      assert_equal('Id', f.sysread(2))
    }
  end

  def test_read
    file = '.unit.test.file'

    open(file, "w") { |f| f.puts "test" }
    buf = "buffer"
    ret = nil
    open(file, "r") { |f| ret = f.read(3, buf) }
    assert_same(buf, ret)
    assert_equal("tes", buf)
    open(file, "r") { |f| ret = f.read(2) }
    assert_not_same(buf, ret)
    assert_equal("te", ret)
    open(file, "r") { |f| ret = f.read() }
    assert_not_same(buf, ret)
    assert_equal("test\n", ret)
  ensure
    File.unlink(file) rescue nil
  end

  def test_sysread
    file = '.unit.test.file'

    open(file, "w") { |f| f.puts "test" }
    buf = "buffer"
    ret = nil
    open(file, "r") { |f| ret = f.sysread(3, buf) }
    assert_same(buf, ret)
    assert_equal("tes", buf)
    open(file, "r") { |f| ret = f.sysread(2) }
    assert_not_same(buf, ret)
    assert_equal("te", ret)
    open(file, "r") { |f|
      assert_raises(ArgumentError) { ret = f.sysread() }
    }
  ensure
    File.unlink(file) rescue nil
  end
end
