about summary refs log tree commit homepage
path: root/test
diff options
context:
space:
mode:
authorEric Wong <normalperson@yhbt.net>2011-05-13 15:55:50 -0700
committerEric Wong <normalperson@yhbt.net>2011-05-13 15:55:50 -0700
commit6cefcff5889cceaa001f76f4be1a1c5e513b241d (patch)
tree1824896fe69e92bbe541b14f233d7269af6c33bd /test
parentab732113e13f1690fd2c1a18d1c66beb7864d847 (diff)
downloadkgio-6cefcff5889cceaa001f76f4be1a1c5e513b241d.tar.gz
For the case where a file is readable, it's faster to
just call open() instead of stat()-ing and then calling
open().

open() failures are still relatively cheap, too, they're still
more expensive than a failed stat() but cheaper than raising
an exception.
Diffstat (limited to 'test')
-rw-r--r--test/test_tryopen.rb71
1 files changed, 71 insertions, 0 deletions
diff --git a/test/test_tryopen.rb b/test/test_tryopen.rb
new file mode 100644
index 0000000..c885ca0
--- /dev/null
+++ b/test/test_tryopen.rb
@@ -0,0 +1,71 @@
+require 'tempfile'
+require 'test/unit'
+$-w = true
+require 'kgio'
+
+class TestTryopen < Test::Unit::TestCase
+
+  def test_tryopen_success
+    tmp = Kgio.tryopen(__FILE__)
+    assert_instance_of File, tmp
+    assert_equal File.read(__FILE__), tmp.read
+    assert_nothing_raised { tmp.close }
+  end
+
+  def test_tryopen_ENOENT
+    tmp = Tempfile.new "tryopen"
+    path = tmp.path
+    tmp.close!
+    tmp = Kgio.tryopen(path)
+    assert_equal :ENOENT, tmp
+  end
+
+  def test_tryopen_EPERM
+    tmp = Tempfile.new "tryopen"
+    File.chmod 0000, tmp.path
+    tmp = Kgio.tryopen(tmp.path)
+    assert_equal :EACCES, tmp
+  end
+
+  def test_tryopen_readwrite
+    tmp = Tempfile.new "tryopen"
+    file = Kgio.tryopen(tmp.path, IO::RDWR)
+    file.syswrite "FOO"
+    assert_equal "FOO", tmp.sysread(3)
+  end
+
+  def test_tryopen_mode
+    tmp = Tempfile.new "tryopen"
+    path = tmp.path
+    tmp.close!
+    file = Kgio.tryopen(path, IO::RDWR|IO::CREAT, 0000)
+    assert_equal 0100000, File.stat(path).mode
+    ensure
+      File.unlink path
+  end
+
+  require "benchmark"
+  def test_benchmark
+    nr = 1000000
+    tmp = Tempfile.new('tryopen')
+    file = tmp.path
+    Benchmark.bmbm do |x|
+      x.report("tryopen (OK)") do
+        nr.times { Kgio.tryopen(file).close }
+      end
+      x.report("open (OK)") do
+        nr.times { File.readable?(file) && File.open(file).close }
+      end
+    end
+    tmp.close!
+    assert_equal :ENOENT, Kgio.tryopen(file)
+    Benchmark.bmbm do |x|
+      x.report("tryopen (ENOENT)") do
+        nr.times { Kgio.tryopen(file) }
+      end
+      x.report("open (ENOENT)") do
+        nr.times { File.readable?(file) && File.open(file) }
+      end
+    end
+  end if ENV["BENCHMARK"]
+end