-
Notifications
You must be signed in to change notification settings - Fork 264
Expand file tree
/
Copy pathMockFileStream.cs
More file actions
342 lines (303 loc) · 12.1 KB
/
MockFileStream.cs
File metadata and controls
342 lines (303 loc) · 12.1 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
using System.Threading.Tasks;
using System.Threading;
using System.Runtime.Versioning;
using System.Security.AccessControl;
namespace System.IO.Abstractions.TestingHelpers
{
/// <inheritdoc />
#if FEATURE_SERIALIZABLE
[Serializable]
#endif
public class MockFileStream : FileSystemStream, IFileSystemAclSupport
{
/// <summary>
/// Wrapper around a <see cref="Stream" /> with no backing store, which
/// is used as a replacement for a <see cref="FileSystemStream" />. As such
/// it implements the same properties and methods as a <see cref="FileSystemStream" />.
/// </summary>
public new static FileSystemStream Null { get; } = new NullFileSystemStream();
private class NullFileSystemStream : FileSystemStream
{
/// <summary>
/// Initializes a new instance of <see cref="NullFileSystemStream" />.
/// </summary>
public NullFileSystemStream() : base(Null, ".", true)
{
}
}
private readonly IMockFileDataAccessor mockFileDataAccessor;
private readonly string path;
private readonly FileAccess access = FileAccess.ReadWrite;
private readonly FileOptions options;
private readonly MockFileData fileData;
private bool disposed;
/// <inheritdoc />
public MockFileStream(
IMockFileDataAccessor mockFileDataAccessor,
string path,
FileMode mode,
FileAccess access = FileAccess.ReadWrite,
FileOptions options = FileOptions.None)
: base(new MemoryStream(),
path == null ? null : Path.GetFullPath(path),
(options & FileOptions.Asynchronous) != 0)
{
ThrowIfInvalidModeAccess(mode, access);
this.mockFileDataAccessor = mockFileDataAccessor ?? throw new ArgumentNullException(nameof(mockFileDataAccessor));
this.path = path;
this.options = options;
if (mockFileDataAccessor.FileExists(path))
{
if (mode.Equals(FileMode.CreateNew))
{
throw CommonExceptions.FileAlreadyExists(path);
}
fileData = mockFileDataAccessor.GetFile(path);
fileData.CheckFileAccess(path, access);
var timeAdjustments = GetTimeAdjustmentsForFileStreamWhenFileExists(mode, access);
mockFileDataAccessor.AdjustTimes(fileData, timeAdjustments);
var existingContents = fileData.Contents;
var keepExistingContents =
existingContents?.Length > 0 &&
mode != FileMode.Truncate && mode != FileMode.Create;
if (keepExistingContents)
{
base.Write(existingContents, 0, existingContents.Length);
base.Seek(0, mode == FileMode.Append
? SeekOrigin.End
: SeekOrigin.Begin);
}
}
else
{
var directoryPath = mockFileDataAccessor.Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(directoryPath) && !mockFileDataAccessor.Directory.Exists(directoryPath))
{
throw CommonExceptions.CouldNotFindPartOfPath(path);
}
if (mode.Equals(FileMode.Open) || mode.Equals(FileMode.Truncate))
{
throw CommonExceptions.FileNotFound(path);
}
fileData = new MockFileData(new byte[] { });
mockFileDataAccessor.AdjustTimes(fileData,
TimeAdjustments.CreationTime | TimeAdjustments.LastAccessTime);
mockFileDataAccessor.AddFile(path, fileData);
}
this.access = access;
}
private static void ThrowIfInvalidModeAccess(FileMode mode, FileAccess access)
{
if (mode == FileMode.Append)
{
if (access == FileAccess.Read)
{
throw CommonExceptions.InvalidAccessCombination(mode, access);
}
if (access != FileAccess.Write)
{
throw CommonExceptions.AppendAccessOnlyInWriteOnlyMode();
}
}
if (!access.HasFlag(FileAccess.Write) &&
(mode == FileMode.Truncate || mode == FileMode.CreateNew ||
mode == FileMode.Create || mode == FileMode.Append))
{
throw CommonExceptions.InvalidAccessCombination(mode, access);
}
}
/// <inheritdoc />
public override bool CanRead => access.HasFlag(FileAccess.Read);
/// <inheritdoc />
public override bool CanWrite => access.HasFlag(FileAccess.Write);
/// <inheritdoc />
public override int Read(byte[] buffer, int offset, int count)
{
mockFileDataAccessor.AdjustTimes(fileData,
TimeAdjustments.LastAccessTime);
return base.Read(buffer, offset, count);
}
/// <inheritdoc />
protected override void Dispose(bool disposing)
{
if (disposed)
{
return;
}
InternalFlush();
base.Dispose(disposing);
OnClose();
disposed = true;
}
/// <inheritdoc cref="FileSystemStream.EndWrite(IAsyncResult)" />
public override void EndWrite(IAsyncResult asyncResult)
{
if (!CanWrite)
{
throw new NotSupportedException("Stream does not support writing.");
}
base.EndWrite(asyncResult);
}
/// <inheritdoc />
public override void SetLength(long value)
{
if (!CanWrite)
{
throw new NotSupportedException("Stream does not support writing.");
}
base.SetLength(value);
}
/// <inheritdoc cref="FileSystemStream.Write(byte[], int, int)" />
public override void Write(byte[] buffer, int offset, int count)
{
if (!CanWrite)
{
throw new NotSupportedException("Stream does not support writing.");
}
mockFileDataAccessor.AdjustTimes(fileData,
TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime);
base.Write(buffer, offset, count);
}
#if FEATURE_SPAN
/// <inheritdoc />
public override void Write(ReadOnlySpan<byte> buffer)
{
if (!CanWrite)
{
throw new NotSupportedException("Stream does not support writing.");
}
mockFileDataAccessor.AdjustTimes(fileData,
TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime);
base.Write(buffer);
}
#endif
/// <inheritdoc cref="FileSystemStream.WriteAsync(byte[], int, int, CancellationToken)" />
public override Task WriteAsync(byte[] buffer, int offset, int count,
CancellationToken cancellationToken)
{
if (!CanWrite)
{
throw new NotSupportedException("Stream does not support writing.");
}
mockFileDataAccessor.AdjustTimes(fileData,
TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime);
return base.WriteAsync(buffer, offset, count, cancellationToken);
}
#if FEATURE_SPAN
/// <inheritdoc />
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer,
CancellationToken cancellationToken = new())
{
if (!CanWrite)
{
throw new NotSupportedException("Stream does not support writing.");
}
mockFileDataAccessor.AdjustTimes(fileData,
TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime);
return base.WriteAsync(buffer, cancellationToken);
}
#endif
/// <inheritdoc cref="FileSystemStream.WriteByte(byte)" />
public override void WriteByte(byte value)
{
if (!CanWrite)
{
throw new NotSupportedException("Stream does not support writing.");
}
mockFileDataAccessor.AdjustTimes(fileData,
TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime);
base.WriteByte(value);
}
/// <inheritdoc />
public override void Flush()
{
InternalFlush();
}
/// <inheritdoc />
public override void Flush(bool flushToDisk)
=> InternalFlush();
/// <inheritdoc />
public override Task FlushAsync(CancellationToken cancellationToken)
{
InternalFlush();
return Task.CompletedTask;
}
/// <inheritdoc cref="IFileSystemAclSupport.GetAccessControl()" />
[SupportedOSPlatform("windows")]
public object GetAccessControl()
{
return GetMockFileData().AccessControl;
}
/// <inheritdoc cref="IFileSystemAclSupport.GetAccessControl(IFileSystemAclSupport.AccessControlSections)" />
[SupportedOSPlatform("windows")]
public object GetAccessControl(IFileSystemAclSupport.AccessControlSections includeSections)
{
return GetMockFileData().AccessControl;
}
/// <inheritdoc cref="IFileSystemAclSupport.SetAccessControl(object)" />
[SupportedOSPlatform("windows")]
public void SetAccessControl(object value)
{
GetMockFileData().AccessControl = value as FileSecurity;
}
private MockFileData GetMockFileData()
{
return mockFileDataAccessor.GetFile(path)
?? throw CommonExceptions.FileNotFound(path);
}
private void InternalFlush()
{
if (mockFileDataAccessor.FileExists(path))
{
var mockFileData = mockFileDataAccessor.GetFile(path);
/* reset back to the beginning .. */
var position = Position;
Seek(0, SeekOrigin.Begin);
/* .. read everything out */
var data = new byte[Length];
_ = Read(data, 0, (int)Length);
/* restore to original position */
Seek(position, SeekOrigin.Begin);
/* .. put it in the mock system */
mockFileData.Contents = data;
}
}
private void OnClose()
{
if (options.HasFlag(FileOptions.DeleteOnClose) && mockFileDataAccessor.FileExists(path))
{
mockFileDataAccessor.RemoveFile(path);
}
if (options.HasFlag(FileOptions.Encrypted) && mockFileDataAccessor.FileExists(path))
{
#pragma warning disable CA1416 // Ignore SupportedOSPlatform for testing helper encryption
mockFileDataAccessor.FileInfo.New(path).Encrypt();
#pragma warning restore CA1416
}
}
private TimeAdjustments GetTimeAdjustmentsForFileStreamWhenFileExists(FileMode mode, FileAccess access)
{
switch (mode)
{
case FileMode.Append:
case FileMode.CreateNew:
if (access.HasFlag(FileAccess.Read))
{
return TimeAdjustments.LastAccessTime;
}
return TimeAdjustments.None;
case FileMode.Create:
case FileMode.Truncate:
if (access.HasFlag(FileAccess.Write))
{
return TimeAdjustments.LastAccessTime | TimeAdjustments.LastWriteTime;
}
return TimeAdjustments.LastAccessTime;
case FileMode.Open:
case FileMode.OpenOrCreate:
default:
return TimeAdjustments.None;
}
}
}
}