From 3a5098092cccbaeaae36c35eee66f07405483305 Mon Sep 17 00:00:00 2001 From: Scott Taylor Date: Wed, 30 Sep 2009 03:28:33 -0400 Subject: [PATCH] Raise an IOError when a file is read in a write-only mode. --- lib/fakefs/file.rb | 7 ++++++- test/fakefs_test.rb | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/lib/fakefs/file.rb b/lib/fakefs/file.rb index 3f5b048..fdc8199 100644 --- a/lib/fakefs/file.rb +++ b/lib/fakefs/file.rb @@ -116,7 +116,8 @@ module FakeFS end def read - raise IOError.new('closed stream') unless @open + raise IOError, 'closed stream' unless @open + raise IOError, 'not opened for reading' if write_only? @file.content end @@ -172,5 +173,9 @@ module FakeFS @file = FileSystem.add(path, FakeFile.new) end end + + def write_only? + @mode == WRITE_ONLY || @mode == APPEND_WRITE_ONLY + end end end diff --git a/test/fakefs_test.rb b/test/fakefs_test.rb index e270833..1d2914c 100644 --- a/test/fakefs_test.rb +++ b/test/fakefs_test.rb @@ -146,6 +146,26 @@ class FakeFSTest < Test::Unit::TestCase assert File.exists?("foo") end + def test_file_in_write_only_raises_error_when_reading + FileUtils.touch("foo") + + f = File.open("foo", "w") + + assert_raises(IOError) do + f.read + end + end + + def test_file_in_append_write_only_raises_error_when_reading + FileUtils.touch("foo") + + f = File.open("foo", "a") + + assert_raises(IOError) do + f.read + end + end + def test_can_read_files_once_written path = '/path/to/file.txt' File.open(path, 'w') do |f|