-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDirectoryEntryTableWriterTests.cs
More file actions
275 lines (244 loc) · 10.9 KB
/
Copy pathDirectoryEntryTableWriterTests.cs
File metadata and controls
275 lines (244 loc) · 10.9 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
using XISOSharp.DataStructures;
using XISOSharp.Models;
namespace XISOSharp.Tests;
/// <summary>
/// Tests for <see cref="DirectoryEntryTableWriter"/> (TODO #3): AVL table builds,
/// offset/size computation, record encoding, and byte-identity with tables
/// written by the whole-image writer.
/// </summary>
[Collection("Sequential")]
public class DirectoryEntryTableWriterTests : IDisposable
{
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;
}
[Fact]
public void BuildTable_Empty_ReturnsNull() => Assert.Null(DirectoryEntryTableWriter.BuildTable([]));
[Fact]
public void BuildTable_InsertsAllEntries_SearchableByName()
{
AvlNode? root = DirectoryEntryTableWriter.BuildTable([
new DirectoryEntryTableWriter.DirectoryTableEntry("beta.txt", false, 10, 100),
new DirectoryEntryTableWriter.DirectoryTableEntry("alpha.txt", false, 11, 200),
new DirectoryEntryTableWriter.DirectoryTableEntry("GAMMA", true, 12, 2048),
]);
Assert.NotNull(root);
Assert.Equal("beta.txt", AvlTree.AvlFetch(root, "BETA.txt")!.Filename);
Assert.Equal("alpha.txt", AvlTree.AvlFetch(root, "Alpha.TXT")!.Filename);
Assert.NotNull(AvlTree.AvlFetch(root, "gamma")!.Subdirectory);
Assert.Null(AvlTree.AvlFetch(root, "beta.txt")!.Subdirectory);
Assert.Null(AvlTree.AvlFetch(root, "missing.txt"));
}
[Fact]
public void BuildTable_DuplicateCaseInsensitive_Throws()
{
InvalidOperationException ex = Assert.Throws<InvalidOperationException>(() =>
DirectoryEntryTableWriter.BuildTable([
new DirectoryEntryTableWriter.DirectoryTableEntry("File.txt", false, 10, 100),
new DirectoryEntryTableWriter.DirectoryTableEntry("FILE.TXT", false, 11, 100),
]));
Assert.Contains("File.txt", ex.Message, StringComparison.OrdinalIgnoreCase);
}
[Theory]
[InlineData("bad/name")]
[InlineData("bad\\name")]
[InlineData("")]
public void BuildTable_InvalidNames_Throw(string name) =>
Assert.Throws<InvalidOperationException>(() =>
DirectoryEntryTableWriter.BuildTable(
[new DirectoryEntryTableWriter.DirectoryTableEntry(name, false, 10, 100)]));
[Fact]
public void BuildTable_TooLongName_Throws()
{
string name = new('a', Constants.FilenameMaxChars + 1);
Assert.Throws<InvalidOperationException>(() =>
DirectoryEntryTableWriter.BuildTable(
[new DirectoryEntryTableWriter.DirectoryTableEntry(name, false, 10, 100)]));
}
[Fact]
public void ComputeTableSize_SingleFile_MatchesHandComputed()
{
// "a": 14 + 1 = 15 bytes, DWORD-padded to 16.
AvlNode? root = DirectoryEntryTableWriter.BuildTable(
[new DirectoryEntryTableWriter.DirectoryTableEntry("a", false, 7, 5)]);
Assert.Equal(16u, DirectoryEntryTableWriter.ComputeTableSize(root));
Assert.Equal(0u, root!.Offset);
}
[Fact]
public void ComputeTableSize_AvoidsSectorStraddle()
{
// 8 entries x (14 + 255 = 269 -> 272 bytes): the 8th would span
// 1904..2176 across the 2048 boundary, so it moves to offset 2048
// and the total is 2048 + 272 = 2320.
IEnumerable<DirectoryEntryTableWriter.DirectoryTableEntry> entries = Enumerable.Range(0, 8).Select(i =>
new DirectoryEntryTableWriter.DirectoryTableEntry($"f{i:D3}_{new string('x', 250)}", false, (uint)i, 10));
AvlNode? root = DirectoryEntryTableWriter.BuildTable(entries);
Assert.Equal(2320u, DirectoryEntryTableWriter.ComputeTableSize(root));
uint[] max = new uint[1];
AvlTree.AvlTraverseDepthFirst(root, static (node, ctx, _) =>
{
uint[] seen = (uint[])ctx!;
if (node.Offset > seen[0]) seen[0] = node.Offset;
return 0;
}, max, AvlTraversalMethod.Prefix, 0);
Assert.Equal(2048u, max[0]);
}
[Fact]
public void SerializeTable_Empty_ReturnsSingleFFSector()
{
foreach (AvlNode? empty in new[] { null, AvlNode.EmptySubdirectory })
{
byte[] bytes = DirectoryEntryTableWriter.SerializeTable(empty);
Assert.Equal(Constants.SectorSize, bytes.Length);
Assert.All(bytes, static b => Assert.Equal(Constants.PadByte, b));
}
Assert.Equal((uint)Constants.SectorSize, DirectoryEntryTableWriter.ComputeTableSize(null));
}
[Fact]
public void EncodeEntry_FileRecord_MatchesHandComputedBytes()
{
AvlNode node = new() { Filename = "AB", StartSector = 0x123, FileSize = 0x456 };
byte[] record = DirectoryEntryTableWriter.EncodeEntry(node);
Assert.Equal(new byte[]
{
0x00, 0x00, // lOffset: no left child
0x00, 0x00, // rOffset: no right child
0x23, 0x01, 0x00, 0x00, // StartSector
0x56, 0x04, 0x00, 0x00, // FileSize (exact for files)
0x20, // AttributeArc
0x02, // name length
0x41, 0x42, // "AB"
}, record);
}
[Fact]
public void EncodeEntry_DirectoryRecord_RoundsSizeAndSetsDirAttribute()
{
// Table byte size 100 -> on-disk 2048; child offsets stored in DWORDs.
AvlNode root = new()
{
Filename = "SUB",
Subdirectory = new AvlNode(),
StartSector = 0x200,
FileSize = 100,
Left = new AvlNode { Filename = "a", Offset = 40 },
Right = new AvlNode { Filename = "z", Offset = 80 },
};
byte[] record = DirectoryEntryTableWriter.EncodeEntry(root);
Assert.Equal(new byte[]
{
0x0A, 0x00, // lOffset: 40 / 4
0x14, 0x00, // rOffset: 80 / 4
0x00, 0x02, 0x00, 0x00, // StartSector
0x00, 0x08, 0x00, 0x00, // FileSize rounded to sector
0x10, // AttributeDir
0x03, // name length
0x53, 0x55, 0x42, // "SUB"
}, record);
}
[Fact]
public void EncodeEntry_PreservesSourceAttributes()
{
// BUG-LIB-034: rewrite used to normalize every file to Archive (0x20),
// losing read-only/hidden/system bits.
AvlNode file = new() { Filename = "R", FileSize = 10, Attributes = 0x21 };
Assert.Equal(0x21, DirectoryEntryTableWriter.EncodeEntry(file)[12]);
AvlNode dir = new()
{
Filename = "D", Subdirectory = new AvlNode(), FileSize = 2048, Attributes = 0x13
};
Assert.Equal(0x13, DirectoryEntryTableWriter.EncodeEntry(dir)[12]);
}
[Fact]
public void EncodeEntry_UnspecifiedAttributes_FallsBackToKindDefault()
{
AvlNode file = new() { Filename = "F", FileSize = 10 };
Assert.Equal(Constants.AttributeArc, DirectoryEntryTableWriter.EncodeEntry(file)[12]);
AvlNode dir = new() { Filename = "D", Subdirectory = new AvlNode(), FileSize = 2048 };
Assert.Equal(Constants.AttributeDir, DirectoryEntryTableWriter.EncodeEntry(dir)[12]);
}
[Fact]
public void BuildTable_NonLatin1Name_ThrowsInvalidOperation()
{
// BUG-LIB-035: must fail fast with a named error, not mid-write with a
// generic ArgumentException after sizing already ran.
InvalidOperationException ex = Assert.Throws<InvalidOperationException>(() =>
DirectoryEntryTableWriter.BuildTable(
[new DirectoryEntryTableWriter.DirectoryTableEntry("😀.txt", false, 10, 100)]));
Assert.Contains("Latin-1", ex.Message, StringComparison.Ordinal);
}
[Fact]
public void BuildTable_AttributesFlowIntoEncodedRecord()
{
AvlNode? root = DirectoryEntryTableWriter.BuildTable(
[new DirectoryEntryTableWriter.DirectoryTableEntry("r.txt", false, 7, 5, 0x23)]);
Assert.NotNull(root);
Assert.Equal(0x23, DirectoryEntryTableWriter.EncodeEntry(root)[12]);
}
[Fact]
public void SerializeTable_MatchesWriterOutput_ForEveryTableInImage()
{
string src = CreateTempDir("xiso_tbl_src");
File.WriteAllText(Path.Combine(src, "file1.txt"), "hello");
byte[] bin = new byte[5000];
new Random(42).NextBytes(bin);
File.WriteAllBytes(Path.Combine(src, "file2.txt"), bin);
File.WriteAllBytes(Path.Combine(src, "empty.txt"), Array.Empty<byte>());
Directory.CreateDirectory(Path.Combine(src, "subdir"));
File.WriteAllText(Path.Combine(src, "subdir", "nested.txt"), "nested");
Directory.CreateDirectory(Path.Combine(src, "emptydir"));
string outDir = CreateTempDir("xiso_tbl_out");
Assert.Equal(0, XisoWriter.CreateXiso(src, outDir, null, null, out string? isoPath, null, null));
Assert.NotNull(isoPath);
SectorLayout layout = XisoReader.GetSectorLayout(isoPath);
Dictionary<string, uint> dirSizes = layout.Entries.Where(static e => e.IsDirectory)
.ToDictionary(static e => e.Path, static e => e.FileSize, StringComparer.Ordinal);
using FileStream fs = new(isoPath, FileMode.Open, FileAccess.Read, FileShare.Read);
foreach (FileSectorExtent dir in layout.Entries.Where(static e => e.IsDirectory))
{
List<DirectoryEntryTableWriter.DirectoryTableEntry> entries = XisoReader.ListDirectory(isoPath, dir.Path)
.Select(e => new DirectoryEntryTableWriter.DirectoryTableEntry(
e.Name,
e.IsDirectory,
e.StartSector,
e.IsDirectory ? dirSizes[JoinPath(dir.Path, e.Name)] : e.FileSize,
// BUG-LIB-034: round-trip the on-disk attribute bits too.
e.Attributes))
.ToList();
AvlNode? table = DirectoryEntryTableWriter.BuildTable(entries);
byte[] serialized = DirectoryEntryTableWriter.SerializeTable(table);
byte[] onDisk = new byte[dir.SectorCount * Constants.SectorSize];
fs.Seek(layout.Volume.DiscLseek + ((long)dir.StartSector * Constants.SectorSize), SeekOrigin.Begin);
int read = 0;
while (read < onDisk.Length)
{
int n = fs.Read(onDisk, read, onDisk.Length - read);
Assert.True(n > 0, "Truncated directory table on disk.");
read += n;
}
Assert.Equal(onDisk, serialized);
}
}
private static string JoinPath(string dir, string name) =>
dir.Equals("/", StringComparison.Ordinal) ? "/" + name : dir + "/" + name;
}