diff --git a/lib/fakefs.rb b/lib/fakefs.rb index e1b2d34..5d8d535 100644 --- a/lib/fakefs.rb +++ b/lib/fakefs.rb @@ -1,4 +1,6 @@ -module FakeFS +require 'fileutils' + +class FakeFS module FileUtils extend self @@ -41,13 +43,17 @@ module FakeFS end def self.expand_path(path) - ::File.expand_path(path) + RealFile.expand_path(path) end def self.readlink(path) symlink = FileSystem.find(path) FileSystem.find(symlink.target).to_s end + + def self.dirname(path) + RealFile.dirname(path) + end end class Dir @@ -60,54 +66,6 @@ module FakeFS end end - module FileSystem - extend self - - def fs - @fs ||= MockDir.new('.') - end - - def clear - @fs = nil - end - - def find(path) - parts = path_parts(path) - - target = parts[0...-1].inject(fs) do |dir, part| - dir[part] || {} - end - - case parts.last - when '*' - target.values - else - target[parts.last] - end - end - - def add(path, object) - parts = path_parts(path) - - d = parts[0...-1].inject(fs) do |dir, part| - dir[part] ||= MockDir.new(part, dir) - end - - object.name = parts.last - object.parent = d - d[parts.last] = object - end - - def delete(path) - if dir = FileSystem.find(path) - dir.parent.delete(dir.name) - end - end - - def path_parts(path) - path.split(File::PATH_SEPARATOR) - end - end class MockDir < Hash attr_accessor :name, :parent @@ -117,6 +75,10 @@ module FakeFS @parent = parent end + def files + values + end + def entry self end @@ -150,8 +112,63 @@ module FakeFS entry.send(*args, &block) end end + + def fs + @fs ||= MockDir.new('.') + end + + def clear + @fs = nil + end + + def find(path) + parts = path_parts(path) + + target = parts[0...-1].inject(fs) do |dir, part| + dir[part] || {} + end + + case parts.last + when '*' + target.values + else + target[parts.last] + end + end + + def add(path, object) + parts = path_parts(path) + + d = parts[0...-1].inject(fs) do |dir, part| + dir[part] ||= MockDir.new(part, dir) + end + + object.name = parts.last + object.parent = d + d[parts.last] = object + end + + def delete(path) + if dir = FileSystem.find(path) + dir.parent.delete(dir.name) + end + end + + def path_parts(path) + path.split(File::PATH_SEPARATOR) + end + + def method_missing(*args, &block) + fs.send(*args, &block) + end + + FileSystem = FakeFS.new('.') end +RealFile = File +RealFileUtils = FileUtils +RealDir = Dir + Object.class_eval do remove_const(:Dir) remove_const(:File) diff --git a/test/fake_fs.rb b/test/fake_fs.rb new file mode 100644 index 0000000..d3fe3ec --- /dev/null +++ b/test/fake_fs.rb @@ -0,0 +1,15 @@ +$LOAD_PATH.unshift File.join(File.dirname(__FILE__), '..', 'lib') +require 'fakefs' +require 'test/unit' + +class FakeFSTest < Test::Unit::TestCase + def test_can_be_initialized_empty + fs = FakeFS.new('.') + assert_equal 0, fs.files.size + end + + def test_can_be_initialized_with_an_existing_directory + fs = FakeFS.new(File.expand_path(File.dirname(__FILE__))) + assert_equal 1, fs.files.size + end +end