Skip to content

Commit fa0634a

Browse files
authored
test: pin ods truncation inside tags and rows, covered and skipped cells, annotations, empty tables and writer whitespace, widths and column freezes (#175)
From the triage of the Stryker.NET run (#151). These are tests only. Each pins behaviour that is right today but that a surviving mutant broke without any test noticing. **Reader:** - **B1:** a content part that ends inside a tag behind the first sheet lists `["A"]` and reads A. The cut falls in an element name, a table start tag, an attribute value, an end tag, a style or its table properties, a comment, CDATA or a processing instruction. One case cuts a name longer than everything before it, so the buffer holds nothing past the end but that name. These mutants loop forever or read past the buffer. Every case runs on a background thread of its own against a 20 s deadline, so a hang fails the test and the run still ends. - **B3:** a part that ends inside a row is refused as `Truncated` at the first `ReadRow`. The cut falls between cells, in a cell's text, in a typed cell that is passed over, in a covered cell or inside a tag. - **A3:** a covered cell that still holds a float or a string reads as empty, repeats included. The cell after it keeps its column. - **A4:** once a sheet has ended, `ReadRow` keeps returning false and never hands out the next sheet's rows. Moving to that sheet still reads them. - **A5:** a cell whose value is in its attributes is skipped exactly to its own end tag. That holds for a float with two `<text:s/>`, a float holding a sub-table and a stated string holding a sub-table. The next cell and the next row read as written. - **A6:** an annotation among the paragraphs adds no text and no line. This covers an annotation with spaces, tabs and line breaks, an empty annotation, one standing first, and one inside a paragraph, whose tail is kept. - **A7:** `IsoDurationTests.Inputs` gains `PT0.1234567891S`, `PT2147483647S`, `PT2147483647M`, `PT1.99999999999` and `PT.99999999999`. Each is checked against `XmlConvert`. - **A12:** an empty `<table:table/>`, with or without a space before the slash, is no sheet. This holds in UTF-8 and UTF-16, and the sheet behind it reads as its own. **Writer:** - **G11:** a space after a tab, after a line break or at the start of a value is written as `<text:s text:c="1"/>`. Since #161 the reader folds white space as ODF does, so a plain space there would be lost. Each case also round-trips. - **G12:** column styles `co1` and `co19` have widths of exactly `0.125in` and `1.4375in`. - **G13:** a sheet that freezes only columns writes `HorizontalSplitMode` 2 and `VerticalSplitMode` 0 in `settings.xml`. Each group's main mutants were applied by hand. The new tests fail against them and pass once they are reverted. All of them passed against the current code. Refs #151.
1 parent cab3f68 commit fa0634a

5 files changed

Lines changed: 250 additions & 3 deletions

File tree

‎tests/TriasDev.Tabular.Tests/Ods/IsoDurationTests.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,8 @@ public sealed class IsoDurationTests
3030
// Near and past the ends of a TimeSpan and of an int.
3131
"P10675199D", "P10675199DT2H48M5.4775807S", "P10675199DT2H48M5.4775808S", "-P10675199DT2H48M5.4775808S",
3232
"-P10675199DT2H48M5.4775809S", "P10675200D", "P2147483647D", "PT2147483647H", "PT2147483648H", "P2147483647Y",
33-
"P29247Y", "P29248Y", "PT1.99999999999999999999S",
33+
"P29247Y", "P29248Y", "PT1.99999999999999999999S", "PT0.1234567891S", "PT2147483647S", "PT2147483647M",
34+
"PT1.99999999999", "PT.99999999999",
3435

3536
// Malformed.
3637
"", " ", "P", "PT", "-", "-P", "T1H", "1H", "P1H", "PT1D", "P1DT", "PT1H2", "P1Y2", "PT1HM", "P-1D", "+PT1H",

‎tests/TriasDev.Tabular.Tests/Ods/OdsCursorTests.cs‎

Lines changed: 102 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,53 @@ public void ListsTheSheetsOfAContentPartWrittenInUtf16()
114114
Assert.Equal("ä", Assert.Single(ReadAll(cursor))[0].AsText());
115115
}
116116

117+
/// <summary>
118+
/// A table element without content, written as an empty tag, holds no rows and is no sheet: the
119+
/// list leaves it out in either encoding, and moving to the sheet behind it reads that sheet's rows
120+
/// rather than refusing the file because the two passes counted differently.
121+
/// </summary>
122+
[Theory]
123+
[InlineData(false)]
124+
[InlineData(true)]
125+
public void ListsNoSheetForATableWithoutContent(bool utf16)
126+
{
127+
static string Row(string text) => "<table:table-row>" + Cell("office:value-type=\"string\"", text) + "</table:table-row>";
128+
OdsPackage package = new OdsPackage()
129+
.WithTable("A", Row("a"))
130+
.WithRawTable("<table:table table:name=\"empty\"/>")
131+
.WithRawTable("<table:table table:name=\"spaced\" />")
132+
.WithTable("B", Row("b"));
133+
134+
using OdsCursor cursor = Open(utf16 ? package.WithContentEncoding(Encoding.Unicode) : package);
135+
136+
Assert.Equal(["A", "B"], cursor.Sheets.Select(s => s.Name));
137+
Assert.Equal("a", Assert.Single(ReadAll(cursor))[0].AsText());
138+
Assert.True(cursor.MoveToSheet(1, TestContext.Current.CancellationToken));
139+
Assert.Equal("b", Assert.Single(ReadAll(cursor))[0].AsText());
140+
Assert.True(cursor.MoveToSheet(0, TestContext.Current.CancellationToken));
141+
Assert.Equal("a", Assert.Single(ReadAll(cursor))[0].AsText());
142+
}
143+
144+
/// <summary>
145+
/// Once a sheet has ended, reading on finds no more rows, however often it is asked: the scanner
146+
/// stands before the next sheet, whose rows are that sheet's and reached only by moving to it.
147+
/// </summary>
148+
[Fact]
149+
public void ReadsNoRowOnceTheSheetHasEndedAndNeverTheNextSheets()
150+
{
151+
static string Row(string text) => "<table:table-row>" + Cell("office:value-type=\"string\"", text) + "</table:table-row>";
152+
using OdsCursor cursor = Open(new OdsPackage().WithTable("A", Row("a1") + Row("a2")).WithTable("B", Row("b1")));
153+
154+
Assert.Equal(["a1", "a2"], ReadAll(cursor).Select(r => r[0].AsText()));
155+
Assert.False(cursor.ReadRow(TestContext.Current.CancellationToken));
156+
Assert.False(cursor.ReadRow(TestContext.Current.CancellationToken));
157+
Assert.True(cursor.CurrentRow.IsEmpty);
158+
Assert.Equal(0, cursor.CurrentSheetIndex);
159+
160+
Assert.True(cursor.MoveToSheet(1, TestContext.Current.CancellationToken));
161+
Assert.Equal("b1", Assert.Single(ReadAll(cursor))[0].AsText());
162+
}
163+
117164
[Fact]
118165
public void MovesEmptyRepeatsAlongWithoutExpandingThem()
119166
{
@@ -166,6 +213,25 @@ public void AssemblesACellsTextFromItsParagraphsAndSpans()
166213
Assert.Equal("Hauptstraße 1\tA\nHinterhaus\n2. OG links", Assert.Single(ReadAll(cursor))[0].AsText());
167214
}
168215

216+
/// <summary>
217+
/// A comment is not the cell's text wherever it stands among the paragraphs, empty or not: its
218+
/// paragraphs add no line, and its spaces, tabs and line breaks add nothing, while the paragraphs
219+
/// around it, and the rest of a paragraph it stands in, are read in full.
220+
/// </summary>
221+
[Theory]
222+
[InlineData("<text:p>a</text:p><office:annotation><dc:creator>x</dc:creator><text:p>note<text:s/>1<text:tab/>2<text:line-break/>3</text:p><text:p>more</text:p></office:annotation><text:p>b</text:p>", "a\nb")]
223+
[InlineData("<text:p>a</text:p><office:annotation/><text:p>b</text:p>", "a\nb")]
224+
[InlineData("<office:annotation/><text:p>a</text:p><text:p>b</text:p>", "a\nb")]
225+
[InlineData("<text:p>a<office:annotation><text:p>note</text:p></office:annotation>b</text:p>", "ab")]
226+
public void LeavesACommentAmongTheParagraphsOutOfTheText(string paragraphs, string expected)
227+
{
228+
using OdsCursor cursor = Open(new OdsPackage().WithTable("S", "<table:table-row>"
229+
+ $"<table:table-cell office:value-type=\"string\">{paragraphs}</table:table-cell>"
230+
+ "</table:table-row>"));
231+
232+
Assert.Equal(RawCell.FromText(expected), Assert.Single(ReadAll(cursor))[0]);
233+
}
234+
169235
/// <summary>
170236
/// ODF's white-space rule for paragraph text: a space, tab, carriage return or line feed written
171237
/// as a character is one space, a run of them collapses to one, and none counts at the start of a
@@ -409,15 +475,49 @@ static string Table(string name) => $"""<table:table table:name="{name}"><table:
409475
[Fact]
410476
public void ReadsTheCoveredPartOfAMergeAsEmpty()
411477
{
478+
// A covered cell may still hold the value it had before the merge, as LibreOffice keeps it;
479+
// the sheet shows the merged cell over it, so it reads as empty, repeats included, and the
480+
// cell after it keeps its column.
412481
string row = "<table:table-row>"
413-
+ "<table:table-cell table:number-columns-spanned=\"2\" office:value-type=\"string\"><text:p>merged</text:p></table:table-cell>"
482+
+ "<table:table-cell table:number-columns-spanned=\"5\" office:value-type=\"string\"><text:p>merged</text:p></table:table-cell>"
414483
+ "<table:covered-table-cell/>"
484+
+ "<table:covered-table-cell office:value-type=\"float\" office:value=\"5\"><text:p>5</text:p></table:covered-table-cell>"
485+
+ "<table:covered-table-cell table:number-columns-repeated=\"2\" office:value-type=\"string\"><text:p>hidden</text:p></table:covered-table-cell>"
415486
+ Cell("office:value-type=\"string\"", "next")
416487
+ "</table:table-row>";
417488

418489
using OdsCursor cursor = Open(new OdsPackage().WithTable("S", row));
419490

420-
Assert.Equal([RawCell.FromText("merged"), RawCell.Empty, RawCell.FromText("next")], Assert.Single(ReadAll(cursor)));
491+
Assert.Equal(
492+
[RawCell.FromText("merged"), RawCell.Empty, RawCell.Empty, RawCell.Empty, RawCell.Empty, RawCell.FromText("next")],
493+
Assert.Single(ReadAll(cursor)));
494+
}
495+
496+
/// <summary>
497+
/// A cell whose value stands in its attributes is passed over to its own end tag, and no further
498+
/// nor less: past the empty elements in its paragraph and past a table nested in it, whose cells
499+
/// and row end are not the row's. The cell after it, and the next row, read as written.
500+
/// </summary>
501+
[Fact]
502+
public void PassesOverExactlyTheCellWhoseValueStandsInItsAttributes()
503+
{
504+
const string SubTable = "<table:table><table:table-row><table:table-cell office:value-type=\"string\"><text:p>inner</text:p></table:table-cell></table:table-row></table:table>";
505+
string rows = "<table:table-row>"
506+
+ "<table:table-cell office:value-type=\"float\" office:value=\"1\"><text:p>1<text:s/><text:s/>0</text:p></table:table-cell>"
507+
+ $"<table:table-cell office:value-type=\"float\" office:value=\"2\">{SubTable}<text:p>2</text:p></table:table-cell>"
508+
+ $"<table:table-cell office:value-type=\"string\" office:string-value=\"stated\">{SubTable}<text:p>shown</text:p></table:table-cell>"
509+
+ Cell("office:value-type=\"string\"", "next")
510+
+ "</table:table-row>"
511+
+ "<table:table-row>" + Cell("office:value-type=\"string\"", "row2") + "</table:table-row>";
512+
513+
using OdsCursor cursor = Open(new OdsPackage().WithTable("S", rows));
514+
515+
Assert.Equal(
516+
[
517+
[RawCell.FromNumber(1), RawCell.FromNumber(2), RawCell.FromText("stated"), RawCell.FromText("next")],
518+
[RawCell.FromText("row2")],
519+
],
520+
ReadAll(cursor));
421521
}
422522

423523
[Fact]

‎tests/TriasDev.Tabular.Tests/Ods/OdsHostileInputTests.cs‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,101 @@ public void RefusesAContentPartThatStopsInsideASheet()
308308
Assert.Equal(TabularFormatException.Truncated, Assert.Throws<TabularFormatException>(() => cursor.ReadRow(Token)).Code);
309309
}
310310

311+
/// <summary>
312+
/// A part that ends inside a row — between its cells, in a cell's text, in a cell passed over or
313+
/// inside a tag — is refused at the first read, never handed out as a row of the cells before
314+
/// the cut.
315+
/// </summary>
316+
[Theory]
317+
[InlineData("<table:table-row><table:table-cell office:value-type=\"string\"><text:p>a</text:p></table:table-cell>")]
318+
[InlineData("<table:table-row><table:table-cell office:value-type=\"string\"><text:p>a")]
319+
[InlineData("<table:table-row><table:table-cell office:value-type=\"float\" office:value=\"1\"><text:p>1")]
320+
[InlineData("<table:table-row><table:covered-table-cell><text:p>c")]
321+
[InlineData("<table:table-row><table:table-cell office:value-type=\"string\"><text:p>a</text:p></table:table-cell><table:table-cell office:value-type=\"str")]
322+
public void RefusesAContentPartThatStopsInsideARowAtTheFirstRead(string cut)
323+
{
324+
string content = Content($"""<table:table table:name="A">{cut}""");
325+
content = content[..content.IndexOf("</office:spreadsheet>", StringComparison.Ordinal)];
326+
327+
using OdsCursor cursor = Open(new OdsPackage().WithRawContent(content));
328+
329+
Assert.Equal(TabularFormatException.Truncated, Assert.Throws<TabularFormatException>(() => cursor.ReadRow(Token)).Code);
330+
}
331+
332+
/// <summary>
333+
/// A part that ends inside a tag behind the first sheet — in an element's name, a start or end
334+
/// tag, an attribute value, a style or a comment — lists the sheets before the cut and reads
335+
/// them. The name pass stops where the part does: it neither goes round the cut for ever nor
336+
/// looks past its data — a name cut off after more characters than stand before it leaves the
337+
/// buffer holding nothing but that name behind its end. Run against a deadline, so a pass that
338+
/// never returns fails the test rather than holding up the run.
339+
/// </summary>
340+
[Theory]
341+
[InlineData("<")]
342+
[InlineData("<table:tab")]
343+
[InlineData("<table:", 4000)]
344+
[InlineData("<table:table")]
345+
[InlineData("<table:table table:name=\"B\"")]
346+
[InlineData("<table:table table:name=\"B>")]
347+
[InlineData("</table:tab")]
348+
[InlineData("<style:style style:name=\"ta1\" style:family=\"table\"")]
349+
[InlineData("<style:style style:name=\"ta1\" style:family=\"table\"><style:table-properties table:display=\"false\"")]
350+
[InlineData("<!-- <table:table table:name=\"B\">")]
351+
[InlineData("<![CDATA[<table:table table:name=\"B\">")]
352+
[InlineData("<?pi <table:table table:name=\"B\">")]
353+
public async Task ListsAndReadsTheSheetsBeforeAContentPartThatStopsInsideATag(string cut, int nameFiller = 0)
354+
{
355+
string content = Content($"""<table:table table:name="A">{Row(Text("a"))}</table:table>""");
356+
content = content[..content.IndexOf("</office:spreadsheet>", StringComparison.Ordinal)] + cut + new string('x', nameFiller);
357+
byte[] package = new OdsPackage().WithRawContent(content).Build();
358+
359+
(string[] sheets, List<string> rows) = await WithinDeadline(token =>
360+
{
361+
using OdsCursor cursor = new(new MemoryStream(package, writable: false), cancellationToken: token);
362+
List<string> read = [];
363+
364+
while (cursor.ReadRow(token))
365+
{
366+
read.Add(cursor.CurrentRow[0].AsText()!);
367+
}
368+
369+
return (cursor.Sheets.Select(s => s.Name).ToArray(), read);
370+
});
371+
372+
Assert.Equal(["A"], sheets);
373+
Assert.Equal(["a"], rows);
374+
}
375+
376+
/// <summary>
377+
/// Runs work that must end on its own, and fails once a deadline passes rather than waiting for
378+
/// it: cancelled through its token if it checks one, abandoned if it does not. The work has a
379+
/// background thread of its own, so an abandoned loop neither holds a pool thread nor the process.
380+
/// </summary>
381+
private static async Task<T> WithinDeadline<T>(Func<CancellationToken, T> work)
382+
{
383+
TimeSpan deadline = TimeSpan.FromSeconds(20);
384+
using CancellationTokenSource stop = CancellationTokenSource.CreateLinkedTokenSource(Token);
385+
stop.CancelAfter(deadline);
386+
CancellationToken token = stop.Token;
387+
TaskCompletionSource<T> done = new(TaskCreationOptions.RunContinuationsAsynchronously);
388+
389+
Thread thread = new(() =>
390+
{
391+
try
392+
{
393+
done.SetResult(work(token));
394+
}
395+
catch (Exception failed)
396+
{
397+
done.SetException(failed);
398+
}
399+
})
400+
{ IsBackground = true };
401+
thread.Start();
402+
403+
return await done.Task.WaitAsync(deadline + TimeSpan.FromSeconds(5), Token);
404+
}
405+
311406
[Fact]
312407
public void TakesItsBoundsFromTheOpenOptions()
313408
{

‎tests/TriasDev.Tabular.Tests/Writing/OdsWriterTests.cs‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,19 @@ public async Task WritesColumnWidthsRoundedToWholeCharacters()
180180
Assert.Contains("style:name=\"co255\"", content, StringComparison.Ordinal);
181181
}
182182

183+
/// <summary>
184+
/// A column style's width is Excel's measure of so many characters — 7 pixels each and 5 of
185+
/// padding, at 96 pixels to the inch — so a column is as wide in LibreOffice as in an xlsx.
186+
/// </summary>
187+
[Fact]
188+
public async Task StatesAColumnWidthInInchesAsExcelMeasuresIt()
189+
{
190+
string content = Content(await Spreadsheet(writer => writer.BeginSheet("data", [new("a", 1), new("b", 19)])));
191+
192+
Assert.Contains("<style:style style:name=\"co1\" style:family=\"table-column\"><style:table-column-properties style:column-width=\"0.125in\"/></style:style>", content, StringComparison.Ordinal);
193+
Assert.Contains("<style:style style:name=\"co19\" style:family=\"table-column\"><style:table-column-properties style:column-width=\"1.4375in\"/></style:style>", content, StringComparison.Ordinal);
194+
}
195+
183196
[Fact]
184197
public async Task RefusesTextLongerThanTheReaderReads()
185198
{
@@ -289,6 +302,29 @@ public async Task WritesTheMarkupLibreOfficeExpects()
289302
Assert.Contains("a <text:s text:c=\"1\"/>b<text:tab/>c", Content(ods), StringComparison.Ordinal);
290303
}
291304

305+
/// <summary>
306+
/// A space at the start of a paragraph, or right after a tab or a line break, is one ODF drops when
307+
/// it stands as a character — LibreOffice does, and so does our reader — so it is written as
308+
/// <c>text:s</c>, and the value reads back with it.
309+
/// </summary>
310+
[Theory]
311+
[InlineData("a\t b", "a<text:tab/><text:s text:c=\"1\"/>b</text:p>")]
312+
[InlineData("a\n b", "a</text:p><text:p><text:s text:c=\"1\"/>b</text:p>")]
313+
[InlineData(" lead", "<text:p><text:s text:c=\"1\"/>lead</text:p>")]
314+
public async Task StatesASpaceAfterATabOrLineBreakOrAtTheStartAsAnElement(string value, string markup)
315+
{
316+
byte[] ods = await Spreadsheet(writer =>
317+
{
318+
writer.BeginSheet("data", [new("v")]);
319+
writer.BeginRow();
320+
writer.Write(value);
321+
writer.EndRow();
322+
});
323+
324+
Assert.Contains(markup, Content(ods), StringComparison.Ordinal);
325+
Assert.Equal(RawCell.FromText(value), Rows(ods)[1][0]);
326+
}
327+
292328
[Theory]
293329
[InlineData("History")]
294330
[InlineData("a/b")]

‎tests/TriasDev.Tabular.Tests/Writing/SheetLayoutTests.cs‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,21 @@ public async Task OdsFreezesEachSheetInItsSettings()
103103
Assert.Contains("xmlns:ooo=\"http://openoffice.org/2004/office\"", settings, StringComparison.Ordinal);
104104
}
105105

106+
[Fact]
107+
public async Task OdsFreezesColumnsAlone()
108+
{
109+
byte[] ods = await Write(TabularFormat.Ods, writer => writer.BeginSheet("data", [new("a"), new("b"), new("c")], new SheetOptions { FreezeColumns = 2 }));
110+
111+
Assert.Contains(
112+
"<config:config-item-map-entry config:name=\"data\">"
113+
+ "<config:config-item config:name=\"HorizontalSplitMode\" config:type=\"short\">2</config:config-item>"
114+
+ "<config:config-item config:name=\"VerticalSplitMode\" config:type=\"short\">0</config:config-item>"
115+
+ "<config:config-item config:name=\"HorizontalSplitPosition\" config:type=\"int\">2</config:config-item>"
116+
+ "<config:config-item config:name=\"VerticalSplitPosition\" config:type=\"int\">0</config:config-item>",
117+
Entry(ods, "settings.xml"),
118+
StringComparison.Ordinal);
119+
}
120+
106121
[Fact]
107122
public async Task OdsWithoutFrozenPanesHasNoSettings()
108123
{

0 commit comments

Comments
 (0)