Skip to content

Instantly share code, notes, and snippets.

Created August 21, 2020 00:27
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
The beginnings of a Coyote file system mock object for Task Programming model...
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
namespace CoyoteTests
internal class FileSystemMock
ConcurrentDictionary<string, byte[]> files = new ConcurrentDictionary<string, byte[]>();
ConcurrentDictionary<string, OpenFileStream> openFiles = new ConcurrentDictionary<string, OpenFileStream>();
public async Task<Stream> OpenAsync(string path)
// model some asynchrony in the file system with a delay.
await Task.Delay(1);
byte[] data;
if (!files.TryGetValue(path, out data))
throw new FileNotFoundException(path);
var f = new OpenFileStream(path, this);
if (!openFiles.TryAdd(path, f))
throw new FileLoadException("File is locked by another task");
return s;
class OpenFileStream : Stream
string filename;
MemoryStream memoryStream;
FileSystemMock owner;
byte[] oldData;
internal OpenFileStream(string path, FileSystemMock owner)
this.filename = path;
this.owner = owner;
public void Open(byte[] data)
this.oldData = data;
this.memoryStream = new MemoryStream(data);
public override bool CanRead => memoryStream.CanRead;
public override bool CanSeek => memoryStream.CanSeek;
public override bool CanWrite => memoryStream.CanWrite;
public override long Length => memoryStream.Length;
public override long Position { get => memoryStream.Position; set => memoryStream.Position = value; }
public override void Flush() => memoryStream.Flush();
public override int Read(byte[] buffer, int offset, int count) => memoryStream.Read(buffer, offset, count);
public override long Seek(long offset, SeekOrigin origin) => memoryStream.Seek(offset, origin);
public override void SetLength(long value) => memoryStream.SetLength(value);
public override void Write(byte[] buffer, int offset, int count) => memoryStream.Write(buffer, offset, count);
protected override void Dispose(bool disposing)
if (this.memoryStream != null)
byte[] newData = this.memoryStream.ToArray();
this.owner.openFiles.Remove(this.filename, out _);
this.owner.files.TryUpdate(this.filename, this.oldData, newData);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment