forked from TestableIO/System.IO.Abstractions
/
MockFileSystem.cs
363 lines (306 loc) · 12.7 KB
/
MockFileSystem.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
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace System.IO.Abstractions.TestingHelpers
{
using XFS = MockUnixSupport;
[Serializable]
public class MockFileSystem : IFileSystem, IMockFileDataAccessor
{
private const string DEFAULT_CURRENT_DIRECTORY = @"C:\";
private const string TEMP_DIRECTORY = @"C:\temp";
private readonly IDictionary<string, MockFileData> files;
private readonly PathVerifier pathVerifier;
public MockFileSystem() : this(null) { }
public MockFileSystem(IDictionary<string, MockFileData> files, string currentDirectory = "")
{
if (string.IsNullOrEmpty(currentDirectory))
{
currentDirectory = XFS.Path(DEFAULT_CURRENT_DIRECTORY);
}
else if (!System.IO.Path.IsPathRooted(currentDirectory))
{
throw new ArgumentException("Current directory needs to be rooted.", nameof(currentDirectory));
}
var defaultTempDirectory = XFS.Path(TEMP_DIRECTORY);
StringOperations = new StringOperations(XFS.IsUnixPlatform());
pathVerifier = new PathVerifier(this);
this.files = new Dictionary<string, MockFileData>(StringOperations.Comparer);
Path = new MockPath(this, defaultTempDirectory);
File = new MockFile(this);
Directory = new MockDirectory(this, currentDirectory);
FileInfo = new MockFileInfoFactory(this);
FileStream = new MockFileStreamFactory(this);
DirectoryInfo = new MockDirectoryInfoFactory(this);
DriveInfo = new MockDriveInfoFactory(this);
FileSystemWatcher = new MockFileSystemWatcherFactory();
if (files != null)
{
foreach (var entry in files)
{
AddFile(entry.Key, entry.Value);
}
}
if (!FileExists(currentDirectory))
{
AddDirectory(currentDirectory);
}
if (!FileExists(defaultTempDirectory))
{
AddDirectory(defaultTempDirectory);
}
}
public StringOperations StringOperations { get; }
public IFile File { get; }
public IDirectory Directory { get; }
public IFileInfoFactory FileInfo { get; }
public IFileStreamFactory FileStream { get; }
public IPath Path { get; }
public IDirectoryInfoFactory DirectoryInfo { get; }
public IDriveInfoFactory DriveInfo { get; }
public IFileSystemWatcherFactory FileSystemWatcher { get; set; }
public IFileSystem FileSystem => this;
public PathVerifier PathVerifier => pathVerifier;
private string FixPath(string path, bool checkCaps = false)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path), StringResources.Manager.GetString("VALUE_CANNOT_BE_NULL"));
}
var pathSeparatorFixed = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
var fullPath = Path.GetFullPath(pathSeparatorFixed);
return checkCaps ? GetPathWithCorrectDirectoryCapitalization(fullPath) : fullPath;
}
//If C:\foo exists, ensures that trying to save a file to "C:\FOO\file.txt" instead saves it to "C:\foo\file.txt".
private string GetPathWithCorrectDirectoryCapitalization(string fullPath)
{
string[] splitPath = fullPath.Split(Path.DirectorySeparatorChar);
string leftHalf = fullPath;
string rightHalf = "";
for (int i = splitPath.Length - 1; i > 1; i--)
{
rightHalf = i == splitPath.Length - 1 ? splitPath[i] : splitPath[i] + Path.DirectorySeparatorChar + rightHalf;
int lastSeparator = leftHalf.LastIndexOf(Path.DirectorySeparatorChar);
leftHalf = lastSeparator > 0 ? leftHalf.Substring(0, lastSeparator) : leftHalf;
if (Directory.Exists(leftHalf))
{
leftHalf = Path.GetFullPath(leftHalf).TrimSlashes();
string baseDirectory = AllDirectories.First(dir => StringOperations.Equals(dir, leftHalf));
return baseDirectory + Path.DirectorySeparatorChar + rightHalf;
}
}
return fullPath.TrimSlashes();
}
public MockFileData GetFile(string path)
{
path = FixPath(path).TrimSlashes();
return GetFileWithoutFixingPath(path);
}
private void SetEntry(string path, MockFileData mockFile)
{
path = FixPath(path, true).TrimSlashes();
files[path] = mockFile;
}
public void AddFile(string path, MockFileData mockFile)
{
var fixedPath = FixPath(path, true);
lock (files)
{
var file = GetFile(fixedPath);
if (file != null)
{
var isReadOnly = (file.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly;
var isHidden = (file.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
if (isReadOnly || isHidden)
{
throw CommonExceptions.AccessDenied(path);
}
file.CheckFileAccess(fixedPath, FileAccess.Write);
}
var directoryPath = Path.GetDirectoryName(fixedPath);
if (!Directory.Exists(directoryPath))
{
AddDirectory(directoryPath);
}
SetEntry(fixedPath, mockFile ?? new MockFileData(string.Empty));
}
}
public void AddDirectory(string path)
{
var fixedPath = FixPath(path, true);
var separator = Path.DirectorySeparatorChar.ToString();
lock (files)
{
if (FileExists(fixedPath) &&
(GetFile(fixedPath).Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
throw CommonExceptions.AccessDenied(fixedPath);
var lastIndex = 0;
var isUnc =
StringOperations.StartsWith(fixedPath, @"\\") ||
StringOperations.StartsWith(fixedPath, @"//");
if (isUnc)
{
//First, confirm they aren't trying to create '\\server\'
lastIndex = StringOperations.IndexOf(fixedPath, separator, 2);
if (lastIndex < 0)
throw CommonExceptions.InvalidUncPath(nameof(path));
/*
* Although CreateDirectory(@"\\server\share\") is not going to work in real code, we allow it here for the purposes of setting up test doubles.
* See PR https://github.com/System-IO-Abstractions/System.IO.Abstractions/pull/90 for conversation
*/
}
while ((lastIndex = StringOperations.IndexOf(fixedPath, separator, lastIndex + 1)) > -1)
{
var segment = fixedPath.Substring(0, lastIndex + 1);
if (!Directory.Exists(segment))
{
SetEntry(segment, new MockDirectoryData());
}
}
var s = StringOperations.EndsWith(fixedPath, separator) ? fixedPath : fixedPath + separator;
SetEntry(s, new MockDirectoryData());
}
}
public void AddFileFromEmbeddedResource(string path, Assembly resourceAssembly, string embeddedResourcePath)
{
using (var embeddedResourceStream = resourceAssembly.GetManifestResourceStream(embeddedResourcePath))
{
if (embeddedResourceStream == null)
{
throw new Exception("Resource not found in assembly");
}
using (var streamReader = new BinaryReader(embeddedResourceStream))
{
var fileData = streamReader.ReadBytes((int)embeddedResourceStream.Length);
AddFile(path, new MockFileData(fileData));
}
}
}
public void AddFilesFromEmbeddedNamespace(string path, Assembly resourceAssembly, string embeddedRresourcePath)
{
var matchingResources = resourceAssembly.GetManifestResourceNames().Where(f => f.StartsWith(embeddedRresourcePath));
foreach (var resource in matchingResources)
{
using (var embeddedResourceStream = resourceAssembly.GetManifestResourceStream(resource))
using (var streamReader = new BinaryReader(embeddedResourceStream))
{
var fileName = resource.Substring(embeddedRresourcePath.Length + 1);
var fileData = streamReader.ReadBytes((int)embeddedResourceStream.Length);
var filePath = Path.Combine(path, fileName);
AddFile(filePath, new MockFileData(fileData));
}
}
}
public void MoveDirectory(string sourcePath, string destPath)
{
sourcePath = FixPath(sourcePath);
destPath = FixPath(destPath);
var sourcePathSequence = sourcePath.Split(new[] {Path.DirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);
lock (files)
{
var affectedPaths = files.Keys
.Where(p => PathStartsWith(p, sourcePathSequence))
.ToList();
foreach (var path in affectedPaths)
{
var newPath = StringOperations.Replace(path, sourcePath, destPath);
files[newPath] = files[path];
files.Remove(path);
}
}
bool PathStartsWith(string path, string[] minMatch)
{
var pathSequence = path.Split(new[] {Path.DirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);
if (pathSequence.Length < minMatch.Length)
{
return false;
}
for (var i = 0; i < minMatch.Length; i++)
{
if (!StringOperations.Equals(minMatch[i], pathSequence[i]))
{
return false;
}
}
return true;
}
}
public void RemoveFile(string path)
{
path = FixPath(path);
lock (files)
{
if (FileExists(path) && (GetFile(path).Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
throw CommonExceptions.AccessDenied(path);
}
files.Remove(path);
}
}
public bool FileExists(string path)
{
if (string.IsNullOrEmpty(path))
{
return false;
}
path = FixPath(path).TrimSlashes();
lock (files)
{
return files.ContainsKey(path);
}
}
public IEnumerable<string> AllPaths
{
get
{
lock (files)
{
return files.Keys.ToArray();
}
}
}
public IEnumerable<string> AllNodes
{
get
{
lock (files)
{
return AllPaths.Where(path => !IsStartOfAnotherPath(path)).ToArray();
}
}
}
public IEnumerable<string> AllFiles
{
get
{
lock (files)
{
return files.Where(f => !f.Value.IsDirectory).Select(f => f.Key).ToArray();
}
}
}
public IEnumerable<string> AllDirectories
{
get
{
lock (files)
{
return files.Where(f => f.Value.IsDirectory).Select(f => f.Key).ToArray();
}
}
}
private bool IsStartOfAnotherPath(string path)
{
return AllPaths.Any(otherPath => otherPath.StartsWith(path) && otherPath != path);
}
private MockFileData GetFileWithoutFixingPath(string path)
{
lock (files)
{
files.TryGetValue(path, out var result);
return result;
}
}
}
}