Repository navigation
Expand file tree
/
Copy pathConfigServiceTests.cs
More file actions
635 lines (561 loc) · 27.5 KB
/
Copy pathConfigServiceTests.cs
File metadata and controls
635 lines (561 loc) · 27.5 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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
using System;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
using FolderDiffIL4DotNet.Common;
using FolderDiffIL4DotNet.Models;
using FolderDiffIL4DotNet.Services;
using FolderDiffIL4DotNet.Tests.Helpers;
using Xunit;
namespace FolderDiffIL4DotNet.Tests.Services
{
public partial class ConfigServiceTests
{
[Fact]
public async Task LoadConfigBuilderAsync_ExplicitConfigFileMissing_ThrowsFileNotFoundException()
{
var service = new ConfigService();
string missingConfigPath = Path.Combine(Path.GetTempPath(), "fd-config-missing-" + Guid.NewGuid().ToString("N"), "missing.json");
var ex = await Assert.ThrowsAsync<FileNotFoundException>(() => service.LoadConfigBuilderAsync(missingConfigPath));
Assert.Contains(Path.GetFullPath(missingConfigPath), ex.Message, StringComparison.Ordinal);
}
[Theory]
[InlineData("ShouldIgnoreMVID")]
[InlineData("shouldignoremvid")]
public async Task LoadConfigBuilderAsync_RemovedShouldIgnoreMvidSetting_ThrowsMigrationError(string propertyName)
{
await WithConfigFileAsync($"{{ \"{propertyName}\": false }}", async () =>
{
var service = new ConfigService();
var ex = await Assert.ThrowsAsync<InvalidDataException>(() => service.LoadConfigBuilderAsync());
Assert.Contains("'ShouldIgnoreMVID' setting has been removed", ex.Message, StringComparison.Ordinal);
Assert.Contains("always normalized", ex.Message, StringComparison.Ordinal);
Assert.NotNull(ConfigService.TryGetResolvedConfigFileAbsolutePath(ex));
});
}
[Fact]
public async Task LoadConfigBuilderAsync_DefaultUserConfigMissing_FallsBackToBundledConfig()
{
using var appDataScope = CreateAppDataOverrideScope();
var service = new ConfigService();
var builder = await service.LoadConfigBuilderAsync();
Assert.NotNull(builder);
Assert.Equal(5, builder.MaxLogGenerations);
Assert.True(builder.ShouldIncludeUnchangedFiles);
}
[Fact]
public void GetLocalApplicationDataRootAbsolutePath_WhenOverrideIsEmpty_ThrowsInvalidOperationException()
{
using var appDataScope = CreateAppDataOverrideScope();
object? originalOverride = AppContext.GetData(AppDataPaths.LOCAL_APP_DATA_OVERRIDE_KEY);
try
{
AppContext.SetData(AppDataPaths.LOCAL_APP_DATA_OVERRIDE_KEY, string.Empty);
var ex = Assert.Throws<InvalidOperationException>(() => AppDataPaths.GetLocalApplicationDataRootAbsolutePath());
Assert.Contains("LocalApplicationData", ex.Message, StringComparison.Ordinal);
}
finally
{
AppContext.SetData(AppDataPaths.LOCAL_APP_DATA_OVERRIDE_KEY, originalOverride);
TryDeleteDirectory(appDataScope.RootAbsolutePath);
}
}
[Fact]
public void ResolveConfigFileAbsolutePath_WhenLocalApplicationDataOverrideIsEmpty_ThrowsInvalidOperationException()
{
using var appDataScope = CreateAppDataOverrideScope();
object? originalOverride = AppContext.GetData(AppDataPaths.LOCAL_APP_DATA_OVERRIDE_KEY);
try
{
AppContext.SetData(AppDataPaths.LOCAL_APP_DATA_OVERRIDE_KEY, string.Empty);
var ex = Assert.Throws<InvalidOperationException>(() => ConfigService.ResolveConfigFileAbsolutePath());
Assert.Contains("LocalApplicationData", ex.Message, StringComparison.Ordinal);
}
finally
{
AppContext.SetData(AppDataPaths.LOCAL_APP_DATA_OVERRIDE_KEY, originalOverride);
TryDeleteDirectory(appDataScope.RootAbsolutePath);
}
}
[Fact]
public async Task LoadConfigBuilderAsync_WhenUserConfigJsonIsInvalid_AttachesResolvedUserConfigPath()
{
using var appDataScope = CreateAppDataOverrideScope();
Directory.CreateDirectory(Path.GetDirectoryName(appDataScope.UserConfigFileAbsolutePath)!);
await File.WriteAllTextAsync(appDataScope.UserConfigFileAbsolutePath, "{ invalid-json");
var service = new ConfigService();
try
{
var ex = await Assert.ThrowsAsync<InvalidDataException>(() => service.LoadConfigBuilderAsync());
Assert.Equal(
Path.GetFullPath(appDataScope.UserConfigFileAbsolutePath),
ConfigService.TryGetResolvedConfigFileAbsolutePath(ex));
}
finally
{
TryDeleteDirectory(appDataScope.RootAbsolutePath);
}
}
[Fact]
public async Task LoadConfigBuilderAsync_WhenBundledFallbackJsonIsInvalid_AttachesResolvedBundledConfigPath()
{
using var appDataScope = CreateAppDataOverrideScope();
string bundledRoot = Path.Combine(Path.GetTempPath(), "fd-bundled-config-" + Guid.NewGuid().ToString("N"));
string bundledConfigPath = Path.Combine(bundledRoot, "config.json");
Directory.CreateDirectory(bundledRoot);
await File.WriteAllTextAsync(bundledConfigPath, "{ invalid-json");
var service = new ConfigService(() => bundledConfigPath);
try
{
var ex = await Assert.ThrowsAsync<InvalidDataException>(() => service.LoadConfigBuilderAsync());
Assert.Equal(
Path.GetFullPath(bundledConfigPath),
ConfigService.TryGetResolvedConfigFileAbsolutePath(ex));
}
finally
{
TryDeleteDirectory(bundledRoot);
TryDeleteDirectory(appDataScope.RootAbsolutePath);
}
}
[Fact]
public async Task AppDataOverrideScope_WhenConcurrentScopesOverlap_SerializesAccessAndRestoresOriginalOverride()
{
object? originalOverride = AppContext.GetData(AppDataPaths.LOCAL_APP_DATA_OVERRIDE_KEY);
string firstRoot = Path.Combine(Path.GetTempPath(), "fd-appdata-scope-first-" + Guid.NewGuid().ToString("N"));
string secondRoot = Path.Combine(Path.GetTempPath(), "fd-appdata-scope-second-" + Guid.NewGuid().ToString("N"));
var secondAttemptStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var secondScopeEntered = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
var releaseSecondScope = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
AppDataOverrideScope? firstScope = null;
try
{
firstScope = new AppDataOverrideScope(firstRoot);
Assert.Equal(Path.GetFullPath(firstRoot), AppContext.GetData(AppDataPaths.LOCAL_APP_DATA_OVERRIDE_KEY));
Task secondTask = Task.Run(async () =>
{
secondAttemptStarted.SetResult();
using var secondScope = new AppDataOverrideScope(secondRoot);
secondScopeEntered.SetResult(secondScope.RootAbsolutePath);
await releaseSecondScope.Task;
});
await secondAttemptStarted.Task.WaitAsync(TimeSpan.FromSeconds(5));
await Task.Delay(100);
Assert.False(secondScopeEntered.Task.IsCompleted);
firstScope.Dispose();
firstScope = null;
string enteredRoot = await secondScopeEntered.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.Equal(Path.GetFullPath(secondRoot), enteredRoot);
Assert.Equal(Path.GetFullPath(secondRoot), AppContext.GetData(AppDataPaths.LOCAL_APP_DATA_OVERRIDE_KEY));
releaseSecondScope.SetResult();
await secondTask;
Assert.Equal(originalOverride, AppContext.GetData(AppDataPaths.LOCAL_APP_DATA_OVERRIDE_KEY));
}
finally
{
firstScope?.Dispose();
AppContext.SetData(AppDataPaths.LOCAL_APP_DATA_OVERRIDE_KEY, originalOverride);
TryDeleteDirectory(firstRoot);
TryDeleteDirectory(secondRoot);
}
}
[Fact]
public async Task LoadConfigBuilderAsync_InvalidJson_ThrowsInvalidDataException()
{
await WithConfigFileAsync("{ invalid-json", async () =>
{
var service = new ConfigService();
var ex = await Assert.ThrowsAsync<InvalidDataException>(() => service.LoadConfigBuilderAsync());
Assert.IsType<JsonException>(ex.InnerException);
Assert.Contains("JSON syntax error", ex.Message, StringComparison.OrdinalIgnoreCase);
});
}
[Fact]
public async Task LoadConfigBuilderAsync_WhenJsonDeserializesToNull_ThrowsInvalidDataExceptionAndStampsResolvedPath()
{
// A syntactically valid JSON literal `null` deserializes to null — the loader must surface
// this as InvalidDataException with the resolved path stamped so downstream error messages
// still know which file was the source. This also guards the new deserialization-returned-null
// wording so it cannot silently revert to the old "JSON syntax error" message.
// 構文的には正しい JSON リテラル `null` は deserialize で null を返す。ローダはこれを
// InvalidDataException として、かつ解決済みパスが添付された状態でサーフェスし、
// 後段のエラーメッセージでソースが識別できる必要がある。新しい「deserialization returned null」
// 文言が旧「JSON syntax error」にこっそり戻らないことも pin する。
using var appDataScope = CreateAppDataOverrideScope();
Directory.CreateDirectory(Path.GetDirectoryName(appDataScope.UserConfigFileAbsolutePath)!);
await File.WriteAllTextAsync(appDataScope.UserConfigFileAbsolutePath, "null");
var service = new ConfigService();
try
{
var ex = await Assert.ThrowsAsync<InvalidDataException>(() => service.LoadConfigBuilderAsync());
Assert.Equal(
Path.GetFullPath(appDataScope.UserConfigFileAbsolutePath),
ConfigService.TryGetResolvedConfigFileAbsolutePath(ex));
Assert.Contains("deserialization returned null", ex.Message, StringComparison.OrdinalIgnoreCase);
Assert.Null(ex.InnerException);
}
finally
{
TryDeleteDirectory(appDataScope.RootAbsolutePath);
}
}
[Fact]
public async Task LoadConfigBuilderAsync_TrailingCommaInObject_ThrowsInvalidDataExceptionWithHint()
{
// Common mistake: trailing comma after the last property in a JSON object
// よくあるミス: オブジェクトの最後のプロパティ後にカンマを入れてしまう
await WithConfigFileAsync("{ \"MaxLogGenerations\": 5, }", async () =>
{
var service = new ConfigService();
var ex = await Assert.ThrowsAsync<InvalidDataException>(() => service.LoadConfigBuilderAsync());
Assert.IsType<JsonException>(ex.InnerException);
Assert.Contains("JSON syntax error", ex.Message, StringComparison.OrdinalIgnoreCase);
Assert.Contains("trailing", ex.Message, StringComparison.OrdinalIgnoreCase);
});
}
[Fact]
public async Task LoadConfigBuilderAsync_TrailingCommaInArray_ThrowsInvalidDataExceptionWithHint()
{
// Common mistake: trailing comma after the last element in a JSON array
// よくあるミス: 配列の最後の要素後にカンマを入れてしまう
await WithConfigFileAsync("{ \"IgnoredExtensions\": [\".pdb\", \".log\",] }", async () =>
{
var service = new ConfigService();
var ex = await Assert.ThrowsAsync<InvalidDataException>(() => service.LoadConfigBuilderAsync());
Assert.IsType<JsonException>(ex.InnerException);
Assert.Contains("JSON syntax error", ex.Message, StringComparison.OrdinalIgnoreCase);
Assert.Contains("trailing", ex.Message, StringComparison.OrdinalIgnoreCase);
});
}
[Fact]
public async Task LoadConfigBuilderAsync_TrailingCommaError_MessageIncludesLineNumber()
{
// Verify that line number information is included in the error message
// 行番号情報がメッセージに含まれることを確認
const string json = """
{
"MaxLogGenerations": 5,
}
""";
await WithConfigFileAsync(json, async () =>
{
var service = new ConfigService();
var ex = await Assert.ThrowsAsync<InvalidDataException>(() => service.LoadConfigBuilderAsync());
Assert.IsType<JsonException>(ex.InnerException);
// Message should contain a line number (integer >= 1)
// メッセージに行番号(1 以上の整数)が含まれている
Assert.Matches(@"line \d+", ex.Message);
});
}
[Fact]
public async Task LoadConfigBuilderAsync_TrailingCommaError_MessageIncludesPositionInfo()
{
// Verify that position information (column) is included alongside line number.
// 行番号に加え位置情報(列)もメッセージに含まれることを確認。
const string json = """
{
"MaxLogGenerations": 5,
}
""";
await WithConfigFileAsync(json, async () =>
{
var service = new ConfigService();
var ex = await Assert.ThrowsAsync<InvalidDataException>(() => service.LoadConfigBuilderAsync());
Assert.IsType<JsonException>(ex.InnerException);
// Message should contain both line and position numbers
// メッセージに行番号と位置番号の両方が含まれている
Assert.Matches(@"line \d+, position \d+", ex.Message);
});
}
[Fact]
public async Task LoadConfigBuilderAsync_InvalidJson_MessageIncludesTrailingCommaHint()
{
// Verify that the trailing-comma hint is appended to every JSON parse error.
// すべてのJSONパースエラーにトレイリングカンマのヒントが付与されることを確認。
await WithConfigFileAsync("{ \"Key\": }", async () =>
{
var service = new ConfigService();
var ex = await Assert.ThrowsAsync<InvalidDataException>(() => service.LoadConfigBuilderAsync());
Assert.IsType<JsonException>(ex.InnerException);
// Hint about trailing commas and comments should be present
// トレイリングカンマとコメントに関するヒントが存在する
Assert.Contains("trailing", ex.Message, StringComparison.OrdinalIgnoreCase);
});
}
[Fact]
public async Task LoadConfigBuilderAsync_CustomConfigPath_FileNotFound_ThrowsFileNotFoundException()
{
// Verify that specifying a non-existent custom config path throws FileNotFoundException.
// 存在しないカスタム設定パスを指定した場合に FileNotFoundException がスローされることを確認。
var service = new ConfigService();
const string customConfigPath = "/non/existent/config.json";
var ex = await Assert.ThrowsAsync<FileNotFoundException>(
() => service.LoadConfigBuilderAsync(customConfigPath));
Assert.Contains(Path.GetFullPath(customConfigPath), ex.Message, StringComparison.Ordinal);
}
[Fact]
public async Task LoadConfigBuilderAsync_ValidJson_ReturnsDeserializedBuilder()
{
const string json = """
{
"IgnoredExtensions": [".tmp"],
"TextFileExtensions": [".cs", ".json"],
"MaxLogGenerations": 42,
"ShouldIncludeUnchangedFiles": false,
"ShouldWarnWhenNewFileTimestampIsOlderThanOldFileTimestamp": false
}
""";
await WithConfigFileAsync(json, async () =>
{
var service = new ConfigService();
var builder = await service.LoadConfigBuilderAsync();
Assert.NotNull(builder);
Assert.Equal(42, builder.MaxLogGenerations);
Assert.False(builder.ShouldIncludeUnchangedFiles);
Assert.False(builder.ShouldWarnWhenNewFileTimestampIsOlderThanOldFileTimestamp);
Assert.Equal(new[] { ".tmp" }, builder.IgnoredExtensions);
Assert.Equal(new[] { ".cs", ".json" }, builder.TextFileExtensions);
});
}
[Fact]
public async Task LoadConfigBuilderAsync_EmptyObject_UsesCodeDefinedDefaults()
{
await WithConfigFileAsync("{}", async () =>
{
var service = new ConfigService();
var builder = await service.LoadConfigBuilderAsync();
Assert.NotNull(builder);
Assert.Equal(5, builder.MaxLogGenerations);
Assert.True(builder.ShouldIncludeUnchangedFiles);
Assert.True(builder.ShouldIncludeIgnoredFiles);
Assert.True(builder.ShouldOutputILText);
Assert.True(builder.ShouldOutputFileTimestamps);
Assert.True(builder.ShouldWarnWhenNewFileTimestampIsOlderThanOldFileTimestamp);
Assert.True(builder.EnableILCache);
Assert.Equal(ConfigSettings.DefaultILCacheStatsLogIntervalSeconds, builder.ILCacheStatsLogIntervalSeconds);
Assert.True(builder.AutoDetectNetworkShares);
Assert.Contains(".cs", builder.TextFileExtensions);
Assert.Contains(".pdb", builder.IgnoredExtensions);
});
}
[Fact]
public async Task LoadConfigBuilderAsync_NullJson_ThrowsInvalidDataException()
{
await WithConfigFileAsync("null", async () =>
{
var service = new ConfigService();
await Assert.ThrowsAsync<InvalidDataException>(() => service.LoadConfigBuilderAsync());
});
}
[Fact]
public void Validate_InvalidMaxLogGenerations_ReturnsErrorWithDetails()
{
var builder = new ConfigSettingsBuilder { MaxLogGenerations = 0 };
var result = builder.Validate();
Assert.False(result.IsValid);
Assert.Contains(result.Errors, e => e.Contains("MaxLogGenerations", StringComparison.Ordinal));
}
[Fact]
public void Validate_InvalidTextDiffThreshold_ReturnsErrorWithDetails()
{
var builder = new ConfigSettingsBuilder { TextDiffParallelThresholdKilobytes = -1 };
var result = builder.Validate();
Assert.False(result.IsValid);
Assert.Contains(result.Errors, e => e.Contains("TextDiffParallelThresholdKilobytes", StringComparison.Ordinal));
}
[Fact]
public void Validate_ChunkSizeEqualToThreshold_ReturnsErrorWithDetails()
{
var builder = new ConfigSettingsBuilder
{
TextDiffChunkSizeKilobytes = 64,
TextDiffParallelThresholdKilobytes = 64
};
var result = builder.Validate();
Assert.False(result.IsValid);
Assert.Contains(result.Errors, e =>
e.Contains("TextDiffChunkSizeKilobytes", StringComparison.Ordinal) &&
e.Contains("TextDiffParallelThresholdKilobytes", StringComparison.Ordinal));
}
[Fact]
public void Validate_MultipleInvalidSettings_ReturnsAllErrorDetails()
{
var builder = new ConfigSettingsBuilder
{
MaxLogGenerations = 0,
TextDiffParallelThresholdKilobytes = 0,
TextDiffChunkSizeKilobytes = 0
};
var result = builder.Validate();
Assert.False(result.IsValid);
Assert.Contains(result.Errors, e => e.Contains("MaxLogGenerations", StringComparison.Ordinal));
Assert.Contains(result.Errors, e => e.Contains("TextDiffParallelThresholdKilobytes", StringComparison.Ordinal));
Assert.Contains(result.Errors, e => e.Contains("TextDiffChunkSizeKilobytes", StringComparison.Ordinal));
}
[Fact]
public async Task LoadConfigBuilderAsync_ValidCustomSettings_ReturnsBuilder()
{
const string json = """
{
"MaxLogGenerations": 3,
"TextDiffParallelThresholdKilobytes": 256,
"TextDiffChunkSizeKilobytes": 32
}
""";
await WithConfigFileAsync(json, async () =>
{
var service = new ConfigService();
var builder = await service.LoadConfigBuilderAsync();
Assert.Equal(3, builder.MaxLogGenerations);
Assert.Equal(256, builder.TextDiffParallelThresholdKilobytes);
Assert.Equal(32, builder.TextDiffChunkSizeKilobytes);
});
}
// ── configFilePath parameter tests / configFilePath パラメータテスト ──
[Fact]
public async Task LoadConfigBuilderAsync_CustomConfigFilePath_LoadsFromSpecifiedPath()
{
var customConfigPath = Path.Combine(Path.GetTempPath(), $"test-custom-{Guid.NewGuid():N}.json");
const string json = """{ "MaxLogGenerations": 99 }""";
await File.WriteAllTextAsync(customConfigPath, json);
try
{
var service = new ConfigService();
var builder = await service.LoadConfigBuilderAsync(customConfigPath);
Assert.NotNull(builder);
Assert.Equal(99, builder.MaxLogGenerations);
}
finally
{
if (File.Exists(customConfigPath))
{
File.Delete(customConfigPath);
}
}
}
[Fact]
public async Task LoadConfigBuilderAsync_CustomConfigFilePathMissing_ThrowsFileNotFoundException()
{
var service = new ConfigService();
await Assert.ThrowsAsync<FileNotFoundException>(
() => service.LoadConfigBuilderAsync("/nonexistent/path/to/config.json"));
}
[Fact]
public async Task LoadConfigBuilderAsync_NullConfigFilePath_FallsBackToDefaultPath()
{
await WithConfigFileAsync("{}", async () =>
{
var service = new ConfigService();
var builder = await service.LoadConfigBuilderAsync(null);
Assert.NotNull(builder);
});
}
[Fact]
public async Task LoadConfigBuilderAsync_EmptyConfigFilePath_FallsBackToDefaultPath()
{
await WithConfigFileAsync("{}", async () =>
{
var service = new ConfigService();
var builder = await service.LoadConfigBuilderAsync(string.Empty);
Assert.NotNull(builder);
});
}
// ── Helpers / ヘルパー ──────────────────────────────────────────────────
private static async Task WithEnvVarsAsync(
(string key, string value)[] vars,
Func<Task> action)
{
var originals = new (string key, string original)[vars.Length];
for (int i = 0; i < vars.Length; i++)
{
originals[i] = (vars[i].key, Environment.GetEnvironmentVariable(vars[i].key));
Environment.SetEnvironmentVariable(vars[i].key, vars[i].value);
}
try
{
await action();
}
finally
{
foreach (var (key, original) in originals)
{
Environment.SetEnvironmentVariable(key, original);
}
}
}
private static void WithEnvVars((string key, string value)[] vars, Action action)
{
var originals = new (string key, string original)[vars.Length];
for (int i = 0; i < vars.Length; i++)
{
originals[i] = (vars[i].key, Environment.GetEnvironmentVariable(vars[i].key));
Environment.SetEnvironmentVariable(vars[i].key, vars[i].value);
}
try
{
action();
}
finally
{
foreach (var (key, original) in originals)
{
Environment.SetEnvironmentVariable(key, original);
}
}
}
private static void WithEnvVar(string key, string value, Action action)
=> WithEnvVars(new[] { (key, value) }, action);
private static async Task WithConfigFileAsync(string content, Func<Task> assertion, bool deleteConfig = false)
{
using var appDataScope = CreateAppDataOverrideScope();
string configFilePath = appDataScope.UserConfigFileAbsolutePath;
var backupExists = File.Exists(configFilePath);
var backupContent = backupExists ? await File.ReadAllTextAsync(configFilePath) : null;
try
{
if (deleteConfig)
{
if (File.Exists(configFilePath))
{
File.Delete(configFilePath);
}
}
else
{
Directory.CreateDirectory(Path.GetDirectoryName(configFilePath)!);
await File.WriteAllTextAsync(configFilePath, content);
}
await assertion();
}
finally
{
if (backupExists)
{
Directory.CreateDirectory(Path.GetDirectoryName(configFilePath)!);
await File.WriteAllTextAsync(configFilePath, backupContent ?? string.Empty);
}
else if (File.Exists(configFilePath))
{
File.Delete(configFilePath);
}
TryDeleteDirectory(appDataScope.RootAbsolutePath);
}
}
private static AppDataOverrideScope CreateAppDataOverrideScope()
=> new(Path.Combine(Path.GetTempPath(), "fd-config-appdata-" + Guid.NewGuid().ToString("N")));
private static void TryDeleteDirectory(string path)
{
try
{
if (Directory.Exists(path))
{
Directory.Delete(path, recursive: true);
}
}
catch
{
// ignore cleanup errors in tests / テストのクリーンアップエラーを無視
}
}
}
}