From 076ef40678c7c4dba1edca0ef420fe4970d7676d Mon Sep 17 00:00:00 2001 From: Aaron Suggs Date: Mon, 11 Jan 2010 19:55:01 -0500 Subject: [PATCH] Add File.rename (a primitive of FileUtils.mv). Closes #29 --- lib/fakefs/file.rb | 17 ++++++++++++++ test/fakefs_test.rb | 55 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) diff --git a/lib/fakefs/file.rb b/lib/fakefs/file.rb index 1588096..4711186 100644 --- a/lib/fakefs/file.rb +++ b/lib/fakefs/file.rb @@ -148,6 +148,23 @@ module FakeFS read(path).split("\n") end + def self.rename(source, dest) + if directory?(source) && file?(dest) + raise Errno::ENOTDIR, "Not a directory - #{source} or #{dest}" + elsif file?(source) && directory?(dest) + raise Errno::EISDIR, "Is a directory - #{source} or #{dest}" + end + + if target = FileSystem.find(source) + FileSystem.add(dest, target.entry.clone) + FileSystem.delete(source) + else + raise Errno::ENOENT, "No such file or directory - #{source} or #{dest}" + end + + 0 + end + def self.link(source, dest) if directory?(source) raise Errno::EPERM, "Operation not permitted - #{source} or #{dest}" diff --git a/test/fakefs_test.rb b/test/fakefs_test.rb index 6411bd9..473557d 100644 --- a/test/fakefs_test.rb +++ b/test/fakefs_test.rb @@ -1267,6 +1267,61 @@ class FakeFSTest < Test::Unit::TestCase assert Dir.tmpdir == "/tmp" end + def test_rename_renames_a_file + FileUtils.touch("/foo") + File.rename("/foo", "/bar") + assert File.file?("/bar") + end + + def test_rename_returns + FileUtils.touch("/foo") + assert_equal 0, File.rename("/foo", "/bar") + end + + def test_rename_renames_two_files + FileUtils.touch("/foo") + FileUtils.touch("/bar") + File.rename("/foo", "/bar") + assert File.file?("/bar") + + end + + def test_rename_renames_a_directories + Dir.mkdir("/foo") + File.rename("/foo", "/bar") + assert File.directory?("/bar") + end + + def test_rename_renames_two_directories + Dir.mkdir("/foo") + Dir.mkdir("/bar") + File.rename("/foo", "/bar") + assert File.directory?("/bar") + end + + def test_rename_file_to_directory_raises_error + FileUtils.touch("/foo") + Dir.mkdir("/bar") + assert_raises(Errno::EISDIR) do + File.rename("/foo", "/bar") + end + end + + def test_rename_directory_to_file_raises_error + Dir.mkdir("/foo") + FileUtils.touch("/bar") + assert_raises(Errno::ENOTDIR) do + File.rename("/foo", "/bar") + end + end + + + def test_rename_with_missing_source_raises_error + assert_raises(Errno::ENOENT) do + File.rename("/no_such_file", "/bar") + end + end + def test_hard_link_creates_file FileUtils.touch("/foo")