Giter Site home page Giter Site logo

testableio / system.io.abstractions Goto Github PK

View Code? Open in Web Editor NEW
1.5K 34.0 256.0 4.24 MB

Just like System.Web.Abstractions, but for System.IO. Yay for testable IO access!

Home Page: http://www.nuget.org/packages/System.IO.Abstractions

License: MIT License

C# 100.00%
testing mocks dotnet c-sharp filesystem io cross-platform tdd

system.io.abstractions's Introduction

System.IO.Abstractions NuGet Continuous Integration Codacy Badge Renovate enabled FOSSA Status

At the core of the library is IFileSystem and FileSystem. Instead of calling methods like File.ReadAllText directly, use IFileSystem.File.ReadAllText. We have exactly the same API, except that ours is injectable and testable.

Usage

dotnet add package TestableIO.System.IO.Abstractions.Wrappers

Note: This NuGet package is also published as System.IO.Abstractions but we suggest to use the prefix to make clear that this is not an official .NET package.

public class MyComponent
{
    readonly IFileSystem fileSystem;

    // <summary>Create MyComponent with the given fileSystem implementation</summary>
    public MyComponent(IFileSystem fileSystem)
    {
        this.fileSystem = fileSystem;
    }
    /// <summary>Create MyComponent</summary>
    public MyComponent() : this(
        fileSystem: new FileSystem() //use default implementation which calls System.IO
    )
    {
    }

    public void Validate()
    {
        foreach (var textFile in fileSystem.Directory.GetFiles(@"c:\", "*.txt", SearchOption.TopDirectoryOnly))
        {
            var text = fileSystem.File.ReadAllText(textFile);
            if (text != "Testing is awesome.")
                throw new NotSupportedException("We can't go on together. It's not me, it's you.");
        }
    }
}

Test helpers

The library also ships with a series of test helpers to save you from having to mock out every call, for basic scenarios. They are not a complete copy of a real-life file system, but they'll get you most of the way there.

dotnet add package TestableIO.System.IO.Abstractions.TestingHelpers

Note: This NuGet package is also published as System.IO.Abstractions.TestingHelpers but we suggest to use the prefix to make clear that this is not an official .NET package.

[Test]
public void MyComponent_Validate_ShouldThrowNotSupportedExceptionIfTestingIsNotAwesome()
{
    // Arrange
    var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
    {
        { @"c:\myfile.txt", new MockFileData("Testing is meh.") },
        { @"c:\demo\jQuery.js", new MockFileData("some js") },
        { @"c:\demo\image.gif", new MockFileData(new byte[] { 0x12, 0x34, 0x56, 0xd2 }) }
    });
    var component = new MyComponent(fileSystem);

    try
    {
        // Act
        component.Validate();
    }
    catch (NotSupportedException ex)
    {
        // Assert
        Assert.That(ex.Message, Is.EqualTo("We can't go on together. It's not me, it's you."));
        return;
    }

    Assert.Fail("The expected exception was not thrown.");
}

We even support casting from the .NET Framework's untestable types to our testable wrappers:

FileInfo SomeApiMethodThatReturnsFileInfo()
{
    return new FileInfo("a");
}

void MyFancyMethod()
{
    var testableFileInfo = (FileInfoBase)SomeApiMethodThatReturnsFileInfo();
    ...
}

Mock support

Since version 4.0 the top-level APIs expose interfaces instead of abstract base classes (these still exist, though), allowing you to completely mock the file system. Here's a small example, using Moq:

[Test]
public void Test1()
{
    var watcher = Mock.Of<IFileSystemWatcher>();
    var file = Mock.Of<IFile>();

    Mock.Get(file).Setup(f => f.Exists(It.IsAny<string>())).Returns(true);
    Mock.Get(file).Setup(f => f.ReadAllText(It.IsAny<string>())).Throws<OutOfMemoryException>();

    var unitUnderTest = new SomeClassUsingFileSystemWatcher(watcher, file);

    Assert.Throws<OutOfMemoryException>(() => {
        Mock.Get(watcher).Raise(w => w.Created += null, new System.IO.FileSystemEventArgs(System.IO.WatcherChangeTypes.Created, @"C:\Some\Directory", "Some.File"));
    });

    Mock.Get(file).Verify(f => f.Exists(It.IsAny<string>()), Times.Once);

    Assert.True(unitUnderTest.FileWasCreated);
}

public class SomeClassUsingFileSystemWatcher
{
    private readonly IFileSystemWatcher _watcher;
    private readonly IFile _file;

