From bfffa910e9a8d5caf1628d7707ef19b7c4e5e1f0 Mon Sep 17 00:00:00 2001 From: Jon Yurek Date: Thu, 29 Oct 2009 21:15:31 -0400 Subject: [PATCH] Bitmask file creation modes allow for Tempfile compatability. --- lib/fakefs/file.rb | 24 +++++++++++++++++++++--- test/fakefs_test.rb | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/lib/fakefs/file.rb b/lib/fakefs/file.rb index 183eb90..4b1099f 100644 --- a/lib/fakefs/file.rb +++ b/lib/fakefs/file.rb @@ -13,6 +13,19 @@ module FakeFS FILE_CREATION_MODES = MODES - [READ_ONLY, READ_WRITE] + MODE_BITMASK = RealFile::RDONLY | + RealFile::WRONLY | + RealFile::RDWR | + RealFile::APPEND | + RealFile::CREAT | + RealFile::EXCL | + RealFile::NONBLOCK | + RealFile::TRUNC | + RealFile::NOCTTY | + RealFile::SYNC + + FILE_CREATION_BITMASK = RealFile::CREAT + def self.extname(path) RealFile.extname(path) end @@ -28,8 +41,9 @@ module FakeFS class << self alias_method :exists?, :exist? - # Assuming that everyone can read files + # Assuming that everyone can read and write files alias_method :readable?, :exist? + alias_method :writable?, :exist? end def self.mtime(path) @@ -248,11 +262,15 @@ module FakeFS end def file_creation_mode? - mode_in? FILE_CREATION_MODES + mode_in?(FILE_CREATION_MODES) || mode_in_bitmask?(FILE_CREATION_BITMASK) end def mode_in?(list) - list.any? { |element| @mode.include?(element) } + list.any? { |element| @mode.include?(element) } if @mode.respond_to?(:include?) + end + + def mode_in_bitmask?(mask) + (@mode & mask) != 0 if @mode.is_a?(Integer) end def create_missing_file diff --git a/test/fakefs_test.rb b/test/fakefs_test.rb index 85d6d34..af6aa93 100644 --- a/test/fakefs_test.rb +++ b/test/fakefs_test.rb @@ -109,6 +109,18 @@ class FakeFSTest < Test::Unit::TestCase assert File.exists?(path) assert File.readable?(path) + assert File.writable?(path) + end + + def test_can_create_files_with_bitmasks + path = '/path/to/file.txt' + File.open(path, File::RDWR | File::CREAT) do |f| + f.write "Yatta!" + end + + assert File.exists?(path) + assert File.readable?(path) + assert File.writable?(path) end def test_file_opens_in_read_only_mode @@ -121,6 +133,16 @@ class FakeFSTest < Test::Unit::TestCase end end + def test_file_opens_in_read_only_mode_with_bitmasks + File.open("foo", "w") { |f| f << "foo" } + + f = File.open("foo", File::RDONLY) + + assert_raises(IOError) do + f << "bar" + end + end + def test_file_opens_in_invalid_mode FileUtils.touch("foo") @@ -146,6 +168,17 @@ class FakeFSTest < Test::Unit::TestCase assert File.exists?("foo") end + def test_creates_files_in_write_only_mode_with_bitmasks + File.open("foo", File::WRONLY | File::CREAT) + assert File.exists?("foo") + end + + def test_raises_in_write_only_mode_without_create_bitmask + assert_raises(Errno::ENOENT) do + File.open("foo", File::WRONLY) + end + end + def test_creates_files_in_read_write_truncate_mode File.open("foo", "w+") assert File.exists?("foo")