Skip to content

Commit f1bf84c

Browse files
Fix VerifySettings copy constructor, temp cleanup, and stream/extensi… (#1768)
* Fix VerifySettings copy constructor, temp cleanup, and stream/extension edge cases - VerifySettings copy ctor: copy throwException (was dropped, so settings.AutoVerify(throwException: true) passed as an instance silently did not throw on mismatch) - VerifySettings copy ctor: clone the mutable collections it was aliasing (appendedFiles, the extension stream/string comparer dictionaries, and the inner lists of ExtensionMappedInstanceScrubbers), so per-test fluent config no longer leaks into a shared base settings instance - TempDirectory/TempFile cleanup: catch IOException/UnauthorizedAccessException for aged-out orphans instead of DirectoryNotFoundException/FileNotFoundException (which File.Delete never throws), so a locked or read-only orphan no longer fails the module initializer on every run - IoHelpers.WriteStream: fall back to copying through the handle when File.Copy cannot re-open the source by path (writable / FileShare.None, or a handle-based stream), resetting position only in that fallback - Extensions.Extension(FileStream): return "noextension" for extension-less files instead of throwing ArgumentOutOfRangeException - TempDirectory/TempFile: guard the AsyncLocal path list with a lock on add/remove/scrub iteration - Add tests for the above * Docs changes --------- Co-authored-by: GitHub Action <action@github.com>
1 parent efaf9ac commit f1bf84c

11 files changed

Lines changed: 296 additions & 51 deletions

‎docs/naming.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -789,7 +789,7 @@ public static string NameWithParent(this Type type)
789789
return type.Name;
790790
}
791791
```
792-
<sup><a href='/src/Verify/Extensions.cs#L114-L126' title='Snippet source file'>snippet source</a> | <a href='#snippet-NameWithParent' title='Start of snippet'>anchor</a></sup>
792+
<sup><a href='/src/Verify/Extensions.cs#L123-L135' title='Snippet source file'>snippet source</a> | <a href='#snippet-NameWithParent' title='Start of snippet'>anchor</a></sup>
793793
<!-- endSnippet -->
794794

795795
Any path calculated in `DerivePathInfo` should be fully qualified to remove the inconsistency of the current directory.

‎docs/temp-file.md‎

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ public void Usage()
3434
// file automatically deleted here
3535
}
3636
```
37-
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L38-L50' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFile' title='Start of snippet'>anchor</a></sup>
37+
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L87-L99' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFile' title='Start of snippet'>anchor</a></sup>
3838
<!-- endSnippet -->
3939

4040

@@ -62,7 +62,7 @@ public void PathProperty()
6262
Assert.True(Path.IsPathRooted(path));
6363
}
6464
```
65-
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L52-L62' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFilePathProperty' title='Start of snippet'>anchor</a></sup>
65+
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L101-L111' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFilePathProperty' title='Start of snippet'>anchor</a></sup>
6666
<!-- endSnippet -->
6767

6868

@@ -91,7 +91,7 @@ public void StringConversion()
9191
Trace.WriteLine(content);
9292
}
9393
```
94-
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L344-L359' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileStringConversion' title='Start of snippet'>anchor</a></sup>
94+
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L393-L408' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileStringConversion' title='Start of snippet'>anchor</a></sup>
9595
<!-- endSnippet -->
9696

9797

@@ -114,7 +114,7 @@ public void FileInfoConversion()
114114
Trace.WriteLine(directoryName);
115115
}
116116
```
117-
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L361-L375' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileFileInfoConversion' title='Start of snippet'>anchor</a></sup>
117+
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L410-L424' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileFileInfoConversion' title='Start of snippet'>anchor</a></sup>
118118
<!-- endSnippet -->
119119

120120

@@ -135,7 +135,7 @@ public void InfoProperty()
135135
Trace.WriteLine(directoryName);
136136
}
137137
```
138-
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L377-L389' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileInfoProperty' title='Start of snippet'>anchor</a></sup>
138+
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L426-L438' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileInfoProperty' title='Start of snippet'>anchor</a></sup>
139139
<!-- endSnippet -->
140140

141141