    public bool FileWasCreated { get; private set; }

    public SomeClassUsingFileSystemWatcher(IFileSystemWatcher watcher, IFile file)
    {
        this._file = file;
        this._watcher = watcher;
        this._watcher.Created += Watcher_Created;
    }

    private void Watcher_Created(object sender, System.IO.FileSystemEventArgs e)
    {
        FileWasCreated = true;

        if(_file.Exists(e.FullPath))
        {
            var text = _file.ReadAllText(e.FullPath);
        }
    }
}

Related projects

system.io.abstractions's People

Contributors

dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar eggnstone avatar ericnewton76 avatar fgreinacher avatar hangy avatar ilkerde avatar jpreese avatar kalldrexx avatar limdaepl avatar lythix avatar manne avatar martindevans avatar patrykolejniczak avatar pianomanjh avatar rcdailey avatar renovate-bot avatar renovate[bot] avatar rkoeninger avatar robertlarkins avatar robkeim avatar roketworks avatar siprbaum avatar srasch avatar tathamoddie avatar tomgillen avatar vbreuss avatar vigneshmoha avatar wtjones avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

system.io.abstractions's Issues

MockFileSystem should have an empty constructor

I'm putting this out to get comments.

It seems like MockFileSystem should have an empty constructor. Granted, you can initialize with an empty dictionary<string,FileData> instance.

What do you guys think?

Inconsistency in MockFile.WriteAllText

There is an inconsistency in MockFile.WriteAllText (and WriteAllLines), the method does not respect the encoding's preamble.
The expectation is, that there should be a BOM.

Example

static void Main()
{
    IFileSystem fs = new MockFileSystem();
    string mockPath = fs.Path.GetTempFileName();
    var mockContent = WriteAllText(fs, mockPath);

    IFileSystem fsr = new FileSystem();
    string tempPath = System.IO.Path.GetTempFileName();
    var realContent = WriteAllText(fsr, mockPath);

    if(!mockContent.Equals(realContent))
    {
        throw new Exception("Should have equal content");
    }
}

static byte[] WriteAllText(IFileSystem fs, string path)
{
    fs.File.WriteAllText(path, "using", Encoding.UTF8);
    var result = fs.File.ReadAllBytes(path);
    fs.File.Delete(path);
    return result;
}

Reading from a file via MockFileStream resets creation time

when having a mocked file in a mockfilesystem, and readfing from it mutates the LastWriteTime of the mocked file.
Here is an XUnit fact which can be used as a regression test to verify the problem, and the solution.

