-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXisoFileCopierTests.cs
More file actions
354 lines (299 loc) · 12.1 KB
/
Copy pathXisoFileCopierTests.cs
File metadata and controls
354 lines (299 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
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
using System.Security.Cryptography;
using XISOSharp.Models;
namespace XISOSharp.Tests;
/// <summary>
/// Tests for the scenario-tuned extraction copier (TODO #8, xdvdfs #167):
/// exact-byte copies across chunk boundaries, truncation/cancellation/error
/// behavior, pooled-buffer path, and the per-chunk <c>FileProgress</c> channel
/// on unpack and copy-out.
/// </summary>
[Collection("Sequential")]
public class XisoFileCopierTests : IDisposable
{
private const int TwoMb = 2 * 1024 * 1024;
private readonly List<string> _tempDirs = [];
public void Dispose()
{
Logger.Quiet = false;
Logger.RealQuiet = false;
foreach (string dir in _tempDirs)
{
try
{
if (Directory.Exists(dir)) Directory.Delete(dir, true);
}
catch
{
// ignored
}
}
}
private string CreateTempDir(string prefix)
{
string dir = Path.Combine(Path.GetTempPath(), $"{prefix}_{Guid.NewGuid():N}");
Directory.CreateDirectory(dir);
_tempDirs.Add(dir);
return dir;
}
private sealed class CollectingProgress : IProgress<ProgressInfo>
{
public List<ProgressInfo> Events { get; } = [];
public void Report(ProgressInfo value)
{
lock (Events)
{
Events.Add(value);
}
}
}
private sealed class ShortReadStream : MemoryStream
{
private readonly int _maxPerRead;
public ShortReadStream(byte[] data, int maxPerRead)
: base(data, writable: false)
{
_maxPerRead = maxPerRead;
}
public override int Read(byte[] buffer, int offset, int count) =>
base.Read(buffer, offset, Math.Min(count, _maxPerRead));
}
private static byte[] RandomBytes(int size, int seed)
{
byte[] data = new byte[size];
new Random(seed).NextBytes(data);
return data;
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2047)]
[InlineData(2048)]
[InlineData(65536)]
[InlineData(TwoMb - 1)]
[InlineData(TwoMb)]
[InlineData(TwoMb + 1)]
[InlineData(3 * 1024 * 1024)]
public void CopyExact_RoundTrips_AllSizes(int size)
{
byte[] data = RandomBytes(size, 1234);
using MemoryStream source = new(data, writable: false);
using MemoryStream dest = new();
List<long> progress = new();
long copied = XisoFileCopier.CopyExact(
source, size,
// ReSharper disable once AccessToDisposedClosure — sink runs synchronously inside CopyExact.
(buffer, count) => dest.Write(buffer, 0, count),
new byte[TwoMb],
progress.Add);
Assert.Equal(size, copied);
Assert.Equal(data, dest.ToArray());
if (size == 0)
{
Assert.Empty(progress);
}
else
{
Assert.NotEmpty(progress);
Assert.Equal(size, progress[^1]);
Assert.Equal(progress.Order().ToArray(), progress.ToArray());
}
}
[Fact]
public void CopyExact_ZeroBytes_InvokesNeitherCallback()
{
using MemoryStream source = new([1, 2, 3], writable: false);
int chunks = 0;
int progress = 0;
long copied = XisoFileCopier.CopyExact(
source, 0,
(_, _) => chunks++,
new byte[TwoMb],
_ => progress++);
Assert.Equal(0, copied);
Assert.Equal(0, chunks);
Assert.Equal(0, progress);
}
[Fact]
public void CopyExact_ShortSource_ThrowsTruncatedWithCounts()
{
using MemoryStream source = new(new byte[300], writable: false);
TruncatedCopyException ex = Assert.Throws<TruncatedCopyException>(() =>
XisoFileCopier.CopyExact(source, 1000, (_, _) => { }, new byte[TwoMb]));
Assert.Equal(1000, ex.ExpectedBytes);
Assert.Equal(300, ex.CopiedBytes);
}
[Fact]
public void CopyExact_ShortReads_StitchedExactly()
{
byte[] data = RandomBytes(10000, 99);
using ShortReadStream source = new(data, maxPerRead: 777);
using MemoryStream dest = new();
long copied = XisoFileCopier.CopyExact(
source, data.Length,
// ReSharper disable once AccessToDisposedClosure — sink runs synchronously inside CopyExact.
(buffer, count) => dest.Write(buffer, 0, count),
new byte[TwoMb]);
Assert.Equal(data.Length, copied);
Assert.Equal(data, dest.ToArray());
}
[Fact]
public void CopyExact_NullBuffer_RentsPooledBuffer()
{
byte[] data = RandomBytes(3 * 1024 * 1024, 7);
using MemoryStream source = new(data, writable: false);
using MemoryStream dest = new();
long copied = XisoFileCopier.CopyExact(
source, data.Length,
// ReSharper disable once AccessToDisposedClosure — sink runs synchronously inside CopyExact.
(buffer, count) => dest.Write(buffer, 0, count),
buffer: null);
Assert.Equal(data.Length, copied);
Assert.Equal(data, dest.ToArray());
}
[Fact]
public void CopyExact_EmptyBuffer_Throws()
{
using MemoryStream source = new([1], writable: false);
Assert.Throws<ArgumentException>(() =>
XisoFileCopier.CopyExact(source, 1, (_, _) => { }, Array.Empty<byte>()));
}
[Fact]
public void CopyExact_NegativeCount_Throws()
{
using MemoryStream source = new([1], writable: false);
Assert.Throws<ArgumentOutOfRangeException>(() =>
XisoFileCopier.CopyExact(source, -1, (_, _) => { }, new byte[TwoMb]));
}
[Fact]
public void CopyExact_PreCancelledToken_Throws()
{
using MemoryStream source = new(new byte[100], writable: false);
using CancellationTokenSource cts = new();
cts.Cancel();
Assert.Throws<OperationCanceledException>(() =>
XisoFileCopier.CopyExact(source, 100, (_, _) => { }, new byte[TwoMb],
cancellationToken: cts.Token));
}
[Fact]
public void CopyExact_CancelMidCopy_AbortsPromptly()
{
byte[] data = RandomBytes(3 * 1024 * 1024, 11);
using MemoryStream source = new(data, writable: false);
using CancellationTokenSource cts = new();
Assert.Throws<OperationCanceledException>(() =>
XisoFileCopier.CopyExact(
source, data.Length,
(_, _) => { },
new byte[TwoMb],
// ReSharper disable once AccessToDisposedClosure — callback runs synchronously inside CopyExact.
_ => cts.Cancel(),
cts.Token));
}
[Fact]
public void CopyExact_SinkException_PropagatesUnwrapped()
{
using MemoryStream source = new(new byte[100], writable: false);
InvalidOperationException boom = new("boom");
InvalidOperationException ex = Assert.Throws<InvalidOperationException>(() =>
XisoFileCopier.CopyExact(source, 100, (_, _) => throw boom, new byte[TwoMb]));
Assert.Same(boom, ex);
}
private string CreateIsoWithSizedFiles(out byte[] big, out byte[] small)
{
string src = CreateTempDir("xiso_copier_src");
big = RandomBytes(3 * 1024 * 1024, 4242);
small = RandomBytes(5000, 43);
File.WriteAllBytes(Path.Combine(src, "big.bin"), big);
File.WriteAllBytes(Path.Combine(src, "small.txt"), small);
File.WriteAllBytes(Path.Combine(src, "empty.txt"), Array.Empty<byte>());
string outDir = CreateTempDir("xiso_copier_out");
Assert.Equal(0, XisoWriter.CreateXiso(src, outDir, null, null, out string? isoPath, null, null));
Assert.NotNull(isoPath);
return isoPath;
}
[Fact]
public void CopyOut_ReportsFileProgress_PerChunk()
{
string isoPath = CreateIsoWithSizedFiles(out byte[] big, out _);
CollectingProgress progress = new();
string dest = Path.Combine(CreateTempDir("xiso_copier_dest"), "big.bin");
XisoReader.CopyOut(isoPath, "/big.bin", dest, progress: progress);
Assert.Equal(big, File.ReadAllBytes(dest));
List<ProgressInfo> events = progress.Events.Where(static e => e.Type == ProgressInfoType.FileProgress).ToList();
// 3 MB through a 2 MB buffer = exactly two chunks.
Assert.Equal(2, events.Count);
Assert.Equal(TwoMb, events[0].Size);
Assert.Equal(big.Length, events[1].Size);
Assert.All(events, e => Assert.Equal(big.Length, e.Count));
Assert.All(events, static e => Assert.Equal("/big.bin", e.Path));
EntryInfo? entry = XisoReader.GetEntryInfo(isoPath, "/big.bin");
Assert.NotNull(entry);
Assert.All(events, e => Assert.Equal(entry.StartSector, (uint)e.Sector));
}
[Fact]
public void CopyOut_SmallAndEmptyFiles_ProgressShape()
{
string isoPath = CreateIsoWithSizedFiles(out _, out byte[] small);
CollectingProgress progress = new();
string smallDest = Path.Combine(CreateTempDir("xiso_copier_dest"), "small.txt");
XisoReader.CopyOut(isoPath, "/small.txt", smallDest, progress: progress);
Assert.Equal(small, File.ReadAllBytes(smallDest));
List<ProgressInfo> smallEvents =
progress.Events.Where(static e => e.Type == ProgressInfoType.FileProgress).ToList();
ProgressInfo single = Assert.Single(smallEvents);
Assert.Equal(small.Length, single.Size);
Assert.Equal(small.Length, single.Count);
progress.Events.Clear();
string emptyDest = Path.Combine(CreateTempDir("xiso_copier_dest"), "empty.txt");
XisoReader.CopyOut(isoPath, "/empty.txt", emptyDest, progress: progress);
Assert.Equal(0, new FileInfo(emptyDest).Length);
Assert.DoesNotContain(progress.Events, static e => e.Type == ProgressInfoType.FileProgress);
}
[Fact]
public void UnpackImage_ReportsFileProgress_AndStillReportsFileAdded()
{
string isoPath = CreateIsoWithSizedFiles(out byte[] big, out byte[] small);
CollectingProgress progress = new();
string dest = CreateTempDir("xiso_copier_unpack");
Assert.Equal(0, XisoReader.UnpackImage(isoPath, dest, progress: progress));
Assert.Equal(big, File.ReadAllBytes(Path.Combine(dest, "big.bin")));
Assert.Equal(small, File.ReadAllBytes(Path.Combine(dest, "small.txt")));
List<ProgressInfo> added = progress.Events
.Where(static e => e.Type == ProgressInfoType.FileAdded)
.ToList();
Assert.Equal(3, added.Count);
Dictionary<string, List<ProgressInfo>> byFile = progress.Events
.Where(static e => e.Type == ProgressInfoType.FileProgress)
.GroupBy(static e => e.Path, StringComparer.Ordinal)
.ToDictionary(static g => g.Key!, static g => g.OrderBy(static e => e.Size).ToList(),
StringComparer.Ordinal);
// Every non-empty file ends its progress at its full size; the empty
// file reports FileAdded but no FileProgress (nothing to copy).
foreach (ProgressInfo file in added)
{
if (file.Size == 0)
{
Assert.DoesNotContain(file.Path!, byFile.Keys, StringComparer.OrdinalIgnoreCase);
}
else
{
Assert.Equal(file.Size, byFile[file.Path!][^1].Size);
}
}
}
[Fact]
public void CopyOut_LargeFile_ByteIdentical()
{
string src = CreateTempDir("xiso_copier_src");
byte[] data = RandomBytes(5 * 1024 * 1024, 2026);
File.WriteAllBytes(Path.Combine(src, "large.bin"), data);
string outDir = CreateTempDir("xiso_copier_out");
Assert.Equal(0, XisoWriter.CreateXiso(src, outDir, null, null, out string? isoPath, null, null));
Assert.NotNull(isoPath);
string dest = Path.Combine(CreateTempDir("xiso_copier_dest"), "large.bin");
XisoReader.CopyOut(isoPath, "/large.bin", dest);
Assert.Equal(data, File.ReadAllBytes(dest));
byte[]? hash = XisoReader.ComputeFileHash(isoPath, "/large.bin", HashAlgorithmName.SHA256);
Assert.Equal(SHA256.HashData(data), hash);
}
}