Repository navigation
Expand file tree
/
Copy pathSymlinkAndCircularDirectoryTests.cs
More file actions
239 lines (206 loc) · 12.1 KB
/
Copy pathSymlinkAndCircularDirectoryTests.cs
File metadata and controls
239 lines (206 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using FolderDiffIL4DotNet.Models;
using FolderDiffIL4DotNet.Services;
using FolderDiffIL4DotNet.Tests.Helpers;
using Xunit;
namespace FolderDiffIL4DotNet.Tests.Services.EdgeCases
{
/// <summary>
/// Tests for symbolic links and circular directory reference handling.
/// Verifies that the folder diff service handles symlink loops, dangling symlinks,
/// and cross-device symlinks gracefully.
/// シンボリックリンクおよび循環ディレクトリ参照のテスト。
/// フォルダ差分サービスがシンボリックリンクループ、ダングリングシンボリックリンク、
/// クロスデバイスシンボリックリンクを正常に処理することを確認する。
/// </summary>
[Trait("Category", "Unit")]
public sealed class SymlinkAndCircularDirectoryTests
{
[Fact]
public async Task ExecuteFolderDiffAsync_WhenSymlinkLoopCausesIOException_LogsAndRethrows()
{
// Symlink loop during file enumeration causes IOException ("Too many levels of symbolic links")
// which should be logged and rethrown
// ファイル列挙中のシンボリックリンクループは IOException を引き起こし、ログ後に再スローされる
const string oldDir = "/virtual/old-symloop";
const string newDir = "/virtual/new-symloop";
const string reportDir = "/virtual/report-symloop";
var fileSystem = new FakeFileSystemService
{
EnumerateFilesExceptionRoot = oldDir,
EnumerateFilesException = new IOException("Too many levels of symbolic links")
};
var fileDiffService = new FakeFileDiffService(new Dictionary<string, bool>());
var resultLists = new FileDiffResultLists();
var logger = new TestLogger();
using var progressReporter = new ProgressReportService(new ConfigSettingsBuilder().Build());
var service = new FolderDiffService(
CreateConfig(1), progressReporter,
CreateExecutionContext(oldDir, newDir, reportDir),
fileDiffService, resultLists, logger, fileSystem);
var ex = await Assert.ThrowsAsync<IOException>(() => service.ExecuteFolderDiffAsync());
Assert.Contains("Too many levels of symbolic links", ex.Message);
Assert.Contains(logger.Entries,
entry => entry.LogLevel == AppLogLevel.Error && entry.Exception is IOException);
}
[Fact]
public async Task ExecuteFolderDiffAsync_WhenSymlinkLoopOnNewSide_LogsAndRethrows()
{
// Same test but the symlink loop is on the new-side folder
// 同じテストだが、シンボリックリンクループが new 側フォルダで発生
const string oldDir = "/virtual/old-symloop-new";
const string newDir = "/virtual/new-symloop-new";
const string reportDir = "/virtual/report-symloop-new";
var fileSystem = new FakeFileSystemService
{
EnumerateFilesExceptionRoot = newDir,
EnumerateFilesException = new IOException("Too many levels of symbolic links")
};
fileSystem.SetFiles(oldDir, Path.Combine(oldDir, "file.txt"));
var fileDiffService = new FakeFileDiffService(new Dictionary<string, bool>());
var resultLists = new FileDiffResultLists();
var logger = new TestLogger();
using var progressReporter = new ProgressReportService(new ConfigSettingsBuilder().Build());
var service = new FolderDiffService(
CreateConfig(1), progressReporter,
CreateExecutionContext(oldDir, newDir, reportDir),
fileDiffService, resultLists, logger, fileSystem);
var ex = await Assert.ThrowsAsync<IOException>(() => service.ExecuteFolderDiffAsync());
Assert.Contains("Too many levels of symbolic links", ex.Message);
}
[Fact]
public async Task ExecuteFolderDiffAsync_WhenDanglingSymlinkCausesFileNotFound_ClassifiesAsRemoved()
{
// A dangling symlink in the new-side causes FileNotFoundException during comparison,
// which should be handled gracefully by classifying the file as Removed
// new 側のダングリングシンボリックリンクにより比較時に FileNotFoundException が発生し、
// ファイルを Removed として分類することで正常に処理される
const string oldDir = "/virtual/old-dangling";
const string newDir = "/virtual/new-dangling";
const string reportDir = "/virtual/report-dangling";
var fileSystem = new FakeFileSystemService();
fileSystem.SetFiles(oldDir, Path.Combine(oldDir, "dangling-target.txt"));
fileSystem.SetFiles(newDir, Path.Combine(newDir, "dangling-target.txt"));
var fileDiffService = new FakeFileDiffService(new Dictionary<string, bool>())
{
FilesAreEqualException = new FileNotFoundException("Symlink target not found: dangling-target.txt")
};
var resultLists = new FileDiffResultLists();
var logger = new TestLogger();
using var progressReporter = new ProgressReportService(new ConfigSettingsBuilder().Build());
var service = new FolderDiffService(
CreateConfig(1), progressReporter,
CreateExecutionContext(oldDir, newDir, reportDir),
fileDiffService, resultLists, logger, fileSystem);
await service.ExecuteFolderDiffAsync();
Assert.Contains(Path.Combine(oldDir, "dangling-target.txt"), resultLists.RemovedFilesAbsolutePath);
}
[Fact]
public async Task ExecuteFolderDiffAsync_WhenAccessDeniedOnSymlink_LogsAndRethrows()
{
// UnauthorizedAccessException on a symlink target should be logged and rethrown
// シンボリックリンクターゲットへの UnauthorizedAccessException はログ後に再スローされる
const string oldDir = "/virtual/old-denied-sym";
const string newDir = "/virtual/new-denied-sym";
const string reportDir = "/virtual/report-denied-sym";
var fileSystem = new FakeFileSystemService
{
EnumerateFilesExceptionRoot = oldDir,
EnumerateFilesException = new UnauthorizedAccessException("Permission denied on symlink target")
};
var fileDiffService = new FakeFileDiffService(new Dictionary<string, bool>());
var resultLists = new FileDiffResultLists();
var logger = new TestLogger();
using var progressReporter = new ProgressReportService(new ConfigSettingsBuilder().Build());
var service = new FolderDiffService(
CreateConfig(1), progressReporter,
CreateExecutionContext(oldDir, newDir, reportDir),
fileDiffService, resultLists, logger, fileSystem);
await Assert.ThrowsAsync<UnauthorizedAccessException>(() => service.ExecuteFolderDiffAsync());
}
[Fact]
public async Task ExecuteFolderDiffAsync_ParallelMode_WhenMultipleDanglingSymlinks_AllClassifiedAsRemoved()
{
// Multiple dangling symlinks in parallel mode should all be classified as Removed
// 並列モードでの複数ダングリングシンボリックリンクはすべて Removed に分類される
const string oldDir = "/virtual/old-multi-dangling";
const string newDir = "/virtual/new-multi-dangling";
const string reportDir = "/virtual/report-multi-dangling";
var fileSystem = new FakeFileSystemService();
fileSystem.SetFiles(oldDir,
Path.Combine(oldDir, "link1.txt"),
Path.Combine(oldDir, "link2.txt"),
Path.Combine(oldDir, "link3.txt"));
fileSystem.SetFiles(newDir,
Path.Combine(newDir, "link1.txt"),
Path.Combine(newDir, "link2.txt"),
Path.Combine(newDir, "link3.txt"));
var fileDiffService = new FakeFileDiffService(new Dictionary<string, bool>())
{
FilesAreEqualException = new FileNotFoundException("symlink target removed")
};
var resultLists = new FileDiffResultLists();
var logger = new TestLogger();
using var progressReporter = new ProgressReportService(new ConfigSettingsBuilder().Build());
var service = new FolderDiffService(
CreateConfig(maxParallelism: 4), progressReporter,
CreateExecutionContext(oldDir, newDir, reportDir),
fileDiffService, resultLists, logger, fileSystem);
await service.ExecuteFolderDiffAsync();
Assert.Equal(3, resultLists.RemovedFilesAbsolutePath.Count);
}
private static ConfigSettings CreateConfig(int maxParallelism) => new ConfigSettingsBuilder
{
IgnoredExtensions = new List<string> { ".pdb" },
TextFileExtensions = new List<string> { ".txt" },
ShouldIncludeUnchangedFiles = true,
ShouldIncludeIgnoredFiles = true,
ShouldOutputILText = false,
ShouldIgnoreILLinesContainingConfiguredStrings = false,
ILIgnoreLineContainingStrings = new List<string>(),
ShouldOutputFileTimestamps = false,
ShouldWarnWhenNewFileTimestampIsOlderThanOldFileTimestamp = true,
MaxParallelism = maxParallelism,
EnableILCache = false,
OptimizeForNetworkShares = false,
AutoDetectNetworkShares = false
}.Build();
private static DiffExecutionContext CreateExecutionContext(string oldDir, string newDir, string reportDir)
=> new(oldDir, newDir, reportDir, optimizeForNetworkShares: false, detectedNetworkOld: false, detectedNetworkNew: false);
private sealed class FakeFileSystemService : IFileSystemService
{
private readonly Dictionary<string, IReadOnlyList<string>> _filesByRoot = new(StringComparer.OrdinalIgnoreCase);
public string EnumerateFilesExceptionRoot { get; init; }
public Exception EnumerateFilesException { get; init; }
public List<string> CreatedDirectories { get; } = new();
public void SetFiles(string root, params string[] files)
=> _filesByRoot[root] = files;
public IEnumerable<string> EnumerateFiles(string root, string pattern, SearchOption option)
{
if (string.Equals(root, EnumerateFilesExceptionRoot, StringComparison.OrdinalIgnoreCase) && EnumerateFilesException != null)
throw EnumerateFilesException;
if (!_filesByRoot.TryGetValue(root, out var files)) yield break;
foreach (var f in files) yield return f;
}
public void CreateDirectory(string path) => CreatedDirectories.Add(path);
public DateTime GetLastWriteTimeUtc(string path) => DateTime.UnixEpoch;
}
private sealed class FakeFileDiffService : IFileDiffService
{
public FakeFileDiffService(Dictionary<string, bool> equalityByRelativePath)
=> EqualityByRelativePath = equalityByRelativePath;
public Dictionary<string, bool> EqualityByRelativePath { get; }
public Exception FilesAreEqualException { get; init; }
public Task PrecomputeAsync(IEnumerable<string> files, int maxParallel, System.Threading.CancellationToken ct = default)
=> Task.CompletedTask;
public Task<bool> FilesAreEqualAsync(string relativePath, int maxParallel = 1, System.Threading.CancellationToken ct = default)
{
if (FilesAreEqualException != null) throw FilesAreEqualException;
return Task.FromResult(EqualityByRelativePath[relativePath]);
}
}
}
}