return Kgio::File for Kgio.tryopen
[kgio.git] / test / test_tryopen.rb
blobca804608a12812affb5d9311863ac861f8777401
1 require 'tempfile'
2 require 'test/unit'
3 $-w = true
4 require 'kgio'
6 class TestTryopen < Test::Unit::TestCase
8   def test_tryopen_success
9     tmp = Kgio.tryopen(__FILE__)
10     assert_kind_of File, tmp
11     assert_equal File.read(__FILE__), tmp.read
12     assert_equal __FILE__, tmp.path
13     assert_equal __FILE__, tmp.to_path
14     assert_nothing_raised { tmp.close }
15   end
17   def test_tryopen_ENOENT
18     tmp = Tempfile.new "tryopen"
19     path = tmp.path
20     tmp.close!
21     tmp = Kgio.tryopen(path)
22     assert_equal :ENOENT, tmp
23   end
25   def test_tryopen_EPERM
26     tmp = Tempfile.new "tryopen"
27     File.chmod 0000, tmp.path
28     tmp = Kgio.tryopen(tmp.path)
29     assert_equal :EACCES, tmp
30   end
32   def test_tryopen_readwrite
33     tmp = Tempfile.new "tryopen"
34     file = Kgio.tryopen(tmp.path, IO::RDWR)
35     file.syswrite "FOO"
36     assert_equal "FOO", tmp.sysread(3)
37   end
39   def test_tryopen_mode
40     tmp = Tempfile.new "tryopen"
41     path = tmp.path
42     tmp.close!
43     file = Kgio.tryopen(path, IO::RDWR|IO::CREAT, 0000)
44     assert_equal 0100000, File.stat(path).mode
45     ensure
46       File.unlink path
47   end
49   require "benchmark"
50   def test_benchmark
51     nr = 1000000
52     tmp = Tempfile.new('tryopen')
53     file = tmp.path
54     Benchmark.bmbm do |x|
55       x.report("tryopen (OK)") do
56         nr.times { Kgio.tryopen(file).close }
57       end
58       x.report("open (OK)") do
59         nr.times { File.readable?(file) && File.open(file).close }
60       end
61     end
62     tmp.close!
63     assert_equal :ENOENT, Kgio.tryopen(file)
64     Benchmark.bmbm do |x|
65       x.report("tryopen (ENOENT)") do
66         nr.times { Kgio.tryopen(file) }
67       end
68       x.report("open (ENOENT)") do
69         nr.times { File.readable?(file) && File.open(file) }
70       end
71     end
72   end if ENV["BENCHMARK"]
73 end