        [Fact]
        public void ReadingFromAFileDoesNotOverwriteIt() {
            // Arrange
            var fs = new MockFileSystem();
            var filename = @"C:\TestData\test.txt";
            var file = new MockFileData(@"This is just a test file

with test contents, which are not modified!");
            var lastmod = new DateTime(2012, 03, 21);
            file.LastWriteTime = lastmod;
            fs.AddFile(filename, file);

            // Act
            using (var reader = fs.File.OpenText(filename)) {
                var firstline = reader.ReadLine();
            }

            // Assert
            Assert.Equal(lastmod, fs.FileInfo.FromFileName(filename).LastWriteTime);
        }

Directory.Exists throws exception for invalid UNC paths

If you call the System.IO versions of Directory.Exists with an invalid UNC path such as "\s" then it returns False.

When calling it from System.IO.Abstractions (v. 1.4.0.86) it is throwing an exception

new MockFileSystem().Directory.Exists(@"\\s");

Exception:

System.ArgumentException: The UNC path should be of the form \\server\share.
Parameter name: path
   at System.IO.Abstractions.TestingHelpers.MockPath.GetFullPath(String path)
   at System.IO.Abstractions.TestingHelpers.MockDirectory.Exists(String path)

Add dotnetcore support

Now the first release candidate is out it'd be great if dotnetcore support could be added in preparation for the first RTM release.

Reading through #25 I noticed the whole issue surrounding corefx and filesystem testability has already been discussed in dotnet/corefx#312. It looks like at some point they're going to redesign the filesystem related framework classes.

This might take some time so until then it'd be good if System.IO.Abstractions could support dotnetcore.

Release notes

It would be very helpful if you could maintain a wiki page or document with the release notes for each version. I'm still on 1.4.0.x but I have no idea if 2.0.0.x has backwards incompatible changes (I assume it does since you bumped the major version). This is preventing me from upgrading to the latest version.

If 2.0.0.x is backwards incompatible, what are the breaking changes?

help using the FileSystemWatcherWrapper in UnitTets

hello.

I am writing some unit tests and wanted to use the FileSystemWatcherWrapper to look at a dir to check if files are added or deleted, but the problem is even if I am using the FileSystemWatcherWrapper the events will be raised on changes to my real file system and I don't see any way to set a custom FileSystem to the Watcher, can you please tell me if this is possible?

thank you in advance

MockFileData Encoding

When I give an encoding to MockFileData it creates the contents with that encoding. However when I try to read the TextContents it always uses the DefaultEncoding. Is this an expected behavior? Shouldn't it use the given encoding? Here is a failling test:

[Test]
public void MockFile_ReadAllText_ShouldReturnTheGivenTextExactlyOnUTF8EncodingWithBOM()
{
    // Arrange
    string path = XFS.Path(@"c:\something\demo.txt");
    string fileContent = "Hello there!";
    var fileSystem = new MockFileSystem();
    var fileData = new MockFileData(fileContent, new UTF8Encoding(true));
    fileSystem.AddFile(path, fileData);

    // Act
    string result = fileSystem.File.ReadAllText(path);
    // Assert
    Assert.AreEqual(
        fileContent,
        result);
}

MockPath implementations

I'm using MockPath to get back InvalidPathChars and DirectorySeparatorChar type things, I can't see any problem with the MockPath class actually returning Path.DirectorySeparatorChar but thought I'd check before doing a PR or asking you to quickly implement it

MockFileSystem.File.GetAttributes does not throw FileNotFoundException

If file C:\test123123 does not exist, then

var fileSystem = new FileSystem();
 Console.WriteLine(fileSystem.File.GetAttributes(@"C:\test123123"));

throws as excpected, but

var fileSystem = new MockFileSystem();
Console.WriteLine(fileSystem.File.GetAttributes(@"C:\test123123"));

does not throw.

System.IO.Abstractions 2.0.0.120

MockDirectory.Move doesn't throw exceptions

The MockDirectory.Move method doesn't throw an exception when the directory names are the same, while Directory.Move does. This is not only so for the Move method, but also for other methods.
You probably want a pull request for this?

Should the testing helpers be renamed to "Stub" instead of "Mock"?

I spent a bit of time trying to verify that a call to "FileSystem.Directory.CreateDirectory" was called with the correct parameter before I realised that the testing helpers aren't really mocks, they are stubs.

Martin Folwer's definitions from here

Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.

Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.

I realize that this would potentially be a breaking change. Perhaps only the documentation could be updated to clarify this? Alternately, all the existing functionality can be renamed to stubs and a new mocking version (based on an existing mocking framework) can be provided that mimics the existing stub functionality while maintaining backward compatibility.

Directory.Exists does not return true if file is added using AddFile [Regression]

Just upgraded pretzel from v1.4.0.44 to v1.4.0.49 and a heap of our tests started failing

Below is a new test which fails, but should pass

    [Test]
    public void MockDirectory_Exists_ShouldReturnTrueForFolderContainingFileAddedToMockFileSystem()
    {
        // Arrange
        var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>());
        fileSystem.AddFile(@"c:\foo\bar.txt", new MockFileData("Demo text content"));

        // Act
        var result = fileSystem.Directory.Exists(@"c:\foo\");

        // Assert
        Assert.IsTrue(result);
    }

NuGet package 2.0.0.115 missing

It looks like somehow the latest NuGet binaries are missing. The Gallery shows 2.0.0.114 and 2.0.0.115 should exist, but when actually requesting the package you're told the package doesn't exist.

PM> get-package -listavailable -filter system.io.abstractions

Id                             Version              Description/Release Notes                                                                                                                                       
--                             -------              -------------------------                                                                                                                                       
AshMind.IO.Abstractions        0.8.0                Similar to System.IO.Abstractions package, but with .NET 4.5 methods and slightly different API.                                                                
System.IO.Abstractions         2.0.0.113            Just like System.Web.Abstractions, but for System.IO. Yay for testable IO access! Be sure to check out the System.IO.Abstractions.TestingHelpers package too.   
System.IO.Abstractions.Test... 2.0.0.113            Testing helpers for the System.IO.Abstractions package to save having to manually mock everything.

When restoring the following error is received.

"C:\ProgramData\chocolatey\lib\NuGet.CommandLine.2.8.5\tools\NuGet.exe" restore Foo.sln
Unable to find version '2.0.0.115' of package 'System.IO.Abstractions'.

File raises from the deleted after "Dispose" in MockFileSystem

This test fails:

    <TestMethod()>
    Public Sub DeleteTest()

        Dim fileSystem = New MockFileSystem
        Const path As String = "C:\test"
        Dim directory As String = fileSystem.Path.GetDirectoryName(path)
        fileSystem.AddFile(path, New MockFileData("Bla"))
        Dim stream = fileSystem.File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.Delete)

