All Projects → System-IO-Abstractions → System.io.abstractions

System-IO-Abstractions / System.io.abstractions

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

Projects that are alternatives of or similar to System.io.abstractions

Notify
🔭 Cross-platform filesystem notification library for Rust.
Stars: ✭ 1,123 (+33.06%)
Mutual labels:  cross-platform, filesystem
Aiofile
Real asynchronous file operations with asyncio support.
Stars: ✭ 214 (-74.64%)
Mutual labels:  io, filesystem
Dfc
Report file system space usage information with style (mirror repository)
Stars: ✭ 84 (-90.05%)
Mutual labels:  cross-platform, filesystem
ModernOperatingSystems AndrewTanenbaum
My notes after reading 'Modern Operating Systems' book by Andrew Tanenbaum and Herbert Bos.
Stars: ✭ 71 (-91.59%)
Mutual labels:  filesystem, io
Renamer
Rename files in bulk.
Stars: ✭ 240 (-71.56%)
Mutual labels:  cross-platform, filesystem
VBCorLib
The VBCorLib framework brings many of the powerful .NET classes to VB6.
Stars: ✭ 81 (-90.4%)
Mutual labels:  filesystem, io
Shellrb
A unix-like shell built in Ruby
Stars: ✭ 24 (-97.16%)
Mutual labels:  cross-platform
Medio
Medical images I/O python package
Stars: ✭ 26 (-96.92%)
Mutual labels:  io
Pty
PTY interface for Go
Stars: ✭ 902 (+6.87%)
Mutual labels:  cross-platform
Node Ntfs
Windows NT File System (NTFS) file system driver
Stars: ✭ 18 (-97.87%)
Mutual labels:  filesystem
Acid
A high speed C++17 Vulkan game engine
Stars: ✭ 838 (-0.71%)
Mutual labels:  cross-platform
Testfs
A simple fs.FS implementation to be used inside tests.
Stars: ✭ 27 (-96.8%)
Mutual labels:  filesystem
Xtd forms
Modern c++17 library to create native gui for Microsoft Windows, Apple macOS and Linux.
Stars: ✭ 25 (-97.04%)
Mutual labels:  cross-platform
Appfolder
🗂 Never use NSSearchPathForDirectoriesInDomains again
Stars: ✭ 928 (+9.95%)
Mutual labels:  filesystem
St handeye graph
General hand-eye calibration based on reprojection error minimization and pose graph optimization
Stars: ✭ 26 (-96.92%)
Mutual labels:  cross-platform
Angular Asp.netcorewebapi Mysql Crud Project
Angular 5 + ASP.Net Core 2.0 WebAPI + MySQL CRUD Sample
Stars: ✭ 22 (-97.39%)
Mutual labels:  cross-platform
Real Live
A cross-platform network media aggregation application.
Stars: ✭ 942 (+11.61%)
Mutual labels:  cross-platform
Tagstore
a research software; a fun way of storing files & folders on your local disk drive; tagging
Stars: ✭ 18 (-97.87%)
Mutual labels:  filesystem
Weblaf
WebLaF is a fully open-source Look & Feel and component library written in pure Java for cross-platform desktop Swing applications.
Stars: ✭ 930 (+10.19%)
Mutual labels:  cross-platform
Gwen Nolegacy Opentk Renderer
A C# port of the GWEN GUI library, with an OpenTK renderer
Stars: ✭ 26 (-96.92%)
Mutual labels:  cross-platform

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

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.

dotnet add package System.IO.Abstractions
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.");
        }
    }
}

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 System.IO.Abstractions.TestingHelpers
[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.AreEqual("We can't go on together. It's not me, it's you.", ex.Message);
        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();
    ...
}

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);
        }
    }
}
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].