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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
|
module dyaml.test.suite;
import std.algorithm;
import std.conv;
import std.datetime.stopwatch;
import std.exception;
import std.file;
import std.format;
import std.meta;
import std.path;
import std.range;
import std.stdio;
import std.string;
import std.typecons;
import dyaml;
import dyaml.event;
import dyaml.parser;
import dyaml.reader;
import dyaml.scanner;
import dyaml.test.suitehelpers;
private version(unittest):
debug(verbose)
{
enum alwaysPrintTestResults = true;
}
else
{
enum alwaysPrintTestResults = false;
}
struct TestResult {
string name;
Nullable!bool emitter;
Nullable!bool constructor;
Nullable!bool loaderError;
Nullable!bool mark1Error;
Nullable!bool mark2Error;
Nullable!bool implicitResolver;
Nullable!bool events;
Nullable!bool specificLoaderError;
Nullable!Mark mark1;
Nullable!Mark mark2;
Event[] parsedData;
Event[][2 * 2 * 5] parsedDataResult;
Node[] loadedData;
Exception nonDYAMLException;
MarkedYAMLException exception;
string eventsExpected;
string eventsGenerated;
string generatedLoadErrorMessage;
string expectedLoadErrorMessage;
string expectedTags;
string generatedTags;
}
/// Pretty-print the differences between two arrays
auto prettyDifferencePrinter(alias eqPred = (a,b) => a == b, T)(string title, T[] expected, T[] got, bool trimWhitespace = false) @safe
{
struct Result
{
void foo() {
toString(nullSink);
}
void toString(W)(ref W writer) const
{
import std.format : formattedWrite;
import std.range : put;
import std.string : lineSplitter;
size_t minWidth = 10;
foreach (line; chain(expected, got))
{
if (line.text.length + 1 > minWidth)
{
minWidth = line.text.length + 1;
}
}
void writeSideBySide(ubyte colour, string a, string b)
{
if (trimWhitespace)
{
a = strip(a);
b = strip(b);
}
writer.formattedWrite!"%s%-(%s%)%s"(colourPrinter(colour, a), " ".repeat(minWidth - a.length), colourPrinter(colour, b));
}
writefln!"%-(%s%)%s%-(%s%)"("=".repeat(max(0, minWidth * 2 - title.length) / 2), title, "=".repeat(max(0, minWidth * 2 - title.length) / 2));
writeSideBySide(0, "Expected", "Got");
put(writer, "\n");
foreach (line1, line2; zip(StoppingPolicy.longest, expected, got))
{
static if (is(T : const char[]))
{
if (trimWhitespace)
{
line1 = strip(line1);
line2 = strip(line2);
}
}
ubyte colour = (eqPred(line1, line2)) ? 32 : 31;
writeSideBySide(colour, line1.text, line2.text);
put(writer, "\n");
}
}
}
return Result();
}
/**
Run a single test from the test suite.
Params:
name = The filename of the document to load, containing the test data
*/
TestResult runTest(string name, Node doc) @safe
{
TestResult result;
string[string] testData;
void tryLoadTestData(string what)
{
if (what in doc)
{
testData[what] = doc[what].as!string;
doc.removeAt(what);
}
}
string yamlPath(string testName, string section)
{
return format!"%s:%s"(testName, section);
}
tryLoadTestData("name");
result.name = name~"#"~testData.get("name", "UNNAMED");
Nullable!Mark getMark(string key)
{
if (auto node = key in doc)
{
Mark mark;
if ("name" in *node)
{
mark.name = (*node)["name"].as!string;
}
else // default to the test name
{
// if we ever have multiple yaml blocks to parse, be sure to change this
mark.name = yamlPath(result.name, "yaml");
}
if ("line" in *node)
{
mark.line = cast(ushort)((*node)["line"].as!ushort - 1);
}
if ("column" in *node)
{
mark.column = cast(ushort)((*node)["column"].as!ushort - 1);
}
return Nullable!Mark(mark);
}
return Nullable!Mark.init;
}
tryLoadTestData("tags");
tryLoadTestData("from");
tryLoadTestData("yaml");
tryLoadTestData("fail");
tryLoadTestData("json"); //not yet implemented
tryLoadTestData("dump"); //not yet implemented
tryLoadTestData("detect");
tryLoadTestData("tree");
tryLoadTestData("error");
tryLoadTestData("code");
assert("yaml" in testData);
{
result.expectedLoadErrorMessage = testData.get("error", "");
result.mark1 = getMark("mark");
result.mark2 = getMark("mark2");
try
{
result.parsedData = parseData(testData["yaml"], yamlPath(result.name, "yaml")).array;
result.loadedData = Loader.fromString(testData["yaml"], yamlPath(result.name, "yaml")).array;
result.emitter = testEmitterStyles(yamlPath(result.name, "canonical"), result.parsedData, result.parsedDataResult);
result.mark1Error = result.mark1.isNull;
result.mark2Error = result.mark2.isNull;
}
catch (MarkedYAMLException e)
{
result.exception = e;
result.generatedLoadErrorMessage = e.msg;
result.mark1Error = !result.mark1.isNull && (result.mark1.get() == e.mark);
result.mark2Error = result.mark2 == e.mark2;
if (testData.get("fail", "false") == "false")
{
result.loaderError = false;
}
else
{
result.loaderError = true;
}
}
catch (Exception e)
{
// all non-DYAML exceptions are failures.
result.nonDYAMLException = e;
result.generatedLoadErrorMessage = e.msg;
result.loaderError = false;
}
result.specificLoaderError = strip(result.generatedLoadErrorMessage) == strip(result.expectedLoadErrorMessage);
}
if (result.loaderError.get(false))
{
// skip other tests if loading failure was expected, because we don't
// have a way to run them yet
return result;
}
if ("tree" in testData)
{
result.eventsGenerated = result.parsedData.map!(x => strip(x.text)).join("\n");
result.eventsExpected = testData["tree"].lineSplitter.map!(x => strip(x)).join("\n");
result.events = result.eventsGenerated == result.eventsExpected;
}
if ("code" in testData)
{
result.constructor = testConstructor(testData["yaml"], testData["code"]);
}
if ("detect" in testData)
{
result.implicitResolver = testImplicitResolver(yamlPath(result.name, "yaml"), testData["yaml"], testData["detect"], result.generatedTags, result.expectedTags);
}
foreach (string remaining, Node _; doc)
{
writeln("Warning: Unhandled section '", remaining, "' in ", result.name);
}
return result;
}
enum goodColour = 32;
enum badColour = 31;
/**
Print something to the console in colour.
Params:
colour = The id of the colour to print, using the 256-colour palette
data = Something to print
*/
private auto colourPrinter(T)(ubyte colour, T data) @safe pure
{
struct Printer
{
void toString(S)(ref S sink)
{
sink.formattedWrite!"\033[%s;1m%s\033[0m"(colour, data);
}
}
return Printer();
}
/**
Run all tests in the test suite and print relevant results. The test docs are
all found in the ./test/data dir.
*/
bool runTests()
{
auto stopWatch = StopWatch(AutoStart.yes);
bool failed;
uint testsRun, testSetsRun, testsFailed;
foreach (string name; dirEntries(buildNormalizedPath("test"), "*.yaml", SpanMode.depth)/*.chain(dirEntries(buildNormalizedPath("yaml-test-suite/src"), "*.yaml", SpanMode.depth))*/)
{
Node doc;
try
{
doc = Loader.fromFile(name).load();
}
catch (Exception e)
{
writefln!"[%s] %s"(colourPrinter(badColour, "FAIL"), name);
writeln(colourPrinter(badColour, e));
assert(0, "Could not load test doc '"~name~"', bailing");
}
assert (doc.nodeID == NodeID.sequence, name~"'s root node is not a sequence!");
foreach (Node test; doc)
{
testSetsRun++;
bool resultPrinted;
// make sure the paths are normalized on windows by replacing backslashes with slashes
TestResult result = runTest(name.replace("\\", "/"), test);
void printResult(string label, Nullable!bool value)
{
if (!value.isNull)
{
if (!value.get)
{
testsFailed++;
}
testsRun++;
}
if (alwaysPrintTestResults && value.get(false))
{
resultPrinted = true;
writef!"[%s]"(colourPrinter(goodColour, label));
}
else if (!value.get(true))
{
resultPrinted = true;
failed = true;
writef!"[%s]"(colourPrinter(badColour, label));
}
}
printResult("Emitter", result.emitter);
printResult("Constructor", result.constructor);
printResult("Mark", result.mark1Error);
printResult("Context mark", result.mark2Error);
printResult("LoaderError", result.loaderError);
printResult("Resolver", result.implicitResolver);
printResult("Events", result.events);
printResult("SpecificLoaderError", result.specificLoaderError);
if (resultPrinted)
{
writeln(" ", result.name);
}
if (!result.loaderError.get(true))
{
if (result.exception is null && result.nonDYAMLException is null)
{
writeln("\tNo Exception thrown");
}
else if (result.nonDYAMLException !is null)
{
writeln(result.nonDYAMLException);
}
else if (result.exception !is null)
{
writeln(result.exception);
}
}
else
{
if (!result.mark1Error.get(true))
{
writeln(prettyDifferencePrinter("Mark mismatch", [result.mark1.text], [result.exception.mark.text]));
}
if (!result.mark2Error.get(true))
{
writeln(prettyDifferencePrinter("Context mark mismatch", [result.mark2.text], [result.exception.mark2.text]));
}
}
if (!result.emitter.get(true))
{
enum titles = [ "Normal", "Canonical" ];
enum styleTitles =
[
"Block literal", "Block folded", "Block double-quoted", "Block single-quoted", "Block plain",
"Flow literal", "Flow folded", "Flow double-quoted", "Flow single-quoted", "Flow plain",
"Block literal", "Block folded", "Block double-quoted", "Block single-quoted", "Block plain",
"Flow literal", "Flow folded", "Flow double-quoted", "Flow single-quoted", "Flow plain",
];
foreach (idx, parsed; result.parsedDataResult)
{
writeln(prettyDifferencePrinter!eventCompare(styleTitles[idx], result.parsedData, parsed));
}
}
if (!result.events.get(true))
{
writeln(prettyDifferencePrinter("Events", result.eventsExpected.splitLines, result.eventsGenerated.splitLines, true));
}
if (!result.specificLoaderError.get(true))
{
writeln(prettyDifferencePrinter("Expected error", result.expectedLoadErrorMessage.splitLines, result.generatedLoadErrorMessage.splitLines));
}
if (!result.implicitResolver.get(true))
{
writeln(prettyDifferencePrinter("Expected error", result.expectedTags.splitLines, result.generatedTags.splitLines));
}
}
}
if (alwaysPrintTestResults || failed)
{
if (testsFailed > 0)
{
writeln(colourPrinter(badColour, "tests failed: "), testsFailed);
}
writeln(testSetsRun, " test sets (", testsRun, " tests total) completed successfully in ", stopWatch.peek());
}
return failed;
}
unittest {
assert(!runTests());
}
|