        Dim actual1 = fileSystem.Directory.GetFiles(directory, "*").Count
        fileSystem.File.Delete(path)
        Dim actual2 = fileSystem.Directory.GetFiles(directory, "*").Count
        stream.Dispose()
        Dim actual3 = fileSystem.Directory.GetFiles(directory, "*").Count

        Assert.AreEqual(1, actual1, "-1-") 'Ok
        Assert.AreEqual(0, actual2, "-2-") 'Ok
        Assert.AreEqual(0, actual3, "-3-") 'Ups, should be 0, but is 1

    End Sub

MockDirectory.EnumerateFiles behave different from Directory.EnumerateFiles

Based on original .NET documentation, using Directory.EnumerateFiles should have one extra behavior:

If the specified extension is exactly three characters long, the method returns files with extensions that begin with the specified extension. For example, "*.xls" returns both "book.xls" and "book.xlsx".

Currently MockDirectory.EnumerateFiles will return "*.xls" only, which is highly logical, but different from original behavior of Directory.EnumerateFiles.

NullReferenceException when instantiating MockFileSystem in Mono/Mac

Environment

  • Xamarin Studio 4.3.4
  • Mono 3.4.0

Reproduction

new MockFileSystem()

Stacktrace

System.IO.Abstractions.TestingHelpers.MockPath.GetFullPath (path="C:\\Foo\\Bar")
System.IO.Abstractions.TestingHelpers.MockFileSystem.FixPath (path="C:\\Foo\\Bar")
System.IO.Abstractions.TestingHelpers.MockFileSystem..ctor (files=(null), currentDirectory="C:\\Foo\\Bar")
System.IO.Abstractions.TestingHelpers.MockFileSystem..ctor ()

Debugging shows that the MockFileSystem constructor calls FixPath which in turns calls this.pathField.GetFullPath (implemented by MockPath.GetFullPath). There's a call to this.mockFileDataAccessor.Directory.GetCurrentDirectory in GetFullPath which fails since MockFileSystem.Directory is null at this point.

TestingHelpers.MockFileSystem level flags to simulate ReadOnly filesystem and Out-Of-Space conditions

I was just considering the scenarios where it would be nice to test low-space conditions and unable to write conditions on the filesystem itself.

In theory, (on TestingHelpers.MockFileSystem) a property bool IsReadOnly and probably a MakeReadOnly method to force the filesystem into readonly mode.

In addition, another "testing" flag to force Out-Of-Space type of exceptions. I realize this could get a bit convoluted, whereby having to keep track of file allocations and byte sizes and so forth, but perhaps an initial "simplistic" version would just bomb on any "new" writes with "OutOfSpaceException" of some sort.

What does everybody else think?

Include files

I am parsing file content that supports include files. My Read() method takes a FileInfoBase object as parameter. I use PathWrapper to combine the original file name and include file name, then I'm reading the include file using a FileInfoWrapper. I'm quite sure that my whole chain uses Abstraction objects only.
However, when reading the include file, it accesses the real file system instead of the mock file system.
Any thoughts on how I could solve that?
Is there an easier way than introducing a FileFactory which creates MockFiles during tests and FileWrappers in real operation?

The repository hasn't been configured correctly for normalized line endings

The repository doesn't have any convention for line endings set up, hence everyone committing with a correctly configured git client is going to end up modifying every line in every file they touch. Hence #37, #31, #38, #30.

We should normalize line feeds in .gitattributes and make a one time commit fixing all line endings, as recommended by github (https://help.github.com/articles/dealing-with-line-endings and http://timclem.wordpress.com/2012/03/01/mind-the-end-of-your-line/).

Support MockFile.Delete

Currently throw NotImplemented. There is MockFileSystem.RemoveFile; however, it is not part of the contract/interface.

MockDirectory.Move fails if drive letters are different cases.

MockDirectory.Move() can fail if drive letters are different cases.

The problem can be duplicated with a slight modification of the MockDirectory_Move_ShouldMove() unit test. Simply change

{ XFS.Path(@"A:\folder1\folder2\file2.txt"), new MockFileData("bbb") },

to

{ XFS.Path(@"a:\folder1\folder2\file2.txt"), new MockFileData("bbb") },

And the test now fails with the following exception:

System.IO.IOException : Source and destination path must be different.
at System.IO.Abstractions.TestingHelpers.MockDirectory.Move(String sourceDirName, String destDirName) in MockDirectory.cs: line 300
at System.IO.Abstractions.TestingHelpers.MockDirectory.Move(String sourceDirName, String destDirName) in MockDirectory.cs: line 318
at System.IO.Abstractions.TestingHelpers.MockDirectoryInfo.MoveTo(String destDirName) in MockDirectoryInfo.cs: line 219
at System.IO.Abstractions.TestingHelpers.Tests.MockDirectoryTests.MockDirectory_Move_ShouldMove() in MockDirectoryTests.cs: line 730

Discuss: Test method names shortening by removing redundant test class name in method

Within the MockDirectoryTests type, do we really need to redundantly name the methods "MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternAndSearchOptionTopDirectoryOnly" with the name of the type?

Since this could shorten to:
GetFiles_ShouldFilterByExtensionBasedSearchPatternAndSearchOptionTopDirectoryOnly

I believe all the test runners report a test as

TypeName.TestMethod

so this illustrates the redundancy:

MockDirectoryTests.MockDirectory_GetFiles_ShouldFilterByExtensionBasedSearchPatternAndSearchOptionTopDirectoryOnly

Sorry... just a nitpick.

File/Directory search pattern

There is a difference between how the real FS does searchPatterns and how System.IO.Abstractions does them.

With a filesystem like this:

_fs = new MockFileSystem(new Dictionary<string, MockFileData>()
{
  { @"C:\Folder\a.foo", new MockFileData("aaa") },
  { @"C:\Folder\.foo\a.file", new MockFileData("bbb") }
}

Looking for *.foo we have two things, a file (a.foo) and a directory (C:\Folder.foo). However, this fails to find the directory (doing this in a similar setup in the real FS finds both):

    var dir = _fs.DirectoryInfo.FromDirectoryName("C:\\");
    var directories = dir.GetDirectories("*.foo");     //Nothing is found!

To make this work I need to use a slightly different search pattern:

*.foo\

Which finds the folder (but not the file a.foo).

I suspect the internal searching system (a quick glance shows it builds a regex) is being overly restrictive. The regex obviously wants directories (which are stored ending with a ) to have that double slash, even though windows file globs don't demand this.

MockFileSystem doesn't throw UnauthorizedAccessException when overriding a hidden file

The MockFileSystem doesn't behave the same way as the real FileSystem.
I know, its a mock, but this would be handy ;)

Testcode (if you want a PR with a real test case, just tell me)

        // Arrange
        var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
        {
            { @"C:\\Document\\Stuff\\MyDoc.foobar", new MockFileData("this is hidden") },
        });
        fileSystem.File.SetAttributes(@"C:\\Document\\Stuff\\MyDoc.foobar", FileAttributes.Hidden);

