Files
poli0981andClaude Opus 5.5 ab51030d42 fix: defects found in review before the 1.2.0 release
- Large batches: the final drain applied at most 2,000 events, so batches
  of more than ~1,000 files left rows "Queued"/"Hashing" and corrupted the
  next run; it now drains until the queue is empty.
- Second launches: PipeMessage had two constructors, so the generated
  serializer threw and the pipe listener stopped after the first message;
  the listener now survives any bad connection. Requests that arrive
  together (one Explorer process per selected file) are merged and handled
  one at a time, waiting while the target page is busy.
- Verify summary counts missing files and rows without a hash as failures
  instead of reporting success; no "folder is empty" after a checksum file
  fills in existing rows; hash files cannot be loaded into queued rows.
- Changing a row's algorithm clears a result computed with another one;
  exports always use the algorithm that produced the hash.
- .sfv files read "name CRC32" first (names starting with eight hex digits
  were taken for GNU lines); SFV lines are parsed without a backtracking
  regex; only LF separates lines (U+2028/U+0085/form feed are valid in names).
- Logging no longer reopens the file for every line after a 10 MB rollover.
- Explorer "Generate hash" on a drive root works (C:\ arrives as C:").
- A timed-out update check reports a network error instead of staying on
  "Checking"; installing an update saves settings and window placement
  first, and the update banner waits until no batch is running.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 13:16:40 +07:00

221 lines
7.8 KiB
C#

using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HashTool.Core.Checksums;
using HashTool.Core.Hashing;
using Xunit;
namespace HashTool.Core.Tests.Checksums;
public sealed class ChecksumParserTests
{
private const string Sha256Empty = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
private const string Md5Abc = "900150983cd24fb0d6963f7d28e17f72";
[Fact]
public void Gnu_TextAndBinaryModes()
{
var doc = ChecksumParser.Parse($"{Sha256Empty} empty.txt\n{Sha256Empty} *sub/dir/empty.bin\n");
Assert.Equal(ChecksumFormat.Gnu, doc.Format);
Assert.Collection(doc.Entries,
e => Assert.Equal(("empty.txt", HashType.SHA256), (e.FileName, e.Algorithm!.Value)),
e => Assert.Equal("sub/dir/empty.bin", e.FileName));
Assert.True(doc.Entries[0].IsAlgorithmGuessed); // 64 hex digits could also be BLAKE3
Assert.Empty(doc.InvalidLines);
}
[Fact]
public void Gnu_FileNameHintDecidesAmbiguousLength()
{
var doc = ChecksumParser.Parse($"{Sha256Empty} a.bin", fileNameHint: HashType.BLAKE3);
Assert.Equal(HashType.BLAKE3, doc.Entries.Single().Algorithm);
Assert.False(doc.Entries.Single().IsAlgorithmGuessed);
}
[Fact]
public void Gnu_EscapedNames()
{
var doc = ChecksumParser.Parse($"\\{Md5Abc} back\\\\slash\\nnewline.txt");
Assert.Equal("back\\slash\nnewline.txt", doc.Entries.Single().FileName);
}
[Fact]
public void Gnu_NameWithSpacesAndHexPrefix()
{
var doc = ChecksumParser.Parse($"{Md5Abc} deadbeef 2024 report.pdf");
var entry = doc.Entries.Single();
Assert.Equal(Md5Abc, entry.Hash);
Assert.Equal("deadbeef 2024 report.pdf", entry.FileName);
}
[Fact]
public void Bsd_TagDecidesAlgorithm_EvenWhenNameLooksLikeHex()
{
var doc = ChecksumParser.Parse($"SHA256 (deadbeefcafebabe.iso) = {Sha256Empty}\nMD5 (abc.txt) = {Md5Abc.ToUpperInvariant()}");
Assert.Equal(ChecksumFormat.Bsd, doc.Format);
Assert.Equal((HashType.SHA256, "deadbeefcafebabe.iso", Sha256Empty), (doc.Entries[0].Algorithm!.Value, doc.Entries[0].FileName, doc.Entries[0].Hash));
Assert.Equal(HashType.MD5, doc.Entries[1].Algorithm);
Assert.False(doc.Entries[0].IsAlgorithmGuessed);
}
[Fact]
public void Bsd_MismatchedLength_IsInvalid()
{
var doc = ChecksumParser.Parse($"MD5 (file) = {Sha256Empty}");
Assert.Empty(doc.Entries);
Assert.Equal([1], doc.InvalidLines);
}
[Fact]
public void Xxhsum_Xxh3Prefix()
{
var doc = ChecksumParser.Parse("XXH3_78af5f94892f3950 abc.txt");
Assert.Equal((HashType.XxHash3, "78af5f94892f3950"), (doc.Entries.Single().Algorithm!.Value, doc.Entries.Single().Hash));
}
[Fact]
public void Sfv_WithComments()
{
var doc = ChecksumParser.Parse("; generated by tool\r\nfile one.iso 1A2B3C4D\r\n", HashType.CRC32);
var entry = doc.Entries.Single();
Assert.Equal(("file one.iso", "1A2B3C4D", HashType.CRC32), (entry.FileName!, entry.Hash, entry.Algorithm!.Value));
}
[Fact]
public void BareHash_LegacySidecar()
{
var doc = ChecksumParser.Parse(Sha256Empty.ToUpperInvariant() + "\n", HashType.SHA256);
var entry = doc.Entries.Single();
Assert.Null(entry.FileName);
Assert.Equal(ChecksumFormat.Bare, doc.Format);
Assert.Same(entry, doc.FindEntry("/anything/at/all.bin", "/"));
}
[Fact]
public void CertUtilOutput()
{
var text = "SHA256 hash of C:\\iso\\win.iso:\r\ne3 b0 c4 42 98 fc 1c 14 9a fb f4 c8 99 6f b9 24 27 ae 41 e4 64 9b 93 4c a4 95 99 1b 78 52 b8 55\r\nCertUtil: -hashfile command completed successfully.\r\n";
var doc = ChecksumParser.Parse(text);
Assert.Equal(Sha256Empty, doc.Entries.Single().Hash);
Assert.Empty(doc.InvalidLines);
}
[Fact]
public void Garbage_IsReportedNotThrown()
{
var doc = ChecksumParser.Parse("hello world\n# comment\n\n" + Md5Abc + " ok.txt\nzz nope");
Assert.Single(doc.Entries);
Assert.Equal([1, 5], doc.InvalidLines);
}
[Fact]
public void UnknownLength_IsInvalid() =>
Assert.Empty(ChecksumParser.Parse("abcdef0123 file").Entries);
[Fact]
public async Task ParseFile_HandlesUtf16AndUsesTheFileName()
{
using var temp = new TempDirectory();
var path = Path.Combine(temp.Path, "SHA256SUMS");
await File.WriteAllTextAsync(path, $"{Sha256Empty} *a.bin\r\n", Encoding.Unicode, TestContext.Current.CancellationToken);
var doc = await ChecksumParser.ParseFileAsync(path, cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(HashType.SHA256, doc.Entries.Single().Algorithm);
Assert.False(doc.Entries.Single().IsAlgorithmGuessed);
}
[Fact]
public async Task ParseFile_RejectsHugeFiles()
{
using var temp = new TempDirectory();
var path = Path.Combine(temp.Path, "huge.sha256");
await using (var stream = File.Create(path)) stream.SetLength(ChecksumParser.MaxFileSize + 1);
await Assert.ThrowsAsync<InvalidDataException>(() =>
ChecksumParser.ParseFileAsync(path, cancellationToken: TestContext.Current.CancellationToken));
}
[Fact]
public void FindEntry_ResolvesRelativeToTheChecksumFile()
{
using var temp = new TempDirectory();
var target = temp.File("sub/data.bin", [1]);
var doc = ChecksumParser.Parse($"{Md5Abc} other.bin\n{Md5Abc.Replace('0', '1')} ./sub/data.bin");
var entry = doc.FindEntry(target, temp.Path);
Assert.Equal(2, entry!.LineNumber);
}
[Theory]
[InlineData(@"\\attacker\share\payload.bin")]
[InlineData("//attacker/share/payload.bin")]
[InlineData(@"\\?\C:\Windows\win.ini")]
public void NetworkAndDevicePaths_AreNeverResolved(string name)
{
var doc = ChecksumParser.Parse($"{Md5Abc} {name}");
Assert.Null(doc.Entries.Single().ResolvePath(Path.GetTempPath()));
}
[Fact]
public void FindEntry_FallsBackToFileName()
{
var doc = ChecksumParser.Parse($"{Md5Abc} somewhere/else/data.bin");
Assert.NotNull(doc.FindEntry(Path.Combine(Path.GetTempPath(), "data.bin"), Path.GetTempPath()));
Assert.Null(doc.FindEntry(Path.Combine(Path.GetTempPath(), "other.bin"), Path.GetTempPath()));
}
[Fact]
public async Task SfvFile_NameStartingWithHexDigits_IsNotReadAsGnu()
{
using var temp = new TempDirectory();
var sfv = temp.File("photos.sfv", "; Generated by Hash Tool\n20231015 Trip.jpg 1A2B3C4D\n");
var doc = await ChecksumParser.ParseFileAsync(sfv, cancellationToken: TestContext.Current.CancellationToken);
var entry = Assert.Single(doc.Entries);
Assert.Equal("20231015 Trip.jpg", entry.FileName);
Assert.Equal("1A2B3C4D", entry.Hash, ignoreCase: true);
Assert.Equal(HashType.CRC32, entry.Algorithm);
}
[Fact]
public void OnlyLineFeedsSeparateLines()
{
// U+2028, U+0085 and form feed are legal in file names; only LF (with an optional CR) ends a line.
var name = "a" + (char)0x2028 + "b" + (char)0x85 + "c" + (char)0x0C + "d.txt";
var doc = ChecksumParser.Parse(Sha256Empty + " " + name + (char)13 + (char)10);
Assert.Equal(name, Assert.Single(doc.Entries).FileName);
Assert.Empty(doc.InvalidLines);
}
[Fact]
public void LongLinesOfSpaces_AreRejectedQuickly()
{
var text = string.Join("\n", Enumerable.Repeat("x" + new string(' ', 30_000) + "y", 20));
var clock = System.Diagnostics.Stopwatch.StartNew();
var doc = ChecksumParser.Parse(text);
Assert.Equal(20, doc.InvalidLines.Count);
Assert.True(clock.Elapsed < System.TimeSpan.FromSeconds(5), $"took {clock.Elapsed}");
}
}