fakefs-0.4.2/0000755000004100000410000000000012057273366013017 5ustar www-datawww-datafakefs-0.4.2/.travis.yml0000644000004100000410000000016312057273366015130 0ustar www-datawww-datarvm: - 1.8.7 - 1.9.3 - jruby - rbx-19mode matrix: allow_failures: - rvm: jruby - rvm: rbx-19mode fakefs-0.4.2/CONTRIBUTORS0000644000004100000410000000230612057273366014700 0ustar www-datawww-dataScott Taylor Pat Nakajima Chris Wanstrath Myles Eftos Jeff Hodges Matt Freels Eero Saynatkari Víctor Martínez Nick Quaranto Aaron Suggs Victor Costan Eric MSP Veith Jon Yurek Jared Luxenberg Lars Gierth Greg Campbell Ben Mabey Mark Sam Goldstein Ryan McGeary Noah Paessel dmathieu <42@dmathieu.com> Mariusz Pietrzyk marano jameswilding Tymon Tobolski Scott Barron Andrius Chamentauskas Keita Urashima David Reese msassak Andrius Chamentauskas timo3377 Mislav Marohnić Rob Sanheim fakefs-0.4.2/test/0000755000004100000410000000000012057273366013776 5ustar www-datawww-datafakefs-0.4.2/test/fake/0000755000004100000410000000000012057273366014704 5ustar www-datawww-datafakefs-0.4.2/test/fake/file/0000755000004100000410000000000012057273366015623 5ustar www-datawww-datafakefs-0.4.2/test/fake/file/stat_test.rb0000644000004100000410000000140712057273366020164 0ustar www-datawww-datarequire "test_helper" class FileStat < Test::Unit::TestCase def setup FakeFS.activate! FakeFS::FileSystem.clear end def teardown FakeFS.deactivate! end def test_calling_stat_should_create_a_new_file_stat_object File.open("foo", "w") do |f| f << "bar" end File.open("foo") do |f| assert_equal File::Stat, f.stat.class end end def test_stat_should_use_correct_file File.open("bar", "w") do |f| f << "1" end File.open("bar") do |f| assert_equal 1, f.stat.size end end def test_stat_should_report_on_symlink_pointer File.open("foo", "w") { |f| f << "some content" } File.symlink "foo", "my_symlink" assert_equal File.stat("my_symlink").size, File.stat("foo").size end endfakefs-0.4.2/test/fake/file/lstat_test.rb0000644000004100000410000000265012057273366020341 0ustar www-datawww-datarequire "test_helper" class FileStat < Test::Unit::TestCase def setup FakeFS.activate! FakeFS::FileSystem.clear end def teardown FakeFS.deactivate! end def test_calling_lstat_should_create_a_new_file_stat_object File.open("foo", "w") do |f| f << "bar" end File.open("foo") do |f| assert_equal File::Stat, f.lstat.class end end def test_lstat_should_use_correct_file File.open("bar", "w") do |f| f << "1" end File.open("bar") do |f| assert_equal 1, f.lstat.size end end def test_lstat_should_report_on_symlink_itself File.open("foo", "w") { |f| f << "some content" } File.symlink "foo", "my_symlink" assert_not_equal File.lstat("my_symlink").size, File.lstat("foo").size end def test_should_report_on_symlink_itself_with_size_instance_method File.open("foo", "w") { |f| f << "some content" } File.symlink "foo", "my_symlink" file = File.open("foo") symlink = File.open("my_symlink") assert_not_equal file.lstat.size, symlink.lstat.size end def test_symlink_size_is_size_of_path_pointed_to File.open("a", "w") { |x| x << "foobarbazfoobarbaz" } File.symlink "a", "one_char_symlink" assert_equal 1, File.lstat("one_char_symlink").size File.open("ab", "w") { |x| x << "foobarbazfoobarbaz" } File.symlink "ab", "two_char_symlink" assert_equal 2, File.lstat("two_char_symlink").size end endfakefs-0.4.2/test/fake/file/sysseek_test.rb0000644000004100000410000000146112057273366020677 0ustar www-datawww-datarequire "test_helper" class FileSysSeek < Test::Unit::TestCase def setup FakeFS.activate! FakeFS::FileSystem.clear end def teardown FakeFS.deactivate! end def test_should_seek_to_position file = File.open("foo", "w") do |f| f << "0123456789" end File.open("foo", "r") do |f| f.sysseek(3) assert_equal 3, f.pos f.sysseek(0) assert_equal 0, f.pos end end def test_seek_returns_offset_into_file File.open("foo", "w") do |f| # 66 chars long str = "0123456789" + "0123456789" + "0123456789" + "0123456789" + "0123456789" + "0123456789" + "012345" f << str end f = File.open("foo") assert_equal 53, f.sysseek(-13, IO::SEEK_END) end endfakefs-0.4.2/test/fake/file/join_test.rb0000644000004100000410000000056412057273366020153 0ustar www-datawww-datarequire "test_helper" class FileJoin < Test::Unit::TestCase def setup FakeFS.activate! end def teardown FakeFS.deactivate! end [ ["a", "b"], ["a/", "b"], ["a", "/b"], ["a/", "/b"], ["a", "/", "b"] ].each_with_index do |args, i| define_method "test_file_join_#{i}" do assert_equal RealFile.join(args), File.join(args) end end endfakefs-0.4.2/test/fake/file/syswrite_test.rb0000644000004100000410000000253712057273366021107 0ustar www-datawww-datarequire "test_helper" class FileSysWriteTest < Test::Unit::TestCase def setup FakeFS.activate! FakeFS::FileSystem.clear end def teardown FakeFS.deactivate! end def test_returns_one_byte_when_written f = File.open "foo", "w" result = f.syswrite "a" assert_equal 1, result end def test_returns_two_bytes_when_two_written f = File.open "foo", "w" result = f.syswrite "ab" assert_equal 2, result end def test_syswrite_writes_file f = File.open "foo", "w" f.syswrite "abcdef" f.close assert_equal "abcdef", File.read("foo") end def test_writes_to_the_actual_position_when_called_after_buffered_io_read File.open("foo", "w") do |file| file.syswrite("012345678901234567890123456789") end file = File.open("foo", "r+") file.read(5) file.syswrite("abcde") File.open("foo") do |file| assert_equal "01234abcde", file.sysread(10) end end def test_writes_all_of_the_strings_bytes_but_does_not_buffer_them File.open("foo", "w") do |file| file.syswrite("012345678901234567890123456789") end file = File.open("foo", "r+") written = file.syswrite("abcde") File.open("foo") do |file| assert_equal "abcde56789", file.sysread(10) file.seek(0) file.fsync assert_equal "abcde56789", file.sysread(10) end end endfakefs-0.4.2/test/fake/file_test.rb0000644000004100000410000000402212057273366017205 0ustar www-datawww-datarequire "test_helper" class FakeFileTest < Test::Unit::TestCase include FakeFS def setup FileSystem.clear @file = FakeFile.new end def test_fake_file_has_empty_content_by_default assert_equal "", @file.content end def test_fake_file_can_read_and_write_to_content @file.content = "foobar" assert_equal "foobar", @file.content end def test_fake_file_has_1_link_by_default assert_equal [@file], @file.links end def test_fake_file_can_create_link other_file = FakeFile.new @file.link(other_file) assert_equal [@file, other_file], @file.links end def test_fake_file_wont_add_link_to_same_file_twice other_file = FakeFile.new @file.link other_file @file.link other_file assert_equal [@file, other_file], @file.links end def test_links_are_mutual other_file = FakeFile.new @file.link(other_file) assert_equal [@file, other_file], other_file.links end def test_can_link_multiple_files file_two = FakeFile.new file_three = FakeFile.new @file.link file_two @file.link file_three assert_equal [@file, file_two, file_three], @file.links assert_equal [@file, file_two, file_three], file_two.links assert_equal [@file, file_two, file_three], file_three.links end def test_links_share_same_content other_file = FakeFile.new @file.link other_file @file.content = "foobar" assert_equal "foobar", other_file.content end def test_clone_creates_new_inode clone = @file.clone assert !clone.inode.equal?(@file.inode) end def test_cloning_does_not_use_same_content_object clone = @file.clone clone.content = "foo" @file.content = "bar" assert_equal "foo", clone.content assert_equal "bar", @file.content end def test_raises_an_error_with_the_correct_path path = "/some/non/existing/file" begin FakeFS::File.new path msg = nil rescue Errno::ENOENT => e msg = e.message end assert_equal "No such file or directory - #{path}", msg end end fakefs-0.4.2/test/fake/symlink_test.rb0000644000004100000410000000040512057273366017755 0ustar www-datawww-datarequire "test_helper" class FakeSymlinkTest < Test::Unit::TestCase include FakeFS def test_symlink_has_method_missing_as_private methods = FakeSymlink.private_instance_methods.map { |m| m.to_s } assert methods.include?("method_missing") end end fakefs-0.4.2/test/file/0000755000004100000410000000000012057273366014715 5ustar www-datawww-datafakefs-0.4.2/test/file/stat_test.rb0000644000004100000410000000425412057273366017261 0ustar www-datawww-datarequire "test_helper" class FileStatTest < Test::Unit::TestCase include FakeFS def setup FileSystem.clear end def touch(*args) FileUtils.touch(*args) end def ln_s(*args) FileUtils.ln_s(*args) end def mkdir(*args) Dir.mkdir(*args) end def ln(*args) File.link(*args) end def test_file_stat_init_with_non_existant_file assert_raises(Errno::ENOENT) do File::Stat.new("/foo") end end def test_symlink_should_be_true_when_symlink touch("/foo") ln_s("/foo", "/bar") assert File::Stat.new("/bar").symlink? end def test_symlink_should_be_false_when_not_a_symlink FileUtils.touch("/foo") assert !File::Stat.new("/foo").symlink? end def test_should_return_false_for_directory_when_not_a_directory FileUtils.touch("/foo") assert !File::Stat.new("/foo").directory? end def test_should_return_true_for_directory_when_a_directory mkdir "/foo" assert File::Stat.new("/foo").directory? end def test_writable_is_true touch("/foo") assert File::Stat.new("/foo").writable? end def test_readable_is_true touch("/foo") assert File::Stat.new("/foo").readable? end def test_one_file_has_hard_link touch "testfile" assert_equal 1, File.stat("testfile").nlink end def test_two_hard_links_show_nlinks_as_two touch "testfile" ln "testfile", "testfile.bak" assert_equal 2, File.stat("testfile").nlink end def test_file_size File.open('testfile', 'w') { |f| f << 'test' } assert_equal 4, File.stat('testfile').size end def test_file_zero? File.open('testfile', 'w') { |f| f << 'test' } assert !File.stat('testfile').zero?, "testfile has size 4, not zero" FileUtils.touch('testfile2') assert File.stat('testfile2').zero?, "testfile2 has size 0, but stat lied" end def test_touch_modifies_mtime FileUtils.touch("/foo") mtime = File.mtime("/foo") FileUtils.touch("/foo") assert File.mtime("/foo") > mtime end def test_writing_to_file_modifies_mtime FileUtils.touch("/foo") mtime = File.mtime("/foo") File.open('/foo', 'w') { |f| f << 'test' } assert File.mtime("/foo") > mtime end end fakefs-0.4.2/test/test_helper.rb0000644000004100000410000000041712057273366016643 0ustar www-datawww-data$LOAD_PATH.unshift File.join(File.dirname(__FILE__), '..', 'lib') require 'fakefs/safe' require 'test/unit' begin require 'redgreen' rescue LoadError end def act_on_real_fs raise ArgumentError unless block_given? FakeFS.deactivate! yield FakeFS.activate! end fakefs-0.4.2/test/verify.rb0000644000004100000410000000157512057273366015637 0ustar www-datawww-data# Figure out what's missing from fakefs # # USAGE # # $ RUBYLIB=test ruby test/verify.rb | grep "not implemented" require "test_helper" class FakeFSVerifierTest < Test::Unit::TestCase class_mapping = { RealFile => FakeFS::File, RealFile::Stat => FakeFS::File::Stat, RealFileUtils => FakeFS::FileUtils, RealDir => FakeFS::Dir, RealFileTest => FakeFS::FileTest } class_mapping.each do |real_class, fake_class| real_class.methods.each do |method| define_method "test #{method} class method" do assert fake_class.respond_to?(method), "#{fake_class}.#{method} not implemented" end end real_class.instance_methods.each do |method| define_method("test #{method} instance method") do assert fake_class.instance_methods.include?(method), "#{fake_class}##{method} not implemented" end end end end fakefs-0.4.2/test/fakefs_test.rb0000644000004100000410000015700412057273366016630 0ustar www-datawww-datarequire "test_helper" class FakeFSTest < Test::Unit::TestCase include FakeFS def setup FakeFS.activate! FileSystem.clear end def teardown FakeFS.deactivate! end def test_can_be_initialized_empty fs = FileSystem assert_equal 0, fs.files.size end def xtest_can_be_initialized_with_an_existing_directory fs = FileSystem fs.clone(File.expand_path(File.dirname(__FILE__))).inspect assert_equal 1, fs.files.size end def test_can_create_directories_with_file_utils_mkdir_p FileUtils.mkdir_p("/path/to/dir") assert_kind_of FakeDir, FileSystem.fs['path']['to']['dir'] end def test_can_create_directories_with_options FileUtils.mkdir_p("/path/to/dir", :mode => 0755) assert_kind_of FakeDir, FileSystem.fs['path']['to']['dir'] end def test_can_create_directories_with_file_utils_mkdir FileUtils.mkdir_p("/path/to/dir") FileUtils.mkdir("/path/to/dir/subdir") assert_kind_of FakeDir, FileSystem.fs['path']['to']['dir']['subdir'] end def test_raises_error_when_creating_a_new_dir_with_mkdir_in_non_existent_path assert_raises Errno::ENOENT do FileUtils.mkdir("/this/path/does/not/exists/newdir") end end def test_can_create_directories_with_mkpath FileUtils.mkpath("/path/to/dir") assert_kind_of FakeDir, FileSystem.fs['path']['to']['dir'] end def test_can_create_directories_with_mkpath_and_options FileUtils.mkpath("/path/to/dir", :mode => 0755) assert_kind_of FakeDir, FileSystem.fs['path']['to']['dir'] end def test_can_create_directories_with_mkdirs FileUtils.makedirs("/path/to/dir") assert_kind_of FakeDir, FileSystem.fs['path']['to']['dir'] end def test_can_create_directories_with_mkdirs_and_options FileUtils.makedirs("/path/to/dir", :mode => 0755) assert_kind_of FakeDir, FileSystem.fs['path']['to']['dir'] end def test_unlink_errors_on_file_not_found assert_raise Errno::ENOENT do FileUtils.rm("/foo") end end def test_unlink_doesnt_error_on_file_not_found_when_forced assert_nothing_raised do FileUtils.rm("/foo", :force => true) end end def test_can_delete_directories FileUtils.mkdir_p("/path/to/dir") FileUtils.rmdir("/path/to/dir") assert File.exists?("/path/to/") assert File.exists?("/path/to/dir") == false end def test_can_delete_multiple_files FileUtils.touch(["foo", "bar"]) FileUtils.rm(["foo", "bar"]) assert File.exists?("foo") == false assert File.exists?("bar") == false end def test_knows_directories_exist FileUtils.mkdir_p(path = "/path/to/dir") assert File.exists?(path) end def test_knows_directories_are_directories FileUtils.mkdir_p(path = "/path/to/dir") assert File.directory?(path) end def test_knows_directories_are_directories_with_periods FileUtils.mkdir_p(period_path = "/path/to/periodfiles/one.one") FileUtils.mkdir("/path/to/periodfiles/one-one") assert File.directory?(period_path) end def test_knows_symlink_directories_are_directories FileUtils.mkdir_p(path = "/path/to/dir") FileUtils.ln_s path, sympath = '/sympath' assert File.directory?(sympath) end def test_knows_non_existent_directories_arent_directories path = 'does/not/exist/' assert_equal RealFile.directory?(path), File.directory?(path) end def test_doesnt_overwrite_existing_directories FileUtils.mkdir_p(path = "/path/to/dir") assert File.exists?(path) FileUtils.mkdir_p("/path/to") assert File.exists?(path) assert_raises Errno::EEXIST do FileUtils.mkdir("/path/to") end assert File.exists?(path) end def test_symlink_with_missing_refferent_does_not_exist File.symlink('/foo', '/bar') assert !File.exists?('/bar') end def test_can_create_symlinks FileUtils.mkdir_p(target = "/path/to/target") FileUtils.ln_s(target, "/path/to/link") assert_kind_of FakeSymlink, FileSystem.fs['path']['to']['link'] assert_raises(Errno::EEXIST) do FileUtils.ln_s(target, '/path/to/link') end end def test_can_force_creation_of_symlinks FileUtils.mkdir_p(target = "/path/to/first/target") FileUtils.ln_s(target, "/path/to/link") assert_kind_of FakeSymlink, FileSystem.fs['path']['to']['link'] FileUtils.ln_s(target, '/path/to/link', :force => true) end def test_create_symlink_using_ln_sf FileUtils.mkdir_p(target = "/path/to/first/target") FileUtils.ln_s(target, "/path/to/link") assert_kind_of FakeSymlink, FileSystem.fs['path']['to']['link'] FileUtils.ln_sf(target, '/path/to/link') end def test_can_follow_symlinks FileUtils.mkdir_p(target = "/path/to/target") FileUtils.ln_s(target, link = "/path/to/symlink") assert_equal target, File.readlink(link) end def test_symlinks_in_different_directories FileUtils.mkdir_p("/path/to/bar") FileUtils.mkdir_p(target = "/path/to/foo/target") FileUtils.ln_s(target, link = "/path/to/bar/symlink") assert_equal target, File.readlink(link) end def test_symlink_with_relative_path_exists FileUtils.touch("/file") FileUtils.mkdir_p("/a/b") FileUtils.ln_s("../../file", link = "/a/b/symlink") assert File.exist?('/a/b/symlink') end def test_symlink_with_relative_path_and_nonexistant_file_does_not_exist FileUtils.touch("/file") FileUtils.mkdir_p("/a/b") FileUtils.ln_s("../../file_foo", link = "/a/b/symlink") assert !File.exist?('/a/b/symlink') end def test_symlink_with_relative_path_has_correct_target FileUtils.touch("/file") FileUtils.mkdir_p("/a/b") FileUtils.ln_s("../../file", link = "/a/b/symlink") assert_equal "../../file", File.readlink(link) end def test_symlinks_to_symlinks FileUtils.mkdir_p(target = "/path/to/foo/target") FileUtils.mkdir_p("/path/to/bar") FileUtils.mkdir_p("/path/to/bar2") FileUtils.ln_s(target, link1 = "/path/to/bar/symlink") FileUtils.ln_s(link1, link2 = "/path/to/bar2/symlink") assert_equal link1, File.readlink(link2) end def test_symlink_to_symlinks_should_raise_error_if_dir_doesnt_exist FileUtils.mkdir_p(target = "/path/to/foo/target") assert !Dir.exists?("/path/to/bar") assert_raise Errno::ENOENT do FileUtils.ln_s(target, "/path/to/bar/symlink") end end def test_knows_symlinks_are_symlinks FileUtils.mkdir_p(target = "/path/to/target") FileUtils.ln_s(target, link = "/path/to/symlink") assert File.symlink?(link) end def test_can_create_files_in_current_dir path = 'file.txt' File.open(path, 'w') do |f| f.write "Yatta!" end assert File.exists?(path) assert File.readable?(path) assert File.writable?(path) end def test_can_create_files_in_existing_dir FileUtils.mkdir_p "/path/to" path = "/path/to/file.txt" File.open(path, 'w') do |f| f.write "Yatta!" end assert File.exists?(path) assert File.readable?(path) assert File.writable?(path) end def test_raises_ENOENT_trying_to_create_files_in_nonexistent_dir path = "/path/to/file.txt" assert_raises(Errno::ENOENT) { File.open(path, 'w') do |f| f.write "Yatta!" end } end def test_raises_ENOENT_trying_to_create_files_in_relative_nonexistent_dir FileUtils.mkdir_p "/some/path" Dir.chdir("/some/path") { assert_raises(Errno::ENOENT) { File.open("../foo") {|f| f.write "moo" } } } end def test_raises_ENOENT_trying_to_create_files_in_obscured_nonexistent_dir FileUtils.mkdir_p "/some/path" assert_raises(Errno::ENOENT) { File.open("/some/path/../foo") {|f| f.write "moo" } } end def test_raises_ENOENT_trying_to_create_tilde_referenced_nonexistent_dir path = "~/fakefs_test_#{$$}_0000" while File.exist? path path = path.succ end assert_raises(Errno::ENOENT) { File.open("#{path}/foo") {|f| f.write "moo" } } end def test_raises_EISDIR_if_trying_to_open_existing_directory_name path = "/path/to" FileUtils.mkdir_p path assert_raises(Errno::EISDIR) { File.open(path, 'w') do |f| f.write "Yatta!" end } end def test_can_create_files_with_bitmasks FileUtils.mkdir_p("/path/to") 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 File.open("foo", "w") { |f| f << "foo" } f = File.open("foo") assert_raises(IOError) do f << "bar" 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") assert_raises(ArgumentError) do File.open("foo", "an_illegal_mode") end end def test_raises_error_when_cannot_find_file_in_read_mode assert_raises(Errno::ENOENT) do File.open("does_not_exist", "r") end end def test_raises_error_when_cannot_find_file_in_read_write_mode assert_raises(Errno::ENOENT) do File.open("does_not_exist", "r+") end end def test_creates_files_in_write_only_mode File.open("foo", "w") 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") end def test_creates_files_in_append_write_only File.open("foo", "a") assert File.exists?("foo") end def test_creates_files_in_append_read_write File.open("foo", "a+") 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_write_mode_truncates_existing_file File.open("foo", "w") { |f| f << "contents" } f = File.open("foo", "w") assert_equal "", File.read("foo") end def test_file_in_read_write_truncation_mode_truncates_file File.open("foo", "w") { |f| f << "foo" } f = File.open("foo", "w+") assert_equal "", File.read("foo") 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 = 'file.txt' File.open(path, 'w') do |f| f.write "Yatta!" end assert_equal "Yatta!", File.read(path) end def test_file_read_accepts_hashes path = 'file.txt' File.open(path, 'w') do |f| f.write 'Yatta!' end assert_nothing_raised { File.read(path, :mode => 'r:UTF-8:-') } end def test_can_write_to_files path = 'file.txt' File.open(path, 'w') do |f| f << 'Yada Yada' end assert_equal 'Yada Yada', File.read(path) end def test_raises_error_when_opening_with_binary_mode_only assert_raise ArgumentError do File.open("/foo", "b") end end def test_can_open_file_in_binary_mode File.open("foo", "wb") { |x| x << "a" } assert_equal "a", File.read("foo") end def test_can_chunk_io_when_reading FileUtils.mkdir_p "/path/to" path = '/path/to/file.txt' File.open(path, 'w') do |f| f << 'Yada Yada' end file = File.new(path, 'r') assert_equal 'Yada', file.read(4) assert_equal ' Yada', file.read(5) assert_equal '', file.read file.rewind assert_equal 'Yada Yada', file.read end def test_can_get_size_of_files path = 'file.txt' File.open(path, 'w') do |f| f << 'Yada Yada' end assert_equal 9, File.size(path) end def test_can_check_if_file_has_size? path = 'file.txt' File.open(path, 'w') do |f| f << 'Yada Yada' end assert File.size?(path) assert_nil File.size?("other.txt") end def test_can_check_size_of_empty_file path = 'file.txt' File.open(path, 'w') do |f| f << '' end assert_nil File.size?("file.txt") end def test_raises_error_on_mtime_if_file_does_not_exist assert_raise Errno::ENOENT do File.mtime('/path/to/file.txt') end end def test_can_return_mtime_on_existing_file path = 'file.txt' File.open(path, 'w') do |f| f << '' end assert File.mtime('file.txt').is_a?(Time) end def test_raises_error_on_ctime_if_file_does_not_exist assert_raise Errno::ENOENT do File.ctime('file.txt') end end def test_can_return_ctime_on_existing_file File.open("foo", "w") { |f| f << "some content" } assert File.ctime('foo').is_a?(Time) end def test_raises_error_on_atime_if_file_does_not_exist assert_raise Errno::ENOENT do File.atime('file.txt') end end def test_can_return_atime_on_existing_file File.open("foo", "w") { |f| f << "some content" } assert File.atime('foo').is_a?(Time) end def test_ctime_mtime_and_atime_are_equal_for_new_files FileUtils.touch('foo') ctime = File.ctime("foo") mtime = File.mtime("foo") atime = File.atime("foo") assert ctime.is_a?(Time) assert mtime.is_a?(Time) assert atime.is_a?(Time) assert_equal ctime, mtime assert_equal ctime, atime File.open("foo", "r") do |f| assert_equal ctime, f.ctime assert_equal mtime, f.mtime assert_equal atime, f.atime end end def test_ctime_mtime_and_atime_are_equal_for_new_directories FileUtils.mkdir_p("foo") ctime = File.ctime("foo") mtime = File.mtime("foo") atime = File.atime("foo") assert ctime.is_a?(Time) assert mtime.is_a?(Time) assert atime.is_a?(Time) assert_equal ctime, mtime assert_equal ctime, atime end def test_file_ctime_is_equal_to_file_stat_ctime File.open("foo", "w") { |f| f << "some content" } assert_equal File.stat("foo").ctime, File.ctime("foo") end def test_directory_ctime_is_equal_to_directory_stat_ctime FileUtils.mkdir_p("foo") assert_equal File.stat("foo").ctime, File.ctime("foo") end def test_file_mtime_is_equal_to_file_stat_mtime File.open("foo", "w") { |f| f << "some content" } assert_equal File.stat("foo").mtime, File.mtime("foo") end def test_directory_mtime_is_equal_to_directory_stat_mtime FileUtils.mkdir_p("foo") assert_equal File.stat("foo").mtime, File.mtime("foo") end def test_file_atime_is_equal_to_file_stat_atime File.open("foo", "w") { |f| f << "some content" } assert_equal File.stat("foo").atime, File.atime("foo") end def test_directory_atime_is_equal_to_directory_stat_atime FileUtils.mkdir_p("foo") assert_equal File.stat("foo").atime, File.atime("foo") end def test_utime_raises_error_if_path_does_not_exist assert_raise Errno::ENOENT do File.utime(Time.now, Time.now, '/path/to/file.txt') end end def test_can_call_utime_on_an_existing_file time = Time.now - 300 # Not now path = 'file.txt' File.open(path, 'w') do |f| f << '' end File.utime(time, time, path) assert_equal time, File.mtime('file.txt') assert_equal time, File.atime('file.txt') end def test_utime_returns_number_of_paths path1, path2 = 'file.txt', 'another_file.txt' [path1, path2].each do |path| File.open(path, 'w') do |f| f << '' end end assert_equal 2, File.utime(Time.now, Time.now, path1, path2) end def test_file_a_time_updated_when_file_is_read old_atime = Time.now - 300 path = "file.txt" File.open(path, "w") do |f| f << "Hello" end File.utime(old_atime, File.mtime(path), path) assert_equal File.atime(path), old_atime File.read(path) assert File.atime(path) != old_atime end def test_can_read_with_File_readlines path = 'file.txt' File.open(path, 'w') do |f| f.puts "Yatta!", "Gatta!" f.puts ["woot","toot"] end assert_equal %w(Yatta! Gatta! woot toot), File.readlines(path) end def test_File_close_disallows_further_access path = 'file.txt' file = File.open(path, 'w') file.write 'Yada' file.close assert_raise IOError do file.read end end def test_File_close_disallows_further_writes path = 'file.txt' file = File.open(path, 'w') file.write 'Yada' file.close assert_raise IOError do file << "foo" end end def test_can_read_from_file_objects path = 'file.txt' File.open(path, 'w') do |f| f.write "Yatta!" end assert_equal "Yatta!", File.new(path).read end if RUBY_VERSION >= "1.9" def test_file_object_has_default_external_encoding Encoding.default_external = "UTF-8" path = 'file.txt' File.open(path, 'w'){|f| f.write 'Yatta!' } assert_equal "UTF-8", File.new(path).read.encoding.name end end def test_file_object_initialization_with_mode_in_hash_parameter assert_nothing_raised do File.open("file.txt", {:mode => "w"}){ |f| f.write 'Yatta!' } end end def test_file_read_errors_appropriately assert_raise Errno::ENOENT do File.read('anything') end end def test_knows_files_are_files path = 'file.txt' File.open(path, 'w') do |f| f.write "Yatta!" end assert File.file?(path) end def test_File_io_returns_self f = File.open("foo", "w") assert_equal f, f.to_io end def test_File_to_i_is_alias_for_filno f = File.open("foo", "w") assert_equal f.method(:to_i), f.method(:fileno) end def test_knows_symlink_files_are_files path = 'file.txt' File.open(path, 'w') do |f| f.write "Yatta!" end FileUtils.ln_s path, sympath='/sympath' assert File.file?(sympath) end def test_knows_non_existent_files_arent_files assert_equal RealFile.file?('does/not/exist.txt'), File.file?('does/not/exist.txt') end def test_can_chown_files good = 'file.txt' bad = 'nofile.txt' File.open(good,'w') { |f| f.write "foo" } username = Etc.getpwuid(Process.uid).name groupname = Etc.getgrgid(Process.gid).name out = FileUtils.chown(1337, 1338, good, :verbose => true) assert_equal [good], out assert_equal File.stat(good).uid, 1337 assert_equal File.stat(good).gid, 1338 assert_raises(Errno::ENOENT) do FileUtils.chown(username, groupname, bad, :verbose => true) end assert_equal [good], FileUtils.chown(username, groupname, good) assert_equal File.stat(good).uid, Process.uid assert_equal File.stat(good).gid, Process.gid assert_raises(Errno::ENOENT) do FileUtils.chown(username, groupname, bad) end assert_equal [good], FileUtils.chown(username, groupname, [good]) assert_equal File.stat(good).uid, Process.uid assert_equal File.stat(good).gid, Process.gid assert_raises(Errno::ENOENT) do FileUtils.chown(username, groupname, [good, bad]) end # FileUtils.chown with nil user and nil group should not change anything FileUtils.chown(username, groupname, good) assert_equal File.stat(good).uid, Process.uid assert_equal File.stat(good).gid, Process.gid assert_equal [good], FileUtils.chown(nil, nil, [good]) assert_equal File.stat(good).uid, Process.uid assert_equal File.stat(good).gid, Process.gid assert_raises(Errno::ENOENT) do FileUtils.chown(nil, nil, [good, bad]) end end def test_can_chown_R_files username = Etc.getpwuid(Process.uid).name groupname = Etc.getgrgid(Process.gid).name FileUtils.mkdir_p '/path/' File.open('/path/foo', 'w') { |f| f.write 'foo' } File.open('/path/foobar', 'w') { |f| f.write 'foo' } assert_equal ['/path'], FileUtils.chown_R(username, groupname, '/path') %w(/path /path/foo /path/foobar).each do |f| assert_equal File.stat(f).uid, Process.uid assert_equal File.stat(f).gid, Process.gid end end def test_can_chmod_files good = "file.txt" bad = "nofile.txt" FileUtils.touch(good) assert_equal [good], FileUtils.chmod(0600, good, :verbose => true) assert_equal File.stat(good).mode, 0100600 assert_raises(Errno::ENOENT) do FileUtils.chmod(0600, bad) end assert_equal [good], FileUtils.chmod(0666, good) assert_equal File.stat(good).mode, 0100666 assert_raises(Errno::ENOENT) do FileUtils.chmod(0666, bad) end assert_equal [good], FileUtils.chmod(0644, [good]) assert_equal File.stat(good).mode, 0100644 assert_raises(Errno::ENOENT) do FileUtils.chmod(0644, bad) end end def test_can_chmod_R_files FileUtils.mkdir_p "/path/sub" FileUtils.touch "/path/file1" FileUtils.touch "/path/sub/file2" assert_equal ["/path"], FileUtils.chmod_R(0600, "/path") assert_equal File.stat("/path").mode, 0100600 assert_equal File.stat("/path/file1").mode, 0100600 assert_equal File.stat("/path/sub").mode, 0100600 assert_equal File.stat("/path/sub/file2").mode, 0100600 FileUtils.mkdir_p "/path2" FileUtils.touch "/path2/hej" assert_equal ["/path2"], FileUtils.chmod_R(0600, "/path2") end def test_dir_globs_paths FileUtils.mkdir_p '/path' File.open('/path/foo', 'w') { |f| f.write 'foo' } File.open('/path/foobar', 'w') { |f| f.write 'foo' } FileUtils.mkdir_p '/path/bar' File.open('/path/bar/baz', 'w') { |f| f.write 'foo' } FileUtils.cp_r '/path/bar', '/path/bar2' assert_equal ['/path'], Dir['/path'] assert_equal %w( /path/bar /path/bar2 /path/foo /path/foobar ), Dir['/path/*'] assert_equal ['/path/bar/baz'], Dir['/path/bar/*'] assert_equal ['/path/foo'], Dir['/path/foo'] assert_equal ['/path'], Dir['/path*'] assert_equal ['/path/foo', '/path/foobar'], Dir['/p*h/foo*'] assert_equal ['/path/foo', '/path/foobar'], Dir['/p??h/foo*'] assert_equal ['/path/bar', '/path/bar/baz', '/path/bar2', '/path/bar2/baz', '/path/foo', '/path/foobar'], Dir['/path/**/*'] assert_equal ['/path', '/path/bar', '/path/bar/baz', '/path/bar2', '/path/bar2/baz', '/path/foo', '/path/foobar'], Dir['/**/*'] assert_equal ['/path/bar', '/path/bar/baz', '/path/bar2', '/path/bar2/baz', '/path/foo', '/path/foobar'], Dir['/path/**/*'] assert_equal ['/path/bar/baz'], Dir['/path/bar/**/*'] assert_equal ['/path/bar/baz', '/path/bar2/baz'], Dir['/path/bar/**/*', '/path/bar2/**/*'] assert_equal ['/path/bar/baz', '/path/bar2/baz', '/path/bar/baz'], Dir['/path/ba*/**/*', '/path/bar/**/*'] FileUtils.cp_r '/path', '/otherpath' assert_equal %w( /otherpath/foo /otherpath/foobar /path/foo /path/foobar ), Dir['/*/foo*'] assert_equal ['/path/bar', '/path/foo'], Dir['/path/{foo,bar}'] assert_equal ['/path/bar', '/path/bar2'], Dir['/path/bar{2,}'] Dir.chdir '/path' do assert_equal ['foo'], Dir['foo'] end end def test_dir_glob_handles_root FileUtils.mkdir_p '/path' # this fails. the root dir should be named '/' but it is '.' assert_equal ['/'], Dir['/'] end def test_dir_glob_handles_recursive_globs FileUtils.mkdir_p "/one/two/three" File.open('/one/two/three/four.rb', 'w') File.open('/one/five.rb', 'w') assert_equal ['/one/five.rb', '/one/two/three/four.rb'], Dir['/one/**/*.rb'] assert_equal ['/one/two'], Dir['/one/**/two'] assert_equal ['/one/two/three'], Dir['/one/**/three'] end def test_dir_recursive_glob_ending_in_wildcards_returns_both_files_and_dirs FileUtils.mkdir_p "/one/two/three" File.open('/one/two/three/four.rb', 'w') File.open('/one/five.rb', 'w') assert_equal ['/one/five.rb', '/one/two', '/one/two/three', '/one/two/three/four.rb'], Dir['/one/**/*'] assert_equal ['/one/five.rb', '/one/two'], Dir['/one/**'] end def test_dir_glob_with_block FileUtils.touch('foo') FileUtils.touch('bar') yielded = [] Dir.glob('*') { |file| yielded << file } assert_equal 2, yielded.size end if RUBY_VERSION >= "1.9" def test_dir_home assert_equal RealDir.home, Dir.home end end def test_should_report_pos_as_0_when_opening File.open("foo", "w") do |f| f << "foobar" f.rewind assert_equal 0, f.pos end end def test_should_report_pos_as_1_when_seeking_one_char File.open("foo", "w") do |f| f << "foobar" f.rewind f.seek(1) assert_equal 1, f.pos end end def test_should_set_pos File.open("foo", "w") do |f| f << "foo" end fp = File.open("foo", "r") fp.pos = 1 assert_equal 1, fp.pos end def test_should_set_pos_with_tell_method File.open("foo", "w") do |f| f << "foo" end fp = File.open("foo", "r") fp.tell = 1 assert_equal 1, fp.pos end def test_every_method_in_file_is_in_fake_fs_file RealFile.instance_methods.each do |method_name| assert File.instance_methods.include?(method_name), "#{method_name} method is not available in File :(" end end def test_file_should_not_respond_to_string_io_unique_methods uniq_string_io_methods = StringIO.instance_methods - RealFile.instance_methods uniq_string_io_methods.each do |method_name| assert !File.instance_methods.include?(method_name), "File responds to #{method_name}" end end def test_does_not_remove_methods_from_stringio stringio = StringIO.new("foo") assert stringio.respond_to?(:size) end def test_chdir_changes_directories_like_a_boss # I know memes! FileUtils.mkdir_p '/path' assert_equal '/', FileSystem.fs.name assert_equal [], Dir.glob('/path/*') Dir.chdir '/path' do File.open('foo', 'w') { |f| f.write 'foo'} File.open('foobar', 'w') { |f| f.write 'foo'} end assert_equal '/', FileSystem.fs.name assert_equal(['/path/foo', '/path/foobar'], Dir.glob('/path/*').sort) c = nil Dir.chdir '/path' do c = File.open('foo', 'r') { |f| f.read } end assert_equal 'foo', c end def test_chdir_shouldnt_keep_us_from_absolute_paths FileUtils.mkdir_p '/path' Dir.chdir '/path' do File.open('foo', 'w') { |f| f.write 'foo'} File.open('/foobar', 'w') { |f| f.write 'foo'} end assert_equal ['/path/foo'], Dir.glob('/path/*').sort assert_equal ['/foobar', '/path'], Dir.glob('/*').sort Dir.chdir '/path' do FileUtils.rm('foo') FileUtils.rm('/foobar') end assert_equal [], Dir.glob('/path/*').sort assert_equal ['/path'], Dir.glob('/*').sort end def test_chdir_should_be_nestable FileUtils.mkdir_p '/path/me' Dir.chdir '/path' do File.open('foo', 'w') { |f| f.write 'foo'} Dir.chdir 'me' do File.open('foobar', 'w') { |f| f.write 'foo'} end end assert_equal ['/path/foo','/path/me'], Dir.glob('/path/*').sort assert_equal ['/path/me/foobar'], Dir.glob('/path/me/*').sort end def test_chdir_should_flop_over_and_die_if_the_dir_doesnt_exist assert_raise(Errno::ENOENT) do Dir.chdir('/nope') do 1 end end end def test_chdir_shouldnt_lose_state_because_of_errors FileUtils.mkdir_p '/path' Dir.chdir '/path' do File.open('foo', 'w') { |f| f.write 'foo'} File.open('foobar', 'w') { |f| f.write 'foo'} end begin Dir.chdir('/path') do raise Exception end rescue Exception # hardcore end Dir.chdir('/path') do begin Dir.chdir('nope'){ } rescue Errno::ENOENT end assert_equal ['/path'], FileSystem.dir_levels end assert_equal(['/path/foo', '/path/foobar'], Dir.glob('/path/*').sort) end def test_chdir_with_no_block_is_awesome FileUtils.mkdir_p '/path' Dir.chdir('/path') FileUtils.mkdir_p 'subdir' assert_equal ['subdir'], Dir.glob('*') Dir.chdir('subdir') File.open('foo', 'w') { |f| f.write 'foo'} assert_equal ['foo'], Dir.glob('*') assert_raises(Errno::ENOENT) do Dir.chdir('subsubdir') end assert_equal ['foo'], Dir.glob('*') end def test_current_dir_reflected_by_pwd FileUtils.mkdir_p '/path' Dir.chdir('/path') assert_equal '/path', Dir.pwd assert_equal '/path', Dir.getwd FileUtils.mkdir_p 'subdir' Dir.chdir('subdir') assert_equal '/path/subdir', Dir.pwd assert_equal '/path/subdir', Dir.getwd end def test_file_open_defaults_to_read File.open('foo','w') { |f| f.write 'bar' } assert_equal 'bar', File.open('foo') { |f| f.read } end def test_flush_exists_on_file r = File.open('foo','w') { |f| f.write 'bar'; f.flush } assert_equal 'foo', r.path end def test_mv_should_raise_error_on_missing_file assert_raise(Errno::ENOENT) do FileUtils.mv 'blafgag', 'foo' end exception = assert_raise(Errno::ENOENT) do FileUtils.mv ['foo', 'bar'], 'destdir' end assert_equal "No such file or directory - foo", exception.message end def test_mv_actually_works File.open('foo', 'w') { |f| f.write 'bar' } FileUtils.mv 'foo', 'baz' assert_equal 'bar', File.open('baz') { |f| f.read } end def test_mv_overwrites_existing_files File.open('foo', 'w') { |f| f.write 'bar' } File.open('baz', 'w') { |f| f.write 'qux' } FileUtils.mv 'foo', 'baz' assert_equal 'bar', File.read('baz') end def test_mv_works_with_options File.open('foo', 'w') {|f| f.write 'bar'} FileUtils.mv 'foo', 'baz', :force => true assert_equal('bar', File.open('baz') { |f| f.read }) end def test_mv_to_directory File.open('foo', 'w') {|f| f.write 'bar'} FileUtils.mkdir_p 'destdir' FileUtils.mv 'foo', 'destdir' assert_equal('bar', File.open('destdir/foo') {|f| f.read }) assert File.directory?('destdir') end def test_mv_array File.open('foo', 'w') {|f| f.write 'bar' } File.open('baz', 'w') {|f| f.write 'binky' } FileUtils.mkdir_p 'destdir' FileUtils.mv %w(foo baz), 'destdir' assert_equal('bar', File.open('destdir/foo') {|f| f.read }) assert_equal('binky', File.open('destdir/baz') {|f| f.read }) end def test_cp_actually_works File.open('foo', 'w') {|f| f.write 'bar' } FileUtils.cp('foo', 'baz') assert_equal 'bar', File.read('baz') end def test_cp_file_into_dir File.open('foo', 'w') {|f| f.write 'bar' } FileUtils.mkdir_p 'baz' FileUtils.cp('foo', 'baz') assert_equal 'bar', File.read('baz/foo') end def test_cp_array_of_files_into_directory File.open('foo', 'w') { |f| f.write 'footext' } File.open('bar', 'w') { |f| f.write 'bartext' } FileUtils.mkdir_p 'destdir' FileUtils.cp(%w(foo bar), 'destdir') assert_equal 'footext', File.read('destdir/foo') assert_equal 'bartext', File.read('destdir/bar') end def test_cp_fails_on_array_of_files_into_non_directory File.open('foo', 'w') { |f| f.write 'footext' } exception = assert_raise(Errno::ENOTDIR) do FileUtils.cp(%w(foo), 'baz') end assert_equal "Not a directory - baz", exception.to_s end def test_cp_overwrites_dest_file File.open('foo', 'w') {|f| f.write 'FOO' } File.open('bar', 'w') {|f| f.write 'BAR' } FileUtils.cp('foo', 'bar') assert_equal 'FOO', File.read('bar') end def test_cp_fails_on_no_source assert_raise Errno::ENOENT do FileUtils.cp('foo', 'baz') end end def test_cp_fails_on_directory_copy FileUtils.mkdir_p 'baz' assert_raise Errno::EISDIR do FileUtils.cp('baz', 'bar') end end def test_cp_r_doesnt_tangle_files_together File.open('foo', 'w') { |f| f.write 'bar' } FileUtils.cp_r('foo', 'baz') File.open('baz', 'w') { |f| f.write 'quux' } assert_equal 'bar', File.open('foo') { |f| f.read } end def test_cp_r_should_raise_error_on_missing_file # Yes, this error sucks, but it conforms to the original Ruby # method. assert_raise(RuntimeError) do FileUtils.cp_r 'blafgag', 'foo' end end def test_cp_r_handles_copying_directories FileUtils.mkdir_p 'subdir' Dir.chdir('subdir'){ File.open('foo', 'w') { |f| f.write 'footext' } } FileUtils.mkdir_p 'baz' # To a previously uncreated directory FileUtils.cp_r('subdir', 'quux') assert_equal 'footext', File.open('quux/foo') { |f| f.read } # To a directory that already exists FileUtils.cp_r('subdir', 'baz') assert_equal 'footext', File.open('baz/subdir/foo') { |f| f.read } # To a subdirectory of a directory that does not exist assert_raises(Errno::ENOENT) do FileUtils.cp_r('subdir', 'nope/something') end end def test_cp_r_array_of_files FileUtils.mkdir_p 'subdir' File.open('foo', 'w') { |f| f.write 'footext' } File.open('bar', 'w') { |f| f.write 'bartext' } FileUtils.cp_r(%w(foo bar), 'subdir') assert_equal 'footext', File.open('subdir/foo') { |f| f.read } assert_equal 'bartext', File.open('subdir/bar') { |f| f.read } end def test_cp_r_array_of_directories %w(foo bar subdir).each { |d| FileUtils.mkdir_p d } File.open('foo/baz', 'w') { |f| f.write 'baztext' } File.open('bar/quux', 'w') { |f| f.write 'quuxtext' } FileUtils.cp_r(%w(foo bar), 'subdir') assert_equal 'baztext', File.open('subdir/foo/baz') { |f| f.read } assert_equal 'quuxtext', File.open('subdir/bar/quux') { |f| f.read } end def test_cp_r_only_copies_into_directories FileUtils.mkdir_p 'subdir' Dir.chdir('subdir') { File.open('foo', 'w') { |f| f.write 'footext' } } File.open('bar', 'w') { |f| f.write 'bartext' } assert_raises(Errno::EEXIST) do FileUtils.cp_r 'subdir', 'bar' end FileUtils.mkdir_p 'otherdir' FileUtils.ln_s 'otherdir', 'symdir' FileUtils.cp_r 'subdir', 'symdir' assert_equal 'footext', File.open('symdir/subdir/foo') { |f| f.read } end def test_cp_r_sets_parent_correctly FileUtils.mkdir_p '/path/foo' File.open('/path/foo/bar', 'w') { |f| f.write 'foo' } File.open('/path/foo/baz', 'w') { |f| f.write 'foo' } FileUtils.cp_r '/path/foo', '/path/bar' assert File.exists?('/path/bar/baz') FileUtils.rm_rf '/path/bar/baz' assert_equal %w( /path/bar/bar ), Dir['/path/bar/*'] end def test_clone_clones_normal_files RealFile.open(here('foo'), 'w') { |f| f.write 'bar' } assert !File.exists?(here('foo')) FileSystem.clone(here('foo')) assert_equal 'bar', File.open(here('foo')) { |f| f.read } ensure RealFile.unlink(here('foo')) if RealFile.exists?(here('foo')) end def test_clone_clones_directories act_on_real_fs { RealFileUtils.mkdir_p(here('subdir')) } FileSystem.clone(here('subdir')) assert File.exists?(here('subdir')), 'subdir was cloned' assert File.directory?(here('subdir')), 'subdir is a directory' ensure act_on_real_fs { RealFileUtils.rm_rf(here('subdir')) } end def test_clone_clones_dot_files_even_hard_to_find_ones act_on_real_fs { RealFileUtils.mkdir_p(here('subdir/.bar/baz/.quux/foo')) } assert !File.exists?(here('subdir')) FileSystem.clone(here('subdir')) assert_equal ['.', '..', '.bar'], Dir.entries(here('subdir')) assert_equal ['.', '..', 'foo'], Dir.entries(here('subdir/.bar/baz/.quux')) ensure act_on_real_fs { RealFileUtils.rm_rf(here('subdir')) } end def test_dir_glob_on_clone_with_absolute_path act_on_real_fs { RealFileUtils.mkdir_p(here('subdir/.bar/baz/.quux/foo')) } FileUtils.mkdir_p '/path' Dir.chdir('/path') FileSystem.clone(here('subdir'), "/foo") assert Dir.glob "/foo/*" ensure act_on_real_fs { RealFileUtils.rm_rf(here('subdir')) } end def test_clone_with_target_specified act_on_real_fs { RealFileUtils.mkdir_p(here('subdir/.bar/baz/.quux/foo')) } assert !File.exists?(here('subdir')) FileSystem.clone(here('subdir'), here('subdir2')) assert !File.exists?(here('subdir')) assert_equal ['.', '..', '.bar'], Dir.entries(here('subdir2')) assert_equal ['.', '..', 'foo'], Dir.entries(here('subdir2/.bar/baz/.quux')) ensure act_on_real_fs { RealFileUtils.rm_rf(here('subdir')) } end def test_putting_a_dot_at_end_copies_the_contents FileUtils.mkdir_p 'subdir' Dir.chdir('subdir') { File.open('foo', 'w') { |f| f.write 'footext' } } FileUtils.mkdir_p 'newdir' FileUtils.cp_r 'subdir/.', 'newdir' assert_equal 'footext', File.open('newdir/foo') { |f| f.read } end def test_file_can_read_from_symlinks File.open('first', 'w') { |f| f.write '1'} FileUtils.ln_s 'first', 'one' assert_equal '1', File.open('one') { |f| f.read } FileUtils.mkdir_p 'subdir' File.open('subdir/nother','w') { |f| f.write 'works' } FileUtils.ln_s 'subdir', 'new' assert_equal 'works', File.open('new/nother') { |f| f.read } end def test_can_symlink_through_file FileUtils.touch("/foo") File.symlink("/foo", "/bar") assert File.symlink?("/bar") end def test_files_can_be_touched FileUtils.touch('touched_file') assert File.exists?('touched_file') list = ['newfile', 'another'] FileUtils.touch(list) list.each { |fp| assert(File.exists?(fp)) } end def test_touch_does_not_work_if_the_dir_path_cannot_be_found assert_raises(Errno::ENOENT) do FileUtils.touch('this/path/should/not/be/here') end FileUtils.mkdir_p('subdir') list = ['subdir/foo', 'nosubdir/bar'] assert_raises(Errno::ENOENT) do FileUtils.touch(list) end end def test_extname assert File.extname("test.doc") == ".doc" end # Directory tests def test_new_directory FileUtils.mkdir_p('/this/path/should/be/here') assert_nothing_raised do Dir.new('/this/path/should/be/here') end end def test_new_directory_does_not_work_if_dir_path_cannot_be_found assert_raises(Errno::ENOENT) do Dir.new('/this/path/should/not/be/here') end end def test_directory_close FileUtils.mkdir_p('/this/path/should/be/here') dir = Dir.new('/this/path/should/be/here') assert dir.close.nil? assert_raises(IOError) do dir.each { |dir| dir } end end def test_directory_each test = ['.', '..', 'file_1', 'file_2', 'file_3', 'file_4', 'file_5' ] FileUtils.mkdir_p('/this/path/should/be/here') test.each do |f| FileUtils.touch("/this/path/should/be/here/#{f}") end dir = Dir.new('/this/path/should/be/here') yielded = [] dir.each do |dir| yielded << dir end assert yielded.size == test.size test.each { |t| assert yielded.include?(t) } end def test_directory_path FileUtils.mkdir_p('/this/path/should/be/here') good_path = '/this/path/should/be/here' assert_equal good_path, Dir.new('/this/path/should/be/here').path end def test_directory_pos test = ['.', '..', 'file_1', 'file_2', 'file_3', 'file_4', 'file_5' ] FileUtils.mkdir_p('/this/path/should/be/here') test.each do |f| FileUtils.touch("/this/path/should/be/here/#{f}") end dir = Dir.new('/this/path/should/be/here') assert dir.pos == 0 dir.read assert dir.pos == 1 dir.read assert dir.pos == 2 dir.read assert dir.pos == 3 dir.read assert dir.pos == 4 dir.read assert dir.pos == 5 end def test_directory_pos_assign test = ['.', '..', 'file_1', 'file_2', 'file_3', 'file_4', 'file_5' ] FileUtils.mkdir_p('/this/path/should/be/here') test.each do |f| FileUtils.touch("/this/path/should/be/here/#{f}") end dir = Dir.new('/this/path/should/be/here') assert dir.pos == 0 dir.pos = 2 assert dir.pos == 2 end def test_directory_read test = ['.', '..', 'file_1', 'file_2', 'file_3', 'file_4', 'file_5' ] FileUtils.mkdir_p('/this/path/should/be/here') test.each do |f| FileUtils.touch("/this/path/should/be/here/#{f}") end dir = Dir.new('/this/path/should/be/here') assert dir.pos == 0 d = dir.read assert dir.pos == 1 assert d == '.' d = dir.read assert dir.pos == 2 assert d == '..' end def test_directory_read_past_length test = ['.', '..', 'file_1', 'file_2', 'file_3', 'file_4', 'file_5' ] FileUtils.mkdir_p('/this/path/should/be/here') test.each do |f| FileUtils.touch("/this/path/should/be/here/#{f}") end dir = Dir.new('/this/path/should/be/here') d = dir.read assert_not_nil d d = dir.read assert_not_nil d d = dir.read assert_not_nil d d = dir.read assert_not_nil d d = dir.read assert_not_nil d d = dir.read assert_not_nil d d = dir.read assert_not_nil d d = dir.read assert_nil d end def test_directory_rewind test = ['.', '..', 'file_1', 'file_2', 'file_3', 'file_4', 'file_5' ] FileUtils.mkdir_p('/this/path/should/be/here') test.each do |f| FileUtils.touch("/this/path/should/be/here/#{f}") end dir = Dir.new('/this/path/should/be/here') d = dir.read d = dir.read assert dir.pos == 2 dir.rewind assert dir.pos == 0 end def test_directory_seek test = ['.', '..', 'file_1', 'file_2', 'file_3', 'file_4', 'file_5' ] FileUtils.mkdir_p('/this/path/should/be/here') test.each do |f| FileUtils.touch("/this/path/should/be/here/#{f}") end dir = Dir.new('/this/path/should/be/here') d = dir.seek 1 assert d == '..' assert dir.pos == 1 end def test_directory_class_delete FileUtils.mkdir_p('/this/path/should/be/here') Dir.delete('/this/path/should/be/here') assert File.exists?('/this/path/should/be/here') == false end def test_directory_class_delete_does_not_act_on_non_empty_directory test = ['.', '..', 'file_1', 'file_2', 'file_3', 'file_4', 'file_5' ] FileUtils.mkdir_p('/this/path/should/be/here') test.each do |f| FileUtils.touch("/this/path/should/be/here/#{f}") end assert_raises(Errno::ENOTEMPTY) do Dir.delete('/this/path/should/be/here') end end def test_directory_class_delete_does_not_work_if_dir_path_cannot_be_found assert_raises(Errno::ENOENT) do Dir.delete('/this/path/should/not/be/here') end end def test_directory_entries test = ['.', '..', 'file_1', 'file_2', 'file_3', 'file_4', 'file_5' ] FileUtils.mkdir_p('/this/path/should/be/here') test.each do |f| FileUtils.touch("/this/path/should/be/here/#{f}") end yielded = Dir.entries('/this/path/should/be/here') assert yielded.size == test.size test.each { |t| assert yielded.include?(t) } end def test_directory_entries_works_with_trailing_slash test = ['.', '..', 'file_1', 'file_2', 'file_3', 'file_4', 'file_5' ] FileUtils.mkdir_p('/this/path/should/be/here') test.each do |f| FileUtils.touch("/this/path/should/be/here/#{f}") end yielded = Dir.entries('/this/path/should/be/here/') assert yielded.size == test.size test.each { |t| assert yielded.include?(t) } end def test_directory_entries_does_not_work_if_dir_path_cannot_be_found assert_raises(Errno::ENOENT) do Dir.delete('/this/path/should/not/be/here') end end def test_directory_foreach test = ['.', '..', 'file_1', 'file_2', 'file_3', 'file_4', 'file_5' ] FileUtils.mkdir_p('/this/path/should/be/here') test.each do |f| FileUtils.touch("/this/path/should/be/here/#{f}") end yielded = [] Dir.foreach('/this/path/should/be/here') do |dir| yielded << dir end assert yielded.size == test.size test.each { |t| assert yielded.include?(t) } end def test_directory_mkdir Dir.mkdir('/path') assert File.exists?('/path') end def test_directory_mkdir_nested Dir.mkdir("/tmp") Dir.mkdir("/tmp/stream20120103-11847-xc8pb.lock") assert File.exists?("/tmp/stream20120103-11847-xc8pb.lock") end def test_can_create_subdirectories_with_dir_mkdir Dir.mkdir 'foo' Dir.mkdir 'foo/bar' assert Dir.exists?('foo/bar') end def test_can_create_absolute_subdirectories_with_dir_mkdir Dir.mkdir '/foo' Dir.mkdir '/foo/bar' assert Dir.exists?('/foo/bar') end def test_can_create_directories_starting_with_dot Dir.mkdir './path' assert File.exists? './path' end def test_directory_mkdir_relative FileUtils.mkdir_p('/new/root') FileSystem.chdir('/new/root') Dir.mkdir('path') assert File.exists?('/new/root/path') end def test_directory_mkdir_not_recursive assert_raises(Errno::ENOENT) do Dir.mkdir('/path/does/not/exist') end end def test_mkdir_raises_error_if_already_created Dir.mkdir "foo" assert_raises(Errno::EEXIST) do Dir.mkdir "foo" end end def test_directory_open test = ['.', '..', 'file_1', 'file_2', 'file_3', 'file_4', 'file_5' ] FileUtils.mkdir_p('/this/path/should/be/here') test.each do |f| FileUtils.touch("/this/path/should/be/here/#{f}") end dir = Dir.open('/this/path/should/be/here') assert dir.path == '/this/path/should/be/here' end def test_directory_open_block test = ['.', '..', 'file_1', 'file_2', 'file_3', 'file_4', 'file_5' ] FileUtils.mkdir_p('/this/path/should/be/here') test.each do |f| FileUtils.touch("/this/path/should/be/here/#{f}") end yielded = [] Dir.open('/this/path/should/be/here') do |dir| yielded << dir end assert yielded.size == test.size test.each { |t| assert yielded.include?(t) } end def test_tmpdir 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") File.link("/foo", "/bar") assert File.exists?("/bar") end def test_hard_link_with_missing_file_raises_error assert_raises(Errno::ENOENT) do File.link("/foo", "/bar") end end def test_hard_link_with_existing_destination_file FileUtils.touch("/foo") FileUtils.touch("/bar") assert_raises(Errno::EEXIST) do File.link("/foo", "/bar") end end def test_hard_link_returns_0_when_successful FileUtils.touch("/foo") assert_equal 0, File.link("/foo", "/bar") end def test_hard_link_returns_duplicate_file File.open("/foo", "w") { |x| x << "some content" } File.link("/foo", "/bar") assert_equal "some content", File.read("/bar") end def test_hard_link_with_directory_raises_error Dir.mkdir "/foo" assert_raises(Errno::EPERM) do File.link("/foo", "/bar") end end def test_file_stat_returns_file_stat_object FileUtils.touch("/foo") assert_equal File::Stat, File.stat("/foo").class end def test_can_delete_file_with_delete FileUtils.touch("/foo") File.delete("/foo") assert !File.exists?("/foo") end def test_can_delete_multiple_files_with_delete FileUtils.touch("/foo") FileUtils.touch("/bar") File.delete("/foo", "/bar") assert !File.exists?("/foo") assert !File.exists?("/bar") end def test_delete_raises_argument_error_with_no_filename_given assert_raises ArgumentError do File.delete end end def test_delete_returns_number_one_when_given_one_arg FileUtils.touch("/foo") assert_equal 1, File.delete("/foo") end def test_delete_returns_number_two_when_given_two_args FileUtils.touch("/foo") FileUtils.touch("/bar") assert_equal 2, File.delete("/foo", "/bar") end def test_delete_raises_error_when_first_file_does_not_exist assert_raises Errno::ENOENT do File.delete("/foo") end end def test_unlink_is_alias_for_delete assert_equal File.method(:unlink), File.method(:delete) end def test_unlink_removes_only_one_file_content File.open("/foo", "w") { |f| f << "some_content" } File.link("/foo", "/bar") File.unlink("/bar") assert_equal "some_content", File.read("/foo") end def test_link_reports_correct_stat_info_after_unlinking File.open("/foo", "w") { |f| f << "some_content" } File.link("/foo", "/bar") File.unlink("/bar") assert_equal 1, File.stat("/foo").nlink end def test_delete_works_with_symlink FileUtils.touch("/foo") File.symlink("/foo", "/bar") File.unlink("/bar") assert File.exists?("/foo") assert !File.exists?("/bar") end def test_delete_works_with_symlink_source FileUtils.touch("/foo") File.symlink("/foo", "/bar") File.unlink("/foo") assert !File.exists?("/foo") end def test_file_seek_returns_0 File.open("/foo", "w") do |f| f << "one\ntwo\nthree" end file = File.open("/foo", "r") assert_equal 0, file.seek(1) end def test_file_seek_seeks_to_location File.open("/foo", "w") do |f| f << "123" end file = File.open("/foo", "r") file.seek(1) assert_equal "23", file.read end def test_file_seek_seeks_to_correct_location File.open("/foo", "w") do |f| f << "123" end file = File.open("/foo", "r") file.seek(2) assert_equal "3", file.read end def test_file_seek_can_take_negative_offset File.open("/foo", "w") do |f| f << "123456789" end file = File.open("/foo", "r") file.seek(-1, IO::SEEK_END) assert_equal "9", file.read file.seek(-2, IO::SEEK_END) assert_equal "89", file.read file.seek(-3, IO::SEEK_END) assert_equal "789", file.read end def test_should_have_constants_inherited_from_descending_from_io assert_equal IO::SEEK_CUR, File::SEEK_CUR assert_equal IO::SEEK_END, File::SEEK_END assert_equal IO::SEEK_SET, File::SEEK_SET end def test_filetest_exists_return_correct_values FileUtils.mkdir_p("/path/to/dir") assert FileTest.exist?("/path/to/") FileUtils.rmdir("/path/to/dir") assert !FileTest.exist?("/path/to/dir") end def test_filetest_directory_returns_correct_values FileUtils.mkdir_p '/path/to/somedir' assert FileTest.directory?('/path/to/somedir') FileUtils.rm_r '/path/to/somedir' assert !FileTest.directory?('/path/to/somedir') end def test_filetest_file_returns_correct_values FileUtils.mkdir_p("/path/to") path = '/path/to/file.txt' File.open(path, 'w') { |f| f.write "Yatta!" } assert FileTest.file?(path) FileUtils.rm path assert !FileTest.file?(path) FileUtils.mkdir_p '/path/to/somedir' assert !FileTest.file?('/path/to/somedir') end def test_pathname_exists_returns_correct_value FileUtils.touch "foo" assert Pathname.new("foo").exist? assert !Pathname.new("bar").exist? end def test_dir_mktmpdir FileUtils.mkdir '/tmp' tmpdir = Dir.mktmpdir assert File.directory?(tmpdir) FileUtils.rm_r tmpdir Dir.mktmpdir do |t| tmpdir = t assert File.directory?(t) end assert !File.directory?(tmpdir) end def test_activating_returns_true FakeFS.deactivate! assert_equal true, FakeFS.activate! end def test_deactivating_returns_true assert_equal true, FakeFS.deactivate! end def test_split assert File.respond_to? :split filename = "/this/is/what/we/expect.txt" path,filename = File.split(filename) assert_equal path, "/this/is/what/we" assert_equal filename, "expect.txt" end ######################### def test_file_default_mode FileUtils.touch "foo" assert_equal File.stat("foo").mode, (0100000 + 0666 - File.umask) end def test_dir_default_mode Dir.mkdir "bar" assert_equal File.stat("bar").mode, (0100000 + 0777 - File.umask) end def test_file_default_uid_and_gid FileUtils.touch "foo" assert_equal File.stat("foo").uid, Process.uid assert_equal File.stat("foo").gid, Process.gid end def test_file_chmod_of_file FileUtils.touch "foo" File.chmod 0600, "foo" assert_equal File.stat("foo").mode, 0100600 File.new("foo").chmod 0644 assert_equal File.stat("foo").mode, 0100644 end def test_file_chmod_of_dir Dir.mkdir "bar" File.chmod 0777, "bar" assert_equal File.stat("bar").mode, 0100777 File.new("bar").chmod 01700 assert_equal File.stat("bar").mode, 0101700 end def test_file_chown_of_file FileUtils.touch "foo" File.chown 1337, 1338, "foo" assert_equal File.stat("foo").uid, 1337 assert_equal File.stat("foo").gid, 1338 end def test_file_chown_of_dir Dir.mkdir "bar" File.chown 1337, 1338, "bar" assert_equal File.stat("bar").uid, 1337 assert_equal File.stat("bar").gid, 1338 end def test_file_chown_of_file_nil_user_group FileUtils.touch "foo" File.chown 1337, 1338, "foo" File.chown nil, nil, "foo" assert_equal File.stat("foo").uid, 1337 assert_equal File.stat("foo").gid, 1338 end def test_file_chown_of_file_negative_user_group FileUtils.touch "foo" File.chown 1337, 1338, "foo" File.chown -1, -1, "foo" assert_equal File.stat("foo").uid, 1337 assert_equal File.stat("foo").gid, 1338 end def test_file_instance_chown_nil_user_group FileUtils.touch('foo') File.chown(1337, 1338, 'foo') assert_equal File.stat('foo').uid, 1337 assert_equal File.stat('foo').gid, 1338 file = File.open('foo') file.chown nil, nil assert_equal File.stat('foo').uid, 1337 assert_equal File.stat('foo').gid, 1338 end def test_file_instance_chown_negative_user_group FileUtils.touch('foo') File.chown(1337, 1338, 'foo') assert_equal File.stat('foo').uid, 1337 assert_equal File.stat('foo').gid, 1338 file = File.new('foo') file.chown -1, -1 file.close assert_equal File.stat('foo').uid, 1337 assert_equal File.stat('foo').gid, 1338 end def test_file_umask assert_equal File.umask, RealFile.umask end def test_file_stat_comparable a_time = Time.new same1 = File.new("s1", "w") same2 = File.new("s2", "w") different1 = File.new("d1", "w") different2 = File.new("d2", "w") FileSystem.find("s1").mtime = a_time FileSystem.find("s2").mtime = a_time FileSystem.find("d1").mtime = a_time FileSystem.find("d2").mtime = a_time + 1 assert same1.mtime == same2.mtime assert different1.mtime != different2.mtime assert same1.stat == same2.stat assert (same1.stat <=> same2.stat) == 0 assert different1.stat != different2.stat assert (different1.stat <=> different2.stat) == -1 end def here(fname) RealFile.expand_path(File.join(RealFile.dirname(__FILE__), fname)) end if RUBY_VERSION >= "1.9.2" def test_file_size File.open("foo", 'w') do |f| f << 'Yada Yada' assert_equal 9, f.size end end def test_fdatasync File.open("foo", 'w') do |f| f << 'Yada Yada' assert_nothing_raised do f.fdatasync end end end def test_autoclose File.open("foo", 'w') do |f| assert_equal true, f.autoclose? f.autoclose = false assert_equal false, f.autoclose? end end def test_to_path File.new("foo", 'w') do |f| assert_equal "foo", f.to_path end end end if RUBY_VERSION >= "1.9.3" def test_advise File.open("foo", 'w') do |f| assert_nothing_raised do f.advise(:normal, 0, 0) end end end end end fakefs-0.4.2/test/safe_test.rb0000644000004100000410000000305312057273366016301 0ustar www-datawww-datarequire "test_helper" class FakeFSSafeTest < Test::Unit::TestCase def setup FakeFS.deactivate! end def teardown FakeFS.activate! end def test_FakeFS_activated_is_accurate 2.times do FakeFS.deactivate! assert !FakeFS.activated? FakeFS.activate! assert FakeFS.activated? end end def test_FakeFS_method_does_not_intrude_on_global_namespace path = 'file.txt' FakeFS do File.open(path, 'w') { |f| f.write "Yatta!" } assert File.exists?(path) end assert ! File.exists?(path) end def test_FakeFS_method_returns_value_of_yield result = FakeFS do File.open('myfile.txt', 'w') { |f| f.write "Yatta!" } File.read('myfile.txt') end assert_equal result, "Yatta!" end def test_FakeFS_method_does_not_deactivate_FakeFS_if_already_activated FakeFS.activate! FakeFS {} assert FakeFS.activated? end def test_FakeFS_method_can_be_nested FakeFS do assert FakeFS.activated? FakeFS do assert FakeFS.activated? end assert FakeFS.activated? end assert !FakeFS.activated? end def test_FakeFS_method_can_be_nested_with_FakeFS_without FakeFS do assert FakeFS.activated? FakeFS.without do assert !FakeFS.activated? end assert FakeFS.activated? end assert !FakeFS.activated? end def test_FakeFS_method_deactivates_FakeFS_when_block_raises_exception begin FakeFS do raise 'boom!' end rescue end assert !FakeFS.activated? end end fakefs-0.4.2/LICENSE0000644000004100000410000000204312057273366014023 0ustar www-datawww-dataCopyright (c) 2009 Chris Wanstrath Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. fakefs-0.4.2/Rakefile0000644000004100000410000000323012057273366014462 0ustar www-datawww-data$LOAD_PATH.unshift File.join(File.dirname(__FILE__)) $LOAD_PATH.unshift File.join(File.dirname(__FILE__), 'test') require "bundler/setup" require 'rake/testtask' Rake::TestTask.new do |t| t.libs << "test" t.test_files = FileList['test/**/*test.rb'] t.verbose = true end begin require 'rspec/core/rake_task' desc "Run specs" RSpec::Core::RakeTask.new rescue LoadError puts "Spec task can't be loaded. `gem install rspec`" end task :default => [:test, :spec] begin require 'jeweler' $LOAD_PATH.unshift File.dirname(__FILE__) + '/lib' require 'fakefs/version' Jeweler::Tasks.new do |gemspec| gemspec.name = "fakefs" gemspec.summary = "A fake filesystem. Use it in your tests." gemspec.email = "chris@ozmm.org" gemspec.homepage = "http://github.com/defunkt/fakefs" gemspec.description = "A fake filesystem. Use it in your tests." gemspec.authors = ["Chris Wanstrath", "Scott Taylor", "Jeff Hodges", "Pat Nakajima"] gemspec.has_rdoc = false gemspec.version = FakeFS::Version.to_s end rescue LoadError puts "Jeweler not available." puts "Install it with: gem install jeweler" end desc "Build a gem" task :gem => [ :gemspec, :build ] desc "Push a new version to Gemcutter" task :publish => [ :gemspec, :build ] do abort("Tests failed!") unless system("rake test") system "git tag v#{FakeFS::Version}" system "git push origin v#{FakeFS::Version}" system "git push origin master" system "gem push pkg/fakefs-#{FakeFS::Version}.gem" system "git clean -fd" exec "rake pages" end desc "Update contributors" task :update_contributors do sh "git-rank-contributors > CONTRIBUTORS" end fakefs-0.4.2/spec/0000755000004100000410000000000012057273366013751 5ustar www-datawww-datafakefs-0.4.2/spec/spec.opts0000644000004100000410000000001012057273366015601 0ustar www-datawww-data--color fakefs-0.4.2/spec/fakefs/0000755000004100000410000000000012057273366015210 5ustar www-datawww-datafakefs-0.4.2/spec/fakefs/spec_helpers_spec.rb0000644000004100000410000000275212057273366021231 0ustar www-datawww-datarequire 'spec_helper' module FakeFS describe SpecHelpers do before do @rspec_example_group = Class.new do def self.before(sym = :each) yield if block_given? end def self.after(sym = :each) yield if block_given? end end end describe "when extending" do context "before each" do it "should call it" do @rspec_example_group.should_receive(:before).with(:each) @rspec_example_group.extend FakeFS::SpecHelpers end it "should call FakeFS.activate!" do FakeFS.should_receive(:activate!) @rspec_example_group.extend FakeFS::SpecHelpers end end context "after each" do it "should call it" do @rspec_example_group.should_receive(:after).with(:each) @rspec_example_group.extend FakeFS::SpecHelpers end it "should deactivate fakefs" do FakeFS.should_receive(:deactivate!) @rspec_example_group.extend FakeFS::SpecHelpers end it "should clear the fakefs filesystem for the next run" do FakeFS::FileSystem.should_receive(:clear) @rspec_example_group.extend FakeFS::SpecHelpers end end end describe "when including" do it "should call before :each" do @rspec_example_group.should_receive(:before) @rspec_example_group.class_eval do include FakeFS::SpecHelpers end end end end end fakefs-0.4.2/spec/spec_helper.rb0000644000004100000410000000014112057273366016563 0ustar www-datawww-data$LOAD_PATH.unshift File.join(File.dirname(__FILE__), '..', 'lib') require 'fakefs/spec_helpers' fakefs-0.4.2/.rspec0000644000004100000410000000000712057273366014131 0ustar www-datawww-data--colorfakefs-0.4.2/README.markdown0000644000004100000410000000663312057273366015530 0ustar www-datawww-dataFakeFS [![build status](https://secure.travis-ci.org/defunkt/fakefs.png)](https://secure.travis-ci.org/defunkt/fakefs) ====== Mocha is great. But when your library is all about manipulating the filesystem, you really want to test the behavior and not the implementation. If you're mocking and stubbing every call to FileUtils or File, you're tightly coupling your tests with the implementation. ``` ruby def test_creates_directory FileUtils.expects(:mkdir).with("directory").once Library.add "directory" end ``` The above test will break if we decide to use `mkdir_p` in our code. Refactoring code shouldn't necessitate refactoring tests. With FakeFS: ``` ruby def test_creates_directory Library.add "directory" assert File.directory?("directory") end ``` Woot. Usage ----- ``` ruby require 'fakefs' # That's it. ``` Don't Fake the FS Immediately ----------------------------- ``` ruby gem "fakefs", :require => "fakefs/safe" require 'fakefs/safe' FakeFS.activate! # your code FakeFS.deactivate! # or FakeFS do # your code end ``` Rails ----- If you are using fakefs in a rails project with bundler, you'll probably want to specify the following in your Gemfile: gem "fakefs", :require => "fakefs/safe" RSpec ----- The above approach works with RSpec as well. In addition you may include FakeFS::SpecHelpers to turn FakeFS on and off in a given example group: ``` ruby require 'fakefs/spec_helpers' describe "my spec" do include FakeFS::SpecHelpers end ``` See `lib/fakefs/spec_helpers.rb` for more info. Integrating with other filesystem libraries -------------------------------------------- Third-party libraries may add methods to filesystem-related classes. FakeFS doesn't support these methods out of the box, but you can define fake versions yourself on the equivalent FakeFS classes. For example, [FileMagic](https://rubygems.org/gems/ruby-filemagic) adds `File#content_type`. A fake version can be provided as follows: ``` ruby module FakeFS class File def content_type 'fake/file' end end end ``` How is this different than MockFS? ---------------------------------- FakeFS provides a test suite and works with symlinks. It's also strictly a test-time dependency: your actual library does not need to use or know about FakeFS. Caveats ------- FakeFS internally uses the `Pathname` and `FileUtils` constants. If you use these in your app, be certain you're properly requiring them and not counting on FakeFS' own require. Speed? ------ Installation ------------ ### [RubyGems](http://rubygems.org/) $ gem install fakefs ### [Rip](http://hellorip.com) $ rip install git://github.com/defunkt/fakefs.git Contributing ------------ Once you've made your great commits: 1. [Fork][0] FakeFS 2. Create a topic branch - `git checkout -b my_branch` 3. Push to your branch - `git push origin my_branch` 5. Open a [Pull Request][1] 5. That's it! Meta ---- * Code: `git clone git://github.com/defunkt/fakefs.git` * Home: * Docs: * Bugs: * List: * Test: * Gems: [0]: http://help.github.com/forking/ [1]: http://help.github.com/send-pull-requests/ Releasing --------- 1. Update version in lib/fakefs/version.rb 2. Commit it 3. rake publish fakefs-0.4.2/metadata.yml0000644000004100000410000000610212057273366015321 0ustar www-datawww-data--- !ruby/object:Gem::Specification name: fakefs version: !ruby/object:Gem::Version version: 0.4.2 prerelease: platform: ruby authors: - Chris Wanstrath - Scott Taylor - Jeff Hodges - Pat Nakajima autorequire: bindir: bin cert_chain: [] date: 2012-11-24 00:00:00.000000000 Z dependencies: - !ruby/object:Gem::Dependency name: rspec requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: jeweler requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' - !ruby/object:Gem::Dependency name: rdiscount requirement: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' description: A fake filesystem. Use it in your tests. email: chris@ozmm.org executables: [] extensions: [] extra_rdoc_files: - LICENSE - README.markdown files: - .autotest - .rspec - .travis.yml - CONTRIBUTORS - Gemfile - Gemfile.lock - LICENSE - README.markdown - Rakefile - fakefs.gemspec - lib/fakefs.rb - lib/fakefs/base.rb - lib/fakefs/dir.rb - lib/fakefs/fake/dir.rb - lib/fakefs/fake/file.rb - lib/fakefs/fake/symlink.rb - lib/fakefs/file.rb - lib/fakefs/file_system.rb - lib/fakefs/file_test.rb - lib/fakefs/fileutils.rb - lib/fakefs/pathname.rb - lib/fakefs/safe.rb - lib/fakefs/spec_helpers.rb - lib/fakefs/version.rb - spec/fakefs/spec_helpers_spec.rb - spec/spec.opts - spec/spec_helper.rb - test/fake/file/join_test.rb - test/fake/file/lstat_test.rb - test/fake/file/stat_test.rb - test/fake/file/sysseek_test.rb - test/fake/file/syswrite_test.rb - test/fake/file_test.rb - test/fake/symlink_test.rb - test/fakefs_test.rb - test/file/stat_test.rb - test/safe_test.rb - test/test_helper.rb - test/verify.rb homepage: http://github.com/defunkt/fakefs licenses: [] post_install_message: rdoc_options: [] require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' segments: - 0 hash: 4092255673165272959 required_rubygems_version: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' requirements: [] rubyforge_project: rubygems_version: 1.8.24 signing_key: specification_version: 3 summary: A fake filesystem. Use it in your tests. test_files: [] fakefs-0.4.2/Gemfile0000644000004100000410000000013312057273366014307 0ustar www-datawww-datasource :rubygems group :development do gem 'rspec' gem 'jeweler' gem 'rdiscount' endfakefs-0.4.2/.autotest0000644000004100000410000000016512057273366014672 0ustar www-datawww-dataAutotest.add_hook :initialize do |at| at.add_mapping(%r%^test/.+_test.rb$%) do |filename, _| filename end endfakefs-0.4.2/lib/0000755000004100000410000000000012057273366013565 5ustar www-datawww-datafakefs-0.4.2/lib/fakefs/0000755000004100000410000000000012057273366015024 5ustar www-datawww-datafakefs-0.4.2/lib/fakefs/fake/0000755000004100000410000000000012057273366015732 5ustar www-datawww-datafakefs-0.4.2/lib/fakefs/fake/symlink.rb0000644000004100000410000000102412057273366017742 0ustar www-datawww-datamodule FakeFS class FakeSymlink attr_accessor :name, :target, :parent def initialize(target) @target = target end def inspect "symlink(#{target.split('/').last})" end def entry FileSystem.find(target) end def delete parent.delete(self) end def to_s File.join(parent.to_s, name) end def respond_to?(method) entry.respond_to?(method) end private def method_missing(*args, &block) entry.send(*args, &block) end end end fakefs-0.4.2/lib/fakefs/fake/file.rb0000644000004100000410000000322212057273366017175 0ustar www-datawww-datamodule FakeFS class FakeFile attr_accessor :name, :parent, :content, :mtime, :atime, :mode, :uid, :gid attr_reader :ctime class Inode def initialize(file_owner) #1.9.3 when possible set default external encoding @content = "".respond_to?(:encode) ? "".encode(Encoding.default_external) : "" @links = [file_owner] end attr_accessor :content attr_accessor :links def link(file) links << file unless links.include?(file) file.inode = self end def unlink(file) links.delete(file) end def clone clone = super clone.content = content.dup clone end end def initialize(name = nil, parent = nil) @name = name @parent = parent @inode = Inode.new(self) @ctime = Time.now @mtime = @ctime @atime = @ctime @mode = 0100000 + (0666 - File.umask) @uid = Process.uid @gid = Process.gid end attr_accessor :inode def content @inode.content end def content=(str) @inode.content = str end def links @inode.links end def link(other_file) @inode.link(other_file) end def clone(parent = nil) clone = super() clone.parent = parent if parent clone.inode = inode.clone clone end def entry self end def inspect "(FakeFile name:#{name.inspect} parent:#{parent.to_s.inspect} size:#{content.size})" end def to_s File.join(parent.to_s, name) end def delete inode.unlink(self) parent.delete(self) end end end fakefs-0.4.2/lib/fakefs/fake/dir.rb0000644000004100000410000000266712057273366017050 0ustar www-datawww-datamodule FakeFS class FakeDir attr_accessor :name, :parent, :mode, :uid, :gid, :mtime, :atime attr_reader :ctime, :content def initialize(name = nil, parent = nil) @name = name @parent = parent @ctime = Time.now @mtime = @ctime @atime = @ctime @mode = 0100000 + (0777 - File.umask) @uid = Process.uid @gid = Process.gid @content = "" @entries = {} end def entry self end def inspect "(FakeDir name:#{name.inspect} parent:#{parent.to_s.inspect} size:#{@entries.size})" end def clone(parent = nil) clone = Marshal.load(Marshal.dump(self)) clone.entries.each do |value| value.parent = clone end clone.parent = parent if parent clone end def to_s if parent && parent.to_s != '.' File.join(parent.to_s, name) elsif parent && parent.to_s == '.' "#{File::PATH_SEPARATOR}#{name}" else name end end def empty? @entries.empty? end def entries @entries.values end def matches(pattern) @entries.reject {|k,v| pattern !~ k }.values end def [](name) @entries[name] end def []=(name, value) @entries[name] = value end def delete(node = self) if node == self parent.delete(self) else @entries.delete(node.name) end end end end fakefs-0.4.2/lib/fakefs/version.rb0000644000004100000410000000015012057273366017032 0ustar www-datawww-datamodule FakeFS module Version VERSION = "0.4.2" def self.to_s VERSION end end end fakefs-0.4.2/lib/fakefs/base.rb0000644000004100000410000000332412057273366016265 0ustar www-datawww-dataRealFile = File RealFileTest = FileTest RealFileUtils = FileUtils RealDir = Dir RealPathname = Pathname module FakeFS @activated = false class << self def activated? @activated end def activate! @activated = true Object.class_eval do remove_const(:Dir) remove_const(:File) remove_const(:FileTest) remove_const(:FileUtils) remove_const(:Pathname) if RUBY_VERSION >= "1.9.3" const_set(:Dir, FakeFS::Dir) const_set(:File, FakeFS::File) const_set(:FileUtils, FakeFS::FileUtils) const_set(:FileTest, FakeFS::FileTest) const_set(:Pathname, FakeFS::Pathname) if RUBY_VERSION >= "1.9.3" end true end def deactivate! @activated = false Object.class_eval do remove_const(:Dir) remove_const(:File) remove_const(:FileTest) remove_const(:FileUtils) remove_const(:Pathname) if RUBY_VERSION >= "1.9.3" const_set(:Dir, RealDir) const_set(:File, RealFile) const_set(:FileTest, RealFileTest) const_set(:FileUtils, RealFileUtils) const_set(:Pathname, RealPathname) if RUBY_VERSION >= "1.9.3" end true end def with if activated? yield else begin activate! yield ensure deactivate! end end end def without if !activated? yield else begin deactivate! yield ensure activate! end end end end end def FakeFS(&block) return ::FakeFS unless block ::FakeFS.with(&block) end fakefs-0.4.2/lib/fakefs/spec_helpers.rb0000644000004100000410000000227012057273366020026 0ustar www-datawww-data# FakeFS::SpecHelpers provides a simple macro for RSpec example groups to turn FakeFS on and off. # To use it simply require 'fakefs/spec_helpers', then include FakeFS::SpecHelpers into any # example groups that you wish to use FakeFS in. For example: # # require 'fakefs/spec_helpers' # # describe "Some specs that deal with files" do # include FakeFS::SpecHelpers # ... # end # # Alternatively, you can include FakeFS::SpecHelpers in all your example groups using RSpec's # configuration block in your spec helper: # # require 'fakefs/spec_helpers' # # Spec::Runner.configure do |config| # config.include FakeFS::SpecHelpers # end # # If you do the above then use_fakefs will be available in all of your example groups. # require 'fakefs/safe' module FakeFS module SpecHelpers def self.extended(example_group) example_group.use_fakefs(example_group) end def self.included(example_group) example_group.extend self end def use_fakefs(describe_block) describe_block.before :each do FakeFS.activate! end describe_block.after :each do FakeFS.deactivate! FakeFS::FileSystem.clear end end end end fakefs-0.4.2/lib/fakefs/file_test.rb0000644000004100000410000000037512057273366017334 0ustar www-datawww-datamodule FakeFS class FileTest def self.exist?(file_name) File.exist?(file_name) end def self.directory?(file_name) File.directory?(file_name) end def self.file?(file_name) File.file?(file_name) end end end fakefs-0.4.2/lib/fakefs/file_system.rb0000644000004100000410000000705012057273366017676 0ustar www-datawww-datamodule FakeFS module FileSystem extend self def dir_levels @dir_levels ||= [] end def fs @fs ||= FakeDir.new('/') end def clear @dir_levels = nil @fs = nil end def files fs.entries end def find(path) parts = path_parts(normalize_path(path)) return fs if parts.empty? # '/' entries = find_recurser(fs, parts).flatten case entries.length when 0 then nil when 1 then entries.first else entries end end def add(path, object=FakeDir.new) parts = path_parts(normalize_path(path)) d = parts[0...-1].inject(fs) do |dir, part| dir[part] ||= FakeDir.new(part, dir) end object.name = parts.last object.parent = d d[parts.last] ||= object end # copies directories and files from the real filesystem # into our fake one def clone(path, target = nil) path = File.expand_path(path) pattern = File.join(path, '**', '*') files = RealFile.file?(path) ? [path] : [path] + RealDir.glob(pattern, RealFile::FNM_DOTMATCH) files.each do |f| target_path = target ? f.gsub(path, target) : f if RealFile.file?(f) FileUtils.mkdir_p(File.dirname(f)) File.open(target_path, File::WRITE_ONLY) do |g| g.print RealFile.open(f){|h| h.read } end elsif RealFile.directory?(f) FileUtils.mkdir_p(target_path) elsif RealFile.symlink?(f) FileUtils.ln_s() end end end def delete(path) if node = FileSystem.find(path) node.delete true end end def chdir(dir, &blk) new_dir = find(dir) dir_levels.push dir if blk raise Errno::ENOENT, dir unless new_dir dir_levels.push dir if !blk blk.call if blk ensure dir_levels.pop if blk end def path_parts(path) drop_root(path.split(File::SEPARATOR)).reject { |part| part.empty? } end def normalize_path(path) if Pathname.new(path).absolute? File.expand_path(path) else parts = dir_levels + [path] File.expand_path(File.join(*parts)) end end def current_dir find(normalize_path('.')) end private def drop_root(path_parts) # we need to remove parts from root dir at least for windows and jruby return path_parts if path_parts.nil? || path_parts.empty? root = File.expand_path('/').split(File::SEPARATOR).first path_parts.shift if path_parts.first == root path_parts end def find_recurser(dir, parts) return [] unless dir.respond_to? :[] pattern , *parts = parts matches = case pattern when '**' case parts when ['*'] parts = [] # end recursion directories_under(dir).map do |d| d.entries.select{|f| f.is_a?(FakeFile) || f.is_a?(FakeDir) } end.flatten.uniq when [] parts = [] # end recursion dir.entries.flatten.uniq else directories_under(dir) end else dir.matches /\A#{pattern.gsub('.', '\.').gsub('?','.').gsub('*', '.*').gsub(/\{(.*?)\}/) { "(#{$1.gsub(',', '|')})" }}\Z/ end if parts.empty? # we're done recursing matches else matches.map{|entry| find_recurser(entry, parts) } end end def directories_under(dir) children = dir.entries.select{|f| f.is_a? FakeDir} ([dir] + children + children.map{|c| directories_under(c)}).flatten.uniq end end end fakefs-0.4.2/lib/fakefs/fileutils.rb0000644000004100000410000001227112057273366017354 0ustar www-datawww-datamodule FakeFS module FileUtils extend self def mkdir_p(path, options = {}) FileSystem.add(path, FakeDir.new) end alias_method :mkpath, :mkdir_p alias_method :makedirs, :mkdir_p def mkdir(path) parent = path.split('/') parent.pop raise Errno::ENOENT, "No such file or directory - #{path}" unless parent.join == "" || parent.join == "." || FileSystem.find(parent.join('/')) raise Errno::EEXIST, "File exists - #{path}" if FileSystem.find(path) FileSystem.add(path, FakeDir.new) end def rmdir(list, options = {}) list = [ list ] unless list.is_a?(Array) list.each do |l| parent = l.split('/') parent.pop raise Errno::ENOENT, "No such file or directory - #{l}" unless parent.join == "" || FileSystem.find(parent.join('/')) raise Errno::ENOENT, l unless FileSystem.find(l) raise Errno::ENOTEMPTY, l unless FileSystem.find(l).empty? rm(l) end end def rm(list, options = {}) Array(list).each do |path| FileSystem.delete(path) or (!options[:force] && raise(Errno::ENOENT.new(path))) end end alias_method :rm_rf, :rm alias_method :rm_r, :rm alias_method :rm_f, :rm def ln_s(target, path, options = {}) options = { :force => false }.merge(options) (FileSystem.find(path) && !options[:force]) ? raise(Errno::EEXIST, path) : FileSystem.delete(path) if !options[:force] && !Dir.exists?(File.dirname(path)) raise Errno::ENOENT, path end FileSystem.add(path, FakeSymlink.new(target)) end def ln_sf(target, path) ln_s(target, path, { :force => true }) end def cp(src, dest) if src.is_a?(Array) && !File.directory?(dest) raise Errno::ENOTDIR, dest end Array(src).each do |src| dst_file = FileSystem.find(dest) src_file = FileSystem.find(src) if !src_file raise Errno::ENOENT, src end if File.directory? src_file raise Errno::EISDIR, src end if dst_file && File.directory?(dst_file) FileSystem.add(File.join(dest, src), src_file.entry.clone(dst_file)) else FileSystem.delete(dest) FileSystem.add(dest, src_file.entry.clone) end end end def cp_r(src, dest) Array(src).each do |src| # This error sucks, but it conforms to the original Ruby # method. raise "unknown file type: #{src}" unless dir = FileSystem.find(src) new_dir = FileSystem.find(dest) if new_dir && !File.directory?(dest) raise Errno::EEXIST, dest end if !new_dir && !FileSystem.find(dest+'/../') raise Errno::ENOENT, dest end # This last bit is a total abuse and should be thought hard # about and cleaned up. if new_dir if src[-2..-1] == '/.' dir.entries.each{|f| new_dir[f.name] = f.clone(new_dir) } else new_dir[dir.name] = dir.entry.clone(new_dir) end else FileSystem.add(dest, dir.entry.clone) end end end def mv(src, dest, options={}) Array(src).each do |path| if target = FileSystem.find(path) dest_path = File.directory?(dest) ? File.join(dest, File.basename(path)) : dest FileSystem.delete(dest_path) FileSystem.add(dest_path, target.entry.clone) FileSystem.delete(path) else raise Errno::ENOENT, path end end end def chown(user, group, list, options={}) list = Array(list) list.each do |f| if File.exists?(f) uid = if user user.to_s.match(/[0-9]+/) ? user.to_i : Etc.getpwnam(user).uid else nil end gid = if group group.to_s.match(/[0-9]+/) ? group.to_i : Etc.getgrnam(group).gid else nil end File.chown(uid, gid, f) else raise Errno::ENOENT, f end end list end def chown_R(user, group, list, options={}) list = Array(list) list.each do |file| chown(user, group, file) [FileSystem.find("#{file}/**/**")].flatten.each do |f| chown(user, group, f.to_s) end end list end def chmod(mode, list, options={}) list = Array(list) list.each do |f| if File.exists?(f) File.chmod(mode, f) else raise Errno::ENOENT, f end end list end def chmod_R(mode, list, options={}) list = Array(list) list.each do |file| chmod(mode, file) [FileSystem.find("#{file}/**/**")].flatten.each do |f| chmod(mode, f.to_s) end end list end def touch(list, options={}) Array(list).each do |f| if fs = FileSystem.find(f) now = Time.now fs.mtime = now fs.atime = now else f = File.open(f, 'w') f.close end end end def cd(dir) FileSystem.chdir(dir) end alias_method :chdir, :cd end end fakefs-0.4.2/lib/fakefs/file.rb0000644000004100000410000002525112057273366016275 0ustar www-datawww-datarequire 'stringio' module FakeFS class File < StringIO MODES = [ READ_ONLY = "r", READ_WRITE = "r+", WRITE_ONLY = "w", READ_WRITE_TRUNCATE = "w+", APPEND_WRITE_ONLY = "a", APPEND_READ_WRITE = "a+" ] 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.const_defined?(:NOCTTY) ? RealFile::NOCTTY : 0) | (RealFile.const_defined?(:SYNC) ? RealFile::SYNC : 0) FILE_CREATION_BITMASK = RealFile::CREAT def self.extname(path) RealFile.extname(path) end def self.join(*parts) RealFile.join(parts) end def self.exist?(path) if(File.symlink?(path)) then referent = File.expand_path(File.readlink(path), File.dirname(path)) exist?(referent) else !!FileSystem.find(path) end end class << self alias_method :exists?, :exist? # Assuming that everyone can read and write files alias_method :readable?, :exist? alias_method :writable?, :exist? end def self.mtime(path) if exists?(path) FileSystem.find(path).mtime else raise Errno::ENOENT end end def self.ctime(path) if exists?(path) FileSystem.find(path).ctime else raise Errno::ENOENT end end def self.atime(path) if exists?(path) FileSystem.find(path).atime else raise Errno::ENOENT end end def self.utime(atime, mtime, *paths) paths.each do |path| if exists?(path) FileSystem.find(path).atime = atime FileSystem.find(path).mtime = mtime else raise Errno::ENOENT end end paths.size end def self.size(path) read(path).length end def self.size?(path) if exists?(path) && !size(path).zero? true else nil end end def self.const_missing(name) RealFile.const_get(name) end def self.directory?(path) if path.respond_to? :entry path.entry.is_a? FakeDir else result = FileSystem.find(path) result ? result.entry.is_a?(FakeDir) : false end end def self.symlink?(path) if path.respond_to? :entry path.is_a? FakeSymlink else FileSystem.find(path).is_a? FakeSymlink end end def self.file?(path) if path.respond_to? :entry path.entry.is_a? FakeFile else result = FileSystem.find(path) result ? result.entry.is_a?(FakeFile) : false end end def self.expand_path(*args) RealFile.expand_path(*args) end def self.basename(*args) RealFile.basename(*args) end def self.dirname(path) RealFile.dirname(path) end def self.readlink(path) symlink = FileSystem.find(path) symlink.target end def self.read(path, *args) file = new(path) if file.exists? FileSystem.find(path).atime = Time.now file.read else raise Errno::ENOENT end end def self.readlines(path) 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}" end if !exists?(source) raise Errno::ENOENT, "No such file or directory - #{source} or #{dest}" end if exists?(dest) raise Errno::EEXIST, "File exists - #{source} or #{dest}" end source = FileSystem.find(source) dest = FileSystem.add(dest, source.entry.clone) source.link(dest) 0 end def self.delete(file_name, *additional_file_names) if !exists?(file_name) raise Errno::ENOENT, "No such file or directory - #{file_name}" end FileUtils.rm(file_name) additional_file_names.each do |file_name| FileUtils.rm(file_name) end additional_file_names.size + 1 end class << self alias_method :unlink, :delete end def self.symlink(source, dest) FileUtils.ln_s(source, dest) end def self.stat(file) File::Stat.new(file) end def self.lstat(file) File::Stat.new(file, true) end def self.split(path) return RealFile.split(path) end def self.chmod(mode_int, filename) FileSystem.find(filename).mode = 0100000 + mode_int end def self.chown(owner_int, group_int, filename) file = FileSystem.find(filename) if owner_int && owner_int != -1 owner_int.is_a?(Fixnum) or raise TypeError, "can't convert String into Integer" file.uid = owner_int end if group_int && group_int != -1 group_int.is_a?(Fixnum) or raise TypeError, "can't convert String into Integer" file.gid = group_int end end def self.umask RealFile.umask end class Stat attr_reader :ctime, :mtime, :atime, :mode, :uid, :gid def initialize(file, __lstat = false) if !File.exists?(file) raise(Errno::ENOENT, "No such file or directory - #{file}") end @file = file @fake_file = FileSystem.find(@file) @__lstat = __lstat @ctime = @fake_file.ctime @mtime = @fake_file.mtime @atime = @fake_file.atime @mode = @fake_file.mode @uid = @fake_file.uid @gid = @fake_file.gid end def symlink? File.symlink?(@file) end def directory? File.directory?(@file) end # assumes, like above, that all files are readable and writable def readable? true end def writable? true end def nlink @fake_file.links.size end def size if @__lstat && symlink? @fake_file.target.size else File.size(@file) end end def zero? size == 0 end include Comparable def <=>(other) @mtime <=> other.mtime end end attr_reader :path def initialize(path, mode = READ_ONLY, perm = nil) @path = path @mode = mode.is_a?(Hash) ? (mode[:mode] || READ_ONLY) : mode @file = FileSystem.find(path) @autoclose = true check_modes! file_creation_mode? ? create_missing_file : check_file_existence! super(@file.content, @mode) end def exists? true end def write(str) val = super(str) @file.mtime = Time.now val end alias_method :tell=, :pos= alias_method :sysread, :read alias_method :syswrite, :write undef_method :closed_read? undef_method :closed_write? undef_method :length undef_method :size undef_method :string undef_method :string= if RUBY_PLATFORM == 'java' undef_method :to_channel undef_method :to_outputstream undef_method :to_inputstream end def ioctl(integer_cmd, arg) raise NotImplementedError end def read_nonblock(maxlen, outbuf = nil) raise NotImplementedError end def stat self.class.stat(@path) end def lstat self.class.lstat(@path) end def sysseek(position, whence = SEEK_SET) seek(position, whence) pos end alias_method :to_i, :fileno def to_io self end def write_nonblock(string) raise NotImplementedError end def readpartial(maxlen, outbuf = nil) raise NotImplementedError end def atime self.class.atime(@path) end def ctime self.class.ctime(@path) end def flock(locking_constant) raise NotImplementedError end def mtime self.class.mtime(@path) end def chmod(mode_int) @file.mode = 0100000 + mode_int end def chown(owner_int, group_int) if owner_int && owner_int != -1 owner_int.is_a?(Fixnum) or raise TypeError, "can't convert String into Integer" @file.uid = owner_int end if group_int && group_int != -1 group_int.is_a?(Fixnum) or raise TypeError, "can't convert String into Integer" @file.gid = group_int end end if RUBY_VERSION >= "1.9" def binmode? raise NotImplementedError end def close_on_exec=(bool) raise NotImplementedError end def close_on_exec? raise NotImplementedError end def to_path @path end end if RUBY_VERSION >= "1.9.2" attr_writer :autoclose def autoclose? @autoclose end def autoclose? @autoclose ? true : false end def autoclose=(autoclose) @autoclose = autoclose end alias_method :fdatasync, :flush def size File.size(@path) end end if RUBY_VERSION >= "1.9.3" def advise(advice, offset=0, len=0) end end private def check_modes! StringIO.new("", @mode) end def check_file_existence! raise Errno::ENOENT, @path unless @file end def file_creation_mode? mode_in?(FILE_CREATION_MODES) || mode_in_bitmask?(FILE_CREATION_BITMASK) end def mode_in?(list) 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 # Create a missing file if the path is valid. # def create_missing_file raise Errno::EISDIR, "Is a directory - #{path}" if File.directory?(@path) if !File.exists?(@path) # Unnecessary check, probably. dirname = RealFile.dirname @path unless dirname == "." dir = FileSystem.find dirname unless dir.kind_of? FakeDir raise Errno::ENOENT, "No such file or directory - #{path}" end end @file = FileSystem.add(path, FakeFile.new) end end end end fakefs-0.4.2/lib/fakefs/dir.rb0000644000004100000410000000777312057273366016145 0ustar www-datawww-datamodule FakeFS class Dir include Enumerable def self._check_for_valid_file(path) raise Errno::ENOENT, "No such file or directory - #{path}" unless FileSystem.find(path) end def initialize(string) self.class._check_for_valid_file(string) @path = string @open = true @pointer = 0 @contents = [ '.', '..', ] + FileSystem.find(@path).entries end def close @open = false @pointer = nil @contents = nil nil end def each(&block) while f = read yield f end end def path @path end def pos @pointer end def pos=(integer) @pointer = integer end def read raise IOError, "closed directory" if @pointer == nil n = @contents[@pointer] @pointer += 1 n.to_s.gsub(path + '/', '') if n end def rewind @pointer = 0 end def seek(integer) raise IOError, "closed directory" if @pointer == nil @pointer = integer @contents[integer] end def self.[](*pattern) glob pattern end def self.exists?(path) File.exists?(path) && File.directory?(path) end def self.chdir(dir, &blk) FileSystem.chdir(dir, &blk) end def self.chroot(string) raise NotImplementedError end def self.delete(string) _check_for_valid_file(string) raise Errno::ENOTEMPTY, "Directory not empty - #{string}" unless FileSystem.find(string).empty? FileSystem.delete(string) end def self.entries(dirname) _check_for_valid_file(dirname) Dir.new(dirname).map { |file| File.basename(file) } end def self.foreach(dirname, &block) Dir.open(dirname) { |file| yield file } end def self.glob(pattern, &block) matches_for_pattern = lambda do |matcher| [FileSystem.find(matcher) || []].flatten.map{|e| Dir.pwd.match(%r[\A/?\z]) || !e.to_s.match(%r[\A#{Dir.pwd}/?]) ? e.to_s : e.to_s.match(%r[\A#{Dir.pwd}/?]).post_match}.sort end if pattern.is_a? Array files = pattern.collect { |matcher| matches_for_pattern.call matcher }.flatten else files = matches_for_pattern.call pattern end return block_given? ? files.each { |file| block.call(file) } : files end if RUBY_VERSION >= "1.9" def self.home(user = nil) RealDir.home(user) end end def self.mkdir(string, integer = 0) FileUtils.mkdir(string) end def self.open(string, &block) if block_given? Dir.new(string).each { |file| yield(file) } else Dir.new(string) end end def self.tmpdir '/tmp' end def self.pwd FileSystem.current_dir.to_s end # This code has been borrowed from Rubinius def self.mktmpdir(prefix_suffix = nil, tmpdir = nil) case prefix_suffix when nil prefix = "d" suffix = "" when String prefix = prefix_suffix suffix = "" when Array prefix = prefix_suffix[0] suffix = prefix_suffix[1] else raise ArgumentError, "unexpected prefix_suffix: #{prefix_suffix.inspect}" end t = Time.now.strftime("%Y%m%d") n = nil begin path = "#{tmpdir}/#{prefix}#{t}-#{$$}-#{rand(0x100000000).to_s(36)}" path << "-#{n}" if n path << suffix mkdir(path, 0700) rescue Errno::EEXIST n ||= 0 n += 1 retry end if block_given? begin yield path ensure require 'fileutils' # This here was using FileUtils.remove_entry_secure instead of just # .rm_r. However, the security concerns that apply to # .rm_r/.remove_entry_secure shouldn't apply to a test fake # filesystem. :^) FileUtils.rm_r path end else path end end class << self alias_method :getwd, :pwd alias_method :rmdir, :delete alias_method :unlink, :delete end end end fakefs-0.4.2/lib/fakefs/pathname.rb0000644000004100000410000006534412057273366017162 0ustar www-datawww-datamodule FakeFS if RUBY_VERSION >= "1.9.3" # # = pathname.rb - From MRI 1.9.2 # # Object-Oriented Pathname Class # # Author:: Tanaka Akira # Documentation:: Author and Gavin Sinclair # # For documentation, see class Pathname. # class Pathname # to_path is implemented so Pathname objects are usable with File.open, etc. TO_PATH = :to_path SAME_PATHS = if File::FNM_SYSCASE.nonzero? proc {|a, b| a.casecmp(b).zero?} else proc {|a, b| a == b} end # :startdoc: # # Create a Pathname object from the given String (or String-like object). # If +path+ contains a NUL character (\0), an ArgumentError is raised. # def initialize(path) path = path.__send__(TO_PATH) if path.respond_to? TO_PATH @path = path.dup if /\0/ =~ @path raise ArgumentError, "pathname contains \\0: #{@path.inspect}" end self.taint if @path.tainted? end def freeze() super; @path.freeze; self end def taint() super; @path.taint; self end def untaint() super; @path.untaint; self end # # Compare this pathname with +other+. The comparison is string-based. # Be aware that two different paths (foo.txt and ./foo.txt) # can refer to the same file. # def ==(other) return false unless Pathname === other other.to_s == @path end alias === == alias eql? == # Provides for comparing pathnames, case-sensitively. def <=>(other) return nil unless Pathname === other @path.tr('/', "\0") <=> other.to_s.tr('/', "\0") end def hash # :nodoc: @path.hash end # Return the path as a String. def to_s @path.dup end # to_path is implemented so Pathname objects are usable with File.open, etc. alias_method TO_PATH, :to_s def inspect # :nodoc: "#<#{self.class}:#{@path}>" end # Return a pathname which is substituted by String#sub. def sub(pattern, *rest, &block) if block path = @path.sub(pattern, *rest) {|*args| begin old = Thread.current[:pathname_sub_matchdata] Thread.current[:pathname_sub_matchdata] = $~ eval("$~ = Thread.current[:pathname_sub_matchdata]", block.binding) ensure Thread.current[:pathname_sub_matchdata] = old end yield(*args) } else path = @path.sub(pattern, *rest) end self.class.new(path) end if File::ALT_SEPARATOR SEPARATOR_LIST = "#{Regexp.quote File::ALT_SEPARATOR}#{Regexp.quote File::SEPARATOR}" SEPARATOR_PAT = /[#{SEPARATOR_LIST}]/ else SEPARATOR_LIST = "#{Regexp.quote File::SEPARATOR}" SEPARATOR_PAT = /#{Regexp.quote File::SEPARATOR}/ end # Return a pathname which the extension of the basename is substituted by # repl. # # If self has no extension part, repl is appended. def sub_ext(repl) ext = File.extname(@path) self.class.new(@path.chomp(ext) + repl) end # chop_basename(path) -> [pre-basename, basename] or nil def chop_basename(path) base = File.basename(path) if /\A#{SEPARATOR_PAT}?\z/o =~ base return nil else return path[0, path.rindex(base)], base end end private :chop_basename # split_names(path) -> prefix, [name, ...] def split_names(path) names = [] while r = chop_basename(path) path, basename = r names.unshift basename end return path, names end private :split_names def prepend_prefix(prefix, relpath) if relpath.empty? File.dirname(prefix) elsif /#{SEPARATOR_PAT}/o =~ prefix prefix = File.dirname(prefix) prefix = File.join(prefix, "") if File.basename(prefix + 'a') != 'a' prefix + relpath else prefix + relpath end end private :prepend_prefix # Returns clean pathname of +self+ with consecutive slashes and useless dots # removed. The filesystem is not accessed. # # If +consider_symlink+ is +true+, then a more conservative algorithm is used # to avoid breaking symbolic linkages. This may retain more .. # entries than absolutely necessary, but without accessing the filesystem, # this can't be avoided. See #realpath. # def cleanpath(consider_symlink=false) if consider_symlink cleanpath_conservative else cleanpath_aggressive end end # # Clean the path simply by resolving and removing excess "." and ".." entries. # Nothing more, nothing less. # def cleanpath_aggressive path = @path names = [] pre = path while r = chop_basename(pre) pre, base = r case base when '.' when '..' names.unshift base else if names[0] == '..' names.shift else names.unshift base end end end if /#{SEPARATOR_PAT}/o =~ File.basename(pre) names.shift while names[0] == '..' end self.class.new(prepend_prefix(pre, File.join(*names))) end private :cleanpath_aggressive # has_trailing_separator?(path) -> bool def has_trailing_separator?(path) if r = chop_basename(path) pre, basename = r pre.length + basename.length < path.length else false end end private :has_trailing_separator? # add_trailing_separator(path) -> path def add_trailing_separator(path) if File.basename(path + 'a') == 'a' path else File.join(path, "") # xxx: Is File.join is appropriate to add separator? end end private :add_trailing_separator def del_trailing_separator(path) if r = chop_basename(path) pre, basename = r pre + basename elsif /#{SEPARATOR_PAT}+\z/o =~ path $` + File.dirname(path)[/#{SEPARATOR_PAT}*\z/o] else path end end private :del_trailing_separator def cleanpath_conservative path = @path names = [] pre = path while r = chop_basename(pre) pre, base = r names.unshift base if base != '.' end if /#{SEPARATOR_PAT}/o =~ File.basename(pre) names.shift while names[0] == '..' end if names.empty? self.class.new(File.dirname(pre)) else if names.last != '..' && File.basename(path) == '.' names << '.' end result = prepend_prefix(pre, File.join(*names)) if /\A(?:\.|\.\.)\z/ !~ names.last && has_trailing_separator?(path) self.class.new(add_trailing_separator(result)) else self.class.new(result) end end end private :cleanpath_conservative # # Returns the real (absolute) pathname of +self+ in the actual # filesystem not containing symlinks or useless dots. # # All components of the pathname must exist when this method is # called. # def realpath(basedir=nil) self.class.new(File.realpath(@path, basedir)) end # # Returns the real (absolute) pathname of +self+ in the actual filesystem. # The real pathname doesn't contain symlinks or useless dots. # # The last component of the real pathname can be nonexistent. # def realdirpath(basedir=nil) self.class.new(File.realdirpath(@path, basedir)) end # #parent returns the parent directory. # # This is same as self + '..'. def parent self + '..' end # #mountpoint? returns +true+ if self points to a mountpoint. def mountpoint? begin stat1 = self.lstat stat2 = self.parent.lstat stat1.dev == stat2.dev && stat1.ino == stat2.ino || stat1.dev != stat2.dev rescue Errno::ENOENT false end end # # #root? is a predicate for root directories. I.e. it returns +true+ if the # pathname consists of consecutive slashes. # # It doesn't access actual filesystem. So it may return +false+ for some # pathnames which points to roots such as /usr/... # def root? !!(chop_basename(@path) == nil && /#{SEPARATOR_PAT}/o =~ @path) end # Predicate method for testing whether a path is absolute. # It returns +true+ if the pathname begins with a slash. def absolute? !relative? end # The opposite of #absolute? def relative? path = @path while r = chop_basename(path) path, basename = r end path == '' end # # Iterates over each component of the path. # # Pathname.new("/usr/bin/ruby").each_filename {|filename| ... } # # yields "usr", "bin", and "ruby". # def each_filename # :yield: filename return to_enum(__method__) unless block_given? prefix, names = split_names(@path) names.each {|filename| yield filename } nil end # Iterates over and yields a new Pathname object # for each element in the given path in descending order. # # Pathname.new('/path/to/some/file.rb').descend {|v| p v} # # # # # # # # # # # # Pathname.new('path/to/some/file.rb').descend {|v| p v} # # # # # # # # # # It doesn't access actual filesystem. # # This method is available since 1.8.5. # def descend vs = [] ascend {|v| vs << v } vs.reverse_each {|v| yield v } nil end # Iterates over and yields a new Pathname object # for each element in the given path in ascending order. # # Pathname.new('/path/to/some/file.rb').ascend {|v| p v} # # # # # # # # # # # # Pathname.new('path/to/some/file.rb').ascend {|v| p v} # # # # # # # # # # It doesn't access actual filesystem. # # This method is available since 1.8.5. # def ascend path = @path yield self while r = chop_basename(path) path, name = r break if path.empty? yield self.class.new(del_trailing_separator(path)) end end # # Pathname#+ appends a pathname fragment to this one to produce a new Pathname # object. # # p1 = Pathname.new("/usr") # Pathname:/usr # p2 = p1 + "bin/ruby" # Pathname:/usr/bin/ruby # p3 = p1 + "/etc/passwd" # Pathname:/etc/passwd # # This method doesn't access the file system; it is pure string manipulation. # def +(other) other = Pathname.new(other) unless Pathname === other Pathname.new(plus(@path, other.to_s)) end def plus(path1, path2) # -> path prefix2 = path2 index_list2 = [] basename_list2 = [] while r2 = chop_basename(prefix2) prefix2, basename2 = r2 index_list2.unshift prefix2.length basename_list2.unshift basename2 end return path2 if prefix2 != '' prefix1 = path1 while true while !basename_list2.empty? && basename_list2.first == '.' index_list2.shift basename_list2.shift end break unless r1 = chop_basename(prefix1) prefix1, basename1 = r1 next if basename1 == '.' if basename1 == '..' || basename_list2.empty? || basename_list2.first != '..' prefix1 = prefix1 + basename1 break end index_list2.shift basename_list2.shift end r1 = chop_basename(prefix1) if !r1 && /#{SEPARATOR_PAT}/o =~ File.basename(prefix1) while !basename_list2.empty? && basename_list2.first == '..' index_list2.shift basename_list2.shift end end if !basename_list2.empty? suffix2 = path2[index_list2.first..-1] r1 ? File.join(prefix1, suffix2) : prefix1 + suffix2 else r1 ? prefix1 : File.dirname(prefix1) end end private :plus # # Pathname#join joins pathnames. # # path0.join(path1, ..., pathN) is the same as # path0 + path1 + ... + pathN. # def join(*args) args.unshift self result = args.pop result = Pathname.new(result) unless Pathname === result return result if result.absolute? args.reverse_each {|arg| arg = Pathname.new(arg) unless Pathname === arg result = arg + result return result if result.absolute? } result end # # Returns the children of the directory (files and subdirectories, not # recursive) as an array of Pathname objects. By default, the returned # pathnames will have enough information to access the files. If you set # +with_directory+ to +false+, then the returned pathnames will contain the # filename only. # # For example: # pn = Pathname("/usr/lib/ruby/1.8") # pn.children # # -> [ Pathname:/usr/lib/ruby/1.8/English.rb, # Pathname:/usr/lib/ruby/1.8/Env.rb, # Pathname:/usr/lib/ruby/1.8/abbrev.rb, ... ] # pn.children(false) # # -> [ Pathname:English.rb, Pathname:Env.rb, Pathname:abbrev.rb, ... ] # # Note that the result never contain the entries . and .. in # the directory because they are not children. # # This method has existed since 1.8.1. # def children(with_directory=true) with_directory = false if @path == '.' result = [] Dir.foreach(@path) {|e| next if e == '.' || e == '..' if with_directory result << self.class.new(File.join(@path, e)) else result << self.class.new(e) end } result end # Iterates over the children of the directory # (files and subdirectories, not recursive). # It yields Pathname object for each child. # By default, the yielded pathnames will have enough information to access the files. # If you set +with_directory+ to +false+, then the returned pathnames will contain the filename only. # # Pathname("/usr/local").each_child {|f| p f } # #=> # # # # # # # # # # # # # # # # # # # # # # # # Pathname("/usr/local").each_child(false) {|f| p f } # #=> # # # # # # # # # # # # # # # # # # # # # # # def each_child(with_directory=true, &b) children(with_directory).each(&b) end # # #relative_path_from returns a relative path from the argument to the # receiver. If +self+ is absolute, the argument must be absolute too. If # +self+ is relative, the argument must be relative too. # # #relative_path_from doesn't access the filesystem. It assumes no symlinks. # # ArgumentError is raised when it cannot find a relative path. # # This method has existed since 1.8.1. # def relative_path_from(base_directory) dest_directory = self.cleanpath.to_s base_directory = base_directory.cleanpath.to_s dest_prefix = dest_directory dest_names = [] while r = chop_basename(dest_prefix) dest_prefix, basename = r dest_names.unshift basename if basename != '.' end base_prefix = base_directory base_names = [] while r = chop_basename(base_prefix) base_prefix, basename = r base_names.unshift basename if basename != '.' end unless SAME_PATHS[dest_prefix, base_prefix] raise ArgumentError, "different prefix: #{dest_prefix.inspect} and #{base_directory.inspect}" end while !dest_names.empty? && !base_names.empty? && SAME_PATHS[dest_names.first, base_names.first] dest_names.shift base_names.shift end if base_names.include? '..' raise ArgumentError, "base_directory has ..: #{base_directory.inspect}" end base_names.fill('..') relpath_names = base_names + dest_names if relpath_names.empty? Pathname.new('.') else Pathname.new(File.join(*relpath_names)) end end end class Pathname # * IO * # # #each_line iterates over the line in the file. It yields a String object # for each line. # # This method has existed since 1.8.1. # def each_line(*args, &block) # :yield: line IO.foreach(@path, *args, &block) end # See IO.read. Returns all data from the file, or the first +N+ bytes # if specified. def read(*args) IO.read(@path, *args) end # See IO.binread. Returns all the bytes from the file, or the first +N+ # if specified. def binread(*args) IO.binread(@path, *args) end # See IO.readlines. Returns all the lines from the file. def readlines(*args) IO.readlines(@path, *args) end # See IO.sysopen. def sysopen(*args) IO.sysopen(@path, *args) end end class Pathname # * File * # See File.atime. Returns last access time. def atime() File.atime(@path) end # See File.ctime. Returns last (directory entry, not file) change time. def ctime() File.ctime(@path) end # See File.mtime. Returns last modification time. def mtime() File.mtime(@path) end # See File.chmod. Changes permissions. def chmod(mode) File.chmod(mode, @path) end # See File.lchmod. def lchmod(mode) File.lchmod(mode, @path) end # See File.chown. Change owner and group of file. def chown(owner, group) File.chown(owner, group, @path) end # See File.lchown. def lchown(owner, group) File.lchown(owner, group, @path) end # See File.fnmatch. Return +true+ if the receiver matches the given # pattern. def fnmatch(pattern, *args) File.fnmatch(pattern, @path, *args) end # See File.fnmatch? (same as #fnmatch). def fnmatch?(pattern, *args) File.fnmatch?(pattern, @path, *args) end # See File.ftype. Returns "type" of file ("file", "directory", # etc). def ftype() File.ftype(@path) end # See File.link. Creates a hard link. def make_link(old) File.link(old, @path) end # See File.open. Opens the file for reading or writing. def open(*args, &block) # :yield: file File.open(@path, *args, &block) end # See File.readlink. Read symbolic link. def readlink() self.class.new(File.readlink(@path)) end # See File.rename. Rename the file. def rename(to) File.rename(@path, to) end # See File.stat. Returns a File::Stat object. def stat() File.stat(@path) end # See File.lstat. def lstat() File.lstat(@path) end # See File.symlink. Creates a symbolic link. def make_symlink(old) File.symlink(old, @path) end # See File.truncate. Truncate the file to +length+ bytes. def truncate(length) File.truncate(@path, length) end # See File.utime. Update the access and modification times. def utime(atime, mtime) File.utime(atime, mtime, @path) end # See File.basename. Returns the last component of the path. def basename(*args) self.class.new(File.basename(@path, *args)) end # See File.dirname. Returns all but the last component of the path. def dirname() self.class.new(File.dirname(@path)) end # See File.extname. Returns the file's extension. def extname() File.extname(@path) end # See File.expand_path. def expand_path(*args) self.class.new(File.expand_path(@path, *args)) end # See File.split. Returns the #dirname and the #basename in an # Array. def split() File.split(@path).map {|f| self.class.new(f) } end end class Pathname # * FileTest * # See FileTest.blockdev?. def blockdev?() FileTest.blockdev?(@path) end # See FileTest.chardev?. def chardev?() FileTest.chardev?(@path) end # See FileTest.executable?. def executable?() FileTest.executable?(@path) end # See FileTest.executable_real?. def executable_real?() FileTest.executable_real?(@path) end # See FileTest.exist?. def exist?() FileTest.exist?(@path) end # See FileTest.grpowned?. def grpowned?() FileTest.grpowned?(@path) end # See FileTest.directory?. def directory?() FileTest.directory?(@path) end # See FileTest.file?. def file?() FileTest.file?(@path) end # See FileTest.pipe?. def pipe?() FileTest.pipe?(@path) end # See FileTest.socket?. def socket?() FileTest.socket?(@path) end # See FileTest.owned?. def owned?() FileTest.owned?(@path) end # See FileTest.readable?. def readable?() FileTest.readable?(@path) end # See FileTest.world_readable?. def world_readable?() FileTest.world_readable?(@path) end # See FileTest.readable_real?. def readable_real?() FileTest.readable_real?(@path) end # See FileTest.setuid?. def setuid?() FileTest.setuid?(@path) end # See FileTest.setgid?. def setgid?() FileTest.setgid?(@path) end # See FileTest.size. def size() FileTest.size(@path) end # See FileTest.size?. def size?() FileTest.size?(@path) end # See FileTest.sticky?. def sticky?() FileTest.sticky?(@path) end # See FileTest.symlink?. def symlink?() FileTest.symlink?(@path) end # See FileTest.writable?. def writable?() FileTest.writable?(@path) end # See FileTest.world_writable?. def world_writable?() FileTest.world_writable?(@path) end # See FileTest.writable_real?. def writable_real?() FileTest.writable_real?(@path) end # See FileTest.zero?. def zero?() FileTest.zero?(@path) end end class Pathname # * Dir * # See Dir.glob. Returns or yields Pathname objects. def Pathname.glob(*args) # :yield: pathname if block_given? Dir.glob(*args) {|f| yield self.new(f) } else Dir.glob(*args).map {|f| self.new(f) } end end # See Dir.getwd. Returns the current working directory as a Pathname. def Pathname.getwd() self.new(Dir.getwd) end class << self; alias pwd getwd end # Return the entries (files and subdirectories) in the directory, each as a # Pathname object. def entries() Dir.entries(@path).map {|f| self.class.new(f) } end # Iterates over the entries (files and subdirectories) in the directory. It # yields a Pathname object for each entry. # # This method has existed since 1.8.1. def each_entry(&block) # :yield: pathname Dir.foreach(@path) {|f| yield self.class.new(f) } end # See Dir.mkdir. Create the referenced directory. def mkdir(*args) Dir.mkdir(@path, *args) end # See Dir.rmdir. Remove the referenced directory. def rmdir() Dir.rmdir(@path) end # See Dir.open. def opendir(&block) # :yield: dir Dir.open(@path, &block) end end class Pathname # * Find * # # Pathname#find is an iterator to traverse a directory tree in a depth first # manner. It yields a Pathname for each file under "this" directory. # # Since it is implemented by find.rb, Find.prune can be used # to control the traverse. # # If +self+ is ., yielded pathnames begin with a filename in the # current directory, not ./. # def find(&block) # :yield: pathname require 'find' if @path == '.' Find.find(@path) {|f| yield self.class.new(f.sub(%r{\A\./}, '')) } else Find.find(@path) {|f| yield self.class.new(f) } end end end class Pathname # * FileUtils * # See FileUtils.mkpath. Creates a full path, including any # intermediate directories that don't yet exist. def mkpath require 'fileutils' FileUtils.mkpath(@path) nil end # See FileUtils.rm_r. Deletes a directory and all beneath it. def rmtree # The name "rmtree" is borrowed from File::Path of Perl. # File::Path provides "mkpath" and "rmtree". require 'fileutils' FileUtils.rm_r(@path) nil end end class Pathname # * mixed * # Removes a file or directory, using File.unlink or # Dir.unlink as necessary. def unlink() begin Dir.unlink @path rescue Errno::ENOTDIR File.unlink @path end end alias delete unlink end class Pathname undef =~ end end # RUBY_VERSION >= 1.9.3 end fakefs-0.4.2/lib/fakefs/safe.rb0000644000004100000410000000050412057273366016266 0ustar www-datawww-datarequire 'fileutils' require 'pathname' require 'fakefs/base' require 'fakefs/fake/file' require 'fakefs/fake/dir' require 'fakefs/fake/symlink' require 'fakefs/file_system' require 'fakefs/fileutils' require 'fakefs/file' require 'fakefs/file_test' require 'fakefs/dir' require 'fakefs/pathname' if RUBY_VERSION >= "1.9.3" fakefs-0.4.2/lib/fakefs.rb0000644000004100000410000000005012057273366015344 0ustar www-datawww-datarequire 'fakefs/safe' FakeFS.activate! fakefs-0.4.2/Gemfile.lock0000644000004100000410000000104012057273366015234 0ustar www-datawww-dataGEM remote: http://rubygems.org/ specs: diff-lcs (1.1.3) git (1.2.5) jeweler (1.8.4) bundler (~> 1.0) git (>= 1.2.5) rake rdoc json (1.7.5) rake (10.0.0) rdiscount (1.6.8) rdoc (3.12) json (~> 1.4) rspec (2.12.0) rspec-core (~> 2.12.0) rspec-expectations (~> 2.12.0) rspec-mocks (~> 2.12.0) rspec-core (2.12.0) rspec-expectations (2.12.0) diff-lcs (~> 1.1.3) rspec-mocks (2.12.0) PLATFORMS ruby DEPENDENCIES jeweler rdiscount rspec fakefs-0.4.2/fakefs.gemspec0000644000004100000410000000463412057273366015632 0ustar www-datawww-data# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "fakefs" s.version = "0.4.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Chris Wanstrath", "Scott Taylor", "Jeff Hodges", "Pat Nakajima"] s.date = "2012-11-24" s.description = "A fake filesystem. Use it in your tests." s.email = "chris@ozmm.org" s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] s.files = [ ".autotest", ".rspec", ".travis.yml", "CONTRIBUTORS", "Gemfile", "Gemfile.lock", "LICENSE", "README.markdown", "Rakefile", "fakefs.gemspec", "lib/fakefs.rb", "lib/fakefs/base.rb", "lib/fakefs/dir.rb", "lib/fakefs/fake/dir.rb", "lib/fakefs/fake/file.rb", "lib/fakefs/fake/symlink.rb", "lib/fakefs/file.rb", "lib/fakefs/file_system.rb", "lib/fakefs/file_test.rb", "lib/fakefs/fileutils.rb", "lib/fakefs/pathname.rb", "lib/fakefs/safe.rb", "lib/fakefs/spec_helpers.rb", "lib/fakefs/version.rb", "spec/fakefs/spec_helpers_spec.rb", "spec/spec.opts", "spec/spec_helper.rb", "test/fake/file/join_test.rb", "test/fake/file/lstat_test.rb", "test/fake/file/stat_test.rb", "test/fake/file/sysseek_test.rb", "test/fake/file/syswrite_test.rb", "test/fake/file_test.rb", "test/fake/symlink_test.rb", "test/fakefs_test.rb", "test/file/stat_test.rb", "test/safe_test.rb", "test/test_helper.rb", "test/verify.rb" ] s.homepage = "http://github.com/defunkt/fakefs" s.require_paths = ["lib"] s.rubygems_version = "1.8.24" s.summary = "A fake filesystem. Use it in your tests." if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q, [">= 0"]) s.add_development_dependency(%q, [">= 0"]) s.add_development_dependency(%q, [">= 0"]) else s.add_dependency(%q, [">= 0"]) s.add_dependency(%q, [">= 0"]) s.add_dependency(%q, [">= 0"]) end else s.add_dependency(%q, [">= 0"]) s.add_dependency(%q, [">= 0"]) s.add_dependency(%q, [">= 0"]) end end