@@ -151,7 +151,7 @@ public void RootDirectory() =>
151151
// Accessing the root directory for all TempDirectory instances
152152
Trace.WriteLine(TempFile.RootDirectory);
153153
```
154-
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L114-L121' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileRootDirectory' title='Start of snippet'>anchor</a></sup>
154+
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L163-L170' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileRootDirectory' title='Start of snippet'>anchor</a></sup>
155155
<!-- endSnippet -->
156156

157157

@@ -186,7 +186,7 @@ public async Task VerifyFileInstance()
186186
await VerifyFile(file);
187187
}
188188
```
189-
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L26-L36' title='Snippet source file'>snippet source</a> | <a href='#snippet-VerifyTempFile' title='Start of snippet'>anchor</a></sup>
189+
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L75-L85' title='Snippet source file'>snippet source</a> | <a href='#snippet-VerifyTempFile' title='Start of snippet'>anchor</a></sup>
190190
<!-- endSnippet -->
191191

192192

@@ -207,7 +207,7 @@ public async Task Scrubbing()
207207
});
208208
}
209209
```
210-
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L96-L110' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileScrubbing' title='Start of snippet'>anchor</a></sup>
210+
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L145-L159' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileScrubbing' title='Start of snippet'>anchor</a></sup>
211211
<!-- endSnippet -->
212212

213213
Result:
@@ -237,7 +237,7 @@ File.WriteAllText(temp, "content");
237237

238238
// file automatically deleted here
239239
```
240-
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L620-L628' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileCreate' title='Start of snippet'>anchor</a></sup>
240+
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L669-L677' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileCreate' title='Start of snippet'>anchor</a></sup>
241241
<!-- endSnippet -->
242242

243243

@@ -252,7 +252,7 @@ using var temp = TempFile.Create(".txt");
252252

253253
File.WriteAllText(temp, "content");
254254
```
255-
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L635-L641' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileCreateWithExtension' title='Start of snippet'>anchor</a></sup>
255+
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L684-L690' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileCreateWithExtension' title='Start of snippet'>anchor</a></sup>
256256
<!-- endSnippet -->
257257

258258

@@ -267,7 +267,7 @@ using var temp = TempFile.Create(".txt", Encoding.UTF8);
267267

268268
File.Exists(temp.Path);
269269
```
270-
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L649-L655' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileCreateWithEncoding' title='Start of snippet'>anchor</a></sup>
270+
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L698-L704' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileCreateWithEncoding' title='Start of snippet'>anchor</a></sup>
271271
<!-- endSnippet -->
272272

273273

@@ -283,7 +283,7 @@ using var temp = await TempFile.CreateText("Hello, World!");
283283
var content = await File.ReadAllTextAsync(temp);
284284
Assert.Equal("Hello, World!", content);
285285
```
286-
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L661-L668' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileCreateText' title='Start of snippet'>anchor</a></sup>
286+
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L710-L717' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileCreateText' title='Start of snippet'>anchor</a></sup>
287287
<!-- endSnippet -->
288288

289289

@@ -304,7 +304,7 @@ using var temp = await TempFile.CreateText(json, ".json");
304304
var content = await File.ReadAllTextAsync(temp);
305305
Assert.Equal(json, content);
306306
```
307-
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L674-L688' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileCreateTextWithExtension' title='Start of snippet'>anchor</a></sup>
307+
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L723-L737' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileCreateTextWithExtension' title='Start of snippet'>anchor</a></sup>
308308
<!-- endSnippet -->
309309

310310