        // Act - this should thrown an UnauthorizeAccessException 
        fileSystem.File.WriteAllText(@"C:\\Document\\Stuff\\MyDoc.foobar", "hello world");

        // No Exception thrown, but it should - like in the real world 
        // http://stackoverflow.com/questions/2246990/how-do-i-write-to-a-hidden-file
        var content = fileSystem.File.ReadAllText(@"C:\\Document\\Stuff\\MyDoc.foobar");

content contains "hello world".

MockFileSystem.File.WriteAllText should throw an exception..

MockFileSystem.File.WriteAllText should throw a DirectoryNotFoundException if (at least) the parent directory of the path does not exist ( "C:\tmp\sioa\140\123123", directory "C:\tmp\sioa\140" can exist)

var fileSystem = new MockFileSystem();
fileSystem.File.WriteAllText(XFS.Path(@"C:\tmp\sioa\140\123123\demo.txt"), "Hello");

see #140

Store IFileSystem to FileSystemInfoBase in order to Create Files and Directories

I can create a FileInfoBase / DirectoryInfoBase during runtime only from IFileSystem.

If that IFileSystem object would be stored in the FileSystemInfoBase while creating (like fileSystem.DirectoryInfo.FromDirectoryName() we could create subfolders / files based on given DirectoryInfoBase later:
DirectoryInfoBase subDir = rootDir.CreateSubDirectory("subDirName)

Split Tests in partial classes

I would like to split some testclasses to some smaller classes (partials). One partial class for one method. Right now, there is one file "MockFileTests.cs" with ~1700 loc.

I think, it would be great to split them up and do it like this:

TestHelper.Tests (project)
  -- MockFileTests (folder)
      -- MockFileTests.Copy.cs
      -- MockFileTests.Move.cs

What do you think?

File.Copy(string, string, bool) Should Throw DirectoryNotFoundException

There is a discrepancy between the behavior of System.IO.File.Copy() and the behavior of System.IO.Abstractions.TestingHelpers.MockFile.Copy(). In the .NET library, if any part of the path of its second argument (destFileName) does not exist, it will throw a DirectoryNotFoundException. The code in MockFile's Copy() leads to an AddFile() that will create any missing directories automatically.

I would expect similar exceptions if the destination directory path does not exist in full.

For example, the following code will throw if you set up the source directory with an empty file and do not create the destination directory:

var filePath = @"C:\PathThatExists\fileName.txt";
File.Copy(filePath, @"C:\PathThatDoesNotExist\fileName.txt", true);

Not Issue, but discussion, How are people using this when dealing with code that doesn't understand the abstractions?

ie, using System.Net.WebClient to download or upload a file from the "mock repository":

  • For the DownloadFile operation, the file isn't written to the mock-repo and is written into the physical file system.
  • For the UploadFile operation, the file won't be found since it "lives" only in the mock-repo.

So a general question is, how is the community utilizing System.IO.Abstractions dealing with this problem?

Directory.Move fails when a directory with different case already exists

Here is a unit test that reproduces the issue.

`
[Test]
public void Move_DirectoryExistsWithDifferentCase_DirectorySuccessfullyMoved()
{
// Arrange
var fileSystem = new MockFileSystem();
fileSystem.AddDirectory(@"\builds\Builds\Suites\6.2.3.309 [6.2.3 135907]\TestShellHotFix\Data"); // HotFix with capital F
fileSystem.AddFile( @"\builds\Builds\Suites\6.2.3.309 [6.2.3 135907]\TestShellHotfix\Data\Content\DriverBuilder\ActiproSoftware.Navigation.Wpf.dll", new MockFileData("abc"));

        // Act
        fileSystem.Directory.Move(@"\\builds\Builds\Suites\6.2.3.309 [6.2.3 135907]\TestShellHotfix", // HotFix with lower f
                @"\\builds\Builds\Suites\6.2.3.309 [6.2.3 135907]\Hotfix1 for CloudShell 6.2.3 GA [6.2.3.187]");

        // Assert
        Assert.IsTrue(
            fileSystem.File.Exists(@"\\builds\Builds\Suites\6.2.3.309 [6.2.3 135907]\Hotfix1 for CloudShell 6.2.3 GA [6.2.3.187]\Data\Content\DriverBuilder\ActiproSoftware.Navigation.Wpf.dll"));
    }

`

Would an abstracted Environment class make sense to be added to System.IO.Abstractions?

I stumbled upon the need to have a mockable Environment.CurrentDirectory property. Quickly looking at its implementation, it's calling Directory.GetCurrentDirectory(), which is, unfortunately, not yet implemented in System.IO.Abstractions.

If someone (I) were to write an abstraction for System.Environment, would you consider merging it into System.IO.Abstractions? (it doesn't really belong to IO, but it uses several things from System.IO directly).

Implementation of File.Open(string,FileMode,FileAccess,FileShare)

So the implementation currently requests someone to do this.

However, the way that MockFileData and MockFileStream are separated makes this wierd.

MockFileData should change to a file system handle type of class that could keep track of the current mode of a file (this simulates the file system itself managing file handles/read-write locks/etc)

MockFileStream should be the primary holder of data, utilizing its internal MemoryStream's byte[].

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.