/
CodeFile.cs
663 lines (573 loc) · 24.4 KB
/
CodeFile.cs
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Palmmedia.ReportGenerator.Core.Logging;
using Palmmedia.ReportGenerator.Core.Parser.FileReading;
namespace Palmmedia.ReportGenerator.Core.Parser.Analysis
{
/// <summary>
/// Represents a source code file.
/// </summary>
public class CodeFile
{
/// <summary>
/// The Logger.
/// </summary>
private static readonly ILogger Logger = LoggerFactory.GetLogger(typeof(CodeFile));
/// <summary>
/// The line coverage by test method.
/// </summary>
private readonly IDictionary<TestMethod, CoverageByTrackedMethod> lineCoveragesByTestMethod = new Dictionary<TestMethod, CoverageByTrackedMethod>();
/// <summary>
/// The method metrics of the class.
/// </summary>
private readonly HashSet<MethodMetric> methodMetrics = new HashSet<MethodMetric>();
/// <summary>
/// The code elements.
/// </summary>
private readonly HashSet<CodeElement> codeElements = new HashSet<CodeElement>();
/// <summary>
/// Array containing the coverage information by line number.
/// -1: Not coverable
/// 0: Not visited
/// >0: Number of visits
/// </summary>
private int[] lineCoverage;
/// <summary>
/// Array containing the line visit status by line number.
/// </summary>
private LineVisitStatus[] lineVisitStatus;
/// <summary>
/// The branches by line number.
/// </summary>
private IDictionary<int, ICollection<Branch>> branches;
/// <summary>
/// The optional additional file reader.
/// </summary>
private IFileReader additionalFileReader;
/// <summary>
/// Initializes a new instance of the <see cref="CodeFile" /> class.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="lineCoverage">The line coverage.</param>
/// <param name="lineVisitStatus">The line visit status.</param>
internal CodeFile(string path, int[] lineCoverage, LineVisitStatus[] lineVisitStatus)
: this(path, lineCoverage, lineVisitStatus, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CodeFile" /> class.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <param name="lineCoverage">The line coverage.</param>
/// <param name="lineVisitStatus">The line visit status.</param>
/// <param name="additionalFileReader">The optional additional file reader.</param>
internal CodeFile(string path, int[] lineCoverage, LineVisitStatus[] lineVisitStatus, IFileReader additionalFileReader)
: this(path, lineCoverage, lineVisitStatus, null, additionalFileReader)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CodeFile" /> class.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="lineCoverage">The line coverage.</param>
/// <param name="lineVisitStatus">The line visit status.</param>
/// <param name="branches">The branches.</param>
internal CodeFile(string path, int[] lineCoverage, LineVisitStatus[] lineVisitStatus, IDictionary<int, ICollection<Branch>> branches)
: this(path, lineCoverage, lineVisitStatus, branches, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CodeFile" /> class.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="lineCoverage">The line coverage.</param>
/// <param name="lineVisitStatus">The line visit status.</param>
/// <param name="branches">The branches.</param>
/// <param name="additionalFileReader">The optional additional file reader.</param>
internal CodeFile(
string path,
int[] lineCoverage,
LineVisitStatus[] lineVisitStatus,
IDictionary<int, ICollection<Branch>> branches,
IFileReader additionalFileReader)
{
if (lineCoverage == null)
{
throw new ArgumentNullException(nameof(lineCoverage));
}
if (lineVisitStatus == null)
{
throw new ArgumentNullException(nameof(lineVisitStatus));
}
if (lineCoverage.LongLength != lineVisitStatus.LongLength)
{
throw new ArgumentException("Length of 'lineCoverage' and 'lineVisitStatus' must match", nameof(lineVisitStatus));
}
this.Path = path ?? throw new ArgumentNullException(nameof(path));
this.lineCoverage = lineCoverage;
this.lineVisitStatus = lineVisitStatus;
this.branches = branches;
this.additionalFileReader = additionalFileReader;
}
/// <summary>
/// Gets the path.
/// </summary>
/// <value>The path.</value>
public string Path { get; }
/// <summary>
/// Gets the test methods.
/// </summary>
/// <value>
/// The test methods.
/// </value>
public IEnumerable<TestMethod> TestMethods => this.lineCoveragesByTestMethod.Keys;
/// <summary>
/// Gets the method metrics.
/// </summary>
/// <value>The method metrics.</value>
public IEnumerable<MethodMetric> MethodMetrics => this.methodMetrics;
/// <summary>
/// Gets the code elements.
/// </summary>
/// <value>
/// The code elements.
/// </value>
public IEnumerable<CodeElement> CodeElements => this.codeElements;
/// <summary>
/// Gets the number of covered lines.
/// </summary>
/// <value>The number of covered lines.</value>
public int CoveredLines => this.lineCoverage.Count(l => l > 0);
/// <summary>
/// Gets the number of coverable lines.
/// </summary>
/// <value>The number of coverable lines.</value>
public int CoverableLines => this.lineCoverage.Count(l => l >= 0);
/// <summary>
/// Gets the number of total lines.
/// </summary>
/// <value>The number of total lines.</value>
public int? TotalLines { get; private set; }
/// <summary>
/// Gets line coverage information by line number for this file.
/// </summary>
public ReadOnlyCollection<int> LineCoverage => Array.AsReadOnly(this.lineCoverage);
/// <summary>
/// Gets line visit status by line number for this file.
/// </summary>
public ReadOnlyCollection<LineVisitStatus> LineVisitStatus => Array.AsReadOnly(this.lineVisitStatus);
/// <summary>
/// Gets the branches by line number.
/// </summary>
public IDictionary<int, ICollection<Branch>> BranchesByLine => this.branches ?? new Dictionary<int, ICollection<Branch>>();
/// <summary>
/// Gets the number of covered branches.
/// </summary>
/// <value>
/// The number of covered branches.
/// </value>
public int? CoveredBranches
{
get
{
if (this.branches == null)
{
return null;
}
return this.branches.Sum(l => l.Value.Count(b => b.BranchVisits > 0));
}
}
/// <summary>
/// Gets the number of total branches.
/// </summary>
/// <value>
/// The number of total branches.
/// </value>
public int? TotalBranches
{
get
{
if (this.branches == null)
{
return null;
}
return this.branches.Sum(l => l.Value.Count);
}
}
/// <summary>
/// Gets the number of covered code elements.
/// </summary>
/// <value>
/// The number of covered code elements.
/// </value>
public int CoveredCodeElements
{
get
{
return this.CodeElements.Count(
x => this.lineCoverage.Skip(x.FirstLine)
.Take(x.LastLine - x.FirstLine + 1)
.Any(y => y > 0));
}
}
/// <summary>
/// Gets the number of total code elements.
/// </summary>
/// <value>
/// The number of total code elements.
/// </value>
public int TotalCodeElements => this.codeElements.Count;
/// <summary>
/// Returns a <see cref="string" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="string" /> that represents this instance.
/// </returns>
public override string ToString()
{
return this.Path;
}
/// <summary>
/// Determines whether the specified <see cref="object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
if (obj == null || !obj.GetType().Equals(typeof(CodeFile)))
{
return false;
}
else
{
var codeFile = (CodeFile)obj;
string fileNameToCompare = codeFile.Path.Substring(codeFile.Path.LastIndexOf('\\') + 1);
string fileName = this.Path.Substring(this.Path.LastIndexOf('\\') + 1);
return fileName.Equals(fileNameToCompare, StringComparison.OrdinalIgnoreCase);
}
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode() => this.Path.GetHashCode();
/// <summary>
/// Calculates the coverage quota in a given range of lines.
/// </summary>
/// <param name="firstLine">The first line.</param>
/// <param name="lastLine">The last line.</param>
/// <returns>The coverage quota or <code>null</code> if not applicable.</returns>
internal decimal? CoverageQuota(int firstLine, int lastLine)
{
if (firstLine < 0
|| firstLine >= this.lineVisitStatus.Length
|| lastLine < 0
|| lastLine >= this.lineVisitStatus.Length
|| firstLine > lastLine)
{
return null;
}
int coverableLines = 0;
int coveredLines = 0;
for (int i = firstLine; i <= lastLine; i++)
{
if (this.lineVisitStatus[i] != Analysis.LineVisitStatus.NotCoverable)
{
coverableLines++;
}
if (this.lineVisitStatus[i] > Analysis.LineVisitStatus.NotCovered)
{
coveredLines++;
}
}
return (coverableLines == 0) ? (decimal?)null : (decimal)Math.Truncate(1000 * (double)coveredLines / (double)coverableLines) / 10;
}
/// <summary>
/// Adds the coverage by test method.
/// </summary>
/// <param name="testMethod">The test method.</param>
/// <param name="trackedMethodCoverage">The coverage by for test method.</param>
internal void AddCoverageByTestMethod(TestMethod testMethod, CoverageByTrackedMethod trackedMethodCoverage)
{
if (testMethod == null)
{
throw new ArgumentNullException(nameof(testMethod));
}
if (trackedMethodCoverage == null)
{
throw new ArgumentNullException(nameof(trackedMethodCoverage));
}
CoverageByTrackedMethod existingTrackedMethodCoverage;
if (!this.lineCoveragesByTestMethod.TryGetValue(testMethod, out existingTrackedMethodCoverage))
{
this.lineCoveragesByTestMethod.Add(testMethod, trackedMethodCoverage);
}
else
{
this.lineCoveragesByTestMethod[testMethod] = MergeCoverageByTrackedMethod(existingTrackedMethodCoverage, trackedMethodCoverage);
}
}
/// <summary>
/// Adds the given method metric.
/// </summary>
/// <param name="methodMetric">The method metric.</param>
internal void AddMethodMetric(MethodMetric methodMetric)
{
this.methodMetrics.Add(methodMetric);
}
/// <summary>
/// Adds the code element.
/// </summary>
/// <param name="codeElement">The code element.</param>
internal void AddCodeElement(CodeElement codeElement)
{
this.codeElements.Add(codeElement);
}
/// <summary>
/// Performs the analysis of the source file.
/// </summary>
/// <param name="fileReader">The file reader.</param>
/// <returns>The analysis result.</returns>
internal FileAnalysis AnalyzeFile(IFileReader fileReader)
{
string error = null;
string[] lines = null;
if (this.additionalFileReader != null)
{
lines = this.additionalFileReader.LoadFile(this.Path, out error);
}
if (this.additionalFileReader == null || error != null)
{
error = null;
lines = fileReader.LoadFile(this.Path, out error);
}
if (error != null)
{
Logger.Error(error);
return new FileAnalysis(this.Path, error);
}
this.TotalLines = lines.Length;
int currentLineNumber = 0;
var result = new FileAnalysis(this.Path);
ICollection<Branch> branchesOfLine = null;
foreach (var line in lines)
{
currentLineNumber++;
int visits = this.lineCoverage.Length > currentLineNumber ? this.lineCoverage[currentLineNumber] : -1;
LineVisitStatus lineVisitStatus = this.lineVisitStatus.Length > currentLineNumber ? this.lineVisitStatus[currentLineNumber] : Analysis.LineVisitStatus.NotCoverable;
var lineCoverageByTestMethod = this.lineCoveragesByTestMethod
.ToDictionary(
l => l.Key,
l =>
{
if (l.Value.Coverage.Length > currentLineNumber)
{
return new ShortLineAnalysis(l.Value.Coverage[currentLineNumber], l.Value.LineVisitStatus[currentLineNumber]);
}
else
{
return new ShortLineAnalysis(-1, Analysis.LineVisitStatus.NotCoverable);
}
});
if (this.branches != null && this.branches.TryGetValue(currentLineNumber, out branchesOfLine))
{
result.AddLineAnalysis(
new LineAnalysis(
visits,
lineVisitStatus,
lineCoverageByTestMethod,
currentLineNumber,
line.TrimEnd(),
branchesOfLine.Count(b => b.BranchVisits > 0),
branchesOfLine.Count));
}
else
{
result.AddLineAnalysis(
new LineAnalysis(
visits,
lineVisitStatus,
lineCoverageByTestMethod,
currentLineNumber,
line.TrimEnd()));
}
}
return result;
}
/// <summary>
/// Merges the given file with the current instance.
/// </summary>
/// <param name="file">The file to merge.</param>
internal void Merge(CodeFile file)
{
if (file == null)
{
throw new ArgumentNullException(nameof(file));
}
// Resize coverage array if necessary
if (file.lineCoverage.LongLength > this.lineCoverage.LongLength)
{
int[] newLineCoverage = new int[file.lineCoverage.LongLength];
Array.Copy(this.lineCoverage, newLineCoverage, this.lineCoverage.LongLength);
for (long i = this.lineCoverage.LongLength; i < file.lineCoverage.LongLength; i++)
{
newLineCoverage[i] = -1;
}
this.lineCoverage = newLineCoverage;
}
// Resize line visit status array if necessary
if (file.lineVisitStatus.LongLength > this.lineVisitStatus.LongLength)
{
LineVisitStatus[] newLineVisitStatus = new LineVisitStatus[file.lineVisitStatus.LongLength];
Array.Copy(this.lineVisitStatus, newLineVisitStatus, this.lineVisitStatus.LongLength);
this.lineVisitStatus = newLineVisitStatus;
}
if (file.branches != null)
{
if (this.branches == null)
{
this.branches = new Dictionary<int, ICollection<Branch>>();
}
foreach (var branchByLine in file.branches)
{
ICollection<Branch> existingBranches = null;
if (this.branches.TryGetValue(branchByLine.Key, out existingBranches))
{
foreach (var branch in branchByLine.Value)
{
Branch existingBranch = existingBranches.FirstOrDefault(b => b.Equals(branch));
if (existingBranch != null)
{
existingBranch.BranchVisits += branch.BranchVisits;
}
else
{
existingBranches.Add(branch);
}
}
}
else
{
this.branches.Add(branchByLine);
}
}
}
for (long i = 0; i < file.lineCoverage.LongLength; i++)
{
int coverage = this.lineCoverage[i];
if (coverage < 0)
{
coverage = file.lineCoverage[i];
}
else if (file.lineCoverage[i] > 0)
{
coverage += file.lineCoverage[i];
}
this.lineCoverage[i] = coverage;
}
for (long i = 0; i < file.lineVisitStatus.LongLength; i++)
{
int lineVisitStatus = Math.Max((int)this.lineVisitStatus[i], (int)file.lineVisitStatus[i]);
this.lineVisitStatus[i] = (LineVisitStatus)lineVisitStatus;
if (this.lineVisitStatus[i] == Analysis.LineVisitStatus.PartiallyCovered
&& this.branches != null
&& this.branches.TryGetValue((int)i, out ICollection<Branch> branches))
{
if (branches.All(b => b.BranchVisits > 0))
{
this.lineVisitStatus[i] = Analysis.LineVisitStatus.Covered;
}
}
}
foreach (var lineCoverageByTestMethod in file.lineCoveragesByTestMethod)
{
CoverageByTrackedMethod existingTrackedMethodCoverage = null;
this.lineCoveragesByTestMethod.TryGetValue(lineCoverageByTestMethod.Key, out existingTrackedMethodCoverage);
if (existingTrackedMethodCoverage == null)
{
this.lineCoveragesByTestMethod.Add(lineCoverageByTestMethod);
}
else
{
this.lineCoveragesByTestMethod[lineCoverageByTestMethod.Key] = MergeCoverageByTrackedMethod(existingTrackedMethodCoverage, lineCoverageByTestMethod.Value);
}
}
foreach (var methodMetric in file.methodMetrics)
{
var existingMethodMetric = this.methodMetrics.FirstOrDefault(m => m.Equals(methodMetric));
if (existingMethodMetric != null)
{
existingMethodMetric.Merge(methodMetric);
}
else
{
this.AddMethodMetric(methodMetric);
}
}
foreach (var codeElement in file.codeElements)
{
this.codeElements.Add(codeElement);
}
foreach (var codeElement in this.codeElements)
{
codeElement.ApplyMaximumCoverageQuota(this.CoverageQuota(codeElement.FirstLine, codeElement.LastLine));
}
if (file.additionalFileReader == null)
{
file.additionalFileReader = this.additionalFileReader;
}
}
/// <summary>
/// Merges the two tracked method coverage.
/// </summary>
/// <param name="existingTrackedMethodCoverage">The existing tracked method coverage.</param>
/// <param name="lineCoverageByTestMethod">The new line coverage by test method.</param>
/// <returns>The merged tracked method coverage.</returns>
private static CoverageByTrackedMethod MergeCoverageByTrackedMethod(CoverageByTrackedMethod existingTrackedMethodCoverage, CoverageByTrackedMethod lineCoverageByTestMethod)
{
// Resize coverage array if neccessary
if (lineCoverageByTestMethod.Coverage.LongLength > existingTrackedMethodCoverage.Coverage.LongLength)
{
int[] newLineCoverage = new int[lineCoverageByTestMethod.Coverage.LongLength];
Array.Copy(lineCoverageByTestMethod.Coverage, newLineCoverage, lineCoverageByTestMethod.Coverage.LongLength);
for (long i = existingTrackedMethodCoverage.Coverage.LongLength; i < lineCoverageByTestMethod.Coverage.LongLength; i++)
{
newLineCoverage[i] = -1;
}
existingTrackedMethodCoverage.Coverage = newLineCoverage;
}
// Resize line visit status array if neccessary
if (lineCoverageByTestMethod.LineVisitStatus.LongLength > existingTrackedMethodCoverage.LineVisitStatus.LongLength)
{
LineVisitStatus[] newLineVisitStatus = new LineVisitStatus[lineCoverageByTestMethod.LineVisitStatus.LongLength];
Array.Copy(lineCoverageByTestMethod.LineVisitStatus, newLineVisitStatus, lineCoverageByTestMethod.LineVisitStatus.LongLength);
existingTrackedMethodCoverage.LineVisitStatus = newLineVisitStatus;
}
for (long i = 0; i < lineCoverageByTestMethod.Coverage.LongLength; i++)
{
int coverage = existingTrackedMethodCoverage.Coverage[i];
if (coverage < 0)
{
coverage = lineCoverageByTestMethod.Coverage[i];
}
else if (lineCoverageByTestMethod.Coverage[i] > 0)
{
coverage += lineCoverageByTestMethod.Coverage[i];
}
existingTrackedMethodCoverage.Coverage[i] = coverage;
}
for (long i = 0; i < lineCoverageByTestMethod.LineVisitStatus.LongLength; i++)
{
int lineVisitStatus = Math.Max((int)existingTrackedMethodCoverage.LineVisitStatus[i], (int)lineCoverageByTestMethod.LineVisitStatus[i]);
existingTrackedMethodCoverage.LineVisitStatus[i] = (LineVisitStatus)lineVisitStatus;
}
return existingTrackedMethodCoverage;
}
}
}