define RARRAY_PTR/RARRAY_LEN macros for Ruby 1.8.6
[kgio.git] / test / test_tryopen.rb
blob5a8efb253297cc055dbe3b4b6c25b4a2ede6aed6
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::File.tryopen(__FILE__)
11     tmp.respond_to?(:close_on_exec?) and
12       assert_equal(RUBY_VERSION.to_f >= 2.0, tmp.close_on_exec?)
14     assert_kind_of File, tmp
15     assert_equal File.read(__FILE__), tmp.read
16     assert_equal __FILE__, tmp.path
17     assert_equal __FILE__, tmp.to_path
18     assert_nothing_raised { tmp.close }
19   end
21   def test_tryopen_ENOENT
22     tmp = Tempfile.new "tryopen"
23     path = tmp.path
24     tmp.close!
25     tmp = Kgio::File.tryopen(path)
26     assert_equal :ENOENT, tmp
27   end
29   def test_tryopen_EPERM
30     tmp = Tempfile.new "tryopen"
31     File.chmod 0000, tmp.path
32     tmp = Kgio::File.tryopen(tmp.path)
33     assert_equal :EACCES, tmp
34   end
36   def test_tryopen_readwrite
37     tmp = Tempfile.new "tryopen"
38     file = Kgio::File.tryopen(tmp.path, IO::RDWR)
39     file.syswrite "FOO"
40     assert_equal "FOO", tmp.sysread(3)
41   end
43   def test_tryopen_try_readwrite
44     tmp = Tempfile.new "tryopen"
45     file = Kgio::File.tryopen(tmp.path, IO::RDWR)
46     assert_nil file.kgio_trywrite("FOO")
47     file.rewind
48     assert_equal "FOO", file.kgio_tryread(3)
49   end
51   def test_tryopen_mode
52     tmp = Tempfile.new "tryopen"
53     path = tmp.path
54     tmp.close!
55     file = Kgio::File.tryopen(path, IO::RDWR|IO::CREAT, 0000)
56     assert_equal 0100000, File.stat(path).mode
57     ensure
58       File.unlink path
59   end
61   require "benchmark"
62   def test_benchmark
63     nr = 1000000
64     tmp = Tempfile.new('tryopen')
65     file = tmp.path
66     Benchmark.bmbm do |x|
67       x.report("tryopen (OK)") do
68         nr.times { Kgio::File.tryopen(file).close }
69       end
70       x.report("open (OK)") do
71         nr.times { File.readable?(file) && File.open(file).close }
72       end
73     end
74     tmp.close!
75     assert_equal :ENOENT, Kgio::File.tryopen(file)
76     Benchmark.bmbm do |x|
77       x.report("tryopen (ENOENT)") do
78         nr.times { Kgio::File.tryopen(file) }
79       end
80       x.report("open (ENOENT)") do
81         nr.times { File.readable?(file) && File.open(file) }
82       end
83     end
84   end if ENV["BENCHMARK"]
85 end