forked from VSoftTechnologies/DUnitX
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DUnitX.Loggers.XML.NUnit.pas
534 lines (469 loc) · 16.2 KB
/
DUnitX.Loggers.XML.NUnit.pas
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
{***************************************************************************}
{ }
{ DUnitX }
{ }
{ Copyright (C) 2015 Vincent Parrett & Contributors }
{ }
{ http://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DUnitX.Loggers.XML.NUnit;
interface
{$I DUnitX.inc}
uses
{$IFDEF USE_NS}
System.Classes,
System.SysUtils,
System.Generics.Collections,
{$ELSE}
Classes,
SysUtils,
Generics.Collections,
{$ENDIF}
DUnitX.TestFramework,
DUnitX.Loggers.Null;
type
TDUnitXXMLNUnitLogger = class(TDUnitXNullLogger)
private
FOutputStream : TStream;
FOwnsStream : boolean;
FIndent : integer;
FFormatSettings : TFormatSettings;
protected
procedure Indent;
procedure Outdent;
procedure WriteXMLLine(const value : string);
procedure OnTestingEnds(const RunResults: IRunResults); override;
procedure WriteCategoryNodes(const ACategoryList: TList<string>);
procedure WriteFixtureResult(const fixtureResult : IFixtureResult);
procedure WriteTestResult(const testResult : ITestResult);
function Format(const Format: string; const Args: array of const): String;
public
constructor Create(const AOutputStream : TStream; const AOwnsStream : boolean = false);
destructor Destroy;override;
end;
TDUnitXXMLNUnitFileLogger = class(TDUnitXXMLNUnitLogger)
public
constructor Create(const AFilename: string = '');
end;
implementation
uses
{$IFDEF USE_NS}
System.TypInfo;
{$ELSE}
TypInfo;
{$ENDIF}
function IsValidXMLChar(wc: WideChar): Boolean;
begin
case Word(wc) of
$0009, $000A, $000C, $000D,
$0020..$D7FF,
$E000..$FFFD, // Standard Unicode chars below $FFFF
$D800..$DBFF, // High surrogate of Unicode character = $10000 - $10FFFF
$DC00..$DFFF: // Low surrogate of Unicode character = $10000 - $10FFFF
result := True;
else
result := False;
end;
end;
function StripInvalidXML(const s: string): string;
var
i, count: Integer;
begin
{$IFNDEF NEXTGEN}
count := Length(s);
setLength(result, count);
for i := 1 to Count do // Iterate
begin
if IsValidXMLChar(WideChar(s[i])) then
result[i] := s[i]
else
result[i] := ' ';
end; // for}
{$ELSE}
count := s.Length;
SetLength(result, count);
for i := 0 to count - 1 do // Iterate
begin
if IsValidXMLChar(s.Chars[i]) then
begin
result := result.Remove(i, 1);
result := result.Insert(i, s.Chars[i]);
end
else
begin
result := result.Remove(i, 1);
result := result.Insert(i, s.Chars[i]);
end;
end; // for}
{$ENDIF}
end;
function EscapeForXML(const value: string; const isAttribute: boolean = True; const isCDATASection : Boolean = False): string;
begin
result := StripInvalidXML(value);
{$IFNDEF NEXTGEN}
if isCDATASection then
begin
Result := StringReplace(Result, ']]>', ']>',[rfReplaceAll]);
exit;
end;
//note we are avoiding replacing & with &amp; !!
Result := StringReplace(result, '&', '[[-xy-amp--]]',[rfReplaceAll]);
Result := StringReplace(result, '&', '&',[rfReplaceAll]);
Result := StringReplace(result, '[[-xy-amp--]]', '&amp;',[rfReplaceAll]);
Result := StringReplace(result, '<', '<',[rfReplaceAll]);
Result := StringReplace(result, '>', '>',[rfReplaceAll]);
if isAttribute then
begin
Result := StringReplace(result, '''', ''',[rfReplaceAll]);
Result := StringReplace(result, '"', '"',[rfReplaceAll]);
end;
{$ELSE}
if isCDATASection then
begin
Result := Result.Replace(']]>', ']>', [rfReplaceAll]);
exit;
end;
//note we are avoiding replacing & with &amp; !!
Result := Result.Replace('&', '[[-xy-amp--]]',[rfReplaceAll]);
Result := Result.Replace('&', '&',[rfReplaceAll]);
Result := Result.Replace('[[-xy-amp--]]', '&amp;',[rfReplaceAll]);
Result := Result.Replace('<', '<',[rfReplaceAll]);
Result := Result.Replace('>', '>',[rfReplaceAll]);
if isAttribute then
begin
Result := Result.Replace('''', ''',[rfReplaceAll]);
Result := Result.Replace('"', '"',[rfReplaceAll]);
end;
{$ENDIF}
end;
{ TDUnitXXMLNUnitLogger }
constructor TDUnitXXMLNUnitLogger.Create(const AOutputStream: TStream; const AOwnsStream : boolean = false);
var
preamble: TBytes;
{$IFNDEF DELPHI_XE_UP}
oldThousandSeparator: Char;
oldDecimalSeparator: Char;
{$ENDIF}
begin
{$IFDEF DELPHI_XE_UP }
FFormatSettings := TFormatSettings.Create;
FFormatSettings.ThousandSeparator := ',';
FFormatSettings.DecimalSeparator := '.';
{$ELSE}
oldThousandSeparator := {$IFDEF USE_NS}System.{$ENDIF}SysUtils.ThousandSeparator;
oldDecimalSeparator := {$IFDEF USE_NS}System.{$ENDIF}DecimalSeparator;
try
SysUtils.ThousandSeparator := ',';
SysUtils.DecimalSeparator := '.';
{$ENDIF}
FOutputStream := AOutputStream;
FOwnsStream := AOwnsStream;
Preamble := TEncoding.UTF8.GetPreamble;
FOutputStream.WriteBuffer(preamble[0], Length(preamble));
{$IFNDEF DELPHI_XE_UP}
finally
{$IFDEF USE_NS}System.{$ENDIF}SysUtils.ThousandSeparator := oldThousandSeparator;
{$IFDEF USE_NS}System.{$ENDIF}SysUtils.DecimalSeparator := oldDecimalSeparator;
end;
{$ENDIF}
end;
destructor TDUnitXXMLNUnitLogger.Destroy;
begin
if FOwnsStream then
FOutputStream.Free;
inherited;
end;
function TDUnitXXMLNUnitLogger.Format(const Format: string; const Args: array of const): String;
begin
Result := {$IFDEF USE_NS}System.{$ENDIF}SysUtils.Format(Format, Args, FFormatSettings);
end;
procedure TDUnitXXMLNUnitLogger.Indent;
begin
Inc(FIndent,2);
end;
procedure TDUnitXXMLNUnitLogger.OnTestingEnds(const RunResults: IRunResults);
procedure LogFixture(const fixture : IFixtureResult; level : integer);
var
child : IFixtureResult;
sLevel : string;
begin
sLevel := StringOfChar(' ', level * 2 );
System.WriteLn(sLevel + fixture.Fixture.NameSpace + ':' + fixture.Fixture.Name + Format(' [Tests: %d] [Children: %d] [Passed : %d]',[fixture.ResultCount,fixture.ChildCount,fixture.PassCount]));
Inc(level);
for child in fixture.Children do
begin
LogFixture(child,level);
end;
end;
var
fixtureRes : IFixtureResult;
sExeName : string;
sResult : string;
sTime : string;
sDate : string;
totalTests : integer;
begin
{ first things first, rollup the namespaces.
So, where parent fixtures have no tests, or only one child fixture, combine into a single fixture.
}
for fixtureRes in RunResults.FixtureResults do
begin
fixtureRes.Reduce;
// LogFixture(fixtureRes,0);
end;
//NUnit reports the total without the Ignored.
totalTests := RunResults.TestCount - RunResults.IgnoredCount;
sExeName := ParamStr(0);
FIndent := 0;
sTime := Format('%.3f',[RunResults.Duration.TotalSeconds]);
sDate := FormatDateTime('yyyy-MM-dd',RunResults.StartTime);
WriteXMLLine('<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>');
WriteXMLLine(Format('<test-results name="%s" total="%d" errors="%d" failures="%d" ignored="%d" inconclusive="0" not-run="%d" skipped="0" invalid="0" date="%s" time="%s">',
[sExeName,totalTests,RunResults.ErrorCount,RunResults.FailureCount,RunResults.IgnoredCount,RunResults.IgnoredCount,sDate,sTime]));
sExeName := ExtractFileName(sExeName);
if RunResults.AllPassed then
sResult := 'Success'
else
sResult := 'Failure';
Indent;
//TODO: Populate these properly.
// WriteXMLLine('<environment nunit-version="DUnitX" clr-version="2.0.0.0" os-version="6.1.0.0" platform="Windows" cwd="" machine-name="" user="" user-domain="" />');
WriteXMLLine('<culture-info current-culture="en" current-uiculture="en" />');
WriteXMLLine(Format('<test-suite type="Assembly" name="%s" executed="true" result="%s" success="%s" time="%s" asserts="0">',[sExeName,sResult,BoolToStr(RunResults.AllPassed,true),sTime]));
Indent;
WriteXMLLine('<results>');
Indent;
for fixtureRes in RunResults.FixtureResults do
WriteFixtureResult(fixtureRes);
Outdent;
WriteXMLLine('</results>');
Outdent;
WriteXMLLine('</test-suite>');
Outdent;
WriteXMLLine('</test-results>');
end;
procedure TDUnitXXMLNUnitLogger.Outdent;
begin
Dec(FIndent,2);
end;
procedure TDUnitXXMLNUnitLogger.WriteFixtureResult(const fixtureResult: IFixtureResult);
var
sResult : string;
sTime : string;
sLineEnd : string;
child : IFixtureResult;
testResult : ITestResult;
sExecuted : string;
sName: string;
sSuccess: string;
begin
Indent;
try
if not fixtureResult.HasFailures then
sResult := 'Success'
else
sResult := 'Failure';
sTime := Format('%.3f',[fixtureResult.Duration.TotalSeconds]);
sName := EscapeForXML(fixtureResult.Fixture.Name);
sResult := EscapeForXML(sResult);
sSuccess := EscapeForXML(BoolToStr(not fixtureResult.HasFailures,true));
sTime := EscapeForXML(sTime);
//its a real fixture if the class is not TObject.
if (not fixtureResult.Fixture.TestClass.ClassNameIs('TObject')) then
begin
//if there were no tests then just ignore this fixture.
if fixtureResult.ResultCount = 0 then
exit;
sExecuted := BoolToStr(fixtureResult.ResultCount > 0,true);
sExecuted := EscapeForXML(sExecuted);
WriteXMLLine(Format('<test-suite type="Fixture" name="%s" executed="%s" result="%s" success="%s" time="%s" >',[sName, sExecuted, sResult, sSuccess, sTime]));
WriteCategoryNodes(fixtureResult.Fixture.Categories);
Indent;
WriteXMLLine('<results>');
for testResult in fixtureResult.TestResults do
begin
WriteTestResult(testResult);
end;
for child in fixtureResult.Children do
begin
WriteFixtureResult(child);
end;
WriteXMLLine('</results>');
Outdent;
WriteXMLLine('</test-suite>');
end
else
begin
if fixtureResult.ChildCount = 0 then
sLineEnd := '/';
//It's a Namespace.
WriteXMLLine(Format('<test-suite type="Namespace" name="%s" executed="true" result="%s" success="%s" time="%s" asserts="0" %s>',[sName, sResult, sSuccess, sTime, sLineEnd]));
if fixtureResult.ChildCount > 0 then
begin
Indent;
WriteXMLLine('<results>');
Indent;
for child in fixtureResult.Children do
begin
WriteFixtureResult(child);
end;
Outdent;
WriteXMLLine('</results>');
Outdent;
WriteXMLLine('</test-suite>');
end;
end;
finally
Outdent;
end;
end;
function ResultTypeToString(const value : TTestResultType) : string;
begin
case value of
TTestResultType.Pass: result := 'Success';
TTestResultType.Failure : result := 'Failure';
TTestResultType.Error : result := 'Error';
TTestResultType.Ignored : result := 'Ignored';
TTestResultType.MemoryLeak : result := 'Failure'; //NUnit xml doesn't understand memory leak
else
result := GetEnumName(TypeInfo(TTestResultType),Ord(value));
end;
end;
procedure TDUnitXXMLNUnitLogger.WriteTestResult(const testResult: ITestResult);
var
sLineEnd : string;
sResult : string;
sTime : string;
sExecuted : string;
sSuccess : string;
sName : string;
begin
Indent;
try
sTime := Format('%.3f',[testResult.Duration.TotalSeconds]);
sResult := ResultTypeToString(testResult.ResultType);
if (testResult.ResultType = TTestResultType.Pass) and (testResult.Test.Categories.Count = 0) then
sLineEnd := '/';
sExecuted := BoolToStr(testResult.ResultType <> TTestResultType.Ignored,true);
if testResult.ResultType <> TTestResultType.Ignored then
sSuccess := Format('success="%s"',[EscapeForXML(BoolToStr(testResult.ResultType = TTestResultType.Pass, true))])
else
sSuccess := '';
sName := EscapeForXML(testResult.Test.Name);
sExecuted := EscapeForXML(sExecuted);
sResult := EscapeForXML(sResult);
sTime := EscapeForXML(sTime);
WriteXMLLine(Format('<test-case name="%s" executed="%s" result="%s" %s time="%s" asserts="0" %s>', [sName, sExecuted, sResult, sSuccess, sTime, sLineEnd]));
WriteCategoryNodes(testResult.Test.Categories);
case testResult.ResultType of
TTestResultType.MemoryLeak,
TTestResultType.Failure,
TTestResultType.Error:
begin
Indent;
WriteXMLLine('<failure>');
Indent;
WriteXMLLine('<message>');
Indent;
WriteXMLLine(Format('<![CDATA[ %s ]]>',[EscapeForXML(testResult.Message, False, True)]));
Outdent;
WriteXMLLine('</message>');
Outdent;
Indent;
WriteXMLLine('<stack-trace>');
Indent;
WriteXMLLine(Format('<![CDATA[ %s ]]>',[EscapeForXML(testResult.StackTrace, False, True)]));
Outdent;
WriteXMLLine('</stack-trace>');
Outdent;
WriteXMLLine('</failure>');
end;
TTestResultType.Ignored:
begin
Indent;
WriteXMLLine('<reason>');
Indent;
WriteXMLLine('<message>');
Indent;
WriteXMLLine(Format('<![CDATA[ %s ]]>',[EscapeForXML(testResult.Message, False, True)]));
Outdent;
WriteXMLLine('</message>');
Outdent;
WriteXMLLine('</reason>');
end;
TTestResultType.Pass :
begin
if testResult.Test.Categories.Count = 0 then
begin
exit;
end;
Indent;
end;
end;
Outdent;
WriteXMLLine('</test-case>');
finally
Outdent;
end;
end;
procedure TDUnitXXMLNUnitLogger.WriteCategoryNodes(const ACategoryList: TList<string>);
var
sCategory: string;
begin
if ACategoryList.Count > 0 then
begin
Indent;
WriteXMLLine('<categories>');
Indent;
for sCategory in ACategoryList do
WriteXMLLine(Format('<category name="%s" />', [sCategory]));
Outdent;
WriteXMLLine('</categories>');
Outdent;
end;
end;
procedure TDUnitXXMLNUnitLogger.WriteXMLLine(const value: string);
var
bytes : TBytes;
s : string;
begin
s := StringOfChar(' ',FIndent) + value + #13#10;
bytes := TEncoding.UTF8.GetBytes(s);
FOutputStream.Write(bytes[0],Length(bytes));
end;
{ TDUnitXXMLNUnitFileLogger }
constructor TDUnitXXMLNUnitFileLogger.Create(const AFilename: string);
var
sXmlFilename : string;
fileStream : TFileStream;
lXmlDirectory: string;
const
DEFAULT_NUNIT_FILE_NAME = 'dunitx-results.xml';
begin
sXmlFilename := AFilename;
if sXmlFilename = '' then
sXmlFilename := ExtractFilePath(ParamStr(0)) + DEFAULT_NUNIT_FILE_NAME;
lXmlDirectory := ExtractFilePath(sXmlFilename);
ForceDirectories(lXmlDirectory);
fileStream := TFileStream.Create(sXmlFilename, fmCreate);
//base class will destroy the stream;
inherited Create(fileStream,true);
end;
end.