@@ -323,7 +323,7 @@ using var temp = await TempFile.CreateText(
323323
var content = await File.ReadAllTextAsync(temp, Encoding.UTF8);
324324
Assert.Equal("Content with special chars: äöü", content);
325325
```
326-
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L694-L704' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileCreateTextWithEncoding' title='Start of snippet'>anchor</a></sup>
326+
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L743-L753' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileCreateTextWithEncoding' title='Start of snippet'>anchor</a></sup>
327327
<!-- endSnippet -->
328328

329329

@@ -341,7 +341,7 @@ using var temp = await TempFile.CreateBinary(data);
341341
var readData = await File.ReadAllBytesAsync(temp);
342342
Assert.Equal(data, readData);
343343
```
344-
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L712-L721' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileCreateBinary' title='Start of snippet'>anchor</a></sup>
344+
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L761-L770' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileCreateBinary' title='Start of snippet'>anchor</a></sup>
345345
<!-- endSnippet -->
346346

347347

@@ -353,7 +353,7 @@ Assert.Equal(data, readData);
353353
byte[] data = [0x01, 0x02, 0x03, 0x04];
354354
using var temp = await TempFile.CreateBinary(data, ".bin");
355355
```
356-
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L727-L732' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileCreateBinaryWithExtension' title='Start of snippet'>anchor</a></sup>
356+
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L776-L781' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileCreateBinaryWithExtension' title='Start of snippet'>anchor</a></sup>
357357
<!-- endSnippet -->
358358

359359

@@ -384,7 +384,7 @@ public void NoUsing()
384384
Debug.WriteLine(temp);
385385
}
386386
```
387-
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L79-L92' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileNoUsing' title='Start of snippet'>anchor</a></sup>
387+
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L128-L141' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileNoUsing' title='Start of snippet'>anchor</a></sup>
388388
<!-- endSnippet -->
389389

390390
The file can then be manually inspected.
@@ -408,7 +408,7 @@ public void OpenExplorerAndDebug()
408408
temp.OpenExplorerAndDebug();
409409
}
410410
```
411-
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L64-L77' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileOpenExplorerAndDebug' title='Start of snippet'>anchor</a></sup>
411+
<sup><a href='/src/Verify.Tests/TempFileTests.cs#L113-L126' title='Snippet source file'>snippet source</a> | <a href='#snippet-TempFileOpenExplorerAndDebug' title='Start of snippet'>anchor</a></sup>
412412
<!-- endSnippet -->
413413

414414
This method is designed to help debug tests by enabling the inspection of the contents of the temporary file while the test is paused. It performs two actions:
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
public class CopyConstructorTests
2+
{
3+
[Fact]
4+
public void PreservesThrowException()
5+
{
6+
var settings = new VerifySettings();
7+
settings.AutoVerify(throwException: true);
8+
9+
var copy = new VerifySettings(settings);
10+
11+
Assert.True(copy.throwException);
12+
}
13+
14+
[Fact]
15+
public void ClonesAppendedFiles()
16+
{
17+
var settings = new VerifySettings();
18+
settings.AppendContentAsFile("base");
19+
20+
var copy = new VerifySettings(settings);
21+
copy.AppendContentAsFile("extra");
22+
23+
// The base settings must not see the file appended to the copy.
24+
Assert.Single(settings.appendedFiles!);
25+
Assert.Equal(2, copy.appendedFiles!.Count);
26+
}
27+
28+
[Fact]
29+
public void ClonesExtensionStreamComparers()
30+
{
31+
var settings = new VerifySettings();
32+
StreamCompare compare = (_, _, _) => Task.FromResult(CompareResult.Equal);
33+
// Extensions unique to this test so the global comparer registry can't
34+
// satisfy the lookup below.
35+
settings.UseStreamComparer(compare, "copyctorext1");
36+
37+
var copy = new VerifySettings(settings);
38+
copy.UseStreamComparer(compare, "copyctorext2");
39+
40+
// The comparer added to the copy must not leak into the base settings.
41+
Assert.False(settings.TryFindStreamComparer("copyctorext2", out _));
42+
Assert.True(copy.TryFindStreamComparer("copyctorext2", out _));
43+
}
44+
45+
[Fact]
46+
public void ClonesExtensionMappedScrubbers()
47+
{
48+
var settings = new VerifySettings();
49+
settings.AddScrubber("txt", _ => { });
50+
51+
var copy = new VerifySettings(settings);
52+
copy.AddScrubber("txt", _ => { });
53+
54+
// The inner list is shared unless deep-copied.
55+
Assert.Single(settings.ExtensionMappedInstanceScrubbers!["txt"]);
56+
Assert.Equal(2, copy.ExtensionMappedInstanceScrubbers!["txt"].Count);
57+
}
58+
}

‎src/Verify.Tests/IoHelpersTests.cs‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,44 @@ public void ResolveDirectoryNameFromSourceFileTests(string sourceFile, string ex
1818

1919
Assert.Equal(expectedDirectory, IoHelpers.ResolveDirectoryFromSourceFile(sourceFile));
2020
}
21+
22+
[Fact]
23+
public async Task WriteStreamHandlesExclusiveFileStream()
24+
{
25+
using var source = new TempFile(".bin");
26+
await File.WriteAllBytesAsync(source, [1, 2, 3, 4, 5, 6, 7, 8]);
27+
var destination = Path.Combine(Path.GetTempPath(), $"WriteStream{Guid.NewGuid():N}.bin");
28+
try
29+
{
30+
// Writable + FileShare.None means File.Copy cannot re-open the source
31+
// by path on Windows; WriteStream must fall back to the handle.
32+
using var stream = new FileStream(source, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
33+
await IoHelpers.WriteStream(destination, stream);
34+
35+
Assert.True(File.Exists(destination));
36+
Assert.Equal(8, new FileInfo(destination).Length);
37+
}
38+
finally
39+
{
40+
File.Delete(destination);
41+
}
42+
}
43+
44+
[Fact]
45+
public void ExtensionForExtensionlessFileStream()
46+
{
47+
var directory = Path.Combine(Path.GetTempPath(), $"ExtTest{Guid.NewGuid():N}");
48+
Directory.CreateDirectory(directory);
49+
var path = Path.Combine(directory, "Dockerfile");
50+
File.WriteAllText(path, "content");
51+
try
52+
{
53+
using var stream = File.OpenRead(path);
54+
Assert.Equal("noextension", stream.Extension());
55+
}
56+
finally
57+
{
58+
Directory.Delete(directory, true);
59+
}
60+
}
2161
}

‎src/Verify.Tests/TempDirectoryTests.cs‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,28 @@ public void IgnoreLockedFiles_DefaultIsFalse()
427427
}
428428
}
429429

430+
[Fact]
431+
public void CleanupDoesNotThrowForUndeletableDirectory()
432+
{
433+
var directoryPath = Path.Combine(TempDirectory.RootDirectory, Path.GetRandomFileName());
434+
Directory.CreateDirectory(directoryPath);
435+
var filePath = Path.Combine(directoryPath, "locked.txt");
436+
File.WriteAllText(filePath, "content");
437+
PreventDeletion(filePath, directoryPath);
438+
Directory.SetLastWriteTime(directoryPath, DateTime.Now.AddDays(-2));
439+
try
440+
{
441+
// An aged-out orphan that cannot be deleted must not fail the whole
442+
// module-initializer cleanup.
443+
TempDirectory.Cleanup();
444+
}
445+
finally
446+
{
447+
AllowDeletion(filePath, directoryPath);
448+
Directory.Delete(directoryPath, true);
449+
}
450+
}
451+
430452
// On Windows, ReadOnly on a file prevents deletion.
431453
// On Unix, file deletion is controlled by the parent directory's write permission.
432454
static void PreventDeletion(string filePath, string directoryPath)

‎src/Verify.Tests/TempFileTests.cs‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,55 @@ public void Constructor_WithExtension_AppliesExtension()
2323
Assert.EndsWith(".txt", temp.Path);
2424
}
2525

26+
[Fact]
27+
public void CleanupDoesNotThrowForUndeletableFile()
28+
{
29+
var filePath = Path.Combine(TempFile.RootDirectory, $"undeletable{Guid.NewGuid():N}.txt");
30+
File.WriteAllText(filePath, "content");
31+
// Age the file out before marking it read-only: on .NET Framework the
32+
// timestamp cannot be set on a read-only file.
33+
File.SetLastWriteTime(filePath, DateTime.Now.AddDays(-2));
34+
// On Windows a read-only file cannot be deleted; on Unix deletion is
35+
// governed by the directory, so the file is deletable there and this
36+
// test is a no-op guard.
37+
var readOnly = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
38+
if (readOnly)
39+
{
40+
File.SetAttributes(filePath, FileAttributes.ReadOnly);
41+
}
42+
43+
try
44+
{
45+
TempFile.Cleanup();
46+
}
47+
finally
48+
{
49+
if (readOnly)
50+
{
51+
File.SetAttributes(filePath, FileAttributes.Normal);
52+
}
53+
54+
if (File.Exists(filePath))
55+
{
56+
File.Delete(filePath);
57+
}
58+
}
59+
}
60+
61+
[Fact]
62+
public async Task ConcurrentInstancesDoNotCorruptState()
63+
{
64+
// Establish the shared async-local path list, then hammer it from many
65+
// child contexts that flow the same list in.
66+
using var parent = new TempFile();
67+
var tasks = Enumerable.Range(0, 200)
68+
.Select(_ => Task.Run(() =>
69+
{
70+
using var temp = new TempFile();
71+
}));
72+
await Task.WhenAll(tasks);
73+
}
74+
2675
#region VerifyTempFile
2776

2877
[Fact]

‎src/Verify/Extensions.cs‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,17 @@ static class Extensions
2020
public static bool IsNumeric(this Type type) =>
2121
numericTypes.Contains(Nullable.GetUnderlyingType(type) ?? type);
2222

23-
public static string Extension(this FileStream file) =>
24-
Path.GetExtension(file.Name)[1..];
23+
public static string Extension(this FileStream file)
24+
{
25+
var extension = Path.GetExtension(file.Name);
26+
if (extension.Length == 0)
27+
{
28+
// Matches the convention used for extension-less directory entries.
29+
return "noextension";
30+
}
31+
32+
return extension[1..];
33+
}
2534

2635
public static Version MajorMinor(this Version version) =>
2736
new(version.Major, version.Minor);

0 commit comments

Comments
 (0)