我正在使用 GZipStream 压缩/解压缩数据。我之所以选择它而不是 DeflateStream,是因为文档指出 GZipStream 还添加了一个 CRC 来检测损坏的数据,这是我想要的另一个功能。我的“肯定”单元测试运行良好,因为我可以压缩一些数据,保存压缩的字节数组,然后再次成功解压缩。.NET GZipStream 压缩和解压缩问题帖子帮助我意识到我需要在访问压缩或解压缩数据之前关闭 GZipStream。
接下来,我继续编写“否定”单元测试,以确保可以检测到损坏的数据。我以前使用MSDN 中的 GZipStream 类的示例来压缩文件,用文本编辑器打开压缩文件,更改一个字节以破坏它(好像用文本编辑器打开它还不够糟糕!),保存它然后解压缩它以确保我得到了预期的 InvalidDataException。
当我编写单元测试时,我选择了一个要损坏的任意字节(例如,compressedDataBytes[50] = 0x99)并得到一个 InvalidDataException。到目前为止,一切都很好。我很好奇,所以我选择了另一个字节,但令我惊讶的是我没有得到异常。这可能没问题(例如,我碰巧碰到了数据块中未使用的字节),只要数据仍然可以成功恢复。但是,我也没有得到正确的数据!
为了确定“不是我”,我从.NET GZipStream 压缩和解压缩问题的底部提取了清理后的代码,并将其修改为顺序损坏压缩数据的每个字节,直到它无法正确解压缩。以下是更改(请注意,我使用的是 Visual Studio 2010 测试框架):
// successful compress / decompress example code from:
// https://stackoverflow.com/questions/1590846/net-gzipstream-compress-and-decompress-problem
[TestMethod]
public void Test_zipping_with_memorystream_and_corrupting_compressed_data()
{
const string sample = "This is a compression test of microsoft .net gzip compression method and decompression methods";
var encoding = new ASCIIEncoding();
var data = encoding.GetBytes(sample);
string sampleOut = null;
byte[] cmpData;
// Compress
using (var cmpStream = new MemoryStream())
{
using (var hgs = new GZipStream(cmpStream, CompressionMode.Compress))
{
hgs.Write(data, 0, data.Length);
}
cmpData = cmpStream.ToArray();
}
int corruptBytesNotDetected = 0;
// corrupt data byte by byte
for (var byteToCorrupt = 0; byteToCorrupt < cmpData.Length; byteToCorrupt++)
{
// corrupt the data
cmpData[byteToCorrupt]++;
using (var decomStream = new MemoryStream(cmpData))
{
using (var hgs = new GZipStream(decomStream, CompressionMode.Decompress))
{
using (var reader = new StreamReader(hgs))
{
try
{
sampleOut = reader.ReadToEnd();
// if we get here, the corrupt data was not detected by GZipStream
// ... okay so long as the correct data is extracted
corruptBytesNotDetected++;
var message = string.Format("ByteCorrupted = {0}, CorruptBytesNotDetected = {1}",
byteToCorrupt, corruptBytesNotDetected);
Assert.IsNotNull(sampleOut, message);
Assert.AreEqual(sample, sampleOut, message);
}
catch(InvalidDataException)
{
// data was corrupted, so we expect to get here
}
}
}
}
// restore the data
cmpData[byteToCorrupt]--;
}
}
当我运行这个测试时,我得到:
Assert.AreEqual failed. Expected:<This is a compression test of microsoft .net gzip compression method and decompression methods>. Actual:<>. ByteCorrupted = 11, CorruptBytesNotDetected = 8
因此,这意味着实际上有 7 次损坏数据没有任何区别(字符串已成功恢复),但损坏字节 11 既没有抛出异常,也没有恢复数据。
我错过了什么或做错了什么?谁能看到为什么没有检测到损坏的压缩数据?