forked from TestableIO/System.IO.Abstractions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMockFileStream.cs
62 lines (56 loc) · 1.93 KB
/
MockFileStream.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
namespace System.IO.Abstractions.TestingHelpers
{
[Serializable]
public class MockFileStream : MemoryStream
{
private readonly IMockFileDataAccessor mockFileDataAccessor;
private readonly string path;
public MockFileStream(IMockFileDataAccessor mockFileDataAccessor, string path, bool forAppend = false)
{
if (mockFileDataAccessor == null)
{
throw new ArgumentNullException("mockFileDataAccessor");
}
this.mockFileDataAccessor = mockFileDataAccessor;
this.path = path;
if (mockFileDataAccessor.FileExists(path))
{
/* only way to make an expandable MemoryStream that starts with a particular content */
var data = mockFileDataAccessor.GetFile(path).Contents;
if (data != null && data.Length > 0)
{
Write(data, 0, data.Length);
Seek(0, forAppend
? SeekOrigin.End
: SeekOrigin.Begin);
}
}
else
{
mockFileDataAccessor.AddFile(path, new MockFileData(new byte[] { }));
}
}
public override void Close()
{
InternalFlush();
}
public override void Flush()
{
InternalFlush();
}
private void InternalFlush()
{
if (mockFileDataAccessor.FileExists(path))
{
var mockFileData = mockFileDataAccessor.GetFile(path);
/* reset back to the beginning .. */
Seek(0, SeekOrigin.Begin);
/* .. read everything out */
var data = new byte[Length];
Read(data, 0, (int)Length);
/* .. put it in the mock system */
mockFileData.Contents = data;
}
}
}
}