README: formatting fix
[kgio.git] / test / test_tryopen.rb
blobabcbd37fe7076812c8a09ea89e6b64e61369d918
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     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_EACCES
30     tmp = Tempfile.new "tryopen"
31     File.chmod 0000, tmp.path
32     tmp = Kgio::File.tryopen(tmp.path)
33     if Process.euid == 0
34       assert_kind_of Kgio::File, tmp
35       warn "cannot test EACCES when euid == 0"
36     else
37       assert_equal(:EACCES, tmp)
38     end
39   end
41   def test_tryopen_readwrite
42     tmp = Tempfile.new "tryopen"
43     file = Kgio::File.tryopen(tmp.path, IO::RDWR)
44     file.syswrite "FOO"
45     assert_equal "FOO", tmp.sysread(3)
46   end
48   def test_tryopen_try_readwrite
49     tmp = Tempfile.new "tryopen"
50     file = Kgio::File.tryopen(tmp.path, IO::RDWR)
51     assert_nil file.kgio_trywrite("FOO")
52     file.rewind
53     assert_equal "FOO", file.kgio_tryread(3)
54   end
56   def test_tryopen_mode
57     tmp = Tempfile.new "tryopen"
58     path = tmp.path
59     tmp.close!
60     file = Kgio::File.tryopen(path, IO::RDWR|IO::CREAT, 0000)
61     assert_equal 0100000, File.stat(path).mode
62     ensure
63       File.unlink path
64   end
66   require "benchmark"
67   def test_benchmark
68     nr = 1000000
69     tmp = Tempfile.new('tryopen')
70     file = tmp.path
71     Benchmark.bmbm do |x|
72       x.report("tryopen (OK)") do
73         nr.times { Kgio::File.tryopen(file).close }
74       end
75       x.report("open (OK)") do
76         nr.times { File.readable?(file) && File.open(file).close }
77       end
78     end
79     tmp.close!
80     assert_equal :ENOENT, Kgio::File.tryopen(file)
81     Benchmark.bmbm do |x|
82       x.report("tryopen (ENOENT)") do
83         nr.times { Kgio::File.tryopen(file) }
84       end
85       x.report("open (ENOENT)") do
86         nr.times { File.readable?(file) && File.open(file) }
87       end
88     end
89   end if ENV["BENCHMARK"]
90 end